difftreelog
feat(evaluator) add ability to call functions with values
in: master
2 files changed
crates/jsonnet-evaluator/src/function.rsdiffbeforeafterboth--- a/crates/jsonnet-evaluator/src/function.rs
+++ b/crates/jsonnet-evaluator/src/function.rs
@@ -1,4 +1,4 @@
-use crate::{create_error, evaluate, lazy_val, resolved_lazy_val, Context, Error, Result};
+use crate::{create_error, evaluate, lazy_val, resolved_lazy_val, Context, Error, Result, Val};
use closure::closure;
use jsonnet_parser::{ArgsDesc, ParamsDesc};
use std::collections::HashMap;
@@ -78,3 +78,34 @@
Ok(body_ctx.unwrap_or(ctx).extend(out, None, None, None)?)
}
+
+#[inline(always)]
+pub(crate) fn place_args(
+ ctx: Context,
+ body_ctx: Option<Context>,
+ params: &ParamsDesc,
+ args: &[Val],
+) -> Result<Context> {
+ let mut out = HashMap::new();
+ let mut positioned_args = vec![None; params.0.len()];
+ for (id, arg) in args.iter().enumerate() {
+ if id >= params.len() {
+ create_error(Error::TooManyArgsFunctionHas(params.len()))?;
+ }
+ positioned_args[id] = Some(arg);
+ }
+ // Fill defaults
+ for (id, p) in params.iter().enumerate() {
+ let val = if let Some(arg) = &positioned_args[id] {
+ (*arg).clone()
+ } else if let Some(default) = &p.1 {
+ evaluate(ctx.clone(), default)?
+ } else {
+ create_error(Error::FunctionParameterNotBoundInCall(p.0.clone()))?;
+ unreachable!()
+ };
+ out.insert(p.0.clone(), resolved_lazy_val!(val));
+ }
+
+ Ok(body_ctx.unwrap_or(ctx).extend(out, None, None, None)?)
+}
crates/jsonnet-evaluator/src/val.rsdiffbeforeafterboth1use crate::{2 create_error, evaluate, function::inline_parse_function_call, Context, Error, ObjValue, Result,3};4use jsonnet_parser::{el, Arg, ArgsDesc, Expr, LocExpr, ParamsDesc};5use std::{6 cell::RefCell,7 fmt::{Debug, Display},8 rc::Rc,9};1011struct LazyValInternals {12 pub f: Option<Box<dyn Fn() -> Result<Val>>>,13 pub cached: RefCell<Option<Val>>,14}15#[derive(Clone)]16pub struct LazyVal(Rc<LazyValInternals>);17impl LazyVal {18 pub fn new(f: Box<dyn Fn() -> Result<Val>>) -> Self {19 LazyVal(Rc::new(LazyValInternals {20 f: Some(f),21 cached: RefCell::new(None),22 }))23 }24 pub fn new_resolved(val: Val) -> Self {25 LazyVal(Rc::new(LazyValInternals {26 f: None,27 cached: RefCell::new(Some(val)),28 }))29 }30 pub fn evaluate(&self) -> Result<Val> {31 {32 let cached = self.0.cached.borrow();33 if cached.is_some() {34 return Ok(cached.clone().unwrap());35 }36 }37 let result = (self.0.f.as_ref().unwrap())()?;38 self.0.cached.borrow_mut().replace(result.clone());39 Ok(result)40 }41}4243#[macro_export]44macro_rules! lazy_val {45 ($f: expr) => {46 $crate::LazyVal::new(Box::new($f))47 };48}49#[macro_export]50macro_rules! resolved_lazy_val {51 ($f: expr) => {52 $crate::LazyVal::new_resolved($f)53 };54}55impl Debug for LazyVal {56 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {57 if self.0.cached.borrow().is_some() {58 write!(f, "{:?}", self.0.cached.borrow().clone().unwrap())59 } else {60 write!(f, "Lazy")61 }62 }63}64impl PartialEq for LazyVal {65 fn eq(&self, other: &Self) -> bool {66 Rc::ptr_eq(&self.0, &other.0)67 }68}6970#[derive(Debug, PartialEq, Clone)]71pub struct FuncDesc {72 pub ctx: Context,73 pub params: ParamsDesc,74 pub body: LocExpr,75}76impl FuncDesc {77 /// This function is always inlined to make tailstrict work78 #[inline(always)]79 pub fn evaluate(&self, call_ctx: Context, args: &ArgsDesc, tailstrict: bool) -> Result<Val> {80 let ctx = inline_parse_function_call(81 call_ctx,82 Some(self.ctx.clone()),83 &self.params,84 args,85 tailstrict,86 )?;87 evaluate(ctx, &self.body)88 }89}9091#[derive(Debug)]92pub enum ValType {93 Bool,94 Null,95 Str,96 Num,97 Arr,98 Obj,99 Func,100}101impl ValType {102 pub fn name(&self) -> &'static str {103 use ValType::*;104 match self {105 Bool => "boolean",106 Null => "null",107 Str => "string",108 Num => "number",109 Arr => "array",110 Obj => "object",111 Func => "function",112 }113 }114}115impl Display for ValType {116 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {117 write!(f, "{}", self.name())118 }119}120121#[derive(Debug, PartialEq, Clone)]122pub enum Val {123 Bool(bool),124 Null,125 Str(String),126 Num(f64),127 Lazy(LazyVal),128 Arr(Vec<Val>),129 Obj(ObjValue),130 Func(FuncDesc),131132 // Library functions implemented in native133 Intristic(String, String),134}135impl Val {136 pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {137 match self.unwrap_if_lazy()? {138 Val::Bool(v) => Ok(v),139 v => create_error(Error::TypeMismatch(140 context,141 vec![ValType::Bool],142 v.value_type()?,143 )),144 }145 }146 pub fn try_cast_str(self, context: &'static str) -> Result<String> {147 match self.unwrap_if_lazy()? {148 Val::Str(v) => Ok(v),149 v => create_error(Error::TypeMismatch(150 context,151 vec![ValType::Str],152 v.value_type()?,153 )),154 }155 }156 pub fn unwrap_if_lazy(self) -> Result<Self> {157 Ok(if let Val::Lazy(v) = self {158 v.evaluate()?.unwrap_if_lazy()?159 } else {160 self161 })162 }163 pub fn value_type(&self) -> Result<ValType> {164 Ok(match self {165 Val::Str(..) => ValType::Str,166 Val::Num(..) => ValType::Num,167 Val::Arr(..) => ValType::Arr,168 Val::Obj(..) => ValType::Obj,169 Val::Func(..) => ValType::Func,170 Val::Bool(_) => ValType::Bool,171 Val::Null => ValType::Null,172 Val::Intristic(_, _) => ValType::Func,173 Val::Lazy(_) => self.clone().unwrap_if_lazy()?.value_type()?,174 })175 }176 pub fn into_json(self, padding: usize) -> Result<String> {177 with_state(|s| {178 let ctx = s179 .create_default_context()?180 .with_var("__tmp__to_json__".to_owned(), self)?;181 if let Val::Str(result) = evaluate(182 ctx,183 &el!(Expr::Apply(184 el!(Expr::Index(185 el!(Expr::Var("std".to_owned())),186 el!(Expr::Str("manifestJsonEx".to_owned()))187 )),188 ArgsDesc(vec![189 Arg(None, el!(Expr::Var("__tmp__to_json__".to_owned()))),190 Arg(None, el!(Expr::Str(" ".repeat(padding))))191 ]),192 false193 )),194 )? {195 Ok(result)196 } else {197 unreachable!()198 }199 })200 }201}1use crate::{2 create_error, evaluate,3 function::{inline_parse_function_call, place_args},4 with_state, Context, Error, ObjValue, Result,5};6use jsonnet_parser::{el, Arg, ArgsDesc, Expr, LocExpr, ParamsDesc};7use std::{8 cell::RefCell,9 fmt::{Debug, Display},10 rc::Rc,11};1213struct LazyValInternals {14 pub f: Option<Box<dyn Fn() -> Result<Val>>>,15 pub cached: RefCell<Option<Val>>,16}17#[derive(Clone)]18pub struct LazyVal(Rc<LazyValInternals>);19impl LazyVal {20 pub fn new(f: Box<dyn Fn() -> Result<Val>>) -> Self {21 LazyVal(Rc::new(LazyValInternals {22 f: Some(f),23 cached: RefCell::new(None),24 }))25 }26 pub fn new_resolved(val: Val) -> Self {27 LazyVal(Rc::new(LazyValInternals {28 f: None,29 cached: RefCell::new(Some(val)),30 }))31 }32 pub fn evaluate(&self) -> Result<Val> {33 {34 let cached = self.0.cached.borrow();35 if cached.is_some() {36 return Ok(cached.clone().unwrap());37 }38 }39 let result = (self.0.f.as_ref().unwrap())()?;40 self.0.cached.borrow_mut().replace(result.clone());41 Ok(result)42 }43}4445#[macro_export]46macro_rules! lazy_val {47 ($f: expr) => {48 $crate::LazyVal::new(Box::new($f))49 };50}51#[macro_export]52macro_rules! resolved_lazy_val {53 ($f: expr) => {54 $crate::LazyVal::new_resolved($f)55 };56}57impl Debug for LazyVal {58 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {59 if self.0.cached.borrow().is_some() {60 write!(f, "{:?}", self.0.cached.borrow().clone().unwrap())61 } else {62 write!(f, "Lazy")63 }64 }65}66impl PartialEq for LazyVal {67 fn eq(&self, other: &Self) -> bool {68 Rc::ptr_eq(&self.0, &other.0)69 }70}7172#[derive(Debug, PartialEq, Clone)]73pub struct FuncDesc {74 pub ctx: Context,75 pub params: ParamsDesc,76 pub body: LocExpr,77}78impl FuncDesc {79 /// This function is always inlined to make tailstrict work80 #[inline(always)]81 pub fn evaluate(&self, call_ctx: Context, args: &ArgsDesc, tailstrict: bool) -> Result<Val> {82 let ctx = inline_parse_function_call(83 call_ctx,84 Some(self.ctx.clone()),85 &self.params,86 args,87 tailstrict,88 )?;89 evaluate(ctx, &self.body)90 }9192 #[inline(always)]93 pub fn evaluate_values(&self, call_ctx: Context, args: &[Val]) -> Result<Val> {94 let ctx = place_args(call_ctx, Some(self.ctx.clone()), &self.params, args)?;95 evaluate(ctx, &self.body)96 }97}9899#[derive(Debug)]100pub enum ValType {101 Bool,102 Null,103 Str,104 Num,105 Arr,106 Obj,107 Func,108}109impl ValType {110 pub fn name(&self) -> &'static str {111 use ValType::*;112 match self {113 Bool => "boolean",114 Null => "null",115 Str => "string",116 Num => "number",117 Arr => "array",118 Obj => "object",119 Func => "function",120 }121 }122}123impl Display for ValType {124 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {125 write!(f, "{}", self.name())126 }127}128129#[derive(Debug, PartialEq, Clone)]130pub enum Val {131 Bool(bool),132 Null,133 Str(String),134 Num(f64),135 Lazy(LazyVal),136 Arr(Vec<Val>),137 Obj(ObjValue),138 Func(FuncDesc),139140 // Library functions implemented in native141 Intristic(String, String),142}143impl Val {144 pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {145 match self.unwrap_if_lazy()? {146 Val::Bool(v) => Ok(v),147 v => create_error(Error::TypeMismatch(148 context,149 vec![ValType::Bool],150 v.value_type()?,151 )),152 }153 }154 pub fn try_cast_str(self, context: &'static str) -> Result<String> {155 match self.unwrap_if_lazy()? {156 Val::Str(v) => Ok(v),157 v => create_error(Error::TypeMismatch(158 context,159 vec![ValType::Str],160 v.value_type()?,161 )),162 }163 }164 pub fn unwrap_if_lazy(self) -> Result<Self> {165 Ok(if let Val::Lazy(v) = self {166 v.evaluate()?.unwrap_if_lazy()?167 } else {168 self169 })170 }171 pub fn value_type(&self) -> Result<ValType> {172 Ok(match self {173 Val::Str(..) => ValType::Str,174 Val::Num(..) => ValType::Num,175 Val::Arr(..) => ValType::Arr,176 Val::Obj(..) => ValType::Obj,177 Val::Func(..) => ValType::Func,178 Val::Bool(_) => ValType::Bool,179 Val::Null => ValType::Null,180 Val::Intristic(_, _) => ValType::Func,181 Val::Lazy(_) => self.clone().unwrap_if_lazy()?.value_type()?,182 })183 }184 pub fn into_json(self, padding: usize) -> Result<String> {185 with_state(|s| {186 let ctx = s187 .create_default_context()?188 .with_var("__tmp__to_json__".to_owned(), self)?;189 if let Val::Str(result) = evaluate(190 ctx,191 &el!(Expr::Apply(192 el!(Expr::Index(193 el!(Expr::Var("std".to_owned())),194 el!(Expr::Str("manifestJsonEx".to_owned()))195 )),196 ArgsDesc(vec![197 Arg(None, el!(Expr::Var("__tmp__to_json__".to_owned()))),198 Arg(None, el!(Expr::Str(" ".repeat(padding))))199 ]),200 false201 )),202 )? {203 Ok(result)204 } else {205 unreachable!()206 }207 })208 }209}