From a5fa86a6c702f13b772aa3bdf0cd95a019d96860 Mon Sep 17 00:00:00 2001 From: JFronny Date: Sat, 11 Mar 2023 13:52:59 +0100 Subject: [PATCH] muScript: support comments --- .../jfronny/muscript/compiler/Lexer.java | 27 ++++++++++++--- .../jfronny/muscript/test/CommentTest.java | 33 +++++++++++++++++++ 2 files changed, 56 insertions(+), 4 deletions(-) create mode 100644 muscript/src/test/java/io/gitlab/jfronny/muscript/test/CommentTest.java diff --git a/muscript/src/main/java/io/gitlab/jfronny/muscript/compiler/Lexer.java b/muscript/src/main/java/io/gitlab/jfronny/muscript/compiler/Lexer.java index 57155d6..a4b430f 100644 --- a/muscript/src/main/java/io/gitlab/jfronny/muscript/compiler/Lexer.java +++ b/muscript/src/main/java/io/gitlab/jfronny/muscript/compiler/Lexer.java @@ -32,7 +32,7 @@ public class Lexer { } // Scan expression - skipWhitespace(); + skipWhitespaceAndComments(); if (isAtEnd()) { createToken(Token.EOF); return; @@ -132,13 +132,32 @@ public class Lexer { } } - private void skipWhitespace() { + private void skipWhitespaceAndComments() { while (true) { if (isAtEnd()) return; - char c = peek(); - switch (c) { + switch (peek()) { case ' ', '\r', '\t', '\n' -> advance(); + case '/' -> { + switch (peekNext()) { + case '/' -> { + while (!isAtEnd() && peek() != '\r' && peek() != '\n') advance(); + } + case '*' -> { + advance(); + advance(); + while (!isAtEnd() && (peek() != '*' || peekNext() != '/')) advance(); + if (!isAtEnd()) { + advance(); + advance(); + } + } + default -> { + start = current; + return; + } + } + } default -> { start = current; return; diff --git a/muscript/src/test/java/io/gitlab/jfronny/muscript/test/CommentTest.java b/muscript/src/test/java/io/gitlab/jfronny/muscript/test/CommentTest.java new file mode 100644 index 0000000..91934de --- /dev/null +++ b/muscript/src/test/java/io/gitlab/jfronny/muscript/test/CommentTest.java @@ -0,0 +1,33 @@ +package io.gitlab.jfronny.muscript.test; + +import io.gitlab.jfronny.muscript.compiler.Parser; +import org.junit.jupiter.api.Test; + +import static io.gitlab.jfronny.muscript.test.util.MuTestUtil.makeArgs; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class CommentTest { + @Test + void singleLine() { + assertEquals(2, Parser.parseScript(""" + n = 5 + n = 2 + // n = 3 + n + """).run(makeArgs()).asNumber().getValue()); + } + + @Test + void multiLine() { + assertEquals(2, Parser.parseScript(""" + n = 2 + /* n = 3 */ + /* + n = 3 + n = 4 + n = 5 + */ + n + """).run(makeArgs()).asNumber().getValue()); + } +}