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}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;