r2rust_core/
repl.rs

1/// REPL (Read-Eval-Print Loop) module for interactive evaluation.
2///
3/// This module implements an interactive interface where users can input
4/// commands and expressions to be evaluated in real-time.
5
6use crate::environment::Environment;
7use crate::evaluator::evaluate;
8use crate::lexer::tokenize;
9use crate::parser::parse;
10use std::io::{self, Write};
11
12/// Starts the REPL (Read-Eval-Print Loop).
13///
14/// This function initializes the REPL environment and processes user input
15/// in an interactive loop. Users can type commands, expressions, or special
16/// keywords like `help` or `exit`.
17pub fn start_repl() {
18    println!("Welcome to R2Rust REPL! 🚀");
19    println!("Type 'exit' to quit or 'help' for instructions.");
20
21    let mut input = String::new();
22    let mut environment = Environment::new(); // Stores variables and their state
23
24    loop {
25        // Display prompt
26        print!("rustr> ");
27        io::stdout().flush().unwrap();
28
29        // Read input from user
30        input.clear();
31        if io::stdin().read_line(&mut input).is_err() {
32            println!("Error reading input. Try again.");
33            continue;
34        }
35        let trimmed_input = input.trim();
36
37        // Handle special commands
38        if trimmed_input == "exit" {
39            println!("Goodbye!");
40            break;
41        } else if trimmed_input == "help" {
42            print_help();
43            continue;
44        }
45
46        // Tokenize the input
47        let tokens = match tokenize(trimmed_input) {
48            tokens => tokens,
49        };
50
51        // Parse tokens into an AST
52        let ast = match parse(&tokens) {
53            Ok(ast) => ast,
54            Err(e) => {
55                println!("Parse Error: {}", e);
56                continue;
57            }
58        };
59
60        // Evaluate the AST
61        match evaluate(ast, &mut environment) {
62            Ok(result) => println!("Result: {}", result),
63            Err(e) => println!("Evaluation Error: {}", e),
64        }
65    }
66}
67
68/// Prints REPL help instructions.
69///
70/// This function displays a list of supported commands and syntax for the REPL.
71fn print_help() {
72    println!("R2Rust REPL Instructions:");
73    println!("  - Type mathematical expressions like `10 + 20`.");
74    println!("  - Assign variables with `<-`, e.g., `x <- 42`.");
75    println!("  - Use variables in expressions, e.g., `y <- x + 8`.");
76    println!("  - Type 'exit' to quit.");
77}