difftreelog
Merge pull request #64 from CertainLach/feat/manifest-yaml-doc-builtin
in: master
Make manifestYamlDoc builtin
6 files changed
crates/jrsonnet-cli/src/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/manifest.rs
+++ b/crates/jrsonnet-cli/src/manifest.rs
@@ -38,9 +38,9 @@
#[clap(long, short = 'y')]
yaml_stream: bool,
/// Number of spaces to pad output manifest with.
- /// `0` for hard tabs, `-1` for single line output
- #[clap(long, default_value = "3")]
- line_padding: usize,
+ /// `0` for hard tabs, `-1` for single line output [default: 3 for json, 2 for yaml]
+ #[clap(long)]
+ line_padding: Option<usize>,
}
impl ConfigureState for ManifestOpts {
fn configure(&self, state: &EvaluationState) -> Result<()> {
@@ -50,10 +50,10 @@
match self.format {
ManifestFormatName::String => state.set_manifest_format(ManifestFormat::String),
ManifestFormatName::Json => {
- state.set_manifest_format(ManifestFormat::Json(self.line_padding))
+ state.set_manifest_format(ManifestFormat::Json(self.line_padding.unwrap_or(3)))
}
ManifestFormatName::Yaml => {
- state.set_manifest_format(ManifestFormat::Yaml(self.line_padding))
+ state.set_manifest_format(ManifestFormat::Yaml(self.line_padding.unwrap_or(2)))
}
}
}
crates/jrsonnet-evaluator/src/builtin/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/manifest.rs
@@ -156,3 +156,127 @@
}
buf.push('"');
}
+
+pub struct ManifestYamlOptions<'s> {
+ /// Padding before fields, i.e
+ /// ```yaml
+ /// a:
+ /// b:
+ /// ## <- this
+ /// ```
+ pub padding: &'s str,
+ /// Padding before array elements in objects
+ /// ```yaml
+ /// a:
+ /// - 1
+ /// ## <- this
+ /// ```
+ pub arr_element_padding: &'s str,
+}
+
+pub fn manifest_yaml_ex(val: &Val, options: &ManifestYamlOptions<'_>) -> Result<String> {
+ let mut out = String::new();
+ manifest_yaml_ex_buf(val, &mut out, &mut String::new(), options)?;
+ Ok(out)
+}
+fn manifest_yaml_ex_buf(
+ val: &Val,
+ buf: &mut String,
+ cur_padding: &mut String,
+ options: &ManifestYamlOptions<'_>,
+) -> Result<()> {
+ use std::fmt::Write;
+ match val {
+ Val::Bool(v) => {
+ if *v {
+ buf.push_str("true")
+ } else {
+ buf.push_str("false")
+ }
+ }
+ Val::Null => buf.push_str("null"),
+ Val::Str(s) => {
+ if s.is_empty() {
+ buf.push_str("\"\"");
+ } else if let Some(s) = s.strip_suffix('\n') {
+ buf.push('|');
+ for line in s.split('\n') {
+ buf.push('\n');
+ buf.push_str(options.padding);
+ buf.push_str(line);
+ }
+ } else {
+ escape_string_json_buf(s, buf)
+ }
+ }
+ Val::Num(n) => write!(buf, "{}", *n).unwrap(),
+ Val::Arr(a) => {
+ if a.is_empty() {
+ buf.push_str("[]");
+ } else {
+ for (i, item) in a.iter().enumerate() {
+ if i != 0 {
+ buf.push('\n');
+ buf.push_str(cur_padding);
+ }
+ let item = item?;
+ buf.push('-');
+ match &item {
+ Val::Arr(a) if !a.is_empty() => {
+ buf.push('\n');
+ buf.push_str(cur_padding);
+ buf.push_str(options.padding);
+ }
+ _ => buf.push(' '),
+ }
+ let extra_padding = match &item {
+ Val::Arr(a) => !a.is_empty(),
+ Val::Obj(o) => !o.is_empty(),
+ _ => false,
+ };
+ let prev_len = cur_padding.len();
+ if extra_padding {
+ cur_padding.push_str(options.padding);
+ }
+ manifest_yaml_ex_buf(&item, buf, cur_padding, options)?;
+ cur_padding.truncate(prev_len);
+ }
+ }
+ }
+ Val::Obj(o) => {
+ if o.is_empty() {
+ buf.push_str("{}");
+ } else {
+ for (i, key) in o.fields().iter().enumerate() {
+ if i != 0 {
+ buf.push('\n');
+ buf.push_str(cur_padding);
+ }
+ escape_string_json_buf(key, buf);
+ buf.push(':');
+ let prev_len = cur_padding.len();
+ let item = o.get(key.clone())?.expect("field exists");
+ match &item {
+ Val::Arr(a) if !a.is_empty() => {
+ buf.push('\n');
+ buf.push_str(cur_padding);
+ buf.push_str(options.arr_element_padding);
+ cur_padding.push_str(options.arr_element_padding);
+ }
+ Val::Obj(o) if !o.is_empty() => {
+ buf.push('\n');
+ buf.push_str(cur_padding);
+ buf.push_str(options.padding);
+ cur_padding.push_str(options.padding);
+ }
+ _ => buf.push(' '),
+ }
+ manifest_yaml_ex_buf(&item, buf, cur_padding, options)?;
+ cur_padding.truncate(prev_len);
+ }
+ }
+ }
+ Val::Func(_) => throw!(RuntimeError("tried to manifest function".into())),
+ }
+ Ok(())
+}
crates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/mod.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/mod.rs
@@ -1,4 +1,5 @@
use crate::{
+ builtin::manifest::{manifest_yaml_ex, ManifestYamlOptions},
equals,
error::{Error::*, Result},
operator::evaluate_mod_op,
@@ -121,6 +122,7 @@
("join".into(), builtin_join),
("escapeStringJson".into(), builtin_escape_string_json),
("manifestJsonEx".into(), builtin_manifest_json_ex),
+ ("manifestYamlDocImpl".into(), builtin_manifest_yaml_doc),
("reverse".into(), builtin_reverse),
("id".into(), builtin_id),
("strReplace".into(), builtin_str_replace),
@@ -768,6 +770,22 @@
})
}
+fn builtin_manifest_yaml_doc(
+ context: Context,
+ _loc: Option<&ExprLocation>,
+ args: &ArgsDesc,
+) -> Result<Val> {
+ parse_args!(context, "manifestYamlDoc", args, 2, [
+ 0, value: ty!(any);
+ 1, indent_array_in_object: ty!(boolean) => Val::Bool;
+ ], {
+ Ok(Val::Str(manifest_yaml_ex(&value, &ManifestYamlOptions {
+ padding: " ",
+ arr_element_padding: if indent_array_in_object { " " } else { "" },
+ })?.into()))
+ })
+}
+
fn builtin_reverse(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
parse_args!(context, "reverse", args, 1, [
0, value: ty!(array) => Val::Arr;
@@ -794,18 +812,7 @@
1, from: ty!(string) => Val::Str;
2, to: ty!(string) => Val::Str;
], {
- let mut out = String::new();
- let mut last_idx = 0;
- while let Some(idx) = (&str[last_idx..]).find(&from as &str) {
- out.push_str(&str[last_idx..last_idx+idx]);
- out.push_str(&to);
- last_idx += idx + from.len();
- }
- if last_idx == 0 {
- return Ok(Val::Str(str))
- }
- out.push_str(&str[last_idx..]);
- Ok(Val::Str(out.into()))
+ Ok(Val::Str(str.replace(&from as &str, &to as &str).into()))
})
}
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -105,6 +105,17 @@
}))
}
+ pub fn is_empty(&self) -> bool {
+ if !self.0.this_entries.is_empty() {
+ return false;
+ }
+ self.0
+ .super_obj
+ .as_ref()
+ .map(|s| s.is_empty())
+ .unwrap_or(true)
+ }
+
/// Run callback for every field found in object
pub(crate) fn enum_fields(&self, handler: &mut impl FnMut(&IStr, &Visibility) -> bool) -> bool {
if let Some(s) = &self.0.super_obj {
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth1use crate::{2 builtin::{3 call_builtin,4 manifest::{5 manifest_json_ex, manifest_yaml_ex, ManifestJsonOptions, ManifestType,6 ManifestYamlOptions,7 },8 },9 error::{Error::*, LocError},10 evaluate,11 function::{parse_function_call, parse_function_call_map, place_args},12 native::NativeCallback,13 throw, Context, ObjValue, Result,14};15use jrsonnet_gc::{Gc, GcCell, Trace};16use jrsonnet_interner::IStr;17use jrsonnet_parser::{ArgsDesc, ExprLocation, LocExpr, ParamsDesc};18use jrsonnet_types::ValType;19use std::{collections::HashMap, fmt::Debug, rc::Rc};2021pub trait LazyValValue: Trace {22 fn get(self: Box<Self>) -> Result<Val>;23}2425#[derive(Trace)]26#[trivially_drop]27enum LazyValInternals {28 Computed(Val),29 Errored(LocError),30 Waiting(Box<dyn LazyValValue>),31 Pending,32}3334#[derive(Clone, Trace)]35#[trivially_drop]36pub struct LazyVal(Gc<GcCell<LazyValInternals>>);37impl LazyVal {38 pub fn new(f: Box<dyn LazyValValue>) -> Self {39 Self(Gc::new(GcCell::new(LazyValInternals::Waiting(f))))40 }41 pub fn new_resolved(val: Val) -> Self {42 Self(Gc::new(GcCell::new(LazyValInternals::Computed(val))))43 }44 pub fn evaluate(&self) -> Result<Val> {45 match &*self.0.borrow() {46 LazyValInternals::Computed(v) => return Ok(v.clone()),47 LazyValInternals::Errored(e) => return Err(e.clone()),48 LazyValInternals::Pending => return Err(RecursiveLazyValueEvaluation.into()),49 _ => (),50 };51 let value = if let LazyValInternals::Waiting(value) =52 std::mem::replace(&mut *self.0.borrow_mut(), LazyValInternals::Pending)53 {54 value55 } else {56 unreachable!()57 };58 let new_value = match value.get() {59 Ok(v) => v,60 Err(e) => {61 *self.0.borrow_mut() = LazyValInternals::Errored(e.clone());62 return Err(e);63 }64 };65 *self.0.borrow_mut() = LazyValInternals::Computed(new_value.clone());66 Ok(new_value)67 }68}6970impl Debug for LazyVal {71 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {72 write!(f, "Lazy")73 }74}75impl PartialEq for LazyVal {76 fn eq(&self, other: &Self) -> bool {77 Gc::ptr_eq(&self.0, &other.0)78 }79}8081#[derive(Debug, PartialEq, Trace)]82#[trivially_drop]83pub struct FuncDesc {84 pub name: IStr,85 pub ctx: Context,86 pub params: ParamsDesc,87 pub body: LocExpr,88}8990#[derive(Debug, Trace)]91#[trivially_drop]92pub enum FuncVal {93 /// Plain function implemented in jsonnet94 Normal(FuncDesc),95 /// Standard library function96 Intrinsic(IStr),97 /// Library functions implemented in native98 NativeExt(IStr, Gc<NativeCallback>),99}100101impl PartialEq for FuncVal {102 fn eq(&self, other: &Self) -> bool {103 match (self, other) {104 (Self::Normal(a), Self::Normal(b)) => a == b,105 (Self::Intrinsic(an), Self::Intrinsic(bn)) => an == bn,106 (Self::NativeExt(an, _), Self::NativeExt(bn, _)) => an == bn,107 (..) => false,108 }109 }110}111impl FuncVal {112 pub fn is_ident(&self) -> bool {113 matches!(&self, Self::Intrinsic(n) if n as &str == "id")114 }115 pub fn name(&self) -> IStr {116 match self {117 Self::Normal(normal) => normal.name.clone(),118 Self::Intrinsic(name) => format!("std.{}", name).into(),119 Self::NativeExt(n, _) => format!("native.{}", n).into(),120 }121 }122 pub fn evaluate(123 &self,124 call_ctx: Context,125 loc: Option<&ExprLocation>,126 args: &ArgsDesc,127 tailstrict: bool,128 ) -> Result<Val> {129 match self {130 Self::Normal(func) => {131 let ctx = parse_function_call(132 call_ctx,133 func.ctx.clone(),134 &func.params,135 args,136 tailstrict,137 )?;138 evaluate(ctx, &func.body)139 }140 Self::Intrinsic(name) => call_builtin(call_ctx, loc, name, args),141 Self::NativeExt(_name, handler) => {142 let args =143 parse_function_call(call_ctx, Context::new(), &handler.params, args, true)?;144 let mut out_args = Vec::with_capacity(handler.params.len());145 for p in handler.params.0.iter() {146 out_args.push(args.binding(p.0.clone())?.evaluate()?);147 }148 Ok(handler.call(loc.map(|l| l.0.clone()), &out_args)?)149 }150 }151 }152153 pub fn evaluate_map(154 &self,155 call_ctx: Context,156 args: &HashMap<IStr, Val>,157 tailstrict: bool,158 ) -> Result<Val> {159 match self {160 Self::Normal(func) => {161 let ctx = parse_function_call_map(162 call_ctx,163 Some(func.ctx.clone()),164 &func.params,165 args,166 tailstrict,167 )?;168 evaluate(ctx, &func.body)169 }170 Self::Intrinsic(_) => todo!(),171 Self::NativeExt(_, _) => todo!(),172 }173 }174175 pub fn evaluate_values(&self, call_ctx: Context, args: &[Val]) -> Result<Val> {176 match self {177 Self::Normal(func) => {178 let ctx = place_args(call_ctx, Some(func.ctx.clone()), &func.params, args)?;179 evaluate(ctx, &func.body)180 }181 Self::Intrinsic(_) => todo!(),182 Self::NativeExt(_, _) => todo!(),183 }184 }185}186187#[derive(Clone)]188pub enum ManifestFormat {189 YamlStream(Box<ManifestFormat>),190 Yaml(usize),191 Json(usize),192 ToString,193 String,194}195196#[derive(Debug, Clone, Trace)]197#[trivially_drop]198pub enum ArrValue {199 Lazy(Gc<Vec<LazyVal>>),200 Eager(Gc<Vec<Val>>),201 Extended(Box<(Self, Self)>),202}203impl ArrValue {204 pub fn new_eager() -> Self {205 Self::Eager(Gc::new(Vec::new()))206 }207208 pub fn len(&self) -> usize {209 match self {210 Self::Lazy(l) => l.len(),211 Self::Eager(e) => e.len(),212 Self::Extended(v) => v.0.len() + v.1.len(),213 }214 }215216 pub fn is_empty(&self) -> bool {217 self.len() == 0218 }219220 pub fn get(&self, index: usize) -> Result<Option<Val>> {221 match self {222 Self::Lazy(vec) => {223 if let Some(v) = vec.get(index) {224 Ok(Some(v.evaluate()?))225 } else {226 Ok(None)227 }228 }229 Self::Eager(vec) => Ok(vec.get(index).cloned()),230 Self::Extended(v) => {231 let a_len = v.0.len();232 if a_len > index {233 v.0.get(index)234 } else {235 v.1.get(index - a_len)236 }237 }238 }239 }240241 pub fn get_lazy(&self, index: usize) -> Option<LazyVal> {242 match self {243 Self::Lazy(vec) => vec.get(index).cloned(),244 Self::Eager(vec) => vec.get(index).cloned().map(LazyVal::new_resolved),245 Self::Extended(v) => {246 let a_len = v.0.len();247 if a_len > index {248 v.0.get_lazy(index)249 } else {250 v.1.get_lazy(index - a_len)251 }252 }253 }254 }255256 pub fn evaluated(&self) -> Result<Gc<Vec<Val>>> {257 Ok(match self {258 Self::Lazy(vec) => {259 let mut out = Vec::with_capacity(vec.len());260 for item in vec.iter() {261 out.push(item.evaluate()?);262 }263 Gc::new(out)264 }265 Self::Eager(vec) => vec.clone(),266 Self::Extended(_v) => {267 let mut out = Vec::with_capacity(self.len());268 for item in self.iter() {269 out.push(item?);270 }271 Gc::new(out)272 }273 })274 }275276 pub fn iter(&self) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {277 (0..self.len()).map(move |idx| match self {278 Self::Lazy(l) => l[idx].evaluate(),279 Self::Eager(e) => Ok(e[idx].clone()),280 Self::Extended(_) => self.get(idx).map(|e| e.unwrap()),281 })282 }283284 pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = LazyVal> + '_ {285 (0..self.len()).map(move |idx| match self {286 Self::Lazy(l) => l[idx].clone(),287 Self::Eager(e) => LazyVal::new_resolved(e[idx].clone()),288 Self::Extended(_) => self.get_lazy(idx).unwrap(),289 })290 }291292 pub fn reversed(self) -> Self {293 match self {294 Self::Lazy(vec) => {295 let mut out = (&vec as &Vec<_>).clone();296 out.reverse();297 Self::Lazy(Gc::new(out))298 }299 Self::Eager(vec) => {300 let mut out = (&vec as &Vec<_>).clone();301 out.reverse();302 Self::Eager(Gc::new(out))303 }304 Self::Extended(b) => Self::Extended(Box::new((b.1.reversed(), b.0.reversed()))),305 }306 }307308 pub fn map(self, mapper: impl Fn(Val) -> Result<Val>) -> Result<Self> {309 let mut out = Vec::with_capacity(self.len());310311 for value in self.iter() {312 out.push(mapper(value?)?);313 }314315 Ok(Self::Eager(Gc::new(out)))316 }317318 pub fn filter(self, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {319 let mut out = Vec::with_capacity(self.len());320321 for value in self.iter() {322 let value = value?;323 if filter(&value)? {324 out.push(value);325 }326 }327328 Ok(Self::Eager(Gc::new(out)))329 }330331 pub fn ptr_eq(a: &Self, b: &Self) -> bool {332 match (a, b) {333 (Self::Lazy(a), Self::Lazy(b)) => Gc::ptr_eq(a, b),334 (Self::Eager(a), Self::Eager(b)) => Gc::ptr_eq(a, b),335 _ => false,336 }337 }338}339340impl From<Vec<LazyVal>> for ArrValue {341 fn from(v: Vec<LazyVal>) -> Self {342 Self::Lazy(Gc::new(v))343 }344}345346impl From<Vec<Val>> for ArrValue {347 fn from(v: Vec<Val>) -> Self {348 Self::Eager(Gc::new(v))349 }350}351352pub enum IndexableVal {353 Str(IStr),354 Arr(ArrValue),355}356357#[derive(Debug, Clone, Trace)]358#[trivially_drop]359pub enum Val {360 Bool(bool),361 Null,362 Str(IStr),363 Num(f64),364 Arr(ArrValue),365 Obj(ObjValue),366 Func(Gc<FuncVal>),367}368369macro_rules! matches_unwrap {370 ($e: expr, $p: pat, $r: expr) => {371 match $e {372 $p => $r,373 _ => panic!("no match"),374 }375 };376}377impl Val {378 /// Creates `Val::Num` after checking for numeric overflow.379 /// As numbers are `f64`, we can just check for their finity.380 pub fn new_checked_num(num: f64) -> Result<Self> {381 if num.is_finite() {382 Ok(Self::Num(num))383 } else {384 throw!(RuntimeError("overflow".into()))385 }386 }387388 pub fn assert_type(&self, context: &'static str, val_type: ValType) -> Result<()> {389 let this_type = self.value_type();390 if this_type != val_type {391 throw!(TypeMismatch(context, vec![val_type], this_type))392 } else {393 Ok(())394 }395 }396 pub fn unwrap_num(self) -> Result<f64> {397 Ok(matches_unwrap!(self, Self::Num(v), v))398 }399 pub fn unwrap_str(self) -> Result<IStr> {400 Ok(matches_unwrap!(self, Self::Str(v), v))401 }402 pub fn unwrap_arr(self) -> Result<ArrValue> {403 Ok(matches_unwrap!(self, Self::Arr(v), v))404 }405 pub fn unwrap_func(self) -> Result<Gc<FuncVal>> {406 Ok(matches_unwrap!(self, Self::Func(v), v))407 }408 pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {409 self.assert_type(context, ValType::Bool)?;410 Ok(matches_unwrap!(self, Self::Bool(v), v))411 }412 pub fn try_cast_str(self, context: &'static str) -> Result<IStr> {413 self.assert_type(context, ValType::Str)?;414 Ok(matches_unwrap!(self, Self::Str(v), v))415 }416 pub fn try_cast_num(self, context: &'static str) -> Result<f64> {417 self.assert_type(context, ValType::Num)?;418 self.unwrap_num()419 }420 pub fn try_cast_nullable_num(self, context: &'static str) -> Result<Option<f64>> {421 Ok(match self {422 Val::Null => None,423 Val::Num(num) => Some(num),424 _ => throw!(TypeMismatch(425 context,426 vec![ValType::Null, ValType::Num],427 self.value_type()428 )),429 })430 }431 pub const fn value_type(&self) -> ValType {432 match self {433 Self::Str(..) => ValType::Str,434 Self::Num(..) => ValType::Num,435 Self::Arr(..) => ValType::Arr,436 Self::Obj(..) => ValType::Obj,437 Self::Bool(_) => ValType::Bool,438 Self::Null => ValType::Null,439 Self::Func(..) => ValType::Func,440 }441 }442443 pub fn to_string(&self) -> Result<IStr> {444 Ok(match self {445 Self::Bool(true) => "true".into(),446 Self::Bool(false) => "false".into(),447 Self::Null => "null".into(),448 Self::Str(s) => s.clone(),449 v => manifest_json_ex(450 v,451 &ManifestJsonOptions {452 padding: "",453 mtype: ManifestType::ToString,454 },455 )?456 .into(),457 })458 }459460 /// Expects value to be object, outputs (key, manifested value) pairs461 pub fn manifest_multi(&self, ty: &ManifestFormat) -> Result<Vec<(IStr, IStr)>> {462 let obj = match self {463 Self::Obj(obj) => obj,464 _ => throw!(MultiManifestOutputIsNotAObject),465 };466 let keys = obj.fields();467 let mut out = Vec::with_capacity(keys.len());468 for key in keys {469 let value = obj470 .get(key.clone())?471 .expect("item in object")472 .manifest(ty)?;473 out.push((key, value));474 }475 Ok(out)476 }477478 /// Expects value to be array, outputs manifested values479 pub fn manifest_stream(&self, ty: &ManifestFormat) -> Result<Vec<IStr>> {480 let arr = match self {481 Self::Arr(a) => a,482 _ => throw!(StreamManifestOutputIsNotAArray),483 };484 let mut out = Vec::with_capacity(arr.len());485 for i in arr.iter() {486 out.push(i?.manifest(ty)?);487 }488 Ok(out)489 }490491 pub fn manifest(&self, ty: &ManifestFormat) -> Result<IStr> {492 Ok(match ty {493 ManifestFormat::YamlStream(format) => {494 let arr = match self {495 Self::Arr(a) => a,496 _ => throw!(StreamManifestOutputIsNotAArray),497 };498 let mut out = String::new();499500 match format as &ManifestFormat {501 ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),502 ManifestFormat::String => throw!(StreamManifestCannotNestString),503 _ => {}504 };505506 if !arr.is_empty() {507 for v in arr.iter() {508 out.push_str("---\n");509 out.push_str(&v?.manifest(format)?);510 out.push('\n');511 }512 out.push_str("...");513 }514515 out.into()516 }517 ManifestFormat::Yaml(padding) => self.to_yaml(*padding)?,518 ManifestFormat::Json(padding) => self.to_json(*padding)?,519 ManifestFormat::ToString => self.to_string()?,520 ManifestFormat::String => match self {521 Self::Str(s) => s.clone(),522 _ => throw!(StringManifestOutputIsNotAString),523 },524 })525 }526527 /// For manifestification528 pub fn to_json(&self, padding: usize) -> Result<IStr> {529 manifest_json_ex(530 self,531 &ManifestJsonOptions {532 padding: &" ".repeat(padding),533 mtype: if padding == 0 {534 ManifestType::Minify535 } else {536 ManifestType::Manifest537 },538 },539 )540 .map(|s| s.into())541 }542543 /// Calls `std.manifestJson`544 pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {545 manifest_json_ex(546 self,547 &ManifestJsonOptions {548 padding: &" ".repeat(padding),549 mtype: ManifestType::Std,550 },551 )552 .map(|s| s.into())553 }554555 pub fn to_yaml(&self, padding: usize) -> Result<IStr> {556 let padding = &" ".repeat(padding);557 manifest_yaml_ex(558 self,559 &ManifestYamlOptions {560 padding,561 arr_element_padding: padding,562 },563 )564 .map(|s| s.into())565 }566 pub fn into_indexable(self) -> Result<IndexableVal> {567 Ok(match self {568 Val::Str(s) => IndexableVal::Str(s),569 Val::Arr(arr) => IndexableVal::Arr(arr),570 _ => throw!(ValueIsNotIndexable(self.value_type())),571 })572 }573}574575const fn is_function_like(val: &Val) -> bool {576 matches!(val, Val::Func(_))577}578579/// Native implementation of `std.primitiveEquals`580pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {581 Ok(match (val_a, val_b) {582 (Val::Bool(a), Val::Bool(b)) => a == b,583 (Val::Null, Val::Null) => true,584 (Val::Str(a), Val::Str(b)) => a == b,585 (Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,586 (Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(587 "primitiveEquals operates on primitive types, got array".into(),588 )),589 (Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(590 "primitiveEquals operates on primitive types, got object".into(),591 )),592 (a, b) if is_function_like(a) && is_function_like(b) => {593 throw!(RuntimeError("cannot test equality of functions".into()))594 }595 (_, _) => false,596 })597}598599/// Native implementation of `std.equals`600pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {601 if val_a.value_type() != val_b.value_type() {602 return Ok(false);603 }604 match (val_a, val_b) {605 (Val::Arr(a), Val::Arr(b)) => {606 if ArrValue::ptr_eq(a, b) {607 return Ok(true);608 }609 if a.len() != b.len() {610 return Ok(false);611 }612 for (a, b) in a.iter().zip(b.iter()) {613 if !equals(&a?, &b?)? {614 return Ok(false);615 }616 }617 Ok(true)618 }619 (Val::Obj(a), Val::Obj(b)) => {620 if ObjValue::ptr_eq(a, b) {621 return Ok(true);622 }623 let fields = a.fields();624 if fields != b.fields() {625 return Ok(false);626 }627 for field in fields {628 if !equals(&a.get(field.clone())?.unwrap(), &b.get(field)?.unwrap())? {629 return Ok(false);630 }631 }632 Ok(true)633 }634 (a, b) => Ok(primitive_equals(a, b)?),635 }636}crates/jrsonnet-stdlib/src/std.jsonnetdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/std.jsonnet
+++ b/crates/jrsonnet-stdlib/src/std.jsonnet
@@ -374,88 +374,9 @@
manifestJsonEx:: $intrinsic(manifestJsonEx),
- manifestYamlDoc(value, indent_array_in_object=false)::
- local aux(v, path, cindent) =
- if v == true then
- 'true'
- else if v == false then
- 'false'
- else if v == null then
- 'null'
- else if std.isNumber(v) then
- '' + v
- else if std.isString(v) then
- local len = std.length(v);
- if len == 0 then
- '""'
- else if v[len - 1] == '\n' then
- local split = std.split(v, '\n');
- std.join('\n' + cindent + ' ', ['|'] + split[0:std.length(split) - 1])
- else
- std.escapeStringJson(v)
- else if std.isFunction(v) then
- error 'Tried to manifest function at ' + path
- else if std.isArray(v) then
- if std.length(v) == 0 then
- '[]'
- else
- local params(value) =
- if std.isArray(value) && std.length(value) > 0 then {
- // While we could avoid the new line, it yields YAML that is
- // hard to read, e.g.:
- // - - - 1
- // - 2
- // - - 3
- // - 4
- new_indent: cindent + ' ',
- space: '\n' + self.new_indent,
- } else if std.isObject(value) && std.length(value) > 0 then {
- new_indent: cindent + ' ',
- // In this case we can start on the same line as the - because the indentation
- // matches up then. The converse is not true, because fields are not always
- // 1 character long.
- space: ' ',
- } else {
- // In this case, new_indent is only used in the case of multi-line strings.
- new_indent: cindent,
- space: ' ',
- };
- local range = std.range(0, std.length(v) - 1);
- local parts = [
- '-' + param.space + aux(v[i], path + [i], param.new_indent)
- for i in range
- for param in [params(v[i])]
- ];
- std.join('\n' + cindent, parts)
- else if std.isObject(v) then
- if std.length(v) == 0 then
- '{}'
- else
- local params(value) =
- if std.isArray(value) && std.length(value) > 0 then {
- // Not indenting allows e.g.
- // ports:
- // - 80
- // instead of
- // ports:
- // - 80
- new_indent: if indent_array_in_object then cindent + ' ' else cindent,
- space: '\n' + self.new_indent,
- } else if std.isObject(value) && std.length(value) > 0 then {
- new_indent: cindent + ' ',
- space: '\n' + self.new_indent,
- } else {
- // In this case, new_indent is only used in the case of multi-line strings.
- new_indent: cindent,
- space: ' ',
- };
- local lines = [
- std.escapeStringJson(k) + ':' + param.space + aux(v[k], path + [k], param.new_indent)
- for k in std.objectFields(v)
- for param in [params(v[k])]
- ];
- std.join('\n' + cindent, lines);
- aux(value, [], ''),
+ manifestYamlDocImpl:: $intrinsic(manifestYamlDocImpl),
+
+ manifestYamlDoc(value, indent_array_in_object=false):: std.manifestYamlDocImpl(value, indent_array_in_object),
manifestYamlStream(value, indent_array_in_object=false, c_document_end=true)::
if !std.isArray(value) then