From cb4507b2da40c1c9f84dbd86002b807b55aaa0f7 Mon Sep 17 00:00:00 2001 From: Michael Schimmel Date: Mon, 9 Mar 2026 10:36:07 +0100 Subject: [PATCH] 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. --- src/bin/ast.rs | 60 +++++++++++++++++++++++++++++++------------------- 1 file changed, 37 insertions(+), 23 deletions(-) diff --git a/src/bin/ast.rs b/src/bin/ast.rs index 4a3dd40..a1f1760 100644 --- a/src/bin/ast.rs +++ b/src/bin/ast.rs @@ -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,41 +74,54 @@ fn main() { return; } - if let Some(script_str) = cli.eval { + // 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) => 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(&script_str) { + match env.dump_ast(&content) { Ok(dump) => println!("{}", dump), Err(e) => eprintln!("Error dumping AST: {}", e), } } else if cli.trace { - execute_trace(&env, &script_str); + execute_trace(&env, &content); } else { - execute(&env, &script_str); - } - } else if let Some(file_path) = cli.file { - match fs::read_to_string(&file_path) { - Ok(content) => { - if cli.dump { - match env.dump_ast(&content) { - Ok(dump) => println!("{}", dump), - Err(e) => eprintln!("Error dumping AST: {}", e), - } - } else if cli.trace { - execute_trace(&env, &content); - } else { - execute(&env, &content); - } - } - Err(e) => { - eprintln!("Error reading file {:?}: {}", file_path, e); - std::process::exit(1); - } + execute(&env, &content); } } else { println!("MYC AST Compiler CLI. Use --help for usage."); } } +fn read_stdin() -> Option { + 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 {