Crate somni_expr

Source
Expand description

§Somni expression evaluation Library

This library provides tools for evaluating expressions.

§Overview

The expression language includes:

  • Literals: integers, floats, booleans, strings.
  • Variables
  • A basic set of operators
  • Function calls

The expression language does not include:

  • Control flow (if, loops, etc.)
  • Complex data structures (arrays, objects, etc.)
  • Defining functions and variables (these are provided by the context)

§Operators

The following binary operators are supported, in order of precedence:

  • ||: logical OR, short-circuiting
  • &&: logical AND, short-circuiting
  • <, <=, >, >=, ==, !=: comparison operators
  • |: bitwise OR
  • ^: bitwise XOR
  • &: bitwise AND
  • <<, >>: bitwise shift
  • +, -: addition and subtraction
  • *, /: multiplication and division

Unary operators include:

  • !: logical NOT
  • -: negation

For the full specification of the grammar, see the parser module’s documentation.

§Numeric types

The Somni language supports three numeric types:

  • Integers
  • Signed integers
  • Floats

By default, the library uses the DefaultTypeSet, which uses u64, i64, and f64 for these types. You can use other type sets like TypeSet32 or TypeSet128 to use 32-bit or 128-bit integers and floats. You need to specify the type set when creating the context.

§Usage

To evaluate an expression, you need to create a Context first. You can assign variables and define functions in this context, and then you can use this context to evaluate expressions.

use somni_expr::Context;

let mut context = Context::new();

// Define a variable
context.add_variable::<u64>("x", 42);
context.add_function("add_one", |x: u64| { x + 1 });
context.add_function("floor", |x: f64| { x.floor() as u64 });

// Evaluate an expression - we expect it to evaluate
// to a number, which is u64 in the default type set.
let result = context.evaluate::<u64>("add_one(x + floor(1.2))");

assert_eq!(result, Ok(44));

Modules§

error
Errors.

Structs§

Context
The expression context, which holds variables, functions, and other state needed for evaluation.
DefaultTypeSet
Use 64-bit integers and 64-bit floats (default).
EvalError
An error that occurs during evaluation of an expression.
ExpressionError
An error that occurs during evaluation.
ExpressionVisitor
A visitor that can process an abstract syntax tree.
TypeSet32
Use 32-bit integers and floats.
TypeSet128
Use 128-bit integers and 64-bit floats.

Enums§

FunctionCallError
An error that occurs when calling a function.
OperatorError
Represents an error that can occur during operator evaluation.
Type
A type in the Somni language.
TypedValue
Represents any value in the expression language.

Traits§

ExprContext
An expression context that provides the necessary environment for evaluating expressions.
TypeSet
Defines numeric types in expressions.