difftreelog
refactor! remove Lazy from Val
in: master
Now lazy is used only in objects/arrays BREAKING CHANGE: value_type() is never fails
9 files changed
bindings/jsonnet/src/val_extract.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/val_extract.rs
+++ b/bindings/jsonnet/src/val_extract.rs
@@ -9,7 +9,7 @@
#[no_mangle]
pub extern "C" fn jsonnet_json_extract_string(_vm: &EvaluationState, v: &Val) -> *mut c_char {
- match v.unwrap_if_lazy().unwrap() {
+ match v {
Val::Str(s) => CString::new(&*s as &str).unwrap().into_raw(),
_ => std::ptr::null_mut(),
}
@@ -20,9 +20,9 @@
v: &Val,
out: &mut c_double,
) -> c_int {
- match v.unwrap_if_lazy().unwrap() {
+ match v {
Val::Num(n) => {
- *out = n;
+ *out = *n;
1
}
_ => 0,
@@ -30,7 +30,7 @@
}
#[no_mangle]
pub extern "C" fn jsonnet_json_extract_bool(_vm: &EvaluationState, v: &Val) -> c_int {
- match v.unwrap_if_lazy().unwrap() {
+ match v {
Val::Bool(false) => 0,
Val::Bool(true) => 1,
_ => 2,
@@ -38,7 +38,7 @@
}
#[no_mangle]
pub extern "C" fn jsonnet_json_extract_null(_vm: &EvaluationState, v: &Val) -> c_int {
- match v.unwrap_if_lazy().unwrap() {
+ match v {
Val::Null => 1,
_ => 0,
}
crates/jrsonnet-evaluator/src/builtin/format.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/format.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/format.rs
@@ -1,7 +1,8 @@
//! faster std.format impl
#![allow(clippy::too_many_arguments)]
-use crate::{error::Error::*, throw, LocError, ObjValue, Result, Val, ValType};
+use crate::{error::Error::*, throw, LocError, ObjValue, Result, Val};
+use jrsonnet_types::ValType;
use thiserror::Error;
#[derive(Debug, Clone, Error)]
@@ -573,7 +574,7 @@
);
}
}
- ConvTypeV::Char => match value.clone().unwrap_if_lazy()? {
+ ConvTypeV::Char => match value.clone() {
Val::Num(n) => tmp_out.push(
std::char::from_u32(n as u32)
.ok_or_else(|| InvalidUnicodeCodepointGot(n as u32))?,
@@ -590,7 +591,7 @@
throw!(TypeMismatch(
"%c requires number/string",
vec![ValType::Num, ValType::Str],
- value.value_type()?,
+ value.value_type(),
));
}
},
crates/jrsonnet-evaluator/src/builtin/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/manifest.rs
@@ -33,9 +33,9 @@
) -> Result<()> {
use std::fmt::Write;
let mtype = options.mtype;
- match val.unwrap_if_lazy()? {
+ match val {
Val::Bool(v) => {
- if v {
+ if *v {
buf.push_str("true");
} else {
buf.push_str("false");
@@ -63,7 +63,7 @@
}
}
buf.push_str(cur_padding);
- manifest_json_ex_buf(item, buf, cur_padding, options)?;
+ manifest_json_ex_buf(&item?, buf, cur_padding, options)?;
}
cur_padding.truncate(old_len);
@@ -118,7 +118,6 @@
buf.push('}');
}
Val::Func(_) => throw!(RuntimeError("tried to manifest function".into())),
- Val::Lazy(_) => unreachable!(),
};
Ok(())
}
crates/jrsonnet-evaluator/src/builtin/sort.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/sort.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/sort.rs
@@ -46,7 +46,6 @@
let mut sort_type = SortKeyType::Unknown;
for i in values.iter_mut() {
let i = key_getter(i);
- i.inplace_unwrap()?;
match (i, sort_type) {
(Val::Str(_), SortKeyType::Unknown) => sort_type = SortKeyType::String,
(Val::Num(_), SortKeyType::Unknown) => sort_type = SortKeyType::Number,
crates/jrsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth1use crate::{1use crate::{2 context_creator, error::Error::*, future_wrapper, lazy_val, push, throw, with_state, Context,2 context_creator, error::Error::*, future_wrapper, lazy_val, push, throw, with_state, Context,3 ContextCreator, FuncDesc, FuncVal, LazyBinding, LazyVal, ObjMember, ObjValue, Result, Val,3 ContextCreator, FuncDesc, FuncVal, LazyBinding, LazyVal, ObjMember, ObjValue, Result, Val,4 ValType,5};4};6use closure::closure;5use closure::closure;7use jrsonnet_parser::{6use jrsonnet_parser::{8 ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, ExprLocation, FieldMember,7 ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, ExprLocation, FieldMember,9 ForSpecData, IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc, UnaryOpType,8 ForSpecData, IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc, UnaryOpType,10 Visibility,9 Visibility,11};10};11use jrsonnet_types::ValType;12use rustc_hash::FxHashMap;12use rustc_hash::FxHashMap;13use std::{collections::HashMap, rc::Rc};13use std::{collections::HashMap, rc::Rc};141461 Ok(match field_name {61 Ok(match field_name {62 jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),62 jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),63 jrsonnet_parser::FieldName::Dyn(expr) => {63 jrsonnet_parser::FieldName::Dyn(expr) => {64 let lazy = evaluate(context, expr)?;64 let value = evaluate(context, expr)?;65 let value = lazy.unwrap_if_lazy()?;66 if matches!(value, Val::Null) {65 if matches!(value, Val::Null) {67 None66 None68 } else {67 } else {747375pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {74pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {76 Ok(match (op, b) {75 Ok(match (op, b) {77 (o, Val::Lazy(l)) => evaluate_unary_op(o, &l.evaluate()?)?,78 (UnaryOpType::Not, Val::Bool(v)) => Val::Bool(!v),76 (UnaryOpType::Not, Val::Bool(v)) => Val::Bool(!v),79 (UnaryOpType::Minus, Val::Num(n)) => Val::Num(-*n),77 (UnaryOpType::Minus, Val::Num(n)) => Val::Num(-*n),80 (UnaryOpType::BitNot, Val::Num(n)) => Val::Num(!(*n as i32) as f64),78 (UnaryOpType::BitNot, Val::Num(n)) => Val::Num(!(*n as i32) as f64),81 (op, o) => throw!(UnaryOperatorDoesNotOperateOnType(op, o.value_type()?)),79 (op, o) => throw!(UnaryOperatorDoesNotOperateOnType(op, o.value_type())),82 })80 })83}81}848294 (o, Val::Str(s)) => Val::Str(format!("{}{}", o.clone().to_string()?, s).into()),92 (o, Val::Str(s)) => Val::Str(format!("{}{}", o.clone().to_string()?, s).into()),959396 (Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.with_super(v1.clone())),94 (Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.with_super(v1.clone())),97 (Val::Arr(a), Val::Arr(b)) => Val::Arr(Rc::new([&a[..], &b[..]].concat())),95 (Val::Arr(a), Val::Arr(b)) => {96 let mut out = Vec::with_capacity(a.len() + b.len());97 out.extend(a.iter_lazy());98 out.extend(b.iter_lazy());99 Val::Arr(out.into())100 }98 (Val::Num(v1), Val::Num(v2)) => Val::new_checked_num(v1 + v2)?,101 (Val::Num(v1), Val::Num(v2)) => Val::new_checked_num(v1 + v2)?,99 _ => throw!(BinaryOperatorDoesNotOperateOnValues(102 _ => throw!(BinaryOperatorDoesNotOperateOnValues(100 BinaryOpType::Add,103 BinaryOpType::Add,101 a.value_type()?,104 a.value_type(),102 b.value_type()?,105 b.value_type(),103 )),106 )),104 })107 })105}108}111 b: &LocExpr,114 b: &LocExpr,112) -> Result<Val> {115) -> Result<Val> {113 Ok(116 Ok(match (evaluate(context.clone(), a)?, op, b) {114 match (evaluate(context.clone(), a)?.unwrap_if_lazy()?, op, b) {115 (Val::Bool(true), BinaryOpType::Or, _o) => Val::Bool(true),117 (Val::Bool(true), BinaryOpType::Or, _o) => Val::Bool(true),116 (Val::Bool(false), BinaryOpType::And, _o) => Val::Bool(false),118 (Val::Bool(false), BinaryOpType::And, _o) => Val::Bool(false),117 (a, op, eb) => {119 (a, op, eb) => evaluate_binary_op_normal(&a, op, &evaluate(context, eb)?)?,118 evaluate_binary_op_normal(&a, op, &evaluate(context, eb)?.unwrap_if_lazy()?)?119 }120 },120 })121 )122}121}177176178 _ => throw!(BinaryOperatorDoesNotOperateOnValues(177 _ => throw!(BinaryOperatorDoesNotOperateOnValues(179 op,178 op,180 a.value_type()?,179 a.value_type(),181 b.value_type()?,180 b.value_type(),182 )),181 )),183 })182 })184}183}200 None199 None201 }200 }202 }201 }203 Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {202 Some(CompSpec::ForSpec(ForSpecData(var, expr))) => match evaluate(context.clone(), expr)? {204 match evaluate(context.clone(), expr)?.unwrap_if_lazy()? {205 Val::Arr(list) => {203 Val::Arr(list) => {206 let mut out = Vec::new();204 let mut out = Vec::new();207 for item in list.iter() {205 for item in list.iter() {208 let item = item.unwrap_if_lazy()?;209 out.push(evaluate_comp(206 out.push(evaluate_comp(210 context.clone().with_var(var.clone(), item.clone()),207 context.clone().with_var(var.clone(), item?.clone()),211 value,208 value,212 &specs[1..],209 &specs[1..],213 )?);210 )?);214 }211 }215 Some(out.into_iter().flatten().flatten().collect())212 Some(out.into_iter().flatten().flatten().collect())216 }213 }217 _ => throw!(InComprehensionCanOnlyIterateOverArray),214 _ => throw!(InComprehensionCanOnlyIterateOverArray),218 }215 },219 }220 })216 })221}217}222218375 },371 },376 );372 );377 }373 }378 v => throw!(FieldMustBeStringGot(v.value_type()?)),374 v => throw!(FieldMustBeStringGot(v.value_type())),379 }375 }380 }376 }381377391 loc: &Option<ExprLocation>,387 loc: &Option<ExprLocation>,392 tailstrict: bool,388 tailstrict: bool,393) -> Result<Val> {389) -> Result<Val> {394 let lazy = evaluate(context.clone(), value)?;390 let value = evaluate(context.clone(), value)?;395 let value = lazy.unwrap_if_lazy()?;396 Ok(match value {391 Ok(match value {397 Val::Func(f) => {392 Val::Func(f) => {398 let body = || f.evaluate(context, loc, args, tailstrict);393 let body = || f.evaluate(context, loc, args, tailstrict);402 push(loc, || format!("function <{}> call", f.name()), body)?397 push(loc, || format!("function <{}> call", f.name()), body)?403 }398 }404 }399 }405 v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type()?)),400 v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),406 })401 })407}402}408403436 Var(name) => push(431 Var(name) => push(437 loc,432 loc,438 || format!("variable <{}>", name),433 || format!("variable <{}>", name),439 || Ok(Val::Lazy(context.binding(name.clone())?).unwrap_if_lazy()?),434 || Ok(context.binding(name.clone())?.evaluate()?),440 )?,435 )?,441 Index(LocExpr(v, _), index) if matches!(&**v, Expr::Literal(LiteralType::Super)) => {436 Index(LocExpr(v, _), index) if matches!(&**v, Expr::Literal(LiteralType::Super)) => {442 let name = evaluate(context.clone(), index)?.try_cast_str("object index")?;437 let name = evaluate(context.clone(), index)?.try_cast_str("object index")?;443 context438 context444 .super_obj()439 .super_obj()445 .clone()440 .clone()446 .expect("no super found")441 .expect("no super found")447 .get_raw(name, &context.this().clone().expect("no this found"))?442 .get_raw(name, Some(&context.this().clone().expect("no this found")))?448 .expect("value not found")443 .expect("value not found")449 }444 }450 Index(value, index) => {445 Index(value, index) => {451 match (446 match (evaluate(context.clone(), value)?, evaluate(context, index)?) {452 evaluate(context.clone(), value)?.unwrap_if_lazy()?,453 evaluate(context, index)?,454 ) {455 (Val::Obj(v), Val::Str(s)) => {447 (Val::Obj(v), Val::Str(s)) => {456 let sn = s.clone();448 let sn = s.clone();459 || format!("field <{}> access", sn),451 || format!("field <{}> access", sn),460 || {452 || {461 if let Some(v) = v.get(s.clone())? {453 if let Some(v) = v.get(s.clone())? {462 Ok(v.unwrap_if_lazy()?)454 Ok(v)463 } else if v.get("__intrinsic_namespace__".into())?.is_some() {455 } else if v.get("__intrinsic_namespace__".into())?.is_some() {464 Ok(Val::Func(Rc::new(FuncVal::Intrinsic(s))))456 Ok(Val::Func(Rc::new(FuncVal::Intrinsic(s))))465 } else {457 } else {471 (Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(463 (Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(472 ValType::Obj,464 ValType::Obj,473 ValType::Str,465 ValType::Str,474 n.value_type()?,466 n.value_type(),475 )),467 )),476468477 (Val::Arr(v), Val::Num(n)) => {469 (Val::Arr(v), Val::Num(n)) => {478 if n.fract() > f64::EPSILON {470 if n.fract() > f64::EPSILON {479 throw!(FractionalIndex)471 throw!(FractionalIndex)480 }472 }481 v.get(n as usize)473 v.get(n as usize)?482 .ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?474 .ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?483 .clone()475 .clone()484 .unwrap_if_lazy()?485 }476 }486 (Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),477 (Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),487 (Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(478 (Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(488 ValType::Arr,479 ValType::Arr,489 ValType::Num,480 ValType::Num,490 n.value_type()?,481 n.value_type(),491 )),482 )),492483493 (Val::Str(s), Val::Num(n)) => Val::Str(484 (Val::Str(s), Val::Num(n)) => Val::Str(500 (Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(491 (Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(501 ValType::Str,492 ValType::Str,502 ValType::Num,493 ValType::Num,503 n.value_type()?,494 n.value_type(),504 )),495 )),505496506 (v, _) => throw!(CantIndexInto(v.value_type()?)),497 (v, _) => throw!(CantIndexInto(v.value_type())),507 }498 }508 }499 }509 LocalExpr(bindings, returned) => {500 LocalExpr(bindings, returned) => {529 Arr(items) => {520 Arr(items) => {530 let mut out = Vec::with_capacity(items.len());521 let mut out = Vec::with_capacity(items.len());531 for item in items {522 for item in items {532 out.push(Val::Lazy(lazy_val!(523 out.push(LazyVal::new(Box::new(533 closure!(clone context, clone item, || {524 closure!(clone context, clone item, || {534 evaluate(context.clone(), &item)525 evaluate(context.clone(), &item)535 })526 }),536 )));527 )));537 }528 }538 Val::Arr(Rc::new(out))529 Val::Arr(out.into())539 }530 }540 ArrComp(expr, comp_specs) => Val::Arr(531 ArrComp(expr, comp_specs) => Val::Arr(541 // First comp_spec should be for_spec, so no "None" possible here532 // First comp_spec should be for_spec, so no "None" possible here542 Rc::new(evaluate_comp(context, &|ctx| evaluate(ctx, expr), comp_specs)?.unwrap()),533 evaluate_comp(context, &|ctx| evaluate(ctx, expr), comp_specs)?534 .unwrap()535 .into(),543 ),536 ),544 Obj(body) => Val::Obj(evaluate_object(context, body)?),537 Obj(body) => Val::Obj(evaluate_object(context, body)?),545 ObjExtend(s, t) => evaluate_add_op(538 ObjExtend(s, t) => evaluate_add_op(crates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -22,11 +22,10 @@
} else {
Number::from_f64(*n).expect("to json number")
}),
- Val::Lazy(v) => (&v.evaluate()?).try_into()?,
Val::Arr(a) => {
let mut out = Vec::with_capacity(a.len());
for item in a.iter() {
- out.push(item.try_into()?);
+ out.push((&item?).try_into()?);
}
Self::Array(out)
}
@@ -55,9 +54,9 @@
Value::Array(a) => {
let mut out = Vec::with_capacity(a.len());
for v in a {
- out.push(v.into());
+ out.push(LazyVal::new_resolved(v.into()));
}
- Self::Arr(Rc::new(out))
+ Self::Arr(out.into())
}
Value::Object(o) => {
let mut entries = HashMap::with_capacity(o.len());
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -102,9 +102,10 @@
visible_fields
}
pub fn get(&self, key: Rc<str>) -> Result<Option<Val>> {
- Ok(self.get_raw(key, self)?)
+ Ok(self.get_raw(key, None)?)
}
- pub(crate) fn get_raw(&self, key: Rc<str>, real_this: &Self) -> Result<Option<Val>> {
+ pub(crate) fn get_raw(&self, key: Rc<str>, real_this: Option<&Self>) -> Result<Option<Val>> {
+ let real_this = real_this.unwrap_or(self);
let cache_key = (key.clone(), Rc::as_ptr(&real_this.0) as usize);
if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {
@@ -115,7 +116,7 @@
(Some(k), Some(s)) => {
let our = self.evaluate_this(k, real_this)?;
if k.add {
- s.get_raw(key, real_this)?
+ s.get_raw(key, Some(real_this))?
.map_or(Ok(Some(our.clone())), |v| {
Ok(Some(evaluate_add_op(&v, &our)?))
})
@@ -123,7 +124,7 @@
Ok(Some(our))
}
}
- (None, Some(s)) => s.get_raw(key, real_this),
+ (None, Some(s)) => s.get_raw(key, Some(real_this)),
(None, None) => Ok(None),
}?;
self.0
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -10,12 +10,8 @@
throw, with_state, Context, ObjValue, Result,
};
use jrsonnet_parser::{el, Arg, ArgsDesc, Expr, ExprLocation, LiteralType, LocExpr, ParamsDesc};
-use std::{
- cell::RefCell,
- collections::HashMap,
- fmt::{Debug, Display},
- rc::Rc,
-};
+use jrsonnet_types::ValType;
+use std::{cell::RefCell, collections::HashMap, fmt::Debug, rc::Rc};
enum LazyValInternals {
Computed(Val),
@@ -166,43 +162,108 @@
}
}
-#[derive(Debug, Clone, Copy, PartialEq)]
-pub enum ValType {
- Bool,
- Null,
- Str,
- Num,
- Arr,
- Obj,
- Func,
+#[derive(Clone)]
+pub enum ManifestFormat {
+ YamlStream(Box<ManifestFormat>),
+ Yaml(usize),
+ Json(usize),
+ ToString,
+ String,
+}
+
+#[derive(Debug, Clone)]
+pub enum ArrValue {
+ Lazy(Rc<Vec<LazyVal>>),
+ Eager(Rc<Vec<Val>>),
}
-impl ValType {
- pub const fn name(&self) -> &'static str {
- use ValType::*;
+impl ArrValue {
+ pub fn len(&self) -> usize {
match self {
- Bool => "boolean",
- Null => "null",
- Str => "string",
- Num => "number",
- Arr => "array",
- Obj => "object",
- Func => "function",
+ ArrValue::Lazy(l) => l.len(),
+ ArrValue::Eager(e) => e.len(),
}
}
+
+ pub fn is_empty(&self) -> bool {
+ self.len() == 0
+ }
+
+ pub fn get(&self, index: usize) -> Result<Option<Val>> {
+ match self {
+ ArrValue::Lazy(vec) => {
+ if let Some(v) = vec.get(index) {
+ Ok(Some(v.evaluate()?))
+ } else {
+ Ok(None)
+ }
+ }
+ ArrValue::Eager(vec) => Ok(vec.get(index).cloned()),
+ }
+ }
+
+ pub fn get_lazy(&self, index: usize) -> Option<LazyVal> {
+ match self {
+ ArrValue::Lazy(vec) => vec.get(index).cloned(),
+ ArrValue::Eager(vec) => vec
+ .get(index)
+ .cloned()
+ .map(|val| LazyVal::new_resolved(val)),
+ }
+ }
+
+ pub fn evaluated(&self) -> Result<Rc<Vec<Val>>> {
+ Ok(match self {
+ ArrValue::Lazy(vec) => {
+ let mut out = Vec::with_capacity(vec.len());
+ for item in vec.iter() {
+ out.push(item.evaluate()?);
+ }
+ Rc::new(out)
+ }
+ ArrValue::Eager(vec) => vec.clone(),
+ })
+ }
+
+ pub fn iter(&self) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {
+ (0..self.len()).map(move |idx| match self {
+ ArrValue::Lazy(l) => l[idx].evaluate(),
+ ArrValue::Eager(e) => Ok(e[idx].clone()),
+ })
+ }
+
+ pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = LazyVal> + '_ {
+ (0..self.len()).map(move |idx| match self {
+ ArrValue::Lazy(l) => l[idx].clone(),
+ ArrValue::Eager(e) => LazyVal::new_resolved(e[idx].clone()),
+ })
+ }
+
+ pub fn reversed(self) -> Self {
+ match self {
+ ArrValue::Lazy(vec) => {
+ let mut out = (&vec as &Vec<_>).clone();
+ out.reverse();
+ Self::Lazy(Rc::new(out))
+ }
+ ArrValue::Eager(vec) => {
+ let mut out = (&vec as &Vec<_>).clone();
+ out.reverse();
+ Self::Eager(Rc::new(out))
+ }
+ }
+ }
}
-impl Display for ValType {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(f, "{}", self.name())
+
+impl From<Vec<LazyVal>> for ArrValue {
+ fn from(v: Vec<LazyVal>) -> Self {
+ Self::Lazy(Rc::new(v))
}
}
-#[derive(Clone)]
-pub enum ManifestFormat {
- YamlStream(Box<ManifestFormat>),
- Yaml(usize),
- Json(usize),
- ToString,
- String,
+impl From<Vec<Val>> for ArrValue {
+ fn from(v: Vec<Val>) -> Self {
+ Self::Eager(Rc::new(v))
+ }
}
#[derive(Debug, Clone)]
@@ -211,8 +272,7 @@
Null,
Str(Rc<str>),
Num(f64),
- Lazy(LazyVal),
- Arr(Rc<Vec<Val>>),
+ Arr(ArrValue),
Obj(ObjValue),
Func(Rc<FuncVal>),
}
@@ -237,40 +297,33 @@
}
pub fn assert_type(&self, context: &'static str, val_type: ValType) -> Result<()> {
- let this_type = self.value_type()?;
+ let this_type = self.value_type();
if this_type != val_type {
throw!(TypeMismatch(context, vec![val_type], this_type))
} else {
Ok(())
}
}
+ pub fn unwrap_num(self) -> Result<f64> {
+ Ok(matches_unwrap!(self, Self::Num(v), v))
+ }
+ pub fn unwrap_func(self) -> Result<Rc<FuncVal>> {
+ Ok(matches_unwrap!(self, Self::Func(v), v))
+ }
pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {
self.assert_type(context, ValType::Bool)?;
- Ok(matches_unwrap!(self.unwrap_if_lazy()?, Self::Bool(v), v))
+ Ok(matches_unwrap!(self, Self::Bool(v), v))
}
pub fn try_cast_str(self, context: &'static str) -> Result<Rc<str>> {
self.assert_type(context, ValType::Str)?;
- Ok(matches_unwrap!(self.unwrap_if_lazy()?, Self::Str(v), v))
+ Ok(matches_unwrap!(self, Self::Str(v), v))
}
pub fn try_cast_num(self, context: &'static str) -> Result<f64> {
self.assert_type(context, ValType::Num)?;
- Ok(matches_unwrap!(self.unwrap_if_lazy()?, Self::Num(v), v))
- }
- pub fn inplace_unwrap(&mut self) -> Result<()> {
- while let Self::Lazy(lazy) = self {
- *self = lazy.evaluate()?;
- }
- Ok(())
+ self.unwrap_num()
}
- pub fn unwrap_if_lazy(&self) -> Result<Self> {
- Ok(if let Self::Lazy(v) = self {
- v.evaluate()?.unwrap_if_lazy()?
- } else {
- self.clone()
- })
- }
- pub fn value_type(&self) -> Result<ValType> {
- Ok(match self {
+ pub fn value_type(&self) -> ValType {
+ match self {
Self::Str(..) => ValType::Str,
Self::Num(..) => ValType::Num,
Self::Arr(..) => ValType::Arr,
@@ -278,16 +331,15 @@
Self::Bool(_) => ValType::Bool,
Self::Null => ValType::Null,
Self::Func(..) => ValType::Func,
- Self::Lazy(_) => self.clone().unwrap_if_lazy()?.value_type()?,
- })
+ }
}
pub fn to_string(&self) -> Result<Rc<str>> {
- Ok(match self.unwrap_if_lazy()? {
+ Ok(match self {
Self::Bool(true) => "true".into(),
Self::Bool(false) => "false".into(),
Self::Null => "null".into(),
- Self::Str(s) => s,
+ Self::Str(s) => s.clone(),
v => manifest_json_ex(
&v,
&ManifestJsonOptions {
@@ -325,7 +377,7 @@
};
let mut out = Vec::with_capacity(arr.len());
for i in arr.iter() {
- out.push(i.manifest(ty)?);
+ out.push(i?.manifest(ty)?);
}
Ok(out)
}
@@ -348,7 +400,7 @@
if !arr.is_empty() {
for v in arr.iter() {
out.push_str("---\n");
- out.push_str(&v.manifest(format)?);
+ out.push_str(&v?.manifest(format)?);
out.push('\n');
}
out.push_str("...");
@@ -456,7 +508,7 @@
/// Native implementation of `std.primitiveEquals`
pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {
- Ok(match (val_a.unwrap_if_lazy()?, val_b.unwrap_if_lazy()?) {
+ Ok(match (val_a, val_b) {
(Val::Bool(a), Val::Bool(b)) => a == b,
(Val::Null, Val::Null) => true,
(Val::Str(a), Val::Str(b)) => a == b,
@@ -476,10 +528,7 @@
/// Native implementation of `std.equals`
pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {
- let val_a = val_a.unwrap_if_lazy()?;
- let val_b = val_b.unwrap_if_lazy()?;
-
- if val_a.value_type()? != val_b.value_type()? {
+ if val_a.value_type() != val_b.value_type() {
return Ok(false);
}
match (val_a, val_b) {
@@ -489,7 +538,7 @@
return Ok(false);
}
for (a, b) in a.iter().zip(b.iter()) {
- if !equals(&a.unwrap_if_lazy()?, &b.unwrap_if_lazy()?)? {
+ if !equals(&a?, &b?)? {
return Ok(false);
}
}
crates/jrsonnet-parser/src/expr.rsdiffbeforeafterboth--- a/crates/jrsonnet-parser/src/expr.rs
+++ b/crates/jrsonnet-parser/src/expr.rs
@@ -97,6 +97,7 @@
Mul,
Div,
+ /// Implemented as intrinsic, put here for completeness
Mod,
Add,