Refactor AST-Tool evaluation logic

Consolidate AST source code evaluation logic to handle script strings,
file paths, and stdin more uniformly. Introduce a `read_stdin` helper
function.
This commit is contained in:
Michael Schimmel
2026-03-09 10:36:07 +01:00
parent 66171b0802
commit cb4507b2da
+32 -18
View File
@@ -2,6 +2,7 @@ use clap::Parser;
use myc::ast::environment::Environment;
use myc::utils::tester;
use std::fs;
use std::io::{self, IsTerminal, Read};
use std::path::PathBuf;
#[derive(Parser)]
@@ -73,20 +74,28 @@ fn main() {
return;
}
if let Some(script_str) = cli.eval {
if cli.dump {
match env.dump_ast(&script_str) {
Ok(dump) => println!("{}", dump),
Err(e) => eprintln!("Error dumping AST: {}", e),
}
} else if cli.trace {
execute_trace(&env, &script_str);
} else {
execute(&env, &script_str);
}
// Determine the source code to execute
let source = if let Some(script_str) = cli.eval {
Some(script_str)
} else if let Some(file_path) = cli.file {
if file_path.to_str() == Some("-") {
read_stdin()
} else {
match fs::read_to_string(&file_path) {
Ok(content) => {
Ok(content) => Some(content),
Err(e) => {
eprintln!("Error reading file {:?}: {}", file_path, e);
std::process::exit(1);
}
}
}
} else if !io::stdin().is_terminal() {
read_stdin()
} else {
None
};
if let Some(content) = source {
if cli.dump {
match env.dump_ast(&content) {
Ok(dump) => println!("{}", dump),
@@ -97,17 +106,22 @@ fn main() {
} else {
execute(&env, &content);
}
}
Err(e) => {
eprintln!("Error reading file {:?}: {}", file_path, e);
std::process::exit(1);
}
}
} else {
println!("MYC AST Compiler CLI. Use --help for usage.");
}
}
fn read_stdin() -> Option<String> {
let mut buffer = String::new();
match io::stdin().read_to_string(&mut buffer) {
Ok(_) => Some(buffer),
Err(e) => {
eprintln!("Error reading from stdin: {}", e);
std::process::exit(1);
}
}
}
fn execute(env: &Environment, source: &str) {
let result = env.compile(source);
for diag in &result.diagnostics.items {