Skip to content

Commit b00c8e7

Browse files
o-bolshakovdanmar
authored andcommitted
Added octal numbers recognition (danmar#172)
* Added octal numbers recognition * More strict octal numbers recognition. constFold() is extended to check octals.
1 parent 229d41f commit b00c8e7

2 files changed

Lines changed: 16 additions & 3 deletions

File tree

simplecpp.cpp

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,11 @@ static bool isHex(const std::string &s)
4545
return s.size()>2 && (s.compare(0,2,"0x")==0 || s.compare(0,2,"0X")==0);
4646
}
4747

48+
static bool isOct(const std::string &s)
49+
{
50+
return s.size()>1 && (s[0]=='0') && (s[1] >= '0') && (s[1] < '8');
51+
}
52+
4853

4954
static const simplecpp::TokenString DEFINE("define");
5055
static const simplecpp::TokenString UNDEF("undef");
@@ -76,9 +81,12 @@ static long long stringToLL(const std::string &s)
7681
{
7782
long long ret;
7883
const bool hex = isHex(s);
79-
std::istringstream istr(hex ? s.substr(2) : s);
84+
const bool oct = isOct(s);
85+
std::istringstream istr(hex ? s.substr(2) : oct ? s.substr(1) : s);
8086
if (hex)
8187
istr >> std::hex;
88+
else if (oct)
89+
istr >> std::oct;
8290
istr >> ret;
8391
return ret;
8492
}
@@ -87,9 +95,12 @@ static unsigned long long stringToULL(const std::string &s)
8795
{
8896
unsigned long long ret;
8997
const bool hex = isHex(s);
90-
std::istringstream istr(hex ? s.substr(2) : s);
98+
const bool oct = isOct(s);
99+
std::istringstream istr(hex ? s.substr(2) : oct ? s.substr(1) : s);
91100
if (hex)
92101
istr >> std::hex;
102+
else if (oct)
103+
istr >> std::oct;
93104
istr >> ret;
94105
return ret;
95106
}
@@ -765,7 +776,7 @@ void simplecpp::TokenList::combineOperators()
765776
}
766777
// match: [0-9.]+E [+-] [0-9]+
767778
const char lastChar = tok->str()[tok->str().size() - 1];
768-
if (tok->number && !isHex(tok->str()) && (lastChar == 'E' || lastChar == 'e') && tok->next && tok->next->isOneOf("+-") && tok->next->next && tok->next->next->number) {
779+
if (tok->number && !isHex(tok->str()) && !isOct(tok->str()) && (lastChar == 'E' || lastChar == 'e') && tok->next && tok->next->isOneOf("+-") && tok->next->next && tok->next->next->number) {
769780
tok->setstr(tok->str() + tok->next->op + tok->next->next->str());
770781
deleteToken(tok->next);
771782
deleteToken(tok->next);

test.cpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,8 @@ static void constFold()
204204
ASSERT_EQUALS("29", testConstFold("13 ^ 16"));
205205
ASSERT_EQUALS("25", testConstFold("24 | 1"));
206206
ASSERT_EQUALS("2", testConstFold("1?2:3"));
207+
ASSERT_EQUALS("24", testConstFold("010+020"));
208+
ASSERT_EQUALS("1", testConstFold("010==8"));
207209
ASSERT_EQUALS("exception", testConstFold("!1 ? 2 :"));
208210
ASSERT_EQUALS("exception", testConstFold("?2:3"));
209211
}

0 commit comments

Comments
 (0)