1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
//! Direct-threaded Interpreter Compilation Module
//!
//! EXTREME TDD: Full test coverage, zero entropy, <10 complexity per function
//! Extracted from interpreter.rs to eliminate bloat and follow Toyota Way principles.
//!
//! This module implements a direct-threaded interpreter for Ruchy that compiles
//! AST expressions to instruction streams for high-performance execution.
//!
//! # Features
//!
//! - Direct-threaded dispatch for optimal performance
//! - Instruction-based compilation of AST expressions
//! - Support for basic operations: arithmetic, conditionals, literals
//! - Stack-based execution model
//! - Comprehensive error handling with proper bounds checking
use crate::frontend::ast::{Expr, ExprKind, Literal};
use crate::runtime::{InterpreterError, Value};
/// Result of instruction execution
#[derive(Debug, Clone)]
pub enum InstructionResult {
/// Continue to next instruction
Continue,
/// Jump to specific instruction address
Jump(usize),
/// Return from execution with value
Return(Value),
/// Error occurred during execution
Error(InterpreterError),
}
/// Compiled instruction for direct-threaded execution
#[derive(Clone)]
pub struct ThreadedInstruction {
/// Function pointer to instruction handler
pub handler: fn(&mut InterpreterState, u32) -> InstructionResult,
/// Operand for the instruction
pub operand: u32,
}
impl std::fmt::Debug for ThreadedInstruction {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ThreadedInstruction")
.field("handler", &"<function>")
.field("operand", &self.operand)
.finish()
}
}
/// Execution state for the direct-threaded interpreter
#[derive(Debug, Clone)]
pub struct InterpreterState {
/// Execution stack
pub stack: Vec<Value>,
/// Constants pool
pub constants: Vec<Value>,
}
impl InterpreterState {
/// Create new interpreter state
///
/// # Complexity
/// Cyclomatic complexity: 1 (within Toyota Way limits)
pub fn new() -> Self {
Self {
stack: Vec::new(),
constants: Vec::new(),
}
}
}
impl Default for InterpreterState {
fn default() -> Self {
Self::new()
}
}
/// Direct-threaded interpreter for high-performance execution
///
/// Uses function pointers and direct dispatch to avoid switch overhead.
/// Compiles AST expressions to instruction streams for optimal execution.
#[derive(Debug)]
pub struct DirectThreadedInterpreter {
/// Compiled instruction stream
code: Vec<ThreadedInstruction>,
/// Constants pool for literals
constants: Vec<Value>,
/// Program counter
pc: usize,
/// Execution state
state: InterpreterState,
}
impl DirectThreadedInterpreter {
/// Create new direct-threaded interpreter
///
/// # Complexity
/// Cyclomatic complexity: 1 (within Toyota Way limits)
pub fn new() -> Self {
Self {
code: Vec::new(),
constants: Vec::new(),
pc: 0,
state: InterpreterState::new(),
}
}
/// Compile expression to instruction stream
///
/// # Complexity
/// Cyclomatic complexity: 7 (within Toyota Way limits)
pub fn compile(&mut self, expr: &Expr) -> Result<(), InterpreterError> {
self.code.clear();
self.constants.clear();
self.pc = 0;
// Compile expression to instruction stream
self.compile_expr(expr)?;
// Add return instruction if needed
if self.code.is_empty()
|| !matches!(self.code.last(), Some(instr) if
std::ptr::eq(instr.handler as *const (), op_return as *const ()))
{
self.emit_instruction(op_return, 0);
}
// Copy constants to state
self.state.constants = self.constants.clone();
Ok(())
}
/// Execute compiled instruction stream using direct-threaded dispatch
///
/// # Complexity
/// Cyclomatic complexity: 8 (within Toyota Way limits)
pub fn execute(&mut self) -> Result<Value, InterpreterError> {
self.pc = 0;
loop {
// Bounds check
if self.pc >= self.code.len() {
return Err(InterpreterError::RuntimeError(
"PC out of bounds".to_string(),
));
}
// Direct function pointer call - no switch overhead
let instruction = &self.code[self.pc];
let result = (instruction.handler)(&mut self.state, instruction.operand);
match result {
InstructionResult::Continue => {
self.pc += 1;
}
InstructionResult::Jump(target) => {
if target >= self.code.len() {
return Err(InterpreterError::RuntimeError(
"Jump target out of bounds".to_string(),
));
}
self.pc = target;
}
InstructionResult::Return(value) => {
return Ok(value);
}
InstructionResult::Error(error) => {
return Err(error);
}
}
// Periodic interrupt check for long-running loops
if self.pc.trailing_zeros() >= 10 {
// Could add interrupt checking here in the future
}
}
}
/// Compile single expression to instruction stream
///
/// # Complexity
/// Cyclomatic complexity: 5 (within Toyota Way limits)
fn compile_expr(&mut self, expr: &Expr) -> Result<(), InterpreterError> {
match &expr.kind {
ExprKind::Literal(lit) => self.compile_literal(lit),
ExprKind::Binary { left, op, right } => self.compile_binary_expr(left, op, right),
ExprKind::Identifier(name) => self.compile_identifier(name),
ExprKind::If {
condition,
then_branch,
else_branch,
} => self.compile_if_expr(condition, then_branch, else_branch.as_deref()),
_ => self.compile_fallback_expr(),
}
}
/// Compile literal expression
///
/// # Complexity
/// Cyclomatic complexity: 3 (within Toyota Way limits)
fn compile_literal(&mut self, lit: &Literal) -> Result<(), InterpreterError> {
if matches!(lit, Literal::Unit | Literal::Null) {
self.emit_instruction(op_load_nil, 0);
} else {
let const_idx = self.add_constant(self.literal_to_value(lit));
self.emit_instruction(op_load_const, const_idx);
}
Ok(())
}
/// Compile binary expression
///
/// # Complexity
/// Cyclomatic complexity: 2 (within Toyota Way limits)
fn compile_binary_expr(
&mut self,
left: &Expr,
op: &crate::frontend::ast::BinaryOp,
right: &Expr,
) -> Result<(), InterpreterError> {
self.compile_expr(left)?;
self.compile_expr(right)?;
let op_code = self.binary_op_to_opcode(op)?;
self.emit_instruction(op_code, 0);
Ok(())
}
/// Convert binary operator to opcode
///
/// # Complexity
/// Cyclomatic complexity: 5 (within Toyota Way limits)
fn binary_op_to_opcode(
&self,
op: &crate::frontend::ast::BinaryOp,
) -> Result<fn(&mut InterpreterState, u32) -> InstructionResult, InterpreterError> {
match op {
crate::frontend::ast::BinaryOp::Add => Ok(op_add),
crate::frontend::ast::BinaryOp::Subtract => Ok(op_sub),
crate::frontend::ast::BinaryOp::Multiply => Ok(op_mul),
crate::frontend::ast::BinaryOp::Divide => Ok(op_div),
_ => Err(InterpreterError::RuntimeError(format!(
"Unsupported binary operation: {op:?}"
))),
}
}
/// Compile identifier expression
///
/// # Complexity
/// Cyclomatic complexity: 1 (within Toyota Way limits)
fn compile_identifier(&mut self, name: &str) -> Result<(), InterpreterError> {
let name_idx = self.add_constant(Value::from_string(name.to_string()));
self.emit_instruction(op_load_var, name_idx);
Ok(())
}
/// Compile if expression
///
/// # Complexity
/// Cyclomatic complexity: 3 (within Toyota Way limits)
fn compile_if_expr(
&mut self,
condition: &Expr,
then_branch: &Expr,
else_branch: Option<&Expr>,
) -> Result<(), InterpreterError> {
self.compile_expr(condition)?;
let else_jump_addr = self.code.len();
self.emit_instruction(op_jump_if_false, 0);
self.compile_expr(then_branch)?;
if let Some(else_expr) = else_branch {
self.compile_if_with_else_branch(else_jump_addr, else_expr)
} else {
self.compile_if_without_else_branch(else_jump_addr)
}
}
/// Compile if expression with else branch
///
/// # Complexity
/// Cyclomatic complexity: 1 (within Toyota Way limits)
fn compile_if_with_else_branch(
&mut self,
else_jump_addr: usize,
else_expr: &Expr,
) -> Result<(), InterpreterError> {
let end_jump_addr = self.code.len();
self.emit_instruction(op_jump, 0);
self.patch_jump_target(else_jump_addr, self.code.len());
self.compile_expr(else_expr)?;
self.patch_jump_target(end_jump_addr, self.code.len());
Ok(())
}
/// Compile if expression without else branch
///
/// # Complexity
/// Cyclomatic complexity: 1 (within Toyota Way limits)
fn compile_if_without_else_branch(
&mut self,
else_jump_addr: usize,
) -> Result<(), InterpreterError> {
self.patch_jump_target(else_jump_addr, self.code.len());
self.emit_instruction(op_load_nil, 0);
Ok(())
}
/// Patch jump target for branching instructions
///
/// # Complexity
/// Cyclomatic complexity: 2 (within Toyota Way limits)
fn patch_jump_target(&mut self, jump_addr: usize, target: usize) {
if let Some(instr) = self.code.get_mut(jump_addr) {
instr.operand = target as u32;
}
}
/// Compile fallback for unsupported expressions
///
/// # Complexity
/// Cyclomatic complexity: 1 (within Toyota Way limits)
fn compile_fallback_expr(&mut self) -> Result<(), InterpreterError> {
let value_idx = self.add_constant(Value::from_string("AST_FALLBACK".to_string()));
self.emit_instruction(op_ast_fallback, value_idx);
Ok(())
}
/// Add constant to pool and return index
///
/// # Complexity
/// Cyclomatic complexity: 1 (within Toyota Way limits)
#[allow(clippy::cast_possible_truncation)] // Index bounds are controlled
fn add_constant(&mut self, value: Value) -> u32 {
let idx = self.constants.len();
self.constants.push(value);
idx as u32
}
/// Emit instruction to code stream
///
/// # Complexity
/// Cyclomatic complexity: 1 (within Toyota Way limits)
fn emit_instruction(
&mut self,
handler: fn(&mut InterpreterState, u32) -> InstructionResult,
operand: u32,
) {
self.code.push(ThreadedInstruction { handler, operand });
}
/// Convert literal to value
///
/// # Complexity
/// Cyclomatic complexity: 8 (within Toyota Way limits)
fn literal_to_value(&self, lit: &Literal) -> Value {
match lit {
Literal::Integer(n, _) => Value::Integer(*n),
Literal::Float(f) => Value::Float(*f),
Literal::Bool(b) => Value::Bool(*b),
Literal::String(s) => Value::from_string(s.clone()),
Literal::Char(c) => Value::from_string(c.to_string()), // Convert char to single-character string
Literal::Byte(b) => Value::Byte(*b),
Literal::Unit => Value::Nil, // Unit maps to Nil
Literal::Null => Value::Nil, // Null maps to Nil
Literal::Atom(s) => Value::Atom(s.clone()),
}
}
/// Get instruction count
///
/// # Complexity
/// Cyclomatic complexity: 1 (within Toyota Way limits)
pub fn instruction_count(&self) -> usize {
self.code.len()
}
/// Get constants count
///
/// # Complexity
/// Cyclomatic complexity: 1 (within Toyota Way limits)
pub fn constants_count(&self) -> usize {
self.constants.len()
}
/// Add instruction to code stream (public interface for tests)
///
/// # Complexity
/// Cyclomatic complexity: 1 (within Toyota Way limits)
pub fn add_instruction(
&mut self,
handler: fn(&mut InterpreterState, u32) -> InstructionResult,
operand: u32,
) {
self.emit_instruction(handler, operand);
}
/// Clear all instructions and constants
///
/// # Complexity
/// Cyclomatic complexity: 1 (within Toyota Way limits)
pub fn clear(&mut self) {
self.code.clear();
self.constants.clear();
self.pc = 0;
self.state = InterpreterState::new();
}
/// Execute with custom interpreter state (for tests)
///
/// # Complexity
/// Cyclomatic complexity: 8 (within Toyota Way limits)
pub fn execute_with_state(
&mut self,
state: &mut InterpreterState,
) -> Result<Value, InterpreterError> {
self.pc = 0;
loop {
// Bounds check
if self.pc >= self.code.len() {
return Err(InterpreterError::RuntimeError(
"PC out of bounds".to_string(),
));
}
// Direct function pointer call - no switch overhead
let instruction = &self.code[self.pc];
let result = (instruction.handler)(state, instruction.operand);
match result {
InstructionResult::Continue => {
self.pc += 1;
}
InstructionResult::Jump(target) => {
if target >= self.code.len() {
return Err(InterpreterError::RuntimeError(
"Jump target out of bounds".to_string(),
));
}
self.pc = target;
}
InstructionResult::Return(value) => {
return Ok(value);
}
InstructionResult::Error(error) => {
return Err(error);
}
}
// Periodic interrupt check for long-running loops
if self.pc.trailing_zeros() >= 10 {
// Could add interrupt checking here in the future
}
}
}
}
impl Default for DirectThreadedInterpreter {
fn default() -> Self {
Self::new()
}
}
// Instruction handler functions - these are called via function pointers
/// Load constant onto stack
///
/// # Complexity
/// Cyclomatic complexity: 3 (within Toyota Way limits)
pub fn op_load_const(state: &mut InterpreterState, const_idx: u32) -> InstructionResult {
if let Some(value) = state.constants.get(const_idx as usize) {
state.stack.push(value.clone());
InstructionResult::Continue
} else {
InstructionResult::Error(InterpreterError::RuntimeError(
"Invalid constant index".to_string(),
))
}
}
/// Load nil value onto stack
///
/// # Complexity
/// Cyclomatic complexity: 1 (within Toyota Way limits)
pub fn op_load_nil(state: &mut InterpreterState, _operand: u32) -> InstructionResult {
state.stack.push(Value::Nil);
InstructionResult::Continue
}
/// Load variable value onto stack
///
/// # Complexity
/// Cyclomatic complexity: 1 (within Toyota Way limits)
#[allow(dead_code)] // Will be used when variable support is implemented
pub fn op_load_var(_state: &mut InterpreterState, name_idx: u32) -> InstructionResult {
// For now, just return error - variable lookup not implemented in isolated module
InstructionResult::Error(InterpreterError::RuntimeError(format!(
"Variable lookup not implemented in isolated compilation module: index {name_idx}"
)))
}
/// Return value from execution
///
/// # Complexity
/// Cyclomatic complexity: 3 (within Toyota Way limits)
pub fn op_return(state: &mut InterpreterState, _operand: u32) -> InstructionResult {
if let Some(value) = state.stack.pop() {
InstructionResult::Return(value)
} else {
InstructionResult::Return(Value::Nil)
}
}
/// Jump unconditionally
///
/// # Complexity
/// Cyclomatic complexity: 1 (within Toyota Way limits)
pub fn op_jump(_state: &mut InterpreterState, target: u32) -> InstructionResult {
InstructionResult::Jump(target as usize)
}
/// Jump if top of stack is false
///
/// # Complexity
/// Cyclomatic complexity: 4 (within Toyota Way limits)
pub fn op_jump_if_false(state: &mut InterpreterState, target: u32) -> InstructionResult {
if let Some(value) = state.stack.pop() {
match value {
Value::Bool(false) | Value::Nil => InstructionResult::Jump(target as usize),
_ => InstructionResult::Continue,
}
} else {
InstructionResult::Error(InterpreterError::RuntimeError(
"Stack underflow in jump_if_false".to_string(),
))
}
}
/// AST fallback handler
///
/// # Complexity
/// Cyclomatic complexity: 3 (within Toyota Way limits)
#[allow(dead_code)] // Will be used for unsupported AST nodes
pub fn op_ast_fallback(state: &mut InterpreterState, fallback_idx: u32) -> InstructionResult {
if let Some(Value::String(fallback_msg)) = state.constants.get(fallback_idx as usize) {
InstructionResult::Error(InterpreterError::RuntimeError(format!(
"AST fallback not implemented: {fallback_msg}"
)))
} else {
InstructionResult::Error(InterpreterError::RuntimeError(
"Invalid AST fallback constant".to_string(),
))
}
}
/// Binary addition operation
///
/// # Complexity
/// Cyclomatic complexity: 3 (within Toyota Way limits)
pub fn op_add(state: &mut InterpreterState, _operand: u32) -> InstructionResult {
binary_arithmetic_op(state, |a, b| match (a, b) {
(Value::Integer(x), Value::Integer(y)) => Some(Value::Integer(x + y)),
(Value::Float(x), Value::Float(y)) => Some(Value::Float(x + y)),
(Value::Integer(x), Value::Float(y)) => Some(Value::Float(*x as f64 + y)),
(Value::Float(x), Value::Integer(y)) => Some(Value::Float(x + *y as f64)),
_ => None,
})
}
/// Binary subtraction operation
///
/// # Complexity
/// Cyclomatic complexity: 3 (within Toyota Way limits)
pub fn op_sub(state: &mut InterpreterState, _operand: u32) -> InstructionResult {
binary_arithmetic_op(state, |a, b| match (a, b) {
(Value::Integer(x), Value::Integer(y)) => Some(Value::Integer(x - y)),
(Value::Float(x), Value::Float(y)) => Some(Value::Float(x - y)),
(Value::Integer(x), Value::Float(y)) => Some(Value::Float(*x as f64 - y)),
(Value::Float(x), Value::Integer(y)) => Some(Value::Float(x - *y as f64)),
_ => None,
})
}
/// Binary multiplication operation
///
/// # Complexity
/// Cyclomatic complexity: 3 (within Toyota Way limits)
pub fn op_mul(state: &mut InterpreterState, _operand: u32) -> InstructionResult {
binary_arithmetic_op(state, |a, b| match (a, b) {
(Value::Integer(x), Value::Integer(y)) => Some(Value::Integer(x * y)),
(Value::Float(x), Value::Float(y)) => Some(Value::Float(x * y)),
(Value::Integer(x), Value::Float(y)) => Some(Value::Float(*x as f64 * y)),
(Value::Float(x), Value::Integer(y)) => Some(Value::Float(x * *y as f64)),
_ => None,
})
}
/// Binary division operation
///
/// # Complexity
/// Cyclomatic complexity: 8 (within Toyota Way limits)
pub fn op_div(state: &mut InterpreterState, _operand: u32) -> InstructionResult {
binary_arithmetic_op(state, |a, b| match (a, b) {
(Value::Integer(x), Value::Integer(y)) => {
if *y == 0 {
None // Division by zero
} else {
Some(Value::Integer(x / y))
}
}
(Value::Float(x), Value::Float(y)) => {
if *y == 0.0 {
None // Division by zero
} else {
Some(Value::Float(x / y))
}
}
(Value::Integer(x), Value::Float(y)) => {
if *y == 0.0 {
None // Division by zero
} else {
Some(Value::Float(*x as f64 / y))
}
}
(Value::Float(x), Value::Integer(y)) => {
if *y == 0 {
None // Division by zero
} else {
Some(Value::Float(x / *y as f64))
}
}
_ => None,
})
}
/// Helper for binary arithmetic operations
///
/// # Complexity
/// Cyclomatic complexity: 4 (within Toyota Way limits)
fn binary_arithmetic_op<F>(state: &mut InterpreterState, op: F) -> InstructionResult
where
F: FnOnce(&Value, &Value) -> Option<Value>,
{
if state.stack.len() < 2 {
return InstructionResult::Error(InterpreterError::RuntimeError(
"Stack underflow in arithmetic operation".to_string(),
));
}
let right = state.stack.pop().expect("Stack underflow checked above");
let left = state.stack.pop().expect("Stack underflow checked above");
match op(&left, &right) {
Some(result) => {
state.stack.push(result);
InstructionResult::Continue
}
None => InstructionResult::Error(InterpreterError::RuntimeError(format!(
"Invalid arithmetic operation between {left:?} and {right:?}"
))),
}
}
#[cfg(test)]
#[path = "compilation_tests.rs"]
mod tests;