diff --git a/compiler.c b/compiler.c index afd4a09..1d15a56 100644 --- a/compiler.c +++ b/compiler.c @@ -191,20 +191,23 @@ static void emitConstant(KrkValue value) { } static void number(int canAssign) { - const char * start= parser.previous.start; + const char * start = parser.previous.start; int base = 10; + + /* These special cases for hexadecimal, binary, octal values. */ if (start[0] == '0' && (start[1] == 'x' || start[1] == 'X')) { - base = 10; + base = 16; start += 2; } else if (start[0] == '0' && (start[1] == 'b' || start[1] == 'B')) { base = 2; start += 2; - } else if (start[0] == '0') { + } else if (start[0] == '0' && (start[1] == 'o' || start[1] == 'O')) { base = 8; - start += 1; + start += 2; } + + /* If it wasn't a special base, it may be a floating point value. */ if (base == 10) { - /* See if it's a float */ for (size_t j = 0; j < parser.previous.length; ++j) { if (parser.previous.start[j] == '.') { double value = strtod(start, NULL); @@ -213,6 +216,8 @@ static void number(int canAssign) { } } } + + /* If we got here, it's an integer of some sort. */ int value = strtol(start, NULL, base); emitConstant(INTEGER_VAL(value)); } diff --git a/scanner.c b/scanner.c index 74bc30e..13d16a0 100644 --- a/scanner.c +++ b/scanner.c @@ -127,30 +127,25 @@ static int isDigit(char c) { } static KrkToken number(char c) { - if (c == 0) { - /* Hexadecimal */ + if (c == '0') { if (peek() == 'x' || peek() == 'X') { + /* Hexadecimal */ advance(); - do { - char n = peek(); - if (isDigit(n) || (n >= 'a' && n <= 'f') || (n >= 'A' && n <= 'F')) { - advance(); - continue; - } - } while (0); + while (isDigit(peek()) || (peek() >= 'a' && peek() <= 'f') || + (peek() >= 'A' && peek() <= 'F')) advance(); return makeToken(TOKEN_NUMBER); - } - - /* Binary */ - if (peek() == 'b' || peek() == 'B') { + } else if (peek() == 'b' || peek() == 'B') { + /* Binary */ advance(); while (peek() == '0' || peek() == '1') advance(); return makeToken(TOKEN_NUMBER); + } if (peek() == 'o' || peek() == 'O') { + /* Octal - must be 0o, none of those silly 0123 things */ + advance(); + while (peek() >= '0' && peek() <= '7') advance(); + return makeToken(TOKEN_NUMBER); } - - /* Octal */ - while (peek() >= '0' && peek() <= '7') advance(); - return makeToken(TOKEN_NUMBER); + /* Otherwise, decimal and maybe 0.123 floating */ } /* Decimal */