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
impl Interpreter
Sourcepub fn new() -> Self
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 expressionsSourcepub fn eval_expr(&mut self, expr: &Expr) -> Result<Value, InterpreterError>
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
Sourcepub fn current_env(&self) -> &HashMap<String, Value>
pub fn current_env(&self) -> &HashMap<String, Value>
Get the current (innermost) environment
Sourcepub fn pop(&mut self) -> Result<Value, InterpreterError>
pub fn pop(&mut self) -> Result<Value, InterpreterError>
Sourcepub fn binary_op(&mut self, op: BinaryOp) -> Result<(), InterpreterError>
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
Sourcepub fn set_variable_string(&mut self, name: String, value: Value)
pub fn set_variable_string(&mut self, name: String, value: Value)
Set a variable in the current scope (public for try/catch)
Sourcepub fn push_scope(&mut self)
pub fn push_scope(&mut self)
Scope management for pattern bindings
pub fn pop_scope(&mut self)
Sourcepub fn get_field_cached(
&mut self,
obj: &Value,
field_name: &str,
) -> Result<Value, InterpreterError>
pub fn get_field_cached( &mut self, obj: &Value, field_name: &str, ) -> Result<Value, InterpreterError>
Sourcepub fn get_cache_stats(&self) -> HashMap<String, f64>
pub fn get_cache_stats(&self) -> HashMap<String, f64>
Get inline cache statistics for profiling
Sourcepub fn clear_caches(&mut self)
pub fn clear_caches(&mut self)
Clear all inline caches (for testing)
Sourcepub fn get_type_feedback_stats(&self) -> TypeFeedbackStats
pub fn get_type_feedback_stats(&self) -> TypeFeedbackStats
Get type feedback statistics
Sourcepub fn get_specialization_candidates(&self) -> Vec<SpecializationCandidate>
pub fn get_specialization_candidates(&self) -> Vec<SpecializationCandidate>
Get specialization candidates for JIT compilation
Sourcepub fn clear_type_feedback(&mut self)
pub fn clear_type_feedback(&mut self)
Clear type feedback data (for testing)
Sourcepub fn gc_collect(&mut self) -> GCStats
pub fn gc_collect(&mut self) -> GCStats
Force garbage collection
Sourcepub fn gc_set_threshold(&mut self, threshold: usize)
pub fn gc_set_threshold(&mut self, threshold: usize)
Set garbage collection threshold
Sourcepub fn gc_set_auto_collect(&mut self, enabled: bool)
pub fn gc_set_auto_collect(&mut self, enabled: bool)
Enable or disable automatic garbage collection
Sourcepub fn gc_alloc_array(&mut self, elements: Vec<Value>) -> Value
pub fn gc_alloc_array(&mut self, elements: Vec<Value>) -> Value
Allocate a new array and track it in GC
Sourcepub fn gc_alloc_string(&mut self, content: String) -> Value
pub fn gc_alloc_string(&mut self, content: String) -> Value
Allocate a new string and track it in GC
Sourcepub fn gc_alloc_closure(
&mut self,
params: Vec<String>,
body: Arc<Expr>,
env: Arc<HashMap<String, Value>>,
) -> Value
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
Sourcepub fn get_global_bindings(&self) -> HashMap<String, Value>
pub fn get_global_bindings(&self) -> HashMap<String, Value>
Get all bindings from the global environment (for SharedSession state persistence)
Sourcepub fn set_global_binding(&mut self, name: String, value: Value)
pub fn set_global_binding(&mut self, name: String, value: Value)
Set a binding in the global environment (for SharedSession state restoration)
Sourcepub fn clear_user_variables(&mut self)
pub fn clear_user_variables(&mut self)
Clear all user variables from global environment, keeping only builtins
Sourcepub fn get_current_bindings(&self) -> HashMap<String, Value>
pub fn get_current_bindings(&self) -> HashMap<String, Value>
Get all bindings from the current environment (for SharedSession extraction)
Sourcepub fn eval_match(
&mut self,
expr: &Expr,
arms: &[MatchArm],
) -> Result<Value, InterpreterError>
pub fn eval_match( &mut self, expr: &Expr, arms: &[MatchArm], ) -> Result<Value, InterpreterError>
Evaluate a match expression
Sourcepub fn eval_method_call(
&mut self,
receiver: &Expr,
method: &str,
args: &[Expr],
) -> Result<Value, InterpreterError>
pub fn eval_method_call( &mut self, receiver: &Expr, method: &str, args: &[Expr], ) -> Result<Value, InterpreterError>
Evaluate a method call
Sourcepub fn push_error_scope(&mut self)
pub fn push_error_scope(&mut self)
Sourcepub fn pop_error_scope(&mut self)
pub fn pop_error_scope(&mut self)
Sourcepub fn set_variable(&mut self, name: &str, value: Value)
pub fn set_variable(&mut self, name: &str, value: Value)
Sourcepub fn get_variable(&self, name: &str) -> Option<Value>
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.
Sourcepub fn pattern_matches(
&mut self,
pattern: &Pattern,
value: &Value,
) -> Result<bool, InterpreterError>
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)
Sourcepub fn capture_stdout(&mut self, output: String)
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!");Sourcepub fn get_stdout(&self) -> String
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");Sourcepub fn clear_stdout(&mut self)
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(), "");Sourcepub fn has_stdout(&self) -> bool
pub fn has_stdout(&self) -> bool
Check if stdout has any captured output Complexity: 1 (single check)
Trait Implementations§
Source§impl Debug for Interpreter
impl Debug for Interpreter
Auto Trait Implementations§
impl Freeze for Interpreter
impl !RefUnwindSafe for Interpreter
impl !Send for Interpreter
impl !Sync for Interpreter
impl Unpin for Interpreter
impl !UnwindSafe for Interpreter
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
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