Interpreter

Struct Interpreter 

Source
pub struct Interpreter { /* private fields */ }
Expand description

Runtime interpreter state.

The Interpreter manages the execution environment for Ruchy programs. It maintains:

  • A value stack for computation
  • Environment stack for lexical scoping
  • Inline caches for field/method optimization
  • Type feedback for future JIT compilation
  • Conservative garbage collection

§Implementation Strategy

This follows a two-tier execution model:

  • Tier 0: AST interpretation (current)
  • Tier 1: JIT compilation (future)

Type feedback and execution counts are collected for hot code identification and optimization.

Implementations§

Source§

impl Interpreter

Source

pub fn new() -> Self

Create a new interpreter instance.

Initializes the interpreter with:

  • Pre-allocated stack for performance
  • Global environment with builtin functions (max, min, floor, ceil, etc.)
  • Type feedback collection for future JIT compilation
  • Conservative garbage collector
§Examples
use ruchy::runtime::interpreter::Interpreter;

let mut interpreter = Interpreter::new();
// Interpreter is ready to evaluate expressions
Source

pub fn eval_expr(&mut self, expr: &Expr) -> Result<Value, InterpreterError>

Evaluate an AST expression directly.

This is the main entry point for interpreting Ruchy expressions. It walks the AST recursively, evaluating expressions and returning their values.

§Examples
use ruchy::runtime::interpreter::Interpreter;
use ruchy::frontend::parser::Parser;

let mut interpreter = Interpreter::new();
let mut parser = Parser::new("42");
let expr = parser.parse().unwrap();
let result = interpreter.eval_expr(&expr).unwrap();
assert_eq!(result.to_string(), "42");
use ruchy::runtime::interpreter::Interpreter;
use ruchy::frontend::parser::Parser;

let mut interpreter = Interpreter::new();
let mut parser = Parser::new("2 + 3");
let expr = parser.parse().unwrap();
let result = interpreter.eval_expr(&expr).unwrap();
assert_eq!(result.to_string(), "5");
§Errors

Returns an error when:

  • Type error (e.g., adding string to number)
  • Runtime error (e.g., undefined variable)
  • Stack overflow/underflow
  • Division by zero
Source

pub fn current_env(&self) -> &HashMap<String, Value>

Get the current (innermost) environment

Source

pub fn push(&mut self, value: Value) -> Result<(), InterpreterError>

Push value onto stack

§Errors

Returns error if stack overflow occurs

Source

pub fn pop(&mut self) -> Result<Value, InterpreterError>

Pop value from stack

§Errors

Returns error if stack underflow occurs

Source

pub fn peek(&self, depth: usize) -> Result<Value, InterpreterError>

Peek at top of stack without popping

§Errors

Returns error if stack underflow occurs

Source

pub fn binary_op(&mut self, op: BinaryOp) -> Result<(), InterpreterError>

Binary arithmetic operation with type checking

§Errors

Returns error if stack underflow, type mismatch, or arithmetic error occurs

Source

pub fn set_variable_string(&mut self, name: String, value: Value)

Set a variable in the current scope (public for try/catch)

Source

pub fn push_scope(&mut self)

Scope management for pattern bindings

Source

pub fn pop_scope(&mut self)

Source

pub fn get_field_cached( &mut self, obj: &Value, field_name: &str, ) -> Result<Value, InterpreterError>

Access field with inline caching optimization

§Errors

Returns error if field access fails

Source

pub fn get_cache_stats(&self) -> HashMap<String, f64>

Get inline cache statistics for profiling

Source

pub fn clear_caches(&mut self)

Clear all inline caches (for testing)

Source

pub fn get_type_feedback_stats(&self) -> TypeFeedbackStats

Get type feedback statistics

Source

pub fn get_specialization_candidates(&self) -> Vec<SpecializationCandidate>

Get specialization candidates for JIT compilation

Source

pub fn clear_type_feedback(&mut self)

Clear type feedback data (for testing)

Source

pub fn gc_track(&mut self, value: Value) -> usize

Track a value in the garbage collector

Source

