From 9f61579dde53959486c80f1d2a5a7ab660ca93cd Mon Sep 17 00:00:00 2001 From: Vincent Ambo Date: Sat, 28 Nov 2020 16:52:13 +0100 Subject: feat(tazjin/rlox): Scan single-line comments Change-Id: I2efafdb1374ac2863a1f8d8a9310123a7dec0900 Reviewed-on: https://cl.tvl.fyi/c/depot/+/2187 Reviewed-by: tazjin Tested-by: BuildkiteCI --- users/tazjin/rlox/src/scanner.rs | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/users/tazjin/rlox/src/scanner.rs b/users/tazjin/rlox/src/scanner.rs index edd85496a73e..6b34288d1082 100644 --- a/users/tazjin/rlox/src/scanner.rs +++ b/users/tazjin/rlox/src/scanner.rs @@ -108,6 +108,17 @@ impl<'a> Scanner<'a> { '<' => self.add_if_next('=', TokenKind::LessEqual, TokenKind::Less), '>' => self.add_if_next('=', TokenKind::GreaterEqual, TokenKind::Greater), + '/' => { + // support comments until EOL by discarding characters + if self.match_next('/') { + while self.peek() != '\n' && !self.is_at_end() { + self.advance(); + } + } else { + self.add_token(TokenKind::Slash); + } + }, + unexpected => self.errors.push(Error { line: self.line, kind: ErrorKind::UnexpectedChar(unexpected), @@ -115,12 +126,28 @@ impl<'a> Scanner<'a> { }; } - fn add_if_next(&mut self, expected:char, then: TokenKind, or: TokenKind) { + fn match_next(&mut self, expected: char) -> bool { if self.is_at_end() || self.source[self.current] != expected { - self.add_token(or); + false } else { self.current += 1; + true + } + } + + fn add_if_next(&mut self, expected: char, then: TokenKind, or: TokenKind) { + if self.match_next(expected) { self.add_token(then); + } else { + self.add_token(or); + } + } + + fn peek(&self) -> char { + if self.is_at_end() { + return '\0'; + } else { + return self.source[self.current]; } } -- cgit 1.4.1