difftreelog
feat configurable array element padding
in: master
3 files changed
crates/jrsonnet-evaluator/src/builtin/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/manifest.rs
@@ -158,8 +158,16 @@
}
pub struct ManifestYamlOptions<'s> {
+ /// Padding before fields, i.e
+ /// a:
+ /// b:
+ /// ^^ this
pub padding: &'s str,
- pub pad_arrays: bool,
+ /// Padding before array elements in objects
+ /// a:
+ /// - 1
+ /// ^^ this
+ pub arr_element_padding: &'s str,
}
pub fn manifest_yaml_ex(val: &Val, options: &ManifestYamlOptions<'_>) -> Result<String> {
@@ -252,9 +260,7 @@
if !a.is_empty() {
buf.push('\n');
buf.push_str(cur_padding);
- if options.pad_arrays {
- buf.push_str(options.padding);
- }
+ buf.push_str(options.arr_element_padding);
} else {
buf.push(' ');
}
@@ -271,8 +277,8 @@
}
let prev_len = cur_padding.len();
if let Val::Arr(a) = &item {
- if !a.is_empty() && options.pad_arrays {
- cur_padding.push_str(options.padding);
+ if !a.is_empty() {
+ cur_padding.push_str(options.arr_element_padding);
}
} else if let Val::Obj(a) = &item {
if !a.is_empty() {
crates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/mod.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/mod.rs
@@ -781,7 +781,7 @@
], {
Ok(Val::Str(manifest_yaml_ex(&value, &ManifestYamlOptions {
padding: " ",
- pad_arrays: indent_array_in_object,
+ arr_element_padding: if indent_array_in_object { " " } else { "" },
})?.into()))
})
}
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 manifest_yaml_ex(557 self,558 &ManifestYamlOptions {559 padding: &" ".repeat(padding),560 pad_arrays: true,561 },562 )563 .map(|s| s.into())564 }565 pub fn into_indexable(self) -> Result<IndexableVal> {566 Ok(match self {567 Val::Str(s) => IndexableVal::Str(s),568 Val::Arr(arr) => IndexableVal::Arr(arr),569 _ => throw!(ValueIsNotIndexable(self.value_type())),570 })571 }572}573574const fn is_function_like(val: &Val) -> bool {575 matches!(val, Val::Func(_))576}577578/// Native implementation of `std.primitiveEquals`579pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {580 Ok(match (val_a, val_b) {581 (Val::Bool(a), Val::Bool(b)) => a == b,582 (Val::Null, Val::Null) => true,583 (Val::Str(a), Val::Str(b)) => a == b,584 (Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,585 (Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(586 "primitiveEquals operates on primitive types, got array".into(),587 )),588 (Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(589 "primitiveEquals operates on primitive types, got object".into(),590 )),591 (a, b) if is_function_like(a) && is_function_like(b) => {592 throw!(RuntimeError("cannot test equality of functions".into()))593 }594 (_, _) => false,595 })596}597598/// Native implementation of `std.equals`599pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {600 if val_a.value_type() != val_b.value_type() {601 return Ok(false);602 }603 match (val_a, val_b) {604 (Val::Arr(a), Val::Arr(b)) => {605 if ArrValue::ptr_eq(a, b) {606 return Ok(true);607 }608 if a.len() != b.len() {609 return Ok(false);610 }611 for (a, b) in a.iter().zip(b.iter()) {612 if !equals(&a?, &b?)? {613 return Ok(false);614 }615 }616 Ok(true)617 }618 (Val::Obj(a), Val::Obj(b)) => {619 if ObjValue::ptr_eq(a, b) {620 return Ok(true);621 }622 let fields = a.fields();623 if fields != b.fields() {624 return Ok(false);625 }626 for field in fields {627 if !equals(&a.get(field.clone())?.unwrap(), &b.get(field)?.unwrap())? {628 return Ok(false);629 }630 }631 Ok(true)632 }633 (a, b) => Ok(primitive_equals(a, b)?),634 }635}