vrl/compiler/
mod.rs

1#![deny(warnings, clippy::pedantic)]
2#![allow(clippy::large_enum_variant)]
3#![allow(clippy::result_large_err)]
4
5use std::fmt::Debug;
6use std::{fmt::Display, str::FromStr};
7
8use serde::{Deserialize, Serialize};
9
10use crate::compiler::unused_expression_checker::check_for_unused_results;
11#[cfg(feature = "stdlib-base")]
12pub use category::Category;
13pub use compiler::{CompilationResult, Compiler};
14pub use context::Context;
15pub use datetime::TimeZone;
16pub use expression::{Expression, ExpressionExt, FunctionExpression};
17pub use expression_error::{ExpressionError, Resolved};
18pub use function::{Function, Parameter};
19pub use program::{Program, ProgramInfo};
20pub use state::{TypeInfo, TypeState};
21pub use target::{SecretTarget, Target, TargetValue, TargetValueRef};
22pub use type_def::TypeDef;
23
24pub(crate) use crate::diagnostic::Span;
25use crate::diagnostic::{DiagnosticList, DiagnosticMessage};
26use crate::parser::parse;
27
28pub use self::compile_config::CompileConfig;
29pub use self::deprecation_warning::DeprecationWarning;
30
31#[allow(clippy::module_inception)]
32mod compiler;
33
34mod compile_config;
35mod context;
36mod datetime;
37mod deprecation_warning;
38mod expression_error;
39mod program;
40mod target;
41#[cfg(any(test, feature = "test"))]
42mod test_util;
43
44#[cfg(feature = "stdlib-base")]
45pub mod category;
46pub mod codes;
47pub mod conversion;
48pub mod expression;
49pub mod function;
50pub mod prelude;
51pub mod runtime;
52pub mod state;
53pub mod type_def;
54pub mod unused_expression_checker;
55pub mod value;
56
57pub type DiagnosticMessages = Vec<Box<dyn DiagnosticMessage>>;
58pub type Result<T = CompilationResult> = std::result::Result<T, DiagnosticList>;
59
60/// Compiles the given source code into the final [`Program`].
61///
62/// This function initializes an external environment and default compilation
63/// configuration before invoking the compilation process.
64///
65/// # Arguments
66///
67/// * `source` - The source code to be compiled.
68/// * `fns` - A list of function definitions available during compilation.
69///
70/// # Returns
71///
72/// A `Result` containing the compiled program or a diagnostic error.
73///
74/// # Errors
75///
76/// On compilation error, a list of diagnostics is returned.
77pub fn compile(source: &str, fns: &[Box<dyn Function>]) -> Result {
78    let external = state::ExternalEnv::default();
79    let config = CompileConfig::default();
80
81    compile_with_external(source, fns, &external, config)
82}
83
84/// Compiles the given source code with a specified external environment and configuration.
85///
86/// This function allows for customization of the compilation environment by providing
87/// an external state and a compilation configuration.
88///
89/// # Arguments
90///
91/// * `source` - The source code to be compiled.
92/// * `fns` - A list of function definitions available during compilation.
93/// * `external` - An external environment providing additional context for compilation.
94/// * `config` - The compilation configuration settings.
95///
96/// # Returns
97///
98/// A `Result` containing the compiled program or a diagnostic errors.
99///
100/// # Errors
101///
102/// On compilation error, a list of diagnostics is returned.
103pub fn compile_with_external(
104    source: &str,
105    fns: &[Box<dyn Function>],
106    external: &state::ExternalEnv,
107    config: CompileConfig,
108) -> Result {
109    let state = TypeState {
110        local: state::LocalEnv::default(),
111        external: external.clone(),
112    };
113
114    compile_with_state(source, fns, &state, config)
115}
116
117/// Compiles the given source code with a specified compilation state and configuration.
118///
119/// This function performs parsing, compilation, and optional unused expression
120/// checking before returning the compilation result.
121///
122/// # Arguments
123///
124/// * `source` - The source code to be compiled.
125/// * `fns` - A list of function definitions available during compilation.
126/// * `state` - The compilation state containing local and external environments.
127/// * `config` - The compilation configuration settings.
128///
129/// # Returns
130///
131/// A `Result` containing the compiled program or a diagnostic errors.
132///
133/// # Errors
134///
135/// On compilation error, a list of diagnostics is returned.
136pub fn compile_with_state(
137    source: &str,
138    fns: &[Box<dyn Function>],
139    state: &TypeState,
140    config: CompileConfig,
141) -> Result {
142    let ast = parse(source)
143        .map_err(|err| crate::diagnostic::DiagnosticList::from(vec![Box::new(err) as Box<_>]))?;
144
145    let unused_expression_check_enabled = config.unused_expression_check_enabled();
146    let result = Compiler::compile(fns, ast.clone(), state, config);
147
148    if unused_expression_check_enabled {
149        let unused_warnings = check_for_unused_results(&ast);
150        if !unused_warnings.is_empty() {
151            return result.map(|mut compilation_result| {
152                compilation_result.warnings.extend(unused_warnings);
153                compilation_result
154            });
155        }
156    }
157
158    result
159}
160
161/// Available VRL runtimes.
162#[derive(Clone, Copy, Debug, Eq, PartialEq, Default, Serialize, Deserialize)]
163#[serde(rename_all = "lowercase")]
164pub enum VrlRuntime {
165    /// Tree-walking runtime.
166    ///
167    /// This is the only, and default, runtime.
168    #[default]
169    Ast,
170}
171
172impl FromStr for VrlRuntime {
173    type Err = &'static str;
174
175    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
176        match s {
177            "ast" => Ok(Self::Ast),
178            _ => Err("runtime must be ast."),
179        }
180    }
181}
182
183impl Display for VrlRuntime {
184    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
185        write!(
186            f,
187            "{}",
188            match self {
189                VrlRuntime::Ast => "ast",
190            }
191        )
192    }
193}
194
195/// re-export of commonly used parser types.
196pub(crate) mod parser {
197    pub(crate) use crate::parser::ast::{self, Ident, Node};
198}