Skip to content

Commit

Permalink
Fix number parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
NeilKleistGao committed Jan 18, 2025
1 parent a9cc07f commit 521444b
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 7 deletions.
28 changes: 23 additions & 5 deletions Src/Runtime/Interpreter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,31 @@ private Literal<Value, Environment> AllocateLiteral(string text) {
else if (text == "false") {
// TODO: bool
}
else if (text.Contains(".") || text.Contains("e") || text.Contains("E")) {
return new EvalNumberLit(Convert.ToDouble(text));
}
else {
int i; double d;
if (int.TryParse(text, out i)) {
return new EvalIntLit(i);
text = text.ToLower();
int flag = 1;
if (text.StartsWith("-")) {
flag = -1;
text = text[1..];
}
else if (text.StartsWith("+")) {
text = text[1..];
}

if (text.StartsWith("0x")) {
return new EvalIntLit(flag * Convert.ToInt32(text[2..], 16));
}
else if (double.TryParse(text, out d)) {
return new EvalNumberLit(d);
else if (text.StartsWith("0b")) {
return new EvalIntLit(flag * Convert.ToInt32(text[2..], 2));
}
else if (text.StartsWith("0")) {
return new EvalIntLit(flag * Convert.ToInt32(text[1..], 8));
}
else {
return new EvalIntLit(flag * Convert.ToInt32(text));
}
}

Expand Down
5 changes: 3 additions & 2 deletions Src/Utils/Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,9 @@ public static bool IsDelimiter(this char value) {
}

public static bool IsDigitComponent(this char value) {
return char.IsDigit(value) || value == '.' || char.ToLower(value) == 'e' || value == '_' ||
char.ToLower(value) == 'x' || char.ToLower(value) == 'b' || char.ToLower(value) == 'p';
return char.IsDigit(value) || value == '.' || value == '+' || value == '-' || char.ToLower(value) == 'e' ||
char.ToLower(value) == 'x' || char.ToLower(value) == 'b' || char.ToLower(value) == 'a' || char.ToLower(value) == 'b' ||
char.ToLower(value) == 'c' || char.ToLower(value) == 'd' || char.ToLower(value) == 'f';
}
}

Expand Down
40 changes: 40 additions & 0 deletions Tests/Mario/literals.mario
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,43 @@
1e5
;;|| --- Result --- ||
;;|| Res: 100000


-12
;;|| --- Result --- ||
;;|| Res: -12


1e-1
;;|| --- Result --- ||
;;|| Res: 0.1


2E2
;;|| --- Result --- ||
;;|| Res: 200


0x12AB
;;|| --- Result --- ||
;;|| Res: 4779


-0x55
;;|| --- Result --- ||
;;|| Res: -85


0b000111
;;|| --- Result --- ||
;;|| Res: 7


0123
;;|| --- Result --- ||
;;|| Res: 83


+0xff
;;|| --- Result --- ||
;;|| Res: 255

0 comments on commit 521444b

Please sign in to comment.