Skip to content

Commit 1d63864

Browse files
committed
Fix #722 (#if: &&, || and ?: do not short-circuit)
A division by zero no longer throws while folding. It gives an error value, that is passed on by the other operators. && || and ?: discard it when the operand is not evaluated. The error is thrown if the error value is still there after folding. Also fold chained ?: from the right, since ?: is right-associative.
1 parent ab23e4a commit 1d63864

2 files changed

Lines changed: 174 additions & 49 deletions

File tree

‎simplecpp.cpp‎

Lines changed: 127 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -1053,6 +1053,40 @@ void simplecpp::TokenList::readfile(Stream &stream, const std::string &filename,
10531053
combineOperators();
10541054
}
10551055

1056+
/*
1057+
* When an operation can't be evaluated (division by zero), its result is an
1058+
* error value. The error is only reported if the error value is used, so an
1059+
* operand that is not evaluated, as in "0 && (1/0)", does not cause an error.
1060+
*/
1061+
static const std::string ERROR_VALUE("#error:");
1062+
1063+
static bool isErrorValue(const simplecpp::Token *tok)
1064+
{
1065+
return tok && tok->str().compare(0, ERROR_VALUE.size(), ERROR_VALUE) == 0;
1066+
}
1067+
1068+
static bool isValue(const simplecpp::Token *tok)
1069+
{
1070+
return tok && (tok->number || isErrorValue(tok));
1071+
}
1072+
1073+
/**
1074+
* If one operand of the binary operator tok is an error value then
1075+
* "lhs op rhs" is replaced by that error value.
1076+
* @return the error value token, or nullptr
1077+
*/
1078+
static simplecpp::Token *foldErrorValue(simplecpp::TokenList &tokens, simplecpp::Token *tok)
1079+
{
1080+
simplecpp::Token * const lhs = tok->previous;
1081+
if (!isErrorValue(lhs) && !isErrorValue(tok->next))
1082+
return nullptr;
1083+
if (!isErrorValue(lhs))
1084+
lhs->setstr(tok->next->str());
1085+
tokens.deleteToken(tok->next);
1086+
tokens.deleteToken(tok);
1087+
return lhs;
1088+
}
1089+
10561090
void simplecpp::TokenList::constFold()
10571091
{
10581092
while (cfront()) {
@@ -1086,6 +1120,11 @@ void simplecpp::TokenList::constFold()
10861120
deleteToken(tok->previous);
10871121
deleteToken(tok->next);
10881122
}
1123+
1124+
for (const Token *tok = cfront(); tok; tok = tok->next) {
1125+
if (isErrorValue(tok))
1126+
throw std::overflow_error(tok->str().substr(ERROR_VALUE.size()));
1127+
}
10891128
}
10901129

10911130
static bool isFloatSuffix(const simplecpp::Token *tok)
@@ -1243,17 +1282,27 @@ void simplecpp::TokenList::constFoldUnaryNotPosNeg(simplecpp::Token *tok)
12431282
else if (isAlternativeUnaryOp(tok, COMPL))
12441283
tok->op = '~';
12451284

