Skip to content

Commit

Permalink
Fix issue when parsing hexadecimal and binary literals. (#242)
Browse files Browse the repository at this point in the history
Fix #241
  • Loading branch information
metoule authored Jun 23, 2022
1 parent b502ef3 commit 42132ad
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
7 changes: 7 additions & 0 deletions src/DynamicExpresso.Core/Parsing/Parser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -893,6 +893,9 @@ private Expression ParseIntegerLiteral()
else if (text.StartsWith("0b") || text.StartsWith("0B"))
{
var binary = text.Substring(2);
if (string.IsNullOrEmpty(binary))
throw CreateParseException(_token.pos, ErrorMessages.InvalidIntegerLiteral, text);

try
{
value = Convert.ToUInt64(binary, 2);
Expand Down Expand Up @@ -3073,6 +3076,8 @@ private void NextToken()
{
NextChar();
} while (char.IsDigit(_parseChar) || (_parseChar >= 'a' && _parseChar <= 'f') || (_parseChar >= 'A' && _parseChar <= 'F'));

PreviousChar();
}
else if (_parseChar == 'b' || _parseChar == 'B')
{
Expand All @@ -3081,6 +3086,8 @@ private void NextToken()
{
NextChar();
} while (_parseChar == '0' || _parseChar == '1');

PreviousChar();
}
else
{
Expand Down
7 changes: 5 additions & 2 deletions test/DynamicExpresso.UnitTest/LiteralsTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -360,8 +360,9 @@ public void Binary_Literals()

Assert.AreEqual(0b101ul, target.Eval("0b101ul"));
Assert.AreEqual(0B1111L, target.Eval("0B1111l"));
Assert.AreEqual(6, target.Eval("4 + 0b10"));
Assert.AreEqual(8, target.Eval("4+0b10+2"));

Assert.Throws<ParseException>(() => target.Eval("0b"));
Assert.Throws<ParseException>(() => target.Eval("0b12"));
Assert.Throws<ParseException>(() => target.Eval("0b10.10"));
Assert.Throws<ParseException>(() => target.Eval("0b10d"));
Expand All @@ -375,8 +376,10 @@ public void Hexadecimal_Literals()

Assert.AreEqual(0x012EFul, target.Eval("0x012EFul"));
Assert.AreEqual(0XAAe2L, target.Eval("0XAAe2l"));
Assert.AreEqual(165, target.Eval("4 + 0xA1"));
Assert.AreEqual(170, target.Eval("4+0xA1+5"));
Assert.AreEqual(170, target.Eval("4+(0xA1)+5"));

Assert.Throws<ParseException>(() => target.Eval("0x"));
Assert.Throws<ParseException>(() => target.Eval("0x1Gl"));
Assert.Throws<ParseException>(() => target.Eval("0x12.12"));
}
Expand Down

0 comments on commit 42132ad

Please sign in to comment.