Trait ExpressionLike

Source
pub trait ExpressionLike {
    // Required methods
    fn write(&self, writer: &mut Writer);
    fn to_sanitized(&self) -> String;
    fn to_formula(&self) -> String;
    fn evaluate(&self, context: &mut dyn ContextLike) -> Result<Value>;
}
Expand description

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

This trait defines the interface that all expression types in the AIMX grammar must implement. It provides methods for evaluation within a context and for converting expressions to various string representations.

The trait is designed to be implemented by all AST node types, allowing the evaluation engine to work uniformly across different expression types without needing to know their specific implementation details.

§Implementation Guidelines

When implementing this trait:

  • Evaluation: Should handle type checking, type promotion, and error handling
  • Serialization: Should produce representations that can be parsed back
  • Context Usage: Should properly interact with the context for variable lookup

§Examples

§Basic Usage

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

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

§Custom Implementation

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

struct ConstantExpression {
    value: Value,
}

impl ExpressionLike for ConstantExpression {
    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()
    }
}

Required Methods§

Source

fn write(&self, writer: &mut Writer)

Write this expression to the provided writer.

This method serializes the expression to a text representation using the writer’s current formatting mode. The writer handles indentation, quoting, and other formatting concerns.

§Arguments
  • writer - The writer to serialize the expression to
§Examples
use aimx::{aimx_parse, ExpressionLike, Writer, PrintMode, Prefix};

let expression = aimx_parse("2 + 3");
let mut writer = Writer::new(PrintMode::None, Prefix::None);
expression.write(&mut writer);
let result = writer.finish();
assert_eq!(result, "2 + 3");
Source

fn to_sanitized(&self) -> String

Convert this expression to a sanitized string representation.

This method produces a string with special characters escaped to make it safe for various contexts like JSON output, HTML embedding, or other contexts where escaping is required.

§Returns

A sanitized string representation of this expression.

§Examples
use aimx::{aimx_parse, ExpressionLike};

let expression = aimx_parse(r#""hello" + "world""#);
let sanitized = expression.to_sanitized();
// Contains properly escaped characters
Source

fn to_formula(&self) -> String

Convert this expression to a formula string representation.

This method produces a string with proper quoting and escaping for use in formulas. The output should be round-trippable, meaning it can be parsed back into an equivalent expression.

§Returns

A formula string representation of this expression.

§Examples
use aimx::{aimx_parse, ExpressionLike};

let expression = aimx_parse("2 + 3");
let formula = expression.to_formula();
assert_eq!(formula, "2 + 3");
Source

fn evaluate(&self, context: &mut dyn ContextLike) -> Result<Value>

Evaluate the expression within the given context.

This is the core method that performs the actual evaluation of the expression. It uses the provided context to resolve variables, call functions, and perform other runtime operations.

§Arguments
  • context - A mutable reference to the evaluation context that provides variable values, function implementations, and other runtime information needed for evaluation.
§Returns

Returns a Result<Value> containing the evaluated result or an error if evaluation fails.

§Errors

This method can return various errors including:

  • Undefined variable errors when referencing undefined variables
  • Type mismatch errors when operations are performed on incompatible types
  • Function not found errors when calling undefined functions
  • Circular reference errors when detecting infinite recursion
  • Division by zero errors in arithmetic operations
  • Other evaluation errors as appropriate for the expression type
§Examples
use aimx::{aimx_parse, ExpressionLike, Context};

let expression = aimx_parse("x + 5");
let mut context = Context::new().with_value("x", aimx::Value::from_number(10.0));
let result = expression.evaluate(&mut context).unwrap();
assert_eq!(result.to_string(), "15");

Implementors§