pub fn gc_collect(&mut self) -> GCStats

Force garbage collection

Source

pub fn gc_stats(&self) -> GCStats

Get garbage collection statistics

Source

pub fn gc_info(&self) -> GCInfo

Get detailed garbage collection information

Source

pub fn gc_set_threshold(&mut self, threshold: usize)

Set garbage collection threshold

Source

pub fn gc_set_auto_collect(&mut self, enabled: bool)

Enable or disable automatic garbage collection

Source

pub fn gc_clear(&mut self)

Clear all GC-tracked objects (for testing)

Source

pub fn gc_alloc_array(&mut self, elements: Vec<Value>) -> Value

Allocate a new array and track it in GC

Source

pub fn gc_alloc_string(&mut self, content: String) -> Value

Allocate a new string and track it in GC

Source

pub fn gc_alloc_closure( &mut self, params: Vec<String>, body: Arc<Expr>, env: Arc<HashMap<String, Value>>, ) -> Value

Allocate a new closure and track it in GC

Source

pub fn get_global_bindings(&self) -> HashMap<String, Value>

Get all bindings from the global environment (for SharedSession state persistence)

Source

pub fn set_global_binding(&mut self, name: String, value: Value)

Set a binding in the global environment (for SharedSession state restoration)

Source

pub fn clear_user_variables(&mut self)

Clear all user variables from global environment, keeping only builtins

Source

pub fn get_current_bindings(&self) -> HashMap<String, Value>

Get all bindings from the current environment (for SharedSession extraction)

Source

pub fn eval_match( &mut self, expr: &Expr, arms: &[MatchArm], ) -> Result<Value, InterpreterError>

Evaluate a match expression

Source

pub fn eval_method_call( &mut self, receiver: &Expr, method: &str, args: &[Expr], ) -> Result<Value, InterpreterError>

Evaluate a method call

Source

pub fn push_error_scope(&mut self)

Push an error handling scope for try/catch blocks

§Complexity

Cyclomatic complexity: 1

Source

pub fn pop_error_scope(&mut self)

Pop an error handling scope

§Complexity

Cyclomatic complexity: 1

Source

pub fn set_variable(&mut self, name: &str, value: Value)

Set a variable in the current scope

§Complexity

Cyclomatic complexity: 1

Source

pub fn get_variable(&self, name: &str) -> Option<Value>

Get a variable from the environment stack

Searches the environment stack from innermost to outermost scope. Returns None if the variable is not found.

Source

pub fn pattern_matches( &mut self, pattern: &Pattern, value: &Value, ) -> Result<bool, InterpreterError>

Pattern matching for try/catch

§Complexity

Cyclomatic complexity: 8 (delegates to existing pattern matcher)

Source

pub fn capture_stdout(&mut self, output: String)

Capture println output to stdout buffer Complexity: 1 (single operation)

§Examples
use ruchy::runtime::interpreter::Interpreter;

let mut interpreter = Interpreter::new();
interpreter.capture_stdout("Hello, World!".to_string());
assert_eq!(interpreter.get_stdout(), "Hello, World!");
Source

pub fn get_stdout(&self) -> String

Get captured stdout as a single string with newlines Complexity: 2 (join + conditional)

§Examples
use ruchy::runtime::interpreter::Interpreter;

let mut interpreter = Interpreter::new();
interpreter.capture_stdout("Line 1".to_string());
interpreter.capture_stdout("Line 2".to_string());
assert_eq!(interpreter.get_stdout(), "Line 1\nLine 2");
Source

pub fn clear_stdout(&mut self)

Clear stdout buffer Complexity: 1 (single operation)

§Examples
use ruchy::runtime::interpreter::Interpreter;

let mut interpreter = Interpreter::new();
interpreter.capture_stdout("test".to_string());
interpreter.clear_stdout();
assert_eq!(interpreter.get_stdout(), "");
Source

pub fn has_stdout(&self) -> bool

Check if stdout has any captured output Complexity: 1 (single check)

Trait Implementations§

Source§

impl Debug for Interpreter

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Interpreter

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,