Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions simplecpp.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3283,8 +3283,9 @@ static long long evaluate(simplecpp::TokenList &expr, const simplecpp::DUI &dui,
simplifyName(expr, dui);
simplifyNumbers(expr);
expr.constFold();
// TODO: handle invalid expressions
return expr.cfront() && expr.cfront() == expr.cback() && expr.cfront()->number ? stringToLL(expr.cfront()->str()) : 0LL;
if (!expr.cfront() || expr.cfront() != expr.cback() || !expr.cfront()->number)
Comment thread
danmar marked this conversation as resolved.
Resolved
throw std::runtime_error("invalid expression");
return stringToLL(expr.cfront()->str());
}

static const simplecpp::Token *gotoNextLine(const simplecpp::Token *tok)
Expand Down
46 changes: 45 additions & 1 deletion test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1842,7 +1842,8 @@ static void hashEscapeTrailingBackslash()
"#endif\n";
simplecpp::OutputList outputList;
preprocess(code, &outputList);
ASSERT_EQUALS(std::string("file0,2,portability_stringify,") + msg, toString(outputList));
ASSERT_EQUALS(std::string("file0,2,portability_stringify,") + msg +
"file0,2,syntax_error,failed to evaluate #if condition, invalid expression\n", toString(outputList));
}
{
// even number of backslashes is fine
Expand Down Expand Up @@ -2942,6 +2943,48 @@ static void ifUnaryOperators()
}
}

static void ifInvalidExpression()
{
const char * const exprs[] = {
// missing operand
"1 +",
"(1 +)",
"(1 +) + 1",
"* 1",
"(* 1)",
"1 + * 2",
"1 <<",
"(1 ==)",
"1 &",
"(1 &&)",
"|| 1",
"!",
"(!)",
"-",
"~",
"(? 1 : 2)",
"(1 ? 2 :)",
"(1 ? 2 3)",
"(1 ? : 2)",
// missing operator
"1 2",
"(1 2)",
// empty parentheses
"()",
"1 + ()",
// syntax errors are reported also in operands that are not evaluated
"0 && (1 +)"
};
for (const char * const expr : exprs) {
const std::string code = std::string("#if ") + expr + "\n"
"1\n"
"#endif\n";
simplecpp::OutputList outputList;
ASSERT_EQUALS("", preprocess(code.c_str(), &outputList));
ASSERT_EQUALS("file0,1,syntax_error,failed to evaluate #if condition, invalid expression\n", toString(outputList));
}
}

static void ifTrueFalse()
{
const char code[] = "#if true && !false\n"
Expand Down Expand Up @@ -5180,6 +5223,7 @@ static void runTests(int argc, char **argv, Input input)
TEST_CASE(ifShortCircuit);
TEST_CASE(ifZeroCondition);
TEST_CASE(ifUnaryOperators);
TEST_CASE(ifInvalidExpression);
TEST_CASE(ifTrueFalse);
TEST_CASE(ifalt); // using "and", "or", etc
TEST_CASE(ifexpr);
Expand Down
Loading