muScript: support comments

This commit is contained in:
Johannes Frohnmeyer 2023-03-11 13:52:59 +01:00
parent 6f180900b6
commit a5fa86a6c7
Signed by: Johannes
GPG Key ID: E76429612C2929F4
2 changed files with 56 additions and 4 deletions

View File

@ -32,7 +32,7 @@ public class Lexer {
} }
// Scan expression // Scan expression
skipWhitespace(); skipWhitespaceAndComments();
if (isAtEnd()) { if (isAtEnd()) {
createToken(Token.EOF); createToken(Token.EOF);
return; return;
@ -132,13 +132,32 @@ public class Lexer {
} }
} }
private void skipWhitespace() { private void skipWhitespaceAndComments() {
while (true) { while (true) {
if (isAtEnd()) return; if (isAtEnd()) return;
char c = peek();
switch (c) { switch (peek()) {
case ' ', '\r', '\t', '\n' -> advance(); 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 -> { default -> {
start = current; start = current;
return; return;

View File

@ -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());
}
}