Skip to content

Commit a62b8ee

Browse files
authored
Fix #727 (#if: two unary operators in a row silently evaluate to false) (#730)
1 parent 9f5687e commit a62b8ee

2 files changed

Lines changed: 43 additions & 3 deletions

File tree

‎simplecpp.cpp‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1291,9 +1291,16 @@ void simplecpp::TokenList::combineOperators()
12911291

12921292
static const std::string COMPL("compl");
12931293
static const std::string NOT("not");
1294-
void simplecpp::TokenList::constFoldUnaryNotPosNeg(simplecpp::Token *tok)
1294+
void simplecpp::TokenList::constFoldUnaryNotPosNeg(simplecpp::Token *tok1)
12951295
{
1296-
for (; tok && tok->op != ')'; tok = tok->next) {
1296+
if (!tok1 || tok1->op == ')')
1297+
return;
1298+
Token *last = tok1;
1299+
while (last->next && last->next->op != ')')
1300+
last = last->next;
1301+
1302+
// unary operators are right-associative, "!-0" means "!(-0)", so they are folded from right to left
1303+
for (Token *tok = last; tok; tok = (tok == tok1) ? nullptr : tok->previous) {
12971304
// "not" might be !
12981305
if (isAlternativeUnaryOp(tok, NOT))
12991306
tok->op = '!';
@@ -1328,7 +1335,10 @@ void simplecpp::TokenList::constFoldUnaryNotPosNeg(simplecpp::Token *tok)
13281335
deleteToken(tok->next);
13291336
break;
13301337
case '-':
1331-
tok->setstr(tok->op + tok->next->str());
1338+
if (tok->next->str()[0] == '-')
1339+
tok->setstr(tok->next->str().substr(1));
1340+
else
1341+
tok->setstr(tok->op + tok->next->str());
13321342
deleteToken(tok->next);
13331343
break;
13341344
}

‎test.cpp‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2913,6 +2913,35 @@ static void ifZeroCondition()
29132913
ASSERT_EQUALS("file0,1,syntax_error,failed to evaluate #if condition, division/modulo by zero\n", toString(outputList));
29142914
}
29152915

2916+
static void ifUnaryOperators()
2917+
{
2918+
// unary operators in a row
2919+
const char * const exprs[] = {
2920+
"!!1",
2921+
"!-0",
2922+
"!+0",
2923+
"!~-1",
2924+
"- -1",
2925+
"-!0",
2926+
"-~0",
2927+
"~!0",
2928+
"+-1 == -1",
2929+
"1 && !-0",
2930+
"!-X",
2931+
"-(-1) == 1",
2932+
"- - -1 == -1",
2933+
"1 - -1 == 2"
2934+
};
2935+
for (const char * const expr : exprs) {
2936+
const std::string code = std::string("#if ") + expr + "\n"
2937+
"1\n"
2938+
"#else\n"
2939+
"2\n"
2940+
"#endif\n";
2941+
ASSERT_EQUALS("\n1", preprocess(code.c_str()));
2942+
}
2943+
}
2944+
29162945
static void ifTrueFalse()
29172946
{
29182947
const char code[] = "#if true && !false\n"
@@ -5150,6 +5179,7 @@ static void runTests(int argc, char **argv, Input input)
51505179
TEST_CASE(ifdiv0);
51515180
TEST_CASE(ifShortCircuit);
51525181
TEST_CASE(ifZeroCondition);
5182+
TEST_CASE(ifUnaryOperators);
51535183
TEST_CASE(ifTrueFalse);
51545184
TEST_CASE(ifalt); // using "and", "or", etc
51555185
TEST_CASE(ifexpr);

0 commit comments

Comments
 (0)