difftreelog
refactor drop FuncVal::Thunk
in: master
3 files changed
crates/jrsonnet-evaluator/src/function/mod.rsdiffbeforeafterboth1use std::{fmt::Debug, rc::Rc};23use educe::Educe;4use jrsonnet_gcmodule::{Cc, Trace};5use jrsonnet_interner::IStr;6use jrsonnet_ir::{ArgsDesc, Destruct, Expr, ExprParams, Span};7pub use jrsonnet_macros::builtin;89use self::{10 builtin::Builtin,11 parse::{parse_builtin_call, parse_default_function_call, parse_function_call},12 prepared::{parse_prepared_builtin_call, parse_prepared_function_call, PreparedCall},13};14use crate::{15 bail, error::ErrorKind::*, evaluate, evaluate_trivial, function::builtin::BuiltinFunc, Context,16 Result, Thunk, Val,17};1819pub mod builtin;20mod native;21mod parse;22mod prepared;2324pub use jrsonnet_ir::function::*;25pub use native::NativeFn;26pub use prepared::PreparedFuncVal;2728/// Function callsite location.29/// Either from other jsonnet code, specified by expression location, or from native (without location).30#[derive(Clone, Copy)]31pub struct CallLocation<'l>(pub Option<&'l Span>);32impl<'l> CallLocation<'l> {33 /// Construct new location for calls coming from specified jsonnet expression location.34 pub const fn new(loc: &'l Span) -> Self {35 Self(Some(loc))36 }37}38impl CallLocation<'static> {39 /// Construct new location for calls coming from native code.40 pub const fn native() -> Self {41 Self(None)42 }43}4445/// Represents Jsonnet function defined in code.46#[derive(Trace, Educe)]47#[educe(Debug, PartialEq)]48pub struct FuncDesc {49 /// # Example50 ///51 /// In expressions like this, deducted to `a`, unspecified otherwise.52 /// ```jsonnet53 /// local a = function() ...54 /// local a() ...55 /// { a: function() ... }56 /// { a() = ... }57 /// ```58 pub name: IStr,59 /// Context, in which this function was evaluated.60 ///61 /// # Example62 /// In63 /// ```jsonnet64 /// local a = 2;65 /// function() ...66 /// ```67 /// context will contain `a`.68 pub ctx: Context,6970 /// Function parameter definition71 pub params: ExprParams,72 /// Function body73 pub body: Rc<Expr>,74}75impl FuncDesc {76 /// Create body context, but fill arguments without defaults with lazy error77 pub fn default_body_context(&self) -> Result<Context> {78 parse_default_function_call(self.ctx.clone(), &self.params)79 }8081 /// Create context, with which body code will run82 pub(crate) fn call_body_context(83 &self,84 call_ctx: Context,85 args: &ArgsDesc,86 tailstrict: bool,87 ) -> Result<Context> {88 parse_function_call(call_ctx, self.ctx.clone(), &self.params, args, tailstrict)89 }9091 pub fn evaluate_trivial(&self) -> Option<Val> {92 evaluate_trivial(&self.body)93 }94}9596/// Represents a Jsonnet function value, including plain functions and user-provided builtins.97#[allow(clippy::module_name_repetitions)]98#[derive(Trace, Clone)]99pub enum FuncVal {100 /// Plain function implemented in jsonnet.101 Normal(Cc<FuncDesc>),102 /// Function without arguments works just as a fancy thunk value.103 Thunk(Thunk<Val>),104 /// User-provided function.105 Builtin(BuiltinFunc),106}107108impl Debug for FuncVal {109 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {110 match self {111 Self::Thunk(arg0) => f.debug_tuple("Thunk").field(arg0).finish(),112 Self::Normal(arg0) => f.debug_tuple("Normal").field(arg0).finish(),113 Self::Builtin(arg0) => f.debug_tuple("Builtin").field(&arg0.name()).finish(),114 }115 }116}117118#[allow(clippy::unnecessary_wraps)]119#[builtin]120pub const fn builtin_id(x: Thunk<Val>) -> Thunk<Val> {121 x122}123124impl FuncVal {125 pub fn builtin(builtin: impl Builtin) -> Self {126 Self::Builtin(BuiltinFunc::new(builtin))127 }128129 pub fn params(&self) -> FunctionSignature {130 match self {131 Self::Builtin(i) => i.params(),132 Self::Normal(p) => p.params.signature.clone(),133 Self::Thunk(_) => FunctionSignature::empty(),134 }135 }136 /// Amount of non-default required arguments137 pub fn params_len(&self) -> usize {138 self.params().iter().filter(|p| !p.has_default()).count()139 }140 /// Function name, as defined in code.141 pub fn name(&self) -> IStr {142 match self {143 Self::Normal(normal) => normal.name.clone(),144 Self::Builtin(builtin) => builtin.name().into(),145 Self::Thunk(_) => "thunk".into(),146 }147 }148 /// Call function using arguments evaluated in specified `call_ctx` [`Context`].149 ///150 /// If `tailstrict` is specified - then arguments will be evaluated before being passed to function body.151 pub fn evaluate(152 &self,153 call_ctx: Context,154 loc: CallLocation<'_>,155 args: &ArgsDesc,156 tailstrict: bool,157 ) -> Result<Val> {158 match self {159 Self::Normal(func) => {160 let body_ctx = func.call_body_context(call_ctx, args, tailstrict)?;161 evaluate(body_ctx, &func.body)162 }163 Self::Thunk(thunk) => {164 if !args.named.is_empty() || !args.unnamed.is_empty() {165 bail!(TooManyArgsFunctionHas(0, FunctionSignature::empty()))166 }167 thunk.evaluate()168 }169 Self::Builtin(b) => {170 let args = parse_builtin_call(call_ctx, b.params(), args, tailstrict)?;171 b.call(loc, &args)172 }173 }174 }175176 pub(crate) fn evaluate_prepared(177 &self,178 prepared: &PreparedCall,179 loc: CallLocation<'_>,180 unnamed: &[Thunk<Val>],181 named: &[Thunk<Val>],182 _tailstrict: bool,183 ) -> Result<Val> {184 match self {185 FuncVal::Normal(func) => {186 let body_ctx = parse_prepared_function_call(187 func.ctx.clone(),188 prepared,189 &func.params,190 unnamed,191 named,192 )?;193 evaluate(body_ctx, &func.body)194 }195 FuncVal::Thunk(t) => t.evaluate(),196 FuncVal::Builtin(b) => {197 let args = parse_prepared_builtin_call(prepared, b.params(), unnamed, named);198 b.call(loc, &args)199 }200 }201 }202203 /// Is this function an indentity function.204 ///205 /// Currently only works for builtin `std.id`, aka `Self::Id` value, and `function(x) x`.206 ///207 /// This function should only be used for optimization, not for the conditional logic, i.e code should work with syntetic identity function too208 pub fn is_identity(&self) -> bool {209 match self {210 Self::Builtin(b) => b.as_any().downcast_ref::<builtin_id>().is_some(),211 Self::Normal(desc) => {212 if desc.params.len() != 1 {213 return false;214 }215 let param = &desc.params.exprs[0];216 if param.default.is_some() {217 return false;218 }219220 #[allow(clippy::infallible_destructuring_match)]221 let id = match ¶m.destruct {222 Destruct::Full(id) => id,223 #[cfg(feature = "exp-destruct")]224 _ => return false,225 };226 matches!(&*desc.body, Expr::Var(v) if &**v == id)227 }228 Self::Thunk(_) => false,229 }230 }231232 pub fn evaluate_trivial(&self) -> Option<Val> {233 match self {234 Self::Normal(n) => n.evaluate_trivial(),235 _ => None,236 }237 }238}239240impl<T> From<T> for FuncVal241where242 T: Builtin,243{244 fn from(value: T) -> Self {245 Self::builtin(value)246 }247}1use std::{fmt::Debug, rc::Rc};23use educe::Educe;4use jrsonnet_gcmodule::{Cc, Trace};5use jrsonnet_interner::IStr;6use jrsonnet_ir::{ArgsDesc, Destruct, Expr, ExprParams, Span};7pub use jrsonnet_macros::builtin;89use self::{10 builtin::Builtin,11 parse::{parse_builtin_call, parse_default_function_call, parse_function_call},12 prepared::{PreparedCall, parse_prepared_builtin_call, parse_prepared_function_call},13};14use crate::{15 Context, Result, Thunk, Val, evaluate, evaluate_trivial, function::builtin::BuiltinFunc,16};1718pub mod builtin;19mod native;20mod parse;21mod prepared;2223pub use jrsonnet_ir::function::*;24pub use native::NativeFn;25pub use prepared::PreparedFuncVal;2627/// Function callsite location.28/// Either from other jsonnet code, specified by expression location, or from native (without location).29#[derive(Clone, Copy)]30pub struct CallLocation<'l>(pub Option<&'l Span>);31impl<'l> CallLocation<'l> {32 /// Construct new location for calls coming from specified jsonnet expression location.33 pub const fn new(loc: &'l Span) -> Self {34 Self(Some(loc))35 }36}37impl CallLocation<'static> {38 /// Construct new location for calls coming from native code.39 pub const fn native() -> Self {40 Self(None)41 }42}4344/// Represents Jsonnet function defined in code.45#[derive(Trace, Educe)]46#[educe(Debug, PartialEq)]47pub struct FuncDesc {48 /// # Example49 ///50 /// In expressions like this, deducted to `a`, unspecified otherwise.51 /// ```jsonnet52 /// local a = function() ...53 /// local a() ...54 /// { a: function() ... }55 /// { a() = ... }56 /// ```57 pub name: IStr,58 /// Context, in which this function was evaluated.59 ///60 /// # Example61 /// In62 /// ```jsonnet63 /// local a = 2;64 /// function() ...65 /// ```66 /// context will contain `a`.67 pub ctx: Context,6869 /// Function parameter definition70 pub params: ExprParams,71 /// Function body72 pub body: Rc<Expr>,73}74impl FuncDesc {75 /// Create body context, but fill arguments without defaults with lazy error76 pub fn default_body_context(&self) -> Result<Context> {77 parse_default_function_call(self.ctx.clone(), &self.params)78 }7980 /// Create context, with which body code will run81 pub(crate) fn call_body_context(82 &self,83 call_ctx: Context,84 args: &ArgsDesc,85 tailstrict: bool,86 ) -> Result<Context> {87 parse_function_call(call_ctx, self.ctx.clone(), &self.params, args, tailstrict)88 }8990 pub fn evaluate_trivial(&self) -> Option<Val> {91 evaluate_trivial(&self.body)92 }93}9495/// Represents a Jsonnet function value, including plain functions and user-provided builtins.96#[allow(clippy::module_name_repetitions)]97#[derive(Trace, Clone)]98pub enum FuncVal {99 /// Plain function implemented in jsonnet.100 Normal(Cc<FuncDesc>),101 /// User-provided function.102 Builtin(BuiltinFunc),103}104105impl Debug for FuncVal {106 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {107 match self {108 Self::Normal(arg0) => f.debug_tuple("Normal").field(arg0).finish(),109 Self::Builtin(arg0) => f.debug_tuple("Builtin").field(&arg0.name()).finish(),110 }111 }112}113114#[allow(clippy::unnecessary_wraps)]115#[builtin]116pub const fn builtin_id(x: Thunk<Val>) -> Thunk<Val> {117 x118}119120impl FuncVal {121 pub fn builtin(builtin: impl Builtin) -> Self {122 Self::Builtin(BuiltinFunc::new(builtin))123 }124125 pub fn params(&self) -> FunctionSignature {126 match self {127 Self::Builtin(i) => i.params(),128 Self::Normal(p) => p.params.signature.clone(),129 }130 }131 /// Amount of non-default required arguments132 pub fn params_len(&self) -> usize {133 self.params().iter().filter(|p| !p.has_default()).count()134 }135 /// Function name, as defined in code.136 pub fn name(&self) -> IStr {137 match self {138 Self::Normal(normal) => normal.name.clone(),139 Self::Builtin(builtin) => builtin.name().into(),140 }141 }142 /// Call function using arguments evaluated in specified `call_ctx` [`Context`].143 ///144 /// If `tailstrict` is specified - then arguments will be evaluated before being passed to function body.145 pub fn evaluate(146 &self,147 call_ctx: Context,148 loc: CallLocation<'_>,149 args: &ArgsDesc,150 tailstrict: bool,151 ) -> Result<Val> {152 match self {153 Self::Normal(func) => {154 let body_ctx = func.call_body_context(call_ctx, args, tailstrict)?;155 evaluate(body_ctx, &func.body)156 }157 Self::Builtin(b) => {158 let args = parse_builtin_call(call_ctx, b.params(), args, tailstrict)?;159 b.call(loc, &args)160 }161 }162 }163164 pub(crate) fn evaluate_prepared(165 &self,166 prepared: &PreparedCall,167 loc: CallLocation<'_>,168 unnamed: &[Thunk<Val>],169 named: &[Thunk<Val>],170 _tailstrict: bool,171 ) -> Result<Val> {172 match self {173 FuncVal::Normal(func) => {174 let body_ctx = parse_prepared_function_call(175 func.ctx.clone(),176 prepared,177 &func.params,178 unnamed,179 named,180 )?;181 evaluate(body_ctx, &func.body)182 }183 FuncVal::Builtin(b) => {184 let args = parse_prepared_builtin_call(prepared, b.params(), unnamed, named);185 b.call(loc, &args)186 }187 }188 }189190 /// Is this function an indentity function.191 ///192 /// Currently only works for builtin `std.id`, aka `Self::Id` value, and `function(x) x`.193 ///194 /// This function should only be used for optimization, not for the conditional logic, i.e code should work with syntetic identity function too195 pub fn is_identity(&self) -> bool {196 match self {197 Self::Builtin(b) => b.as_any().downcast_ref::<builtin_id>().is_some(),198 Self::Normal(desc) => {199 if desc.params.len() != 1 {200 return false;201 }202 let param = &desc.params.exprs[0];203 if param.default.is_some() {204 return false;205 }206207 #[allow(clippy::infallible_destructuring_match)]208 let id = match ¶m.destruct {209 Destruct::Full(id) => id,210 #[cfg(feature = "exp-destruct")]211 _ => return false,212 };213 matches!(&*desc.body, Expr::Var(v) if &**v == id)214 }215 }216 }217218 pub fn evaluate_trivial(&self) -> Option<Val> {219 match self {220 Self::Normal(n) => n.evaluate_trivial(),221 Self::Builtin(_) => None,222 }223 }224}225226impl<T> From<T> for FuncVal227where228 T: Builtin,229{230 fn from(value: T) -> Self {231 Self::builtin(value)232 }233}crates/jrsonnet-macros/src/typed.rsdiffbeforeafterboth--- a/crates/jrsonnet-macros/src/typed.rs
+++ b/crates/jrsonnet-macros/src/typed.rs
@@ -1,10 +1,10 @@
use proc_macro2::TokenStream;
use quote::quote;
use syn::{
- parenthesized,
+ DeriveInput, Error, Ident, LitStr, Result, Token, Type, parenthesized,
parse::{Parse, ParseStream},
spanned::Spanned as _,
- token, DeriveInput, Error, Ident, LitStr, Result, Token, Type,
+ token,
};
use crate::{extract_type_from_option, kw, names::Names, parse_attr, type_is_path};
crates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -12,13 +12,13 @@
pub use encoding::*;
pub use hash::*;
use jrsonnet_evaluator::{
+ ContextBuilder, IStr, ObjValue, ObjValueBuilder, Thunk, Val,
error::Result,
- function::{builtin_id, CallLocation, FuncVal},
+ function::{CallLocation, FuncVal, builtin_id},
tla::TlaArg,
trace::PathResolver,
typed::SerializeTypedObj as _,
val::NumValue,
- ContextBuilder, IStr, ObjValue, ObjValueBuilder, Thunk, Val,
};
use jrsonnet_gcmodule::{Acyclic, Cc, Trace};
use jrsonnet_ir::Source;