Module evaluate

Source
Expand description

Core evaluation traits and utilities for AIMX expressions.

This module defines the core traits and utilities for evaluating expressions within a context. It provides the foundation for the AIMX evaluation system, including the main ExpressionLike trait that all expression types implement, and utility functions for type promotion and static evaluation.

The evaluation system follows a recursive descent pattern where each expression type knows how to evaluate itself within a given context. This design allows for flexible extension and maintains separation of concerns between parsing and evaluation.

§Key Components

§Architecture

The evaluation system is designed around the ExpressionLike trait, which provides a uniform interface for evaluating different types of expressions. Each expression type (arithmetic, logical, conditional, etc.) implements this trait to provide its specific evaluation logic.

§Type Promotion

AIMX uses a sophisticated type promotion system where the left operand’s type determines how the right operand is converted. The evaluate_and_promote function implements this logic for binary operators.

§Static Evaluation

The statically_evaluate function allows evaluating expressions that contain only literals and built-in functions, without requiring external context. This is useful for constant folding, optimization, and testing.

§Examples

§Basic Expression Evaluation

use aimx::{aimx_parse, ExpressionLike, Context};

let expression = aimx_parse("2 + 3");
let mut context = Context::new();
let result = expression.evaluate(&mut context).unwrap();
assert_eq!(result.to_string(), "5");

§Using Static Evaluation

use aimx::{aimx_parse, evaluate::statically_evaluate};

let expression = aimx_parse("sqrt(16) + abs(-5)");
let result = statically_evaluate(&expression).unwrap();
assert_eq!(result.to_string(), "9");

§Implementing Custom Expression Types

use aimx::{ExpressionLike, ContextLike, Value, Writer};
use anyhow::Result;

struct CustomExpression {
    value: Value,
}

impl ExpressionLike for CustomExpression {
    fn evaluate(&self, _context: &mut dyn ContextLike) -> Result<Value> {
        Ok(self.value.clone())
    }

    fn write(&self, writer: &mut Writer) {
        writer.print_value(&writer.prefix(), &self.value);
    }

    fn to_sanitized(&self) -> String {
        self.value.to_sanitized()
    }

    fn to_formula(&self) -> String {
        self.value.to_formula()
    }
}

Traits§

ExpressionLike
Core trait for evaluating expressions and serializing them to text representations.

Functions§

evaluate_and_promote
Helper function to evaluate two expressions and promote the right operand to match the type of the left operand.
statically_evaluate
Evaluate an expression statically without external context.