Scanner - Block comments w/ nesting

This commit is contained in:
Emmanuel BENOîT 2022-12-30 20:19:00 +01:00
parent 21778a745e
commit c1025153d1

View file

@ -85,6 +85,8 @@ impl Scanner {
while self.peek() != '\n' && !self.is_at_end() {
self.current += 1;
}
} else if self.is_match('*') {
self.block_comment(err_hdl);
} else {
self.add_token(TokenType::Slash)
}
@ -195,6 +197,32 @@ impl Scanner {
}
}
/// Read (and ignore) a block comment. Block comments may be nested.
fn block_comment(&mut self, err_hdl: &mut ErrorHandler) {
let mut depth = 1;
loop {
if self.is_at_end() {
err_hdl.error(self.line, "unterminated block comment");
return
}
let cur = self.advance();
let next = self.peek();
if cur == '*' && next == '/' {
depth -= 1;
self.current += 1;
if depth == 0 {
return;
}
} else if cur == '/' && next == '*' {
depth += 1;
self.current += 1;
} else if cur == '\n' {
self.line += 1;
}
}
}
/// Check whether the end of the input has been reached.
fn is_at_end(&self) -> bool {
self.current >= self.len