diff --git a/src/errors.rs b/src/errors.rs new file mode 100644 index 0000000..14e724b --- /dev/null +++ b/src/errors.rs @@ -0,0 +1,23 @@ +/// Error handler. Can be used to print error messages; will also retain the +/// current error status. +#[derive(Default, Debug)] +pub struct ErrorHandler { + had_error: bool, +} + +impl ErrorHandler { + /// Check whether this handler reported an error. + pub fn had_error(&self) -> bool { + self.had_error + } + + /// Report an error. + pub fn error(&mut self, line: usize, message: &str) { + self.report(line, "", message) + } + + fn report(&mut self, line: usize, pos: &str, message: &str) { + self.had_error = true; + println!("[line {line}] Error{pos}: {message}") + } +} diff --git a/src/main.rs b/src/main.rs index 637f4ad..2bd696a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,5 @@ +mod errors; +mod scanner; mod tokens; use std::{ @@ -6,40 +8,17 @@ use std::{ process::ExitCode, }; -/// Error handler. Can be used to print error messages; will also retain the -/// current error status. -#[derive(Default, Debug)] -struct ErrorHandler { - had_error: bool, -} - -impl ErrorHandler { - /// Check whether this handler reported an error. - pub fn had_error(&self) -> bool { - self.had_error - } - - /// Report an error. - pub fn error(&mut self, line: usize, message: &str) { - self.report(line, "", message) - } - - fn report(&mut self, line: usize, pos: &str, message: &str) { - self.had_error = true; - println!("[line {line}] Error{pos}: {message}") - } -} +use errors::ErrorHandler; +use scanner::Scanner; /// Execute a script. -fn run(_source: String) -> ErrorHandler { - let error_handler = ErrorHandler::default(); - /* +fn run(source: String) -> ErrorHandler { + let mut error_handler = ErrorHandler::default(); let scanner = Scanner::new(source); - let tokens = scanner.scan_tokens(); + let tokens = scanner.scan_tokens(&mut error_handler); for token in tokens { - println!("{}", token); + println!("{:#?}", token); } - */ error_handler } diff --git a/src/scanner.rs b/src/scanner.rs new file mode 100644 index 0000000..820d682 --- /dev/null +++ b/src/scanner.rs @@ -0,0 +1,31 @@ +use crate::ErrorHandler; + +use super::tokens::Token; + +/// The scanner's state, including the source it is scanning. +pub struct Scanner { + source: String, + tokens: Vec, + start: usize, + current: usize, + line: usize, +} + +impl Scanner { + /// Initialize a scanner by specifying the source code to scan. + pub fn new(source: String) -> Scanner { + Scanner{ + source: source, + tokens: Vec::new(), + start: 0, + current: 0, + line: 1, + } + } + + /// Scan the source code, generating the list of tokens and returning it. + /// The scanner itself is destroyed once the process is complete. + pub fn scan_tokens(self, err_hdl: &mut ErrorHandler) -> Vec { + self.tokens + } +}