From 0fcd4d09f1fcb5841b651a552bfe727dbcfab335 Mon Sep 17 00:00:00 2001 From: Emmanuel BERNAT Date: Fri, 29 Mar 2024 07:56:40 +0100 Subject: [PATCH] =?UTF-8?q?S=C3=A9paration=20de=20RLox=20dans=20un=20sous-?= =?UTF-8?q?module=20ind=C3=A9pendant.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main.rs | 32 ++++++++++++++++++++++++-------- src/rlox.rs | 16 ++++++++++++++++ 2 files changed, 40 insertions(+), 8 deletions(-) create mode 100644 src/rlox.rs diff --git a/src/main.rs b/src/main.rs index c0eacd4..9e078e5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,27 +2,40 @@ use std::env; use std::fs; use std::io; use std::io::Write; +use crate::rlox::RLox; +use std::process; + +pub mod rlox; + +// Exit codes from #include +const EX_OK: i32 = 0; +const EX_DATAERR: i32 = 65; +const EX_USAGE : i32 = 66; fn main() { let args: Vec = env::args().collect(); - match args.len() { + let exit_code = match args.len() { 1 => run_prompt(), 2 => run_file(&args[1]), _ => { println!("Usage : rlox [script]"); + EX_USAGE } - } + }; + + process::exit(exit_code); } -fn run_file( file_path: &str ) { +fn run_file( file_path: &str ) -> i32 { let contents = fs::read_to_string(file_path) .expect(&format!("Should have been able to read the file {file_path}")); - run(contents); + run(contents) } -fn run_prompt() { +fn run_prompt() -> i32 { + let mut exit_code = EX_OK; loop { print!("> "); io::stdout().flush().expect("Unable to flush stdout"); @@ -36,12 +49,15 @@ fn run_prompt() { break; } - run(line); + exit_code = run(line); } + exit_code } -fn run( _script: String ) { +fn run( script: String ) -> i32 { + let rlox_interpreter = RLox { had_error: false }; + + if rlox_interpreter.had_error { EX_DATAERR } else { EX_OK } } -// http://www.craftinginterpreters.com/scanning.html#error-handling \ No newline at end of file diff --git a/src/rlox.rs b/src/rlox.rs new file mode 100644 index 0000000..8066210 --- /dev/null +++ b/src/rlox.rs @@ -0,0 +1,16 @@ + + +pub struct RLox { + pub had_error: bool, +} + + +impl RLox { + fn error( &self, line: u32, message: String ) { + self.report(line, String::from(""), message); + } + + fn report( &self, line: u32, place: String, message: String ) { + println!("[line {line}] Error {place}: {message}"); + } +}