git.delta.rocks / jrsonnet / refs/commits / 1979dbda1bc0

difftreelog

source

crates/jrsonnet-evaluator/src/function/mod.rs4.9 KiBsourcehistory
1use std::{fmt::Debug, rc::Rc};23use educe::Educe;4use jrsonnet_gcmodule::{Cc, Trace};5use jrsonnet_interner::IStr;6use jrsonnet_ir::{Destruct, Expr, ExprParams, Span};7pub use jrsonnet_macros::builtin;89use self::{10	builtin::Builtin,11	parse::parse_default_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(crate) 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	pub fn evaluate_trivial(&self) -> Option<Val> {81		evaluate_trivial(&self.body)82	}83}8485/// Represents a Jsonnet function value, including plain functions and user-provided builtins.86#[allow(clippy::module_name_repetitions)]87#[derive(Trace, Clone)]88pub enum FuncVal {89	/// Plain function implemented in jsonnet.90	Normal(Cc<FuncDesc>),91	/// User-provided function.92	Builtin(BuiltinFunc),93}9495impl Debug for FuncVal {96	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {97		match self {98			Self::Normal(arg0) => f.debug_tuple("Normal").field(arg0).finish(),99			Self::Builtin(arg0) => f.debug_tuple("Builtin").field(&arg0.name()).finish(),100		}101	}102}103104#[allow(clippy::unnecessary_wraps)]105#[builtin]106pub const fn builtin_id(x: Thunk<Val>) -> Thunk<Val> {107	x108}109110impl FuncVal {111	pub fn builtin(builtin: impl Builtin) -> Self {112		Self::Builtin(BuiltinFunc::new(builtin))113	}114115	pub fn params(&self) -> FunctionSignature {116		match self {117			Self::Builtin(i) => i.params(),118			Self::Normal(p) => p.params.signature.clone(),119		}120	}121	/// Amount of non-default required arguments122	pub fn params_len(&self) -> usize {123		self.params().iter().filter(|p| !p.has_default()).count()124	}125	/// Function name, as defined in code.126	pub fn name(&self) -> IStr {127		match self {128			Self::Normal(normal) => normal.name.clone(),129			Self::Builtin(builtin) => builtin.name().into(),130		}131	}132133	pub(crate) fn evaluate_prepared(134		&self,135		prepared: &PreparedCall,136		loc: CallLocation<'_>,137		unnamed: &[Thunk<Val>],138		named: &[Thunk<Val>],139		_tailstrict: bool,140	) -> Result<Val> {141		match self {142			FuncVal::Normal(func) => {143				let body_ctx = parse_prepared_function_call(144					func.ctx.clone(),145					prepared,146					&func.params,147					unnamed,148					named,149				)?;150				evaluate(body_ctx, &func.body)151			}152			FuncVal::Builtin(b) => {153				let args = parse_prepared_builtin_call(prepared, b.params(), unnamed, named);154				b.call(loc, &args)155			}156		}157	}158159	/// Is this function an indentity function.160	///161	/// Currently only works for builtin `std.id`, aka `Self::Id` value, and `function(x) x`.162	///163	/// This function should only be used for optimization, not for the conditional logic, i.e code should work with syntetic identity function too164	pub fn is_identity(&self) -> bool {165		match self {166			Self::Builtin(b) => b.as_any().downcast_ref::<builtin_id>().is_some(),167			Self::Normal(desc) => {168				if desc.params.len() != 1 {169					return false;170				}171				let param = &desc.params.exprs[0];172				if param.default.is_some() {173					return false;174				}175176				#[allow(clippy::infallible_destructuring_match)]177				let id = match &param.destruct {178					Destruct::Full(id) => id,179					#[cfg(feature = "exp-destruct")]180					_ => return false,181				};182				matches!(&*desc.body, Expr::Var(v) if &**v == id)183			}184		}185	}186187	pub fn evaluate_trivial(&self) -> Option<Val> {188		match self {189			Self::Normal(n) => n.evaluate_trivial(),190			Self::Builtin(_) => None,191		}192	}193}194195impl<T> From<T> for FuncVal196where197	T: Builtin,198{199	fn from(value: T) -> Self {200		Self::builtin(value)201	}202}