Skip to main content

ksl/eval/
mod.rs

1//! # ksl::eval
2//!
3//! Defines some functions related to the evaluation of KSL values.
4
5pub mod apply;
6pub(crate) mod pair;
7pub(crate) mod plugin;
8mod sentence;
9
10use crate::{
11    Environment,
12    eval::{apply::eval_apply, sentence::eval_sentence},
13    token::{TokenType, source_to_token},
14    value::Value,
15};
16
17/// Evaluate the source code.
18///
19/// # Example
20///
21/// ```rust
22/// let source = r#"
23/// Let[f, Fun[{x}, Add[x, 1]]];
24/// Let[x, 2];
25/// f[x]
26///     "#;
27/// let env = ksl::init_environment(None);
28/// match ksl::eval::eval(source, env) {
29///     Ok(value) => assert_eq!(value, ksl::value::Value::Number(3.0)),
30///     Err(_) => unreachable!(),
31/// }
32/// ```
33pub fn eval(source: &str, env: Environment) -> Result<Value, std::sync::Arc<str>> {
34    let mut current_val = Value::Unit;
35    for sentence in source_to_token(source)?
36        .split(|token| matches!(token.value, TokenType::SentenceSeperator))
37        .filter(|s| !s.is_empty())
38    {
39        current_val = eval_sentence(sentence, env.clone()).and_then(|val| eval_apply(&val, env.clone()))?;
40    }
41    Ok(current_val)
42}