2025-10-03 19:07:12 +02:00
|
|
|
mod backend;
|
|
|
|
|
mod frontend;
|
|
|
|
|
mod logging;
|
|
|
|
|
mod result;
|
|
|
|
|
|
|
|
|
|
use crate::{
|
2025-10-06 18:52:32 +02:00
|
|
|
backend::interpreter::{EvaluateInterpreter, Interpreter},
|
2025-10-03 19:07:12 +02:00
|
|
|
frontend::{
|
|
|
|
|
lexer::Lexer,
|
|
|
|
|
parser::Parser,
|
2025-10-06 18:52:32 +02:00
|
|
|
source_registry::{SourceId, SourceRegistry},
|
2025-10-03 19:07:12 +02:00
|
|
|
},
|
|
|
|
|
result::{LoxError, LoxResult},
|
|
|
|
|
};
|
2025-10-04 21:05:00 +02:00
|
|
|
use std::env;
|
2025-10-03 19:07:12 +02:00
|
|
|
use std::fs;
|
|
|
|
|
|
2025-10-06 18:52:32 +02:00
|
|
|
#[derive(Debug, Clone, Copy, PartialEq)]
|
|
|
|
|
enum ExecutionStage {
|
|
|
|
|
Tokens,
|
|
|
|
|
Ast,
|
|
|
|
|
Full,
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-03 19:07:12 +02:00
|
|
|
fn main() -> LoxResult<()> {
|
|
|
|
|
let args: Vec<String> = env::args().collect();
|
|
|
|
|
let mut lox = LoxInterpreter::new();
|
|
|
|
|
|
2025-10-06 18:52:32 +02:00
|
|
|
let (stage, file_path) = parse_args(&args);
|
|
|
|
|
|
|
|
|
|
let _ = match file_path {
|
|
|
|
|
Some(path) => lox.run_file(&path, stage),
|
|
|
|
|
None => lox.run_prompt(stage),
|
2025-10-04 19:02:33 +02:00
|
|
|
};
|
2025-10-03 19:07:12 +02:00
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-06 18:52:32 +02:00
|
|
|
fn parse_args(args: &[String]) -> (ExecutionStage, Option<String>) {
|
|
|
|
|
if args.len() == 1 {
|
|
|
|
|
// Solo il nome del programma: modalità interattiva completa
|
|
|
|
|
(ExecutionStage::Full, None)
|
|
|
|
|
} else if args.len() == 2 {
|
|
|
|
|
// Un argomento: potrebbe essere file o flag
|
|
|
|
|
let arg = &args[1];
|
|
|
|
|
if arg == "--tokens" || arg == "--ast" || arg == "--full" {
|
|
|
|
|
// Flag senza file: modalità interattiva
|
|
|
|
|
let stage = match arg.as_str() {
|
|
|
|
|
"--tokens" => ExecutionStage::Tokens,
|
|
|
|
|
"--ast" => ExecutionStage::Ast,
|
|
|
|
|
"--full" => ExecutionStage::Full,
|
|
|
|
|
_ => ExecutionStage::Full,
|
|
|
|
|
};
|
|
|
|
|
(stage, None)
|
|
|
|
|
} else {
|
|
|
|
|
// File senza flag: esecuzione completa del file
|
|
|
|
|
(ExecutionStage::Full, Some(arg.clone()))
|
|
|
|
|
}
|
|
|
|
|
} else if args.len() == 3 {
|
|
|
|
|
// Due argomenti: flag + file
|
|
|
|
|
let flag = &args[1];
|
|
|
|
|
let file = &args[2];
|
|
|
|
|
let stage = match flag.as_str() {
|
|
|
|
|
"--tokens" => ExecutionStage::Tokens,
|
|
|
|
|
"--ast" => ExecutionStage::Ast,
|
|
|
|
|
"--full" => ExecutionStage::Full,
|
|
|
|
|
_ => {
|
|
|
|
|
eprintln!("Unknown flag: {}. Use --tokens, --ast, or --full", flag);
|
|
|
|
|
eprintln!("Usage: {} [--tokens|--ast|--full] [script]", args[0]);
|
|
|
|
|
std::process::exit(64);
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
(stage, Some(file.clone()))
|
|
|
|
|
} else {
|
|
|
|
|
eprintln!("Usage: {} [--tokens|--ast|--full] [script]", args[0]);
|
|
|
|
|
std::process::exit(64);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-03 19:07:12 +02:00
|
|
|
struct LoxInterpreter {
|
|
|
|
|
source_registry: SourceRegistry,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl LoxInterpreter {
|
|
|
|
|
pub fn new() -> Self {
|
|
|
|
|
LoxInterpreter {
|
|
|
|
|
source_registry: SourceRegistry::new(),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ✅ Pipeline funzionale per file
|
2025-10-06 18:52:32 +02:00
|
|
|
fn run_file(&mut self, path: &str, stage: ExecutionStage) -> LoxResult<()> {
|
2025-10-03 19:07:12 +02:00
|
|
|
fs::read_to_string(path)
|
|
|
|
|
.map_err(|e| LoxError::IoError {
|
|
|
|
|
message: e.to_string(),
|
|
|
|
|
})
|
|
|
|
|
.and_then(|source| self.source_registry.add_source_string(source))
|
2025-10-06 18:52:32 +02:00
|
|
|
.and_then(|source_id| self.process_source(source_id, stage))
|
|
|
|
|
.map(|result| match stage {
|
|
|
|
|
ExecutionStage::Tokens => println!("=== TOKENS ===\n{}", result),
|
|
|
|
|
ExecutionStage::Ast => println!("=== AST ===\n{}", result),
|
|
|
|
|
ExecutionStage::Full => println!("=== EXECUTION RESULT ===\n{}", result),
|
|
|
|
|
})
|
2025-10-03 19:07:12 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ✅ Pipeline funzionale per prompt
|
2025-10-06 18:52:32 +02:00
|
|
|
fn run_prompt(&mut self, stage: ExecutionStage) -> LoxResult<()> {
|
|
|
|
|
use std::io::{self, Write};
|
2025-10-03 19:07:12 +02:00
|
|
|
|
2025-10-06 18:52:32 +02:00
|
|
|
println!("Lox REPL (Stage: {:?}) - Type 'exit' to quit", stage);
|
|
|
|
|
|
|
|
|
|
loop {
|
|
|
|
|
print!("> ");
|
|
|
|
|
io::stdout().flush().ok();
|
|
|
|
|
|
|
|
|
|
let mut input = String::new();
|
|
|
|
|
match io::stdin().read_line(&mut input) {
|
|
|
|
|
Ok(_) => {
|
|
|
|
|
let line = input.trim();
|
|
|
|
|
if line == "exit" || line.is_empty() {
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
match self.source_registry.add_source_string(line.to_string()) {
|
|
|
|
|
Ok(source_id) => {
|
|
|
|
|
match self.process_source(source_id, stage) {
|
|
|
|
|
Ok(result) => match stage {
|
|
|
|
|
ExecutionStage::Tokens => println!("Tokens: {}", result),
|
|
|
|
|
ExecutionStage::Ast => println!("AST: {}", result),
|
|
|
|
|
ExecutionStage::Full => println!("Result: {}", result),
|
|
|
|
|
},
|
|
|
|
|
Err(_) => {} // Errore già stampato in process_source
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
Err(e) => eprintln!("Error: {}", e),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
Err(e) => {
|
|
|
|
|
eprintln!("Error reading input: {}", e);
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2025-10-03 19:07:12 +02:00
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-06 18:52:32 +02:00
|
|
|
fn process_source(&self, source_id: SourceId, stage: ExecutionStage) -> LoxResult<String> {
|
|
|
|
|
let source_content = self.source_registry.get_by_id(source_id).content.clone();
|
|
|
|
|
let mut lexer = Lexer::new(source_content, source_id);
|
|
|
|
|
|
|
|
|
|
// Stage 1: Tokenization
|
|
|
|
|
let tokens = lexer.scans_tokens().or_else(|err| {
|
|
|
|
|
err.print_with_context(&self.source_registry);
|
|
|
|
|
Err(err)
|
|
|
|
|
})?;
|
|
|
|
|
|
|
|
|
|
if stage == ExecutionStage::Tokens {
|
|
|
|
|
return Ok(format_tokens(&tokens));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Stage 2: Parsing
|
|
|
|
|
let ast = Parser::new(tokens).parse().or_else(|err| {
|
|
|
|
|
err.print_with_context(&self.source_registry);
|
|
|
|
|
Err(err)
|
|
|
|
|
})?;
|
|
|
|
|
|
|
|
|
|
if stage == ExecutionStage::Ast {
|
|
|
|
|
return Ok(format_ast(&ast));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Stage 3: Interpretation
|
|
|
|
|
let mut interpreter = Interpreter::new();
|
|
|
|
|
let mut result = None;
|
|
|
|
|
|
|
|
|
|
for (index, stmt) in ast.iter().enumerate() {
|
|
|
|
|
println!("Executing statement {}: {:?}", index, stmt);
|
|
|
|
|
result = Some(interpreter.evaluate(stmt.clone()).or_else(|err| {
|
2025-10-03 19:07:12 +02:00
|
|
|
err.print_with_context(&self.source_registry);
|
|
|
|
|
Err(err)
|
2025-10-06 18:52:32 +02:00
|
|
|
})?);
|
|
|
|
|
}
|
2025-10-03 19:07:12 +02:00
|
|
|
|
2025-10-06 18:52:32 +02:00
|
|
|
match result {
|
|
|
|
|
Some(res) => Ok(format!("{}", res)),
|
|
|
|
|
None => Ok("No statements executed".to_string()),
|
|
|
|
|
}
|
2025-10-03 19:07:12 +02:00
|
|
|
}
|
|
|
|
|
}
|
2025-10-06 18:52:32 +02:00
|
|
|
|
|
|
|
|
fn format_tokens(tokens: &[crate::frontend::tokens::Token]) -> String {
|
|
|
|
|
tokens
|
|
|
|
|
.iter()
|
|
|
|
|
.enumerate()
|
|
|
|
|
.map(|(i, token)| format!("{:3}: {:?}", i, token))
|
|
|
|
|
.collect::<Vec<_>>()
|
|
|
|
|
.join("\n")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn format_ast(ast: &[crate::frontend::ast::AstNode<crate::frontend::ast::Stmt>]) -> String {
|
|
|
|
|
use crate::logging::display_ast::{pretty_print_with_config, PrettyConfig};
|
|
|
|
|
|
|
|
|
|
let config = PrettyConfig {
|
|
|
|
|
indent: " ".to_string(),
|
|
|
|
|
max_depth: None,
|
|
|
|
|
show_positions: false,
|
|
|
|
|
..Default::default()
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
ast.iter()
|
|
|
|
|
.enumerate()
|
|
|
|
|
.map(|(i, stmt)| {
|
|
|
|
|
format!(
|
|
|
|
|
"Statement {}:\n{}",
|
|
|
|
|
i,
|
|
|
|
|
pretty_print_with_config(&stmt.node, &config)
|
|
|
|
|
)
|
|
|
|
|
})
|
|
|
|
|
.collect::<Vec<_>>()
|
|
|
|
|
.join("\n\n")
|
|
|
|
|
}
|