difftreelog
fix use new ArrValue variants
in: master
2 files changed
crates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/mod.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/mod.rs
@@ -379,7 +379,7 @@
1, to: ty!(number) => Val::Num;
], {
if to < from {
- return Ok(Val::Arr(Rc::new(Vec::new())))
+ return Ok(Val::Arr(ArrValue::new_eager()))
}
let mut out = Vec::with_capacity((1+to as usize-from as usize).max(0));
for i in from as usize..=to as usize {
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth1use crate::{2 builtin::{3 call_builtin,4 manifest::{manifest_json_ex, ManifestJsonOptions, ManifestType},5 },6 error::Error::*,7 evaluate,8 function::{parse_function_call, parse_function_call_map, place_args},9 native::NativeCallback,10 throw, with_state, Context, ObjValue, Result,11};12use jrsonnet_interner::IStr;13use jrsonnet_parser::{el, Arg, ArgsDesc, Expr, ExprLocation, LiteralType, LocExpr, ParamsDesc};14use jrsonnet_types::ValType;15use std::{cell::RefCell, collections::HashMap, fmt::Debug, rc::Rc};1617enum LazyValInternals {18 Computed(Val),19 Waiting(Box<dyn Fn() -> Result<Val>>),20}21#[derive(Clone)]22pub struct LazyVal(Rc<RefCell<LazyValInternals>>);23impl LazyVal {24 pub fn new(f: Box<dyn Fn() -> Result<Val>>) -> Self {25 Self(Rc::new(RefCell::new(LazyValInternals::Waiting(f))))26 }27 pub fn new_resolved(val: Val) -> Self {28 Self(Rc::new(RefCell::new(LazyValInternals::Computed(val))))29 }30 pub fn evaluate(&self) -> Result<Val> {31 let new_value = match &*self.0.borrow() {32 LazyValInternals::Computed(v) => return Ok(v.clone()),33 LazyValInternals::Waiting(f) => f()?,34 };35 *self.0.borrow_mut() = LazyValInternals::Computed(new_value.clone());36 Ok(new_value)37 }38}3940#[macro_export]41macro_rules! lazy_val {42 ($f: expr) => {43 $crate::LazyVal::new(Box::new($f))44 };45}46#[macro_export]47macro_rules! resolved_lazy_val {48 ($f: expr) => {49 $crate::LazyVal::new_resolved($f)50 };51}52impl Debug for LazyVal {53 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {54 write!(f, "Lazy")55 }56}57impl PartialEq for LazyVal {58 fn eq(&self, other: &Self) -> bool {59 Rc::ptr_eq(&self.0, &other.0)60 }61}6263#[derive(Debug, PartialEq)]64pub struct FuncDesc {65 pub name: IStr,66 pub ctx: Context,67 pub params: ParamsDesc,68 pub body: LocExpr,69}7071#[derive(Debug)]72pub enum FuncVal {73 /// Plain function implemented in jsonnet74 Normal(FuncDesc),75 /// Standard library function76 Intrinsic(IStr),77 /// Library functions implemented in native78 NativeExt(IStr, Rc<NativeCallback>),79}8081impl PartialEq for FuncVal {82 fn eq(&self, other: &Self) -> bool {83 match (self, other) {84 (Self::Normal(a), Self::Normal(b)) => a == b,85 (Self::Intrinsic(an), Self::Intrinsic(bn)) => an == bn,86 (Self::NativeExt(an, _), Self::NativeExt(bn, _)) => an == bn,87 (..) => false,88 }89 }90}91impl FuncVal {92 pub fn is_ident(&self) -> bool {93 matches!(&self, Self::Intrinsic(n) if n as &str == "id")94 }95 pub fn name(&self) -> IStr {96 match self {97 Self::Normal(normal) => normal.name.clone(),98 Self::Intrinsic(name) => format!("std.{}", name).into(),99 Self::NativeExt(n, _) => format!("native.{}", n).into(),100 }101 }102 pub fn evaluate(103 &self,104 call_ctx: Context,105 loc: Option<&ExprLocation>,106 args: &ArgsDesc,107 tailstrict: bool,108 ) -> Result<Val> {109 match self {110 Self::Normal(func) => {111 let ctx = parse_function_call(112 call_ctx,113 Some(func.ctx.clone()),114 &func.params,115 args,116 tailstrict,117 )?;118 evaluate(ctx, &func.body)119 }120 Self::Intrinsic(name) => call_builtin(call_ctx, loc, name, args),121 Self::NativeExt(_name, handler) => {122 let args = parse_function_call(call_ctx, None, &handler.params, args, true)?;123 let mut out_args = Vec::with_capacity(handler.params.len());124 for p in handler.params.0.iter() {125 out_args.push(args.binding(p.0.clone())?.evaluate()?);126 }127 Ok(handler.call(loc.clone().map(|l| l.0.clone()), &out_args)?)128 }129 }130 }131132 pub fn evaluate_map(133 &self,134 call_ctx: Context,135 args: &HashMap<IStr, Val>,136 tailstrict: bool,137 ) -> Result<Val> {138 match self {139 Self::Normal(func) => {140 let ctx = parse_function_call_map(141 call_ctx,142 Some(func.ctx.clone()),143 &func.params,144 args,145 tailstrict,146 )?;147 evaluate(ctx, &func.body)148 }149 Self::Intrinsic(_) => todo!(),150 Self::NativeExt(_, _) => todo!(),151 }152 }153154 pub fn evaluate_values(&self, call_ctx: Context, args: &[Val]) -> Result<Val> {155 match self {156 Self::Normal(func) => {157 let ctx = place_args(call_ctx, Some(func.ctx.clone()), &func.params, args)?;158 evaluate(ctx, &func.body)159 }160 Self::Intrinsic(_) => todo!(),161 Self::NativeExt(_, _) => todo!(),162 }163 }164}165166#[derive(Clone)]167pub enum ManifestFormat {168 YamlStream(Box<ManifestFormat>),169 Yaml(usize),170 Json(usize),171 ToString,172 String,173}174175#[derive(Debug, Clone)]176pub enum ArrValue {177 Lazy(Rc<Vec<LazyVal>>),178 Eager(Rc<Vec<Val>>),179 Extended(Box<(Self, Self)>),180}181impl ArrValue {182 pub fn len(&self) -> usize {183 match self {184 Self::Lazy(l) => l.len(),185 Self::Eager(e) => e.len(),186 Self::Extended(v) => v.0.len() + v.1.len(),187 }188 }189190 pub fn is_empty(&self) -> bool {191 self.len() == 0192 }193194 pub fn get(&self, index: usize) -> Result<Option<Val>> {195 match self {196 Self::Lazy(vec) => {197 if let Some(v) = vec.get(index) {198 Ok(Some(v.evaluate()?))199 } else {200 Ok(None)201 }202 }203 Self::Eager(vec) => Ok(vec.get(index).cloned()),204 Self::Extended(v) => {205 let a_len = v.0.len();206 if a_len > index {207 v.0.get(index)208 } else {209 v.1.get(index - a_len)210 }211 }212 }213 }214215 pub fn get_lazy(&self, index: usize) -> Option<LazyVal> {216 match self {217 Self::Lazy(vec) => vec.get(index).cloned(),218 Self::Eager(vec) => vec.get(index).cloned().map(LazyVal::new_resolved),219 Self::Extended(v) => {220 let a_len = v.0.len();221 if a_len > index {222 v.0.get_lazy(index)223 } else {224 v.1.get_lazy(index - a_len)225 }226 }227 }228 }229230 pub fn evaluated(&self) -> Result<Rc<Vec<Val>>> {231 Ok(match self {232 Self::Lazy(vec) => {233 let mut out = Vec::with_capacity(vec.len());234 for item in vec.iter() {235 out.push(item.evaluate()?);236 }237 Rc::new(out)238 }239 Self::Eager(vec) => vec.clone(),240 Self::Extended(_v) => {241 let mut out = Vec::with_capacity(self.len());242 for item in self.iter() {243 out.push(item?);244 }245 Rc::new(out)246 }247 })248 }249250 pub fn iter(&self) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {251 (0..self.len()).map(move |idx| match self {252 Self::Lazy(l) => l[idx].evaluate(),253 Self::Eager(e) => Ok(e[idx].clone()),254 Self::Extended(_) => self.get(idx).map(|e| e.unwrap()),255 })256 }257258 pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = LazyVal> + '_ {259 (0..self.len()).map(move |idx| match self {260 Self::Lazy(l) => l[idx].clone(),261 Self::Eager(e) => LazyVal::new_resolved(e[idx].clone()),262 Self::Extended(_) => self.get_lazy(idx).unwrap(),263 })264 }265266 pub fn reversed(self) -> Self {267 match self {268 Self::Lazy(vec) => {269 let mut out = (&vec as &Vec<_>).clone();270 out.reverse();271 Self::Lazy(Rc::new(out))272 }273 Self::Eager(vec) => {274 let mut out = (&vec as &Vec<_>).clone();275 out.reverse();276 Self::Eager(Rc::new(out))277 }278 Self::Extended(b) => Self::Extended(Box::new((b.1.reversed(), b.0.reversed()))),279 }280 }281282 pub fn ptr_eq(a: &Self, b: &Self) -> bool {283 match (a, b) {284 (Self::Lazy(a), Self::Lazy(b)) => Rc::ptr_eq(a, b),285 (Self::Eager(a), Self::Eager(b)) => Rc::ptr_eq(a, b),286 _ => false,287 }288 }289}290291impl From<Vec<LazyVal>> for ArrValue {292 fn from(v: Vec<LazyVal>) -> Self {293 Self::Lazy(Rc::new(v))294 }295}296297impl From<Vec<Val>> for ArrValue {298 fn from(v: Vec<Val>) -> Self {299 Self::Eager(Rc::new(v))300 }301}302303#[derive(Debug, Clone)]304pub enum Val {305 Bool(bool),306 Null,307 Str(IStr),308 Num(f64),309 Arr(ArrValue),310 Obj(ObjValue),311 Func(Rc<FuncVal>),312}313314macro_rules! matches_unwrap {315 ($e: expr, $p: pat, $r: expr) => {316 match $e {317 $p => $r,318 _ => panic!("no match"),319 }320 };321}322impl Val {323 /// Creates `Val::Num` after checking for numeric overflow.324 /// As numbers are `f64`, we can just check for their finity.325 pub fn new_checked_num(num: f64) -> Result<Self> {326 if num.is_finite() {327 Ok(Self::Num(num))328 } else {329 throw!(RuntimeError("overflow".into()))330 }331 }332333 pub fn assert_type(&self, context: &'static str, val_type: ValType) -> Result<()> {334 let this_type = self.value_type();335 if this_type != val_type {336 throw!(TypeMismatch(context, vec![val_type], this_type))337 } else {338 Ok(())339 }340 }341 pub fn unwrap_num(self) -> Result<f64> {342 Ok(matches_unwrap!(self, Self::Num(v), v))343 }344 pub fn unwrap_func(self) -> Result<Rc<FuncVal>> {345 Ok(matches_unwrap!(self, Self::Func(v), v))346 }347 pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {348 self.assert_type(context, ValType::Bool)?;349 Ok(matches_unwrap!(self, Self::Bool(v), v))350 }351 pub fn try_cast_str(self, context: &'static str) -> Result<IStr> {352 self.assert_type(context, ValType::Str)?;353 Ok(matches_unwrap!(self, Self::Str(v), v))354 }355 pub fn try_cast_num(self, context: &'static str) -> Result<f64> {356 self.assert_type(context, ValType::Num)?;357 self.unwrap_num()358 }359 pub const fn value_type(&self) -> ValType {360 match self {361 Self::Str(..) => ValType::Str,362 Self::Num(..) => ValType::Num,363 Self::Arr(..) => ValType::Arr,364 Self::Obj(..) => ValType::Obj,365 Self::Bool(_) => ValType::Bool,366 Self::Null => ValType::Null,367 Self::Func(..) => ValType::Func,368 }369 }370371 pub fn to_string(&self) -> Result<IStr> {372 Ok(match self {373 Self::Bool(true) => "true".into(),374 Self::Bool(false) => "false".into(),375 Self::Null => "null".into(),376 Self::Str(s) => s.clone(),377 v => manifest_json_ex(378 v,379 &ManifestJsonOptions {380 padding: "",381 mtype: ManifestType::ToString,382 },383 )?384 .into(),385 })386 }387388 /// Expects value to be object, outputs (key, manifested value) pairs389 pub fn manifest_multi(&self, ty: &ManifestFormat) -> Result<Vec<(IStr, IStr)>> {390 let obj = match self {391 Self::Obj(obj) => obj,392 _ => throw!(MultiManifestOutputIsNotAObject),393 };394 let keys = obj.visible_fields();395 let mut out = Vec::with_capacity(keys.len());396 for key in keys {397 let value = obj398 .get(key.clone())?399 .expect("item in object")400 .manifest(ty)?;401 out.push((key, value));402 }403 Ok(out)404 }405406 /// Expects value to be array, outputs manifested values407 pub fn manifest_stream(&self, ty: &ManifestFormat) -> Result<Vec<IStr>> {408 let arr = match self {409 Self::Arr(a) => a,410 _ => throw!(StreamManifestOutputIsNotAArray),411 };412 let mut out = Vec::with_capacity(arr.len());413 for i in arr.iter() {414 out.push(i?.manifest(ty)?);415 }416 Ok(out)417 }418419 pub fn manifest(&self, ty: &ManifestFormat) -> Result<IStr> {420 Ok(match ty {421 ManifestFormat::YamlStream(format) => {422 let arr = match self {423 Self::Arr(a) => a,424 _ => throw!(StreamManifestOutputIsNotAArray),425 };426 let mut out = String::new();427428 match format as &ManifestFormat {429 ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),430 ManifestFormat::String => throw!(StreamManifestCannotNestString),431 _ => {}432 };433434 if !arr.is_empty() {435 for v in arr.iter() {436 out.push_str("---\n");437 out.push_str(&v?.manifest(format)?);438 out.push('\n');439 }440 out.push_str("...");441 }442443 out.into()444 }445 ManifestFormat::Yaml(padding) => self.to_yaml(*padding)?,446 ManifestFormat::Json(padding) => self.to_json(*padding)?,447 ManifestFormat::ToString => self.to_string()?,448 ManifestFormat::String => match self {449 Self::Str(s) => s.clone(),450 _ => throw!(StringManifestOutputIsNotAString),451 },452 })453 }454455 /// For manifestification456 pub fn to_json(&self, padding: usize) -> Result<IStr> {457 manifest_json_ex(458 self,459 &ManifestJsonOptions {460 padding: &" ".repeat(padding),461 mtype: if padding == 0 {462 ManifestType::Minify463 } else {464 ManifestType::Manifest465 },466 },467 )468 .map(|s| s.into())469 }470471 /// Calls `std.manifestJson`472 #[cfg(feature = "faster")]473 pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {474 manifest_json_ex(475 self,476 &ManifestJsonOptions {477 padding: &" ".repeat(padding),478 mtype: ManifestType::Std,479 },480 )481 .map(|s| s.into())482 }483484 /// Calls `std.manifestJson`485 #[cfg(not(feature = "faster"))]486 pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {487 with_state(|s| {488 let ctx = s489 .create_default_context()?490 .with_var("__tmp__to_json__".into(), self.clone())?;491 Ok(evaluate(492 ctx,493 &el!(Expr::Apply(494 el!(Expr::Index(495 el!(Expr::Var("std".into())),496 el!(Expr::Str("manifestJsonEx".into()))497 )),498 ArgsDesc(vec![499 Arg(None, el!(Expr::Var("__tmp__to_json__".into()))),500 Arg(None, el!(Expr::Str(" ".repeat(padding).into())))501 ]),502 false503 )),504 )?505 .try_cast_str("to json")?)506 })507 }508 pub fn to_yaml(&self, padding: usize) -> Result<IStr> {509 with_state(|s| {510 let ctx = s511 .create_default_context()?512 .with_var("__tmp__to_json__".into(), self.clone());513 Ok(evaluate(514 ctx,515 &el!(Expr::Apply(516 el!(Expr::Index(517 el!(Expr::Var("std".into())),518 el!(Expr::Str("manifestYamlDoc".into()))519 )),520 ArgsDesc(vec![521 Arg(None, el!(Expr::Var("__tmp__to_json__".into()))),522 Arg(523 None,524 el!(Expr::Literal(if padding != 0 {525 LiteralType::True526 } else {527 LiteralType::False528 }))529 )530 ]),531 false532 )),533 )?534 .try_cast_str("to json")?)535 })536 }537}538539const fn is_function_like(val: &Val) -> bool {540 matches!(val, Val::Func(_))541}542543/// Native implementation of `std.primitiveEquals`544pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {545 Ok(match (val_a, val_b) {546 (Val::Bool(a), Val::Bool(b)) => a == b,547 (Val::Null, Val::Null) => true,548 (Val::Str(a), Val::Str(b)) => a == b,549 (Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,550 (Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(551 "primitiveEquals operates on primitive types, got array".into(),552 )),553 (Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(554 "primitiveEquals operates on primitive types, got object".into(),555 )),556 (a, b) if is_function_like(a) && is_function_like(b) => {557 throw!(RuntimeError("cannot test equality of functions".into()))558 }559 (_, _) => false,560 })561}562563/// Native implementation of `std.equals`564pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {565 if val_a.value_type() != val_b.value_type() {566 return Ok(false);567 }568 match (val_a, val_b) {569 (Val::Arr(a), Val::Arr(b)) => {570 if ArrValue::ptr_eq(a, b) {571 return Ok(true);572 }573 if a.len() != b.len() {574 return Ok(false);575 }576 for (a, b) in a.iter().zip(b.iter()) {577 if !equals(&a?, &b?)? {578 return Ok(false);579 }580 }581 Ok(true)582 }583 (Val::Obj(a), Val::Obj(b)) => {584 if ObjValue::ptr_eq(a, b) {585 return Ok(true);586 }587 let fields = a.visible_fields();588 if fields != b.visible_fields() {589 return Ok(false);590 }591 for field in fields {592 if !equals(&a.get(field.clone())?.unwrap(), &b.get(field)?.unwrap())? {593 return Ok(false);594 }595 }596 Ok(true)597 }598 (a, b) => Ok(primitive_equals(a, b)?),599 }600}