Visitar URL original
fixed #51 - invalid ternary expression · dummyunit/simplecpp@6767e6f · GitHub
Skip to content

Commit 6767e6f

Browse files
committed
fixed cppcheck-opensource#51 - invalid ternary expression
1 parent a8e68fd commit 6767e6f

2 files changed

Lines changed: 13 additions & 5 deletions

File tree

‎simplecpp.cpp‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -814,15 +814,17 @@ void simplecpp::TokenList::constFoldQuestionOp(Token **tok1) {
814814
gotoTok1 = false;
815815
if (tok->str != "?")
816816
continue;
817-
if (!tok->previous || !tok->previous->number)
818-
continue;
819-
if (!tok->next)
817+
if (!tok->previous || !tok->next || !tok->next->next)
818+
throw std::runtime_error("invalid expression");
819+
if (!tok->previous->number)
820820
continue;
821-
if (!tok->next->next || tok->next->next->op != ':')
821+
if (tok->next->next->op != ':')
822822
continue;
823823
Token * const condTok = tok->previous;
824824
Token * const trueTok = tok->next;
825825
Token * const falseTok = trueTok->next->next;
826+
if (!falseTok)
827+
throw std::runtime_error("invalid expression");
826828
if (condTok == *tok1)
827829
*tok1 = (condTok->str != "0" ? trueTok : falseTok);
828830
deleteToken(condTok->next); // ?

‎test.cpp‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,11 @@ static std::string testConstFold(const char code[]) {
124124
std::istringstream istr(code);
125125
std::vector<std::string> files;
126126
simplecpp::TokenList expr(istr, files);
127-
expr.constFold();
127+
try {
128+
expr.constFold();
129+
} catch (std::exception &) {
130+
return "exception";
131+
}
128132
return expr.stringify();
129133
}
130134

@@ -173,6 +177,8 @@ static void constFold() {
173177
ASSERT_EQUALS("29", testConstFold("13 ^ 16"));
174178
ASSERT_EQUALS("25", testConstFold("24 | 1"));
175179
ASSERT_EQUALS("2", testConstFold("1?2:3"));
180+
ASSERT_EQUALS("exception", testConstFold("!1 ? 2 :"));
181+
ASSERT_EQUALS("exception", testConstFold("?2:3"));
176182
}
177183

178184
void define1() {

0 commit comments

Comments
 (0)