vrl/compiler/expression/function.rs
1use crate::compiler::state::{TypeInfo, TypeState};
2use crate::compiler::{Context, Expression, Resolved, TypeDef};
3use crate::value::Value;
4use dyn_clone::DynClone;
5use std::fmt;
6use std::fmt::Debug;
7
8/// A trait similar to `Expression`, but simplified specifically for functions.
9/// The main difference is this trait prevents mutation of variables both at runtime
10/// and compile time.
11#[allow(clippy::module_name_repetitions)]
12pub trait FunctionExpression: Send + Sync + fmt::Debug + DynClone + Clone + 'static {
13 /// Resolves the function expression to a concrete [`Value`].
14 /// This method is executed at runtime.
15 /// An expression is allowed to fail, which aborts the running program.
16 // This should be a read-only reference to `Context`, but function args
17 // are resolved in the function themselves, which can theoretically mutate
18 // see: https://github.com/vectordotdev/vector/issues/13752
19 ///
20 /// # Arguments
21 /// * `ctx` - The context in which to resolve the expression.
22 ///
23 /// # Returns
24 /// A `Result` containing the resolved value or an error.
25 ///
26 /// # Errors
27 /// Returns an error if the resolution fails.
28 fn resolve(&self, ctx: &mut Context) -> Resolved;
29
30 /// The resulting type that the function resolves to.
31 fn type_def(&self, state: &TypeState) -> TypeDef;
32
33 /// Resolves values at compile-time for constant functions.
34 ///
35 /// This returns `Some` for constant expressions, or `None` otherwise.
36 fn as_value(&self) -> Option<Value> {
37 None
38 }
39
40 /// Converts this function to a normal `Expression`.
41 fn as_expr(&self) -> Box<dyn Expression> {
42 Box::new(FunctionExpressionAdapter {
43 inner: self.clone(),
44 })
45 }
46}
47
48#[derive(Debug, Clone)]
49struct FunctionExpressionAdapter<T> {
50 inner: T,
51}
52
53impl<T: FunctionExpression + Debug + Clone> Expression for FunctionExpressionAdapter<T> {
54 fn resolve(&self, ctx: &mut Context) -> Resolved {
55 self.inner.resolve(ctx)
56 }
57
58 fn type_info(&self, state: &TypeState) -> TypeInfo {
59 let result = self.inner.type_def(state);
60 TypeInfo::new(state, result)
61 }
62}