git.delta.rocks / jrsonnet / refs/commits / 028057c85dc5

difftreelog

refactor! remove Lazy from Val

Yaroslav Bolyukin2020-12-01parent: #194642f.patch.diff
in: master
Now lazy is used only in objects/arrays
BREAKING CHANGE: value_type() is never fails

9 files changed

modifiedbindings/jsonnet/src/val_extract.rsdiffbeforeafterboth
99
10#[no_mangle]10#[no_mangle]
11pub extern "C" fn jsonnet_json_extract_string(_vm: &EvaluationState, v: &Val) -> *mut c_char {11pub extern "C" fn jsonnet_json_extract_string(_vm: &EvaluationState, v: &Val) -> *mut c_char {
12 match v.unwrap_if_lazy().unwrap() {12 match v {
13 Val::Str(s) => CString::new(&*s as &str).unwrap().into_raw(),13 Val::Str(s) => CString::new(&*s as &str).unwrap().into_raw(),
14 _ => std::ptr::null_mut(),14 _ => std::ptr::null_mut(),
15 }15 }
20 v: &Val,20 v: &Val,
21 out: &mut c_double,21 out: &mut c_double,
22) -> c_int {22) -> c_int {
23 match v.unwrap_if_lazy().unwrap() {23 match v {
24 Val::Num(n) => {24 Val::Num(n) => {
25 *out = n;25 *out = *n;
26 126 1
27 }27 }
28 _ => 0,28 _ => 0,
29 }29 }
30}30}
31#[no_mangle]31#[no_mangle]
32pub extern "C" fn jsonnet_json_extract_bool(_vm: &EvaluationState, v: &Val) -> c_int {32pub extern "C" fn jsonnet_json_extract_bool(_vm: &EvaluationState, v: &Val) -> c_int {
33 match v.unwrap_if_lazy().unwrap() {33 match v {
34 Val::Bool(false) => 0,34 Val::Bool(false) => 0,
35 Val::Bool(true) => 1,35 Val::Bool(true) => 1,
36 _ => 2,36 _ => 2,
37 }37 }
38}38}
39#[no_mangle]39#[no_mangle]
40pub extern "C" fn jsonnet_json_extract_null(_vm: &EvaluationState, v: &Val) -> c_int {40pub extern "C" fn jsonnet_json_extract_null(_vm: &EvaluationState, v: &Val) -> c_int {
41 match v.unwrap_if_lazy().unwrap() {41 match v {
42 Val::Null => 1,42 Val::Null => 1,
43 _ => 0,43 _ => 0,
44 }44 }
modifiedcrates/jrsonnet-evaluator/src/builtin/format.rsdiffbeforeafterboth
1//! faster std.format impl1//! faster std.format impl
2#![allow(clippy::too_many_arguments)]2#![allow(clippy::too_many_arguments)]
33
4use crate::{error::Error::*, throw, LocError, ObjValue, Result, Val, ValType};4use crate::{error::Error::*, throw, LocError, ObjValue, Result, Val};
5use jrsonnet_types::ValType;
5use thiserror::Error;6use thiserror::Error;
67
7#[derive(Debug, Clone, Error)]8#[derive(Debug, Clone, Error)]
573 );574 );
574 }575 }
575 }576 }
576 ConvTypeV::Char => match value.clone().unwrap_if_lazy()? {577 ConvTypeV::Char => match value.clone() {
577 Val::Num(n) => tmp_out.push(578 Val::Num(n) => tmp_out.push(
578 std::char::from_u32(n as u32)579 std::char::from_u32(n as u32)
579 .ok_or_else(|| InvalidUnicodeCodepointGot(n as u32))?,580 .ok_or_else(|| InvalidUnicodeCodepointGot(n as u32))?,
590 throw!(TypeMismatch(591 throw!(TypeMismatch(
591 "%c requires number/string",592 "%c requires number/string",
592 vec![ValType::Num, ValType::Str],593 vec![ValType::Num, ValType::Str],
593 value.value_type()?,594 value.value_type(),
594 ));595 ));
595 }596 }
596 },597 },
modifiedcrates/jrsonnet-evaluator/src/builtin/manifest.rsdiffbeforeafterboth
33) -> Result<()> {33) -> Result<()> {
34 use std::fmt::Write;34 use std::fmt::Write;
35 let mtype = options.mtype;35 let mtype = options.mtype;
36 match val.unwrap_if_lazy()? {36 match val {
37 Val::Bool(v) => {37 Val::Bool(v) => {
38 if v {38 if *v {
39 buf.push_str("true");39 buf.push_str("true");
40 } else {40 } else {
41 buf.push_str("false");41 buf.push_str("false");
63 }63 }
64 }64 }
65 buf.push_str(cur_padding);65 buf.push_str(cur_padding);
66 manifest_json_ex_buf(item, buf, cur_padding, options)?;66 manifest_json_ex_buf(&item?, buf, cur_padding, options)?;
67 }67 }
68 cur_padding.truncate(old_len);68 cur_padding.truncate(old_len);
6969
118 buf.push('}');118 buf.push('}');
119 }119 }
120 Val::Func(_) => throw!(RuntimeError("tried to manifest function".into())),120 Val::Func(_) => throw!(RuntimeError("tried to manifest function".into())),
121 Val::Lazy(_) => unreachable!(),
122 };121 };
123 Ok(())122 Ok(())
124}123}
modifiedcrates/jrsonnet-evaluator/src/builtin/sort.rsdiffbeforeafterboth
46 let mut sort_type = SortKeyType::Unknown;46 let mut sort_type = SortKeyType::Unknown;
47 for i in values.iter_mut() {47 for i in values.iter_mut() {
48 let i = key_getter(i);48 let i = key_getter(i);
49 i.inplace_unwrap()?;
50 match (i, sort_type) {49 match (i, sort_type) {
51 (Val::Str(_), SortKeyType::Unknown) => sort_type = SortKeyType::String,50 (Val::Str(_), SortKeyType::Unknown) => sort_type = SortKeyType::String,
52 (Val::Num(_), SortKeyType::Unknown) => sort_type = SortKeyType::Number,51 (Val::Num(_), SortKeyType::Unknown) => sort_type = SortKeyType::Number,
modifiedcrates/jrsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth
1use 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};
1414
61 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 None
68 } else {67 } else {
7473
75pub 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}
8482
94 (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()),
9593
96 (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}
177176
178 _ => 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 None
201 }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}
222218
375 },371 },
376 );372 );
377 }373 }
378 v => throw!(FieldMustBeStringGot(v.value_type()?)),374 v => throw!(FieldMustBeStringGot(v.value_type())),
379 }375 }
380 }376 }
381377
391 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}
408403
436 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 context
444 .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 )),
476468
477 (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 )),
492483
493 (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 )),
505496
506 (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 here
542 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(
modifiedcrates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth
22 } else {22 } else {
23 Number::from_f64(*n).expect("to json number")23 Number::from_f64(*n).expect("to json number")
24 }),24 }),
25 Val::Lazy(v) => (&v.evaluate()?).try_into()?,
26 Val::Arr(a) => {25 Val::Arr(a) => {
27 let mut out = Vec::with_capacity(a.len());26 let mut out = Vec::with_capacity(a.len());
28 for item in a.iter() {27 for item in a.iter() {
29 out.push(item.try_into()?);28 out.push((&item?).try_into()?);
30 }29 }
31 Self::Array(out)30 Self::Array(out)
32 }31 }
55 Value::Array(a) => {54 Value::Array(a) => {
56 let mut out = Vec::with_capacity(a.len());55 let mut out = Vec::with_capacity(a.len());
57 for v in a {56 for v in a {
58 out.push(v.into());57 out.push(LazyVal::new_resolved(v.into()));
59 }58 }
60 Self::Arr(Rc::new(out))59 Self::Arr(out.into())
61 }60 }
62 Value::Object(o) => {61 Value::Object(o) => {
63 let mut entries = HashMap::with_capacity(o.len());62 let mut entries = HashMap::with_capacity(o.len());
modifiedcrates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth
102 visible_fields102 visible_fields
103 }103 }
104 pub fn get(&self, key: Rc<str>) -> Result<Option<Val>> {104 pub fn get(&self, key: Rc<str>) -> Result<Option<Val>> {
105 Ok(self.get_raw(key, self)?)105 Ok(self.get_raw(key, None)?)
106 }106 }
107 pub(crate) fn get_raw(&self, key: Rc<str>, real_this: &Self) -> Result<Option<Val>> {107 pub(crate) fn get_raw(&self, key: Rc<str>, real_this: Option<&Self>) -> Result<Option<Val>> {
108 let real_this = real_this.unwrap_or(self);
108 let cache_key = (key.clone(), Rc::as_ptr(&real_this.0) as usize);109 let cache_key = (key.clone(), Rc::as_ptr(&real_this.0) as usize);
109110
110 if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {111 if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {
115 (Some(k), Some(s)) => {116 (Some(k), Some(s)) => {
116 let our = self.evaluate_this(k, real_this)?;117 let our = self.evaluate_this(k, real_this)?;
117 if k.add {118 if k.add {
118 s.get_raw(key, real_this)?119 s.get_raw(key, Some(real_this))?
119 .map_or(Ok(Some(our.clone())), |v| {120 .map_or(Ok(Some(our.clone())), |v| {
120 Ok(Some(evaluate_add_op(&v, &our)?))121 Ok(Some(evaluate_add_op(&v, &our)?))
121 })122 })
122 } else {123 } else {
123 Ok(Some(our))124 Ok(Some(our))
124 }125 }
125 }126 }
126 (None, Some(s)) => s.get_raw(key, real_this),127 (None, Some(s)) => s.get_raw(key, Some(real_this)),
127 (None, None) => Ok(None),128 (None, None) => Ok(None),
128 }?;129 }?;
129 self.0130 self.0
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
10 throw, with_state, Context, ObjValue, Result,10 throw, with_state, Context, ObjValue, Result,
11};11};
12use jrsonnet_parser::{el, Arg, ArgsDesc, Expr, ExprLocation, LiteralType, LocExpr, ParamsDesc};12use jrsonnet_parser::{el, Arg, ArgsDesc, Expr, ExprLocation, LiteralType, LocExpr, ParamsDesc};
13use jrsonnet_types::ValType;
13use std::{14use std::{cell::RefCell, collections::HashMap, fmt::Debug, rc::Rc};
14 cell::RefCell,
15 collections::HashMap,
16 fmt::{Debug, Display},
17 rc::Rc,
18};
1915
20enum LazyValInternals {16enum LazyValInternals {
166 }162 }
167}163}
168
169#[derive(Debug, Clone, Copy, PartialEq)]
170pub enum ValType {
171 Bool,
172 Null,
173 Str,
174 Num,
175 Arr,
176 Obj,
177 Func,
178}
179impl ValType {
180 pub const fn name(&self) -> &'static str {
181 use ValType::*;
182 match self {
183 Bool => "boolean",
184 Null => "null",
185 Str => "string",
186 Num => "number",
187 Arr => "array",
188 Obj => "object",
189 Func => "function",
190 }
191 }
192}
193impl Display for ValType {
194 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
195 write!(f, "{}", self.name())
196 }
197}
198164
199#[derive(Clone)]165#[derive(Clone)]
200pub enum ManifestFormat {166pub enum ManifestFormat {
205 String,171 String,
206}172}
173
174#[derive(Debug, Clone)]
175pub enum ArrValue {
176 Lazy(Rc<Vec<LazyVal>>),
177 Eager(Rc<Vec<Val>>),
178}
179impl ArrValue {
180 pub fn len(&self) -> usize {
181 match self {
182 ArrValue::Lazy(l) => l.len(),
183 ArrValue::Eager(e) => e.len(),
184 }
185 }
186
187 pub fn is_empty(&self) -> bool {
188 self.len() == 0
189 }
190
191 pub fn get(&self, index: usize) -> Result<Option<Val>> {
192 match self {
193 ArrValue::Lazy(vec) => {
194 if let Some(v) = vec.get(index) {
195 Ok(Some(v.evaluate()?))
196 } else {
197 Ok(None)
198 }
199 }
200 ArrValue::Eager(vec) => Ok(vec.get(index).cloned()),
201 }
202 }
203
204 pub fn get_lazy(&self, index: usize) -> Option<LazyVal> {
205 match self {
206 ArrValue::Lazy(vec) => vec.get(index).cloned(),
207 ArrValue::Eager(vec) => vec
208 .get(index)
209 .cloned()
210 .map(|val| LazyVal::new_resolved(val)),
211 }
212 }
213
214 pub fn evaluated(&self) -> Result<Rc<Vec<Val>>> {
215 Ok(match self {
216 ArrValue::Lazy(vec) => {
217 let mut out = Vec::with_capacity(vec.len());
218 for item in vec.iter() {
219 out.push(item.evaluate()?);
220 }
221 Rc::new(out)
222 }
223 ArrValue::Eager(vec) => vec.clone(),
224 })
225 }
226
227 pub fn iter(&self) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {
228 (0..self.len()).map(move |idx| match self {
229 ArrValue::Lazy(l) => l[idx].evaluate(),
230 ArrValue::Eager(e) => Ok(e[idx].clone()),
231 })
232 }
233
234 pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = LazyVal> + '_ {
235 (0..self.len()).map(move |idx| match self {
236 ArrValue::Lazy(l) => l[idx].clone(),
237 ArrValue::Eager(e) => LazyVal::new_resolved(e[idx].clone()),
238 })
239 }
240
241 pub fn reversed(self) -> Self {
242 match self {
243 ArrValue::Lazy(vec) => {
244 let mut out = (&vec as &Vec<_>).clone();
245 out.reverse();
246 Self::Lazy(Rc::new(out))
247 }
248 ArrValue::Eager(vec) => {
249 let mut out = (&vec as &Vec<_>).clone();
250 out.reverse();
251 Self::Eager(Rc::new(out))
252 }
253 }
254 }
255}
256
257impl From<Vec<LazyVal>> for ArrValue {
258 fn from(v: Vec<LazyVal>) -> Self {
259 Self::Lazy(Rc::new(v))
260 }
261}
262
263impl From<Vec<Val>> for ArrValue {
264 fn from(v: Vec<Val>) -> Self {
265 Self::Eager(Rc::new(v))
266 }
267}
207268
208#[derive(Debug, Clone)]269#[derive(Debug, Clone)]
209pub enum Val {270pub enum Val {
210 Bool(bool),271 Bool(bool),
211 Null,272 Null,
212 Str(Rc<str>),273 Str(Rc<str>),
213 Num(f64),274 Num(f64),
214 Lazy(LazyVal),
215 Arr(Rc<Vec<Val>>),275 Arr(ArrValue),
216 Obj(ObjValue),276 Obj(ObjValue),
217 Func(Rc<FuncVal>),277 Func(Rc<FuncVal>),
218}278}
237 }297 }
238298
239 pub fn assert_type(&self, context: &'static str, val_type: ValType) -> Result<()> {299 pub fn assert_type(&self, context: &'static str, val_type: ValType) -> Result<()> {
240 let this_type = self.value_type()?;300 let this_type = self.value_type();
241 if this_type != val_type {301 if this_type != val_type {
242 throw!(TypeMismatch(context, vec![val_type], this_type))302 throw!(TypeMismatch(context, vec![val_type], this_type))
243 } else {303 } else {
244 Ok(())304 Ok(())
245 }305 }
246 }306 }
307 pub fn unwrap_num(self) -> Result<f64> {
308 Ok(matches_unwrap!(self, Self::Num(v), v))
309 }
310 pub fn unwrap_func(self) -> Result<Rc<FuncVal>> {
311 Ok(matches_unwrap!(self, Self::Func(v), v))
312 }
247 pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {313 pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {
248 self.assert_type(context, ValType::Bool)?;314 self.assert_type(context, ValType::Bool)?;
249 Ok(matches_unwrap!(self.unwrap_if_lazy()?, Self::Bool(v), v))315 Ok(matches_unwrap!(self, Self::Bool(v), v))
250 }316 }
251 pub fn try_cast_str(self, context: &'static str) -> Result<Rc<str>> {317 pub fn try_cast_str(self, context: &'static str) -> Result<Rc<str>> {
252 self.assert_type(context, ValType::Str)?;318 self.assert_type(context, ValType::Str)?;
253 Ok(matches_unwrap!(self.unwrap_if_lazy()?, Self::Str(v), v))319 Ok(matches_unwrap!(self, Self::Str(v), v))
254 }320 }
255 pub fn try_cast_num(self, context: &'static str) -> Result<f64> {321 pub fn try_cast_num(self, context: &'static str) -> Result<f64> {
256 self.assert_type(context, ValType::Num)?;322 self.assert_type(context, ValType::Num)?;
257 Ok(matches_unwrap!(self.unwrap_if_lazy()?, Self::Num(v), v))323 self.unwrap_num()
258 }324 }
259 pub fn inplace_unwrap(&mut self) -> Result<()> {
260 while let Self::Lazy(lazy) = self {
261 *self = lazy.evaluate()?;
262 }
263 Ok(())
264 }
265 pub fn unwrap_if_lazy(&self) -> Result<Self> {
266 Ok(if let Self::Lazy(v) = self {
267 v.evaluate()?.unwrap_if_lazy()?
268 } else {
269 self.clone()
270 })
271 }
272 pub fn value_type(&self) -> Result<ValType> {325 pub fn value_type(&self) -> ValType {
273 Ok(match self {326 match self {
274 Self::Str(..) => ValType::Str,327 Self::Str(..) => ValType::Str,
275 Self::Num(..) => ValType::Num,328 Self::Num(..) => ValType::Num,
276 Self::Arr(..) => ValType::Arr,329 Self::Arr(..) => ValType::Arr,
277 Self::Obj(..) => ValType::Obj,330 Self::Obj(..) => ValType::Obj,
278 Self::Bool(_) => ValType::Bool,331 Self::Bool(_) => ValType::Bool,
279 Self::Null => ValType::Null,332 Self::Null => ValType::Null,
280 Self::Func(..) => ValType::Func,333 Self::Func(..) => ValType::Func,
281 Self::Lazy(_) => self.clone().unwrap_if_lazy()?.value_type()?,
282 })334 }
283 }335 }
284336
285 pub fn to_string(&self) -> Result<Rc<str>> {337 pub fn to_string(&self) -> Result<Rc<str>> {
286 Ok(match self.unwrap_if_lazy()? {338 Ok(match self {
287 Self::Bool(true) => "true".into(),339 Self::Bool(true) => "true".into(),
288 Self::Bool(false) => "false".into(),340 Self::Bool(false) => "false".into(),
289 Self::Null => "null".into(),341 Self::Null => "null".into(),
290 Self::Str(s) => s,342 Self::Str(s) => s.clone(),
291 v => manifest_json_ex(343 v => manifest_json_ex(
292 &v,344 &v,
293 &ManifestJsonOptions {345 &ManifestJsonOptions {
325 };377 };
326 let mut out = Vec::with_capacity(arr.len());378 let mut out = Vec::with_capacity(arr.len());
327 for i in arr.iter() {379 for i in arr.iter() {
328 out.push(i.manifest(ty)?);380 out.push(i?.manifest(ty)?);
329 }381 }
330 Ok(out)382 Ok(out)
331 }383 }
348 if !arr.is_empty() {400 if !arr.is_empty() {
349 for v in arr.iter() {401 for v in arr.iter() {
350 out.push_str("---\n");402 out.push_str("---\n");
351 out.push_str(&v.manifest(format)?);403 out.push_str(&v?.manifest(format)?);
352 out.push('\n');404 out.push('\n');
353 }405 }
354 out.push_str("...");406 out.push_str("...");
456508
457/// Native implementation of `std.primitiveEquals`509/// Native implementation of `std.primitiveEquals`
458pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {510pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {
459 Ok(match (val_a.unwrap_if_lazy()?, val_b.unwrap_if_lazy()?) {511 Ok(match (val_a, val_b) {
460 (Val::Bool(a), Val::Bool(b)) => a == b,512 (Val::Bool(a), Val::Bool(b)) => a == b,
461 (Val::Null, Val::Null) => true,513 (Val::Null, Val::Null) => true,
462 (Val::Str(a), Val::Str(b)) => a == b,514 (Val::Str(a), Val::Str(b)) => a == b,
476528
477/// Native implementation of `std.equals`529/// Native implementation of `std.equals`
478pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {530pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {
479 let val_a = val_a.unwrap_if_lazy()?;
480 let val_b = val_b.unwrap_if_lazy()?;
481
482 if val_a.value_type()? != val_b.value_type()? {531 if val_a.value_type() != val_b.value_type() {
483 return Ok(false);532 return Ok(false);
484 }533 }
485 match (val_a, val_b) {534 match (val_a, val_b) {
489 return Ok(false);538 return Ok(false);
490 }539 }
491 for (a, b) in a.iter().zip(b.iter()) {540 for (a, b) in a.iter().zip(b.iter()) {
492 if !equals(&a.unwrap_if_lazy()?, &b.unwrap_if_lazy()?)? {541 if !equals(&a?, &b?)? {
493 return Ok(false);542 return Ok(false);
494 }543 }
495 }544 }
modifiedcrates/jrsonnet-parser/src/expr.rsdiffbeforeafterboth
97 Mul,97 Mul,
98 Div,98 Div,
9999
100 /// Implemented as intrinsic, put here for completeness
100 Mod,101 Mod,
101102
102 Add,103 Add,