Skip to content

Commit

Permalink
(parser) Support octal literals (#220)
Browse files Browse the repository at this point in the history
Last step towards closing #69, building on top of #217 and #219.
  • Loading branch information
perlun authored Oct 13, 2021
1 parent 80c0bf5 commit aac5570
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/Perlang.Parser/Scanner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -307,14 +307,18 @@ private void Number()

char currentChar = Char.ToLower(Peek());

if (currentChar is 'b' or 'x')
if (currentChar is 'b' or 'o' or 'x')
{
switch (currentChar)
{
case 'b':
numberBase = Base.BINARY;
break;

case 'o':
numberBase = Base.OCTAL;
break;

case 'x':
numberStyles = NumberStyles.HexNumber;
numberBase = Base.HEXADECIMAL;
Expand Down Expand Up @@ -367,6 +371,9 @@ private void Number()
Base.BINARY =>
Convert.ToUInt64(numberCharacters, 2),

Base.OCTAL =>
Convert.ToUInt64(numberCharacters, 8),

Base.HEXADECIMAL =>
// Quoting from
// https://docs.microsoft.com/en-us/dotnet/api/system.numerics.biginteger.parse?view=net-5.0#System_Numerics_BigInteger_Parse_System_ReadOnlySpan_System_Char__System_Globalization_NumberStyles_System_IFormatProvider_
Expand Down Expand Up @@ -523,6 +530,7 @@ private void AddToken(TokenType type, object literal = null)
private enum Base
{
BINARY = 2,
OCTAL = 8,
DECIMAL = 10,
HEXADECIMAL = 16,
}
Expand Down
12 changes: 12 additions & 0 deletions src/Perlang.Tests.Integration/Number/NumberTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,18 @@ public void literal_binary()
Assert.Equal(42, result);
}

[Fact]
public void literal_octal()
{
string source = @"
0o755
";

object result = Eval(source);

Assert.Equal(493, result);
}

[Fact]
public void literal_hexadecimal()
{
Expand Down
13 changes: 13 additions & 0 deletions src/Perlang.Tests/Interpreter/Typing/TypeResolverTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,19 @@ public void Resolve_implicitly_typed_var_initialized_from_binary_literal_has_exp
Assert.Equal(typeof(Int32), ((Stmt.Var)singleStatement).TypeReference.ClrType);
}

[Fact]
public void Resolve_implicitly_typed_var_initialized_from_octal_literal_has_expected_ClrType()
{
(Stmt singleStatement, NameResolver resolver) = ScanParseResolveAndTypeResolveSingleStatement(@"
var v = 0o755;
");

// Assert
Assert.IsType<Stmt.Var>(singleStatement);
Assert.True(resolver.Globals.ContainsKey("v"));
Assert.Equal(typeof(Int32), ((Stmt.Var)singleStatement).TypeReference.ClrType);
}

[Fact]
public void Resolve_implicitly_typed_var_initialized_from_hexadecimal_literal_has_expected_ClrType()
{
Expand Down

0 comments on commit aac5570

Please sign in to comment.