rib/interpreter/
eval.rs

1// Copyright 2024-2025 Golem Cloud
2//
3// Licensed under the Golem Source License v1.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://license.golem.cloud/LICENSE
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use crate::{
16    DefaultWorkerNameGenerator, Expr, GenerateWorkerName, RibCompilationError, RibCompiler,
17    RibCompilerConfig, RibComponentFunctionInvoke, RibInput, RibResult, RibRuntimeError,
18};
19use std::sync::Arc;
20
21pub struct RibEvalConfig {
22    compiler_config: RibCompilerConfig,
23    rib_input: RibInput,
24    function_invoke: Arc<dyn RibComponentFunctionInvoke + Sync + Send>,
25    generate_worker_name: Arc<dyn GenerateWorkerName + Sync + Send>,
26}
27
28impl RibEvalConfig {
29    pub fn new(
30        compiler_config: RibCompilerConfig,
31        rib_input: RibInput,
32        function_invoke: Arc<dyn RibComponentFunctionInvoke + Sync + Send>,
33        generate_worker_name: Option<Arc<dyn GenerateWorkerName + Sync + Send>>,
34    ) -> Self {
35        RibEvalConfig {
36            compiler_config,
37            rib_input,
38            function_invoke,
39            generate_worker_name: generate_worker_name
40                .unwrap_or_else(|| Arc::new(DefaultWorkerNameGenerator)),
41        }
42    }
43}
44
45pub struct RibEvaluator {
46    pub config: RibEvalConfig,
47}
48
49impl RibEvaluator {
50    pub fn new(config: RibEvalConfig) -> Self {
51        RibEvaluator { config }
52    }
53
54    pub async fn eval(self, rib: &str) -> Result<RibResult, RibEvaluationError> {
55        let expr = Expr::from_text(rib).map_err(RibEvaluationError::ParseError)?;
56        let config = self.config.compiler_config;
57        let compiler = RibCompiler::new(config);
58        let compiled = compiler.compile(expr.clone())?;
59
60        let result = crate::interpret(
61            compiled.byte_code,
62            self.config.rib_input,
63            self.config.function_invoke,
64            Some(self.config.generate_worker_name.clone()),
65        )
66        .await?;
67
68        Ok(result)
69    }
70}
71
72#[derive(Debug)]
73pub enum RibEvaluationError {
74    ParseError(String),
75    CompileError(RibCompilationError),
76    RuntimeError(RibRuntimeError),
77}
78
79impl From<RibCompilationError> for RibEvaluationError {
80    fn from(error: RibCompilationError) -> Self {
81        RibEvaluationError::CompileError(error)
82    }
83}
84
85impl From<RibRuntimeError> for RibEvaluationError {
86    fn from(error: RibRuntimeError) -> Self {
87        RibEvaluationError::RuntimeError(error)
88    }
89}