Skip to content

Commit

Permalink
impl binary numbers
Browse files Browse the repository at this point in the history
  • Loading branch information
omdxp committed Feb 17, 2024
1 parent 4792d1a commit 7e328df
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
36 changes: 35 additions & 1 deletion lexer.c
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ static char assert_next_char(char c)
{
char next_c = nextc();
assert(c == next_c);
return nextc;
return next_c;
}

static struct pos
Expand Down Expand Up @@ -477,19 +477,52 @@ token_make_special_number_hexadecimal()
return token_make_number_for_value(number);
}

void lexer_validate_binary_string(const char *str)
{
size_t len = strlen(str);
for (int i = 0; i < len; i++)
{
if (str[i] != '0' && str[i] != '1')
{
compiler_error(lex_process->compiler, "Not valid binary number");
}
}
}

struct token *token_make_special_number_binary()
{
nextc(); // skip 'b'

unsigned long number = 0;
const char *number_str = read_number_str();
lexer_validate_binary_string(number_str);
number = strtol(number_str, 0, 2);
return token_make_number_for_value(number);
}

struct token *
token_make_special_number()
{
struct token *token = NULL;
struct token *last_token = lexer_last_token();

// check if it is a special number or any other identifier (.e.g x3)
if (!last_token || !(last_token->type == TOKEN_TYPE_NUMBER && last_token->llnum == 0))
{
return token_make_identifier_or_keyword();
}

lexer_pop_token(); // poping off the first 0

char c = peekc();
if (c == 'x')
{
token = token_make_special_number_hexadecimal();
}
else if (c == 'b')
{
token = token_make_special_number_binary();
}

return token;
}
Expand Down Expand Up @@ -538,6 +571,7 @@ struct token *read_next_token()
token = token_make_symbol();
break;

case 'b':
case 'x': // '0' is already tokenized as a number
token = token_make_special_number();
break;
Expand Down
2 changes: 1 addition & 1 deletion test.c
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@

'a' '\n' '\t'

0xFE12
0xFE12 0b1110011

0 comments on commit 7e328df

Please sign in to comment.