ksl 0.1.30

KSL core library and interpreter
Documentation
//! # ksl::eval
//!
//! Defines some functions related to the evaluation of KSL values.

pub mod apply;
pub(crate) mod pair;
pub(crate) mod plugin;
mod sentence;

use crate::{
    Environment,
    eval::{apply::eval_apply, sentence::eval_sentence},
    token::{TokenType, source_to_token},
    value::Value,
};

/// Evaluate the source code.
///
/// # Example
///
/// ```rust
/// let source = r#"
/// Let[f, Fun[{x}, Add[x, 1]]];
/// Let[x, 2];
/// f[x]
///     "#;
/// let env = ksl::init_environment(None);
/// match ksl::eval::eval(source, env) {
///     Ok(value) => assert_eq!(value, ksl::value::Value::Number(3.0)),
///     Err(_) => unreachable!(),
/// }
/// ```
pub fn eval(source: &str, env: Environment) -> Result<Value, std::sync::Arc<str>> {
    let mut current_val = Value::Unit;
    for sentence in source_to_token(source)?
        .split(|token| matches!(token.value, TokenType::SentenceSeperator))
        .filter(|s| !s.is_empty())
    {
        current_val = eval_sentence(sentence, env.clone()).and_then(|val| eval_apply(&val, env.clone()))?;
    }
    Ok(current_val)
}