1246-
if (tok->op == '!' && tok->next && tok->next->number) {
1285+
if (tok->isOneOf("!~") && isErrorValue(tok->next)) {
1286+
tok->setstr(tok->next->str());
1287+
deleteToken(tok->next);
1288+
} else if (tok->op == '!' && tok->next && tok->next->number) {
12471289
tok->setstr(tok->next->str() == "0" ? "1" : "0");
12481290
deleteToken(tok->next);
12491291
} else if (tok->op == '~' && tok->next && tok->next->number) {
12501292
tok->setstr(toString(~stringToLL(tok->next->str())));
12511293
deleteToken(tok->next);
12521294
} else {
1253-
if (tok->previous && (tok->previous->number || tok->previous->name))
1295+
if (tok->previous && (isValue(tok->previous) || tok->previous->name))
1296+
continue;
1297+
if (!isValue(tok->next))
12541298
continue;
1255-
if (!tok->next || !tok->next->number)
1299+
if (isErrorValue(tok->next)) {
1300+
if (tok->isOneOf("+-")) {
1301+
tok->setstr(tok->next->str());
1302+
deleteToken(tok->next);
1303+
}
12561304
continue;
1305+
}
12571306
switch (tok->op) {
12581307
case '+':
12591308
tok->setstr(tok->next->str());
@@ -1271,32 +1320,33 @@ void simplecpp::TokenList::constFoldUnaryNotPosNeg(simplecpp::Token *tok)
12711320
void simplecpp::TokenList::constFoldMulDivRem(Token *tok)
12721321
{
12731322
for (; tok && tok->op != ')'; tok = tok->next) {
1274-
if (!tok->previous || !tok->previous->number)
1323+
if (!isValue(tok->previous) || !isValue(tok->next))
12751324
continue;
1276-
if (!tok->next || !tok->next->number)
1325+
if (!tok->isOneOf("*/%"))
12771326
continue;
1327+
if (Token * const errorValue = foldErrorValue(*this, tok)) {
1328+
tok = errorValue;
1329+
continue;
1330+
}
12781331

1279-
long long result;
1332+
std::string result;
12801333
if (tok->op == '*') {
1281-
result = (stringToLL(tok->previous->str()) * stringToLL(tok->next->str()));
1282-
}
1283-
else if (tok->op == '/' || tok->op == '%') {
1334+
result = toString(stringToLL(tok->previous->str()) * stringToLL(tok->next->str()));
1335+
} else {
12841336
const long long rhs = stringToLL(tok->next->str());
1285-
if (rhs == 0)
1286-
throw std::overflow_error("division/modulo by zero");
12871337
const long long lhs = stringToLL(tok->previous->str());
1288-
if (rhs == -1 && lhs == std::numeric_limits<long long>::min())
1289-
throw std::overflow_error("division overflow");
1290-
if (tok->op == '/')
1291-
result = (lhs / rhs);
1338+
if (rhs == 0)
1339+
result = ERROR_VALUE + "division/modulo by zero";
1340+
else if (rhs == -1 && lhs == std::numeric_limits<long long>::min())
1341+
result = ERROR_VALUE + "division overflow";
1342+
else if (tok->op == '/')
1343+
result = toString(lhs / rhs);
12921344
else
1293-
result = (lhs % rhs);
1294-
} else {
1295-
continue;
1345+
result = toString(lhs % rhs);
12961346
}
12971347

12981348
tok = tok->previous;
1299-
tok->setstr(toString(result));
1349+
tok->setstr(result);
13001350
deleteToken(tok->next);
13011351
deleteToken(tok->next);
13021352
}
@@ -1305,10 +1355,14 @@ void simplecpp::TokenList::constFoldMulDivRem(Token *tok)
13051355
void simplecpp::TokenList::constFoldAddSub(Token *tok)
13061356
{
13071357
for (; tok && tok->op != ')'; tok = tok->next) {
1308-
if (!tok->previous || !tok->previous->number)
1358+
if (!isValue(tok->previous) || !isValue(tok->next))
13091359
continue;
1310-
if (!tok->next || !tok->next->number)
1360+
if (!tok->isOneOf("+-"))
13111361
continue;
1362+
if (Token * const errorValue = foldErrorValue(*this, tok)) {
1363+
tok = errorValue;
1364+
continue;
1365+
}
13121366

13131367
long long result;
13141368
if (tok->op == '+')
@@ -1328,10 +1382,14 @@ void simplecpp::TokenList::constFoldAddSub(Token *tok)
13281382
void simplecpp::TokenList::constFoldShift(Token *tok)
13291383
{
13301384
for (; tok && tok->op != ')'; tok = tok->next) {
1331-
if (!tok->previous || !tok->previous->number)
1385+
if (!isValue(tok->previous) || !isValue(tok->next))
1386+
continue;
1387+
if (tok->str() != "<<" && tok->str() != ">>")
13321388
continue;
1333-
if (!tok->next || !tok->next->number)
1389+
if (Token * const errorValue = foldErrorValue(*this, tok)) {
1390+
tok = errorValue;
13341391
continue;
1392+
}
13351393

13361394
long long result;
13371395
if (tok->str() == "<<")
@@ -1355,12 +1413,14 @@ void simplecpp::TokenList::constFoldComparison(Token *tok)
13551413
if (isAlternativeBinaryOp(tok,NOTEQ))
13561414
tok->setstr("!=");
13571415

1358-
if (!tok->startsWithOneOf("<>=!"))
1416+
if (!tok->isOneOf("<>") && tok->str() != "<=" && tok->str() != ">=" && tok->str() != "==" && tok->str() != "!=")
13591417
continue;
1360-
if (!tok->previous || !tok->previous->number)
1418+
if (!isValue(tok->previous) || !isValue(tok->next))
13611419
continue;
1362-
if (!tok->next || !tok->next->number)
1420+
if (Token * const errorValue = foldErrorValue(*this, tok)) {
1421+
tok = errorValue;
13631422
continue;
1423+
}
13641424

13651425
int result;
13661426
if (tok->str() == "==")
@@ -1400,10 +1460,12 @@ void simplecpp::TokenList::constFoldBitwise(Token *tok)
14001460
for (tok = tok1; tok && tok->op != ')'; tok = tok->next) {
14011461
if (tok->op != *op && !isAlternativeBinaryOp(tok, *alternativeOp))
14021462
continue;
1403-
if (!tok->previous || !tok->previous->number)
1463+
if (!isValue(tok->previous) || !isValue(tok->next))
14041464
continue;
1405-
if (!tok->next || !tok->next->number)
1465+
if (Token * const errorValue = foldErrorValue(*this, tok)) {
1466+
tok = errorValue;
14061467
continue;
1468+
}
14071469
long long result;
14081470
if (*op == '&')
14091471
result = (stringToLL(tok->previous->str()) & stringToLL(tok->next->str()));
@@ -1436,19 +1498,24 @@ void simplecpp::TokenList::constFoldLogicalOp(Token *tok)
14361498
for (Token *t = tok; t && t->op != ')'; t = t->next) {
14371499
if (t->str() != op)
14381500
continue;
1439-
if (!t->previous || !t->previous->number)
1440-
continue;
1441-
if (!t->next || !t->next->number)
1501+
if (!isValue(t->previous) || !isValue(t->next))
14421502
continue;
14431503

1444-
int result;
1445-
if (t->str() == "||")
1446-
result = (stringToLL(t->previous->str()) || stringToLL(t->next->str()));
1447-
else /*if (t->str() == "&&")*/
1448-
result = (stringToLL(t->previous->str()) && stringToLL(t->next->str()));
1504+
// the right operand is not evaluated if the left operand decides the result
1505+
std::string result;
1506+
if (isErrorValue(t->previous))
1507+
result = t->previous->str();
1508+
else if (t->str() == "||" && stringToLL(t->previous->str()) != 0)
1509+
result = "1";
1510+
else if (t->str() == "&&" && stringToLL(t->previous->str()) == 0)
1511+
result = "0";
1512+
else if (isErrorValue(t->next))
1513+
result = t->next->str();
1514+
else
1515+
result = (stringToLL(t->next->str()) != 0) ? "1" : "0";
14491516

14501517
t = t->previous;
1451-
t->setstr(toString(result));
1518+
t->setstr(result);
14521519
deleteToken(t->next);
14531520
deleteToken(t->next);
14541521
}
@@ -1457,30 +1524,41 @@ void simplecpp::TokenList::constFoldLogicalOp(Token *tok)
14571524

14581525
void simplecpp::TokenList::constFoldQuestionOp(Token *&tok1)
14591526
{
1460-
bool gotoTok1 = false;
1461-
// NOLINTNEXTLINE(misc-const-correctness) - technically correct but used to access non-const data
1462-
for (Token *tok = tok1; tok && tok->op != ')'; tok = gotoTok1 ? tok1 : tok->next) {
1463-
gotoTok1 = false;
1464-
if (tok->str() != "?")
1465-
continue;
1527+
// ?: is right-associative, "a ? b : c ? d : e" means "a ? b : (c ? d : e)",
1528+
// so the last ? is folded first
1529+
for (;;) {
1530+
const Token *tok = nullptr;
1531+
for (const Token *t = tok1; t && t->op != ')'; t = t->next) {
1532+
if (t->str() == "?")
1533+
tok = t;
1534+
}
1535+
if (!tok)
1536+
return;
14661537
if (!tok->previous || !tok->next || !tok->next->next)
14671538
throw std::runtime_error("invalid expression");
1468-
if (!tok->previous->number)
1469-
continue;
1470-
if (tok->next->next->op != ':')
1471-
continue;
14721539
Token * const condTok = tok->previous;
14731540
Token * const trueTok = tok->next;
14741541
Token * const falseTok = trueTok->next->next;
14751542
if (!falseTok)
14761543
throw std::runtime_error("invalid expression");
1544+
if (trueTok->next->op != ':')
1545+
return;
1546+
if (!isValue(condTok) || !isValue(trueTok) || !isValue(falseTok))
1547+
return;
1548+
if (isErrorValue(condTok)) {
1549+
// "error ? x : y" => error
1550+
deleteToken(condTok->next); // ?
1551+
deleteToken(trueTok->next); // :
1552+
deleteToken(trueTok);
1553+
deleteToken(falseTok);
1554+
continue;
1555+
}
14771556
if (condTok == tok1)
14781557
tok1 = (condTok->str() != "0" ? trueTok : falseTok);
14791558
deleteToken(condTok->next); // ?
14801559
deleteToken(trueTok->next); // :
1481-
deleteToken(condTok->str() == "0" ? trueTok : falseTok);
1560+
deleteToken(condTok->str() == "0" ? trueTok : falseTok); // the operand that is not evaluated
14821561
deleteToken(condTok);
1483-
gotoTok1 = true;
14841562
}
14851563
}
14861564

‎test.cpp‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -620,6 +620,22 @@ static void constFold()
620620
ASSERT_EQUALS("1", testConstFold("010==8"));
621621
ASSERT_EQUALS("exception", testConstFold("!1 ? 2 :"));
622622
ASSERT_EQUALS("exception", testConstFold("?2:3"));
623+
ASSERT_EQUALS("0", testConstFold("0 && 1/0"));
624+
ASSERT_EQUALS("1", testConstFold("1 || 1/0"));
625+
ASSERT_EQUALS("2", testConstFold("1 ? 2 : 1/0"));
626+
ASSERT_EQUALS("exception", testConstFold("1 && 1/0"));
627+
ASSERT_EQUALS("exception", testConstFold("1/0 && 0"));
628+
ASSERT_EQUALS("exception", testConstFold("(1/0) ? 1 : 2"));
629+
ASSERT_EQUALS("exception", testConstFold("-(1/0) + 1"));
630+
// ?: is right-associative
631+
ASSERT_EQUALS("1", testConstFold("1 ? 1 : 0 ? 2 : 3"));
632+
ASSERT_EQUALS("3", testConstFold("0 ? 1 : 0 ? 2 : 3"));
633+
ASSERT_EQUALS("2", testConstFold("1 ? 2 : 3 ? 4 : 5 ? 6 : 7"));
634+
ASSERT_EQUALS("7", testConstFold("0 ? 2 : 0 ? 4 : 0 ? 6 : 7"));
635+
ASSERT_EQUALS("6", testConstFold("1 ? 0 ? 5 : 6 : 7"));
636+
ASSERT_EQUALS("2", testConstFold("(1 ? 1 : 0) ? 2 : 3"));
637+
ASSERT_EQUALS("1", testConstFold("1 ? 1 : (1/0) ? 2 : 3"));
638+
ASSERT_EQUALS("exception", testConstFold("0 ? 1 : (1/0) ? 2 : 3"));
623639
}
624640

625641
#ifdef __CYGWIN__
@@ -2759,6 +2775,36 @@ static void ifdiv0()
27592775
ASSERT_EQUALS("", preprocess(code));
27602776
}
27612777

2778+
static void ifShortCircuit()
2779+
{
2780+
// operands that are not evaluated must not cause errors
2781+
const char * const exprs[] = {
2782+
"0 && (1/0)",
2783+
"!(1 || (1/0))",
2784+
"0 ? 1/0 : 0",
2785+
"1 ? 0 : 1/0",
2786+
"0 && 1 % 0 && 1",
2787+
"(1 || 1/0) && !(0 && 1/0) && 0",
2788+
"0 && (2 + (3 * (1/0)))",
2789+
"0 && -(1/0)"
2790+
};
2791+
for (const char * const expr : exprs) {
2792+
const std::string code = std::string("#if ") + expr + "\n"
2793+
"1\n"
2794+
"#else\n"
2795+
"2\n"
2796+
"#endif\n";
2797+
simplecpp::OutputList outputList;
2798+
ASSERT_EQUALS("\n\n\n2", preprocess(code.c_str(), &outputList));
2799+
ASSERT_EQUALS("", toString(outputList));
2800+
}
2801+
2802+
// evaluated operands are still checked
2803+
simplecpp::OutputList outputList;
2804+
ASSERT_EQUALS("", preprocess("#if 1 && (1/0)\n#endif\n", &outputList));
2805+
ASSERT_EQUALS("file0,1,syntax_error,failed to evaluate #if condition, division/modulo by zero\n", toString(outputList));
2806+
}
2807+
27622808
static void ifTrueFalse()
27632809
{
27642810
const char code[] = "#if true && !false\n"
@@ -4991,6 +5037,7 @@ static void runTests(int argc, char **argv, Input input)
49915037
TEST_CASE(ifif);
49925038
TEST_CASE(ifoverflow);
49935039
TEST_CASE(ifdiv0);
5040+
TEST_CASE(ifShortCircuit);
49945041
TEST_CASE(ifTrueFalse);
49955042
TEST_CASE(ifalt); // using "and", "or", etc
49965043
TEST_CASE(ifexpr);

0 commit comments

Comments
 (0)