Clarify calculation: Added warnings for << and >>

This commit is contained in:
Daniel Marjamäki 2011-04-03 22:12:22 +02:00
parent 266d1cc4d3
commit 63acd9bb3e
3 changed files with 15 additions and 10 deletions

View File

@ -86,10 +86,10 @@ void CheckOther::clarifyCalculation()
continue;
// calculation
if (!Token::Match(cond, "[+-*/]"))
if (!Token::Match(cond, "[+-*/]") && !Token::Match(cond, "<<|>>"))
continue;
const char op = cond->str()[0];
const std::string &op = cond->str();
cond = cond->previous();
// skip previous multiplications..
@ -106,28 +106,28 @@ void CheckOther::clarifyCalculation()
}
else if (cond->isName() || cond->isNumber())
{
if (Token::Match(cond->previous(),"return|+|-|,|("))
if (Token::Match(cond->previous(),("return|+|-|,|(|"+op).c_str()))
clarifyCalculationError(cond, op);
}
}
}
}
void CheckOther::clarifyCalculationError(const Token *tok, char op)
void CheckOther::clarifyCalculationError(const Token *tok, const std::string &op)
{
// suspicious calculation
const std::string calc(std::string("'a") + op + "b?c:d'");
const std::string calc("'a" + op + "b?c:d'");
// recommended calculation #1
const std::string s1(std::string("'(a") + op + "b)?c:d'");
const std::string s1("'(a" + op + "b)?c:d'");
// recommended calculation #2
const std::string s2(std::string("'a") + op + "(b?c:d)'");
const std::string s2("'a" + op + "(b?c:d)'");
reportError(tok,
Severity::style,
"clarifyCalculation",
std::string("Clarify calculation precedence for ") + op + " and ?\n" +
"Clarify calculation precedence for " + op + " and ?\n"
"Suspicious calculation. Please use parentheses to clarify the code. "
"The code " + calc + " should be written as either " + s1 + " or " + s2 + ".");
}

View File

@ -97,7 +97,7 @@ public:
/** @brief Clarify calculation for ".. a * b ? .." */
void clarifyCalculation();
void clarifyCalculationError(const Token *tok, char op);
void clarifyCalculationError(const Token *tok, const std::string &op);
/** @brief Suspicious condition (assignment+comparison) */
void clarifyCondition();
@ -269,7 +269,7 @@ public:
c.unassignedVariableError(0, "varname");
c.catchExceptionByValueError(0);
c.memsetZeroBytesError(0, "varname");
c.clarifyCalculationError(0, '+');
c.clarifyCalculationError(0, "+");
c.clarifyConditionError(0);
c.incorrectStringCompareError(0, "substr", "\"Hello World\"", "12");
c.incrementBooleanError(0);

View File

@ -2291,6 +2291,11 @@ private:
" printf(\"%i\", 1 + 1 ? 1 : 2);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Clarify calculation precedence for + and ?\n", errout.str());
check("void f() {\n"
" std::cout << x << 1 ? 2 : 3;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Clarify calculation precedence for << and ?\n", errout.str());
}
// clarify conditions with = and comparison