From 7cdaa49a8e1d8755dbcefbf0d5adf335ef8b9612 Mon Sep 17 00:00:00 2001 From: AYM1607 Date: Sun, 7 May 2023 01:25:59 +0000 Subject: [PATCH] Implement c-style nested comments. --- golox/internal/runner/scanner.go | 34 ++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/golox/internal/runner/scanner.go b/golox/internal/runner/scanner.go index 646c042..c436550 100644 --- a/golox/internal/runner/scanner.go +++ b/golox/internal/runner/scanner.go @@ -90,6 +90,8 @@ func (s *Scanner) scanToken() { for s.peek() != '\n' && !s.isAtEnd() { s.advance() } + } else if s.match('*') { + s.scanInlineComment() } else { s.addToken(SLASH) } @@ -217,6 +219,38 @@ func (s *Scanner) scanIdentifier() { s.addToken(typ) } +func (s *Scanner) scanInlineComment() { + depth := 1 + closed := false + for !s.isAtEnd() && depth >= 1 { + p := s.peek() + pn := s.peekNex() + switch { + case p == '\n': + s.line += 1 + case p == '/' && pn == '*': + // Consume the extra character. + s.advance() + depth += 1 + case p == '*' && pn == '/': + // Consume the extra character. + s.advance() + depth -= 1 + if depth == 0 { + closed = true + } + } + // Always consume at least one character. + s.advance() + } + + // Only report an error if the last nested (could just be one) comment + // did not close. + if s.isAtEnd() && !closed { + lerrors.EmitError(s.line, "Unterminated comment.") + } +} + // addToken produces a single token without a literal value. func (s *Scanner) addToken(typ TokenType) { s.addTokenWithLiteral(typ, nil)