diff options
Diffstat (limited to 'users/tazjin/rlox')
-rw-r--r-- | users/tazjin/rlox/src/errors.rs | 4 | ||||
-rw-r--r-- | users/tazjin/rlox/src/interpreter.rs | 19 | ||||
-rw-r--r-- | users/tazjin/rlox/src/scanner.rs | 15 |
3 files changed, 29 insertions, 9 deletions
diff --git a/users/tazjin/rlox/src/errors.rs b/users/tazjin/rlox/src/errors.rs index 306cfec4ca34..bab3f4667a74 100644 --- a/users/tazjin/rlox/src/errors.rs +++ b/users/tazjin/rlox/src/errors.rs @@ -10,6 +10,6 @@ pub struct Error { pub kind: ErrorKind, } -pub fn report(loc: &str, err: &Error) { - eprintln!("[line {}] Error {}: {:?}", err.line, loc, err.kind); +pub fn report(err: &Error) { + eprintln!("[line {}] Error: {:?}", err.line, err.kind); } diff --git a/users/tazjin/rlox/src/interpreter.rs b/users/tazjin/rlox/src/interpreter.rs index 8031329e7074..77f2492a46a2 100644 --- a/users/tazjin/rlox/src/interpreter.rs +++ b/users/tazjin/rlox/src/interpreter.rs @@ -1,9 +1,24 @@ -use crate::scanner; +use crate::errors::{report, Error}; +use crate::scanner::{self, Token}; // Run some Lox code and print it to stdout pub fn run(code: &str) { let chars: Vec<char> = code.chars().collect(); - for token in scanner::scan(&chars) { + + match scanner::scan(&chars) { + Ok(tokens) => print_tokens(tokens), + Err(errors) => report_errors(errors), + } +} + +fn print_tokens<'a>(tokens: Vec<Token<'a>>) { + for token in tokens { println!("{:?}", token); } } + +fn report_errors(errors: Vec<Error>) { + for error in errors { + report(&error); + } +} diff --git a/users/tazjin/rlox/src/scanner.rs b/users/tazjin/rlox/src/scanner.rs index e0b04981b4a4..2eed89bd6beb 100644 --- a/users/tazjin/rlox/src/scanner.rs +++ b/users/tazjin/rlox/src/scanner.rs @@ -254,19 +254,18 @@ impl<'a> Scanner<'a> { self.add_token(token_kind); } - fn scan_tokens(mut self) -> Vec<Token<'a>> { + fn scan_tokens(&mut self) { while !self.is_at_end() { self.start = self.current; self.scan_token(); } self.add_token(TokenKind::Eof); - return self.tokens; } } -pub fn scan<'a>(input: &'a [char]) -> Vec<Token<'a>> { - let scanner = Scanner { +pub fn scan<'a>(input: &'a [char]) -> Result<Vec<Token<'a>>, Vec<Error>> { + let mut scanner = Scanner { source: &input, tokens: vec![], errors: vec![], @@ -275,5 +274,11 @@ pub fn scan<'a>(input: &'a [char]) -> Vec<Token<'a>> { line: 0, }; - return scanner.scan_tokens(); + scanner.scan_tokens(); + + if !scanner.errors.is_empty() { + return Err(scanner.errors); + } + + return Ok(scanner.tokens); } |