diff options
Diffstat (limited to 'src')
3 files changed, 37 insertions, 1 deletions
diff --git a/src/main/java/org/shedlang/compiler/parser/IntLiteralCannotHaveLeadingZeroesError.java b/src/main/java/org/shedlang/compiler/parser/IntLiteralCannotHaveLeadingZeroesError.java new file mode 100644 index 00000000..28421cad --- /dev/null +++ b/src/main/java/org/shedlang/compiler/parser/IntLiteralCannotHaveLeadingZeroesError.java @@ -0,0 +1,10 @@ +package org.shedlang.compiler.parser; + +import org.shedlang.compiler.errors.SourceError; +import org.shedlang.compiler.sources.Source; + +public class IntLiteralCannotHaveLeadingZeroesError extends SourceError { + public IntLiteralCannotHaveLeadingZeroesError(Source source) { + super("int literal cannot have leading zeroes", source); + } +} diff --git a/src/main/java/org/shedlang/compiler/parser/Parser.java b/src/main/java/org/shedlang/compiler/parser/Parser.java index 763d0a01..fcc92d99 100644 --- a/src/main/java/org/shedlang/compiler/parser/Parser.java +++ b/src/main/java/org/shedlang/compiler/parser/Parser.java @@ -481,6 +481,12 @@ public class Parser { var end = tokens.position(); var source = start.to(end); + if (string.length() > 1 && string.startsWith("0")) { + throw new IntLiteralCannotHaveLeadingZeroesError(source); + } else if (string.length() > 2 && string.startsWith("-0")) { + throw new IntLiteralCannotHaveLeadingZeroesError(source); + } + return new UntypedIntLiteralNode(value, source); } diff --git a/src/test/java/org/shedlang/compiler/parser/ParserIntLiteralTests.java b/src/test/java/org/shedlang/compiler/parser/ParserIntLiteralTests.java index bc0dcad9..f4865e1c 100644 --- a/src/test/java/org/shedlang/compiler/parser/ParserIntLiteralTests.java +++ b/src/test/java/org/shedlang/compiler/parser/ParserIntLiteralTests.java @@ -2,13 +2,13 @@ package org.shedlang.compiler.parser; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.shedlang.compiler.ast.untyped.UntypedNodeMatchers.isUntypedIntLiteralNode; import static org.shedlang.compiler.parser.ParserTesting.parseString; import static org.zwobble.precisely.AssertThat.assertThat; public class ParserIntLiteralTests { // TODO: forbid negative zero? - // TODO: forbid leading zeroes? @Test public void canParseZero() { @@ -54,4 +54,24 @@ public class ParserIntLiteralTests { assertThat(node, isUntypedIntLiteralNode(-723)); } + + @Test + public void leadingZeroesOnPositiveNumberAreForbidden() { + var source = "01"; + + assertThrows( + IntLiteralCannotHaveLeadingZeroesError.class, + () -> parseString(source, Parser::parseTopLevelExpression) + ); + } + + @Test + public void leadingZeroesOnNegativeNumberAreForbidden() { + var source = "-01"; + + assertThrows( + IntLiteralCannotHaveLeadingZeroesError.class, + () -> parseString(source, Parser::parseTopLevelExpression) + ); + } } |
