From c4615e0363baf5fb90257cdc0009485a22396ce2 Mon Sep 17 00:00:00 2001 From: Josh Holtrop Date: Wed, 30 May 2018 21:18:03 -0400 Subject: [PATCH] add binary literals --- src/parser/parser.l | 29 +++++++++++++++++++++++++++++ tests/t005.cxl | 8 ++++++++ tests/t005.x | 1 + 3 files changed, 38 insertions(+) create mode 100644 tests/t005.cxl create mode 100644 tests/t005.x diff --git a/src/parser/parser.l b/src/parser/parser.l index 235767b..7060c96 100644 --- a/src/parser/parser.l +++ b/src/parser/parser.l @@ -22,6 +22,7 @@ static std::string * build_string = nullptr; static size_t current_line = 1u; static std::string * current_file = nullptr; void handle_loc(const char * input); +static const char hex_digit[] = "0123456789ABCDEF"; %} @@ -136,6 +137,34 @@ L?'\\x[0-9A-Fa-f]{2}' return CHAR_CONST; L?'\\[0-7]{1,3}' return CHAR_CONST; [0-9]+[uU]?[lL]?[lL]? return INT_CONST; 0[xX][0-9a-fA-F]+([uU][lL]?[lL]?)? return INT_CONST; +0[bB][01]+([uU][lL]?[lL]?)? { + size_t end = 3u; + while (yytext[end] == '0' || yytext[end] == '1') + { + end++; + } + std::string * hex_str = new std::string("0x"); + size_t n_bits_to_nibble = ((end - 2u + 3u) % 4u) + 1u; + int nibble_value = 0; + for (size_t i = 2u; i < end; i++) + { + nibble_value <<= 1u; + nibble_value += yytext[i] - '0'; + if (n_bits_to_nibble == 1) + { + *hex_str += hex_digit[nibble_value]; + n_bits_to_nibble = 4; + nibble_value = 0; + } + else + { + n_bits_to_nibble--; + } + } + *hex_str += yytext[end]; + (*yylval)->token.text = hex_str; + return INT_CONST; +} ([0-9]+\.[0-9]*|\.[0-9]+)([eE][-+]?[0-9]+)?[fFlL]? return FLOAT_CONST; L?\" { diff --git a/tests/t005.cxl b/tests/t005.cxl new file mode 100644 index 0000000..2b04a13 --- /dev/null +++ b/tests/t005.cxl @@ -0,0 +1,8 @@ +#include + +int main(int argc, char * argv[]) +{ + printf("%d;", 0b01u | 0b10u); + printf("%d;", 0x100 - 0b100000000); + printf("\n"); +} diff --git a/tests/t005.x b/tests/t005.x new file mode 100644 index 0000000..edd8d81 --- /dev/null +++ b/tests/t005.x @@ -0,0 +1 @@ +3;0;