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