git.delta.rocks / jrsonnet / refs/commits / 0f5b614a0779

difftreelog

source

crates/jrsonnet-evaluator/src/function/mod.rs5.8 KiBsourcehistory
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 &param.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}