From ab75e7342152afab877f61580c454f623ce4826e Mon Sep 17 00:00:00 2001 From: Tom Willemse Date: Thu, 22 Oct 2020 11:52:10 -0700 Subject: [PATCH] Add support for nested multi-line comments MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit For example, this is a nested multi-line comment: /* Here's a multi-line comment /* It explains what this function does */ It shouldn't appear in any output */ If the comment isn’t closed at the end of the file, that’s fine. --- src/com/craftinginterpreters/lox/Scanner.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/com/craftinginterpreters/lox/Scanner.java b/src/com/craftinginterpreters/lox/Scanner.java index e21f701..9f95073 100644 --- a/src/com/craftinginterpreters/lox/Scanner.java +++ b/src/com/craftinginterpreters/lox/Scanner.java @@ -80,6 +80,8 @@ class Scanner { if (match('/')) { // A comment goes until the end of the line. while (peek() != '\n' && !isAtEnd()) advance(); + } else if (match('*')) { + multiline_comment(); } else { addToken(SLASH); } @@ -155,6 +157,34 @@ class Scanner { addToken(STRING, value); } + private void multiline_comment() { + int depth = 0; + + while (!isAtEnd() + && (peek() != '*' || peekNext() != '/' || depth != 0)) { + if (peek() == '\n') line++; + + if (peek() == '/' && peekNext() == '*') { + depth++; + advance(); + } + + if (peek() == '*' && peekNext() == '/') { + depth--; + advance(); + } + + advance(); + } + + if (isAtEnd()) { + return; + } + + advance(); + advance(); + } + private boolean match(char expected) { if (isAtEnd()) return false; if (source.charAt(current) != expected) return false;