Trait Interpreter

Source
pub trait Interpreter: 'static {
    type Value: Clone;
    type Error: From<String> + From<&'static String>;
    type Env;
    type Expr;

    // Required methods
    fn parse(code: &str) -> Result<Self::Expr, Self::Error>;
    fn global_env() -> Self::Env;
    fn evaluate(
        env: &Self::Env,
        expr: &Self::Expr,
    ) -> Result<Self::Value, Self::Error>;

    // Provided method
    fn interpret(code: &str) -> Result<Self::Value, Self::Error> { ... }
}
Expand description

A lightweight interpreter interface.

Required Associated Types§

Source

type Value: Clone

The value type the interpreter uses and returns.

It is usually a trait object that allows supporting different kinds of actual values.

Refer to the value module for example implementations.

Source

type Error: From<String> + From<&'static String>

The error type that the interpreter raises.

Could be a string, or the same as the Value type, or a dedicated error type.

Source

type Env

The environment type that is used to evaluate code.

Environments are complementary (mutable) structures that helps resolving static expressions.

For example, environments might include these kinds of information:

  • The state (registers, heap and the stack). Tracking local and outer variables.
  • What to do next (the program counter). Making it possible to suspend and resume execution. This would require explicit support from the stdlib so execution can be suspended and resumed.

Refer to the env module for example implementations.

Source

type Expr

The expression type.

The type that can represent parsed code of this language. If the language wants to operate code as data, then there needs a way to convert Expr to Value. For interpreters that use bytecode, this might also include the bytecode.

Refer to the expr module for example implementations.

Required Methods§

Source

fn parse(code: &str) -> Result<Self::Expr, Self::Error>

Parse code into an Expr.

For interpreters that use bytecode, consider compiling the code into bytecode in this function.

Source

fn global_env() -> Self::Env

Define the default global environment.

Usually this defines the standard library.

Source

fn evaluate( env: &Self::Env, expr: &Self::Expr, ) -> Result<Self::Value, Self::Error>

Evaluate an expression in a given environment.

Provided Methods§

Source

fn interpret(code: &str) -> Result<Self::Value, Self::Error>

Evaluate code in string. This is a shortcut for calling parse, and evaluate with global_env().

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§