ID
int64 1
1.09k
| Language
stringclasses 1
value | Repository Name
stringclasses 8
values | File Name
stringlengths 3
35
| File Path in Repository
stringlengths 9
82
| File Path for Unit Test
stringclasses 5
values | Code
stringlengths 17
1.91M
| Unit Test - (Ground Truth)
stringclasses 5
values |
---|---|---|---|---|---|---|---|
901 | cpp | cppcheck | astutils.cpp | lib/astutils.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#include "astutils.h"
#include "config.h"
#include "errortypes.h"
#include "findtoken.h"
#include "infer.h"
#include "library.h"
#include "mathlib.h"
#include "settings.h"
#include "symboldatabase.h"
#include "token.h"
#include "utils.h"
#include "valueflow.h"
#include "valueptr.h"
#include "vfvalue.h"
#include "checkclass.h"
#include <algorithm>
#include <cassert>
#include <cstring>
#include <functional>
#include <initializer_list>
#include <iterator>
#include <list>
#include <set>
#include <type_traits>
#include <unordered_map>
#include <utility>
const Token* findExpression(const nonneg int exprid,
const Token* start,
const Token* end,
const std::function<bool(const Token*)>& pred)
{
if (exprid == 0)
return nullptr;
if (!precedes(start, end))
return nullptr;
for (const Token* tok = start; tok != end; tok = tok->next()) {
if (tok->exprId() != exprid)
continue;
if (pred(tok))
return tok;
}
return nullptr;
}
static int findArgumentPosRecursive(const Token* tok, const Token* tokToFind, bool &found, nonneg int depth=0)
{
++depth;
if (!tok || depth >= 100)
return -1;
if (tok->str() == ",") {
int res = findArgumentPosRecursive(tok->astOperand1(), tokToFind, found, depth);
if (res == -1)
return -1;
if (found)
return res;
const int argn = res;
res = findArgumentPosRecursive(tok->astOperand2(), tokToFind, found, depth);
if (res == -1)
return -1;
return argn + res;
}
if (tokToFind == tok)
found = true;
return 1;
}
static int findArgumentPos(const Token* tok, const Token* tokToFind){
bool found = false;
const int argn = findArgumentPosRecursive(tok, tokToFind, found, 0);
if (found)
return argn - 1;
return -1;
}
static int getArgumentPos(const Token* ftok, const Token* tokToFind){
const Token* tok = ftok;
if (Token::Match(tok, "%name% (|{"))
tok = ftok->next();
if (!Token::Match(tok, "(|{|["))
return -1;
const Token* startTok = tok->astOperand2();
if (!startTok && tok->next() != tok->link())
startTok = tok->astOperand1();
return findArgumentPos(startTok, tokToFind);
}
template<class T, class OuputIterator, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
static void astFlattenCopy(T* tok, const char* op, OuputIterator out, nonneg int depth = 100)
{
--depth;
if (!tok || depth < 0)
return;
if (strcmp(tok->str().c_str(), op) == 0) {
astFlattenCopy(tok->astOperand1(), op, out, depth);
astFlattenCopy(tok->astOperand2(), op, out, depth);
} else {
*out = tok;
++out;
}
}
std::vector<const Token*> astFlatten(const Token* tok, const char* op)
{
std::vector<const Token*> result;
astFlattenCopy(tok, op, std::back_inserter(result));
return result;
}
std::vector<Token*> astFlatten(Token* tok, const char* op)
{
std::vector<Token*> result;
astFlattenCopy(tok, op, std::back_inserter(result));
return result;
}
nonneg int astCount(const Token* tok, const char* op, int depth)
{
--depth;
if (!tok || depth < 0)
return 0;
if (strcmp(tok->str().c_str(), op) == 0)
return astCount(tok->astOperand1(), op, depth) + astCount(tok->astOperand2(), op, depth);
return 1;
}
bool astHasToken(const Token* root, const Token * tok)
{
if (!root)
return false;
while (tok->astParent() && tok != root)
tok = tok->astParent();
return root == tok;
}
bool astHasVar(const Token * tok, nonneg int varid)
{
if (!tok)
return false;
if (tok->varId() == varid)
return true;
return astHasVar(tok->astOperand1(), varid) || astHasVar(tok->astOperand2(), varid);
}
bool astHasExpr(const Token* tok, nonneg int exprid)
{
if (!tok)
return false;
if (tok->exprId() == exprid)
return true;
return astHasExpr(tok->astOperand1(), exprid) || astHasExpr(tok->astOperand2(), exprid);
}
static bool astIsCharWithSign(const Token *tok, ValueType::Sign sign)
{
if (!tok)
return false;
const ValueType *valueType = tok->valueType();
if (!valueType)
return false;
return valueType->type == ValueType::Type::CHAR && valueType->pointer == 0U && valueType->sign == sign;
}
bool astIsSignedChar(const Token *tok)
{
return astIsCharWithSign(tok, ValueType::Sign::SIGNED);
}
bool astIsUnknownSignChar(const Token *tok)
{
return astIsCharWithSign(tok, ValueType::Sign::UNKNOWN_SIGN);
}
bool astIsGenericChar(const Token* tok)
{
return !astIsPointer(tok) && tok && tok->valueType() && (tok->valueType()->type == ValueType::Type::CHAR || tok->valueType()->type == ValueType::Type::WCHAR_T);
}
bool astIsPrimitive(const Token* tok)
{
const ValueType* vt = tok ? tok->valueType() : nullptr;
if (!vt)
return false;
return vt->isPrimitive();
}
bool astIsIntegral(const Token *tok, bool unknown)
{
const ValueType *vt = tok ? tok->valueType() : nullptr;
if (!vt)
return unknown;
return vt->isIntegral() && vt->pointer == 0U;
}
bool astIsUnsigned(const Token* tok)
{
return tok && tok->valueType() && tok->valueType()->sign == ValueType::UNSIGNED;
}
bool astIsFloat(const Token *tok, bool unknown)
{
const ValueType *vt = tok ? tok->valueType() : nullptr;
if (!vt)
return unknown;
return vt->type >= ValueType::Type::FLOAT && vt->pointer == 0U;
}
bool astIsBool(const Token *tok)
{
return tok && (tok->isBoolean() || (tok->valueType() && tok->valueType()->type == ValueType::Type::BOOL && !tok->valueType()->pointer));
}
bool astIsPointer(const Token *tok)
{
return tok && tok->valueType() && tok->valueType()->pointer;
}
bool astIsSmartPointer(const Token* tok)
{
return tok && tok->valueType() && tok->valueType()->smartPointerTypeToken;
}
bool astIsUniqueSmartPointer(const Token* tok)
{
if (!astIsSmartPointer(tok))
return false;
if (!tok->valueType()->smartPointer)
return false;
return tok->valueType()->smartPointer->unique;
}
bool astIsIterator(const Token *tok)
{
return tok && tok->valueType() && tok->valueType()->type == ValueType::Type::ITERATOR;
}
bool astIsContainer(const Token* tok) {
return getLibraryContainer(tok) != nullptr && !astIsIterator(tok);
}
bool astIsNonStringContainer(const Token* tok)
{
const Library::Container* container = getLibraryContainer(tok);
return container && !container->stdStringLike && !astIsIterator(tok);
}
bool astIsContainerView(const Token* tok)
{
const Library::Container* container = getLibraryContainer(tok);
return container && !astIsIterator(tok) && container->view;
}
bool astIsContainerOwned(const Token* tok) {
return astIsContainer(tok) && !astIsContainerView(tok);
}
bool astIsContainerString(const Token* tok)
{
if (!tok)
return false;
if (!tok->valueType())
return false;
const Library::Container* container = tok->valueType()->container;
if (!container)
return false;
return container->stdStringLike;
}
static std::pair<const Token*, const Library::Container*> getContainerFunction(const Token* tok, const Settings* settings)
{
const Library::Container* cont{};
if (!tok || !tok->valueType() || (!tok->valueType()->container && (!settings || !(cont = settings->library.detectContainerOrIterator(tok->valueType()->smartPointerTypeToken)))))
return {};
const Token* parent = tok->astParent();
if (Token::Match(parent, ". %name% (") && astIsLHS(tok)) {
return { parent->next(), cont ? cont : tok->valueType()->container };
}
return {};
}
Library::Container::Action astContainerAction(const Token* tok, const Token** ftok, const Settings* settings)
{
const auto ftokCont = getContainerFunction(tok, settings);
if (ftok)
*ftok = ftokCont.first;
if (!ftokCont.first)
return Library::Container::Action::NO_ACTION;
return ftokCont.second->getAction(ftokCont.first->str());
}
Library::Container::Yield astContainerYield(const Token* tok, const Token** ftok, const Settings* settings)
{
const auto ftokCont = getContainerFunction(tok, settings);
if (ftok)
*ftok = ftokCont.first;
if (!ftokCont.first)
return Library::Container::Yield::NO_YIELD;
return ftokCont.second->getYield(ftokCont.first->str());
}
Library::Container::Yield astFunctionYield(const Token* tok, const Settings& settings, const Token** ftok)
{
if (!tok)
return Library::Container::Yield::NO_YIELD;
const auto* function = settings.library.getFunction(tok);
if (!function)
return Library::Container::Yield::NO_YIELD;
if (ftok)
*ftok = tok;
return function->containerYield;
}
bool astIsRangeBasedForDecl(const Token* tok)
{
return Token::simpleMatch(tok->astParent(), ":") && Token::simpleMatch(tok->astParent()->astParent(), "(");
}
std::string astCanonicalType(const Token *expr, bool pointedToType)
{
if (!expr)
return "";
std::pair<const Token*, const Token*> decl = Token::typeDecl(expr, pointedToType);
if (decl.first && decl.second) {
std::string ret;
for (const Token *type = decl.first; Token::Match(type,"%name%|::") && type != decl.second; type = type->next()) {
if (!Token::Match(type, "const|static"))
ret += type->str();
}
return ret;
}
return "";
}
static bool match(const Token *tok, const std::string &rhs)
{
if (tok->str() == rhs)
return true;
if (!tok->varId() && tok->hasKnownIntValue() && std::to_string(tok->values().front().intvalue) == rhs)
return true;
return false;
}
const Token * astIsVariableComparison(const Token *tok, const std::string &comp, const std::string &rhs, const Token **vartok)
{
if (!tok)
return nullptr;
const Token *ret = nullptr;
if (tok->isComparisonOp()) {
if (tok->astOperand1() && match(tok->astOperand1(), rhs)) {
// Invert comparator
std::string s = tok->str();
if (s[0] == '>')
s[0] = '<';
else if (s[0] == '<')
s[0] = '>';
if (s == comp) {
ret = tok->astOperand2();
}
} else if (tok->str() == comp && tok->astOperand2() && match(tok->astOperand2(), rhs)) {
ret = tok->astOperand1();
}
} else if (comp == "!=" && rhs == "0") {
if (tok->str() == "!") {
ret = tok->astOperand1();
// handle (!(x==0)) as (x!=0)
astIsVariableComparison(ret, "==", "0", &ret);
} else
ret = tok;
} else if (comp == "==" && rhs == "0") {
if (tok->str() == "!") {
ret = tok->astOperand1();
// handle (!(x!=0)) as (x==0)
astIsVariableComparison(ret, "!=", "0", &ret);
}
}
while (ret && ret->str() == ".")
ret = ret->astOperand2();
if (ret && ret->str() == "=" && ret->astOperand1() && ret->astOperand1()->varId())
ret = ret->astOperand1();
else if (ret && ret->varId() == 0U)
ret = nullptr;
if (vartok)
*vartok = ret;
return ret;
}
bool isVariableDecl(const Token* tok)
{
if (!tok)
return false;
const Variable* var = tok->variable();
if (!var)
return false;
if (var->nameToken() == tok)
return true;
const Token * const varDeclEndToken = var->declEndToken();
return Token::Match(varDeclEndToken, "; %var%") && varDeclEndToken->next() == tok;
}
bool isStlStringType(const Token* tok)
{
return Token::Match(tok, "std :: string|wstring|u16string|u32string !!::") ||
(Token::simpleMatch(tok, "std :: basic_string <") && !Token::simpleMatch(tok->linkAt(3), "> ::"));
}
bool isTemporary(const Token* tok, const Library* library, bool unknown)
{
if (!tok)
return false;
if (Token::simpleMatch(tok, "."))
return (tok->originalName() != "->" && isTemporary(tok->astOperand1(), library)) ||
isTemporary(tok->astOperand2(), library);
if (Token::Match(tok, ",|::"))
return isTemporary(tok->astOperand2(), library);
if (tok->isCast() || (tok->isCpp() && isCPPCast(tok)))
return isTemporary(tok->astOperand2(), library);
if (Token::Match(tok, ".|[|++|--|%name%|%assign%"))
return false;
if (tok->isUnaryOp("*"))
return false;
if (Token::Match(tok, "&|<<|>>") && isLikelyStream(tok->astOperand1()))
return false;
if (Token::simpleMatch(tok, "?")) {
const Token* branchTok = tok->astOperand2();
if (!branchTok->astOperand1() || !branchTok->astOperand1()->valueType())
return false;
if (!branchTok->astOperand2()->valueType())
return false;
return !branchTok->astOperand1()->valueType()->isTypeEqual(branchTok->astOperand2()->valueType());
}
if (Token::simpleMatch(tok, "(") && tok->astOperand1() &&
(tok->astOperand2() || Token::simpleMatch(tok->next(), ")"))) {
if (Token::simpleMatch(tok->astOperand1(), "typeid"))
return false;
if (tok->valueType()) {
if (tok->valueType()->pointer > 0) {
const Token* const parent = tok->astParent();
if (Token::simpleMatch(parent, "&"))
return true;
if (Token::simpleMatch(parent, "return") && parent->valueType()->reference != Reference::None &&
parent->valueType()->container && parent->valueType()->container->stdStringLike)
return true;
}
return tok->valueType()->reference == Reference::None && tok->valueType()->pointer == 0;
}
const Token* ftok = nullptr;
if (Token::simpleMatch(tok->previous(), ">") && tok->linkAt(-1))
ftok = tok->linkAt(-1)->previous();
else
ftok = tok->previous();
if (!ftok)
return false;
if (const Function * f = ftok->function())
return !Function::returnsReference(f, true);
if (ftok->type())
return true;
if (library) {
const std::string& returnType = library->returnValueType(ftok);
return !returnType.empty() && returnType.back() != '&';
}
return unknown;
}
if (tok->isCast())
return false;
// Currying a function is unknown in cppcheck
if (Token::simpleMatch(tok, "(") && Token::simpleMatch(tok->astOperand1(), "("))
return unknown;
if (Token::simpleMatch(tok, "{") && Token::simpleMatch(tok->astParent(), "return") && tok->astOperand1() &&
!tok->astOperand2())
return isTemporary(tok->astOperand1(), library);
return true;
}
static bool isFunctionCall(const Token* tok)
{
if (Token::Match(tok, "%name% ("))
return true;
if (Token::Match(tok, "%name% <") && Token::simpleMatch(tok->linkAt(1), "> ("))
return true;
if (Token::Match(tok, "%name% ::"))
return isFunctionCall(tok->tokAt(2));
return false;
}
static bool hasToken(const Token * startTok, const Token * stopTok, const Token * tok)
{
for (const Token * tok2 = startTok; tok2 != stopTok; tok2 = tok2->next()) {
if (tok2 == tok)
return true;
}
return false;
}
template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
static T* previousBeforeAstLeftmostLeafGeneric(T* tok)
{
if (!tok)
return nullptr;
T* leftmostLeaf = tok;
while (leftmostLeaf->astOperand1())
leftmostLeaf = leftmostLeaf->astOperand1();
return leftmostLeaf->previous();
}
const Token* previousBeforeAstLeftmostLeaf(const Token* tok)
{
return previousBeforeAstLeftmostLeafGeneric(tok);
}
Token* previousBeforeAstLeftmostLeaf(Token* tok)
{
return previousBeforeAstLeftmostLeafGeneric(tok);
}
template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
static T* nextAfterAstRightmostLeafGeneric(T* tok)
{
T * rightmostLeaf = tok;
if (!rightmostLeaf || !rightmostLeaf->astOperand1())
return nullptr;
do {
if (T* lam = findLambdaEndToken(rightmostLeaf)) {
rightmostLeaf = lam;
break;
}
if (rightmostLeaf->astOperand2() && precedes(rightmostLeaf, rightmostLeaf->astOperand2()))
rightmostLeaf = rightmostLeaf->astOperand2();
else if (rightmostLeaf->astOperand1() && precedes(rightmostLeaf, rightmostLeaf->astOperand1()))
rightmostLeaf = rightmostLeaf->astOperand1();
else
break;
} while (rightmostLeaf->astOperand1() || rightmostLeaf->astOperand2());
while (Token::Match(rightmostLeaf->next(), "]|)") && !hasToken(rightmostLeaf->linkAt(1), rightmostLeaf->next(), tok))
rightmostLeaf = rightmostLeaf->next();
if (Token::Match(rightmostLeaf, "{|(|[") && rightmostLeaf->link())
rightmostLeaf = rightmostLeaf->link();
return rightmostLeaf->next();
}
const Token* nextAfterAstRightmostLeaf(const Token* tok)
{
return nextAfterAstRightmostLeafGeneric(tok);
}
Token* nextAfterAstRightmostLeaf(Token* tok)
{
return nextAfterAstRightmostLeafGeneric(tok);
}
const Token* astParentSkipParens(const Token* tok)
{
return astParentSkipParens(const_cast<Token*>(tok));
}
Token* astParentSkipParens(Token* tok)
{
if (!tok)
return nullptr;
Token * parent = tok->astParent();
if (!Token::simpleMatch(parent, "("))
return parent;
if (parent->link() != nextAfterAstRightmostLeaf(tok))
return parent;
if (Token::Match(parent->previous(), "%name% (") ||
(Token::simpleMatch(parent->previous(), "> (") && parent->linkAt(-1)))
return parent;
return astParentSkipParens(parent);
}
const Token* getParentMember(const Token * tok)
{
if (!tok)
return tok;
const Token * parent = tok->astParent();
if (!Token::simpleMatch(parent, "."))
return tok;
if (astIsRHS(tok)) {
if (Token::simpleMatch(parent->astOperand1(), "."))
return parent->astOperand1()->astOperand2();
return parent->astOperand1();
}
const Token * gparent = parent->astParent();
if (!Token::simpleMatch(gparent, ".") || gparent->astOperand2() != parent)
return tok;
if (gparent->astOperand1())
return gparent->astOperand1();
return tok;
}
const Token* getParentLifetime(const Token* tok)
{
if (!tok)
return tok;
// Skipping checking for variable if its a pointer-to-member
if (!Token::simpleMatch(tok->previous(), ". *")) {
const Variable* var = tok->variable();
// TODO: Call getLifetimeVariable for deeper analysis
if (!var)
return tok;
if (var->isLocal() || var->isArgument())
return tok;
}
const Token* parent = getParentMember(tok);
if (parent != tok)
return getParentLifetime(parent);
return tok;
}
static std::vector<const Token*> getParentMembers(const Token* tok)
{
if (!tok)
return {};
if (!Token::simpleMatch(tok->astParent(), "."))
return {tok};
const Token* parent = tok->astParent();
while (Token::simpleMatch(parent->astParent(), "."))
parent = parent->astParent();
std::vector<const Token*> result;
for (const Token* tok2 : astFlatten(parent, ".")) {
if (Token::simpleMatch(tok2, "(") && Token::simpleMatch(tok2->astOperand1(), ".")) {
std::vector<const Token*> sub = getParentMembers(tok2->astOperand1());
result.insert(result.end(), sub.cbegin(), sub.cend());
}
result.push_back(tok2);
}
return result;
}
static const Token* getParentLifetimeObject(const Token* tok)
{
while (Token::simpleMatch(tok, "["))
tok = tok->astOperand1();
return tok;
}
const Token* getParentLifetime(const Token* tok, const Library& library)
{
std::vector<const Token*> members = getParentMembers(tok);
if (members.size() < 2)
return tok;
// Find the first local variable, temporary, or array
auto it = std::find_if(members.crbegin(), members.crend(), [&](const Token* tok2) {
const Variable* var = tok2->variable();
if (var)
return var->isLocal() || var->isArgument();
if (Token::simpleMatch(tok2, "["))
return true;
return isTemporary(tok2, &library);
});
if (it == members.rend())
return tok;
// If any of the submembers are borrowed types then stop
if (std::any_of(it.base() - 1, members.cend() - 1, [&](const Token* tok2) {
const Token* obj = getParentLifetimeObject(tok2);
const Variable* var = obj->variable();
// Check for arrays first since astIsPointer will return true, but an array is not a borrowed type
if (var && var->isArray())
return false;
if (astIsPointer(obj) || astIsContainerView(obj) || astIsIterator(obj))
return true;
if (!astIsUniqueSmartPointer(obj)) {
if (astIsSmartPointer(obj))
return true;
const Token* dotTok = obj->next();
if (!Token::simpleMatch(dotTok, ".")) {
const Token* endTok = nextAfterAstRightmostLeaf(obj);
if (!endTok)
dotTok = obj->next();
else if (Token::simpleMatch(endTok, "."))
dotTok = endTok;
else if (Token::simpleMatch(endTok->next(), "."))
dotTok = endTok->next();
}
// If we are dereferencing the member variable then treat it as borrowed
if (Token::simpleMatch(dotTok, ".") && dotTok->originalName() == "->")
return true;
}
return var && var->isReference();
}))
return nullptr;
const Token* result = getParentLifetimeObject(*it);
if (result != *it)
return getParentLifetime(result);
return result;
}
static bool isInConstructorList(const Token* tok)
{
if (!tok)
return false;
if (!astIsRHS(tok))
return false;
const Token* parent = tok->astParent();
if (!Token::Match(parent, "{|("))
return false;
if (!Token::Match(parent->previous(), "%var% {|("))
return false;
if (!parent->astOperand1() || !parent->astOperand2())
return false;
do {
parent = parent->astParent();
} while (Token::simpleMatch(parent, ","));
return Token::simpleMatch(parent, ":") && !Token::simpleMatch(parent->astParent(), "?");
}
std::vector<ValueType> getParentValueTypes(const Token* tok, const Settings& settings, const Token** parent)
{
if (!tok)
return {};
if (!tok->astParent())
return {};
if (isInConstructorList(tok)) {
if (parent)
*parent = tok->astParent()->astOperand1();
if (tok->astParent()->astOperand1()->valueType())
return {*tok->astParent()->astOperand1()->valueType()};
return {};
}
const Token* ftok = nullptr;
if (Token::Match(tok->astParent(), "(|{|,")) {
int argn = -1;
ftok = getTokenArgumentFunction(tok, argn);
const Token* typeTok = nullptr;
if (ftok && argn >= 0) {
if (ftok->function()) {
std::vector<ValueType> result;
const Token* nameTok = nullptr;
for (const Variable* var : getArgumentVars(ftok, argn)) {
if (!var)
continue;
if (!var->valueType())
continue;
nameTok = var->nameToken();
result.push_back(*var->valueType());
if (var->isArray())
result.back().pointer += var->dimensions().size();
}
if (result.size() == 1 && nameTok && parent) {
*parent = nameTok;
}
return result;
}
if (const Type* t = Token::typeOf(ftok, &typeTok)) {
if (astIsPointer(typeTok))
return {*typeTok->valueType()};
const Scope* scope = t->classScope;
// Check for aggregate constructors
if (scope && scope->numConstructors == 0 && t->derivedFrom.empty() &&
(t->isClassType() || t->isStructType()) && numberOfArguments(ftok) <= scope->varlist.size() &&
!scope->varlist.empty()) {
assert(argn < scope->varlist.size());
auto it = std::next(scope->varlist.cbegin(), argn);
if (it->valueType())
return {*it->valueType()};
}
}
}
}
if (Token::Match(tok->astParent()->tokAt(-2), ". push_back|push_front|insert|push (") &&
astIsContainer(tok->astParent()->tokAt(-2)->astOperand1())) {
const Token* contTok = tok->astParent()->tokAt(-2)->astOperand1();
const ValueType* vtCont = contTok->valueType();
if (!vtCont->containerTypeToken)
return {};
ValueType vtParent = ValueType::parseDecl(vtCont->containerTypeToken, settings);
return {std::move(vtParent)};
}
// The return type of a function is not the parent valuetype
if (Token::simpleMatch(tok->astParent(), "(") && ftok && !tok->astParent()->isCast() &&
ftok->tokType() != Token::eType)
return {};
if (parent && Token::Match(tok->astParent(), "return|(|{|%assign%")) {
*parent = tok->astParent();
}
if (tok->astParent()->valueType())
return {*tok->astParent()->valueType()};
return {};
}
bool astIsLHS(const Token* tok)
{
if (!tok)
return false;
const Token* parent = tok->astParent();
if (!parent)
return false;
if (!parent->astOperand1())
return false;
if (!parent->astOperand2())
return false;
return parent->astOperand1() == tok;
}
bool astIsRHS(const Token* tok)
{
if (!tok)
return false;
const Token* parent = tok->astParent();
if (!parent)
return false;
if (!parent->astOperand1())
return false;
if (!parent->astOperand2())
return false;
return parent->astOperand2() == tok;
}
template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
static T* getCondTokImpl(T* tok)
{
if (!tok)
return nullptr;
if (Token::simpleMatch(tok, "("))
return getCondTok(tok->previous());
if (Token::simpleMatch(tok, "do {")) {
T* endTok = tok->linkAt(1);
if (Token::simpleMatch(endTok, "} while ("))
return endTok->tokAt(2)->astOperand2();
}
if (Token::simpleMatch(tok, "for") && Token::simpleMatch(tok->next()->astOperand2(), ";") &&
tok->next()->astOperand2()->astOperand2())
return tok->next()->astOperand2()->astOperand2()->astOperand1();
if (Token::simpleMatch(tok->next()->astOperand2(), ";"))
return tok->next()->astOperand2()->astOperand1();
if (tok->isName() && !tok->isControlFlowKeyword())
return nullptr;
return tok->next()->astOperand2();
}
template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
static T* getCondTokFromEndImpl(T* endBlock)
{
if (!Token::simpleMatch(endBlock, "}"))
return nullptr;
T* startBlock = endBlock->link();
if (!Token::simpleMatch(startBlock, "{"))
return nullptr;
if (Token::simpleMatch(startBlock->previous(), "do"))
return getCondTok(startBlock->previous());
if (Token::simpleMatch(startBlock->previous(), ")"))
return getCondTok(startBlock->linkAt(-1));
if (Token::simpleMatch(startBlock->tokAt(-2), "} else {"))
return getCondTokFromEnd(startBlock->tokAt(-2));
return nullptr;
}
template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
static T* getInitTokImpl(T* tok)
{
if (!tok)
return nullptr;
if (Token::Match(tok, "%name% ("))
return getInitTokImpl(tok->next());
if (tok->str() != "(")
return nullptr;
if (!Token::simpleMatch(tok->astOperand2(), ";"))
return nullptr;
if (Token::simpleMatch(tok->astOperand2()->astOperand1(), ";"))
return nullptr;
return tok->astOperand2()->astOperand1();
}
template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
static T* getStepTokImpl(T* tok)
{
if (!tok)
return nullptr;
if (Token::Match(tok, "%name% ("))
return getStepTokImpl(tok->next());
if (tok->str() != "(")
return nullptr;
if (!Token::simpleMatch(tok->astOperand2(), ";"))
return nullptr;
if (!Token::simpleMatch(tok->astOperand2()->astOperand2(), ";"))
return nullptr;
return tok->astOperand2()->astOperand2()->astOperand2();
}
Token* getCondTok(Token* tok)
{
return getCondTokImpl(tok);
}
const Token* getCondTok(const Token* tok)
{
return getCondTokImpl(tok);
}
Token* getCondTokFromEnd(Token* endBlock)
{
return getCondTokFromEndImpl(endBlock);
}
const Token* getCondTokFromEnd(const Token* endBlock)
{
return getCondTokFromEndImpl(endBlock);
}
Token* getInitTok(Token* tok) {
return getInitTokImpl(tok);
}
const Token* getInitTok(const Token* tok) {
return getInitTokImpl(tok);
}
Token* getStepTok(Token* tok) {
return getStepTokImpl(tok);
}
const Token* getStepTok(const Token* tok) {
return getStepTokImpl(tok);
}
const Token *findNextTokenFromBreak(const Token *breakToken)
{
const Scope *scope = breakToken->scope();
while (scope) {
if (scope->isLoopScope() || scope->type == Scope::ScopeType::eSwitch) {
if (scope->type == Scope::ScopeType::eDo && Token::simpleMatch(scope->bodyEnd, "} while ("))
return scope->bodyEnd->linkAt(2)->next();
return scope->bodyEnd;
}
scope = scope->nestedIn;
}
return nullptr;
}
bool extractForLoopValues(const Token *forToken,
nonneg int &varid,
bool &knownInitValue,
MathLib::bigint &initValue,
bool &partialCond,
MathLib::bigint &stepValue,
MathLib::bigint &lastValue)
{
if (!Token::simpleMatch(forToken, "for (") || !Token::simpleMatch(forToken->next()->astOperand2(), ";"))
return false;
const Token *initExpr = forToken->next()->astOperand2()->astOperand1();
const Token *condExpr = forToken->next()->astOperand2()->astOperand2()->astOperand1();
const Token *incExpr = forToken->next()->astOperand2()->astOperand2()->astOperand2();
if (!initExpr || !initExpr->isBinaryOp() || initExpr->str() != "=" || !Token::Match(initExpr->astOperand1(), "%var%"))
return false;
std::vector<MathLib::bigint> minInitValue =
getMinValue(makeIntegralInferModel(), initExpr->astOperand2()->values());
if (minInitValue.empty()) {
const ValueFlow::Value* v = initExpr->astOperand2()->getMinValue(true);
if (v)
minInitValue.push_back(v->intvalue);
}
if (minInitValue.empty())
return false;
varid = initExpr->astOperand1()->varId();
knownInitValue = initExpr->astOperand2()->hasKnownIntValue();
initValue = minInitValue.front();
partialCond = Token::Match(condExpr, "%oror%|&&");
visitAstNodes(condExpr, [varid, &condExpr](const Token *tok) {
if (Token::Match(tok, "%oror%|&&"))
return ChildrenToVisit::op1_and_op2;
if (Token::Match(tok, "<|<=") && tok->isBinaryOp() && tok->astOperand1()->varId() == varid && tok->astOperand2()->hasKnownIntValue()) {
if (Token::Match(condExpr, "%oror%|&&") || tok->astOperand2()->getKnownIntValue() < condExpr->astOperand2()->getKnownIntValue())
condExpr = tok;
}
return ChildrenToVisit::none;
});
if (!Token::Match(condExpr, "<|<=") || !condExpr->isBinaryOp() || condExpr->astOperand1()->varId() != varid || !condExpr->astOperand2()->hasKnownIntValue())
return false;
if (!incExpr || !incExpr->isUnaryOp("++") || incExpr->astOperand1()->varId() != varid)
return false;
stepValue = 1;
if (condExpr->str() == "<")
lastValue = condExpr->astOperand2()->getKnownIntValue() - 1;
else
lastValue = condExpr->astOperand2()->getKnownIntValue();
return true;
}
static const Token * getVariableInitExpression(const Variable * var)
{
if (!var)
return nullptr;
const Token *varDeclEndToken = var->declEndToken();
if (!varDeclEndToken)
return nullptr;
if (Token::Match(varDeclEndToken, "; %varid% =", var->declarationId()))
return varDeclEndToken->tokAt(2)->astOperand2();
return varDeclEndToken->astOperand2();
}
const Token* isInLoopCondition(const Token* tok)
{
const Token* top = tok->astTop();
return Token::Match(top->previous(), "for|while (") ? top : nullptr;
}
/// If tok2 comes after tok1
bool precedes(const Token * tok1, const Token * tok2)
{
if (tok1 == tok2)
return false;
if (!tok1)
return false;
if (!tok2)
return true;
return tok1->index() < tok2->index();
}
/// If tok1 comes after tok2
bool succeeds(const Token* tok1, const Token* tok2)
{
if (tok1 == tok2)
return false;
if (!tok1)
return false;
if (!tok2)
return true;
return tok1->index() > tok2->index();
}
bool isAliasOf(const Token *tok, nonneg int varid, bool* inconclusive)
{
if (tok->varId() == varid)
return false;
// NOLINTNEXTLINE(readability-use-anyofallof) - TODO: fix this / also Cppcheck false negative
for (const ValueFlow::Value &val : tok->values()) {
if (!val.isLocalLifetimeValue())
continue;
if (val.tokvalue->varId() == varid) {
if (val.isInconclusive()) {
if (inconclusive)
*inconclusive = true;
else
continue;
}
return true;
}
}
return false;
}
bool isAliasOf(const Token* tok, const Token* expr, int* indirect)
{
const Token* r = nullptr;
if (indirect)
*indirect = 1;
for (const ReferenceToken& ref : followAllReferences(tok)) {
const bool pointer = astIsPointer(ref.token);
r = findAstNode(expr, [&](const Token* childTok) {
if (childTok->exprId() == 0)
return false;
if (ref.token != tok && expr->exprId() == childTok->exprId()) {
if (indirect)
*indirect = 0;
return true;
}
for (const ValueFlow::Value& val : ref.token->values()) {
if (val.isImpossible())
continue;
if (val.isLocalLifetimeValue() || (pointer && val.isSymbolicValue() && val.intvalue == 0)) {
if (findAstNode(val.tokvalue,
[&](const Token* aliasTok) {
return aliasTok != childTok && aliasTok->exprId() == childTok->exprId();
})) {
return true;
}
}
}
return false;
});
if (r)
break;
}
return r;
}
static bool isAliased(const Token *startTok, const Token *endTok, nonneg int varid)
{
if (!precedes(startTok, endTok))
return false;
for (const Token *tok = startTok; tok != endTok; tok = tok->next()) {
if (Token::Match(tok, "= & %varid% ;", varid))
return true;
if (isAliasOf(tok, varid))
return true;
}
return false;
}
bool exprDependsOnThis(const Token* expr, bool onVar, nonneg int depth)
{
if (!expr)
return false;
if (expr->str() == "this")
return true;
if (depth >= 1000)
// Abort recursion to avoid stack overflow
return true;
++depth;
// calling nonstatic method?
if (Token::Match(expr, "%name% (")) {
if (expr->function() && expr->function()->nestedIn && expr->function()->nestedIn->isClassOrStruct() && !expr->function()->isStatic()) {
// is it a method of this?
const Scope* fScope = expr->scope();
while (!fScope->functionOf && fScope->nestedIn)
fScope = fScope->nestedIn;
const Scope* classScope = fScope->functionOf;
if (classScope && classScope->function)
classScope = classScope->function->token->scope();
if (classScope && classScope->isClassOrStruct())
return contains(classScope->findAssociatedScopes(), expr->function()->nestedIn);
return false;
}
if (expr->isOperatorKeyword() && !Token::simpleMatch(expr->next()->astParent(), "."))
return true;
}
if (onVar && expr->variable()) {
const Variable* var = expr->variable();
return ((var->isPrivate() || var->isPublic() || var->isProtected()) && !var->isStatic());
}
if (Token::simpleMatch(expr, "."))
return exprDependsOnThis(expr->astOperand1(), onVar, depth);
return exprDependsOnThis(expr->astOperand1(), onVar, depth) || exprDependsOnThis(expr->astOperand2(), onVar, depth);
}
static bool hasUnknownVars(const Token* startTok)
{
bool result = false;
visitAstNodes(startTok, [&](const Token* tok) {
if (tok->varId() > 0 && !tok->variable()) {
result = true;
return ChildrenToVisit::done;
}
return ChildrenToVisit::op1_and_op2;
});
return result;
}
bool isStructuredBindingVariable(const Variable* var)
{
if (!var)
return false;
const Token* tok = var->nameToken();
while (tok && Token::Match(tok->astParent(), "[|,|:"))
tok = tok->astParent();
return tok && (tok->str() == "[" || Token::simpleMatch(tok->previous(), "] :")); // TODO: remove workaround when #11105 is fixed
}
/// This takes a token that refers to a variable and it will return the token
/// to the expression that the variable is assigned to. If its not valid to
/// make such substitution then it will return the original token.
static const Token * followVariableExpression(const Settings& settings, const Token * tok, const Token * end = nullptr)
{
if (!tok)
return tok;
// Skip following variables that is across multiple files
if (end && end->fileIndex() != tok->fileIndex())
return tok;
// Skip array access
if (Token::Match(tok, "%var% ["))
return tok;
// Skip pointer indirection
if (tok->astParent() && tok->isUnaryOp("*"))
return tok;
// Skip following variables if it is used in an assignment
if (Token::Match(tok->next(), "%assign%"))
return tok;
const Variable * var = tok->variable();
const Token * varTok = getVariableInitExpression(var);
if (!varTok)
return tok;
if (hasUnknownVars(varTok))
return tok;
if (var->isVolatile())
return tok;
if (!var->isLocal() && !var->isConst())
return tok;
if (var->isStatic() && !var->isConst())
return tok;
if (var->isArgument())
return tok;
if (isStructuredBindingVariable(var))
return tok;
// assigning a floating point value to an integer does not preserve the value
if (var->valueType() && var->valueType()->isIntegral() && varTok->valueType() && varTok->valueType()->isFloat())
return tok;
const Token * lastTok = precedes(tok, end) ? end : tok;
// If this is in a loop then check if variables are modified in the entire scope
const Token * endToken = (isInLoopCondition(tok) || isInLoopCondition(varTok) || var->scope() != tok->scope()) ? var->scope()->bodyEnd : lastTok;
if (!var->isConst() && (!precedes(varTok, endToken) || isVariableChanged(varTok, endToken, tok->varId(), false, settings)))
return tok;
if (precedes(varTok, endToken) && isAliased(varTok, endToken, tok->varId()))
return tok;
const Token* startToken = nextAfterAstRightmostLeaf(varTok);
if (!startToken)
startToken = varTok;
if (varTok->exprId() == 0) {
if (!varTok->isLiteral())
return tok;
} else if (!precedes(startToken, endToken)) {
return tok;
} else if (findExpressionChanged(varTok, startToken, endToken, settings)) {
return tok;
}
return varTok;
}
static void followVariableExpressionError(const Token *tok1, const Token *tok2, ErrorPath* errors)
{
if (!errors)
return;
if (!tok1)
return;
if (!tok2)
return;
ErrorPathItem item = std::make_pair(tok2, "'" + tok1->str() + "' is assigned value '" + tok2->expressionString() + "' here.");
if (std::find(errors->cbegin(), errors->cend(), item) != errors->cend())
return;
errors->push_back(std::move(item));
}
SmallVector<ReferenceToken> followAllReferences(const Token* tok,
bool temporary,
bool inconclusive,
ErrorPath errors,
int depth)
{
struct ReferenceTokenLess {
bool operator()(const ReferenceToken& x, const ReferenceToken& y) const {
return x.token < y.token;
}
};
if (!tok)
return {};
if (depth < 0) {
SmallVector<ReferenceToken> refs_result;
refs_result.emplace_back(tok, std::move(errors));
return refs_result;
}
const Variable *var = tok->variable();
if (var && var->declarationId() == tok->varId()) {
if (var->nameToken() == tok || isStructuredBindingVariable(var)) {
SmallVector<ReferenceToken> refs_result;
refs_result.emplace_back(tok, std::move(errors));
return refs_result;
}
if (var->isReference() || var->isRValueReference()) {
const Token * const varDeclEndToken = var->declEndToken();
if (!varDeclEndToken) {
SmallVector<ReferenceToken> refs_result;
refs_result.emplace_back(tok, std::move(errors));
return refs_result;
}
if (var->isArgument()) {
errors.emplace_back(varDeclEndToken, "Passed to reference.");
SmallVector<ReferenceToken> refs_result;
refs_result.emplace_back(tok, std::move(errors));
return refs_result;
}
if (Token::simpleMatch(varDeclEndToken, "=")) {
if (astHasToken(varDeclEndToken, tok))
return {};
errors.emplace_back(varDeclEndToken, "Assigned to reference.");
const Token *vartok = varDeclEndToken->astOperand2();
if (vartok == tok || (!temporary && isTemporary(vartok, nullptr, true) &&
(var->isConst() || var->isRValueReference()))) {
SmallVector<ReferenceToken> refs_result;
refs_result.emplace_back(tok, std::move(errors));
return refs_result;
}
if (vartok)
return followAllReferences(vartok, temporary, inconclusive, std::move(errors), depth - 1);
}
}
} else if (Token::simpleMatch(tok, "?") && Token::simpleMatch(tok->astOperand2(), ":")) {
std::set<ReferenceToken, ReferenceTokenLess> result;
const Token* tok2 = tok->astOperand2();
auto refs = followAllReferences(tok2->astOperand1(), temporary, inconclusive, errors, depth - 1);
result.insert(refs.cbegin(), refs.cend());
refs = followAllReferences(tok2->astOperand2(), temporary, inconclusive, errors, depth - 1);
result.insert(refs.cbegin(), refs.cend());
if (!inconclusive && result.size() != 1) {
SmallVector<ReferenceToken> refs_result;
refs_result.emplace_back(tok, std::move(errors));
return refs_result;
}
if (!result.empty()) {
SmallVector<ReferenceToken> refs_result;
refs_result.insert(refs_result.end(), result.cbegin(), result.cend());
return refs_result;
}
} else if (tok->previous() && tok->previous()->function() && Token::Match(tok->previous(), "%name% (")) {
const Function *f = tok->previous()->function();
if (!Function::returnsReference(f)) {
SmallVector<ReferenceToken> refs_result;
refs_result.emplace_back(tok, std::move(errors));
return refs_result;
}
std::set<ReferenceToken, ReferenceTokenLess> result;
std::vector<const Token*> returns = Function::findReturns(f);
for (const Token* returnTok : returns) {
if (returnTok == tok)
continue;
for (const ReferenceToken& rt :
followAllReferences(returnTok, temporary, inconclusive, errors, depth - returns.size())) {
const Variable* argvar = rt.token->variable();
if (!argvar) {
SmallVector<ReferenceToken> refs_result;
refs_result.emplace_back(tok, std::move(errors));
return refs_result;
}
if (argvar->isArgument() && (argvar->isReference() || argvar->isRValueReference())) {
const int n = getArgumentPos(argvar, f);
if (n < 0) {
SmallVector<ReferenceToken> refs_result;
refs_result.emplace_back(tok, std::move(errors));
return refs_result;
}
std::vector<const Token*> args = getArguments(tok->previous());
if (n >= args.size()) {
SmallVector<ReferenceToken> refs_result;
refs_result.emplace_back(tok, std::move(errors));
return refs_result;
}
const Token* argTok = args[n];
ErrorPath er = errors;
er.emplace_back(returnTok, "Return reference.");
er.emplace_back(tok->previous(), "Called function passing '" + argTok->expressionString() + "'.");
auto refs =
followAllReferences(argTok, temporary, inconclusive, std::move(er), depth - returns.size());
result.insert(refs.cbegin(), refs.cend());
if (!inconclusive && result.size() > 1) {
SmallVector<ReferenceToken> refs_result;
refs_result.emplace_back(tok, std::move(errors));
return refs_result;
}
}
}
}
if (!result.empty()) {
SmallVector<ReferenceToken> refs_result;
refs_result.insert(refs_result.end(), result.cbegin(), result.cend());
return refs_result;
}
}
SmallVector<ReferenceToken> refs_result;
refs_result.emplace_back(tok, std::move(errors));
return refs_result;
}
const Token* followReferences(const Token* tok, ErrorPath* errors)
{
if (!tok)
return nullptr;
auto refs = followAllReferences(tok, true, false);
if (refs.size() == 1) {
if (errors)
*errors = std::move(refs.front().errors);
return refs.front().token;
}
return nullptr;
}
static bool isSameLifetime(const Token * const tok1, const Token * const tok2)
{
ValueFlow::Value v1 = ValueFlow::getLifetimeObjValue(tok1);
if (!v1.isLifetimeValue())
return false;
ValueFlow::Value v2 = ValueFlow::getLifetimeObjValue(tok2);
if (!v2.isLifetimeValue())
return false;
return v1.tokvalue == v2.tokvalue;
}
static bool compareKnownValue(const Token * const tok1, const Token * const tok2, const std::function<bool(const ValueFlow::Value&, const ValueFlow::Value&, bool)> &compare)
{
static const auto isKnownFn = std::mem_fn(&ValueFlow::Value::isKnown);
const auto v1 = std::find_if(tok1->values().cbegin(), tok1->values().cend(), isKnownFn);
if (v1 == tok1->values().end()) {
return false;
}
if (v1->isNonValue() || v1->isContainerSizeValue() || v1->isSymbolicValue())
return false;
const auto v2 = std::find_if(tok2->values().cbegin(), tok2->values().cend(), isKnownFn);
if (v2 == tok2->values().end()) {
return false;
}
if (v1->valueType != v2->valueType) {
return false;
}
const bool sameLifetime = isSameLifetime(tok1, tok2);
return compare(*v1, *v2, sameLifetime);
}
bool isEqualKnownValue(const Token * const tok1, const Token * const tok2)
{
return compareKnownValue(tok1, tok2, [&](const ValueFlow::Value& v1, const ValueFlow::Value& v2, bool sameLifetime) {
bool r = v1.equalValue(v2);
if (v1.isIteratorValue()) {
r &= sameLifetime;
}
return r;
});
}
static inline bool isDifferentKnownValues(const Token * const tok1, const Token * const tok2)
{
return compareKnownValue(tok1, tok2, [&](const ValueFlow::Value& v1, const ValueFlow::Value& v2, bool sameLifetime) {
bool r = v1.equalValue(v2);
if (v1.isIteratorValue()) {
r &= sameLifetime;
}
return !r;
});
}
static inline bool isSameConstantValue(bool macro, const Token* tok1, const Token* tok2)
{
if (tok1 == nullptr || tok2 == nullptr)
return false;
auto adjustForCast = [](const Token* tok) {
if (tok->astOperand2() && Token::Match(tok->previous(), "%type% (|{") && tok->previous()->isStandardType())
return tok->astOperand2();
return tok;
};
tok1 = adjustForCast(tok1);
if (!tok1->isNumber() && !tok1->enumerator())
return false;
tok2 = adjustForCast(tok2);
if (!tok2->isNumber() && !tok2->enumerator())
return false;
if (macro && (tok1->isExpandedMacro() || tok2->isExpandedMacro() || tok1->isTemplateArg() || tok2->isTemplateArg()))
return false;
const ValueType * v1 = tok1->valueType();
const ValueType * v2 = tok2->valueType();
if (!v1 || !v2 || v1->sign != v2->sign || v1->type != v2->type || v1->pointer != v2->pointer)
return false;
return isEqualKnownValue(tok1, tok2);
}
static bool isForLoopCondition(const Token * const tok)
{
if (!tok)
return false;
const Token *const parent = tok->astParent();
return Token::simpleMatch(parent, ";") && parent->astOperand1() == tok &&
Token::simpleMatch(parent->astParent(), ";") &&
Token::simpleMatch(parent->astParent()->astParent(), "(") &&
parent->astParent()->astParent()->astOperand1()->str() == "for";
}
static bool isForLoopIncrement(const Token* const tok)
{
if (!tok)
return false;
const Token *const parent = tok->astParent();
return Token::simpleMatch(parent, ";") && parent->astOperand2() == tok &&
Token::simpleMatch(parent->astParent(), ";") &&
Token::simpleMatch(parent->astParent()->astParent(), "(") &&
parent->astParent()->astParent()->astOperand1()->str() == "for";
}
bool isUsedAsBool(const Token* const tok, const Settings& settings)
{
if (!tok)
return false;
if (isForLoopIncrement(tok))
return false;
if (astIsBool(tok))
return true;
if (Token::Match(tok, "!|&&|%oror%|%comp%"))
return true;
const Token* parent = tok->astParent();
if (!parent)
return false;
if (Token::simpleMatch(parent, "["))
return false;
if (parent->isUnaryOp("*"))
return false;
if (Token::simpleMatch(parent, ".")) {
if (astIsRHS(tok))
return isUsedAsBool(parent, settings);
return false;
}
if (Token::Match(parent, "&&|!|%oror%"))
return true;
if (parent->isCast())
return !Token::simpleMatch(parent->astOperand1(), "dynamic_cast") && isUsedAsBool(parent, settings);
if (parent->isUnaryOp("*"))
return isUsedAsBool(parent, settings);
if (Token::Match(parent, "==|!=") && (tok->astSibling()->isNumber() || tok->astSibling()->isKeyword()) && tok->astSibling()->hasKnownIntValue() &&
tok->astSibling()->values().front().intvalue == 0)
return true;
if (parent->str() == "(" && astIsRHS(tok) && Token::Match(parent->astOperand1(), "if|while"))
return true;
if (Token::simpleMatch(parent, "?") && astIsLHS(tok))
return true;
if (isForLoopCondition(tok))
return true;
if (!Token::Match(parent, "%cop%") && !(parent->str() == "(" && tok == parent->astOperand1())) {
if (parent->str() == "," && parent->isInitComma())
return false;
std::vector<ValueType> vtParents = getParentValueTypes(tok, settings);
return std::any_of(vtParents.cbegin(), vtParents.cend(), [&](const ValueType& vt) {
return vt.pointer == 0 && vt.type == ValueType::BOOL;
});
}
return false;
}
bool compareTokenFlags(const Token* tok1, const Token* tok2, bool macro) {
if (macro) {
if (tok1->isExpandedMacro() != tok2->isExpandedMacro())
return false;
if (tok1->isExpandedMacro()) { // both are macros
if (tok1->getMacroName() != tok2->getMacroName())
return false;
if (tok1->astParent() && tok2->astParent() && tok1->astParent()->isExpandedMacro() && tok1->astParent()->getMacroName() == tok2->astParent()->getMacroName())
return false;
}
if (tok1->isTemplateArg() || tok2->isTemplateArg())
return false;
}
if (tok1->isComplex() != tok2->isComplex())
return false;
if (tok1->isLong() != tok2->isLong())
return false;
if (tok1->isUnsigned() != tok2->isUnsigned())
return false;
if (tok1->isSigned() != tok2->isSigned())
return false;
return true;
}
static bool astIsBoolLike(const Token* tok, const Settings& settings)
{
return astIsBool(tok) || isUsedAsBool(tok, settings);
}
bool isSameExpression(bool macro, const Token *tok1, const Token *tok2, const Settings& settings, bool pure, bool followVar, ErrorPath* errors)
{
if (tok1 == tok2)
return true;
if (tok1 == nullptr || tok2 == nullptr)
return false;
// tokens needs to be from the same TokenList so no need check standard on both of them
if (tok1->isCpp()) {
if (tok1->str() == "." && tok1->astOperand1() && tok1->astOperand1()->str() == "this")
tok1 = tok1->astOperand2();
if (tok2->str() == "." && tok2->astOperand1() && tok2->astOperand1()->str() == "this")
tok2 = tok2->astOperand2();
}
// Skip double not
if (Token::simpleMatch(tok1, "!") && Token::simpleMatch(tok1->astOperand1(), "!") && !Token::simpleMatch(tok1->astParent(), "=") && astIsBoolLike(tok2, settings)) {
return isSameExpression(macro, tok1->astOperand1()->astOperand1(), tok2, settings, pure, followVar, errors);
}
if (Token::simpleMatch(tok2, "!") && Token::simpleMatch(tok2->astOperand1(), "!") && !Token::simpleMatch(tok2->astParent(), "=") && astIsBoolLike(tok1, settings)) {
return isSameExpression(macro, tok1, tok2->astOperand1()->astOperand1(), settings, pure, followVar, errors);
}
const bool tok_str_eq = tok1->str() == tok2->str();
if (!tok_str_eq && isDifferentKnownValues(tok1, tok2))
return false;
const Token *followTok1 = tok1, *followTok2 = tok2;
while (Token::simpleMatch(followTok1, "::") && followTok1->astOperand2())
followTok1 = followTok1->astOperand2();
while (Token::simpleMatch(followTok2, "::") && followTok2->astOperand2())
followTok2 = followTok2->astOperand2();
if (isSameConstantValue(macro, followTok1, followTok2))
return true;
// Follow variable
if (followVar && !tok_str_eq && (followTok1->varId() || followTok2->varId() || followTok1->enumerator() || followTok2->enumerator())) {
const Token * varTok1 = followVariableExpression(settings, followTok1, followTok2);
if ((varTok1->str() == followTok2->str()) || isSameConstantValue(macro, varTok1, followTok2)) {
followVariableExpressionError(followTok1, varTok1, errors);
return isSameExpression(macro, varTok1, followTok2, settings, true, followVar, errors);
}
const Token * varTok2 = followVariableExpression(settings, followTok2, followTok1);
if ((followTok1->str() == varTok2->str()) || isSameConstantValue(macro, followTok1, varTok2)) {
followVariableExpressionError(followTok2, varTok2, errors);
return isSameExpression(macro, followTok1, varTok2, settings, true, followVar, errors);
}
if ((varTok1->str() == varTok2->str()) || isSameConstantValue(macro, varTok1, varTok2)) {
followVariableExpressionError(tok1, varTok1, errors);
followVariableExpressionError(tok2, varTok2, errors);
return isSameExpression(macro, varTok1, varTok2, settings, true, followVar, errors);
}
}
// Follow references
if (!tok_str_eq) {
const Token* refTok1 = followReferences(tok1, errors);
const Token* refTok2 = followReferences(tok2, errors);
if (refTok1 != tok1 || refTok2 != tok2) {
if (refTok1 && !refTok1->varId() && refTok2 && !refTok2->varId()) { // complex reference expression
const Token *start = refTok1, *end = refTok2;
if (!precedes(start, end))
std::swap(start, end);
if (findExpressionChanged(start, start, end, settings))
return false;
}
return isSameExpression(macro, refTok1, refTok2, settings, pure, followVar, errors);
}
}
if (tok1->varId() != tok2->varId() || !tok_str_eq || tok1->originalName() != tok2->originalName()) {
if ((Token::Match(tok1,"<|>") && Token::Match(tok2,"<|>")) ||
(Token::Match(tok1,"<=|>=") && Token::Match(tok2,"<=|>="))) {
return isSameExpression(macro, tok1->astOperand1(), tok2->astOperand2(), settings, pure, followVar, errors) &&
isSameExpression(macro, tok1->astOperand2(), tok2->astOperand1(), settings, pure, followVar, errors);
}
const Token* condTok = nullptr;
const Token* exprTok = nullptr;
if (Token::Match(tok1, "==|!=")) {
condTok = tok1;
exprTok = tok2;
} else if (Token::Match(tok2, "==|!=")) {
condTok = tok2;
exprTok = tok1;
}
if (condTok && condTok->astOperand1() && condTok->astOperand2() && !Token::Match(exprTok, "%comp%")) {
const Token* varTok1 = nullptr;
const Token* varTok2 = exprTok;
const ValueFlow::Value* value = nullptr;
if (condTok->astOperand1()->hasKnownIntValue()) {
value = &condTok->astOperand1()->values().front();
varTok1 = condTok->astOperand2();
} else if (condTok->astOperand2()->hasKnownIntValue()) {
value = &condTok->astOperand2()->values().front();
varTok1 = condTok->astOperand1();
}
const bool exprIsNot = Token::simpleMatch(exprTok, "!");
if (exprIsNot)
varTok2 = exprTok->astOperand1();
bool compare = false;
if (value) {
if (value->intvalue == 0 && exprIsNot && Token::simpleMatch(condTok, "==")) {
compare = true;
} else if (value->intvalue == 0 && !exprIsNot && Token::simpleMatch(condTok, "!=")) {
compare = true;
} else if (value->intvalue != 0 && exprIsNot && Token::simpleMatch(condTok, "!=")) {
compare = true;
} else if (value->intvalue != 0 && !exprIsNot && Token::simpleMatch(condTok, "==")) {
compare = true;
}
}
if (compare && astIsBoolLike(varTok1, settings) && astIsBoolLike(varTok2, settings))
return isSameExpression(macro, varTok1, varTok2, settings, pure, followVar, errors);
}
return false;
}
if (!compareTokenFlags(tok1, tok2, macro))
return false;
if (pure && tok1->isName() && tok1->strAt(1) == "(" && tok1->str() != "sizeof" && !(tok1->variable() && tok1 == tok1->variable()->nameToken())) {
if (!tok1->function()) {
if (Token::simpleMatch(tok1->previous(), ".")) {
const Token *lhs = tok1->previous();
while (Token::Match(lhs, "(|.|["))
lhs = lhs->astOperand1();
if (!lhs)
return false;
const bool lhsIsConst = (lhs->variable() && lhs->variable()->isConst()) ||
(lhs->valueType() && lhs->valueType()->constness > 0) ||
(Token::Match(lhs, "%var% . %name% (") && settings.library.isFunctionConst(lhs->tokAt(2)));
if (!lhsIsConst)
return false;
} else {
const Token * ftok = tok1;
if (!settings.library.isFunctionConst(ftok) && !ftok->isAttributeConst() && !ftok->isAttributePure())
return false;
}
} else {
if (!tok1->function()->isConst() && !tok1->function()->isAttributeConst() &&
!tok1->function()->isAttributePure())
return false;
}
}
// templates/casts
if ((tok1->next() && tok1->linkAt(1) && Token::Match(tok1, "%name% <")) ||
(tok2->next() && tok2->linkAt(1) && Token::Match(tok2, "%name% <"))) {
// non-const template function that is not a dynamic_cast => return false
if (pure && Token::simpleMatch(tok1->linkAt(1), "> (") &&
!(tok1->function() && tok1->function()->isConst()) &&
tok1->str() != "dynamic_cast")
return false;
// some template/cast stuff.. check that the template arguments are same
const Token *t1 = tok1->next();
const Token *t2 = tok2->next();
const Token *end1 = t1->link();
const Token *end2 = t2->link();
while (t1 && t2 && t1 != end1 && t2 != end2) {
if (t1->str() != t2->str() || !compareTokenFlags(t1, t2, macro))
return false;
t1 = t1->next();
t2 = t2->next();
}
if (t1 != end1 || t2 != end2)
return false;
}
if (tok1->tokType() == Token::eIncDecOp || tok1->isAssignmentOp())
return false;
// bailout when we see ({..})
if (tok1->str() == "{")
return false;
// cast => assert that the casts are equal
if (tok1->str() == "(" && tok1->previous() &&
!tok1->previous()->isName() &&
!(tok1->strAt(-1) == ">" && tok1->linkAt(-1))) {
const Token *t1 = tok1->next();
const Token *t2 = tok2->next();
while (t1 && t2 &&
t1->str() == t2->str() &&
compareTokenFlags(t1, t2, macro) &&
(t1->isName() || t1->str() == "*")) {
t1 = t1->next();
t2 = t2->next();
}
if (!t1 || !t2 || t1->str() != ")" || t2->str() != ")")
return false;
}
bool noncommutativeEquals =
isSameExpression(macro, tok1->astOperand1(), tok2->astOperand1(), settings, pure, followVar, errors);
noncommutativeEquals = noncommutativeEquals &&
isSameExpression(macro, tok1->astOperand2(), tok2->astOperand2(), settings, pure, followVar, errors);
if (noncommutativeEquals)
return true;
// in c++, a+b might be different to b+a, depending on the type of a and b
if (tok1->isCpp() && tok1->str() == "+" && tok1->isBinaryOp()) {
const ValueType* vt1 = tok1->astOperand1()->valueType();
const ValueType* vt2 = tok1->astOperand2()->valueType();
if (!(vt1 && (vt1->type >= ValueType::VOID || vt1->pointer) && vt2 && (vt2->type >= ValueType::VOID || vt2->pointer)))
return false;
}
const bool commutative = tok1->isBinaryOp() && Token::Match(tok1, "%or%|%oror%|+|*|&|&&|^|==|!=");
bool commutativeEquals = commutative &&
isSameExpression(macro, tok1->astOperand2(), tok2->astOperand1(), settings, pure, followVar, errors);
commutativeEquals = commutativeEquals &&
isSameExpression(macro, tok1->astOperand1(), tok2->astOperand2(), settings, pure, followVar, errors);
return commutativeEquals;
}
static bool isZeroBoundCond(const Token * const cond)
{
if (cond == nullptr)
return false;
// Assume unsigned
// TODO: Handle reverse conditions
const bool isZero = cond->astOperand2()->getValue(0);
if (cond->str() == "==" || cond->str() == ">=")
return isZero;
if (cond->str() == "<=")
return true;
if (cond->str() == "<")
return !isZero;
if (cond->str() == ">")
return false;
return false;
}
bool isOppositeCond(bool isNot, const Token * const cond1, const Token * const cond2, const Settings& settings, bool pure, bool followVar, ErrorPath* errors)
{
if (!cond1 || !cond2)
return false;
if (isSameExpression(true, cond1, cond2, settings, pure, followVar, errors))
return false;
if (!isNot && cond1->str() == "&&" && cond2->str() == "&&") {
for (const Token* tok1: {
cond1->astOperand1(), cond1->astOperand2()
}) {
for (const Token* tok2: {
cond2->astOperand1(), cond2->astOperand2()
}) {
if (isSameExpression(true, tok1, tok2, settings, pure, followVar, errors)) {
if (isOppositeCond(isNot, tok1->astSibling(), tok2->astSibling(), settings, pure, followVar, errors))
return true;
}
}
}
}
if (cond1->str() != cond2->str() && (cond1->str() == "||" || cond2->str() == "||")) {
const Token* orCond = nullptr;
const Token* otherCond = nullptr;
if (cond1->str() == "||") {
orCond = cond1;
otherCond = cond2;
}
if (cond2->str() == "||") {
orCond = cond2;
otherCond = cond1;
}
return isOppositeCond(isNot, orCond->astOperand1(), otherCond, settings, pure, followVar, errors) &&
isOppositeCond(isNot, orCond->astOperand2(), otherCond, settings, pure, followVar, errors);
}
if (cond1->str() == "!") {
if (cond2->str() == "!=") {
if (cond2->astOperand1() && cond2->astOperand1()->str() == "0")
return isSameExpression(true, cond1->astOperand1(), cond2->astOperand2(), settings, pure, followVar, errors);
if (cond2->astOperand2() && cond2->astOperand2()->str() == "0")
return isSameExpression(true, cond1->astOperand1(), cond2->astOperand1(), settings, pure, followVar, errors);
}
if (!isUsedAsBool(cond2, settings))
return false;
return isSameExpression(true, cond1->astOperand1(), cond2, settings, pure, followVar, errors);
}
if (cond2->str() == "!")
return isOppositeCond(isNot, cond2, cond1, settings, pure, followVar, errors);
if (!isNot) {
if (cond1->str() == "==" && cond2->str() == "==") {
if (isSameExpression(true, cond1->astOperand1(), cond2->astOperand1(), settings, pure, followVar, errors))
return isDifferentKnownValues(cond1->astOperand2(), cond2->astOperand2());
if (isSameExpression(true, cond1->astOperand2(), cond2->astOperand2(), settings, pure, followVar, errors))
return isDifferentKnownValues(cond1->astOperand1(), cond2->astOperand1());
}
// TODO: Handle reverse conditions
if (Library::isContainerYield(cond1, Library::Container::Yield::EMPTY, "empty") &&
Library::isContainerYield(cond2->astOperand1(), Library::Container::Yield::SIZE, "size") &&
isSameExpression(true,
cond1->astOperand1()->astOperand1(),
cond2->astOperand1()->astOperand1()->astOperand1(),
settings,
pure,
followVar,
errors)) {
return !isZeroBoundCond(cond2);
}
if (Library::isContainerYield(cond2, Library::Container::Yield::EMPTY, "empty") &&
Library::isContainerYield(cond1->astOperand1(), Library::Container::Yield::SIZE, "size") &&
isSameExpression(true,
cond2->astOperand1()->astOperand1(),
cond1->astOperand1()->astOperand1()->astOperand1(),
settings,
pure,
followVar,
errors)) {
return !isZeroBoundCond(cond1);
}
}
if (!cond1->isComparisonOp() || !cond2->isComparisonOp())
return false;
const std::string &comp1 = cond1->str();
// condition found .. get comparator
std::string comp2;
if (isSameExpression(true, cond1->astOperand1(), cond2->astOperand1(), settings, pure, followVar, errors) &&
isSameExpression(true, cond1->astOperand2(), cond2->astOperand2(), settings, pure, followVar, errors)) {
comp2 = cond2->str();
} else if (isSameExpression(true, cond1->astOperand1(), cond2->astOperand2(), settings, pure, followVar, errors) &&
isSameExpression(true, cond1->astOperand2(), cond2->astOperand1(), settings, pure, followVar, errors)) {
comp2 = cond2->str();
if (comp2[0] == '>')
comp2[0] = '<';
else if (comp2[0] == '<')
comp2[0] = '>';
}
if (!isNot && comp2.empty()) {
const Token *expr1 = nullptr, *value1 = nullptr, *expr2 = nullptr, *value2 = nullptr;
std::string op1 = cond1->str(), op2 = cond2->str();
if (cond1->astOperand2()->hasKnownIntValue()) {
expr1 = cond1->astOperand1();
value1 = cond1->astOperand2();
} else if (cond1->astOperand1()->hasKnownIntValue()) {
expr1 = cond1->astOperand2();
value1 = cond1->astOperand1();
if (op1[0] == '>')
op1[0] = '<';
else if (op1[0] == '<')
op1[0] = '>';
}
if (cond2->astOperand2()->hasKnownIntValue()) {
expr2 = cond2->astOperand1();
value2 = cond2->astOperand2();
} else if (cond2->astOperand1()->hasKnownIntValue()) {
expr2 = cond2->astOperand2();
value2 = cond2->astOperand1();
if (op2[0] == '>')
op2[0] = '<';
else if (op2[0] == '<')
op2[0] = '>';
}
if (!expr1 || !value1 || !expr2 || !value2) {
return false;
}
if (!isSameExpression(true, expr1, expr2, settings, pure, followVar, errors))
return false;
const ValueFlow::Value &rhsValue1 = value1->values().front();
const ValueFlow::Value &rhsValue2 = value2->values().front();
if (op1 == "<" || op1 == "<=")
return (op2 == "==" || op2 == ">" || op2 == ">=") && (rhsValue1.intvalue < rhsValue2.intvalue);
if (op1 == ">=" || op1 == ">")
return (op2 == "==" || op2 == "<" || op2 == "<=") && (rhsValue1.intvalue > rhsValue2.intvalue);
return false;
}
// is condition opposite?
return ((comp1 == "==" && comp2 == "!=") ||
(comp1 == "!=" && comp2 == "==") ||
(comp1 == "<" && comp2 == ">=") ||
(comp1 == "<=" && comp2 == ">") ||
(comp1 == ">" && comp2 == "<=") ||
(comp1 == ">=" && comp2 == "<") ||
(!isNot && ((comp1 == "<" && comp2 == ">") ||
(comp1 == ">" && comp2 == "<") ||
(comp1 == "==" && (comp2 == "!=" || comp2 == ">" || comp2 == "<")) ||
((comp1 == "!=" || comp1 == ">" || comp1 == "<") && comp2 == "==")
)));
}
bool isOppositeExpression(const Token * const tok1, const Token * const tok2, const Settings& settings, bool pure, bool followVar, ErrorPath* errors)
{
if (!tok1 || !tok2)
return false;
if (isOppositeCond(true, tok1, tok2, settings, pure, followVar, errors))
return true;
if (tok1->isUnaryOp("-") && !(tok2->astParent() && tok2->astParent()->tokType() == Token::eBitOp))
return isSameExpression(true, tok1->astOperand1(), tok2, settings, pure, followVar, errors);
if (tok2->isUnaryOp("-") && !(tok2->astParent() && tok2->astParent()->tokType() == Token::eBitOp))
return isSameExpression(true, tok2->astOperand1(), tok1, settings, pure, followVar, errors);
return false;
}
static bool functionModifiesArguments(const Function* f)
{
return std::any_of(f->argumentList.cbegin(), f->argumentList.cend(), [](const Variable& var) {
if (var.isReference() || var.isPointer())
return !var.isConst();
return true;
});
}
bool isConstFunctionCall(const Token* ftok, const Library& library)
{
if (isUnevaluated(ftok))
return true;
if (!Token::Match(ftok, "%name% ("))
return false;
if (const Function* f = ftok->function()) {
if (f->isAttributePure() || f->isAttributeConst())
return true;
// Any modified arguments
if (functionModifiesArguments(f))
return false;
if (Function::returnsVoid(f))
return false;
// Member function call
if (Token::simpleMatch(ftok->previous(), ".") || exprDependsOnThis(ftok->next())) {
if (f->isConst())
return true;
// Check for const overloaded function that just return the const version
if (!Function::returnsConst(f)) {
std::vector<const Function*> fs = f->getOverloadedFunctions();
if (std::any_of(fs.cbegin(), fs.cend(), [&](const Function* g) {
if (f == g)
return false;
if (f->argumentList.size() != g->argumentList.size())
return false;
if (functionModifiesArguments(g))
return false;
if (g->isConst() && Function::returnsConst(g))
return true;
return false;
}))
return true;
}
return false;
}
if (f->argumentList.empty())
return f->isConstexpr();
} else if (Token::Match(ftok->previous(), ". %name% (") && ftok->previous()->originalName() != "->" &&
astIsSmartPointer(ftok->previous()->astOperand1())) {
return Token::Match(ftok, "get|get_deleter ( )");
} else if (Token::Match(ftok->previous(), ". %name% (") && astIsContainer(ftok->previous()->astOperand1())) {
const Library::Container* container = ftok->previous()->astOperand1()->valueType()->container;
if (!container)
return false;
if (container->getYield(ftok->str()) != Library::Container::Yield::NO_YIELD)
return true;
if (container->getAction(ftok->str()) == Library::Container::Action::FIND_CONST)
return true;
return false;
} else if (const Library::Function* lf = library.getFunction(ftok)) {
if (lf->ispure)
return true;
if (lf->containerYield != Library::Container::Yield::NO_YIELD)
return true;
if (lf->containerAction == Library::Container::Action::FIND_CONST)
return true;
return false;
} else {
const bool memberFunction = Token::Match(ftok->previous(), ". %name% (");
bool constMember = !memberFunction;
if (Token::Match(ftok->tokAt(-2), "%var% . %name% (")) {
const Variable* var = ftok->tokAt(-2)->variable();
if (var)
constMember = var->isConst();
}
// TODO: Only check const on lvalues
std::vector<const Token*> args = getArguments(ftok);
if (args.empty())
return false;
return constMember && std::all_of(args.cbegin(), args.cend(), [](const Token* tok) {
const Variable* var = tok->variable();
if (var)
return var->isConst();
return false;
});
}
return true;
}
bool isConstExpression(const Token *tok, const Library& library)
{
if (!tok)
return true;
if (tok->variable() && tok->variable()->isVolatile())
return false;
if (tok->isName() && tok->strAt(1) == "(") {
if (!isConstFunctionCall(tok, library))
return false;
}
if (tok->tokType() == Token::eIncDecOp)
return false;
if (tok->isAssignmentOp())
return false;
if (isLikelyStreamRead(tok))
return false;
// bailout when we see ({..})
if (tok->str() == "{")
return false;
return isConstExpression(tok->astOperand1(), library) && isConstExpression(tok->astOperand2(), library);
}
bool isWithoutSideEffects(const Token* tok, bool checkArrayAccess, bool checkReference)
{
if (!tok)
return true;
if (!tok->isCpp())
return true;
while (tok && tok->astOperand2() && tok->astOperand2()->str() != "(")
tok = tok->astOperand2();
if (tok && tok->varId()) {
const Variable* var = tok->variable();
return var && ((!var->isClass() && (checkReference || !var->isReference())) || var->isPointer() || (checkArrayAccess ? var->isStlType() && !var->isStlType(CheckClass::stl_containers_not_const) : var->isStlType()));
}
return true;
}
bool isUniqueExpression(const Token* tok)
{
if (!tok)
return true;
if (tok->function()) {
const Function * fun = tok->function();
const Scope * scope = fun->nestedIn;
if (!scope)
return true;
const std::string returnType = fun->retType ? fun->retType->name() : fun->retDef->stringifyList(fun->tokenDef);
if (!std::all_of(scope->functionList.begin(), scope->functionList.end(), [&](const Function& f) {
if (f.type != Function::eFunction)
return true;
const std::string freturnType = f.retType ? f.retType->name() : f.retDef->stringifyList(f.returnDefEnd());
return f.argumentList.size() != fun->argumentList.size() || returnType != freturnType || f.name() == fun->name();
}))
return false;
} else if (tok->variable()) {
const Variable * var = tok->variable();
const Scope * scope = var->scope();
if (!scope)
return true;
const Type * varType = var->type();
// Iterate over the variables in scope and the parameters of the function if possible
const Function * fun = scope->function;
auto pred = [=](const Variable& v) {
if (varType)
return v.type() && v.type()->name() == varType->name() && v.name() != var->name();
return v.isFloatingType() == var->isFloatingType() &&
v.isEnumType() == var->isEnumType() &&
v.isClass() == var->isClass() &&
v.isArray() == var->isArray() &&
v.isPointer() == var->isPointer() &&
v.name() != var->name();
};
if (std::any_of(scope->varlist.cbegin(), scope->varlist.cend(), pred))
return false;
if (fun) {
if (std::any_of(fun->argumentList.cbegin(), fun->argumentList.cend(), pred))
return false;
}
} else if (!isUniqueExpression(tok->astOperand1())) {
return false;
}
return isUniqueExpression(tok->astOperand2());
}
static bool isEscaped(const Token* tok, bool functionsScope, const Library& library)
{
if (library.isnoreturn(tok))
return true;
if (functionsScope)
return Token::simpleMatch(tok, "throw");
return Token::Match(tok, "return|throw");
}
static bool isEscapedOrJump(const Token* tok, bool functionsScope, const Library& library)
{
if (library.isnoreturn(tok))
return true;
if (functionsScope)
return Token::simpleMatch(tok, "throw");
return Token::Match(tok, "return|goto|throw|continue|break");
}
bool isEscapeFunction(const Token* ftok, const Library* library)
{
if (!Token::Match(ftok, "%name% ("))
return false;
const Function* function = ftok->function();
if (function) {
if (function->isEscapeFunction())
return true;
if (function->isAttributeNoreturn())
return true;
} else if (library) {
if (library->isnoreturn(ftok))
return true;
}
return false;
}
static bool hasNoreturnFunction(const Token* tok, const Library& library, const Token** unknownFunc)
{
if (!tok)
return false;
const Token* ftok = tok->str() == "(" ? tok->previous() : nullptr;
while (Token::simpleMatch(ftok, "("))
ftok = ftok->astOperand1();
if (ftok) {
const Function * function = ftok->function();
if (function) {
if (function->isEscapeFunction())
return true;
if (function->isAttributeNoreturn())
return true;
} else if (library.isnoreturn(ftok)) {
return true;
} else if (Token::Match(ftok, "exit|abort")) {
return true;
}
if (unknownFunc && !function && library.functions().count(library.getFunctionName(ftok)) == 0)
*unknownFunc = ftok;
return false;
}
if (tok->isConstOp()) {
return hasNoreturnFunction(tok->astOperand1(), library, unknownFunc) || hasNoreturnFunction(tok->astOperand2(), library, unknownFunc);
}
return false;
}
bool isReturnScope(const Token* const endToken, const Library& library, const Token** unknownFunc, bool functionScope)
{
if (!endToken || endToken->str() != "}")
return false;
const Token *prev = endToken->previous();
while (prev && Token::simpleMatch(prev->previous(), "; ;"))
prev = prev->previous();
if (prev && Token::simpleMatch(prev->previous(), "} ;"))
prev = prev->previous();
if (Token::simpleMatch(prev, "}")) {
if (Token::simpleMatch(prev->link()->tokAt(-2), "} else {"))
return isReturnScope(prev, library, unknownFunc, functionScope) &&
isReturnScope(prev->link()->tokAt(-2), library, unknownFunc, functionScope);
// TODO: Check all cases
if (!functionScope && Token::simpleMatch(prev->link()->previous(), ") {") &&
Token::simpleMatch(prev->link()->linkAt(-1)->previous(), "switch (") &&
!Token::findsimplematch(prev->link(), "break", prev)) {
return isReturnScope(prev, library, unknownFunc, functionScope);
}
if (isEscaped(prev->link()->astTop(), functionScope, library))
return true;
if (Token::Match(prev->link()->previous(), "[;{}] {"))
return isReturnScope(prev, library, unknownFunc, functionScope);
} else if (Token::simpleMatch(prev, ";")) {
if (prev->tokAt(-2) && hasNoreturnFunction(prev->tokAt(-2)->astTop(), library, unknownFunc))
return true;
// Unknown symbol
if (Token::Match(prev->tokAt(-2), ";|}|{ %name% ;") && prev->previous()->isIncompleteVar()) {
if (unknownFunc)
*unknownFunc = prev->previous();
return false;
}
if (Token::simpleMatch(prev->previous(), ") ;") && prev->linkAt(-1) &&
isEscaped(prev->linkAt(-1)->astTop(), functionScope, library))
return true;
if (isEscaped(prev->previous()->astTop(), functionScope, library))
return true;
// return/goto statement
prev = prev->previous();
while (prev && !Token::Match(prev, ";|{|}") && !isEscapedOrJump(prev, functionScope, library))
prev = prev->previous();
return prev && prev->isName();
}
return false;
}
bool isWithinScope(const Token* tok, const Variable* var, Scope::ScopeType type)
{
if (!tok || !var)
return false;
const Scope* scope = tok->scope();
while (scope && scope != var->scope()) {
if (scope->type == type)
return true;
scope = scope->nestedIn;
}
return false;
}
bool isVariableChangedByFunctionCall(const Token *tok, int indirect, nonneg int varid, const Settings &settings, bool *inconclusive)
{
if (!tok)
return false;
if (tok->varId() == varid)
return isVariableChangedByFunctionCall(tok, indirect, settings, inconclusive);
return isVariableChangedByFunctionCall(tok->astOperand1(), indirect, varid, settings, inconclusive) ||
isVariableChangedByFunctionCall(tok->astOperand2(), indirect, varid, settings, inconclusive);
}
bool isScopeBracket(const Token* tok)
{
if (!Token::Match(tok, "{|}"))
return false;
if (!tok->scope())
return false;
if (tok->str() == "{")
return tok->scope()->bodyStart == tok;
if (tok->str() == "}")
return tok->scope()->bodyEnd == tok;
return false;
}
template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
static T* getTokenArgumentFunctionImpl(T* tok, int& argn)
{
argn = -1;
{
T* parent = tok->astParent();
if (parent && (parent->isUnaryOp("&") || parent->isIncDecOp()))
parent = parent->astParent();
while (parent && parent->isCast())
parent = parent->astParent();
if (Token::Match(parent, "[+-]") && parent->valueType() && parent->valueType()->pointer)
parent = parent->astParent();
// passing variable to subfunction?
if (Token::Match(parent, "[[(,{.]") || Token::Match(parent, "%oror%|&&") || (parent && parent->isUnaryOp("*")))
;
else if (Token::simpleMatch(parent, ":")) {
while (Token::Match(parent, "[?:]"))
parent = parent->astParent();
while (Token::simpleMatch(parent, ","))
parent = parent->astParent();
if (!parent || parent->str() != "(")
return nullptr;
} else
return nullptr;
}
T* argtok = tok;
while (argtok && argtok->astParent() && (!Token::Match(argtok->astParent(), ",|(|{") || argtok->astParent()->isCast())) {
argtok = argtok->astParent();
}
if (!argtok)
return nullptr;
if (Token::simpleMatch(argtok, ","))
argtok = argtok->astOperand1();
tok = argtok;
while (Token::Match(tok->astParent(), ",|(|{")) {
tok = tok->astParent();
if (Token::Match(tok, "(|{"))
break;
}
argn = getArgumentPos(tok, argtok);
if (argn == -1)
return nullptr;
if (!Token::Match(tok, "{|("))
return nullptr;
if (tok->astOperand2())
tok = tok->astOperand1();
while (tok && (tok->isUnaryOp("*") || tok->str() == "["))
tok = tok->astOperand1();
if (Token::Match(tok, ". * %name%")) // bailout for pointer to member
return tok->tokAt(2);
while (Token::simpleMatch(tok, "."))
tok = tok->astOperand2();
while (Token::simpleMatch(tok, "::")) {
// If there is only a op1 and not op2, then this is a global scope
if (!tok->astOperand2() && tok->astOperand1()) {
tok = tok->astOperand1();
break;
}
tok = tok->astOperand2();
if (Token::simpleMatch(tok, "<") && tok->link())
tok = tok->astOperand1();
}
if (tok && tok->link() && tok->str() == ">")
tok = tok->link()->previous();
if (!Token::Match(tok, "%name%|(|{"))
return nullptr;
// Skip labels
if (Token::Match(tok, "%name% :"))
return nullptr;
return tok;
}
const Token* getTokenArgumentFunction(const Token* tok, int& argn) {
return getTokenArgumentFunctionImpl(tok, argn);
}
Token* getTokenArgumentFunction(Token* tok, int& argn) {
return getTokenArgumentFunctionImpl(tok, argn);
}
std::vector<const Variable*> getArgumentVars(const Token* tok, int argnr)
{
std::vector<const Variable*> result;
if (!tok)
return result;
if (tok->function()) {
const Variable* argvar = tok->function()->getArgumentVar(argnr);
if (argvar)
return {argvar};
return result;
}
if (tok->variable() || Token::simpleMatch(tok, "{") || Token::Match(tok->previous(), "%type% (|{")) {
const Type* type = Token::typeOf(tok);
if (!type)
return result;
const Scope* typeScope = type->classScope;
if (!typeScope)
return result;
const bool tokIsBrace = Token::simpleMatch(tok, "{");
// Aggregate constructor
if (tokIsBrace && typeScope->numConstructors == 0 && argnr < typeScope->varlist.size()) {
auto it = std::next(typeScope->varlist.cbegin(), argnr);
return {&*it};
}
const int argCount = numberOfArguments(tok);
const bool constructor = tokIsBrace || (tok->variable() && tok->variable()->nameToken() == tok);
for (const Function &function : typeScope->functionList) {
if (function.argCount() < argCount)
continue;
if (constructor && !function.isConstructor())
continue;
if (!constructor && !Token::simpleMatch(function.token, "operator()"))
continue;
const Variable* argvar = function.getArgumentVar(argnr);
if (argvar)
result.push_back(argvar);
}
}
return result;
}
static bool isCPPCastKeyword(const Token* tok)
{
if (!tok)
return false;
return endsWith(tok->str(), "_cast");
}
static bool isTrivialConstructor(const Token* tok)
{
const Token* typeTok = nullptr;
const Type* t = Token::typeOf(tok, &typeTok);
if (t)
return false;
if (typeTok->valueType() && typeTok->valueType()->isPrimitive())
return true;
return false;
}
static bool isArray(const Token* tok)
{
if (!tok)
return false;
if (tok->variable())
return tok->variable()->isArray();
if (Token::simpleMatch(tok, "."))
return isArray(tok->astOperand2());
return false;
}
static inline
// limit it to CLang as compiling with GCC might fail with
// error: inlining failed in call to always_inline 'bool isMutableExpression(const Token*)': function not considered for inlining
// error: inlining failed in call to ‘always_inline’ ‘bool isMutableExpression(const Token*)’: recursive inlining
#if defined(__clang__)
__attribute__((always_inline))
#endif
bool isMutableExpression(const Token* tok)
{
if (!tok)
return false;
if (tok->isLiteral() || tok->isKeyword() || tok->isStandardType() || tok->isEnumerator())
return false;
if (Token::Match(tok, ",|;|:|]|)|}"))
return false;
if (Token::simpleMatch(tok, "[ ]"))
return false;
if (tok->previous() && tok->previous()->isKeyword() && Token::Match(tok->previous(), "%name% ("))
return false;
if (tok->link() && Token::Match(tok, "<|>"))
return false;
if (tok->astOperand1() && Token::simpleMatch(tok, "["))
return isMutableExpression(tok->astOperand1());
if (const Variable* var = tok->variable()) {
if (var->nameToken() == tok)
return false;
if (!var->isPointer() && var->isConst())
return false;
}
return true;
}
bool isVariableChangedByFunctionCall(const Token *tok, int indirect, const Settings &settings, bool *inconclusive)
{
if (!tok)
return false;
if (Token::simpleMatch(tok, ","))
return false;
const Token * const tok1 = tok;
// address of variable
const bool addressOf = tok->astParent() && tok->astParent()->isUnaryOp("&");
if (addressOf)
indirect++;
const bool deref = tok->astParent() && tok->astParent()->isUnaryOp("*");
if (deref && indirect > 0)
indirect--;
if (indirect == 1 && tok->isCpp() && tok->tokAt(-1) && Token::simpleMatch(tok->tokAt(-2), "new (")) // placement new TODO: fix AST
return true;
int argnr;
tok = getTokenArgumentFunction(tok, argnr);
if (!tok)
return false; // not a function => variable not changed
if (Token::simpleMatch(tok, "{") && isTrivialConstructor(tok))
return false;
if (tok->isKeyword() && !isCPPCastKeyword(tok) && !startsWith(tok->str(),"operator"))
return false;
// A functional cast won't modify the variable
if (Token::Match(tok, "%type% (|{") && tok->tokType() == Token::eType && astIsPrimitive(tok->next()))
return false;
const Token * parenTok = tok->next();
if (Token::simpleMatch(parenTok, "<") && parenTok->link())
parenTok = parenTok->link()->next();
const bool possiblyPassedByReference = (parenTok->next() == tok1 || Token::Match(tok1->previous(), ", %name% [,)}]"));
if (!tok->function() && !tok->variable() && tok->isName()) {
// Check if direction (in, out, inout) is specified in the library configuration and use that
const Library::ArgumentChecks::Direction argDirection = settings.library.getArgDirection(tok, 1 + argnr, indirect);
if (argDirection == Library::ArgumentChecks::Direction::DIR_IN)
return false;
const bool requireNonNull = settings.library.isnullargbad(tok, 1 + argnr);
if (argDirection == Library::ArgumentChecks::Direction::DIR_OUT ||
argDirection == Library::ArgumentChecks::Direction::DIR_INOUT) {
if (indirect == 0 && isArray(tok1))
return true;
const bool requireInit = settings.library.isuninitargbad(tok, 1 + argnr);
// Assume that if the variable must be initialized then the indirection is 1
if (indirect > 0 && requireInit && requireNonNull)
return true;
}
if (Token::simpleMatch(tok->tokAt(-2), "std :: tie"))
return true;
// if the library says 0 is invalid
// => it is assumed that parameter is an in parameter (TODO: this is a bad heuristic)
if (indirect == 0 && requireNonNull)
return false;
// possible pass-by-reference => inconclusive
if (possiblyPassedByReference) {
if (inconclusive != nullptr)
*inconclusive = true;
return false;
}
// Safe guess: Assume that parameter is changed by function call
return true;
}
if (const Variable* var = tok->variable()) {
if (tok == var->nameToken() && (!var->isReference() || (var->isConst() && var->type() == tok1->type())) && (!var->isClass() || (var->valueType() && var->valueType()->container))) // const ref or passed to (copy) ctor
return false;
}
std::vector<const Variable*> args = getArgumentVars(tok, argnr);
bool conclusive = false;
for (const Variable *arg:args) {
if (!arg)
continue;
conclusive = true;
if (indirect > 0) {
if (arg->isPointer() && !(arg->valueType() && arg->valueType()->isConst(indirect)))
return true;
if (indirect > 1 && addressOf && arg->isPointer() && (!arg->valueType() || !arg->valueType()->isConst(indirect-1)))
return true;
if (arg->isArray() || (!arg->isPointer() && (!arg->valueType() || arg->valueType()->type == ValueType::UNKNOWN_TYPE)))
return true;
}
if (!arg->isConst() && arg->isReference())
return true;
}
if (addressOf && tok1->astParent()->isUnaryOp("&")) {
const Token* castToken = tok1->astParent();
while (castToken->astParent()->isCast())
castToken = castToken->astParent();
if (Token::Match(castToken->astParent(), ",|(") &&
castToken->valueType() &&
castToken->valueType()->isIntegral() &&
castToken->valueType()->pointer == 0)
return true;
}
if (!conclusive && inconclusive) {
*inconclusive = true;
}
return false;
}
bool isVariableChanged(const Token *tok, int indirect, const Settings &settings, int depth)
{
if (!isMutableExpression(tok))
return false;
if (indirect == 0 && isConstVarExpression(tok))
return false;
const Token *tok2 = tok;
int derefs = 0;
while ((tok2->astParent() && tok2->astParent()->isUnaryOp("*")) ||
(Token::simpleMatch(tok2->astParent(), ".") && !Token::Match(tok2->astParent()->astParent(), "[(,]")) ||
(tok2->astParent() && tok2->astParent()->isUnaryOp("&") && Token::simpleMatch(tok2->astParent()->astParent(), ".") && tok2->astParent()->astParent()->originalName()=="->") ||
(Token::simpleMatch(tok2->astParent(), "[") && tok2 == tok2->astParent()->astOperand1())) {
if (tok2->astParent() && (tok2->astParent()->isUnaryOp("*") || (astIsLHS(tok2) && tok2->astParent()->originalName() == "->")))
derefs++;
if (derefs > indirect)
break;
if (tok2->astParent() && tok2->astParent()->isUnaryOp("&") && Token::simpleMatch(tok2->astParent()->astParent(), ".") && tok2->astParent()->astParent()->originalName()=="->")
tok2 = tok2->astParent();
tok2 = tok2->astParent();
}
if (tok2->astParent() && tok2->astParent()->isUnaryOp("&")) {
const Token* parent = tok2->astParent();
while (parent->astParent() && parent->astParent()->isCast())
parent = parent->astParent();
if (parent->astParent() && parent->astParent()->isUnaryOp("*"))
tok2 = parent->astParent();
}
while ((Token::simpleMatch(tok2, ":") && Token::simpleMatch(tok2->astParent(), "?")) ||
(Token::simpleMatch(tok2->astParent(), ":") && Token::simpleMatch(tok2->astParent()->astParent(), "?")))
tok2 = tok2->astParent();
if (indirect == 0 && tok2->astParent() && tok2->astParent()->tokType() == Token::eIncDecOp)
return true;
auto skipRedundantPtrOp = [](const Token* tok, const Token* parent) {
const Token* gparent = parent ? parent->astParent() : nullptr;
while (parent && gparent && ((parent->isUnaryOp("*") && gparent->isUnaryOp("&")) || (parent->isUnaryOp("&") && gparent->isUnaryOp("*")))) {
tok = gparent;
parent = gparent->astParent();
if (parent)
gparent = parent->astParent();
}
return tok;
};
tok2 = skipRedundantPtrOp(tok2, tok2->astParent());
if (tok2->astParent() && tok2->astParent()->isAssignmentOp()) {
if (astIsLHS(tok2))
return true;
// Check if assigning to a non-const lvalue
const Variable * var = getLHSVariable(tok2->astParent());
if (var && var->isReference() && !var->isConst() && var->nameToken() &&
var->nameToken()->next() == tok2->astParent()) {
if (!var->isLocal() || isVariableChanged(var, settings, depth - 1))
return true;
}
}
const ValueType* vt = tok->variable() ? tok->variable()->valueType() : tok->valueType();
// Check addressof
if (tok2->astParent() && tok2->astParent()->isUnaryOp("&")) {
if (isVariableChanged(tok2->astParent(), indirect + 1, settings, depth - 1))
return true;
} else {
// If its already const then it cant be modified
if (vt && vt->isConst(indirect))
return false;
}
if (tok2->isCpp() && Token::Match(tok2->astParent(), ">>|&") && astIsRHS(tok2) && isLikelyStreamRead(tok2->astParent()))
return true;
if (isLikelyStream(tok2))
return true;
// Member function call
if (Token::Match(tok2->astParent(), ". %name%") && isFunctionCall(tok2->astParent()->next()) &&
tok2->astParent()->astOperand1() == tok2) {
// Member function cannot change what `this` points to
if (indirect == 0 && astIsPointer(tok))
return false;
const Token *ftok = tok2->astParent()->astOperand2();
const Token* const ctok = tok2->str() == "." ? tok2->astOperand2() : tok2;
if (astIsContainer(ctok) && ctok->valueType() && ctok->valueType()->container) {
const Library::Container* c = ctok->valueType()->container;
const Library::Container::Action action = c->getAction(ftok->str());
if (contains({Library::Container::Action::INSERT,
Library::Container::Action::ERASE,
Library::Container::Action::APPEND,
Library::Container::Action::CHANGE,
Library::Container::Action::CHANGE_CONTENT,
Library::Container::Action::CHANGE_INTERNAL,
Library::Container::Action::CLEAR,
Library::Container::Action::FIND,
Library::Container::Action::PUSH,
Library::Container::Action::POP,
Library::Container::Action::RESIZE},
action))
return true;
const Library::Container::Yield yield = c->getYield(ftok->str());
// If accessing element check if the element is changed
if (contains({Library::Container::Yield::ITEM, Library::Container::Yield::AT_INDEX}, yield))
return isVariableChanged(ftok->next(), indirect, settings, depth - 1);
if (contains({Library::Container::Yield::BUFFER,
Library::Container::Yield::BUFFER_NT,
Library::Container::Yield::START_ITERATOR,
Library::Container::Yield::ITERATOR},
yield)) {
return isVariableChanged(ftok->next(), indirect + 1, settings, depth - 1);
}
if (contains({Library::Container::Yield::SIZE,
Library::Container::Yield::EMPTY,
Library::Container::Yield::END_ITERATOR},
yield)) {
return false;
}
}
if (settings.library.isFunctionConst(ftok) || (astIsSmartPointer(tok) && ftok->str() == "get")) // TODO: replace with action/yield?
return false;
const Function * fun = ftok->function();
if (!fun)
return true;
return !fun->isConst();
}
// Member pointer
if (Token::Match(tok2->astParent(), ". * ( & %name% ::")) {
const Token* ftok = tok2->astParent()->linkAt(2)->previous();
// TODO: Check for pointer to member variable
if (!ftok->function() || !ftok->function()->isConst())
return true;
}
if (Token::Match(tok2->astParent(), ". * %name%")) // bailout
return true;
if (Token::simpleMatch(tok2, "[") && astIsContainer(tok) && vt && vt->container && vt->container->stdAssociativeLike)
return true;
const Token *ftok = tok2;
while (ftok && (!Token::Match(ftok, "[({]") || ftok->isCast()))
ftok = ftok->astParent();
if (ftok && Token::Match(ftok->link(), ")|} !!{")) {
if (ftok->str() == "(" && Token::simpleMatch(ftok->astOperand1(), "[")) // operator() on array element, bail out
return true;
const Token * ptok = tok2;
while (Token::Match(ptok->astParent(), ".|::|["))
ptok = ptok->astParent();
int pindirect = indirect;
if (indirect == 0 && astIsLHS(tok2) && Token::Match(ptok, ". %var%") && astIsPointer(ptok->next()))
pindirect = 1;
bool inconclusive = false;
bool isChanged = isVariableChangedByFunctionCall(ptok, pindirect, settings, &inconclusive);
isChanged |= inconclusive;
if (isChanged)
return true;
}
const Token *parent = tok2->astParent();
while (Token::Match(parent, ".|::"))
parent = parent->astParent();
if (parent && parent->tokType() == Token::eIncDecOp && (indirect == 0 || tok2 != tok))
return true;
// structured binding, nonconst reference variable in lhs
if (Token::Match(tok2->astParent(), ":|=") && tok2 == tok2->astParent()->astOperand2() && Token::simpleMatch(tok2->astParent()->previous(), "]")) {
const Token *typeStart = tok2->astParent()->linkAt(-1)->previous();
if (Token::simpleMatch(typeStart, "&"))
typeStart = typeStart->previous();
if (typeStart && Token::Match(typeStart->previous(), "[;{}(] auto &| [")) {
for (const Token *vartok = typeStart->tokAt(2); vartok != tok2; vartok = vartok->next()) {
if (vartok->varId()) {
const Variable* refvar = vartok->variable();
if (!refvar || (!refvar->isConst() && refvar->isReference()))
return true;
}
}
}
}
if (Token::simpleMatch(tok2->astParent(), ":") && tok2->astParent()->astParent() && Token::simpleMatch(tok2->astParent()->astParent()->previous(), "for (")) {
// TODO: Check if container is empty or not
if (astIsLHS(tok2))
return true;
const Token * varTok = tok2->astParent()->previous();
if (!varTok)
return false;
const Variable * loopVar = varTok->variable();
if (!loopVar)
return false;
if (!loopVar->isConst() && loopVar->isReference() && isVariableChanged(loopVar, settings, depth - 1))
return true;
return false;
}
if (indirect > 0) {
// check for `*(ptr + 1) = new_value` case
parent = tok2->astParent();
while (parent && ((parent->isArithmeticalOp() && parent->isBinaryOp()) || parent->isIncDecOp())) {
parent = parent->astParent();
}
if (Token::simpleMatch(parent, "*")) {
if (parent->astParent() && parent->astParent()->isAssignmentOp() &&
(parent->astParent()->astOperand1() == parent)) {
return true;
}
}
}
return false;
}
bool isVariableChanged(const Token *start, const Token *end, const nonneg int exprid, bool globalvar, const Settings &settings, int depth)
{
return findVariableChanged(start, end, 0, exprid, globalvar, settings, depth) != nullptr;
}
bool isVariableChanged(const Token *start, const Token *end, int indirect, const nonneg int exprid, bool globalvar, const Settings &settings, int depth)
{
return findVariableChanged(start, end, indirect, exprid, globalvar, settings, depth) != nullptr;
}
const Token* findExpression(const Token* start, const nonneg int exprid)
{
const Function* f = Scope::nestedInFunction(start->scope());
if (!f)
return nullptr;
const Scope* scope = f->functionScope;
if (!scope)
return nullptr;
for (const Token *tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
if (tok->exprId() != exprid)
continue;
return tok;
}
return nullptr;
}
const Token* findEscapeStatement(const Scope* scope, const Library* library)
{
if (!scope)
return nullptr;
for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
const Scope* escapeScope = tok->scope();
if (!escapeScope->isExecutable()) { // skip type definitions
tok = escapeScope->bodyEnd;
continue;
}
if (const Token* lambdaEnd = findLambdaEndToken(tok)) { // skip lambdas
tok = lambdaEnd;
continue;
}
if (!tok->isName())
continue;
if (isEscapeFunction(tok, library))
return tok;
if (!tok->isKeyword())
continue;
if (Token::Match(tok, "goto|return|throw")) // TODO: check try/catch, labels?
return tok;
if (!Token::Match(tok, "break|continue"))
continue;
const bool isBreak = tok->str()[0] == 'b';
while (escapeScope && escapeScope != scope) {
if (escapeScope->isLoopScope() || (isBreak && escapeScope->type == Scope::ScopeType::eSwitch))
return nullptr;
escapeScope = escapeScope->nestedIn;
}
return tok;
}
return nullptr;
}
// Thread-unsafe memoization
template<class F, class R=decltype(std::declval<F>()())>
static std::function<R()> memoize(F f)
{
bool init = false;
R result{};
return [=]() mutable -> R {
if (init)
return result;
result = f();
init = true;
return result;
};
}
template<class F,
REQUIRES("F must be a function that returns a Token class",
std::is_convertible<decltype(std::declval<F>()()), const Token*> )>
static bool isExpressionChangedAt(const F& getExprTok,
const Token* tok,
int indirect,
const nonneg int exprid,
bool globalvar,
const Settings& settings,
int depth)
{
if (depth < 0)
return true;
if (!isMutableExpression(tok))
return false;
if (tok->exprId() != exprid || (!tok->varId() && !tok->isName())) {
if (globalvar && Token::Match(tok, "%name% (") &&
(!(tok->function() && (tok->function()->isAttributePure() || tok->function()->isAttributeConst())))) {
if (!Token::simpleMatch(tok->astParent(), "."))
return true;
const auto yield = astContainerYield(tok->astParent()->astOperand1());
if (yield != Library::Container::Yield::SIZE && yield != Library::Container::Yield::EMPTY &&
yield != Library::Container::Yield::BUFFER && yield != Library::Container::Yield::BUFFER_NT)
// TODO: Is global variable really changed by function call?
return true;
}
int i = 1;
bool aliased = false;
// If we can't find the expression then assume it is an alias
auto expr = getExprTok();
if (!expr && !(tok->valueType() && tok->valueType()->pointer == 0 && tok->valueType()->reference == Reference::None))
aliased = true;
if (!aliased)
aliased = isAliasOf(tok, expr, &i);
if (!aliased)
return false;
if (isVariableChanged(tok, indirect + i, settings, depth))
return true;
// TODO: Try to traverse the lambda function
if (Token::Match(tok, "%var% ("))
return true;
return false;
}
return (isVariableChanged(tok, indirect, settings, depth));
}
bool isExpressionChangedAt(const Token* expr,
const Token* tok,
int indirect,
bool globalvar,
const Settings& settings,
int depth)
{
return isExpressionChangedAt([&] {
return expr;
}, tok, indirect, expr->exprId(), globalvar, settings, depth);
}
Token* findVariableChanged(Token *start, const Token *end, int indirect, const nonneg int exprid, bool globalvar, const Settings &settings, int depth)
{
if (!precedes(start, end))
return nullptr;
if (depth < 0)
return start;
auto getExprTok = memoize([&] {
return findExpression(start, exprid);
});
for (Token *tok = start; tok != end; tok = tok->next()) {
if (isExpressionChangedAt(getExprTok, tok, indirect, exprid, globalvar, settings, depth))
return tok;
}
return nullptr;
}
const Token* findVariableChanged(const Token *start, const Token *end, int indirect, const nonneg int exprid, bool globalvar, const Settings &settings, int depth)
{
return findVariableChanged(const_cast<Token*>(start), end, indirect, exprid, globalvar, settings, depth);
}
bool isVariableChanged(const Variable * var, const Settings &settings, int depth)
{
if (!var)
return false;
if (!var->scope())
return false;
const Token * start = var->declEndToken();
if (!start)
return false;
if (Token::Match(start, "; %varid% =", var->declarationId()))
start = start->tokAt(2);
if (Token::simpleMatch(start, "=")) {
const Token* next = nextAfterAstRightmostLeafGeneric(start);
if (next)
start = next;
}
return findExpressionChanged(var->nameToken(), start->next(), var->scope()->bodyEnd, settings, depth);
}
bool isVariablesChanged(const Token* start,
const Token* end,
int indirect,
const std::vector<const Variable*> &vars,
const Settings& settings)
{
std::set<int> varids;
std::transform(vars.cbegin(), vars.cend(), std::inserter(varids, varids.begin()), [](const Variable* var) {
return var->declarationId();
});
const bool globalvar = std::any_of(vars.cbegin(), vars.cend(), [](const Variable* var) {
return var->isGlobal();
});
for (const Token* tok = start; tok != end; tok = tok->next()) {
if (tok->varId() == 0 || varids.count(tok->varId()) == 0) {
if (globalvar && Token::Match(tok, "%name% ("))
// TODO: Is global variable really changed by function call?
return true;
continue;
}
if (isVariableChanged(tok, indirect, settings))
return true;
}
return false;
}
bool isThisChanged(const Token* tok, int indirect, const Settings& settings)
{
if ((Token::Match(tok->previous(), "%name% (") && !Token::simpleMatch(tok->astOperand1(), ".")) ||
Token::Match(tok->tokAt(-3), "this . %name% (")) {
if (tok->previous()->function()) {
return (!tok->previous()->function()->isConst() && !tok->previous()->function()->isStatic());
}
if (!tok->previous()->isKeyword() || tok->previous()->isOperatorKeyword()) {
return true;
}
}
if (isVariableChanged(tok, indirect, settings))
return true;
return false;
}
static const Token* findThisChanged(const Token* start, const Token* end, int indirect, const Settings& settings)
{
if (!precedes(start, end))
return nullptr;
for (const Token* tok = start; tok != end; tok = tok->next()) {
if (!exprDependsOnThis(tok))
continue;
if (isThisChanged(tok, indirect, settings))
return tok;
}
return nullptr;
}
template<class Find>
static const Token* findExpressionChangedImpl(const Token* expr,
const Token* start,
const Token* end,
const Settings& settings,
int depth,
Find find)
{
if (depth < 0)
return start;
if (!precedes(start, end))
return nullptr;
const Token* result = nullptr;
findAstNode(expr, [&](const Token* tok) {
if (exprDependsOnThis(tok)) {
result = findThisChanged(start, end, /*indirect*/ 0, settings);
if (result)
return true;
}
bool global = false;
if (tok->variable()) {
if (tok->variable()->isConst())
return false;
global = !tok->variable()->isLocal() && !tok->variable()->isArgument() &&
!(tok->variable()->isMember() && !tok->variable()->isStatic());
} else if (tok->isIncompleteVar() && !tok->isIncompleteConstant()) {
global = true;
}
if (tok->exprId() > 0 || global) {
const Token* modifedTok = find(start, end, [&](const Token* tok2) {
int indirect = 0;
if (const ValueType* vt = tok->valueType()) {
indirect = vt->pointer;
if (vt->type == ValueType::ITERATOR)
++indirect;
}
for (int i = 0; i <= indirect; ++i) {
if (isExpressionChangedAt(tok, tok2, i, global, settings, depth))
return true;
}
return false;
});
if (modifedTok) {
result = modifedTok;
return true;
}
}
return false;
});
return result;
}
namespace {
struct ExpressionChangedSimpleFind {
template<class F>
const Token* operator()(const Token* start, const Token* end, F f) const
{
return findToken(start, end, f);
}
};
struct ExpressionChangedSkipDeadCode {
const Library& library;
const std::function<std::vector<MathLib::bigint>(const Token* tok)>* evaluate;
ExpressionChangedSkipDeadCode(const Library& library,
const std::function<std::vector<MathLib::bigint>(const Token* tok)>& evaluate)
: library(library), evaluate(&evaluate)
{}
template<class F>
const Token* operator()(const Token* start, const Token* end, F f) const
{
return findTokenSkipDeadCode(library, start, end, f, *evaluate);
}
};
}
const Token* findExpressionChanged(const Token* expr,
const Token* start,
const Token* end,
const Settings& settings,
int depth)
{
return findExpressionChangedImpl(expr, start, end, settings, depth, ExpressionChangedSimpleFind{});
}
const Token* findExpressionChangedSkipDeadCode(const Token* expr,
const Token* start,
const Token* end,
const Settings& settings,
const std::function<std::vector<MathLib::bigint>(const Token* tok)>& evaluate,
int depth)
{
return findExpressionChangedImpl(
expr, start, end, settings, depth, ExpressionChangedSkipDeadCode{settings.library, evaluate});
}
const Token* getArgumentStart(const Token* ftok)
{
const Token* tok = ftok;
if (Token::Match(tok, "%name% (|{|)"))
tok = ftok->next();
while (Token::simpleMatch(tok, ")"))
tok = tok->next();
if (!Token::Match(tok, "(|{|["))
return nullptr;
const Token* startTok = tok->astOperand2();
if (!startTok && tok->next() != tok->link())
startTok = tok->astOperand1();
return startTok;
}
int numberOfArguments(const Token* ftok) {
return astCount(getArgumentStart(ftok), ",");
}
int numberOfArgumentsWithoutAst(const Token* start)
{
int arguments = 0;
const Token* openBracket = start->next();
while (Token::simpleMatch(openBracket, ")"))
openBracket = openBracket->next();
if (openBracket && openBracket->str()=="(" && openBracket->next() && openBracket->strAt(1)!=")") {
const Token* argument=openBracket->next();
while (argument) {
++arguments;
argument = argument->nextArgument();
}
}
return arguments;
}
std::vector<const Token*> getArguments(const Token* ftok) {
return astFlatten(getArgumentStart(ftok), ",");
}
int getArgumentPos(const Variable* var, const Function* f)
{
auto arg_it = std::find_if(f->argumentList.cbegin(), f->argumentList.cend(), [&](const Variable& v) {
return v.nameToken() == var->nameToken();
});
if (arg_it == f->argumentList.end())
return -1;
return std::distance(f->argumentList.cbegin(), arg_it);
}
const Token* getIteratorExpression(const Token* tok)
{
if (!tok)
return nullptr;
if (tok->isUnaryOp("*"))
return nullptr;
if (!tok->isName()) {
const Token* iter1 = getIteratorExpression(tok->astOperand1());
if (iter1)
return iter1;
if (tok->str() == "(")
return nullptr;
const Token* iter2 = getIteratorExpression(tok->astOperand2());
if (iter2)
return iter2;
} else if (Token::Match(tok, "begin|cbegin|rbegin|crbegin|end|cend|rend|crend (")) {
if (Token::Match(tok->previous(), ". %name% ( ) !!."))
return tok->previous()->astOperand1();
if (!Token::simpleMatch(tok->previous(), ".") && Token::Match(tok, "%name% ( !!)") &&
!Token::simpleMatch(tok->linkAt(1), ") ."))
return tok->next()->astOperand2();
}
return nullptr;
}
bool isIteratorPair(const std::vector<const Token*>& args)
{
if (args.size() != 2)
return false;
if (astIsPointer(args[0]) && astIsPointer(args[1]))
return true;
// Check if iterator is from same container
const Token* tok1 = nullptr;
const Token* tok2 = nullptr;
if (astIsIterator(args[0]) && astIsIterator(args[1])) {
tok1 = ValueFlow::getLifetimeObjValue(args[0]).tokvalue;
tok2 = ValueFlow::getLifetimeObjValue(args[1]).tokvalue;
if (!tok1 || !tok2)
return true;
} else {
tok1 = getIteratorExpression(args[0]);
tok2 = getIteratorExpression(args[1]);
}
if (tok1 && tok2)
return tok1->exprId() == tok2->exprId();
return tok1 || tok2;
}
const Token *findLambdaStartToken(const Token *last)
{
if (!last || !last->isCpp() || last->str() != "}")
return nullptr;
const Token* tok = last->link();
if (Token::simpleMatch(tok->astParent(), "("))
tok = tok->astParent();
if (Token::simpleMatch(tok->astParent(), "["))
return tok->astParent();
return nullptr;
}
template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
static T* findLambdaEndTokenGeneric(T* first)
{
auto maybeLambda = [](T* tok) -> bool {
while (Token::Match(tok, "*|%name%|::|>")) {
if (tok->link())
tok = tok->link()->previous();
else {
if (tok->str() == ">")
return true;
if (tok->str() == "new")
return false;
tok = tok->previous();
}
}
return true;
};
if (!first || !first->isCpp() || first->str() != "[")
return nullptr;
if (!maybeLambda(first->previous()))
return nullptr;
if (!Token::Match(first->link(), "] (|{|<"))
return nullptr;
const Token* roundOrCurly = first->link()->next();
if (roundOrCurly->link() && roundOrCurly->str() == "<")
roundOrCurly = roundOrCurly->link()->next();
if (first->astOperand1() != roundOrCurly)
return nullptr;
T * tok = first;
if (tok->astOperand1() && tok->astOperand1()->str() == "(")
tok = tok->astOperand1();
if (tok->astOperand1() && tok->astOperand1()->str() == "{")
return tok->astOperand1()->link();
return nullptr;
}
const Token* findLambdaEndToken(const Token* first)
{
return findLambdaEndTokenGeneric(first);
}
Token* findLambdaEndToken(Token* first)
{
return findLambdaEndTokenGeneric(first);
}
bool isLikelyStream(const Token *stream)
{
if (!stream)
return false;
if (!stream->isCpp())
return false;
if (!Token::Match(stream->astParent(), "&|<<|>>") || !stream->astParent()->isBinaryOp())
return false;
if (stream->astParent()->astOperand1() != stream)
return false;
return !astIsIntegral(stream, false);
}
bool isLikelyStreamRead(const Token *op)
{
if (!op)
return false;
if (!op->isCpp())
return false;
if (!Token::Match(op, "&|>>") || !op->isBinaryOp())
return false;
if (!Token::Match(op->astOperand2(), "%name%|.|*|[") && op->str() != op->astOperand2()->str())
return false;
const Token *parent = op;
while (parent->astParent() && parent->astParent()->str() == op->str())
parent = parent->astParent();
if (parent->astParent() && !Token::Match(parent->astParent(), "%oror%|&&|(|,|.|!|;|return"))
return false;
if (op->str() == "&" && parent->astParent())
return false;
if (!parent->astOperand1() || !parent->astOperand2())
return false;
return (!parent->astOperand1()->valueType() || !parent->astOperand1()->valueType()->isIntegral());
}
bool isCPPCast(const Token* tok)
{
return tok && Token::simpleMatch(tok->previous(), "> (") && tok->astOperand2() && tok->astOperand1() && isCPPCastKeyword(tok->astOperand1());
}
bool isConstVarExpression(const Token *tok, const std::function<bool(const Token*)>& skipPredicate)
{
if (!tok)
return false;
if (tok->str() == "?" && tok->astOperand2() && tok->astOperand2()->str() == ":") // ternary operator
return isConstVarExpression(tok->astOperand2()->astOperand1()) && isConstVarExpression(tok->astOperand2()->astOperand2()); // left and right of ":"
if (skipPredicate && skipPredicate(tok))
return false;
if (Token::simpleMatch(tok->previous(), "sizeof ("))
return true;
if (Token::Match(tok->previous(), "%name% (")) {
if (Token::simpleMatch(tok->astOperand1(), ".") && !isConstVarExpression(tok->astOperand1(), skipPredicate))
return false;
std::vector<const Token *> args = getArguments(tok);
if (args.empty() && tok->previous()->function() && tok->previous()->function()->isConstexpr())
return true;
return !args.empty() && std::all_of(args.cbegin(), args.cend(), [&](const Token* t) {
return isConstVarExpression(t, skipPredicate);
});
}
if (isCPPCast(tok)) {
return isConstVarExpression(tok->astOperand2(), skipPredicate);
}
if (Token::Match(tok, "( %type%"))
return isConstVarExpression(tok->astOperand1(), skipPredicate);
if (tok->str() == "::" && tok->hasKnownValue())
return isConstVarExpression(tok->astOperand2(), skipPredicate);
if (Token::Match(tok, "%cop%|[|.")) {
if (tok->astOperand1() && !isConstVarExpression(tok->astOperand1(), skipPredicate))
return false;
if (tok->astOperand2() && !isConstVarExpression(tok->astOperand2(), skipPredicate))
return false;
return true;
}
if (Token::Match(tok, "%bool%|%num%|%str%|%char%|nullptr|NULL"))
return true;
if (tok->isEnumerator())
return true;
if (tok->variable())
return tok->variable()->isConst() && tok->variable()->nameToken() && tok->variable()->nameToken()->hasKnownValue();
return false;
}
static ExprUsage getFunctionUsage(const Token* tok, int indirect, const Settings& settings)
{
const bool addressOf = tok->astParent() && tok->astParent()->isUnaryOp("&");
int argnr;
const Token* ftok = getTokenArgumentFunction(tok, argnr);
if (!ftok)
return ExprUsage::None;
const Function* func = ftok->function();
// variable init/constructor call?
if (!func && ftok->variable() && ftok == ftok->variable()->nameToken()) {
// STL types or containers don't initialize external variables
if (ftok->variable()->isStlType() || (ftok->variable()->valueType() && ftok->variable()->valueType()->container))
return ExprUsage::Used;
// TODO: resolve multiple constructors
if (ftok->variable()->type() && ftok->variable()->type()->classScope) {
const int nCtor = ftok->variable()->type()->classScope->numConstructors;
if (nCtor == 0)
return ExprUsage::Used;
if (nCtor == 1) {
const Scope* scope = ftok->variable()->type()->classScope;
auto it = std::find_if(scope->functionList.begin(), scope->functionList.end(), [](const Function& f) {
return f.isConstructor();
});
if (it != scope->functionList.end())
func = &*it;
}
}
}
if (func) {
std::vector<const Variable*> args = getArgumentVars(ftok, argnr);
for (const Variable* arg : args) {
if (!arg)
continue;
if (arg->isReference() || (arg->isPointer() && indirect == 1)) {
if (!func->hasBody())
return ExprUsage::PassedByReference;
for (const Token* bodytok = func->functionScope->bodyStart; bodytok != func->functionScope->bodyEnd; bodytok = bodytok->next()) {
if (bodytok->variable() == arg) {
if (arg->isReference())
return ExprUsage::PassedByReference;
if (Token::Match(bodytok->astParent(), "%comp%|!"))
return ExprUsage::NotUsed;
return ExprUsage::PassedByReference;
}
}
return ExprUsage::NotUsed;
}
}
if (!args.empty() && indirect == 0 && !addressOf)
return ExprUsage::Used;
} else if (ftok->isControlFlowKeyword()) {
return ExprUsage::Used;
} else if (ftok->str() == "{") {
return indirect == 0 ? ExprUsage::Used : ExprUsage::Inconclusive;
} else {
const bool isnullbad = settings.library.isnullargbad(ftok, argnr + 1);
if (indirect == 0 && astIsPointer(tok) && !addressOf && isnullbad)
return ExprUsage::Used;
bool hasIndirect = false;
const bool isuninitbad = settings.library.isuninitargbad(ftok, argnr + 1, indirect, &hasIndirect);
if (isuninitbad && (!addressOf || isnullbad))
return ExprUsage::Used;
}
return ExprUsage::Inconclusive;
}
bool isLeafDot(const Token* tok)
{
if (!tok)
return false;
const Token * parent = tok->astParent();
if (!Token::simpleMatch(parent, "."))
return false;
if (parent->astOperand2() == tok && !Token::simpleMatch(parent->astParent(), "."))
return true;
return isLeafDot(parent);
}
ExprUsage getExprUsage(const Token* tok, int indirect, const Settings& settings)
{
const Token* parent = tok->astParent();
if (indirect > 0 && parent) {
while (Token::simpleMatch(parent, "[") && parent->astParent())
parent = parent->astParent();
if (Token::Match(parent, "%assign%") && (astIsRHS(tok) || astIsLHS(parent->astOperand1())))
return ExprUsage::NotUsed;
if (Token::Match(parent, "++|--"))
return ExprUsage::NotUsed;
if (parent->isConstOp())
return ExprUsage::NotUsed;
if (parent->isCast())
return ExprUsage::NotUsed;
if (Token::simpleMatch(parent, ":") && Token::simpleMatch(parent->astParent(), "?"))
return getExprUsage(parent->astParent(), indirect, settings);
if (isUsedAsBool(tok, settings))
return ExprUsage::NotUsed;
}
if (tok->isUnaryOp("&") && !parent)
return ExprUsage::NotUsed;
if (indirect == 0) {
if (Token::Match(parent, "%cop%|%assign%|++|--") && parent->str() != "=" &&
!parent->isUnaryOp("&") &&
!(astIsRHS(tok) && isLikelyStreamRead(parent)))
return ExprUsage::Used;
if (isLeafDot(tok)) {
const Token* op = parent->astParent();
while (Token::simpleMatch(op, "."))
op = op->astParent();
if (Token::Match(op, "%assign%|++|--")) {
if (op->str() == "=") {
if (precedes(tok, op))
return ExprUsage::NotUsed;
} else
return ExprUsage::Used;
}
}
if (Token::simpleMatch(parent, "=") && astIsRHS(tok)) {
const Token* const lhs = parent->astOperand1();
if (lhs && lhs->variable() && lhs->variable()->isReference() && lhs == lhs->variable()->nameToken())
return ExprUsage::NotUsed;
return ExprUsage::Used;
}
// Function call or index
if (((Token::simpleMatch(parent, "(") && !parent->isCast()) || (Token::simpleMatch(parent, "[") && tok->valueType())) &&
(astIsLHS(tok) || Token::simpleMatch(parent, "( )")))
return ExprUsage::Used;
}
return getFunctionUsage(tok, indirect, settings);
}
static void getLHSVariablesRecursive(std::vector<const Variable*>& vars, const Token* tok)
{
if (!tok)
return;
if (vars.empty() && Token::Match(tok, "*|&|&&|[")) {
getLHSVariablesRecursive(vars, tok->astOperand1());
if (!vars.empty() || Token::simpleMatch(tok, "["))
return;
getLHSVariablesRecursive(vars, tok->astOperand2());
} else if (Token::Match(tok->previous(), "this . %var%")) {
getLHSVariablesRecursive(vars, tok->next());
} else if (Token::simpleMatch(tok, ".")) {
getLHSVariablesRecursive(vars, tok->astOperand1());
getLHSVariablesRecursive(vars, tok->astOperand2());
} else if (Token::simpleMatch(tok, "::")) {
getLHSVariablesRecursive(vars, tok->astOperand2());
} else if (tok->variable()) {
vars.push_back(tok->variable());
}
}
std::vector<const Variable*> getLHSVariables(const Token* tok)
{
std::vector<const Variable*> result;
if (!Token::Match(tok, "%assign%|(|{"))
return result;
if (!tok->astOperand1())
return result;
if (tok->astOperand1()->varId() > 0 && tok->astOperand1()->variable())
return {tok->astOperand1()->variable()};
getLHSVariablesRecursive(result, tok->astOperand1());
return result;
}
static const Token* getLHSVariableRecursive(const Token* tok)
{
if (!tok)
return nullptr;
if (Token::Match(tok, "*|&|&&|[")) {
const Token* vartok = getLHSVariableRecursive(tok->astOperand1());
if ((vartok && vartok->variable()) || Token::simpleMatch(tok, "["))
return vartok;
return getLHSVariableRecursive(tok->astOperand2());
}
if (Token::Match(tok->previous(), "this . %var%"))
return tok->next();
return tok;
}
const Variable *getLHSVariable(const Token *tok)
{
if (!tok || !tok->isAssignmentOp())
return nullptr;
if (!tok->astOperand1())
return nullptr;
if (tok->astOperand1()->varId() > 0 && tok->astOperand1()->variable())
return tok->astOperand1()->variable();
const Token* vartok = getLHSVariableRecursive(tok->astOperand1());
if (!vartok)
return nullptr;
return vartok->variable();
}
const Token* getLHSVariableToken(const Token* tok)
{
if (!Token::Match(tok, "%assign%"))
return nullptr;
if (!tok->astOperand1())
return nullptr;
if (tok->astOperand1()->varId() > 0)
return tok->astOperand1();
const Token* vartok = getLHSVariableRecursive(tok->astOperand1());
if (vartok && vartok->variable() && vartok->variable()->nameToken() == vartok)
return vartok;
return tok->astOperand1();
}
const Token* findAllocFuncCallToken(const Token *expr, const Library &library)
{
if (!expr)
return nullptr;
if (Token::Match(expr, "[+-]")) {
const Token *tok1 = findAllocFuncCallToken(expr->astOperand1(), library);
return tok1 ? tok1 : findAllocFuncCallToken(expr->astOperand2(), library);
}
if (expr->isCast())
return findAllocFuncCallToken(expr->astOperand2() ? expr->astOperand2() : expr->astOperand1(), library);
if (Token::Match(expr->previous(), "%name% (") && library.getAllocFuncInfo(expr->astOperand1()))
return expr->astOperand1();
return (Token::simpleMatch(expr, "new") && expr->astOperand1()) ? expr : nullptr;
}
bool isNullOperand(const Token *expr)
{
if (!expr)
return false;
if (expr->isCpp() && Token::Match(expr, "static_cast|const_cast|dynamic_cast|reinterpret_cast <"))
expr = expr->astParent();
else if (!expr->isCast())
return Token::Match(expr, "NULL|nullptr");
if (expr->valueType() && expr->valueType()->pointer == 0)
return false;
const Token *castOp = expr->astOperand2() ? expr->astOperand2() : expr->astOperand1();
return Token::Match(castOp, "NULL|nullptr") || (MathLib::isInt(castOp->str()) && MathLib::isNullValue(castOp->str()));
}
bool isGlobalData(const Token *expr)
{
// function call that returns reference => assume global data
if (expr && expr->str() == "(" && expr->valueType() && expr->valueType()->reference != Reference::None) {
if (expr->isBinaryOp())
return true;
if (expr->astOperand1() && precedes(expr->astOperand1(), expr))
return true;
}
bool globalData = false;
bool var = false;
visitAstNodes(expr,
[expr, &globalData, &var](const Token *tok) {
if (tok->varId())
var = true;
if (tok->varId() && !tok->variable()) {
// Bailout, this is probably global
globalData = true;
return ChildrenToVisit::none;
}
if (tok->originalName() == "->") {
// TODO check if pointer points at local data
globalData = true;
return ChildrenToVisit::none;
}
if (Token::Match(tok, "[*[]") && tok->astOperand1() && tok->astOperand1()->variable()) {
// TODO check if pointer points at local data
const Variable *lhsvar = tok->astOperand1()->variable();
const ValueType *lhstype = tok->astOperand1()->valueType();
if (lhsvar->isPointer()) {
globalData = true;
return ChildrenToVisit::none;
}
if (lhsvar->isArgument() && lhsvar->isArray()) {
globalData = true;
return ChildrenToVisit::none;
}
if (lhsvar->isArgument() && (!lhstype || (lhstype->type <= ValueType::Type::VOID && !lhstype->container))) {
globalData = true;
return ChildrenToVisit::none;
}
}
if (tok->varId() == 0 && tok->isName() && tok->strAt(-1) != ".") {
globalData = true;
return ChildrenToVisit::none;
}
if (tok->variable()) {
// TODO : Check references
if (tok->variable()->isReference() && tok != tok->variable()->nameToken()) {
globalData = true;
return ChildrenToVisit::none;
}
if (tok->variable()->isExtern()) {
globalData = true;
return ChildrenToVisit::none;
}
if (tok->strAt(-1) != "." && !tok->variable()->isLocal() && !tok->variable()->isArgument()) {
globalData = true;
return ChildrenToVisit::none;
}
if (tok->variable()->isArgument() && tok->variable()->isPointer() && tok != expr) {
globalData = true;
return ChildrenToVisit::none;
}
if (tok->variable()->isPointerArray()) {
globalData = true;
return ChildrenToVisit::none;
}
}
// Unknown argument type => it might be some reference type..
if (tok->isCpp() && tok->str() == "." && tok->astOperand1() && tok->astOperand1()->variable() && !tok->astOperand1()->valueType()) {
globalData = true;
return ChildrenToVisit::none;
}
if (Token::Match(tok, ".|["))
return ChildrenToVisit::op1;
return ChildrenToVisit::op1_and_op2;
});
return globalData || !var;
}
bool isUnevaluated(const Token *tok)
{
return Token::Match(tok, "alignof|_Alignof|_alignof|__alignof|__alignof__|decltype|offsetof|sizeof|typeid|typeof|__typeof__ (");
}
static std::set<MathLib::bigint> getSwitchValues(const Token *startbrace, bool &hasDefault)
{
std::set<MathLib::bigint> values;
const Token *endbrace = startbrace->link();
if (!endbrace)
return values;
hasDefault = false;
for (const Token *tok = startbrace->next(); tok && tok != endbrace; tok = tok->next()) {
if (Token::simpleMatch(tok, "{") && tok->scope()->type == Scope::ScopeType::eSwitch) {
tok = tok->link();
continue;
}
if (Token::simpleMatch(tok, "default")) {
hasDefault = true;
break;
}
if (Token::simpleMatch(tok, "case")) {
const Token *valueTok = tok->astOperand1();
if (valueTok->hasKnownIntValue())
values.insert(valueTok->getKnownIntValue());
continue;
}
}
return values;
}
bool isExhaustiveSwitch(const Token *startbrace)
{
if (!startbrace || !Token::simpleMatch(startbrace->previous(), ") {") || startbrace->scope()->type != Scope::ScopeType::eSwitch)
return false;
const Token *rpar = startbrace->previous();
const Token *lpar = rpar->link();
const Token *condition = lpar->astOperand2();
if (!condition->valueType())
return true;
bool hasDefault = false;
const std::set<MathLib::bigint> switchValues = getSwitchValues(startbrace, hasDefault);
if (hasDefault)
return true;
if (condition->valueType()->type == ValueType::Type::BOOL)
return switchValues.count(0) && switchValues.count(1);
if (condition->valueType()->isEnum()) {
const std::vector<Enumerator> &enumList = condition->valueType()->typeScope->enumeratorList;
return std::all_of(enumList.cbegin(), enumList.cend(), [&](const Enumerator &e) {
return !e.value_known || switchValues.count(e.value);
});
}
return false;
}
bool isUnreachableOperand(const Token *tok)
{
for (;;)
{
const Token *parent = tok->astParent();
if (!parent)
break;
if (parent->isBinaryOp()) {
const bool left = tok == parent->astOperand1();
const Token *sibling = left ? parent->astOperand2() : parent->astOperand1();
// logical and
if (Token::simpleMatch(parent, "&&") && !left && sibling->hasKnownIntValue()
&& !sibling->getKnownIntValue())
return true;
// logical or
if (Token::simpleMatch(parent, "||") && !left && sibling->hasKnownIntValue()
&& sibling->getKnownIntValue())
return true;
// ternary
if (Token::simpleMatch(parent, ":") && Token::simpleMatch(parent->astParent(), "?")) {
const Token *condTok = parent->astParent()->astOperand1();
if (condTok->hasKnownIntValue() && static_cast<bool>(condTok->getKnownIntValue()) != left)
return true;
}
}
tok = parent;
}
return false;
}
static bool unknownLeafValuesAreTemplateArgs(const Token *tok)
{
if (!tok)
return true;
if (!tok->astOperand1() && !tok->astOperand2())
return tok->isTemplateArg() || tok->hasKnownIntValue();
return unknownLeafValuesAreTemplateArgs(tok->astOperand1())
&& unknownLeafValuesAreTemplateArgs(tok->astOperand2());
}
static const Token *skipUnreachableIfBranch(const Token *tok)
{
const Token *condTok = tok->linkAt(-1);
if (!condTok)
return tok;
if (!Token::simpleMatch(condTok->tokAt(-1), "if") && !Token::simpleMatch(condTok->tokAt(-2), "if constexpr"))
return tok;
condTok = condTok->astOperand2();
if (!condTok)
return tok;
if ((condTok->hasKnownIntValue() && condTok->getKnownIntValue() == 0)
|| (unknownLeafValuesAreTemplateArgs(condTok) && condTok->getValue(0))) {
tok = tok->link();
}
return tok;
}
static const Token *skipUnreachableElseBranch(const Token *tok)
{
if (!Token::simpleMatch(tok->tokAt(-2), "} else {"))
return tok;
const Token *condTok = tok->linkAt(-2);
if (!condTok)
return tok;
condTok = condTok->linkAt(-1);
if (!condTok)
return tok;
if (!Token::simpleMatch(condTok->tokAt(-1), "if (") && !Token::simpleMatch(condTok->tokAt(-2), "if constexpr ("))
return tok;
condTok = condTok->astOperand2();
if ((condTok->hasKnownIntValue() && condTok->getKnownIntValue() != 0)
|| (unknownLeafValuesAreTemplateArgs(condTok) && condTok->getValueNE(0))) {
tok = tok->link();
}
return tok;
}
const Token *skipUnreachableBranch(const Token *tok)
{
if (!Token::simpleMatch(tok, "{"))
return tok;
if (tok->scope()->type == Scope::ScopeType::eIf) {
return skipUnreachableIfBranch(tok);
}
if (tok->scope()->type == Scope::ScopeType::eElse) {
return skipUnreachableElseBranch(tok);
}
return tok;
}
| null |
902 | cpp | cppcheck | vfvalue.h | lib/vfvalue.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef vfvalueH
#define vfvalueH
//---------------------------------------------------------------------------
#include "config.h"
#include "errortypes.h"
#include "mathlib.h"
#include <cassert>
#include <cmath>
#include <cstdint>
#include <functional>
#include <string>
#include <type_traits>
#include <vector>
FORCE_WARNING_CLANG_PUSH("-Wpadded")
class Token;
namespace ValueFlow
{
class CPPCHECKLIB Value {
public:
enum class Bound : std::uint8_t { Upper, Lower, Point };
explicit Value(MathLib::bigint val = 0, Bound b = Bound::Point) :
bound(b),
safe(false),
conditional(false),
macro(false),
defaultArg(false),
intvalue(val),
varvalue(val),
wideintvalue(val)
{}
Value(const Token* c, MathLib::bigint val, Bound b = Bound::Point);
static Value unknown() {
Value v;
v.valueType = ValueType::UNINIT;
return v;
}
bool equalValue(const ValueFlow::Value& rhs) const {
if (valueType != rhs.valueType)
return false;
switch (valueType) {
case ValueType::INT:
case ValueType::CONTAINER_SIZE:
case ValueType::BUFFER_SIZE:
case ValueType::ITERATOR_START:
case ValueType::ITERATOR_END:
if (intvalue != rhs.intvalue)
return false;
break;
case ValueType::TOK:
if (tokvalue != rhs.tokvalue)
return false;
break;
case ValueType::FLOAT:
if (floatValue > rhs.floatValue || floatValue < rhs.floatValue || std::signbit(floatValue) != std::signbit(rhs.floatValue))
return false;
break;
case ValueType::MOVED:
if (moveKind != rhs.moveKind)
return false;
break;
case ValueType::UNINIT:
break;
case ValueType::LIFETIME:
if (tokvalue != rhs.tokvalue)
return false;
break;
case ValueType::SYMBOLIC:
if (!sameToken(tokvalue, rhs.tokvalue))
return false;
if (intvalue != rhs.intvalue)
return false;
break;
}
return true;
}
template<class T, class F>
static void visitValue(T& self, F f) {
switch (self.valueType) {
case ValueType::INT:
case ValueType::SYMBOLIC:
case ValueType::BUFFER_SIZE:
case ValueType::CONTAINER_SIZE:
case ValueType::ITERATOR_START:
case ValueType::ITERATOR_END: {
f(self.intvalue);
break;
}
case ValueType::FLOAT: {
f(self.floatValue);
break;
}
case ValueType::UNINIT:
case ValueType::TOK:
case ValueType::LIFETIME:
case ValueType::MOVED:
break;
}
}
struct compareVisitor {
struct innerVisitor {
template<class Compare, class T, class U>
void operator()(bool& result, Compare compare, T x, U y) const {
result = compare(x, y);
}
};
template<class Compare, class T>
void operator()(bool& result, const Value& rhs, Compare compare, T x) const {
visitValue(rhs,
std::bind(innerVisitor{}, std::ref(result), std::move(compare), x, std::placeholders::_1));
}
};
template<class Compare>
bool compareValue(const Value& rhs, Compare compare) const {
assert((!this->isSymbolicValue() && !rhs.isSymbolicValue()) ||
(this->valueType == rhs.valueType && sameToken(this->tokvalue, rhs.tokvalue)));
bool result = false;
visitValue(
*this,
std::bind(compareVisitor{}, std::ref(result), std::ref(rhs), std::move(compare), std::placeholders::_1));
return result;
}
bool operator==(const Value &rhs) const {
if (!equalValue(rhs))
return false;
return varvalue == rhs.varvalue &&
condition == rhs.condition &&
varId == rhs.varId &&
conditional == rhs.conditional &&
defaultArg == rhs.defaultArg &&
indirect == rhs.indirect &&
valueKind == rhs.valueKind;
}
bool operator!=(const Value &rhs) const {
return !(*this == rhs);
}
template<class T, REQUIRES("T must be an arithmetic type", std::is_arithmetic<T> )>
bool equalTo(const T& x) const {
bool result = false;
visitValue(*this, std::bind(equalVisitor{}, std::ref(result), x, std::placeholders::_1));
return result;
}
void decreaseRange() {
if (bound == Bound::Lower)
visitValue(*this, increment{});
else if (bound == Bound::Upper)
visitValue(*this, decrement{});
}
void invertBound() {
if (bound == Bound::Lower)
bound = Bound::Upper;
else if (bound == Bound::Upper)
bound = Bound::Lower;
}
void invertRange() {
invertBound();
decreaseRange();
}
void assumeCondition(const Token* tok);
std::string infoString() const;
std::string toString() const;
enum class ValueType : std::uint8_t {
INT,
TOK,
FLOAT,
MOVED,
UNINIT,
CONTAINER_SIZE,
LIFETIME,
BUFFER_SIZE,
ITERATOR_START,
ITERATOR_END,
SYMBOLIC
} valueType = ValueType::INT;
bool isIntValue() const {
return valueType == ValueType::INT;
}
bool isTokValue() const {
return valueType == ValueType::TOK;
}
bool isFloatValue() const {
return valueType == ValueType::FLOAT;
}
bool isMovedValue() const {
return valueType == ValueType::MOVED;
}
bool isUninitValue() const {
return valueType == ValueType::UNINIT;
}
bool isContainerSizeValue() const {
return valueType == ValueType::CONTAINER_SIZE;
}
bool isLifetimeValue() const {
return valueType == ValueType::LIFETIME;
}
bool isBufferSizeValue() const {
return valueType == ValueType::BUFFER_SIZE;
}
bool isIteratorValue() const {
return valueType == ValueType::ITERATOR_START || valueType == ValueType::ITERATOR_END;
}
bool isIteratorStartValue() const {
return valueType == ValueType::ITERATOR_START;
}
bool isIteratorEndValue() const {
return valueType == ValueType::ITERATOR_END;
}
bool isSymbolicValue() const {
return valueType == ValueType::SYMBOLIC;
}
bool isLocalLifetimeValue() const {
return valueType == ValueType::LIFETIME && lifetimeScope == LifetimeScope::Local;
}
bool isArgumentLifetimeValue() const {
return valueType == ValueType::LIFETIME && lifetimeScope == LifetimeScope::Argument;
}
bool isSubFunctionLifetimeValue() const {
return valueType == ValueType::LIFETIME && lifetimeScope == LifetimeScope::SubFunction;
}
bool isNonValue() const {
return isMovedValue() || isUninitValue() || isLifetimeValue();
}
/** The value bound */
Bound bound = Bound::Point;
/** value relies on safe checking */
// cppcheck-suppress premium-misra-cpp-2023-12.2.1
bool safe : 1;
/** Conditional value */
bool conditional : 1;
/** Value is is from an expanded macro */
bool macro : 1;
/** Is this value passed as default parameter to the function? */
bool defaultArg : 1;
long long : 4; // padding
/** kind of moved */
enum class MoveKind : std::uint8_t { NonMovedVariable, MovedVariable, ForwardedVariable } moveKind = MoveKind::NonMovedVariable;
enum class LifetimeScope : std::uint8_t { Local, Argument, SubFunction, ThisPointer, ThisValue } lifetimeScope = LifetimeScope::Local;
enum class LifetimeKind : std::uint8_t {
// Pointer points to a member of lifetime
Object,
// A member of object points to the lifetime
SubObject,
// Lambda has captured lifetime(similar to SubObject)
Lambda,
// Iterator points to the lifetime of a container(similar to Object)
Iterator,
// A pointer that holds the address of the lifetime
Address
} lifetimeKind = LifetimeKind::Object;
/** How known is this value */
enum class ValueKind : std::uint8_t {
/** This value is possible, other unlisted values may also be possible */
Possible,
/** Only listed values are possible */
Known,
/** Inconclusive */
Inconclusive,
/** Listed values are impossible */
Impossible
} valueKind = ValueKind::Possible;
std::int8_t indirect{}; // TODO: can we reduce the size?
/** int value (or sometimes bool value?) */
MathLib::bigint intvalue{};
/** token value - the token that has the value. this is used for pointer aliases, strings, etc. */
const Token* tokvalue{};
/** float value */
double floatValue{};
/** For calculated values - variable value that calculated value depends on */
MathLib::bigint varvalue{};
/** Condition that this value depends on */
const Token* condition{};
ErrorPath errorPath;
ErrorPath debugPath; // TODO: make lighter by default
/** For calculated values - varId that calculated value depends on */
nonneg int varId{};
enum class UnknownFunctionReturn : std::uint8_t {
no, // not unknown function return
outOfMemory, // out of memory
outOfResources, // out of resource
other // other
};
UnknownFunctionReturn unknownFunctionReturn{UnknownFunctionReturn::no};
long long : 24; // padding
/** Path id */
MathLib::bigint path{};
/** int value before implicit truncation */
MathLib::bigint wideintvalue{};
std::vector<std::string> subexpressions;
// Set to where a lifetime is captured by value
const Token* capturetok{};
RET_NONNULL static const char* toString(MoveKind moveKind);
RET_NONNULL static const char* toString(LifetimeKind lifetimeKind);
RET_NONNULL static const char* toString(LifetimeScope lifetimeScope);
RET_NONNULL static const char* toString(Bound bound);
void setKnown() {
valueKind = ValueKind::Known;
}
bool isKnown() const {
return valueKind == ValueKind::Known;
}
void setPossible() {
valueKind = ValueKind::Possible;
}
bool isPossible() const {
return valueKind == ValueKind::Possible;
}
bool isImpossible() const {
return valueKind == ValueKind::Impossible;
}
void setImpossible() {
valueKind = ValueKind::Impossible;
}
void setInconclusive(bool inconclusive = true) {
if (inconclusive)
valueKind = ValueKind::Inconclusive;
}
bool isInconclusive() const {
return valueKind == ValueKind::Inconclusive;
}
void changeKnownToPossible() {
if (isKnown())
valueKind = ValueKind::Possible;
}
bool errorSeverity() const {
return !condition && !defaultArg;
}
static bool sameToken(const Token* tok1, const Token* tok2);
private:
struct equalVisitor {
template<class T, class U>
void operator()(bool& result, T x, U y) const {
result = !(x > y || x < y);
}
};
struct increment {
template<class T>
void operator()(T& x) const {
x++;
}
};
struct decrement {
template<class T>
void operator()(T& x) const {
x--;
}
};
};
}
FORCE_WARNING_CLANG_POP
#endif // vfvalueH
| null |
903 | cpp | cppcheck | fwdanalysis.h | lib/fwdanalysis.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef fwdanalysisH
#define fwdanalysisH
//---------------------------------------------------------------------------
#include "config.h"
#include <cstdint>
#include <set>
#include <vector>
class Token;
class Settings;
/**
* Forward data flow analysis for checks
* - unused value
* - redundant assignment
* - valueflow analysis
*/
class FwdAnalysis {
public:
explicit FwdAnalysis(const Settings &settings) : mSettings(settings) {}
bool hasOperand(const Token *tok, const Token *lhs) const;
/**
* Check if "expr" is reassigned. The "expr" can be a tree (x.y[12]).
* @param expr Symbolic expression to perform forward analysis for
* @param startToken First token in forward analysis
* @param endToken Last token in forward analysis
* @return Token where expr is reassigned. If it's not reassigned then nullptr is returned.
*/
const Token *reassign(const Token *expr, const Token *startToken, const Token *endToken);
/**
* Check if "expr" is used. The "expr" can be a tree (x.y[12]).
* @param expr Symbolic expression to perform forward analysis for
* @param startToken First token in forward analysis
* @param endToken Last token in forward analysis
* @return true if expr is used.
*/
bool unusedValue(const Token *expr, const Token *startToken, const Token *endToken);
struct KnownAndToken {
bool known{};
const Token* token{};
};
/** Is there some possible alias for given expression */
bool possiblyAliased(const Token *expr, const Token *startToken) const;
std::set<nonneg int> getExprVarIds(const Token* expr, bool* localOut = nullptr, bool* unknownVarIdOut = nullptr) const;
private:
static bool isEscapedAlias(const Token* expr);
/** Result of forward analysis */
struct Result {
enum class Type : std::uint8_t { NONE, READ, WRITE, BREAK, RETURN, BAILOUT } type;
explicit Result(Type type) : type(type) {}
Result(Type type, const Token *token) : type(type), token(token) {}
const Token* token{};
};
Result check(const Token *expr, const Token *startToken, const Token *endToken);
Result checkRecursive(const Token *expr, const Token *startToken, const Token *endToken, const std::set<nonneg int> &exprVarIds, bool local, bool inInnerClass, int depth=0);
const Settings &mSettings;
enum class What : std::uint8_t { Reassign, UnusedValue, ValueFlow } mWhat = What::Reassign;
std::vector<KnownAndToken> mValueFlow;
bool mValueFlowKnown = true;
};
#endif // fwdanalysisH
| null |
904 | cpp | cppcheck | summaries.h | lib/summaries.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef summariesH
#define summariesH
//---------------------------------------------------------------------------
#include "config.h"
#include <set>
#include <string>
class Tokenizer;
namespace Summaries {
CPPCHECKLIB std::string create(const Tokenizer &tokenizer, const std::string &cfg);
CPPCHECKLIB void loadReturn(const std::string &buildDir, std::set<std::string> &summaryReturn);
}
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
| null |
905 | cpp | cppcheck | checkio.h | lib/checkio.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef checkioH
#define checkioH
//---------------------------------------------------------------------------
#include "check.h"
#include "config.h"
#include "tokenize.h"
#include <cstdint>
#include <ostream>
#include <string>
class Function;
class Settings;
class Token;
class Variable;
class ErrorLogger;
enum class Severity : std::uint8_t;
/// @addtogroup Checks
/// @{
/** @brief %Check input output operations. */
class CPPCHECKLIB CheckIO : public Check {
friend class TestIO;
public:
/** @brief This constructor is used when registering CheckIO */
CheckIO() : Check(myName()) {}
private:
/** @brief This constructor is used when running checks. */
CheckIO(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {}
/** @brief Run checks on the normal token list */
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
CheckIO checkIO(&tokenizer, &tokenizer.getSettings(), errorLogger);
checkIO.checkWrongPrintfScanfArguments();
checkIO.checkCoutCerrMisusage();
checkIO.checkFileUsage();
checkIO.invalidScanf();
}
/** @brief %Check for missusage of std::cout */
void checkCoutCerrMisusage();
/** @brief %Check usage of files*/
void checkFileUsage();
/** @brief scanf can crash if width specifiers are not used */
void invalidScanf();
/** @brief %Checks type and number of arguments given to functions like printf or scanf*/
void checkWrongPrintfScanfArguments();
class ArgumentInfo {
public:
ArgumentInfo(const Token *arg, const Settings &settings, bool _isCPP);
~ArgumentInfo();
ArgumentInfo(const ArgumentInfo &) = delete;
ArgumentInfo& operator= (const ArgumentInfo &) = delete;
bool isArrayOrPointer() const;
bool isComplexType() const;
bool isKnownType() const;
bool isStdVectorOrString();
bool isStdContainer(const Token *tok);
bool isLibraryType(const Settings &settings) const;
const Variable* variableInfo{};
const Token* typeToken{};
const Function* functionInfo{};
Token* tempToken{};
bool element{};
bool _template{};
bool address{};
bool isCPP{};
};
void checkFormatString(const Token * tok,
const Token * formatStringTok,
const Token * argListTok,
bool scan,
bool scanf_s);
// Reporting errors..
void coutCerrMisusageError(const Token* tok, const std::string& streamName);
void fflushOnInputStreamError(const Token *tok, const std::string &varname);
void ioWithoutPositioningError(const Token *tok);
void readWriteOnlyFileError(const Token *tok);
void writeReadOnlyFileError(const Token *tok);
void useClosedFileError(const Token *tok);
void seekOnAppendedFileError(const Token *tok);
void incompatibleFileOpenError(const Token *tok, const std::string &filename);
void invalidScanfError(const Token *tok);
void wrongPrintfScanfArgumentsError(const Token* tok,
const std::string &functionName,
nonneg int numFormat,
nonneg int numFunction);
void wrongPrintfScanfPosixParameterPositionError(const Token* tok, const std::string& functionName,
nonneg int index, nonneg int numFunction);
void invalidScanfArgTypeError_s(const Token* tok, nonneg int numFormat, const std::string& specifier, const ArgumentInfo* argInfo);
void invalidScanfArgTypeError_int(const Token* tok, nonneg int numFormat, const std::string& specifier, const ArgumentInfo* argInfo, bool isUnsigned);
void invalidScanfArgTypeError_float(const Token* tok, nonneg int numFormat, const std::string& specifier, const ArgumentInfo* argInfo);
void invalidPrintfArgTypeError_s(const Token* tok, nonneg int numFormat, const ArgumentInfo* argInfo);
void invalidPrintfArgTypeError_n(const Token* tok, nonneg int numFormat, const ArgumentInfo* argInfo);
void invalidPrintfArgTypeError_p(const Token* tok, nonneg int numFormat, const ArgumentInfo* argInfo);
void invalidPrintfArgTypeError_uint(const Token* tok, nonneg int numFormat, const std::string& specifier, const ArgumentInfo* argInfo);
void invalidPrintfArgTypeError_sint(const Token* tok, nonneg int numFormat, const std::string& specifier, const ArgumentInfo* argInfo);
void invalidPrintfArgTypeError_float(const Token* tok, nonneg int numFormat, const std::string& specifier, const ArgumentInfo* argInfo);
void invalidLengthModifierError(const Token* tok, nonneg int numFormat, const std::string& modifier);
void invalidScanfFormatWidthError(const Token* tok, nonneg int numFormat, int width, const Variable *var, const std::string& specifier);
static void argumentType(std::ostream & os, const ArgumentInfo * argInfo);
static Severity getSeverity(const ArgumentInfo *argInfo);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const override {
CheckIO c(nullptr, settings, errorLogger);
c.coutCerrMisusageError(nullptr, "cout");
c.fflushOnInputStreamError(nullptr, "stdin");
c.ioWithoutPositioningError(nullptr);
c.readWriteOnlyFileError(nullptr);
c.writeReadOnlyFileError(nullptr);
c.useClosedFileError(nullptr);
c.seekOnAppendedFileError(nullptr);
c.incompatibleFileOpenError(nullptr, "tmp");
c.invalidScanfError(nullptr);
c.wrongPrintfScanfArgumentsError(nullptr, "printf",3,2);
c.invalidScanfArgTypeError_s(nullptr, 1, "s", nullptr);
c.invalidScanfArgTypeError_int(nullptr, 1, "d", nullptr, false);
c.invalidScanfArgTypeError_float(nullptr, 1, "f", nullptr);
c.invalidPrintfArgTypeError_s(nullptr, 1, nullptr);
c.invalidPrintfArgTypeError_n(nullptr, 1, nullptr);
c.invalidPrintfArgTypeError_p(nullptr, 1, nullptr);
c.invalidPrintfArgTypeError_uint(nullptr, 1, "u", nullptr);
c.invalidPrintfArgTypeError_sint(nullptr, 1, "i", nullptr);
c.invalidPrintfArgTypeError_float(nullptr, 1, "f", nullptr);
c.invalidLengthModifierError(nullptr, 1, "I");
c.invalidScanfFormatWidthError(nullptr, 10, 5, nullptr, "s");
c.invalidScanfFormatWidthError(nullptr, 99, -1, nullptr, "s");
c.wrongPrintfScanfPosixParameterPositionError(nullptr, "printf", 2, 1);
}
static std::string myName() {
return "IO using format string";
}
std::string classInfo() const override {
return "Check format string input/output operations.\n"
"- Bad usage of the function 'sprintf' (overlapping data)\n"
"- Missing or wrong width specifiers in 'scanf' format string\n"
"- Use a file that has been closed\n"
"- File input/output without positioning results in undefined behaviour\n"
"- Read to a file that has only been opened for writing (or vice versa)\n"
"- Repositioning operation on a file opened in append mode\n"
"- The same file can't be open for read and write at the same time on different streams\n"
"- Using fflush() on an input stream\n"
"- Invalid usage of output stream. For example: 'std::cout << std::cout;'\n"
"- Wrong number of arguments given to 'printf' or 'scanf;'\n";
}
};
/// @}
//---------------------------------------------------------------------------
#endif // checkioH
| null |
906 | cpp | cppcheck | color.h | lib/color.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef colorH
#define colorH
#include "config.h"
#include <cstdint>
#include <ostream>
#include <string>
enum class Color : std::uint8_t {
Reset = 0,
Bold = 1,
Dim = 2,
FgRed = 31,
FgGreen = 32,
FgBlue = 34,
FgMagenta = 35,
FgDefault = 39
};
CPPCHECKLIB std::ostream& operator<<(std::ostream& os, Color c);
CPPCHECKLIB std::string toString(Color c);
extern CPPCHECKLIB bool gDisableColors; // for testing
#endif
| null |
907 | cpp | cppcheck | timer.cpp | lib/timer.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2023 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "timer.h"
#include "utils.h"
#include <algorithm>
#include <iostream>
#include <utility>
#include <vector>
namespace {
using dataElementType = std::pair<std::string, TimerResultsData>;
bool more_second_sec(const dataElementType& lhs, const dataElementType& rhs)
{
return lhs.second.seconds() > rhs.second.seconds();
}
// TODO: remove and print through (synchronized) ErrorLogger instead
std::mutex stdCoutLock;
}
// TODO: this does not include any file context when SHOWTIME_FILE thus rendering it useless - should we include the logging with the progress logging?
// that could also get rid of the broader locking
void TimerResults::showResults(SHOWTIME_MODES mode) const
{
if (mode == SHOWTIME_MODES::SHOWTIME_NONE || mode == SHOWTIME_MODES::SHOWTIME_FILE_TOTAL)
return;
TimerResultsData overallData;
std::vector<dataElementType> data;
{
std::lock_guard<std::mutex> l(mResultsSync);
data.reserve(mResults.size());
data.insert(data.begin(), mResults.cbegin(), mResults.cend());
}
std::sort(data.begin(), data.end(), more_second_sec);
// lock the whole logging operation to avoid multiple threads printing their results at the same time
std::lock_guard<std::mutex> l(stdCoutLock);
std::cout << std::endl;
size_t ordinal = 1; // maybe it would be nice to have an ordinal in output later!
for (std::vector<dataElementType>::const_iterator iter=data.cbegin(); iter!=data.cend(); ++iter) {
const double sec = iter->second.seconds();
const double secAverage = sec / (double)(iter->second.mNumberOfResults);
bool hasParent = false;
{
// Do not use valueFlow.. in "Overall time" because those are included in Tokenizer already
if (startsWith(iter->first,"valueFlow"))
hasParent = true;
// Do not use inner timers in "Overall time"
const std::string::size_type pos = iter->first.rfind("::");
if (pos != std::string::npos)
hasParent = std::any_of(data.cbegin(), data.cend(), [iter,pos](const dataElementType& d) {
return d.first.size() == pos && iter->first.compare(0, d.first.size(), d.first) == 0;
});
}
if (!hasParent)
overallData.mClocks += iter->second.mClocks;
if ((mode != SHOWTIME_MODES::SHOWTIME_TOP5_FILE && mode != SHOWTIME_MODES::SHOWTIME_TOP5_SUMMARY) || (ordinal<=5)) {
std::cout << iter->first << ": " << sec << "s (avg. " << secAverage << "s - " << iter->second.mNumberOfResults << " result(s))" << std::endl;
}
++ordinal;
}
const double secOverall = overallData.seconds();
std::cout << "Overall time: " << secOverall << "s" << std::endl;
}
void TimerResults::addResults(const std::string& str, std::clock_t clocks)
{
std::lock_guard<std::mutex> l(mResultsSync);
mResults[str].mClocks += clocks;
mResults[str].mNumberOfResults++;
}
void TimerResults::reset()
{
std::lock_guard<std::mutex> l(mResultsSync);
mResults.clear();
}
Timer::Timer(std::string str, SHOWTIME_MODES showtimeMode, TimerResultsIntf* timerResults)
: mStr(std::move(str))
, mTimerResults(timerResults)
, mStart(std::clock())
, mShowTimeMode(showtimeMode)
, mStopped(showtimeMode == SHOWTIME_MODES::SHOWTIME_NONE || showtimeMode == SHOWTIME_MODES::SHOWTIME_FILE_TOTAL)
{}
Timer::Timer(bool fileTotal, std::string filename)
: mStr(std::move(filename))
, mStopped(!fileTotal)
{}
Timer::~Timer()
{
stop();
}
void Timer::stop()
{
if ((mShowTimeMode != SHOWTIME_MODES::SHOWTIME_NONE) && !mStopped) {
const std::clock_t end = std::clock();
const std::clock_t diff = end - mStart;
if (mShowTimeMode == SHOWTIME_MODES::SHOWTIME_FILE) {
const double sec = (double)diff / CLOCKS_PER_SEC;
std::lock_guard<std::mutex> l(stdCoutLock);
std::cout << mStr << ": " << sec << "s" << std::endl;
} else if (mShowTimeMode == SHOWTIME_MODES::SHOWTIME_FILE_TOTAL) {
const double sec = (double)diff / CLOCKS_PER_SEC;
std::lock_guard<std::mutex> l(stdCoutLock);
std::cout << "Check time: " << mStr << ": " << sec << "s" << std::endl;
} else {
if (mTimerResults)
mTimerResults->addResults(mStr, diff);
}
}
mStopped = true;
}
| null |
908 | cpp | cppcheck | checknullpointer.h | lib/checknullpointer.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef checknullpointerH
#define checknullpointerH
//---------------------------------------------------------------------------
#include "check.h"
#include "config.h"
#include "tokenize.h"
#include "vfvalue.h"
#include <list>
#include <string>
class ErrorLogger;
class Library;
class Settings;
class Token;
/// @addtogroup Checks
/// @{
/** @brief check for null pointer dereferencing */
class CPPCHECKLIB CheckNullPointer : public Check {
friend class TestNullPointer;
public:
/** @brief This constructor is used when registering the CheckNullPointer */
CheckNullPointer() : Check(myName()) {}
/**
* Is there a pointer dereference? Everything that should result in
* a nullpointer dereference error message will result in a true
* return value. If it's unknown if the pointer is dereferenced false
* is returned.
* @param tok token for the pointer
* @param unknown it is not known if there is a pointer dereference (could be reported as a debug message)
* @return true => there is a dereference
*/
bool isPointerDeRef(const Token *tok, bool &unknown) const;
static bool isPointerDeRef(const Token *tok, bool &unknown, const Settings &settings, bool checkNullArg = true);
private:
/**
* @brief parse a function call and extract information about variable usage
* @param tok first token
* @param var variables that the function read / write.
* @param library --library files data
*/
static void parseFunctionCall(const Token &tok,
std::list<const Token *> &var,
const Library &library, bool checkNullArg = true);
/** @brief This constructor is used when running checks. */
CheckNullPointer(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {}
/** @brief Run checks against the normal token list */
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
CheckNullPointer checkNullPointer(&tokenizer, &tokenizer.getSettings(), errorLogger);
checkNullPointer.nullPointer();
checkNullPointer.arithmetic();
checkNullPointer.nullConstantDereference();
}
/** @brief possible null pointer dereference */
void nullPointer();
/** @brief dereferencing null constant (after Tokenizer::simplifyKnownVariables) */
void nullConstantDereference();
void nullPointerError(const Token *tok) {
ValueFlow::Value v(0);
v.setKnown();
nullPointerError(tok, emptyString, &v, false);
}
void nullPointerError(const Token *tok, const std::string &varname, const ValueFlow::Value* value, bool inconclusive);
/** @brief Parse current TU and extract file info */
Check::FileInfo *getFileInfo(const Tokenizer &tokenizer, const Settings &settings) const override;
Check::FileInfo * loadFileInfoFromXml(const tinyxml2::XMLElement *xmlElement) const override;
/** @brief Analyse all file infos for all TU */
bool analyseWholeProgram(const CTU::FileInfo *ctu, const std::list<Check::FileInfo*> &fileInfo, const Settings& settings, ErrorLogger &errorLogger) override;
/** Get error messages. Used by --errorlist */
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const override {
CheckNullPointer c(nullptr, settings, errorLogger);
c.nullPointerError(nullptr, "pointer", nullptr, false);
c.pointerArithmeticError(nullptr, nullptr, false);
c.redundantConditionWarning(nullptr, nullptr, nullptr, false);
}
/** Name of check */
static std::string myName() {
return "Null pointer";
}
/** class info in WIKI format. Used by --doc */
std::string classInfo() const override {
return "Null pointers\n"
"- null pointer dereferencing\n"
"- undefined null pointer arithmetic\n";
}
/**
* @brief Does one part of the check for nullPointer().
* Dereferencing a pointer and then checking if it's NULL..
*/
void nullPointerByDeRefAndCheck();
/** undefined null pointer arithmetic */
void arithmetic();
void pointerArithmeticError(const Token* tok, const ValueFlow::Value *value, bool inconclusive);
void redundantConditionWarning(const Token* tok, const ValueFlow::Value *value, const Token *condition, bool inconclusive);
};
/// @}
//---------------------------------------------------------------------------
#endif // checknullpointerH
| null |
909 | cpp | cppcheck | checkexceptionsafety.h | lib/checkexceptionsafety.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef checkexceptionsafetyH
#define checkexceptionsafetyH
//---------------------------------------------------------------------------
#include "check.h"
#include "config.h"
#include "tokenize.h"
#include <string>
class Settings;
class ErrorLogger;
class Token;
/// @addtogroup Checks
/// @{
/**
* @brief %Check exception safety (exceptions shouldn't cause leaks nor corrupt data)
*
* The problem with these checks is that Cppcheck can't determine what the valid
* values are for variables. But in some cases (dead pointers) it can be determined
* that certain variable values are corrupt.
*/
class CPPCHECKLIB CheckExceptionSafety : public Check {
public:
/** This constructor is used when registering the CheckClass */
CheckExceptionSafety() : Check(myName()) {}
private:
/** This constructor is used when running checks. */
CheckExceptionSafety(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {}
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
if (tokenizer.isC())
return;
CheckExceptionSafety checkExceptionSafety(&tokenizer, &tokenizer.getSettings(), errorLogger);
checkExceptionSafety.destructors();
checkExceptionSafety.deallocThrow();
checkExceptionSafety.checkRethrowCopy();
checkExceptionSafety.checkCatchExceptionByValue();
checkExceptionSafety.nothrowThrows();
checkExceptionSafety.unhandledExceptionSpecification();
checkExceptionSafety.rethrowNoCurrentException();
}
/** Don't throw exceptions in destructors */
void destructors();
/** deallocating memory and then throw (dead pointer) */
void deallocThrow();
/** Don't rethrow a copy of the caught exception; use a bare throw instead */
void checkRethrowCopy();
/** @brief %Check for exceptions that are caught by value instead of by reference */
void checkCatchExceptionByValue();
/** @brief %Check for functions that throw that shouldn't */
void nothrowThrows();
/** @brief %Check for unhandled exception specification */
void unhandledExceptionSpecification();
/** @brief %Check for rethrow not from catch scope */
void rethrowNoCurrentException();
/** Don't throw exceptions in destructors */
void destructorsError(const Token * tok, const std::string &className);
void deallocThrowError(const Token * tok, const std::string &varname);
void rethrowCopyError(const Token * tok, const std::string &varname);
void catchExceptionByValueError(const Token *tok);
void noexceptThrowError(const Token * tok);
/** Missing exception specification */
void unhandledExceptionSpecificationError(const Token * tok1, const Token * tok2, const std::string & funcname);
/** Rethrow without currently handled exception */
void rethrowNoCurrentExceptionError(const Token *tok);
/** Generate all possible errors (for --errorlist) */
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const override {
CheckExceptionSafety c(nullptr, settings, errorLogger);
c.destructorsError(nullptr, "Class");
c.deallocThrowError(nullptr, "p");
c.rethrowCopyError(nullptr, "varname");
c.catchExceptionByValueError(nullptr);
c.noexceptThrowError(nullptr);
c.unhandledExceptionSpecificationError(nullptr, nullptr, "funcname");
c.rethrowNoCurrentExceptionError(nullptr);
}
/** Short description of class (for --doc) */
static std::string myName() {
return "Exception Safety";
}
/** wiki formatted description of the class (for --doc) */
std::string classInfo() const override {
return "Checking exception safety\n"
"- Throwing exceptions in destructors\n"
"- Throwing exception during invalid state\n"
"- Throwing a copy of a caught exception instead of rethrowing the original exception\n"
"- Exception caught by value instead of by reference\n"
"- Throwing exception in noexcept, nothrow(), __attribute__((nothrow)) or __declspec(nothrow) function\n"
"- Unhandled exception specification when calling function foo()\n"
"- Rethrow without currently handled exception\n";
}
};
/// @}
//---------------------------------------------------------------------------
#endif // checkexceptionsafetyH
| null |
910 | cpp | cppcheck | checkmemoryleak.cpp | lib/checkmemoryleak.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "checkmemoryleak.h"
#include "astutils.h"
#include "errorlogger.h"
#include "errortypes.h"
#include "library.h"
#include "mathlib.h"
#include "platform.h"
#include "settings.h"
#include "symboldatabase.h"
#include "token.h"
#include "tokenize.h"
#include <algorithm>
#include <utility>
#include <vector>
//---------------------------------------------------------------------------
// Register this check class (by creating a static instance of it)
namespace {
CheckMemoryLeakInFunction instance1;
CheckMemoryLeakInClass instance2;
CheckMemoryLeakStructMember instance3;
CheckMemoryLeakNoVar instance4;
}
// CWE ID used:
static const CWE CWE398(398U); // Indicator of Poor Code Quality
static const CWE CWE401(401U); // Improper Release of Memory Before Removing Last Reference ('Memory Leak')
static const CWE CWE771(771U); // Missing Reference to Active Allocated Resource
static const CWE CWE772(772U); // Missing Release of Resource after Effective Lifetime
//---------------------------------------------------------------------------
CheckMemoryLeak::AllocType CheckMemoryLeak::getAllocationType(const Token *tok2, nonneg int varid, std::list<const Function*> *callstack) const
{
// What we may have...
// * var = (char *)malloc(10);
// * var = new char[10];
// * var = strdup("hello");
// * var = strndup("hello", 3);
if (tok2 && tok2->str() == "(") {
tok2 = tok2->link();
tok2 = tok2 ? tok2->next() : nullptr;
}
if (!tok2)
return No;
if (tok2->str() == "::")
tok2 = tok2->next();
while (Token::Match(tok2, "%name% :: %type%"))
tok2 = tok2->tokAt(2);
if (!tok2->isName())
return No;
if (!Token::Match(tok2, "%name% . %type%")) {
// Using realloc..
AllocType reallocType = getReallocationType(tok2, varid);
if (reallocType != No)
return reallocType;
if (tok2->isCpp() && tok2->str() == "new") {
if (tok2->strAt(1) == "(" && !Token::Match(tok2->next(),"( std| ::| nothrow )"))
return No;
if (tok2->astOperand1() && (tok2->astOperand1()->str() == "[" || (tok2->astOperand1()->astOperand1() && tok2->astOperand1()->astOperand1()->str() == "[")))
return NewArray;
const Token *typeTok = tok2->next();
while (Token::Match(typeTok, "%name% :: %name%"))
typeTok = typeTok->tokAt(2);
const Scope* classScope = nullptr;
if (typeTok->type() && (typeTok->type()->isClassType() || typeTok->type()->isStructType() || typeTok->type()->isUnionType())) {
classScope = typeTok->type()->classScope;
} else if (typeTok->function() && typeTok->function()->isConstructor()) {
classScope = typeTok->function()->nestedIn;
}
if (classScope && classScope->numConstructors > 0)
return No;
return New;
}
if (mSettings_->hasLib("posix")) {
if (Token::Match(tok2, "open|openat|creat|mkstemp|mkostemp|socket (")) {
// simple sanity check of function parameters..
// TODO: Make such check for all these functions
const int num = numberOfArguments(tok2);
if (tok2->str() == "open" && num != 2 && num != 3)
return No;
// is there a user function with this name?
if (tok2->function())
return No;
return Fd;
}
if (Token::simpleMatch(tok2, "popen ("))
return Pipe;
}
// Does tok2 point on a Library allocation function?
const int alloctype = mSettings_->library.getAllocId(tok2, -1);
if (alloctype > 0) {
if (alloctype == mSettings_->library.deallocId("free"))
return Malloc;
if (alloctype == mSettings_->library.deallocId("fclose"))
return File;
return Library::ismemory(alloctype) ? OtherMem : OtherRes;
}
}
while (Token::Match(tok2,"%name% . %type%"))
tok2 = tok2->tokAt(2);
// User function
const Function* func = tok2->function();
if (func == nullptr)
return No;
// Prevent recursion
if (callstack && std::find(callstack->cbegin(), callstack->cend(), func) != callstack->cend())
return No;
std::list<const Function*> cs;
if (!callstack)
callstack = &cs;
callstack->push_back(func);
return functionReturnType(func, callstack);
}
CheckMemoryLeak::AllocType CheckMemoryLeak::getReallocationType(const Token *tok2, nonneg int varid) const
{
// What we may have...
// * var = (char *)realloc(..;
if (tok2 && tok2->str() == "(") {
tok2 = tok2->link();
tok2 = tok2 ? tok2->next() : nullptr;
}
if (!tok2)
return No;
if (!Token::Match(tok2, "%name% ("))
return No;
const Library::AllocFunc *f = mSettings_->library.getReallocFuncInfo(tok2);
if (!(f && f->reallocArg > 0 && f->reallocArg <= numberOfArguments(tok2)))
return No;
const auto args = getArguments(tok2);
if (args.size() < (f->reallocArg))
return No;
const Token* arg = args.at(f->reallocArg - 1);
while (arg && arg->isCast())
arg = arg->astOperand1();
while (arg && arg->isUnaryOp("*"))
arg = arg->astOperand1();
if (varid > 0 && !Token::Match(arg, "%varid% [,)]", varid))
return No;
const int realloctype = mSettings_->library.getReallocId(tok2, -1);
if (realloctype > 0) {
if (realloctype == mSettings_->library.deallocId("free"))
return Malloc;
if (realloctype == mSettings_->library.deallocId("fclose"))
return File;
return Library::ismemory(realloctype) ? OtherMem : OtherRes;
}
return No;
}
CheckMemoryLeak::AllocType CheckMemoryLeak::getDeallocationType(const Token *tok, nonneg int varid) const
{
if (tok->isCpp() && tok->str() == "delete" && tok->astOperand1()) {
const Token* vartok = tok->astOperand1();
if (Token::Match(vartok, ".|::"))
vartok = vartok->astOperand2();
if (vartok && vartok->varId() == varid) {
if (tok->strAt(1) == "[")
return NewArray;
return New;
}
}
if (tok->str() == "::")
tok = tok->next();
if (Token::Match(tok, "%name% (")) {
if (Token::simpleMatch(tok, "fcloseall ( )"))
return File;
int argNr = 1;
for (const Token* tok2 = tok->tokAt(2); tok2; tok2 = tok2->nextArgument()) {
const Token* vartok = tok2;
while (Token::Match(vartok, "%name% .|::"))
vartok = vartok->tokAt(2);
if (Token::Match(vartok, "%varid% )|,|-", varid)) {
if (tok->str() == "realloc" && Token::simpleMatch(vartok->next(), ", 0 )"))
return Malloc;
if (mSettings_->hasLib("posix")) {
if (tok->str() == "close")
return Fd;
if (tok->str() == "pclose")
return Pipe;
}
// Does tok point on a Library deallocation function?
const int dealloctype = mSettings_->library.getDeallocId(tok, argNr);
if (dealloctype > 0) {
if (dealloctype == mSettings_->library.deallocId("free"))
return Malloc;
if (dealloctype == mSettings_->library.deallocId("fclose"))
return File;
return Library::ismemory(dealloctype) ? OtherMem : OtherRes;
}
}
argNr++;
}
}
return No;
}
bool CheckMemoryLeak::isReopenStandardStream(const Token *tok) const
{
if (getReallocationType(tok, 0) == File) {
const Library::AllocFunc *f = mSettings_->library.getReallocFuncInfo(tok);
if (f && f->reallocArg > 0 && f->reallocArg <= numberOfArguments(tok)) {
const Token* arg = getArguments(tok).at(f->reallocArg - 1);
if (Token::Match(arg, "stdin|stdout|stderr"))
return true;
}
}
return false;
}
bool CheckMemoryLeak::isOpenDevNull(const Token *tok) const
{
if (mSettings_->hasLib("posix") && tok->str() == "open" && numberOfArguments(tok) == 2) {
const Token* arg = getArguments(tok).at(0);
if (Token::simpleMatch(arg, "\"/dev/null\""))
return true;
}
return false;
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
void CheckMemoryLeak::memoryLeak(const Token *tok, const std::string &varname, AllocType alloctype) const
{
if (alloctype == CheckMemoryLeak::File ||
alloctype == CheckMemoryLeak::Pipe ||
alloctype == CheckMemoryLeak::Fd ||
alloctype == CheckMemoryLeak::OtherRes)
resourceLeakError(tok, varname);
else
memleakError(tok, varname);
}
//---------------------------------------------------------------------------
void CheckMemoryLeak::reportErr(const Token *tok, Severity severity, const std::string &id, const std::string &msg, const CWE &cwe) const
{
std::list<const Token *> callstack;
if (tok)
callstack.push_back(tok);
reportErr(callstack, severity, id, msg, cwe);
}
void CheckMemoryLeak::reportErr(const std::list<const Token *> &callstack, Severity severity, const std::string &id, const std::string &msg, const CWE &cwe) const
{
const ErrorMessage errmsg(callstack, mTokenizer_ ? &mTokenizer_->list : nullptr, severity, id, msg, cwe, Certainty::normal);
if (mErrorLogger_)
mErrorLogger_->reportErr(errmsg);
else
Check::writeToErrorList(errmsg);
}
void CheckMemoryLeak::memleakError(const Token *tok, const std::string &varname) const
{
reportErr(tok, Severity::error, "memleak", "$symbol:" + varname + "\nMemory leak: $symbol", CWE(401U));
}
void CheckMemoryLeak::memleakUponReallocFailureError(const Token *tok, const std::string &reallocfunction, const std::string &varname) const
{
reportErr(tok, Severity::error, "memleakOnRealloc", "$symbol:" + varname + "\nCommon " + reallocfunction + " mistake: \'$symbol\' nulled but not freed upon failure", CWE(401U));
}
void CheckMemoryLeak::resourceLeakError(const Token *tok, const std::string &varname) const
{
std::string errmsg("Resource leak");
if (!varname.empty())
errmsg = "$symbol:" + varname + '\n' + errmsg + ": $symbol";
reportErr(tok, Severity::error, "resourceLeak", errmsg, CWE(775U));
}
void CheckMemoryLeak::deallocuseError(const Token *tok, const std::string &varname) const
{
reportErr(tok, Severity::error, "deallocuse", "$symbol:" + varname + "\nDereferencing '$symbol' after it is deallocated / released", CWE(416U));
}
void CheckMemoryLeak::mismatchAllocDealloc(const std::list<const Token *> &callstack, const std::string &varname) const
{
reportErr(callstack, Severity::error, "mismatchAllocDealloc", "$symbol:" + varname + "\nMismatching allocation and deallocation: $symbol", CWE(762U));
}
CheckMemoryLeak::AllocType CheckMemoryLeak::functionReturnType(const Function* func, std::list<const Function*> *callstack) const
{
if (!func || !func->hasBody() || !func->functionScope)
return No;
// Get return pointer..
const Variable* var = nullptr;
for (const Token *tok2 = func->functionScope->bodyStart; tok2 != func->functionScope->bodyEnd; tok2 = tok2->next()) {
if (const Token *endOfLambda = findLambdaEndToken(tok2))
tok2 = endOfLambda;
if (tok2->str() == "{" && !tok2->scope()->isExecutable())
tok2 = tok2->link();
if (tok2->str() == "return") {
const AllocType allocType = getAllocationType(tok2->next(), 0, callstack);
if (allocType != No)
return allocType;
if (tok2->scope() != func->functionScope || !tok2->astOperand1())
return No;
const Token* tok = tok2->astOperand1();
if (Token::Match(tok, ".|::"))
tok = tok->astOperand2() ? tok->astOperand2() : tok->astOperand1();
if (tok)
var = tok->variable();
break;
}
}
// Not returning pointer value..
if (!var)
return No;
// If variable is not local then alloctype shall be "No"
// Todo: there can be false negatives about mismatching allocation/deallocation.
// => Generate "alloc ; use ;" if variable is not local?
if (!var->isLocal() || var->isStatic())
return No;
// Check if return pointer is allocated..
AllocType allocType = No;
nonneg int const varid = var->declarationId();
for (const Token* tok = func->functionScope->bodyStart; tok != func->functionScope->bodyEnd; tok = tok->next()) {
if (Token::Match(tok, "%varid% =", varid)) {
allocType = getAllocationType(tok->tokAt(2), varid, callstack);
}
if (Token::Match(tok, "= %varid% ;", varid)) {
return No;
}
if (!tok->isC() && Token::Match(tok, "[(,] %varid% [,)]", varid)) {
return No;
}
if (Token::Match(tok, "[(,] & %varid% [.,)]", varid)) {
return No;
}
if (Token::Match(tok, "[;{}] %varid% .", varid)) {
return No;
}
if (allocType == No && tok->str() == "return")
return No;
}
return allocType;
}
static bool notvar(const Token *tok, nonneg int varid)
{
if (!tok)
return false;
if (Token::Match(tok, "&&|;"))
return notvar(tok->astOperand1(),varid) || notvar(tok->astOperand2(),varid);
if (tok->str() == "(" && Token::Match(tok->astOperand1(), "UNLIKELY|LIKELY"))
return notvar(tok->astOperand2(), varid);
const Token *vartok = astIsVariableComparison(tok, "==", "0");
return vartok && (vartok->varId() == varid);
}
static bool ifvar(const Token *tok, nonneg int varid, const std::string &comp, const std::string &rhs)
{
if (!Token::simpleMatch(tok, "if ("))
return false;
const Token *condition = tok->next()->astOperand2();
if (condition && condition->str() == "(" && Token::Match(condition->astOperand1(), "UNLIKELY|LIKELY"))
condition = condition->astOperand2();
if (!condition || condition->str() == "&&")
return false;
const Token *vartok = astIsVariableComparison(condition, comp, rhs);
return (vartok && vartok->varId() == varid);
}
//---------------------------------------------------------------------------
// Check for memory leaks due to improper realloc() usage.
// Below, "a" may be set to null without being freed if realloc() cannot
// allocate the requested memory:
// a = malloc(10); a = realloc(a, 100);
//---------------------------------------------------------------------------
void CheckMemoryLeakInFunction::checkReallocUsage()
{
logChecker("CheckMemoryLeakInFunction::checkReallocUsage");
// only check functions
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
// Search for the "var = realloc(var, 100" pattern within this function
for (const Token *tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (tok->varId() > 0 && Token::Match(tok, "%name% =")) {
// Get the parenthesis in "realloc("
const Token* parTok = tok->next()->astOperand2();
// Skip casts
while (parTok && parTok->isCast())
parTok = parTok->astOperand1();
if (!parTok)
continue;
const Token *const reallocTok = parTok->astOperand1();
if (!reallocTok)
continue;
const Library::AllocFunc* f = mSettings->library.getReallocFuncInfo(reallocTok);
if (!(f && f->arg == -1 && mSettings->library.isnotnoreturn(reallocTok)))
continue;
const AllocType allocType = getReallocationType(reallocTok, tok->varId());
if (!((allocType == Malloc || allocType == OtherMem)))
continue;
const Token* arg = getArguments(reallocTok).at(f->reallocArg - 1);
while (arg && arg->isCast())
arg = arg->astOperand1();
const Token* tok2 = tok;
while (arg && arg->isUnaryOp("*") && tok2 && tok2->astParent() && tok2->astParent()->isUnaryOp("*")) {
arg = arg->astOperand1();
tok2 = tok2->astParent();
}
if (!arg || !tok2)
continue;
if (!(tok->varId() == arg->varId() && tok->variable() && !tok->variable()->isArgument()))
continue;
// Check that another copy of the pointer wasn't saved earlier in the function
if (Token::findmatch(scope->bodyStart, "%name% = %varid% ;", tok, tok->varId()) ||
Token::findmatch(scope->bodyStart, "[{};] %varid% = *| %var% .| %var%| [;=]", tok, tok->varId()))
continue;
// Check if the argument is known to be null, which means it is not a memory leak
if (arg->hasKnownIntValue() && arg->getKnownIntValue() == 0) {
continue;
}
const Token* tokEndRealloc = reallocTok->linkAt(1);
// Check that the allocation isn't followed immediately by an 'if (!var) { error(); }' that might handle failure
if (Token::simpleMatch(tokEndRealloc->next(), "; if (") &&
notvar(tokEndRealloc->tokAt(3)->astOperand2(), tok->varId())) {
const Token* tokEndBrace = tokEndRealloc->linkAt(3)->linkAt(1);
if (tokEndBrace && mTokenizer->isScopeNoReturn(tokEndBrace))
continue;
}
memleakUponReallocFailureError(tok, reallocTok->str(), tok->str());
}
}
}
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// Checks for memory leaks in classes..
//---------------------------------------------------------------------------
void CheckMemoryLeakInClass::check()
{
logChecker("CheckMemoryLeakInClass::check");
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
// only check classes and structures
for (const Scope * scope : symbolDatabase->classAndStructScopes) {
for (const Variable &var : scope->varlist) {
if (!var.isStatic() && (var.isPointer() || var.isPointerArray())) {
// allocation but no deallocation of private variables in public function..
const Token *tok = var.typeStartToken();
// Either it is of standard type or a non-derived type
if (tok->isStandardType() || (var.type() && var.type()->derivedFrom.empty())) {
if (var.isPrivate())
checkPublicFunctions(scope, var.nameToken());
variable(scope, var.nameToken());
}
}
}
}
}
void CheckMemoryLeakInClass::variable(const Scope *scope, const Token *tokVarname)
{
const std::string& varname = tokVarname->str();
const int varid = tokVarname->varId();
const std::string& classname = scope->className;
// Check if member variable has been allocated and deallocated..
CheckMemoryLeak::AllocType memberAlloc = CheckMemoryLeak::No;
CheckMemoryLeak::AllocType memberDealloc = CheckMemoryLeak::No;
bool allocInConstructor = false;
bool deallocInDestructor = false;
// Inspect member functions
for (const Function &func : scope->functionList) {
const bool constructor = func.isConstructor();
const bool destructor = func.isDestructor();
if (!func.hasBody()) {
if (destructor && !func.isDefault()) { // implementation for destructor is not seen and not defaulted => assume it deallocates all variables properly
deallocInDestructor = true;
memberDealloc = CheckMemoryLeak::Many;
}
continue;
}
bool body = false;
const Token *end = func.functionScope->bodyEnd;
for (const Token *tok = func.arg->link(); tok != end; tok = tok->next()) {
if (tok == func.functionScope->bodyStart)
body = true;
else {
if (!body) {
if (!Token::Match(tok, ":|, %varid% (", varid))
continue;
}
// Allocate..
if (!body || Token::Match(tok, "%varid% =|[", varid)) {
// var1 = var2 = ...
// bail out
if (tok->strAt(-1) == "=")
return;
// Foo::var1 = ..
// bail out when not same class
if (tok->strAt(-1) == "::" &&
tok->strAt(-2) != scope->className)
return;
const Token* allocTok = tok->tokAt(body ? 2 : 3);
if (tok->astParent() && tok->astParent()->str() == "[" && tok->astParent()->astParent())
allocTok = tok->astParent()->astParent()->astOperand2();
AllocType alloc = getAllocationType(allocTok, 0);
if (alloc != CheckMemoryLeak::No) {
if (constructor)
allocInConstructor = true;
if (memberAlloc != No && memberAlloc != alloc)
alloc = CheckMemoryLeak::Many;
if (alloc != CheckMemoryLeak::Many && memberDealloc != CheckMemoryLeak::No && memberDealloc != CheckMemoryLeak::Many && memberDealloc != alloc) {
mismatchAllocDealloc({tok}, classname + "::" + varname);
}
memberAlloc = alloc;
}
}
if (!body)
continue;
// Deallocate..
AllocType dealloc = getDeallocationType(tok, varid);
// some usage in the destructor => assume it's related
// to deallocation
if (destructor && tok->str() == varname)
dealloc = CheckMemoryLeak::Many;
if (dealloc != CheckMemoryLeak::No) {
if (destructor)
deallocInDestructor = true;
if (dealloc != CheckMemoryLeak::Many && memberAlloc != CheckMemoryLeak::No && memberAlloc != Many && memberAlloc != dealloc) {
mismatchAllocDealloc({tok}, classname + "::" + varname);
}
// several types of allocation/deallocation?
if (memberDealloc != CheckMemoryLeak::No && memberDealloc != dealloc)
dealloc = CheckMemoryLeak::Many;
memberDealloc = dealloc;
}
// Function call .. possible deallocation
else if (Token::Match(tok->previous(), "[{};] %name% (") && !tok->isKeyword() && !mSettings->library.isLeakIgnore(tok->str())) {
return;
}
}
}
}
if (allocInConstructor && !deallocInDestructor) {
unsafeClassError(tokVarname, classname, classname + "::" + varname /*, memberAlloc*/);
} else if (memberAlloc != CheckMemoryLeak::No && memberDealloc == CheckMemoryLeak::No) {
unsafeClassError(tokVarname, classname, classname + "::" + varname /*, memberAlloc*/);
}
}
void CheckMemoryLeakInClass::unsafeClassError(const Token *tok, const std::string &classname, const std::string &varname)
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("unsafeClassCanLeak"))
return;
reportError(tok, Severity::style, "unsafeClassCanLeak",
"$symbol:" + classname + "\n"
"$symbol:" + varname + "\n"
"Class '" + classname + "' is unsafe, '" + varname + "' can leak by wrong usage.\n"
"The class '" + classname + "' is unsafe, wrong usage can cause memory/resource leaks for '" + varname + "'. This can for instance be fixed by adding proper cleanup in the destructor.", CWE398, Certainty::normal);
}
void CheckMemoryLeakInClass::checkPublicFunctions(const Scope *scope, const Token *classtok)
{
// Check that public functions deallocate the pointers that they allocate.
// There is no checking how these functions are used and therefore it
// isn't established if there is real leaks or not.
if (!mSettings->severity.isEnabled(Severity::warning))
return;
const int varid = classtok->varId();
// Parse public functions..
// If they allocate member variables, they should also deallocate
for (const Function &func : scope->functionList) {
if ((func.type == Function::eFunction || func.type == Function::eOperatorEqual) &&
func.access == AccessControl::Public && func.hasBody()) {
const Token *tok2 = func.functionScope->bodyStart->next();
if (Token::Match(tok2, "%varid% =", varid)) {
const CheckMemoryLeak::AllocType alloc = getAllocationType(tok2->tokAt(2), varid);
if (alloc != CheckMemoryLeak::No)
publicAllocationError(tok2, tok2->str());
} else if (Token::Match(tok2, "%type% :: %varid% =", varid) &&
tok2->str() == scope->className) {
const CheckMemoryLeak::AllocType alloc = getAllocationType(tok2->tokAt(4), varid);
if (alloc != CheckMemoryLeak::No)
publicAllocationError(tok2, tok2->strAt(2));
}
}
}
}
void CheckMemoryLeakInClass::publicAllocationError(const Token *tok, const std::string &varname)
{
reportError(tok, Severity::warning, "publicAllocationError", "$symbol:" + varname + "\nPossible leak in public function. The pointer '$symbol' is not deallocated before it is allocated.", CWE398, Certainty::normal);
}
void CheckMemoryLeakStructMember::check()
{
if (mSettings->clang)
return;
logChecker("CheckMemoryLeakStructMember::check");
const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Variable* var : symbolDatabase->variableList()) {
if (!var || (!var->isLocal() && !(var->isArgument() && var->scope())) || var->isStatic())
continue;
if (var->isReference() || (var->valueType() && var->valueType()->pointer > 1))
continue;
if (var->typeEndToken()->isStandardType())
continue;
checkStructVariable(var);
}
}
bool CheckMemoryLeakStructMember::isMalloc(const Variable *variable) const
{
if (!variable)
return false;
const int declarationId(variable->declarationId());
bool alloc = false;
for (const Token *tok2 = variable->nameToken(); tok2 && tok2 != variable->scope()->bodyEnd; tok2 = tok2->next()) {
if (Token::Match(tok2, "= %varid% [;=]", declarationId))
return false;
if (Token::Match(tok2, "%varid% = %name% (", declarationId) && mSettings->library.getAllocFuncInfo(tok2->tokAt(2)))
alloc = true;
}
return alloc;
}
void CheckMemoryLeakStructMember::checkStructVariable(const Variable* const variable) const
{
if (!variable)
return;
// Is struct variable a pointer?
if (variable->isArrayOrPointer()) {
// Check that variable is allocated with malloc
if (!isMalloc(variable))
return;
} else if (!mTokenizer->isC() && (!variable->typeScope() || variable->typeScope()->getDestructor())) {
// For non-C code a destructor might cleanup members
return;
}
// Check struct..
int indentlevel2 = 0;
auto deallocInFunction = [this](const Token* tok, int structid) -> bool {
// Calling non-function / function that doesn't deallocate?
if (tok->isKeyword() || mSettings->library.isLeakIgnore(tok->str()))
return false;
// Check if the struct is used..
bool deallocated = false;
const Token* const end = tok->linkAt(1);
for (const Token* tok2 = tok; tok2 != end; tok2 = tok2->next()) {
if (Token::Match(tok2, "[(,] &| %varid% [,)]", structid)) {
/** @todo check if the function deallocates the memory */
deallocated = true;
break;
}
if (Token::Match(tok2, "[(,] &| %varid% . %name% [,)]", structid)) {
/** @todo check if the function deallocates the memory */
deallocated = true;
break;
}
}
return deallocated;
};
// return { memberTok, rhsTok }
auto isMemberAssignment = [](const Token* varTok, int varId) -> std::pair<const Token*, const Token*> {
if (varTok->varId() != varId)
return {};
const Token* top = varTok;
while (top->astParent()) {
if (Token::Match(top->astParent(), "(|["))
return {};
top = top->astParent();
}
if (!Token::simpleMatch(top, "=") || !precedes(varTok, top))
return {};
const Token* dot = top->astOperand1();
while (dot && dot->str() != ".")
dot = dot->astOperand1();
if (!dot)
return {};
return { dot->astOperand2(), top->next() };
};
std::pair<const Token*, const Token*> assignToks;
const Token* tokStart = variable->nameToken();
if (variable->isArgument() && variable->scope())
tokStart = variable->scope()->bodyStart->next();
for (const Token *tok2 = tokStart; tok2 && tok2 != variable->scope()->bodyEnd; tok2 = tok2->next()) {
if (tok2->str() == "{")
++indentlevel2;
else if (tok2->str() == "}") {
if (indentlevel2 == 0)
break;
--indentlevel2;
}
// Unknown usage of struct
/** @todo Check how the struct is used. Only bail out if necessary */
else if (Token::Match(tok2, "[(,] %varid% [,)]", variable->declarationId()))
break;
// Struct member is allocated => check if it is also properly deallocated..
else if ((assignToks = isMemberAssignment(tok2, variable->declarationId())).first && assignToks.first->varId()) {
const AllocType allocType = getAllocationType(assignToks.second, assignToks.first->varId());
if (allocType == AllocType::No)
continue;
if (variable->isArgument() && variable->valueType() && variable->valueType()->type == ValueType::UNKNOWN_TYPE && assignToks.first->astParent()) {
const Token* accessTok = assignToks.first->astParent();
while (Token::simpleMatch(accessTok->astOperand1(), "."))
accessTok = accessTok->astOperand1();
if (Token::simpleMatch(accessTok, ".") && accessTok->originalName() == "->")
continue;
}
const int structid(variable->declarationId());
const int structmemberid(assignToks.first->varId());
// This struct member is allocated.. check that it is deallocated
int indentlevel3 = indentlevel2;
for (const Token *tok3 = tok2; tok3; tok3 = tok3->next()) {
if (tok3->str() == "{")
++indentlevel3;
else if (tok3->str() == "}") {
if (indentlevel3 == 0) {
memoryLeak(tok3, variable->name() + "." + assignToks.first->str(), allocType);
break;
}
--indentlevel3;
}
// Deallocating the struct member..
else if (getDeallocationType(tok3, structmemberid) != AllocType::No) {
// If the deallocation happens at the base level, don't check this member anymore
if (indentlevel3 == 0)
break;
// deallocating and then returning from function in a conditional block =>
// skip ahead out of the block
bool ret = false;
while (tok3) {
if (tok3->str() == "return")
ret = true;
else if (tok3->str() == "{" || tok3->str() == "}")
break;
tok3 = tok3->next();
}
if (!ret || !tok3 || tok3->str() != "}")
break;
--indentlevel3;
continue;
}
// Deallocating the struct..
else if (Token::Match(tok3, "%name% ( %varid% )", structid) && mSettings->library.getDeallocFuncInfo(tok3)) {
if (indentlevel2 == 0)
memoryLeak(tok3, variable->name() + "." + tok2->strAt(2), allocType);
break;
}
// failed allocation => skip code..
else if (Token::simpleMatch(tok3, "if (") &&
notvar(tok3->next()->astOperand2(), structmemberid)) {
// Goto the ")"
tok3 = tok3->linkAt(1);
// make sure we have ") {".. it should be
if (!Token::simpleMatch(tok3, ") {"))
break;
// Goto the "}"
tok3 = tok3->linkAt(1);
}
// succeeded allocation
else if (ifvar(tok3, structmemberid, "!=", "0")) {
// goto the ")"
tok3 = tok3->linkAt(1);
// check if the variable is deallocated or returned..
int indentlevel4 = 0;
for (const Token *tok4 = tok3; tok4; tok4 = tok4->next()) {
if (tok4->str() == "{")
++indentlevel4;
else if (tok4->str() == "}") {
--indentlevel4;
if (indentlevel4 == 0)
break;
} else if (Token::Match(tok4, "%name% ( %var% . %varid% )", structmemberid) && mSettings->library.getDeallocFuncInfo(tok4)) {
break;
}
}
// was there a proper deallocation?
if (indentlevel4 > 0)
break;
}
// Returning from function..
else if ((tok3->scope()->type != Scope::ScopeType::eLambda || tok3->scope() == variable->scope()) && tok3->str() == "return") {
// Returning from function without deallocating struct member?
if (!Token::Match(tok3, "return %varid% ;", structid) &&
!Token::Match(tok3, "return & %varid%", structid) &&
!(Token::Match(tok3, "return %varid% . %var%", structid) && tok3->tokAt(3)->varId() == structmemberid) &&
!(Token::Match(tok3, "return %name% (") && tok3->astOperand1() && deallocInFunction(tok3->astOperand1(), structid))) {
memoryLeak(tok3, variable->name() + "." + tok2->strAt(2), allocType);
}
break;
}
// struct assignment..
else if (Token::Match(tok3, "= %varid% ;", structid)) {
break;
} else if (Token::Match(tok3, "= %var% . %varid% ;", structmemberid)) {
break;
}
// goto isn't handled well.. bail out even though there might be leaks
else if (tok3->str() == "goto")
break;
// using struct in a function call..
else if (Token::Match(tok3, "%name% (")) {
if (deallocInFunction(tok3, structid))
break;
}
}
}
}
}
void CheckMemoryLeakNoVar::check()
{
logChecker("CheckMemoryLeakNoVar::check");
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
// only check functions
for (const Scope * scope : symbolDatabase->functionScopes) {
// Checks if a call to an allocation function like malloc() is made and its return value is not assigned.
checkForUnusedReturnValue(scope);
// Checks to see if a function is called with memory allocated for an argument that
// could be leaked if a function called for another argument throws.
checkForUnsafeArgAlloc(scope);
// Check for leaks where a the return value of an allocation function like malloc() is an input argument,
// for example f(malloc(1)), where f is known to not release the input argument.
checkForUnreleasedInputArgument(scope);
}
}
//---------------------------------------------------------------------------
// Checks if an input argument to a function is the return value of an allocation function
// like malloc(), and the function does not release it.
//---------------------------------------------------------------------------
void CheckMemoryLeakNoVar::checkForUnreleasedInputArgument(const Scope *scope)
{
// parse the executable scope until tok is reached...
for (const Token *tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
// allocating memory in parameter for function call..
if (tok->varId() || !Token::Match(tok, "%name% ("))
continue;
// check if the output of the function is assigned
const Token* tok2 = tok->next()->astParent();
while (tok2 && (tok2->isCast() || Token::Match(tok2, "?|:")))
tok2 = tok2->astParent();
if (Token::Match(tok2, "%assign%")) // TODO: check if function returns allocated resource
continue;
if (Token::simpleMatch(tok->astTop(), "return"))
continue;
const std::string& functionName = tok->str();
if ((tok->isCpp() && functionName == "delete") ||
functionName == "return")
continue;
if (Token::simpleMatch(tok->next()->astParent(), "(")) // passed to another function
continue;
if (!tok->isKeyword() && !tok->function() && !mSettings->library.isLeakIgnore(functionName))
continue;
const std::vector<const Token *> args = getArguments(tok);
int argnr = -1;
for (const Token* arg : args) {
++argnr;
if (arg->isOp() && !(tok->isKeyword() && arg->str() == "*")) // e.g. switch (*new int)
continue;
while (arg->astOperand1()) {
if (arg->isCpp() && Token::simpleMatch(arg, "new"))
break;
arg = arg->astOperand1();
}
const AllocType alloc = getAllocationType(arg, 0);
if (alloc == No)
continue;
if (alloc == New || alloc == NewArray) {
const Token* typeTok = arg->next();
bool bail = !typeTok->isStandardType() &&
!mSettings->library.detectContainerOrIterator(typeTok) &&
!mSettings->library.podtype(typeTok->expressionString());
if (bail && typeTok->type() && typeTok->type()->classScope &&
typeTok->type()->classScope->numConstructors == 0 &&
typeTok->type()->classScope->getDestructor() == nullptr) {
bail = false;
}
if (bail)
continue;
}
if (isReopenStandardStream(arg))
continue;
if (tok->function()) {
const Variable* argvar = tok->function()->getArgumentVar(argnr);
if (!argvar || !argvar->valueType())
continue;
const MathLib::bigint argSize = argvar->valueType()->typeSize(mSettings->platform, /*p*/ true);
if (argSize <= 0 || argSize >= mSettings->platform.sizeof_pointer)
continue;
}
functionCallLeak(arg, arg->str(), functionName);
}
}
}
//---------------------------------------------------------------------------
// Checks if a call to an allocation function like malloc() is made and its return value is not assigned.
//---------------------------------------------------------------------------
void CheckMemoryLeakNoVar::checkForUnusedReturnValue(const Scope *scope)
{
for (const Token *tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
const bool isNew = tok->isCpp() && tok->str() == "new";
if (!isNew && !Token::Match(tok, "%name% ("))
continue;
if (tok->varId())
continue;
const AllocType allocType = getAllocationType(tok, 0);
if (allocType == No)
continue;
if (tok != tok->next()->astOperand1() && !isNew)
continue;
if (isReopenStandardStream(tok))
continue;
if (isOpenDevNull(tok))
continue;
// get ast parent, skip casts
const Token *parent = isNew ? tok->astParent() : tok->next()->astParent();
while (parent && parent->isCast())
parent = parent->astParent();
bool warn = true;
if (isNew) {
const Token* typeTok = tok->next();
warn = typeTok && (typeTok->isStandardType() || mSettings->library.detectContainer(typeTok));
}
if (!parent && warn) {
// Check if we are in a C++11 constructor
const Token * closingBrace = Token::findmatch(tok, "}|;");
if (closingBrace->str() == "}" && Token::Match(closingBrace->link()->tokAt(-1), "%name%") && (!isNew && precedes(tok, closingBrace->link())))
continue;
returnValueNotUsedError(tok, tok->str());
} else if (Token::Match(parent, "%comp%|!|,|%oror%|&&|:")) {
if (parent->astParent() && parent->str() == ",")
continue;
if (parent->str() == ":") {
if (!(Token::simpleMatch(parent->astParent(), "?") && !parent->astParent()->astParent()))
continue;
}
returnValueNotUsedError(tok, tok->str());
}
}
}
//---------------------------------------------------------------------------
// Check if an exception could cause a leak in an argument constructed with
// shared_ptr/unique_ptr. For example, in the following code, it is possible
// that if g() throws an exception, the memory allocated by "new int(42)"
// could be leaked. See stackoverflow.com/questions/19034538/
// why-is-there-memory-leak-while-using-shared-ptr-as-a-function-parameter
//
// void x() {
// f(shared_ptr<int>(new int(42)), g());
// }
//---------------------------------------------------------------------------
void CheckMemoryLeakNoVar::checkForUnsafeArgAlloc(const Scope *scope)
{
// This test only applies to C++ source
if (!mTokenizer->isCPP())
return;
if (!mSettings->isPremiumEnabled("leakUnsafeArgAlloc") && (!mSettings->certainty.isEnabled(Certainty::inconclusive) || !mSettings->severity.isEnabled(Severity::warning)))
return;
logChecker("CheckMemoryLeakNoVar::checkForUnsafeArgAlloc");
for (const Token *tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
if (Token::Match(tok, "%name% (")) {
const Token *endParamToken = tok->linkAt(1);
const Token* pointerType = nullptr;
const Token* functionCalled = nullptr;
// Scan through the arguments to the function call
for (const Token *tok2 = tok->tokAt(2); tok2 && tok2 != endParamToken; tok2 = tok2->nextArgument()) {
const Function *func = tok2->function();
const bool isNothrow = func && (func->isAttributeNothrow() || func->isThrow());
if (Token::Match(tok2, "shared_ptr|unique_ptr <") && Token::Match(tok2->linkAt(1), "> ( new %name%")) {
pointerType = tok2;
} else if (!isNothrow) {
if (Token::Match(tok2, "%name% ("))
functionCalled = tok2;
else if (tok2->isName() && Token::simpleMatch(tok2->linkAt(1), "> ("))
functionCalled = tok2;
}
}
if (pointerType && functionCalled) {
std::string functionName = functionCalled->str();
if (functionCalled->strAt(1) == "<") {
functionName += '<';
for (const Token* tok2 = functionCalled->tokAt(2); tok2 != functionCalled->linkAt(1); tok2 = tok2->next())
functionName += tok2->str();
functionName += '>';
}
std::string objectTypeName;
for (const Token* tok2 = pointerType->tokAt(2); tok2 != pointerType->linkAt(1); tok2 = tok2->next())
objectTypeName += tok2->str();
unsafeArgAllocError(tok, functionName, pointerType->str(), objectTypeName);
}
}
}
}
void CheckMemoryLeakNoVar::functionCallLeak(const Token *loc, const std::string &alloc, const std::string &functionCall)
{
reportError(loc, Severity::error, "leakNoVarFunctionCall", "Allocation with " + alloc + ", " + functionCall + " doesn't release it.", CWE772, Certainty::normal);
}
void CheckMemoryLeakNoVar::returnValueNotUsedError(const Token *tok, const std::string &alloc)
{
reportError(tok, Severity::error, "leakReturnValNotUsed", "$symbol:" + alloc + "\nReturn value of allocation function '$symbol' is not stored.", CWE771, Certainty::normal);
}
void CheckMemoryLeakNoVar::unsafeArgAllocError(const Token *tok, const std::string &funcName, const std::string &ptrType, const std::string& objType)
{
const std::string factoryFunc = ptrType == "shared_ptr" ? "make_shared" : "make_unique";
reportError(tok, Severity::warning, "leakUnsafeArgAlloc",
"$symbol:" + funcName + "\n"
"Unsafe allocation. If $symbol() throws, memory could be leaked. Use " + factoryFunc + "<" + objType + ">() instead.",
CWE401,
Certainty::inconclusive); // Inconclusive because funcName may never throw
}
| null |
911 | cpp | cppcheck | errorlogger.h | lib/errorlogger.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef errorloggerH
#define errorloggerH
//---------------------------------------------------------------------------
#include "config.h"
#include "errortypes.h"
#include "color.h"
#include <cstddef>
#include <list>
#include <set>
#include <string>
#include <utility>
#include <vector>
class Token;
class TokenList;
namespace tinyxml2 {
class XMLElement;
}
/// @addtogroup Core
/// @{
/**
* Wrapper for error messages, provided by reportErr()
*/
class CPPCHECKLIB ErrorMessage {
public:
/**
* File name and line number.
* Internally paths are stored with / separator. When getting the filename
* it is by default converted to native separators.
*/
class CPPCHECKLIB WARN_UNUSED FileLocation {
public:
FileLocation(const std::string &file, int line, unsigned int column)
: fileIndex(0), line(line), column(column), mOrigFileName(file), mFileName(file) {}
FileLocation(const std::string &file, std::string info, int line, unsigned int column)
: fileIndex(0), line(line), column(column), mOrigFileName(file), mFileName(file), mInfo(std::move(info)) {}
FileLocation(const Token* tok, const TokenList* tokenList);
FileLocation(const Token* tok, std::string info, const TokenList* tokenList);
/**
* Return the filename.
* @param convert If true convert path to native separators.
* @return filename.
*/
std::string getfile(bool convert = true) const;
/**
* Filename with the whole path (no --rp)
* @param convert If true convert path to native separators.
* @return filename.
*/
std::string getOrigFile(bool convert = true) const;
/**
* Set the filename.
* @param file Filename to set.
*/
void setfile(std::string file);
/**
* @return the location as a string. Format: [file:line]
*/
std::string stringify() const;
unsigned int fileIndex;
int line; // negative value means "no line"
unsigned int column;
const std::string& getinfo() const {
return mInfo;
}
private:
std::string mOrigFileName;
std::string mFileName;
std::string mInfo;
};
ErrorMessage(std::list<FileLocation> callStack,
std::string file1,
Severity severity,
const std::string &msg,
std::string id, Certainty certainty);
ErrorMessage(std::list<FileLocation> callStack,
std::string file1,
Severity severity,
const std::string &msg,
std::string id,
const CWE &cwe,
Certainty certainty);
ErrorMessage(const std::list<const Token*>& callstack,
const TokenList* list,
Severity severity,
std::string id,
const std::string& msg,
Certainty certainty);
ErrorMessage(const std::list<const Token*>& callstack,
const TokenList* list,
Severity severity,
std::string id,
const std::string& msg,
const CWE &cwe,
Certainty certainty);
ErrorMessage(const ErrorPath &errorPath,
const TokenList *tokenList,
Severity severity,
const char id[],
const std::string &msg,
const CWE &cwe,
Certainty certainty);
ErrorMessage();
explicit ErrorMessage(const tinyxml2::XMLElement * errmsg);
/**
* Format the error message in XML format
*/
std::string toXML() const;
static std::string getXMLHeader(std::string productName, int xmlVersion = 2);
static std::string getXMLFooter(int xmlVersion);
/**
* Format the error message into a string.
* @param verbose use verbose message
* @param templateFormat Empty string to use default output format
* or template to be used. E.g. "{file}:{line},{severity},{id},{message}"
* @param templateLocation Format Empty string to use default output format
* or template to be used. E.g. "{file}:{line},{info}"
* @return formatted string
*/
std::string toString(bool verbose,
const std::string &templateFormat = emptyString,
const std::string &templateLocation = emptyString) const;
std::string serialize() const;
void deserialize(const std::string &data);
std::list<FileLocation> callStack;
std::string id;
/** For GUI rechecking; source file (not header) */
std::string file0;
Severity severity;
CWE cwe;
Certainty certainty;
/** remark from REMARK comment */
std::string remark;
/** Warning hash */
std::size_t hash;
/** set short and verbose messages */
void setmsg(const std::string &msg);
/** Short message (single line short message) */
const std::string &shortMessage() const {
return mShortMessage;
}
/** Verbose message (may be the same as the short message) */
// cppcheck-suppress unusedFunction - used by GUI only
const std::string &verboseMessage() const {
return mVerboseMessage;
}
/** Symbol names */
const std::string &symbolNames() const {
return mSymbolNames;
}
static ErrorMessage fromInternalError(const InternalError &internalError, const TokenList *tokenList, const std::string &filename, const std::string& msg = emptyString);
private:
static std::string fixInvalidChars(const std::string& raw);
/** Short message */
std::string mShortMessage;
/** Verbose message */
std::string mVerboseMessage;
/** symbol names */
std::string mSymbolNames;
};
/**
* @brief This is an interface, which the class responsible of error logging
* should implement.
*/
class CPPCHECKLIB ErrorLogger {
public:
ErrorLogger() = default;
virtual ~ErrorLogger() = default;
/**
* Information about progress is directed here.
* Override this to receive the progress messages.
*
* @param outmsg Message to show e.g. "Checking main.cpp..."
*/
virtual void reportOut(const std::string &outmsg, Color c = Color::Reset) = 0;
/**
* Information about found errors and warnings is directed
* here. Override this to receive the errormessages.
*
* @param msg Location and other information about the found error.
*/
virtual void reportErr(const ErrorMessage &msg) = 0;
/**
* Report progress to client
* @param filename main file that is checked
* @param stage for example preprocess / tokenize / simplify / check
* @param value progress value (0-100)
*/
virtual void reportProgress(const std::string &filename, const char stage[], const std::size_t value) {
(void)filename;
(void)stage;
(void)value;
}
static std::string callStackToString(const std::list<ErrorMessage::FileLocation> &callStack);
/**
* Convert XML-sensitive characters into XML entities
* @param str The input string containing XML-sensitive characters
* @return The output string containing XML entities
*/
static std::string toxml(const std::string &str);
static std::string plistHeader(const std::string &version, const std::vector<std::string> &files);
static std::string plistData(const ErrorMessage &msg);
static const char *plistFooter() {
return " </array>\r\n"
"</dict>\r\n"
"</plist>";
}
static bool isCriticalErrorId(const std::string& id) {
return mCriticalErrorIds.count(id) != 0;
}
private:
static const std::set<std::string> mCriticalErrorIds;
};
/** Replace substring. Example replaceStr("1,NR,3", "NR", "2") => "1,2,3" */
std::string replaceStr(std::string s, const std::string &from, const std::string &to);
/** replaces the static parts of the location template **/
CPPCHECKLIB void substituteTemplateFormatStatic(std::string& templateFormat);
/** replaces the static parts of the location template **/
CPPCHECKLIB void substituteTemplateLocationStatic(std::string& templateLocation);
/// @}
//---------------------------------------------------------------------------
#endif // errorloggerH
| null |
912 | cpp | cppcheck | checkinternal.h | lib/checkinternal.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef checkinternalH
#define checkinternalH
//---------------------------------------------------------------------------
#include "check.h"
#include "config.h"
#include "errortypes.h"
#include "settings.h"
#include "tokenize.h"
#include <string>
class ErrorLogger;
class Token;
/// @addtogroup Checks
/// @{
/** @brief %Check Internal cppcheck API usage */
class CPPCHECKLIB CheckInternal : public Check {
public:
/** This constructor is used when registering the CheckClass */
CheckInternal() : Check(myName()) {}
private:
/** This constructor is used when running checks. */
CheckInternal(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {}
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
if (!tokenizer.getSettings().checks.isEnabled(Checks::internalCheck))
return;
CheckInternal checkInternal(&tokenizer, &tokenizer.getSettings(), errorLogger);
checkInternal.checkTokenMatchPatterns();
checkInternal.checkTokenSimpleMatchPatterns();
checkInternal.checkMissingPercentCharacter();
checkInternal.checkUnknownPattern();
checkInternal.checkRedundantNextPrevious();
checkInternal.checkExtraWhitespace();
checkInternal.checkRedundantTokCheck();
}
/** @brief %Check if a simple pattern is used inside Token::Match or Token::findmatch */
void checkTokenMatchPatterns();
/** @brief %Check if a complex pattern is used inside Token::simpleMatch or Token::findsimplematch */
void checkTokenSimpleMatchPatterns();
/** @brief %Check for missing % end character in Token::Match pattern */
void checkMissingPercentCharacter();
/** @brief %Check for unknown (invalid) complex patterns like "%typ%" */
void checkUnknownPattern();
/** @brief %Check for inefficient usage of Token::next(), Token::previous() and Token::tokAt() */
void checkRedundantNextPrevious();
/** @brief %Check if there is whitespace at the beginning or at the end of a pattern */
void checkExtraWhitespace();
/** @brief %Check if there is a redundant check for none-nullness of parameter before Match functions, such as (tok && Token::Match(tok, "foo")) */
void checkRedundantTokCheck();
void multiComparePatternError(const Token *tok, const std::string &pattern, const std::string &funcname);
void simplePatternError(const Token *tok, const std::string &pattern, const std::string &funcname);
void complexPatternError(const Token *tok, const std::string &pattern, const std::string &funcname);
void missingPercentCharacterError(const Token *tok, const std::string &pattern, const std::string &funcname);
void unknownPatternError(const Token* tok, const std::string& pattern);
void redundantNextPreviousError(const Token* tok, const std::string& func1, const std::string& func2);
void orInComplexPattern(const Token *tok, const std::string &pattern, const std::string &funcname);
void extraWhitespaceError(const Token *tok, const std::string &pattern, const std::string &funcname);
void checkRedundantTokCheckError(const Token *tok);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const override {
CheckInternal c(nullptr, settings, errorLogger);
c.multiComparePatternError(nullptr, ";|%type%", "Match");
c.simplePatternError(nullptr, "class {", "Match");
c.complexPatternError(nullptr, "%type% ( )", "Match");
c.missingPercentCharacterError(nullptr, "%num", "Match");
c.unknownPatternError(nullptr, "%typ");
c.redundantNextPreviousError(nullptr, "previous", "next");
c.orInComplexPattern(nullptr, "||", "Match");
c.extraWhitespaceError(nullptr, "%str% ", "Match");
c.checkRedundantTokCheckError(nullptr);
}
static std::string myName() {
return "cppcheck internal API usage";
}
std::string classInfo() const override {
// Don't include these checks on the WIKI where people can read what
// checks there are. These checks are not intended for users.
return "";
}
};
/// @}
//---------------------------------------------------------------------------
#endif // checkinternalH
| null |
913 | cpp | cppcheck | checkassert.cpp | lib/checkassert.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
// You should not write statements with side effects in assert()
//---------------------------------------------------------------------------
#include "checkassert.h"
#include "astutils.h"
#include "errortypes.h"
#include "library.h"
#include "settings.h"
#include "symboldatabase.h"
#include "token.h"
#include "tokenize.h"
#include "tokenlist.h"
#include <algorithm>
#include <utility>
//---------------------------------------------------------------------------
// CWE ids used
static const CWE CWE398(398U); // Indicator of Poor Code Quality
// Register this check class (by creating a static instance of it)
namespace {
CheckAssert instance;
}
void CheckAssert::assertWithSideEffects()
{
if (!mSettings->severity.isEnabled(Severity::warning))
return;
logChecker("CheckAssert::assertWithSideEffects"); // warning
for (const Token* tok = mTokenizer->list.front(); tok; tok = tok->next()) {
if (!Token::simpleMatch(tok, "assert ("))
continue;
const Token *endTok = tok->linkAt(1);
for (const Token* tmp = tok->next(); tmp != endTok; tmp = tmp->next()) {
if (Token::simpleMatch(tmp, "sizeof ("))
tmp = tmp->linkAt(1);
checkVariableAssignment(tmp, tok->scope());
if (tmp->tokType() != Token::eFunction) {
if (const Library::Function* f = mSettings->library.getFunction(tmp)) {
if (f->isconst || f->ispure)
continue;
if (Library::getContainerYield(tmp->next()) != Library::Container::Yield::NO_YIELD) // bailout, assume read access
continue;
if (std::any_of(f->argumentChecks.begin(), f->argumentChecks.end(), [](const std::pair<int, Library::ArgumentChecks>& ac) {
return ac.second.iteratorInfo.container > 0; // bailout, takes iterators -> assume read access
}))
continue;
if (tmp->str() == "get" && Token::simpleMatch(tmp->astParent(), ".") && astIsSmartPointer(tmp->astParent()->astOperand1()))
continue;
if (f->containerYield == Library::Container::Yield::START_ITERATOR || // bailout for std::begin/end/prev/next
f->containerYield == Library::Container::Yield::END_ITERATOR ||
f->containerYield == Library::Container::Yield::ITERATOR)
continue;
sideEffectInAssertError(tmp, mSettings->library.getFunctionName(tmp));
}
continue;
}
const Function* f = tmp->function();
const Scope* scope = f->functionScope;
if (!scope) {
// guess that const method doesn't have side effects
if (f->nestedIn->isClassOrStruct() && !f->isConst() && !f->isStatic())
sideEffectInAssertError(tmp, f->name()); // Non-const member function called, assume it has side effects
continue;
}
for (const Token *tok2 = scope->bodyStart; tok2 != scope->bodyEnd; tok2 = tok2->next()) {
if (!tok2->isAssignmentOp() && tok2->tokType() != Token::eIncDecOp)
continue;
const Variable* var = tok2->previous()->variable();
if (!var || var->isLocal() || (var->isArgument() && !var->isReference() && !var->isPointer()))
continue; // See ticket #4937. Assigning function arguments not passed by reference is ok.
if (var->isArgument() && var->isPointer() && tok2->strAt(-2) != "*")
continue; // Pointers need to be dereferenced, otherwise there is no error
bool noReturnInScope = true;
for (const Token *rt = scope->bodyStart; rt != scope->bodyEnd; rt = rt->next()) {
if (rt->str() != "return") continue; // find all return statements
if (inSameScope(rt, tok2)) {
noReturnInScope = false;
break;
}
}
if (noReturnInScope) continue;
sideEffectInAssertError(tmp, f->name());
break;
}
}
tok = endTok;
}
}
//---------------------------------------------------------------------------
void CheckAssert::sideEffectInAssertError(const Token *tok, const std::string& functionName)
{
reportError(tok, Severity::warning,
"assertWithSideEffect",
"$symbol:" + functionName + "\n"
"Assert statement calls a function which may have desired side effects: '$symbol'.\n"
"Non-pure function: '$symbol' is called inside assert statement. "
"Assert statements are removed from release builds so the code inside "
"assert statement is not executed. If the code is needed also in release "
"builds, this is a bug.", CWE398, Certainty::normal);
}
void CheckAssert::assignmentInAssertError(const Token *tok, const std::string& varname)
{
reportError(tok, Severity::warning,
"assignmentInAssert",
"$symbol:" + varname + "\n"
"Assert statement modifies '$symbol'.\n"
"Variable '$symbol' is modified inside assert statement. "
"Assert statements are removed from release builds so the code inside "
"assert statement is not executed. If the code is needed also in release "
"builds, this is a bug.", CWE398, Certainty::normal);
}
// checks if side effects happen on the variable prior to tmp
void CheckAssert::checkVariableAssignment(const Token* assignTok, const Scope *assertionScope)
{
if (!assignTok->isAssignmentOp() && assignTok->tokType() != Token::eIncDecOp)
return;
const Variable* var = assignTok->astOperand1()->variable();
if (!var)
return;
// Variable declared in inner scope in assert => don't warn
if (assertionScope != var->scope()) {
const Scope *s = var->scope();
while (s && s != assertionScope)
s = s->nestedIn;
if (s == assertionScope)
return;
}
// assignment
if (assignTok->isAssignmentOp() || assignTok->tokType() == Token::eIncDecOp) {
if (var->isConst()) {
return;
}
assignmentInAssertError(assignTok, var->name());
}
// TODO: function calls on var
}
bool CheckAssert::inSameScope(const Token* returnTok, const Token* assignTok)
{
// TODO: even if a return is in the same scope, the assignment might not affect it.
return returnTok->scope() == assignTok->scope();
}
| null |
914 | cpp | cppcheck | checkstring.cpp | lib/checkstring.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#include "checkstring.h"
#include "astutils.h"
#include "errortypes.h"
#include "mathlib.h"
#include "settings.h"
#include "symboldatabase.h"
#include "token.h"
#include "tokenize.h"
#include "utils.h"
#include <cstddef>
#include <list>
#include <vector>
#include <utility>
//---------------------------------------------------------------------------
// Register this check class (by creating a static instance of it)
namespace {
CheckString instance;
}
// CWE ids used:
static const CWE CWE570(570U); // Expression is Always False
static const CWE CWE571(571U); // Expression is Always True
static const CWE CWE595(595U); // Comparison of Object References Instead of Object Contents
static const CWE CWE628(628U); // Function Call with Incorrectly Specified Arguments
static const CWE CWE665(665U); // Improper Initialization
static const CWE CWE758(758U); // Reliance on Undefined, Unspecified, or Implementation-Defined Behavior
//---------------------------------------------------------------------------
// Writing string literal is UB
//---------------------------------------------------------------------------
void CheckString::stringLiteralWrite()
{
logChecker("CheckString::stringLiteralWrite");
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (!tok->variable() || !tok->variable()->isPointer())
continue;
const Token *str = tok->getValueTokenMinStrSize(*mSettings);
if (!str)
continue;
if (Token::Match(tok, "%var% [") && Token::simpleMatch(tok->linkAt(1), "] ="))
stringLiteralWriteError(tok, str);
else if (Token::Match(tok->previous(), "* %var% ="))
stringLiteralWriteError(tok, str);
}
}
}
void CheckString::stringLiteralWriteError(const Token *tok, const Token *strValue)
{
std::list<const Token*> callstack{ tok };
if (strValue)
callstack.push_back(strValue);
std::string errmsg("Modifying string literal");
if (strValue) {
std::string s = strValue->str();
// 20 is an arbitrary value, the max string length shown in a warning message
if (s.size() > 20U)
s.replace(17, std::string::npos, "..\"");
errmsg += " " + s;
}
errmsg += " directly or indirectly is undefined behaviour.";
reportError(callstack, Severity::error, "stringLiteralWrite", errmsg, CWE758, Certainty::normal);
}
//---------------------------------------------------------------------------
// Check for string comparison involving two static strings.
// if(strcmp("00FF00","00FF00")==0) // <- statement is always true
//---------------------------------------------------------------------------
void CheckString::checkAlwaysTrueOrFalseStringCompare()
{
if (!mSettings->severity.isEnabled(Severity::warning))
return;
logChecker("CheckString::checkAlwaysTrueOrFalseStringCompare"); // warning
for (const Token* tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (tok->isName() && tok->strAt(1) == "(" && Token::Match(tok, "memcmp|strncmp|strcmp|stricmp|strverscmp|bcmp|strcmpi|strcasecmp|strncasecmp|strncasecmp_l|strcasecmp_l|wcsncasecmp|wcscasecmp|wmemcmp|wcscmp|wcscasecmp_l|wcsncasecmp_l|wcsncmp|_mbscmp|_mbscmp_l|_memicmp|_memicmp_l|_stricmp|_wcsicmp|_mbsicmp|_stricmp_l|_wcsicmp_l|_mbsicmp_l")) {
if (Token::Match(tok->tokAt(2), "%str% , %str% ,|)")) {
const std::string &str1 = tok->strAt(2);
const std::string &str2 = tok->strAt(4);
if (!tok->isExpandedMacro() && !tok->tokAt(2)->isExpandedMacro() && !tok->tokAt(4)->isExpandedMacro())
alwaysTrueFalseStringCompareError(tok, str1, str2);
tok = tok->tokAt(5);
} else if (Token::Match(tok->tokAt(2), "%name% , %name% ,|)")) {
const std::string &str1 = tok->strAt(2);
const std::string &str2 = tok->strAt(4);
if (str1 == str2)
alwaysTrueStringVariableCompareError(tok, str1, str2);
tok = tok->tokAt(5);
} else if (Token::Match(tok->tokAt(2), "%name% . c_str ( ) , %name% . c_str ( ) ,|)")) {
const std::string &str1 = tok->strAt(2);
const std::string &str2 = tok->strAt(8);
if (str1 == str2)
alwaysTrueStringVariableCompareError(tok, str1, str2);
tok = tok->tokAt(13);
}
} else if (tok->isName() && Token::Match(tok, "QString :: compare ( %str% , %str% )")) {
const std::string &str1 = tok->strAt(4);
const std::string &str2 = tok->strAt(6);
alwaysTrueFalseStringCompareError(tok, str1, str2);
tok = tok->tokAt(7);
} else if (Token::Match(tok, "!!+ %str% ==|!= %str% !!+")) {
const std::string &str1 = tok->strAt(1);
const std::string &str2 = tok->strAt(3);
alwaysTrueFalseStringCompareError(tok, str1, str2);
tok = tok->tokAt(5);
}
if (!tok)
break;
}
}
void CheckString::alwaysTrueFalseStringCompareError(const Token *tok, const std::string& str1, const std::string& str2)
{
constexpr std::size_t stringLen = 10;
const std::string string1 = (str1.size() < stringLen) ? str1 : (str1.substr(0, stringLen-2) + "..");
const std::string string2 = (str2.size() < stringLen) ? str2 : (str2.substr(0, stringLen-2) + "..");
reportError(tok, Severity::warning, "staticStringCompare",
"Unnecessary comparison of static strings.\n"
"The compared strings, '" + string1 + "' and '" + string2 + "', are always " + (str1==str2?"identical":"unequal") + ". "
"Therefore the comparison is unnecessary and looks suspicious.", (str1==str2)?CWE571:CWE570, Certainty::normal);
}
void CheckString::alwaysTrueStringVariableCompareError(const Token *tok, const std::string& str1, const std::string& str2)
{
reportError(tok, Severity::warning, "stringCompare",
"Comparison of identical string variables.\n"
"The compared strings, '" + str1 + "' and '" + str2 + "', are identical. "
"This could be a logic bug.", CWE571, Certainty::normal);
}
//-----------------------------------------------------------------------------
// Detect "str == '\0'" where "*str == '\0'" is correct.
// Comparing char* with each other instead of using strcmp()
//-----------------------------------------------------------------------------
void CheckString::checkSuspiciousStringCompare()
{
if (!mSettings->severity.isEnabled(Severity::warning))
return;
logChecker("CheckString::checkSuspiciousStringCompare"); // warning
const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (!tok->isComparisonOp())
continue;
const Token* varTok = tok->astOperand1();
const Token* litTok = tok->astOperand2();
if (!varTok || !litTok) // <- failed to create AST for comparison
continue;
if (Token::Match(varTok, "%char%|%num%|%str%"))
std::swap(varTok, litTok);
else if (!Token::Match(litTok, "%char%|%num%|%str%"))
continue;
if (varTok->isLiteral())
continue;
const ValueType* varType = varTok->valueType();
if (varTok->isCpp() && (!varType || !varType->isIntegral()))
continue;
if (litTok->tokType() == Token::eString) {
if (varTok->isC() || (varType && varType->pointer))
suspiciousStringCompareError(tok, varTok->expressionString(), litTok->isLong());
} else if (litTok->tokType() == Token::eChar && varType && varType->pointer) {
suspiciousStringCompareError_char(tok, varTok->expressionString());
}
}
}
}
void CheckString::suspiciousStringCompareError(const Token* tok, const std::string& var, bool isLong)
{
const std::string cmpFunc = isLong ? "wcscmp" : "strcmp";
reportError(tok, Severity::warning, "literalWithCharPtrCompare",
"$symbol:" + var + "\nString literal compared with variable '$symbol'. Did you intend to use " + cmpFunc + "() instead?", CWE595, Certainty::normal);
}
void CheckString::suspiciousStringCompareError_char(const Token* tok, const std::string& var)
{
reportError(tok, Severity::warning, "charLiteralWithCharPtrCompare",
"$symbol:" + var + "\nChar literal compared with pointer '$symbol'. Did you intend to dereference it?", CWE595, Certainty::normal);
}
//---------------------------------------------------------------------------
// Adding C-string and char with operator+
//---------------------------------------------------------------------------
static bool isChar(const Variable* var)
{
return (var && !var->isPointer() && !var->isArray() && (var->typeStartToken()->str() == "char" || var->typeStartToken()->str() == "wchar_t"));
}
void CheckString::strPlusChar()
{
logChecker("CheckString::strPlusChar");
const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (tok->str() == "+") {
if (tok->astOperand1() && (tok->astOperand1()->tokType() == Token::eString)) { // string literal...
if (tok->astOperand2() && (tok->astOperand2()->tokType() == Token::eChar || isChar(tok->astOperand2()->variable()))) // added to char variable or char constant
strPlusCharError(tok);
}
}
}
}
}
void CheckString::strPlusCharError(const Token *tok)
{
std::string charType = "char";
if (tok && tok->astOperand2() && tok->astOperand2()->variable())
charType = tok->astOperand2()->variable()->typeStartToken()->str();
else if (tok && tok->astOperand2() && tok->astOperand2()->tokType() == Token::eChar && tok->astOperand2()->isLong())
charType = "wchar_t";
reportError(tok, Severity::error, "strPlusChar", "Unusual pointer arithmetic. A value of type '" + charType +"' is added to a string literal.", CWE665, Certainty::normal);
}
static bool isMacroUsage(const Token* tok)
{
if (const Token* parent = tok->astParent()) {
while (parent && (parent->isCast() || parent->str() == "&&")) {
if (parent->isExpandedMacro())
return true;
parent = parent->astParent();
}
if (!parent)
return false;
if (parent->isExpandedMacro())
return true;
if (parent->isUnaryOp("!") || parent->isComparisonOp()) {
int argn{};
const Token* ftok = getTokenArgumentFunction(parent, argn);
if (ftok && !ftok->function())
return true;
}
}
return false;
}
//---------------------------------------------------------------------------
// Implicit casts of string literals to bool
// Comparing string literal with strlen() with wrong length
//---------------------------------------------------------------------------
void CheckString::checkIncorrectStringCompare()
{
if (!mSettings->severity.isEnabled(Severity::warning))
return;
logChecker("CheckString::checkIncorrectStringCompare"); // warning
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
// skip "assert(str && ..)" and "assert(.. && str)"
if ((endsWith(tok->str(), "assert") || endsWith(tok->str(), "ASSERT")) &&
Token::Match(tok, "%name% (") &&
(Token::Match(tok->tokAt(2), "%str% &&") || Token::Match(tok->linkAt(1)->tokAt(-2), "&& %str% )")))
tok = tok->linkAt(1);
if (Token::simpleMatch(tok, ". substr (") && Token::Match(tok->tokAt(3)->nextArgument(), "%num% )")) {
const MathLib::biguint clen = MathLib::toBigUNumber(tok->linkAt(2)->strAt(-1));
const Token* begin = tok->previous();
for (;;) { // Find start of statement
while (begin->link() && Token::Match(begin, "]|)|>"))
begin = begin->link()->previous();
if (Token::Match(begin->previous(), ".|::"))
begin = begin->tokAt(-2);
else
break;
}
begin = begin->previous();
const Token* end = tok->linkAt(2)->next();
if (Token::Match(begin->previous(), "%str% ==|!=") && begin->strAt(-2) != "+") {
const std::size_t slen = Token::getStrLength(begin->previous());
if (clen != slen) {
incorrectStringCompareError(tok->next(), "substr", begin->strAt(-1));
}
} else if (Token::Match(end, "==|!= %str% !!+")) {
const std::size_t slen = Token::getStrLength(end->next());
if (clen != slen) {
incorrectStringCompareError(tok->next(), "substr", end->strAt(1));
}
}
} else if (Token::Match(tok, "%str%|%char%") &&
isUsedAsBool(tok, *mSettings) &&
!isMacroUsage(tok))
incorrectStringBooleanError(tok, tok->str());
}
}
}
void CheckString::incorrectStringCompareError(const Token *tok, const std::string& func, const std::string &string)
{
reportError(tok, Severity::warning, "incorrectStringCompare", "$symbol:" + func + "\nString literal " + string + " doesn't match length argument for $symbol().", CWE570, Certainty::normal);
}
void CheckString::incorrectStringBooleanError(const Token *tok, const std::string& string)
{
const bool charLiteral = isCharLiteral(string);
const std::string literalType = charLiteral ? "char" : "string";
const std::string result = bool_to_string(getCharLiteral(string) != "\\0");
reportError(tok,
Severity::warning,
charLiteral ? "incorrectCharBooleanError" : "incorrectStringBooleanError",
"Conversion of " + literalType + " literal " + string + " to bool always evaluates to " + result + '.', CWE571, Certainty::normal);
}
//---------------------------------------------------------------------------
// always true: strcmp(str,"a")==0 || strcmp(str,"b")
// TODO: Library configuration for string comparison functions
//---------------------------------------------------------------------------
void CheckString::overlappingStrcmp()
{
if (!mSettings->severity.isEnabled(Severity::warning))
return;
logChecker("CheckString::overlappingStrcmp"); // warning
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (tok->str() != "||")
continue;
std::list<const Token *> equals0;
std::list<const Token *> notEquals0;
visitAstNodes(tok, [&](const Token * t) {
if (!t)
return ChildrenToVisit::none;
if (t->str() == "||") {
return ChildrenToVisit::op1_and_op2;
}
if (t->str() == "==") {
if (Token::simpleMatch(t->astOperand1(), "(") && Token::simpleMatch(t->astOperand2(), "0"))
equals0.push_back(t->astOperand1());
else if (Token::simpleMatch(t->astOperand2(), "(") && Token::simpleMatch(t->astOperand1(), "0"))
equals0.push_back(t->astOperand2());
return ChildrenToVisit::none;
}
if (t->str() == "!=") {
if (Token::simpleMatch(t->astOperand1(), "(") && Token::simpleMatch(t->astOperand2(), "0"))
notEquals0.push_back(t->astOperand1());
else if (Token::simpleMatch(t->astOperand2(), "(") && Token::simpleMatch(t->astOperand1(), "0"))
notEquals0.push_back(t->astOperand2());
return ChildrenToVisit::none;
}
if (t->str() == "!" && Token::simpleMatch(t->astOperand1(), "("))
equals0.push_back(t->astOperand1());
else if (t->str() == "(")
notEquals0.push_back(t);
return ChildrenToVisit::none;
});
for (const Token *eq0 : equals0) {
for (const Token * ne0 : notEquals0) {
if (!Token::Match(eq0->previous(), "strcmp|wcscmp ("))
continue;
if (!Token::Match(ne0->previous(), "strcmp|wcscmp ("))
continue;
const std::vector<const Token *> args1 = getArguments(eq0->previous());
const std::vector<const Token *> args2 = getArguments(ne0->previous());
if (args1.size() != 2 || args2.size() != 2)
continue;
if (args1[1]->isLiteral() &&
args2[1]->isLiteral() &&
args1[1]->str() != args2[1]->str() &&
isSameExpression(true, args1[0], args2[0], *mSettings, true, false))
overlappingStrcmpError(eq0, ne0);
}
}
}
}
}
void CheckString::overlappingStrcmpError(const Token *eq0, const Token *ne0)
{
std::string eq0Expr(eq0 ? eq0->expressionString() : std::string("strcmp(x,\"abc\")"));
if (eq0 && eq0->astParent()->str() == "!")
eq0Expr = "!" + eq0Expr;
else
eq0Expr += " == 0";
const std::string ne0Expr = (ne0 ? ne0->expressionString() : std::string("strcmp(x,\"def\")")) + " != 0";
reportError(ne0, Severity::warning, "overlappingStrcmp", "The expression '" + ne0Expr + "' is suspicious. It overlaps '" + eq0Expr + "'.");
}
//---------------------------------------------------------------------------
// Overlapping source and destination passed to sprintf().
// TODO: Library configuration for overlapping arguments
//---------------------------------------------------------------------------
void CheckString::sprintfOverlappingData()
{
logChecker("CheckString::sprintfOverlappingData");
const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (!Token::Match(tok, "sprintf|snprintf|swprintf ("))
continue;
const std::vector<const Token *> args = getArguments(tok);
const int formatString = Token::simpleMatch(tok, "sprintf") ? 1 : 2;
for (unsigned int argnr = formatString + 1; argnr < args.size(); ++argnr) {
const Token *dest = args[0];
while (dest->isCast())
dest = dest->astOperand2() ? dest->astOperand2() : dest->astOperand1();
const Token *arg = args[argnr];
if (!arg->valueType() || arg->valueType()->pointer != 1)
continue;
while (arg->isCast())
arg = arg->astOperand2() ? arg->astOperand2() : arg->astOperand1();
const bool same = isSameExpression(false,
dest,
arg,
*mSettings,
true,
false);
if (same) {
sprintfOverlappingDataError(tok, args[argnr], arg->expressionString());
}
}
}
}
}
void CheckString::sprintfOverlappingDataError(const Token *funcTok, const Token *tok, const std::string &varname)
{
const std::string func = funcTok ? funcTok->str() : "s[n]printf";
reportError(tok, Severity::error, "sprintfOverlappingData",
"$symbol:" + varname + "\n"
"Undefined behavior: Variable '$symbol' is used as parameter and destination in " + func + "().\n" +
"The variable '$symbol' is used both as a parameter and as destination in " +
func + "(). The origin and destination buffers overlap. Quote from glibc (C-library) "
"documentation (http://www.gnu.org/software/libc/manual/html_mono/libc.html#Formatted-Output-Functions): "
"\"If copying takes place between objects that overlap as a result of a call "
"to sprintf() or snprintf(), the results are undefined.\"", CWE628, Certainty::normal);
}
| null |
915 | cpp | cppcheck | checkunusedvar.h | lib/checkunusedvar.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef checkunusedvarH
#define checkunusedvarH
//---------------------------------------------------------------------------
#include "check.h"
#include "config.h"
#include "tokenize.h"
#include <list>
#include <map>
#include <string>
class ErrorLogger;
class Scope;
class Settings;
class Token;
class Type;
class Variables;
class Variable;
class Function;
/// @addtogroup Checks
/// @{
/** @brief Various small checks */
class CPPCHECKLIB CheckUnusedVar : public Check {
friend class TestUnusedVar;
public:
/** @brief This constructor is used when registering the CheckClass */
CheckUnusedVar() : Check(myName()) {}
private:
/** @brief This constructor is used when running checks. */
CheckUnusedVar(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {}
/** @brief Run checks against the normal token list */
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
CheckUnusedVar checkUnusedVar(&tokenizer, &tokenizer.getSettings(), errorLogger);
// Coding style checks
checkUnusedVar.checkStructMemberUsage();
checkUnusedVar.checkFunctionVariableUsage();
}
/** @brief %Check for unused function variables */
void checkFunctionVariableUsage_iterateScopes(const Scope* scope, Variables& variables);
void checkFunctionVariableUsage();
/** @brief %Check that all struct members are used */
void checkStructMemberUsage();
bool isRecordTypeWithoutSideEffects(const Type* type);
bool isVariableWithoutSideEffects(const Variable& var, const Type* type = nullptr);
bool isEmptyType(const Type* type);
bool isFunctionWithoutSideEffects(const Function& func, const Token* functionUsageToken,
std::list<const Function*> checkedFuncs);
// Error messages..
void unusedStructMemberError(const Token *tok, const std::string &structname, const std::string &varname, const std::string& prefix = "struct");
void unusedVariableError(const Token *tok, const std::string &varname);
void allocatedButUnusedVariableError(const Token *tok, const std::string &varname);
void unreadVariableError(const Token *tok, const std::string &varname, bool modified);
void unassignedVariableError(const Token *tok, const std::string &varname);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const override {
CheckUnusedVar c(nullptr, settings, errorLogger);
c.unusedVariableError(nullptr, "varname");
c.allocatedButUnusedVariableError(nullptr, "varname");
c.unreadVariableError(nullptr, "varname", false);
c.unassignedVariableError(nullptr, "varname");
c.unusedStructMemberError(nullptr, "structname", "variable");
}
static std::string myName() {
return "UnusedVar";
}
std::string classInfo() const override {
return "UnusedVar checks\n"
// style
"- unused variable\n"
"- allocated but unused variable\n"
"- unread variable\n"
"- unassigned variable\n"
"- unused struct member\n";
}
std::map<const Type *,bool> mIsRecordTypeWithoutSideEffectsMap;
std::map<const Type *,bool> mIsEmptyTypeMap;
};
/// @}
//---------------------------------------------------------------------------
#endif // checkunusedvarH
| null |
916 | cpp | cppcheck | analyzerinfo.cpp | lib/analyzerinfo.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "analyzerinfo.h"
#include "errorlogger.h"
#include "filesettings.h"
#include "path.h"
#include "utils.h"
#include <cstring>
#include <map>
#include "xml.h"
AnalyzerInformation::~AnalyzerInformation()
{
close();
}
static std::string getFilename(const std::string &fullpath)
{
std::string::size_type pos1 = fullpath.find_last_of("/\\");
pos1 = (pos1 == std::string::npos) ? 0U : (pos1 + 1U);
std::string::size_type pos2 = fullpath.rfind('.');
if (pos2 < pos1)
pos2 = std::string::npos;
if (pos2 != std::string::npos)
pos2 = pos2 - pos1;
return fullpath.substr(pos1,pos2);
}
void AnalyzerInformation::writeFilesTxt(const std::string &buildDir, const std::list<std::string> &sourcefiles, const std::string &userDefines, const std::list<FileSettings> &fileSettings)
{
std::map<std::string, unsigned int> fileCount;
const std::string filesTxt(buildDir + "/files.txt");
std::ofstream fout(filesTxt);
for (const std::string &f : sourcefiles) {
const std::string afile = getFilename(f);
fout << afile << ".a" << (++fileCount[afile]) << "::" << Path::simplifyPath(f) << '\n';
if (!userDefines.empty())
fout << afile << ".a" << (++fileCount[afile]) << ":" << userDefines << ":" << Path::simplifyPath(f) << '\n';
}
for (const FileSettings &fs : fileSettings) {
const std::string afile = getFilename(fs.filename());
fout << afile << ".a" << (++fileCount[afile]) << ":" << fs.cfg << ":" << Path::simplifyPath(fs.filename()) << std::endl;
}
}
void AnalyzerInformation::close()
{
mAnalyzerInfoFile.clear();
if (mOutputStream.is_open()) {
mOutputStream << "</analyzerinfo>\n";
mOutputStream.close();
}
}
static bool skipAnalysis(const std::string &analyzerInfoFile, std::size_t hash, std::list<ErrorMessage> &errors)
{
tinyxml2::XMLDocument doc;
const tinyxml2::XMLError error = doc.LoadFile(analyzerInfoFile.c_str());
if (error != tinyxml2::XML_SUCCESS)
return false;
const tinyxml2::XMLElement * const rootNode = doc.FirstChildElement();
if (rootNode == nullptr)
return false;
const char *attr = rootNode->Attribute("hash");
if (!attr || attr != std::to_string(hash))
return false;
for (const tinyxml2::XMLElement *e = rootNode->FirstChildElement(); e; e = e->NextSiblingElement()) {
if (std::strcmp(e->Name(), "error") == 0)
errors.emplace_back(e);
}
return true;
}
std::string AnalyzerInformation::getAnalyzerInfoFileFromFilesTxt(std::istream& filesTxt, const std::string &sourcefile, const std::string &cfg)
{
std::string line;
const std::string end(':' + cfg + ':' + Path::simplifyPath(sourcefile));
while (std::getline(filesTxt,line)) {
if (line.size() <= end.size() + 2U)
continue;
if (!endsWith(line, end.c_str(), end.size()))
continue;
return line.substr(0,line.find(':'));
}
return "";
}
std::string AnalyzerInformation::getAnalyzerInfoFile(const std::string &buildDir, const std::string &sourcefile, const std::string &cfg)
{
std::ifstream fin(Path::join(buildDir, "files.txt"));
if (fin.is_open()) {
const std::string& ret = getAnalyzerInfoFileFromFilesTxt(fin, sourcefile, cfg);
if (!ret.empty())
return Path::join(buildDir, ret);
}
const std::string::size_type pos = sourcefile.rfind('/');
std::string filename;
if (pos == std::string::npos)
filename = sourcefile;
else
filename = sourcefile.substr(pos + 1);
return Path::join(buildDir, filename) + ".analyzerinfo";
}
bool AnalyzerInformation::analyzeFile(const std::string &buildDir, const std::string &sourcefile, const std::string &cfg, std::size_t hash, std::list<ErrorMessage> &errors)
{
if (buildDir.empty() || sourcefile.empty())
return true;
close();
mAnalyzerInfoFile = AnalyzerInformation::getAnalyzerInfoFile(buildDir,sourcefile,cfg);
if (skipAnalysis(mAnalyzerInfoFile, hash, errors))
return false;
mOutputStream.open(mAnalyzerInfoFile);
if (mOutputStream.is_open()) {
mOutputStream << "<?xml version=\"1.0\"?>\n";
mOutputStream << "<analyzerinfo hash=\"" << hash << "\">\n";
} else {
mAnalyzerInfoFile.clear();
}
return true;
}
void AnalyzerInformation::reportErr(const ErrorMessage &msg)
{
if (mOutputStream.is_open())
mOutputStream << msg.toXML() << '\n';
}
void AnalyzerInformation::setFileInfo(const std::string &check, const std::string &fileInfo)
{
if (mOutputStream.is_open() && !fileInfo.empty())
mOutputStream << " <FileInfo check=\"" << check << "\">\n" << fileInfo << " </FileInfo>\n";
}
| null |
917 | cpp | cppcheck | pathmatch.h | lib/pathmatch.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PATHMATCH_H
#define PATHMATCH_H
#include "config.h"
#include <string>
#include <vector>
/// @addtogroup CLI
/// @{
/**
* @brief Simple path matching for ignoring paths in CLI.
*/
class CPPCHECKLIB PathMatch {
public:
/**
* The constructor.
* @param paths List of masks.
* @param caseSensitive Match the case of the characters when
* matching paths?
*/
explicit PathMatch(std::vector<std::string> paths, bool caseSensitive = true);
/**
* @brief Match path against list of masks.
* @param path Path to match.
* @return true if any of the masks match the path, false otherwise.
*/
bool match(const std::string &path) const;
protected:
/**
* @brief Remove filename part from the path.
* @param path Path to edit.
* @return path without filename part.
*/
static std::string removeFilename(const std::string &path);
private:
std::vector<std::string> mPaths;
bool mCaseSensitive;
std::vector<std::string> mWorkingDirectory;
};
/// @}
#endif // PATHMATCH_H
| null |
918 | cpp | cppcheck | symboldatabase.cpp | lib/symboldatabase.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#include "symboldatabase.h"
#include "astutils.h"
#include "errorlogger.h"
#include "errortypes.h"
#include "keywords.h"
#include "library.h"
#include "mathlib.h"
#include "path.h"
#include "platform.h"
#include "settings.h"
#include "standards.h"
#include "templatesimplifier.h"
#include "token.h"
#include "tokenize.h"
#include "tokenlist.h"
#include "utils.h"
#include "valueflow.h"
#include <algorithm>
#include <cassert>
#include <cstring>
#include <initializer_list>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <sstream>
#include <stack>
#include <string>
#include <tuple>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
//---------------------------------------------------------------------------
SymbolDatabase::SymbolDatabase(Tokenizer& tokenizer, const Settings& settings, ErrorLogger& errorLogger)
: mTokenizer(tokenizer), mSettings(settings), mErrorLogger(errorLogger)
{
if (!mTokenizer.tokens())
return;
if (mSettings.platform.defaultSign == 's' || mSettings.platform.defaultSign == 'S')
mDefaultSignedness = ValueType::SIGNED;
else if (mSettings.platform.defaultSign == 'u' || mSettings.platform.defaultSign == 'U')
mDefaultSignedness = ValueType::UNSIGNED;
else
mDefaultSignedness = ValueType::UNKNOWN_SIGN;
createSymbolDatabaseFindAllScopes();
createSymbolDatabaseClassInfo();
createSymbolDatabaseVariableInfo();
createSymbolDatabaseCopyAndMoveConstructors();
createSymbolDatabaseFunctionScopes();
createSymbolDatabaseClassAndStructScopes();
createSymbolDatabaseFunctionReturnTypes();
createSymbolDatabaseNeedInitialization();
createSymbolDatabaseVariableSymbolTable();
createSymbolDatabaseSetScopePointers();
createSymbolDatabaseSetVariablePointers();
createSymbolDatabaseSetTypePointers();
setValueTypeInTokenList(false);
createSymbolDatabaseSetFunctionPointers(true);
createSymbolDatabaseSetSmartPointerType();
setValueTypeInTokenList(false);
createSymbolDatabaseEnums();
createSymbolDatabaseEscapeFunctions();
createSymbolDatabaseIncompleteVars();
createSymbolDatabaseExprIds();
debugSymbolDatabase();
}
static const Token* skipScopeIdentifiers(const Token* tok)
{
if (Token::Match(tok, ":: %name%"))
tok = tok->next();
while (Token::Match(tok, "%name% ::") ||
(Token::Match(tok, "%name% <") && Token::Match(tok->linkAt(1), ">|>> ::"))) {
if (tok->strAt(1) == "::")
tok = tok->tokAt(2);
else
tok = tok->linkAt(1)->tokAt(2);
}
return tok;
}
static bool isExecutableScope(const Token* tok)
{
if (!Token::simpleMatch(tok, "{"))
return false;
const Token * tok2 = tok->link()->previous();
if (Token::simpleMatch(tok2, "; }"))
return true;
if (tok2 == tok)
return false;
if (Token::simpleMatch(tok2, "} }")) { // inner scope
const Token* startTok = tok2->link();
if (Token::Match(startTok->previous(), "do|try|else {"))
return true;
if (Token::Match(startTok->previous(), ")|] {"))
return !findLambdaStartToken(tok2);
return isExecutableScope(startTok);
}
return false;
}
const Token* SymbolDatabase::isEnumDefinition(const Token* tok)
{
if (!Token::Match(tok, "enum class| %name%| {|:"))
return nullptr;
while (!Token::Match(tok, "[{:]"))
tok = tok->next();
if (tok->str() == "{")
return tok;
tok = tok->next(); // skip ':'
while (Token::Match(tok, "%name%|::"))
tok = tok->next();
return Token::simpleMatch(tok, "{") ? tok : nullptr;
}
void SymbolDatabase::createSymbolDatabaseFindAllScopes()
{
// create global scope
scopeList.emplace_back(this, nullptr, nullptr);
// pointer to current scope
Scope *scope = &scopeList.back();
// Store the ending of init lists
std::stack<std::pair<const Token*, const Scope*>> endInitList;
auto inInitList = [&] {
if (endInitList.empty())
return false;
return endInitList.top().second == scope;
};
std::stack<const Token*> inIfCondition;
auto addLambda = [this, &scope](const Token* tok, const Token* lambdaEndToken) -> const Token* {
const Token* lambdaStartToken = lambdaEndToken->link();
const Token* argStart = lambdaStartToken->astParent();
const Token* funcStart = Token::simpleMatch(argStart, "[") ? argStart : argStart->astParent();
const Function* function = addGlobalFunction(scope, tok, argStart, funcStart);
if (!function)
mTokenizer.syntaxError(tok);
return lambdaStartToken;
};
// Store current access in each scope (depends on evaluation progress)
std::map<const Scope*, AccessControl> access;
// find all scopes
for (const Token *tok = mTokenizer.tokens(); tok; tok = tok ? tok->next() : nullptr) {
// #5593 suggested to add here:
mErrorLogger.reportProgress(mTokenizer.list.getSourceFilePath(),
"SymbolDatabase",
tok->progressValue());
// Locate next class
if ((tok->isCpp() && tok->isKeyword() &&
((Token::Match(tok, "class|struct|union|namespace ::| %name% final| {|:|::|<") &&
!Token::Match(tok->previous(), "new|friend|const|enum|typedef|mutable|volatile|using|)|(|<")) ||
isEnumDefinition(tok)))
|| (tok->isC() && tok->isKeyword() && Token::Match(tok, "struct|union|enum %name% {"))) {
const Token *tok2 = tok->tokAt(2);
if (tok->strAt(1) == "::")
tok2 = tok2->next();
else if (tok->isCpp() && tok->strAt(1) == "class")
tok2 = tok2->next();
while (Token::Match(tok2, ":: %name%"))
tok2 = tok2->tokAt(2);
while (Token::Match(tok2, "%name% :: %name%"))
tok2 = tok2->tokAt(2);
// skip over template args
while (tok2 && tok2->str() == "<" && tok2->link()) {
tok2 = tok2->link()->next();
while (Token::Match(tok2, ":: %name%"))
tok2 = tok2->tokAt(2);
}
// skip over final
if (tok2 && tok2->isCpp() && Token::simpleMatch(tok2, "final"))
tok2 = tok2->next();
// make sure we have valid code
if (!Token::Match(tok2, "{|:")) {
// check for qualified variable
if (tok2 && tok2->next()) {
if (tok2->strAt(1) == ";")
tok = tok2->next();
else if (Token::simpleMatch(tok2->next(), "= {") &&
Token::simpleMatch(tok2->linkAt(2), "} ;"))
tok = tok2->linkAt(2)->next();
else if (Token::Match(tok2->next(), "(|{") &&
tok2->linkAt(1)->strAt(1) == ";")
tok = tok2->linkAt(1)->next();
// skip variable declaration
else if (Token::Match(tok2, "*|&|>"))
continue;
else if (Token::Match(tok2, "%name% (") && Tokenizer::isFunctionHead(tok2->next(), "{;"))
continue;
else if (Token::Match(tok2, "%name% [|="))
continue;
// skip template
else if (Token::simpleMatch(tok2, ";") &&
Token::Match(tok->previous(), "template|> class|struct")) {
tok = tok2;
continue;
}
// forward declaration
else if (Token::simpleMatch(tok2, ";") &&
Token::Match(tok, "class|struct|union")) {
// TODO: see if it can be used
tok = tok2;
continue;
}
// skip constructor
else if (Token::simpleMatch(tok2, "(") &&
Token::simpleMatch(tok2->link(), ") ;")) {
tok = tok2->link()->next();
continue;
} else
throw InternalError(tok2, "SymbolDatabase bailout; unhandled code", InternalError::SYNTAX);
continue;
}
break; // bail
}
const Token * name = tok->next();
if (name->str() == "class" && name->strAt(-1) == "enum")
name = name->next();
Scope *new_scope = findScope(name, scope);
if (new_scope) {
// only create base list for classes and structures
if (new_scope->isClassOrStruct()) {
// goto initial '{'
if (!new_scope->definedType)
mTokenizer.syntaxError(nullptr); // #6808
tok2 = new_scope->definedType->initBaseInfo(tok, tok2);
// make sure we have valid code
if (!tok2) {
break;
}
}
// definition may be different than declaration
if (tok->isCpp() && tok->str() == "class") {
access[new_scope] = AccessControl::Private;
new_scope->type = Scope::eClass;
} else if (tok->str() == "struct") {
access[new_scope] = AccessControl::Public;
new_scope->type = Scope::eStruct;
}
new_scope->classDef = tok;
new_scope->setBodyStartEnd(tok2);
// make sure we have valid code
if (!new_scope->bodyEnd) {
mTokenizer.syntaxError(tok);
}
scope = new_scope;
tok = tok2;
} else {
scopeList.emplace_back(this, tok, scope);
new_scope = &scopeList.back();
if (tok->str() == "class")
access[new_scope] = AccessControl::Private;
else if (tok->str() == "struct" || tok->str() == "union")
access[new_scope] = AccessControl::Public;
// fill typeList...
if (new_scope->isClassOrStructOrUnion() || new_scope->type == Scope::eEnum) {
Type* new_type = findType(name, scope);
if (!new_type) {
typeList.emplace_back(new_scope->classDef, new_scope, scope);
new_type = &typeList.back();
scope->definedTypesMap[new_type->name()] = new_type;
} else
new_type->classScope = new_scope;
new_scope->definedType = new_type;
}
// only create base list for classes and structures
if (new_scope->isClassOrStruct()) {
// goto initial '{'
tok2 = new_scope->definedType->initBaseInfo(tok, tok2);
// make sure we have valid code
if (!tok2) {
mTokenizer.syntaxError(tok);
}
} else if (new_scope->type == Scope::eEnum) {
if (tok2->str() == ":") {
tok2 = tok2->tokAt(2);
while (Token::Match(tok2, "%name%|::"))
tok2 = tok2->next();
}
}
new_scope->setBodyStartEnd(tok2);
// make sure we have valid code
if (!new_scope->bodyEnd) {
mTokenizer.syntaxError(tok);
}
if (new_scope->type == Scope::eEnum) {
tok2 = new_scope->addEnum(tok);
scope->nestedList.push_back(new_scope);
if (!tok2)
mTokenizer.syntaxError(tok);
} else {
// make the new scope the current scope
scope->nestedList.push_back(new_scope);
scope = new_scope;
}
tok = tok2;
}
}
// Namespace and unknown macro (#3854)
else if (tok->isCpp() && tok->isKeyword() &&
Token::Match(tok, "namespace %name% %type% (") &&
tok->tokAt(2)->isUpperCaseName() &&
Token::simpleMatch(tok->linkAt(3), ") {")) {
scopeList.emplace_back(this, tok, scope);
Scope *new_scope = &scopeList.back();
access[new_scope] = AccessControl::Public;
const Token *tok2 = tok->linkAt(3)->next();
new_scope->setBodyStartEnd(tok2);
// make sure we have valid code
if (!new_scope->bodyEnd) {
scopeList.pop_back();
break;
}
// make the new scope the current scope
scope->nestedList.push_back(new_scope);
scope = &scopeList.back();
tok = tok2;
}
// forward declaration
else if (tok->isKeyword() && Token::Match(tok, "class|struct|union %name% ;") &&
tok->strAt(-1) != "friend") {
if (!findType(tok->next(), scope)) {
// fill typeList..
typeList.emplace_back(tok, nullptr, scope);
Type* new_type = &typeList.back();
scope->definedTypesMap[new_type->name()] = new_type;
}
tok = tok->tokAt(2);
}
// using namespace
else if (tok->isCpp() && tok->isKeyword() && Token::Match(tok, "using namespace ::| %type% ;|::")) {
Scope::UsingInfo using_info;
using_info.start = tok; // save location
using_info.scope = findNamespace(tok->tokAt(2), scope);
scope->usingList.push_back(using_info);
// check for global namespace
if (tok->strAt(2) == "::")
tok = tok->tokAt(4);
else
tok = tok->tokAt(3);
// skip over qualification
while (Token::Match(tok, "%type% ::"))
tok = tok->tokAt(2);
}
// using type alias
else if (tok->isCpp() && tok->isKeyword() && Token::Match(tok, "using %name% =") && !tok->tokAt(2)->isSimplifiedTypedef()) {
if (tok->strAt(-1) != ">" && !findType(tok->next(), scope)) {
// fill typeList..
typeList.emplace_back(tok, nullptr, scope);
Type* new_type = &typeList.back();
scope->definedTypesMap[new_type->name()] = new_type;
}
tok = tok->tokAt(3);
while (tok && tok->str() != ";") {
if (Token::simpleMatch(tok, "decltype ("))
tok = tok->linkAt(1);
else
tok = tok->next();
}
}
// unnamed struct and union
else if (tok->isKeyword() && Token::Match(tok, "struct|union {") &&
Token::Match(tok->linkAt(1), "} *|&| %name% ;|[|=")) {
scopeList.emplace_back(this, tok, scope);
Scope *new_scope = &scopeList.back();
access[new_scope] = AccessControl::Public;
const Token* varNameTok = tok->linkAt(1)->next();
if (varNameTok->str() == "*") {
varNameTok = varNameTok->next();
} else if (varNameTok->str() == "&") {
varNameTok = varNameTok->next();
}
typeList.emplace_back(tok, new_scope, scope);
{
Type* new_type = &typeList.back();
new_scope->definedType = new_type;
scope->definedTypesMap[new_type->name()] = new_type;
}
scope->addVariable(varNameTok, tok, tok, access[scope], new_scope->definedType, scope, mSettings);
const Token *tok2 = tok->next();
new_scope->setBodyStartEnd(tok2);
// make sure we have valid code
if (!new_scope->bodyEnd) {
scopeList.pop_back();
break;
}
// make the new scope the current scope
scope->nestedList.push_back(new_scope);
scope = new_scope;
tok = tok2;
}
// anonymous struct, union and namespace
else if (tok->isKeyword() && ((Token::Match(tok, "struct|union {") &&
Token::simpleMatch(tok->linkAt(1), "} ;")) ||
Token::simpleMatch(tok, "namespace {"))) {
scopeList.emplace_back(this, tok, scope);
Scope *new_scope = &scopeList.back();
access[new_scope] = AccessControl::Public;
const Token *tok2 = tok->next();
new_scope->setBodyStartEnd(tok2);
typeList.emplace_back(tok, new_scope, scope);
{
Type* new_type = &typeList.back();
new_scope->definedType = new_type;
scope->definedTypesMap[new_type->name()] = new_type;
}
// make sure we have valid code
if (!new_scope->bodyEnd) {
scopeList.pop_back();
break;
}
// make the new scope the current scope
scope->nestedList.push_back(new_scope);
scope = new_scope;
tok = tok2;
}
// forward declared enum
else if (tok->isKeyword() && (Token::Match(tok, "enum class| %name% ;") || Token::Match(tok, "enum class| %name% : %name% ;"))) {
typeList.emplace_back(tok, nullptr, scope);
Type* new_type = &typeList.back();
scope->definedTypesMap[new_type->name()] = new_type;
tok = tok->tokAt(2);
}
// check for end of scope
else if (tok == scope->bodyEnd) {
do {
access.erase(scope);
scope = const_cast<Scope*>(scope->nestedIn);
} while (scope->type != Scope::eGlobal && succeeds(tok, scope->bodyEnd));
continue;
}
// check for end of init list
else if (inInitList() && tok == endInitList.top().first) {
endInitList.pop();
continue;
}
// check if in class or structure or union
else if (scope->isClassOrStructOrUnion()) {
const Token *funcStart = nullptr;
const Token *argStart = nullptr;
const Token *declEnd = nullptr;
// What section are we in..
if (tok->str() == "private:")
access[scope] = AccessControl::Private;
else if (tok->str() == "protected:")
access[scope] = AccessControl::Protected;
else if (tok->str() == "public:" || tok->str() == "__published:")
access[scope] = AccessControl::Public;
else if (Token::Match(tok, "public|protected|private %name% :")) {
if (tok->str() == "private")
access[scope] = AccessControl::Private;
else if (tok->str() == "protected")
access[scope] = AccessControl::Protected;
else
access[scope] = AccessControl::Public;
tok = tok->tokAt(2);
}
// class function?
else if (isFunction(tok, scope, funcStart, argStart, declEnd)) {
if (tok->strAt(-1) != "::" || tok->strAt(-2) == scope->className) {
Function function(tok, scope, funcStart, argStart);
// save the access type
function.access = access[scope];
const Token *end = function.argDef->link();
// count the number of constructors
if (function.isConstructor())
scope->numConstructors++;
// assume implementation is inline (definition and implementation same)
function.token = function.tokenDef;
function.arg = function.argDef;
// out of line function
if (const Token *endTok = Tokenizer::isFunctionHead(end, ";")) {
tok = endTok;
scope->addFunction(std::move(function));
}
// inline function
else {
// find start of function '{'
bool foundInitList = false;
while (end && end->str() != "{" && end->str() != ";") {
if (end->link() && Token::Match(end, "(|<")) {
end = end->link();
} else if (foundInitList &&
Token::Match(end, "%name%|> {") &&
Token::Match(end->linkAt(1), "} ,|{")) {
end = end->linkAt(1);
} else {
if (end->str() == ":")
foundInitList = true;
end = end->next();
}
}
if (!end || end->str() == ";")
continue;
scope->addFunction(function);
Function* funcptr = &scope->functionList.back();
const Token *tok2 = funcStart;
addNewFunction(scope, tok2);
if (scope) {
scope->functionOf = function.nestedIn;
scope->function = funcptr;
scope->function->functionScope = scope;
}
tok = tok2;
}
}
// nested class or friend function?
else {
/** @todo check entire qualification for match */
const Scope * const nested = scope->findInNestedListRecursive(tok->strAt(-2));
if (nested)
addClassFunction(scope, tok, argStart);
else {
/** @todo handle friend functions */
}
}
}
// friend class declaration?
else if (tok->isCpp() && tok->isKeyword() && Token::Match(tok, "friend class|struct| ::| %any% ;|::")) {
Type::FriendInfo friendInfo;
// save the name start
friendInfo.nameStart = tok->strAt(1) == "class" ? tok->tokAt(2) : tok->next();
friendInfo.nameEnd = friendInfo.nameStart;
// skip leading "::"
if (friendInfo.nameEnd->str() == "::")
friendInfo.nameEnd = friendInfo.nameEnd->next();
// skip qualification "name ::"
while (friendInfo.nameEnd && friendInfo.nameEnd->strAt(1) == "::")
friendInfo.nameEnd = friendInfo.nameEnd->tokAt(2);
// fill this in after parsing is complete
friendInfo.type = nullptr;
if (!scope->definedType)
mTokenizer.syntaxError(tok);
scope->definedType->friendList.push_back(friendInfo);
}
} else if (scope->type == Scope::eNamespace || scope->type == Scope::eGlobal) {
const Token *funcStart = nullptr;
const Token *argStart = nullptr;
const Token *declEnd = nullptr;
// function?
if (isFunction(tok, scope, funcStart, argStart, declEnd)) {
// has body?
if (declEnd && declEnd->str() == "{") {
tok = funcStart;
// class function
if (tok->previous() && tok->strAt(-1) == "::")
addClassFunction(scope, tok, argStart);
// class destructor
else if (tok->previous() &&
tok->strAt(-1) == "~" &&
tok->strAt(-2) == "::")
addClassFunction(scope, tok, argStart);
// regular function
else {
const Function* const function = addGlobalFunction(scope, tok, argStart, funcStart);
if (!function)
mTokenizer.syntaxError(tok);
}
// syntax error?
if (!scope)
mTokenizer.syntaxError(tok);
}
// function prototype?
else if (declEnd && declEnd->str() == ";") {
if (tok->astParent() && tok->astParent()->str() == "::" &&
Token::Match(declEnd->previous(), "default|delete")) {
addClassFunction(scope, tok, argStart);
continue;
}
bool newFunc = true; // Is this function already in the database?
auto range = scope->functionMap.equal_range(tok->str());
for (std::multimap<std::string, const Function*>::const_iterator it = range.first; it != range.second; ++it) {
if (it->second->argsMatch(scope, it->second->argDef, argStart, emptyString, 0)) {
newFunc = false;
break;
}
}
// save function prototype in database
if (newFunc) {
addGlobalFunctionDecl(scope, tok, argStart, funcStart);
}
tok = declEnd;
continue;
}
} else if (const Token *lambdaEndToken = findLambdaEndToken(tok)) {
tok = addLambda(tok, lambdaEndToken);
}
} else if (scope->isExecutable()) {
if (tok->isKeyword() && Token::Match(tok, "else|try|do {")) {
const Token* tok1 = tok->next();
if (tok->str() == "else")
scopeList.emplace_back(this, tok, scope, Scope::eElse, tok1);
else if (tok->str() == "do")
scopeList.emplace_back(this, tok, scope, Scope::eDo, tok1);
else //if (tok->str() == "try")
scopeList.emplace_back(this, tok, scope, Scope::eTry, tok1);
tok = tok1;
scope->nestedList.push_back(&scopeList.back());
scope = &scopeList.back();
} else if (tok->isKeyword() && Token::Match(tok, "if|for|while|catch|switch (") && Token::simpleMatch(tok->linkAt(1), ") {")) {
const Token *scopeStartTok = tok->linkAt(1)->next();
if (tok->str() == "if")
scopeList.emplace_back(this, tok, scope, Scope::eIf, scopeStartTok);
else if (tok->str() == "for") {
scopeList.emplace_back(this, tok, scope, Scope::eFor, scopeStartTok);
} else if (tok->str() == "while")
scopeList.emplace_back(this, tok, scope, Scope::eWhile, scopeStartTok);
else if (tok->str() == "catch") {
scopeList.emplace_back(this, tok, scope, Scope::eCatch, scopeStartTok);
} else // if (tok->str() == "switch")
scopeList.emplace_back(this, tok, scope, Scope::eSwitch, scopeStartTok);
scope->nestedList.push_back(&scopeList.back());
scope = &scopeList.back();
if (scope->type == Scope::eFor)
scope->checkVariable(tok->tokAt(2), AccessControl::Local, mSettings); // check for variable declaration and add it to new scope if found
else if (scope->type == Scope::eCatch)
scope->checkVariable(tok->tokAt(2), AccessControl::Throw, mSettings); // check for variable declaration and add it to new scope if found
tok = tok->next();
inIfCondition.push(scopeStartTok);
} else if (Token::Match(tok, "%var% {")) {
endInitList.emplace(tok->linkAt(1), scope);
tok = tok->next();
} else if (const Token *lambdaEndToken = findLambdaEndToken(tok)) {
tok = addLambda(tok, lambdaEndToken);
} else if (tok->str() == "{") {
if (inInitList()) {
endInitList.emplace(tok->link(), scope);
} else if (!inIfCondition.empty() && tok == inIfCondition.top()) {
inIfCondition.pop();
} else if (isExecutableScope(tok)) {
scopeList.emplace_back(this, tok, scope, Scope::eUnconditional, tok);
scope->nestedList.push_back(&scopeList.back());
scope = &scopeList.back();
} else {
endInitList.emplace(tok->link(), scope);
}
} else if (Token::Match(tok, "extern %type%")) {
const Token * ftok = tok->next();
while (Token::Match(ftok, "%name%|*|&"))
ftok = ftok->next();
if (!ftok || ftok->str() != "(")
continue;
ftok = ftok->previous();
if (Token::simpleMatch(ftok->linkAt(1), ") ;")) {
const Token *funcStart = nullptr;
const Token *argStart = nullptr;
const Token *declEnd = nullptr;
if (isFunction(ftok, scope, funcStart, argStart, declEnd)) {
if (declEnd && declEnd->str() == ";") {
bool newFunc = true; // Is this function already in the database?
auto range = scope->functionMap.equal_range(ftok->str());
for (std::multimap<std::string, const Function*>::const_iterator it = range.first; it != range.second; ++it) {
if (it->second->argsMatch(scope, it->second->argDef, argStart, emptyString, 0)) {
newFunc = false;
break;
}
}
// save function prototype in database
if (newFunc) {
Function function(ftok, scope, funcStart, argStart);
if (function.isExtern()) {
scope->addFunction(std::move(function));
tok = declEnd;
}
}
}
}
}
}
// syntax error?
if (!scope)
mTokenizer.syntaxError(tok);
// End of scope or list should be handled above
if (tok->str() == "}")
mTokenizer.syntaxError(tok);
}
}
}
void SymbolDatabase::createSymbolDatabaseClassInfo()
{
if (mTokenizer.isC())
return;
// fill in using info
for (Scope& scope : scopeList) {
for (Scope::UsingInfo& usingInfo : scope.usingList) {
// only find if not already found
if (usingInfo.scope == nullptr) {
// check scope for match
const Scope * const found = findScope(usingInfo.start->tokAt(2), &scope);
if (found) {
// set found scope
usingInfo.scope = found;
break;
}
}
}
}
// fill in base class info
for (Type& type : typeList) {
// finish filling in base class info
for (Type::BaseInfo & i : type.derivedFrom) {
const Type* found = findType(i.nameTok, type.enclosingScope, /*lookOutside*/ true);
if (found && found->findDependency(&type)) {
// circular dependency
//mTokenizer.syntaxError(nullptr);
} else {
i.type = found;
}
}
}
// fill in friend info
for (Type & type : typeList) {
for (Type::FriendInfo &friendInfo : type.friendList) {
friendInfo.type = findType(friendInfo.nameStart, type.enclosingScope);
}
}
}
void SymbolDatabase::createSymbolDatabaseVariableInfo()
{
// fill in variable info
for (Scope& scope : scopeList) {
// find variables
scope.getVariableList(mSettings);
}
// fill in function arguments
for (Scope& scope : scopeList) {
std::list<Function>::iterator func;
for (func = scope.functionList.begin(); func != scope.functionList.end(); ++func) {
// add arguments
func->addArguments(this, &scope);
}
}
}
void SymbolDatabase::createSymbolDatabaseCopyAndMoveConstructors()
{
// fill in class and struct copy/move constructors
for (Scope& scope : scopeList) {
if (!scope.isClassOrStruct())
continue;
std::list<Function>::iterator func;
for (func = scope.functionList.begin(); func != scope.functionList.end(); ++func) {
if (!func->isConstructor() || func->minArgCount() != 1)
continue;
const Variable* firstArg = func->getArgumentVar(0);
if (firstArg->type() == scope.definedType) {
if (firstArg->isRValueReference())
func->type = Function::eMoveConstructor;
else if (firstArg->isReference() && !firstArg->isPointer())
func->type = Function::eCopyConstructor;
}
if (func->type == Function::eCopyConstructor ||
func->type == Function::eMoveConstructor)
scope.numCopyOrMoveConstructors++;
}
}
}
void SymbolDatabase::createSymbolDatabaseFunctionScopes()
{
// fill in function scopes
for (const Scope & scope : scopeList) {
if (scope.type == Scope::eFunction)
functionScopes.push_back(&scope);
}
}
void SymbolDatabase::createSymbolDatabaseClassAndStructScopes()
{
// fill in class and struct scopes
for (const Scope& scope : scopeList) {
if (scope.isClassOrStruct())
classAndStructScopes.push_back(&scope);
}
}
void SymbolDatabase::createSymbolDatabaseFunctionReturnTypes()
{
// fill in function return types
for (Scope& scope : scopeList) {
std::list<Function>::iterator func;
for (func = scope.functionList.begin(); func != scope.functionList.end(); ++func) {
// add return types
if (func->retDef) {
const Token *type = func->retDef;
while (Token::Match(type, "static|const|struct|union|enum"))
type = type->next();
if (type) {
func->retType = findVariableTypeInBase(&scope, type);
if (!func->retType)
func->retType = findTypeInNested(type, func->nestedIn);
}
}
}
}
}
void SymbolDatabase::createSymbolDatabaseNeedInitialization()
{
if (mTokenizer.isC()) {
// For C code it is easy, as there are no constructors and no default values
for (const Scope& scope : scopeList) {
if (scope.definedType)
scope.definedType->needInitialization = Type::NeedInitialization::True;
}
} else {
// For C++, it is more difficult: Determine if user defined type needs initialization...
unsigned int unknowns = 0; // stop checking when there are no unknowns
unsigned int retry = 0; // bail if we don't resolve all the variable types for some reason
do {
unknowns = 0;
for (Scope& scope : scopeList) {
if (!scope.isClassOrStructOrUnion())
continue;
if (scope.classDef && Token::simpleMatch(scope.classDef->previous(), ">")) // skip uninstantiated template
continue;
if (!scope.definedType) {
mBlankTypes.emplace_back();
scope.definedType = &mBlankTypes.back();
}
if (scope.isClassOrStruct() && scope.definedType->needInitialization == Type::NeedInitialization::Unknown) {
// check for default constructor
bool hasDefaultConstructor = false;
for (const Function& func : scope.functionList) {
if (func.type == Function::eConstructor) {
// check for no arguments: func ( )
if (func.argCount() == 0) {
hasDefaultConstructor = true;
break;
}
/** check for arguments with default values */
if (func.argCount() == func.initializedArgCount()) {
hasDefaultConstructor = true;
break;
}
}
}
// User defined types with user defined default constructor doesn't need initialization.
// We assume the default constructor initializes everything.
// Another check will figure out if the constructor actually initializes everything.
if (hasDefaultConstructor)
scope.definedType->needInitialization = Type::NeedInitialization::False;
// check each member variable to see if it needs initialization
else {
bool needInitialization = false;
bool unknown = false;
for (const Variable& var: scope.varlist) {
if (var.isStatic())
continue;
if (var.isClass() && !var.isReference()) {
if (var.type()) {
// does this type need initialization?
if (var.type()->needInitialization == Type::NeedInitialization::True && !var.hasDefault() && !var.isStatic())
needInitialization = true;
else if (var.type()->needInitialization == Type::NeedInitialization::Unknown) {
if (!(var.valueType() && var.valueType()->type == ValueType::CONTAINER))
unknown = true;
}
}
} else if (!var.hasDefault()) {
needInitialization = true;
break;
}
}
if (needInitialization)
scope.definedType->needInitialization = Type::NeedInitialization::True;
else if (!unknown)
scope.definedType->needInitialization = Type::NeedInitialization::False;
else {
if (scope.definedType->needInitialization == Type::NeedInitialization::Unknown)
unknowns++;
}
}
} else if (scope.type == Scope::eUnion && scope.definedType->needInitialization == Type::NeedInitialization::Unknown)
scope.definedType->needInitialization = Type::NeedInitialization::True;
}
retry++;
} while (unknowns && retry < 100);
// this shouldn't happen so output a debug warning
if (retry == 100 && mSettings.debugwarnings) {
for (const Scope& scope : scopeList) {
if (scope.isClassOrStruct() && scope.definedType->needInitialization == Type::NeedInitialization::Unknown)
debugMessage(scope.classDef, "debug", "SymbolDatabase couldn't resolve all user defined types.");
}
}
}
}
void SymbolDatabase::createSymbolDatabaseVariableSymbolTable()
{
// create variable symbol table
mVariableList.resize(mTokenizer.varIdCount() + 1);
std::fill_n(mVariableList.begin(), mVariableList.size(), nullptr);
// check all scopes for variables
for (Scope& scope : scopeList) {
// add all variables
for (Variable& var: scope.varlist) {
const int varId = var.declarationId();
if (varId)
mVariableList[varId] = &var;
// fix up variables without type
if (!var.type() && !var.typeStartToken()->isStandardType()) {
const Type *type = findType(var.typeStartToken(), &scope);
if (type)
var.type(type);
}
}
// add all function parameters
for (Function& func : scope.functionList) {
for (Variable& arg: func.argumentList) {
// check for named parameters
if (arg.nameToken() && arg.declarationId()) {
const int declarationId = arg.declarationId();
mVariableList[declarationId] = &arg;
// fix up parameters without type
if (!arg.type() && !arg.typeStartToken()->isStandardType()) {
const Type *type = findTypeInNested(arg.typeStartToken(), &scope);
if (type)
arg.type(type);
}
}
}
}
}
// fill in missing variables if possible
for (const Scope *func: functionScopes) {
for (const Token *tok = func->bodyStart->next(); tok && tok != func->bodyEnd; tok = tok->next()) {
// check for member variable
if (!Token::Match(tok, "%var% .|["))
continue;
const Token* tokDot = tok->next();
while (Token::simpleMatch(tokDot, "["))
tokDot = tokDot->link()->next();
if (!Token::Match(tokDot, ". %var%"))
continue;
const Token *member = tokDot->next();
if (mVariableList[member->varId()] == nullptr) {
const Variable *var1 = mVariableList[tok->varId()];
if (var1 && var1->typeScope()) {
const Variable* memberVar = var1->typeScope()->getVariable(member->str());
if (memberVar) {
// add this variable to the look up table
mVariableList[member->varId()] = memberVar;
}
}
}
}
}
}
void SymbolDatabase::createSymbolDatabaseSetScopePointers()
{
auto setScopePointers = [](const Scope &scope, const Token *bodyStart, const Token *bodyEnd) {
assert(bodyStart);
assert(bodyEnd);
const_cast<Token *>(bodyEnd)->scope(&scope);
for (auto* tok = const_cast<Token *>(bodyStart); tok != bodyEnd; tok = tok->next()) {
if (bodyStart != bodyEnd && tok->str() == "{") {
bool isEndOfScope = false;
for (Scope* innerScope: scope.nestedList) {
const auto &list = innerScope->bodyStartList;
if (std::find(list.cbegin(), list.cend(), tok) != list.cend()) { // Is begin of inner scope
tok = tok->link();
if (tok->next() == bodyEnd || !tok->next()) {
isEndOfScope = true;
break;
}
tok = tok->next();
break;
}
}
if (isEndOfScope)
break;
}
tok->scope(&scope);
}
};
// Set scope pointers
for (const Scope& scope: scopeList) {
if (scope.type == Scope::eGlobal)
setScopePointers(scope, mTokenizer.list.front(), mTokenizer.list.back());
else {
for (const Token *bodyStart: scope.bodyStartList)
setScopePointers(scope, bodyStart, bodyStart->link());
}
}
}
void SymbolDatabase::createSymbolDatabaseSetFunctionPointers(bool firstPass)
{
if (firstPass) {
// Set function definition and declaration pointers
for (const Scope& scope: scopeList) {
for (const Function& func: scope.functionList) {
if (func.tokenDef)
const_cast<Token *>(func.tokenDef)->function(&func);
if (func.token)
const_cast<Token *>(func.token)->function(&func);
}
}
}
// Set function call pointers
const Token* inTemplateArg = nullptr;
for (Token* tok = mTokenizer.list.front(); tok != mTokenizer.list.back(); tok = tok->next()) {
if (inTemplateArg == nullptr && tok->link() && tok->str() == "<")
inTemplateArg = tok->link();
if (inTemplateArg == tok)
inTemplateArg = nullptr;
if (tok->isName() && !tok->function() && tok->varId() == 0 && ((tok->astParent() && tok->astParent()->isComparisonOp()) || Token::Match(tok, "%name% [{(,)>;:]]")) && !isReservedName(tok)) {
if (tok->strAt(1) == ">" && !tok->linkAt(1))
continue;
const Function *function = findFunction(tok);
if (!function || (inTemplateArg && function->isConstructor()))
continue;
tok->function(function);
if (tok->strAt(1) != "(")
const_cast<Function *>(function)->functionPointerUsage = tok;
}
}
// Set C++ 11 delegate constructor function call pointers
for (const Scope& scope: scopeList) {
for (const Function& func: scope.functionList) {
// look for initializer list
if (func.isConstructor() && func.functionScope && func.functionScope->functionOf && func.arg) {
const Token * tok = func.arg->link()->next();
if (tok->str() == "noexcept") {
const Token * closingParenTok = tok->linkAt(1);
if (!closingParenTok || !closingParenTok->next()) {
continue;
}
tok = closingParenTok->next();
}
if (tok->str() != ":") {
continue;
}
tok = tok->next();
while (tok && tok != func.functionScope->bodyStart) {
if (Token::Match(tok, "%name% {|(")) {
if (tok->str() == func.tokenDef->str()) {
const Function *function = func.functionScope->functionOf->findFunction(tok);
if (function)
const_cast<Token *>(tok)->function(function);
break;
}
tok = tok->linkAt(1);
}
tok = tok->next();
}
}
}
}
}
void SymbolDatabase::createSymbolDatabaseSetTypePointers()
{
std::unordered_set<std::string> typenames;
for (const Type &t : typeList) {
typenames.insert(t.name());
}
// Set type pointers
for (Token* tok = mTokenizer.list.front(); tok != mTokenizer.list.back(); tok = tok->next()) {
if (!tok->isName() || tok->varId() || tok->function() || tok->type() || tok->enumerator())
continue;
if (typenames.find(tok->str()) == typenames.end())
continue;
const Type *type = findVariableType(tok->scope(), tok);
if (type)
tok->type(type);
}
}
void SymbolDatabase::createSymbolDatabaseSetSmartPointerType()
{
for (Scope &scope: scopeList) {
for (Variable &var: scope.varlist) {
if (var.valueType() && var.valueType()->smartPointerTypeToken && !var.valueType()->smartPointerType) {
ValueType vt(*var.valueType());
vt.smartPointerType = vt.smartPointerTypeToken->type();
var.setValueType(vt);
}
}
}
}
void SymbolDatabase::fixVarId(VarIdMap & varIds, const Token * vartok, Token * membertok, const Variable * membervar)
{
VarIdMap::iterator varId = varIds.find(vartok->varId());
if (varId == varIds.end()) {
MemberIdMap memberId;
if (membertok->varId() == 0) {
memberId[membervar->nameToken()->varId()] = mTokenizer.newVarId();
mVariableList.push_back(membervar);
} else
mVariableList[membertok->varId()] = membervar;
varIds.emplace(vartok->varId(), memberId);
varId = varIds.find(vartok->varId());
}
MemberIdMap::const_iterator memberId = varId->second.find(membervar->nameToken()->varId());
if (memberId == varId->second.cend()) {
if (membertok->varId() == 0) {
varId->second.emplace(membervar->nameToken()->varId(), mTokenizer.newVarId());
mVariableList.push_back(membervar);
memberId = varId->second.find(membervar->nameToken()->varId());
} else
mVariableList[membertok->varId()] = membervar;
}
if (membertok->varId() == 0)
membertok->varId(memberId->second);
}
static bool isContainerYieldElement(Library::Container::Yield yield);
void SymbolDatabase::createSymbolDatabaseSetVariablePointers()
{
VarIdMap varIds;
auto setMemberVar = [&](const Variable* membervar, Token* membertok, const Token* vartok) -> void {
if (membervar) {
membertok->variable(membervar);
if (vartok && (membertok->varId() == 0 || mVariableList[membertok->varId()] == nullptr))
fixVarId(varIds, vartok, membertok, membervar);
}
};
// Set variable pointers
for (Token* tok = mTokenizer.list.front(); tok != mTokenizer.list.back(); tok = tok->next()) {
if (!tok->isName() || tok->isKeyword() || tok->isStandardType())
continue;
if (tok->varId())
tok->variable(getVariableFromVarId(tok->varId()));
// Set Token::variable pointer for array member variable
// Since it doesn't point at a fixed location it doesn't have varid
const bool isVar = tok->variable() && (tok->variable()->typeScope() || tok->variable()->isSmartPointer() ||
(tok->valueType() && (tok->valueType()->type == ValueType::CONTAINER || tok->valueType()->type == ValueType::ITERATOR)));
const bool isArrayAccess = isVar && Token::simpleMatch(tok->astParent(), "[");
const bool isDirectAccess = isVar && !isArrayAccess && Token::simpleMatch(tok->astParent(), ".");
const bool isDerefAccess = isVar && !isDirectAccess && Token::simpleMatch(tok->astParent(), "*") && Token::simpleMatch(tok->astParent()->astParent(), ".");
if (isVar && (isArrayAccess || isDirectAccess || isDerefAccess)) {
Token* membertok{};
if (isArrayAccess) {
membertok = tok->astParent();
while (Token::simpleMatch(membertok, "["))
membertok = membertok->astParent();
if (membertok)
membertok = membertok->astOperand2();
}
else if (isDirectAccess) {
membertok = tok->astParent()->astOperand2();
if (membertok == tok) {
Token* gptok = tok->astParent()->astParent();
if (Token::simpleMatch(gptok, ".")) // chained access
membertok = gptok->astOperand2();
else if (Token::simpleMatch(gptok, "[") && Token::simpleMatch(gptok->astParent(), "."))
membertok = gptok->astParent()->astOperand2();
}
}
else { // isDerefAccess
membertok = tok->astParent();
while (Token::simpleMatch(membertok, "*"))
membertok = membertok->astParent();
if (membertok)
membertok = membertok->astOperand2();
}
if (membertok && membertok != tok) {
const Variable *var = tok->variable();
if (var->typeScope()) {
const Variable *membervar = var->typeScope()->getVariable(membertok->str());
setMemberVar(membervar, membertok, tok);
} else if (const ::Type *type = var->smartPointerType()) {
const Scope *classScope = type->classScope;
const Variable *membervar = classScope ? classScope->getVariable(membertok->str()) : nullptr;
setMemberVar(membervar, membertok, tok);
} else if (tok->valueType() && tok->valueType()->type == ValueType::CONTAINER) {
if (const Token* ctt = tok->valueType()->containerTypeToken) {
while (ctt && ctt->isKeyword())
ctt = ctt->next();
const Type* ct = findTypeInNested(ctt, tok->scope());
if (ct && ct->classScope && ct->classScope->definedType) {
const Variable *membervar = ct->classScope->getVariable(membertok->str());
setMemberVar(membervar, membertok, tok);
}
}
} else if (const Type* iterType = var->iteratorType()) {
if (iterType->classScope && iterType->classScope->definedType) {
const Variable *membervar = iterType->classScope->getVariable(membertok->str());
setMemberVar(membervar, membertok, tok);
}
}
}
}
// check for function returning record type
// func(...).var
// func(...)[...].var
else if (tok->function() && tok->strAt(1) == "(" &&
(Token::Match(tok->linkAt(1), ") . %name% !!(") ||
(Token::Match(tok->linkAt(1), ") [") && Token::Match(tok->linkAt(1)->linkAt(1), "] . %name% !!(")))) {
const Type *type = tok->function()->retType;
Token* membertok;
if (tok->linkAt(1)->strAt(1) == ".")
membertok = tok->linkAt(1)->tokAt(2);
else
membertok = tok->linkAt(1)->linkAt(1)->tokAt(2);
if (type) {
const Variable *membervar = membertok->variable();
if (!membervar) {
if (type->classScope) {
membervar = type->classScope->getVariable(membertok->str());
setMemberVar(membervar, membertok, tok->function()->retDef);
}
}
} else if (mSettings.library.detectSmartPointer(tok->function()->retDef)) {
if (const Token* templateArg = Token::findsimplematch(tok->function()->retDef, "<")) {
if (const Type* spType = findTypeInNested(templateArg->next(), tok->scope())) {
if (spType->classScope) {
const Variable* membervar = spType->classScope->getVariable(membertok->str());
setMemberVar(membervar, membertok, tok->function()->retDef);
}
}
}
}
}
else if (Token::simpleMatch(tok->astParent(), ".") && tok->strAt(1) == "(" &&
astIsContainer(tok->astParent()->astOperand1()) && Token::Match(tok->linkAt(1), ") . %name% !!(")) {
const ValueType* vt = tok->astParent()->astOperand1()->valueType();
const Library::Container* cont = vt->container;
auto it = cont->functions.find(tok->str());
if (it != cont->functions.end() && isContainerYieldElement(it->second.yield) && vt->containerTypeToken) {
Token* memberTok = tok->linkAt(1)->tokAt(2);
const Scope* scope = vt->containerTypeToken->scope();
const Type* contType{};
const std::string& typeStr = vt->containerTypeToken->str(); // TODO: handle complex type expressions
while (scope && !contType) {
contType = scope->findType(typeStr); // find the type stored in the container
scope = scope->nestedIn;
}
if (contType && contType->classScope) {
const Variable* membervar = contType->classScope->getVariable(memberTok->str());
setMemberVar(membervar, memberTok, vt->containerTypeToken);
}
}
}
}
}
void SymbolDatabase::createSymbolDatabaseEnums()
{
// fill in enumerators in enum
for (const Scope &scope : scopeList) {
if (scope.type != Scope::eEnum)
continue;
// add enumerators to enumerator tokens
for (const Enumerator & i : scope.enumeratorList)
const_cast<Token *>(i.name)->enumerator(&i);
}
std::set<std::string> tokensThatAreNotEnumeratorValues;
for (const Scope &scope : scopeList) {
if (scope.type != Scope::eEnum)
continue;
for (const Enumerator & enumerator : scope.enumeratorList) {
// look for initialization tokens that can be converted to enumerators and convert them
if (enumerator.start) {
if (!enumerator.end)
mTokenizer.syntaxError(enumerator.start);
for (const Token * tok3 = enumerator.start; tok3 && tok3 != enumerator.end->next(); tok3 = tok3->next()) {
if (tok3->tokType() == Token::eName) {
const Enumerator * e = findEnumerator(tok3, tokensThatAreNotEnumeratorValues);
if (e)
const_cast<Token *>(tok3)->enumerator(e);
}
}
}
}
}
// find enumerators
for (Token* tok = mTokenizer.list.front(); tok != mTokenizer.list.back(); tok = tok->next()) {
const bool isVariable = (tok->tokType() == Token::eVariable && !tok->variable());
if (tok->tokType() != Token::eName && !isVariable)
continue;
const Enumerator * enumerator = findEnumerator(tok, tokensThatAreNotEnumeratorValues);
if (enumerator) {
if (isVariable)
tok->varId(0);
tok->enumerator(enumerator);
}
}
}
void SymbolDatabase::createSymbolDatabaseIncompleteVars()
{
for (Token* tok = mTokenizer.list.front(); tok != mTokenizer.list.back(); tok = tok->next()) {
const Scope * scope = tok->scope();
if (!scope)
continue;
if (!scope->isExecutable())
continue;
if (tok->varId() != 0)
continue;
if (tok->isCast() && !isCPPCast(tok) && tok->link() && tok->str() == "(") {
tok = tok->link();
continue;
}
if (tok->isCpp()) {
if (Token::Match(tok, "catch|typeid (") ||
Token::Match(tok, "static_cast|dynamic_cast|const_cast|reinterpret_cast")) {
tok = tok->linkAt(1);
continue;
}
if (tok->str() == "using") {
tok = Token::findsimplematch(tok, ";");
continue;
}
}
if (tok->str() == "NULL")
continue;
if (tok->isKeyword() || !tok->isNameOnly())
continue;
if (tok->type())
continue;
if (Token::Match(tok->next(), "::|.|(|{|:|%var%"))
continue;
if (Token::Match(tok->next(), "&|&&|* *| *| )|,|%var%|const"))
continue;
// Very likely a typelist
if (Token::Match(tok->tokAt(-2), "%type% ,") || Token::Match(tok->next(), ", %type%"))
continue;
// Inside template brackets
if (Token::simpleMatch(tok->next(), "<") && tok->linkAt(1)) {
tok = tok->linkAt(1);
continue;
}
// Skip goto labels
if (Token::simpleMatch(tok->previous(), "goto"))
continue;
std::string fstr = tok->str();
const Token* ftok = tok->previous();
while (Token::simpleMatch(ftok, "::")) {
if (!Token::Match(ftok->previous(), "%name%"))
break;
fstr.insert(0, ftok->strAt(-1) + "::");
ftok = ftok->tokAt(-2);
}
if (mSettings.library.functions().find(fstr) != mSettings.library.functions().end())
continue;
if (tok->isCpp()) {
const Token* parent = tok->astParent();
while (Token::Match(parent, "::|[|{"))
parent = parent->astParent();
if (Token::simpleMatch(parent, "new"))
continue;
// trailing return type
if (Token::simpleMatch(ftok, ".") && ftok->originalName() == "->" && Token::Match(ftok->tokAt(-1), "[])]"))
continue;
}
tok->isIncompleteVar(true);
}
}
void SymbolDatabase::createSymbolDatabaseEscapeFunctions()
{
for (const Scope& scope : scopeList) {
if (scope.type != Scope::eFunction)
continue;
Function * function = scope.function;
if (!function)
continue;
if (Token::findsimplematch(scope.bodyStart, "return", scope.bodyEnd))
continue;
function->isEscapeFunction(isReturnScope(scope.bodyEnd, mSettings.library, nullptr, true));
}
}
static bool isExpression(const Token* tok)
{
if (!tok)
return false;
if (Token::simpleMatch(tok, "{") && tok->scope() && tok->scope()->bodyStart != tok &&
(tok->astOperand1() || tok->astOperand2()))
return true;
if (!Token::Match(tok, "(|.|[|::|?|:|++|--|%cop%|%assign%"))
return false;
if (Token::Match(tok, "*|&|&&")) {
const Token* vartok = findAstNode(tok, [&](const Token* tok2) {
const Variable* var = tok2->variable();
if (!var)
return false;
return var->nameToken() == tok2;
});
if (vartok)
return false;
}
return true;
}
static std::string getIncompleteNameID(const Token* tok)
{
std::string result = tok->str() + "@";
while (Token::Match(tok->astParent(), ".|::"))
tok = tok->astParent();
return result + tok->expressionString();
}
namespace {
struct ExprIdKey {
std::string parentOp;
nonneg int operand1;
nonneg int operand2;
bool operator<(const ExprIdKey& k) const {
return std::tie(parentOp, operand1, operand2) < std::tie(k.parentOp, k.operand1, k.operand2);
}
};
using ExprIdMap = std::map<ExprIdKey, nonneg int>;
void setParentExprId(Token* tok, ExprIdMap& exprIdMap, nonneg int &id) {
for (;;) {
if (!tok->astParent() || tok->astParent()->isControlFlowKeyword())
break;
const Token* op1 = tok->astParent()->astOperand1();
if (op1 && op1->exprId() == 0 && !Token::Match(op1, "[{[]"))
break;
const Token* op2 = tok->astParent()->astOperand2();
if (op2 && op2->exprId() == 0 &&
!((tok->astParent()->astParent() && tok->astParent()->isAssignmentOp() && tok->astParent()->astParent()->isAssignmentOp()) ||
isLambdaCaptureList(op2) ||
(op2->str() == "(" && isLambdaCaptureList(op2->astOperand1())) ||
Token::simpleMatch(op2, "{ }") ||
(Token::simpleMatch(tok->astParent(), "[") && op2->str() == "{")))
break;
if (tok->astParent()->isExpandedMacro() || Token::Match(tok->astParent(), "++|--")) {
tok->astParent()->exprId(id);
++id;
tok = tok->astParent();
continue;
}
ExprIdKey key;
key.parentOp = tok->astParent()->str();
key.operand1 = op1 ? op1->exprId() : 0;
key.operand2 = op2 ? op2->exprId() : 0;
if (tok->astParent()->isCast() && tok->astParent()->str() == "(") {
const Token* typeStartToken;
const Token* typeEndToken;
if (tok->astParent()->astOperand2()) {
typeStartToken = tok->astParent()->astOperand1();
typeEndToken = tok;
} else {
typeStartToken = tok->astParent()->next();
typeEndToken = tok->astParent()->link();
}
std::string type;
for (const Token* t = typeStartToken; t != typeEndToken; t = t->next()) {
type += " " + t->str();
}
key.parentOp += type;
}
for (const auto& ref: followAllReferences(op1)) {
if (ref.token->exprId() != 0) { // cppcheck-suppress useStlAlgorithm
key.operand1 = ref.token->exprId();
break;
}
}
for (const auto& ref: followAllReferences(op2)) {
if (ref.token->exprId() != 0) { // cppcheck-suppress useStlAlgorithm
key.operand2 = ref.token->exprId();
break;
}
}
if (key.operand1 > key.operand2 && key.operand2 &&
Token::Match(tok->astParent(), "%or%|%oror%|+|*|&|&&|^|==|!=")) {
// In C++ the order of operands of + might matter
if (!tok->isCpp() ||
key.parentOp != "+" ||
!tok->astParent()->valueType() ||
tok->astParent()->valueType()->isIntegral() ||
tok->astParent()->valueType()->isFloat() ||
tok->astParent()->valueType()->pointer > 0)
std::swap(key.operand1, key.operand2);
}
const auto it = exprIdMap.find(key);
if (it == exprIdMap.end()) {
exprIdMap[key] = id;
tok->astParent()->exprId(id);
++id;
} else {
tok->astParent()->exprId(it->second);
}
tok = tok->astParent();
}
}
}
void SymbolDatabase::createSymbolDatabaseExprIds()
{
// Find highest varId
nonneg int maximumVarId = 0;
for (const Token* tok = mTokenizer.list.front(); tok; tok = tok->next()) {
maximumVarId = std::max(tok->varId(), maximumVarId);
}
nonneg int id = maximumVarId + 1;
// Find incomplete vars that are used in constant context
std::unordered_map<std::string, nonneg int> unknownConstantIds;
const Token* inConstExpr = nullptr;
for (const Token* tok = mTokenizer.list.front(); tok != mTokenizer.list.back(); tok = tok->next()) {
if (Token::Match(tok, "decltype|sizeof|typeof (") && tok->linkAt(1)) {
tok = tok->linkAt(1)->previous();
} else if (tok == inConstExpr) {
inConstExpr = nullptr;
} else if (inConstExpr) {
if (!tok->isIncompleteVar())
continue;
if (!isExpression(tok->astParent()))
continue;
const std::string& name = getIncompleteNameID(tok);
if (unknownConstantIds.count(name) > 0)
continue;
unknownConstantIds[name] = id++;
} else if (tok->link() && tok->str() == "<") {
inConstExpr = tok->link();
} else if (Token::Match(tok, "%var% [") && tok->variable() && tok->variable()->nameToken() == tok) {
inConstExpr = tok->linkAt(1);
}
}
auto exprScopes = functionScopes; // functions + global lambdas + namespaces
std::copy_if(scopeList.front().nestedList.begin(), scopeList.front().nestedList.end(), std::back_inserter(exprScopes), [](const Scope* scope) {
return scope && (scope->type == Scope::eLambda || scope->type == Scope::eNamespace);
});
for (const Scope * scope : exprScopes) {
std::unordered_map<std::string, nonneg int> unknownIds;
// Assign IDs to incomplete vars which are part of an expression
// Such variables should be assumed global
for (auto* tok = const_cast<Token*>(scope->bodyStart); tok != scope->bodyEnd; tok = tok->next()) {
if (!tok->isIncompleteVar())
continue;
if (!isExpression(tok->astParent()))
continue;
const std::string& name = getIncompleteNameID(tok);
nonneg int sid = 0;
if (unknownConstantIds.count(name) > 0) {
sid = unknownConstantIds.at(name);
tok->isIncompleteConstant(true);
} else if (unknownIds.count(name) == 0) {
sid = id++;
unknownIds[name] = sid;
} else {
sid = unknownIds.at(name);
}
assert(sid > 0);
tok->exprId(sid);
}
// Assign IDs
ExprIdMap exprIdMap;
std::map<std::string, std::pair<nonneg int, const Token*>> baseIds;
for (auto* tok = const_cast<Token*>(scope->bodyStart); tok != scope->bodyEnd; tok = tok->next()) {
if (tok->varId() > 0) {
tok->exprId(tok->varId());
if (tok->astParent() && tok->astParent()->exprId() == 0)
setParentExprId(tok, exprIdMap, id);
} else if (tok->astParent() && !tok->astOperand1() && !tok->astOperand2()) {
if (tok->tokType() == Token::Type::eBracket)
continue;
if (tok->astParent()->str() == "=")
continue;
if (tok->isControlFlowKeyword())
continue;
if (Token::Match(tok->tokAt(-1), ". %name%") && Token::Match(tok->tokAt(-2), "[{,]")) // designated initializers
continue;
if (Token::Match(tok, "%name% <") && tok->linkAt(1)) {
tok->exprId(id);
++id;
} else {
const auto it = baseIds.find(tok->str());
if (it != baseIds.end() && compareTokenFlags(tok, it->second.second, /*macro*/ true)) {
tok->exprId(it->second.first);
} else {
baseIds[tok->str()] = { id, tok };
tok->exprId(id);
++id;
}
}
setParentExprId(tok, exprIdMap, id);
}
}
for (auto* tok = const_cast<Token*>(scope->bodyStart); tok != scope->bodyEnd; tok = tok->next()) {
if (tok->varId() == 0 && tok->exprId() > 0 && tok->astParent() && !tok->astOperand1() && !tok->astOperand2()) {
if (tok->isNumber() || tok->isKeyword() || Token::Match(tok->astParent(), ".|::") ||
(Token::simpleMatch(tok->astParent(), "(") && precedes(tok, tok->astParent())))
tok->exprId(0);
}
}
}
// Mark expressions that are unique
std::vector<std::pair<Token*, int>> uniqueExprId(id);
for (Token* tok = mTokenizer.list.front(); tok; tok = tok->next()) {
const auto id2 = tok->exprId();
if (id2 == 0 || id2 <= maximumVarId)
continue;
uniqueExprId[id2].first = tok;
uniqueExprId[id2].second++;
}
for (const auto& p : uniqueExprId) {
if (!p.first || p.second != 1)
continue;
if (p.first->variable()) {
const Variable* var = p.first->variable();
if (var->nameToken() != p.first)
continue;
}
p.first->setUniqueExprId();
}
}
void SymbolDatabase::setArrayDimensionsUsingValueFlow()
{
// set all unknown array dimensions
for (const Variable *var : mVariableList) {
// check each array variable
if (!var || !var->isArray())
continue;
// check each array dimension
for (const Dimension &const_dimension : var->dimensions()) {
auto &dimension = const_cast<Dimension &>(const_dimension);
if (dimension.num != 0 || !dimension.tok)
continue;
if (Token::Match(dimension.tok->previous(), "[<,]")) {
if (dimension.known)
continue;
if (!Token::Match(dimension.tok->previous(), "[<,]"))
continue;
// In template arguments, there might not be AST
// Determine size by using the "raw tokens"
TokenList tokenList(&mSettings);
tokenList.setLang(dimension.tok->isCpp() ? Standards::Language::CPP : Standards::Language::C);
tokenList.addtoken(";", 0, 0, 0, false);
bool fail = false;
for (const Token *tok = dimension.tok; tok && !Token::Match(tok, "[,>]"); tok = tok->next()) {
if (!tok->isName())
tokenList.addtoken(tok->str(), 0, 0, 0, false);
else if (tok->hasKnownIntValue())
tokenList.addtoken(std::to_string(tok->getKnownIntValue()), 0, 0, 0, false);
else {
fail = true;
break;
}
}
if (fail)
continue;
tokenList.addtoken(";", 0, 0, 0, false);
for (Token *tok = tokenList.front(); tok;) {
if (TemplateSimplifier::simplifyNumericCalculations(tok, false))
tok = tokenList.front();
else
tok = tok->next();
}
if (Token::Match(tokenList.front(), "; %num% ;")) {
dimension.known = true;
dimension.num = MathLib::toBigNumber(tokenList.front()->strAt(1));
}
continue;
}
// Normal array [..dimension..]
dimension.known = false;
// check for a single token dimension
if (dimension.tok->hasKnownIntValue()) {
dimension.known = true;
dimension.num = dimension.tok->getKnownIntValue();
continue;
}
if (dimension.tok->valueType() && dimension.tok->valueType()->pointer == 0) {
int bits = 0;
switch (dimension.tok->valueType()->type) {
case ValueType::Type::CHAR:
bits = mSettings.platform.char_bit;
break;
case ValueType::Type::SHORT:
bits = mSettings.platform.short_bit;
break;
case ValueType::Type::INT:
bits = mSettings.platform.int_bit;
break;
case ValueType::Type::LONG:
bits = mSettings.platform.long_bit;
break;
case ValueType::Type::LONGLONG:
bits = mSettings.platform.long_long_bit;
break;
default:
break;
}
if (bits > 0 && bits <= 62) {
if (dimension.tok->valueType()->sign == ValueType::Sign::UNSIGNED)
dimension.num = 1LL << bits;
else
dimension.num = 1LL << (bits - 1);
}
}
}
}
}
SymbolDatabase::~SymbolDatabase()
{
// Clear scope, type, function and variable pointers
for (Token* tok = mTokenizer.list.front(); tok; tok = tok->next()) {
tok->scope(nullptr);
tok->type(nullptr);
tok->function(nullptr);
tok->variable(nullptr);
tok->enumerator(nullptr);
tok->setValueType(nullptr);
}
}
bool SymbolDatabase::isFunction(const Token *tok, const Scope* outerScope, const Token *&funcStart, const Token *&argStart, const Token*& declEnd) const
{
if (tok->varId())
return false;
// function returning function pointer? '... ( ... %name% ( ... ))( ... ) {'
// function returning reference to array '... ( & %name% ( ... ))[ ... ] {'
// TODO: Activate this again
if ((false) && tok->str() == "(" && tok->strAt(1) != "*" && // NOLINT(readability-simplify-boolean-expr)
(tok->link()->strAt(-1) == ")" || Token::simpleMatch(tok->link()->tokAt(-2), ") const"))) {
const Token* tok2 = tok->link()->next();
if (tok2 && tok2->str() == "(" && Token::Match(tok2->link()->next(), "{|;|const|=")) {
const Token* argStartTok;
if (tok->link()->strAt(-1) == "const")
argStartTok = tok->link()->linkAt(-2);
else
argStartTok = tok->link()->linkAt(-1);
funcStart = argStartTok->previous();
argStart = argStartTok;
declEnd = Token::findmatch(tok2->link()->next(), "{|;");
return true;
}
if (tok2 && tok2->str() == "[") {
while (tok2 && tok2->str() == "[")
tok2 = tok2->link()->next();
if (Token::Match(tok2, "{|;|const|=")) {
const Token* argStartTok;
if (tok->link()->strAt(-1) == "const")
argStartTok = tok->link()->linkAt(-2);
else
argStartTok = tok->link()->linkAt(-1);
funcStart = argStartTok->previous();
argStart = argStartTok;
declEnd = Token::findmatch(tok2, "{|;");
return true;
}
}
}
else if (!tok->isName() || !tok->next() || !tok->linkAt(1))
return false;
// regular function?
else if (Token::Match(tok, "%name% (") && !isReservedName(tok) && tok->previous() &&
(Token::Match(tok->previous(), "%name%|>|&|&&|*|::|~") || // Either a return type or scope qualifier in front of tok
outerScope->isClassOrStructOrUnion())) { // or a ctor/dtor
const Token* tok1 = tok->previous();
const Token* tok2 = tok->linkAt(1)->next();
if (!Tokenizer::isFunctionHead(tok->next(), ";:{"))
return false;
// skip over destructor "~"
if (tok1->str() == "~")
tok1 = tok1->previous();
// skip over qualification
while (Token::simpleMatch(tok1, "::")) {
tok1 = tok1->previous();
if (tok1 && tok1->isName())
tok1 = tok1->previous();
else if (tok1 && tok1->str() == ">" && tok1->link() && Token::Match(tok1->link()->previous(), "%name%"))
tok1 = tok1->link()->tokAt(-2);
}
// skip over const, noexcept, throw, override, final and volatile specifiers
while (Token::Match(tok2, "const|noexcept|throw|override|final|volatile|&|&&")) {
tok2 = tok2->next();
if (tok2 && tok2->str() == "(")
tok2 = tok2->link()->next();
}
// skip over trailing return type
bool hasTrailingRet = false;
if (tok2 && tok2->str() == ".") {
hasTrailingRet = true;
for (tok2 = tok2->next(); tok2; tok2 = tok2->next()) {
if (Token::Match(tok2, ";|{|=|override|final"))
break;
if (tok2->link() && Token::Match(tok2, "<|[|("))
tok2 = tok2->link();
}
}
// done if constructor or destructor
if (!Token::Match(tok1, "{|}|;|public:|protected:|private:") && tok1) {
// skip over pointers and references
while (Token::Match(tok1, "%type%|*|&|&&") && !endsWith(tok1->str(), ':') && (!isReservedName(tok1) || tok1->str() == "const"))
tok1 = tok1->previous();
// skip over decltype
if (Token::simpleMatch(tok1, ")") && tok1->link() &&
Token::simpleMatch(tok1->link()->previous(), "decltype ("))
tok1 = tok1->link()->tokAt(-2);
// skip over template
if (tok1 && tok1->str() == ">") {
if (tok1->link())
tok1 = tok1->link()->previous();
else
return false;
}
// function can't have number or variable as return type
if (tok1 && (tok1->isNumber() || tok1->varId()))
return false;
// skip over return type
if (tok1 && tok1->isName()) {
if (tok1->str() == "return")
return false;
if (tok1->str() != "friend")
tok1 = tok1->previous();
}
// skip over qualification
while (Token::simpleMatch(tok1, "::")) {
tok1 = tok1->previous();
if (tok1 && tok1->isName())
tok1 = tok1->previous();
else if (tok1 && tok1->str() == ">" && tok1->link() && Token::Match(tok1->link()->previous(), "%name%"))
tok1 = tok1->link()->tokAt(-2);
else if (Token::simpleMatch(tok1, ")") && tok1->link() &&
Token::simpleMatch(tok1->link()->previous(), "decltype ("))
tok1 = tok1->link()->tokAt(-2);
}
// skip over modifiers and other stuff
while (Token::Match(tok1, "const|static|extern|template|virtual|struct|class|enum|%name%")) {
// friend type func(); is not a function
if (tok1->isCpp() && tok1->str() == "friend" && tok2->str() == ";")
return false;
tok1 = tok1->previous();
}
// should be at a sequence point if this is a function
if (!Token::Match(tok1, ">|{|}|;|public:|protected:|private:") && tok1)
return false;
}
if (tok2 &&
(Token::Match(tok2, ";|{|=") ||
(tok2->isUpperCaseName() && Token::Match(tok2, "%name% ;|{")) ||
(tok2->isUpperCaseName() && Token::Match(tok2, "%name% (") && tok2->linkAt(1)->strAt(1) == "{") ||
Token::Match(tok2, ": ::| %name% (|::|<|{") ||
Token::Match(tok2, "&|&&| ;|{") ||
Token::Match(tok2, "= delete|default ;") ||
(hasTrailingRet && Token::Match(tok2, "final|override")))) {
funcStart = tok;
argStart = tok->next();
declEnd = Token::findmatch(tok2, "{|;");
return true;
}
}
// UNKNOWN_MACRO(a,b) { ... }
else if (outerScope->type == Scope::eGlobal &&
Token::Match(tok, "%name% (") &&
tok->isUpperCaseName() &&
Token::simpleMatch(tok->linkAt(1), ") {") &&
(!tok->previous() || Token::Match(tok->previous(), "[;{}]"))) {
funcStart = tok;
argStart = tok->next();
declEnd = tok->linkAt(1)->next();
return true;
}
// template constructor?
else if (Token::Match(tok, "%name% <") && Token::simpleMatch(tok->linkAt(1), "> (")) {
if (tok->isKeyword() || tok->isStandardType() || !outerScope->isClassOrStructOrUnion())
return false;
const Token* tok2 = tok->linkAt(1)->linkAt(1);
if (Token::Match(tok2, ") const| ;|{|=") ||
Token::Match(tok2, ") : ::| %name% (|::|<|{") ||
Token::Match(tok2, ") const| noexcept {|;|(")) {
funcStart = tok;
argStart = tok2->link();
declEnd = Token::findmatch(tok2->next(), "{|;");
return true;
}
}
// regular C function with missing return or invalid C++ ?
else if (Token::Match(tok, "%name% (") && !isReservedName(tok) &&
Token::simpleMatch(tok->linkAt(1), ") {") &&
(!tok->previous() || Token::Match(tok->previous(), ";|}"))) {
if (tok->isC()) {
returnImplicitIntError(tok);
funcStart = tok;
argStart = tok->next();
declEnd = tok->linkAt(1)->next();
return true;
}
mTokenizer.syntaxError(tok);
}
return false;
}
void SymbolDatabase::validateExecutableScopes() const
{
const std::size_t functions = functionScopes.size();
for (std::size_t i = 0; i < functions; ++i) {
const Scope* const scope = functionScopes[i];
const Function* const function = scope->function;
if (scope->isExecutable() && !function) {
const std::list<const Token*> callstack(1, scope->classDef);
const std::string msg = std::string("Executable scope '") + scope->classDef->str() + "' with unknown function.";
const ErrorMessage errmsg(callstack, &mTokenizer.list, Severity::debug,
"symbolDatabaseWarning",
msg,
Certainty::normal);
mErrorLogger.reportErr(errmsg);
}
}
}
namespace {
const Function* getFunctionForArgumentvariable(const Variable * const var)
{
if (const Scope* scope = var->nameToken()->scope()) {
auto it = std::find_if(scope->functionList.begin(), scope->functionList.end(), [&](const Function& function) {
for (nonneg int arg = 0; arg < function.argCount(); ++arg) {
if (var == function.getArgumentVar(arg))
return true;
}
return false;
});
if (it != scope->functionList.end())
return &*it;
}
return nullptr;
}
}
void SymbolDatabase::validateVariables() const
{
for (auto iter = mVariableList.cbegin(); iter!=mVariableList.cend(); ++iter) {
const Variable * const var = *iter;
if (var) {
if (!var->scope()) {
const Function* function = getFunctionForArgumentvariable(var);
if (!var->isArgument() || (!function || function->hasBody())) { // variables which only appear in a function declaration do not have a scope
throw InternalError(var->nameToken(), "Analysis failed (variable without scope). If the code is valid then please report this failure.", InternalError::INTERNAL);
}
}
}
}
}
void SymbolDatabase::validate() const
{
if (mSettings.debugwarnings) {
validateExecutableScopes();
}
validateVariables();
}
void SymbolDatabase::clangSetVariables(const std::vector<const Variable *> &variableList)
{
mVariableList = variableList;
}
void SymbolDatabase::debugSymbolDatabase() const
{
if (!mSettings.debugnormal && !mSettings.debugwarnings)
return;
for (const Token* tok = mTokenizer.list.front(); tok != mTokenizer.list.back(); tok = tok->next()) {
if (tok->astParent() && tok->astParent()->getTokenDebug() == tok->getTokenDebug())
continue;
if (tok->getTokenDebug() == TokenDebug::ValueType) {
std::string msg = "Value type is ";
ErrorPath errorPath;
if (tok->valueType()) {
msg += tok->valueType()->str();
errorPath.insert(errorPath.end(), tok->valueType()->debugPath.cbegin(), tok->valueType()->debugPath.cend());
} else {
msg += "missing";
}
errorPath.emplace_back(tok, "");
mErrorLogger.reportErr(
{errorPath, &mTokenizer.list, Severity::debug, "valueType", msg, CWE{0}, Certainty::normal});
}
}
}
Variable::Variable(const Token *name_, const std::string &clangType, const Token *typeStart,
const Token *typeEnd, nonneg int index_, AccessControl access_,
const Type *type_, const Scope *scope_)
: mNameToken(name_),
mTypeStartToken(typeStart),
mTypeEndToken(typeEnd),
mIndex(index_),
mAccess(access_),
mFlags(0),
mType(type_),
mScope(scope_)
{
if (!mTypeStartToken && mTypeEndToken) {
mTypeStartToken = mTypeEndToken;
while (Token::Match(mTypeStartToken->previous(), "%type%|*|&"))
mTypeStartToken = mTypeStartToken->previous();
}
while (Token::Match(mTypeStartToken, "const|struct|static")) {
if (mTypeStartToken->str() == "static")
setFlag(fIsStatic, true);
mTypeStartToken = mTypeStartToken->next();
}
if (Token::simpleMatch(mTypeEndToken, "&"))
setFlag(fIsReference, true);
else if (Token::simpleMatch(mTypeEndToken, "&&")) {
setFlag(fIsReference, true);
setFlag(fIsRValueRef, true);
}
std::string::size_type pos = clangType.find('[');
if (pos != std::string::npos) {
setFlag(fIsArray, true);
do {
const std::string::size_type pos1 = pos+1;
pos = clangType.find(']', pos1);
Dimension dim;
dim.tok = nullptr;
dim.known = pos > pos1;
if (pos > pos1)
dim.num = MathLib::toBigNumber(clangType.substr(pos1, pos - pos1));
else
dim.num = 0;
mDimensions.push_back(dim);
++pos;
} while (pos < clangType.size() && clangType[pos] == '[');
}
// Is there initialization in variable declaration
const Token *initTok = mNameToken ? mNameToken->next() : nullptr;
while (initTok && initTok->str() == "[")
initTok = initTok->link()->next();
if (Token::Match(initTok, "=|{") || (initTok && initTok->isSplittedVarDeclEq()))
setFlag(fIsInit, true);
}
Variable::Variable(const Variable &var, const Scope *scope)
{
*this = var;
mScope = scope;
}
Variable::Variable(const Variable &var)
{
*this = var;
}
Variable::~Variable()
{
delete mValueType;
}
Variable& Variable::operator=(const Variable &var) &
{
if (this == &var)
return *this;
ValueType* vt = nullptr;
if (var.mValueType)
vt = new ValueType(*var.mValueType);
mNameToken = var.mNameToken;
mTypeStartToken = var.mTypeStartToken;
mTypeEndToken = var.mTypeEndToken;
mIndex = var.mIndex;
mAccess = var.mAccess;
mFlags = var.mFlags;
mType = var.mType;
mScope = var.mScope;
mDimensions = var.mDimensions;
delete mValueType;
mValueType = vt;
return *this;
}
bool Variable::isMember() const {
return mScope && mScope->isClassOrStructOrUnion();
}
bool Variable::isPointerArray() const
{
return isArray() && nameToken() && nameToken()->previous() && (nameToken()->strAt(-1) == "*");
}
bool Variable::isUnsigned() const
{
return mValueType ? (mValueType->sign == ValueType::Sign::UNSIGNED) : mTypeStartToken->isUnsigned();
}
const Token * Variable::declEndToken() const
{
Token const * declEnd = typeStartToken();
while (declEnd && !Token::Match(declEnd, "[;,)={]")) {
if (declEnd->link() && Token::Match(declEnd,"(|[|<"))
declEnd = declEnd->link();
declEnd = declEnd->next();
}
return declEnd;
}
void Variable::evaluate(const Settings& settings)
{
// Is there initialization in variable declaration
const Token *initTok = mNameToken ? mNameToken->next() : nullptr;
while (Token::Match(initTok, "[")) {
initTok = initTok->link()->next();
if (Token::simpleMatch(initTok, ")"))
initTok = initTok->next();
}
if (Token::Match(initTok, "[={(]") || (initTok && initTok->isSplittedVarDeclEq()))
setFlag(fIsInit, true);
const Library & lib = settings.library;
bool isContainer = false;
if (mNameToken)
setFlag(fIsArray, arrayDimensions(settings, isContainer));
if (mTypeStartToken)
setValueType(ValueType::parseDecl(mTypeStartToken,settings));
const Token* tok = mTypeStartToken;
while (tok && tok->previous() && tok->previous()->isName())
tok = tok->previous();
const Token* end = mTypeEndToken;
if (end)
end = end->next();
while (tok != end) {
if (tok->str() == "static")
setFlag(fIsStatic, true);
else if (tok->str() == "extern")
setFlag(fIsExtern, true);
else if (tok->str() == "volatile" || Token::simpleMatch(tok, "std :: atomic <"))
setFlag(fIsVolatile, true);
else if (tok->str() == "mutable")
setFlag(fIsMutable, true);
else if (tok->str() == "const")
setFlag(fIsConst, true);
else if (tok->str() == "constexpr") {
setFlag(fIsConst, true);
setFlag(fIsStatic, true);
} else if (tok->str() == "*") {
setFlag(fIsPointer, !isArray() || (isContainer && !Token::Match(tok->next(), "%name% [")) || Token::Match(tok, "* const| %name% )"));
setFlag(fIsConst, false); // Points to const, isn't necessarily const itself
} else if (tok->str() == "&") {
if (isReference())
setFlag(fIsRValueRef, true);
setFlag(fIsReference, true);
} else if (tok->str() == "&&") { // Before simplification, && isn't split up
setFlag(fIsRValueRef, true);
setFlag(fIsReference, true); // Set also fIsReference
}
if (tok->isAttributeMaybeUnused()) {
setFlag(fIsMaybeUnused, true);
}
if (tok->str() == "<" && tok->link())
tok = tok->link();
else
tok = tok->next();
}
while (Token::Match(mTypeStartToken, "static|const|constexpr|volatile %any%"))
mTypeStartToken = mTypeStartToken->next();
while (mTypeEndToken && mTypeEndToken->previous() && Token::Match(mTypeEndToken, "const|volatile"))
mTypeEndToken = mTypeEndToken->previous();
if (mTypeStartToken) {
std::string strtype = mTypeStartToken->str();
for (const Token *typeToken = mTypeStartToken; Token::Match(typeToken, "%type% :: %type%"); typeToken = typeToken->tokAt(2))
strtype += "::" + typeToken->strAt(2);
setFlag(fIsClass, !lib.podtype(strtype) && !mTypeStartToken->isStandardType() && !isEnumType() && !isPointer() && !isReference() && strtype != "...");
setFlag(fIsStlType, Token::simpleMatch(mTypeStartToken, "std ::"));
setFlag(fIsStlString, ::isStlStringType(mTypeStartToken));
setFlag(fIsSmartPointer, mTypeStartToken->isCpp() && lib.isSmartPointer(mTypeStartToken));
}
if (mAccess == AccessControl::Argument) {
tok = mNameToken;
if (!tok) {
// Argument without name
tok = mTypeEndToken;
// back up to start of array dimensions
while (tok && tok->str() == "]")
tok = tok->link()->previous();
// add array dimensions if present
if (tok && tok->strAt(1) == "[")
setFlag(fIsArray, arrayDimensions(settings, isContainer));
}
if (!tok)
return;
tok = tok->next();
while (tok->str() == "[")
tok = tok->link();
setFlag(fHasDefault, tok->str() == "=");
}
// check for C++11 member initialization
if (mScope && mScope->isClassOrStruct()) {
// type var = x or
// type var = {x}
// type var = x; gets simplified to: type var ; var = x ;
Token const * declEnd = declEndToken();
if ((Token::Match(declEnd, "; %name% =") && declEnd->strAt(1) == mNameToken->str()) ||
Token::Match(declEnd, "=|{"))
setFlag(fHasDefault, true);
}
if (mTypeStartToken) {
if (Token::Match(mTypeStartToken, "float|double"))
setFlag(fIsFloatType, true);
}
}
void Variable::setValueType(const ValueType &valueType)
{
if (valueType.type == ValueType::Type::UNKNOWN_TYPE) {
const Token *declType = Token::findsimplematch(mTypeStartToken, "decltype (", mTypeEndToken);
if (declType && !declType->next()->valueType())
return;
}
auto* vt = new ValueType(valueType);
delete mValueType;
mValueType = vt;
if ((mValueType->pointer > 0) && (!isArray() || Token::Match(mNameToken->previous(), "( * %name% )")))
setFlag(fIsPointer, true);
setFlag(fIsConst, mValueType->constness & (1U << mValueType->pointer));
setFlag(fIsVolatile, mValueType->volatileness & (1U << mValueType->pointer));
if (mValueType->smartPointerType)
setFlag(fIsSmartPointer, true);
}
const Type* Variable::smartPointerType() const
{
if (!isSmartPointer())
return nullptr;
if (mValueType->smartPointerType)
return mValueType->smartPointerType;
// TODO: Cache result, handle more complex type expression
const Token* typeTok = typeStartToken();
while (Token::Match(typeTok, "%name%|::"))
typeTok = typeTok->next();
if (Token::Match(typeTok, "< %name% >")) {
// cppcheck-suppress shadowFunction - TODO: fix this
const Scope* scope = typeTok->scope();
const Type* ptrType{};
while (scope && !ptrType) {
ptrType = scope->findType(typeTok->strAt(1));
scope = scope->nestedIn;
}
return ptrType;
}
return nullptr;
}
const Type* Variable::iteratorType() const
{
if (!mValueType || mValueType->type != ValueType::ITERATOR)
return nullptr;
if (mValueType->containerTypeToken)
return mValueType->containerTypeToken->type();
return nullptr;
}
bool Variable::isStlStringViewType() const
{
return getFlag(fIsStlType) && valueType() && valueType()->container && valueType()->container->stdStringLike && valueType()->container->view;
}
std::string Variable::getTypeName() const
{
std::string ret;
// TODO: For known types, generate the full type name
for (const Token *typeTok = mTypeStartToken; Token::Match(typeTok, "%name%|::") && typeTok->varId() == 0; typeTok = typeTok->next()) {
ret += typeTok->str();
if (Token::simpleMatch(typeTok->next(), "<") && typeTok->linkAt(1)) // skip template arguments
typeTok = typeTok->linkAt(1);
}
return ret;
}
static bool isOperator(const Token *tokenDef)
{
if (!tokenDef)
return false;
if (tokenDef->isOperatorKeyword())
return true;
const std::string &name = tokenDef->str();
return name.size() > 8 && startsWith(name,"operator") && std::strchr("+-*/%&|~^<>!=[(", name[8]);
}
static bool isTrailingReturnType(const Token* tok)
{
while (tok && tok->isKeyword())
tok = tok->next();
return Token::Match(tok, "&|&&| .");
}
Function::Function(const Token *tok,
const Scope *scope,
const Token *tokDef,
const Token *tokArgDef)
: tokenDef(tokDef),
argDef(tokArgDef),
nestedIn(scope)
{
// operator function
if (::isOperator(tokenDef)) {
isOperator(true);
// 'operator =' is special
if (tokenDef->str() == "operator=")
type = Function::eOperatorEqual;
}
else if (tokenDef->str() == "[") {
type = Function::eLambda;
}
// class constructor/destructor
else if (scope->isClassOrStructOrUnion() &&
((tokenDef->str() == scope->className) ||
(tokenDef->str().substr(0, scope->className.size()) == scope->className &&
tokenDef->str().size() > scope->className.size() + 1 &&
tokenDef->str()[scope->className.size() + 1] == '<'))) {
// destructor
if (tokenDef->strAt(-1) == "~") {
type = Function::eDestructor;
isNoExcept(true);
}
// constructor of any kind
else
type = Function::eConstructor;
isExplicit(tokenDef->strAt(-1) == "explicit" || tokenDef->strAt(-2) == "explicit");
}
const Token *tok1 = setFlags(tok, scope);
// find the return type
if (!isConstructor() && !isDestructor()) {
// @todo auto type deduction should be checked
// @todo attributes and exception specification can also precede trailing return type
if (isTrailingReturnType(argDef->link()->next())) { // Trailing return type
hasTrailingReturnType(true);
if (argDef->link()->strAt(1) == ".")
retDef = argDef->link()->tokAt(2);
else if (argDef->link()->strAt(2) == ".")
retDef = argDef->link()->tokAt(3);
else if (argDef->link()->strAt(3) == ".")
retDef = argDef->link()->tokAt(4);
} else if (!isLambda()) {
if (tok1->str() == ">")
tok1 = tok1->next();
while (Token::Match(tok1, "extern|virtual|static|friend|struct|union|enum"))
tok1 = tok1->next();
retDef = tok1;
}
}
const Token *end = argDef->link();
// parse function attributes..
tok = end->next();
while (tok) {
if (tok->str() == "const")
isConst(true);
else if (tok->str() == "&")
hasLvalRefQualifier(true);
else if (tok->str() == "&&")
hasRvalRefQualifier(true);
else if (tok->str() == "override")
setFlag(fHasOverrideSpecifier, true);
else if (tok->str() == "final")
setFlag(fHasFinalSpecifier, true);
else if (tok->str() == "volatile")
isVolatile(true);
else if (tok->str() == "noexcept") {
isNoExcept(!Token::simpleMatch(tok->next(), "( false )"));
if (tok->strAt(1) == "(")
tok = tok->linkAt(1);
} else if (Token::simpleMatch(tok, "throw (")) {
isThrow(true);
if (tok->strAt(2) != ")")
throwArg = tok->next();
tok = tok->linkAt(1);
} else if (Token::Match(tok, "= 0|default|delete ;")) {
const std::string& modifier = tok->strAt(1);
isPure(modifier == "0");
isDefault(modifier == "default");
isDelete(modifier == "delete");
} else if (tok->str() == ".") { // trailing return type
// skip over return type
while (tok && !Token::Match(tok->next(), ";|{|override|final"))
tok = tok->next();
} else
break;
if (tok)
tok = tok->next();
}
if (Tokenizer::isFunctionHead(end, ":{")) {
// assume implementation is inline (definition and implementation same)
token = tokenDef;
arg = argDef;
isInline(true);
hasBody(true);
}
}
Function::Function(const Token *tokenDef, const std::string &clangType)
: tokenDef(tokenDef)
{
// operator function
if (::isOperator(tokenDef)) {
isOperator(true);
// 'operator =' is special
if (tokenDef->str() == "operator=")
type = Function::eOperatorEqual;
}
setFlags(tokenDef, tokenDef->scope());
if (endsWith(clangType, " const"))
isConst(true);
}
const Token *Function::setFlags(const Token *tok1, const Scope *scope)
{
if (tok1->isInline())
isInlineKeyword(true);
// look for end of previous statement
while (tok1->previous() && !Token::Match(tok1->previous(), ";|}|{|public:|protected:|private:")) {
tok1 = tok1->previous();
if (tok1->isInline())
isInlineKeyword(true);
// extern function
if (tok1->isExternC() || tok1->str() == "extern") {
isExtern(true);
}
// virtual function
else if (tok1->str() == "virtual") {
hasVirtualSpecifier(true);
}
// static function
else if (tok1->str() == "static") {
isStatic(true);
if (scope->type == Scope::eNamespace || scope->type == Scope::eGlobal)
isStaticLocal(true);
}
// friend function
else if (tok1->str() == "friend") {
isFriend(true);
}
// constexpr function
else if (tok1->str() == "constexpr") {
isConstexpr(true);
}
// decltype
else if (tok1->str() == ")" && Token::simpleMatch(tok1->link()->previous(), "decltype (")) {
tok1 = tok1->link()->previous();
}
else if (tok1->link() && tok1->str() == ">") {
// Function template
if (Token::simpleMatch(tok1->link()->previous(), "template <")) {
templateDef = tok1->link()->previous();
break;
}
tok1 = tok1->link();
}
}
return tok1;
}
std::string Function::fullName() const
{
std::string ret = name();
for (const Scope *s = nestedIn; s; s = s->nestedIn) {
if (!s->className.empty())
ret = s->className + "::" + ret;
}
ret += "(";
for (const Variable &a : argumentList)
ret += (a.index() == 0 ? "" : ",") + a.name();
return ret + ")";
}
static std::string qualifiedName(const Scope *scope)
{
std::string name = scope->className;
while (scope->nestedIn) {
if (!scope->nestedIn->className.empty())
name = (scope->nestedIn->className + " :: ") + name;
scope = scope->nestedIn;
}
return name;
}
static bool usingNamespace(const Scope *scope, const Token *first, const Token *second, int &offset)
{
// check if qualifications match first before checking if using is needed
const Token *tok1 = first;
const Token *tok2 = second;
bool match = false;
while (Token::Match(tok1, "%type% :: %type%") && Token::Match(tok2, "%type% :: %type%")) {
if (tok1->str() == tok2->str()) {
tok1 = tok1->tokAt(2);
tok2 = tok2->tokAt(2);
match = true;
} else {
match = false;
break;
}
}
if (match)
return false;
offset = 0;
std::string name = first->str();
while (Token::Match(first, "%type% :: %type%")) {
if (offset)
name += (" :: " + first->str());
offset += 2;
first = first->tokAt(2);
if (first->str() == second->str()) {
break;
}
}
if (offset) {
while (scope) {
for (const auto & info : scope->usingList) {
if (info.scope) {
if (name == qualifiedName(info.scope))
return true;
}
// no scope so get name from using
else {
const Token *start = info.start->tokAt(2);
std::string nsName;
while (start && start->str() != ";") {
if (!nsName.empty())
nsName += " ";
nsName += start->str();
start = start->next();
}
if (nsName == name)
return true;
}
}
scope = scope->nestedIn;
}
}
return false;
}
static bool typesMatch(
const Scope *first_scope,
const Token *first_token,
const Scope *second_scope,
const Token *second_token,
const Token *&new_first,
const Token *&new_second)
{
// get first type
const Type* first_type = first_scope->check->findType(first_token, first_scope, /*lookOutside*/ true);
if (first_type) {
// get second type
const Type* second_type = second_scope->check->findType(second_token, second_scope, /*lookOutside*/ true);
// check if types match
if (first_type == second_type) {
const Token* tok1 = first_token;
while (tok1 && tok1->str() != first_type->name())
tok1 = tok1->next();
const Token *tok2 = second_token;
while (tok2 && tok2->str() != second_type->name())
tok2 = tok2->next();
// update parser token positions
if (tok1 && tok2) {
new_first = tok1->previous();
new_second = tok2->previous();
return true;
}
}
}
return false;
}
bool Function::argsMatch(const Scope *scope, const Token *first, const Token *second, const std::string &path, nonneg int path_length) const
{
if (!first->isCpp()) // C does not support overloads
return true;
int arg_path_length = path_length;
int offset = 0;
int openParen = 0;
// check for () == (void) and (void) == ()
if ((Token::simpleMatch(first, "( )") && Token::simpleMatch(second, "( void )")) ||
(Token::simpleMatch(first, "( void )") && Token::simpleMatch(second, "( )")))
return true;
auto skipTopLevelConst = [](const Token* start) -> const Token* {
const Token* tok = start->next();
if (Token::simpleMatch(tok, "const")) {
tok = tok->next();
while (Token::Match(tok, "%name%|%type%|::"))
tok = tok->next();
if (Token::Match(tok, ",|)|="))
return start->next();
}
return start;
};
while (first->str() == second->str() &&
first->isLong() == second->isLong() &&
first->isUnsigned() == second->isUnsigned()) {
if (first->str() == "(")
openParen++;
// at end of argument list
else if (first->str() == ")") {
if (openParen == 1)
return true;
--openParen;
}
// skip optional type information
if (Token::Match(first->next(), "struct|enum|union|class"))
first = first->next();
if (Token::Match(second->next(), "struct|enum|union|class"))
second = second->next();
// skip const on type passed by value
const Token* const oldSecond = second;
first = skipTopLevelConst(first);
second = skipTopLevelConst(second);
// skip default value assignment
if (oldSecond == second && first->strAt(1) == "=") {
first = first->nextArgument();
if (first)
first = first->tokAt(-2);
if (second->strAt(1) == "=") {
second = second->nextArgument();
if (second)
second = second->tokAt(-2);
if (!first || !second) { // End of argument list (first or second)
return !first && !second;
}
} else if (!first) { // End of argument list (first)
return !second->nextArgument(); // End of argument list (second)
}
} else if (oldSecond == second && second->strAt(1) == "=") {
second = second->nextArgument();
if (second)
second = second->tokAt(-2);
if (!second) { // End of argument list (second)
return !first->nextArgument();
}
}
// definition missing variable name
else if ((first->strAt(1) == "," && second->strAt(1) != ",") ||
(Token::Match(first, "!!( )") && second->strAt(1) != ")")) {
second = second->next();
// skip default value assignment
if (second->strAt(1) == "=") {
do {
second = second->next();
} while (!Token::Match(second->next(), ",|)"));
}
} else if (first->strAt(1) == "[" && second->strAt(1) != "[")
second = second->next();
// function missing variable name
else if ((second->strAt(1) == "," && first->strAt(1) != ",") ||
(Token::Match(second, "!!( )") && first->strAt(1) != ")")) {
first = first->next();
// skip default value assignment
if (first->strAt(1) == "=") {
do {
first = first->next();
} while (!Token::Match(first->next(), ",|)"));
}
} else if (second->strAt(1) == "[" && first->strAt(1) != "[")
first = first->next();
// unnamed parameters
else if (Token::Match(first, "(|, %type% ,|)") && Token::Match(second, "(|, %type% ,|)")) {
if (first->next()->expressionString() != second->next()->expressionString())
break;
first = first->next();
second = second->next();
continue;
}
// argument list has different number of arguments
else if (openParen == 1 && second->str() == ")" && first->str() != ")")
break;
// check for type * x == type x[]
else if (Token::Match(first->next(), "* %name%| ,|)|=") &&
Token::Match(second->next(), "%name%| [ ] ,|)")) {
do {
first = first->next();
} while (!Token::Match(first->next(), ",|)"));
do {
second = second->next();
} while (!Token::Match(second->next(), ",|)"));
}
// const after *
else if (first->strAt(1) == "*" && second->strAt(1) == "*" &&
((first->strAt(2) != "const" && second->strAt(2) == "const") ||
(first->strAt(2) == "const" && second->strAt(2) != "const"))) {
if (first->strAt(2) != "const") {
if (Token::Match(first->tokAt(2), "%name%| ,|)") && Token::Match(second->tokAt(3), "%name%| ,|)")) {
first = first->tokAt(Token::Match(first->tokAt(2), "%name%") ? 2 : 1);
second = second->tokAt(Token::Match(second->tokAt(3), "%name%") ? 3 : 2);
} else {
first = first->next();
second = second->tokAt(2);
}
} else {
if (Token::Match(second->tokAt(2), "%name%| ,|)") && Token::Match(first->tokAt(3), "%name%| ,|)")) {
first = first->tokAt(Token::Match(first->tokAt(3), "%name%") ? 3 : 2);
second = second->tokAt(Token::Match(second->tokAt(2), "%name%") ? 2 : 1);
} else {
first = first->tokAt(2);
second = second->next();
}
}
}
// variable names are different
else if ((Token::Match(first->next(), "%name% ,|)|=|[") &&
Token::Match(second->next(), "%name% ,|)|[")) &&
(first->strAt(1) != second->strAt(1))) {
// skip variable names
first = first->next();
second = second->next();
// skip default value assignment
if (first->strAt(1) == "=") {
do {
first = first->next();
} while (!Token::Match(first->next(), ",|)"));
}
}
// using namespace
else if (usingNamespace(scope, first->next(), second->next(), offset))
first = first->tokAt(offset);
// same type with different qualification
else if (typesMatch(scope, first->next(), nestedIn, second->next(), first, second))
;
// variable with class path
else if (arg_path_length && Token::Match(first->next(), "%name%") && first->strAt(1) != "const") {
std::string param = path;
if (Token::simpleMatch(second->next(), param.c_str(), param.size())) {
// check for redundant qualification before skipping it
if (!Token::simpleMatch(first->next(), param.c_str(), param.size())) {
second = second->tokAt(arg_path_length);
arg_path_length = 0;
}
}
// nested or base class variable
else if (arg_path_length <= 2 && Token::Match(first->next(), "%name%") &&
(Token::Match(second->next(), "%name% :: %name%") ||
(Token::Match(second->next(), "%name% <") &&
Token::Match(second->linkAt(1), "> :: %name%"))) &&
((second->strAt(1) == scope->className) ||
(scope->nestedIn && second->strAt(1) == scope->nestedIn->className) ||
(scope->definedType && scope->definedType->isDerivedFrom(second->strAt(1)))) &&
(first->strAt(1) == second->strAt(3))) {
if (Token::Match(second->next(), "%name% <"))
second = second->linkAt(1)->next();
else
second = second->tokAt(2);
}
// remove class name
else if (arg_path_length > 2 && first->strAt(1) != second->strAt(1)) {
std::string short_path = path;
int short_path_length = arg_path_length;
// remove last " :: "
short_path.resize(short_path.size() - 4);
short_path_length--;
// remove last name
std::string::size_type lastSpace = short_path.find_last_of(' ');
if (lastSpace != std::string::npos) {
short_path.resize(lastSpace+1);
short_path_length--;
if (short_path[short_path.size() - 1] == '>') {
short_path.resize(short_path.size() - 3);
while (short_path[short_path.size() - 1] == '<') {
lastSpace = short_path.find_last_of(' ');
short_path.resize(lastSpace+1);
short_path_length--;
}
}
}
param = std::move(short_path);
if (Token::simpleMatch(second->next(), param.c_str(), param.size())) {
second = second->tokAt(short_path_length);
arg_path_length = 0;
}
}
}
first = first->next();
second = second->next();
// reset path length
if (first->str() == "," || second->str() == ",")
arg_path_length = path_length;
}
return false;
}
static bool isUnknownType(const Token* start, const Token* end)
{
while (Token::Match(start, "const|volatile"))
start = start->next();
start = skipScopeIdentifiers(start);
if (start->tokAt(1) == end && !start->type() && !start->isStandardType())
return true;
// TODO: Try to deduce the type of the expression
if (Token::Match(start, "decltype|typeof"))
return true;
return false;
}
static const Token* getEnableIfReturnType(const Token* start)
{
if (!start)
return nullptr;
for (const Token* tok = start->next(); precedes(tok, start->link()); tok = tok->next()) {
if (tok->link() && Token::Match(tok, "(|[|{|<")) {
tok = tok->link();
continue;
}
if (Token::simpleMatch(tok, ","))
return tok->next();
}
return nullptr;
}
template<class Predicate>
static bool checkReturns(const Function* function, bool unknown, bool emptyEnableIf, Predicate pred)
{
if (!function)
return false;
if (function->type != Function::eFunction && function->type != Function::eOperatorEqual && function->type != Function::eLambda)
return false;
const Token* defStart = function->retDef;
if (!defStart)
return unknown;
const Token* defEnd = function->returnDefEnd();
if (!defEnd)
return unknown;
if (defEnd == defStart)
return unknown;
if (pred(defStart, defEnd))
return true;
if (Token::Match(defEnd->tokAt(-1), "*|&|&&"))
return false;
// void STDCALL foo()
while (defEnd->previous() != defStart && Token::Match(defEnd->tokAt(-2), "%name%|> %name%") &&
!Token::Match(defEnd->tokAt(-2), "const|volatile"))
defEnd = defEnd->previous();
// enable_if
const Token* enableIfEnd = nullptr;
if (Token::simpleMatch(defEnd->previous(), ">"))
enableIfEnd = defEnd->previous();
else if (Token::simpleMatch(defEnd->tokAt(-3), "> :: type"))
enableIfEnd = defEnd->tokAt(-3);
if (enableIfEnd && enableIfEnd->link() &&
Token::Match(enableIfEnd->link()->previous(), "enable_if|enable_if_t|EnableIf")) {
if (const Token* start = getEnableIfReturnType(enableIfEnd->link())) {
defStart = start;
defEnd = enableIfEnd;
} else {
return emptyEnableIf;
}
}
assert(defEnd != defStart);
if (pred(defStart, defEnd))
return true;
if (isUnknownType(defStart, defEnd))
return unknown;
return false;
}
bool Function::returnsConst(const Function* function, bool unknown)
{
return checkReturns(function, unknown, false, [](const Token* defStart, const Token* defEnd) {
return Token::findsimplematch(defStart, "const", defEnd);
});
}
bool Function::returnsReference(const Function* function, bool unknown, bool includeRValueRef)
{
return checkReturns(function, unknown, false, [includeRValueRef](const Token* /*defStart*/, const Token* defEnd) {
return includeRValueRef ? Token::Match(defEnd->previous(), "&|&&") : Token::simpleMatch(defEnd->previous(), "&");
});
}
bool Function::returnsPointer(const Function* function, bool unknown)
{
return checkReturns(function, unknown, false, [](const Token* /*defStart*/, const Token* defEnd) {
return Token::simpleMatch(defEnd->previous(), "*");
});
}
bool Function::returnsStandardType(const Function* function, bool unknown)
{
return checkReturns(function, unknown, true, [](const Token* /*defStart*/, const Token* defEnd) {
return defEnd->previous() && defEnd->previous()->isStandardType();
});
}
bool Function::returnsVoid(const Function* function, bool unknown)
{
return checkReturns(function, unknown, true, [](const Token* /*defStart*/, const Token* defEnd) {
return Token::simpleMatch(defEnd->previous(), "void");
});
}
std::vector<const Token*> Function::findReturns(const Function* f)
{
std::vector<const Token*> result;
if (!f)
return result;
const Scope* scope = f->functionScope;
if (!scope)
return result;
if (!scope->bodyStart)
return result;
for (const Token* tok = scope->bodyStart->next(); tok && tok != scope->bodyEnd; tok = tok->next()) {
if (tok->str() == "{" && tok->scope() &&
(tok->scope()->type == Scope::eLambda || tok->scope()->type == Scope::eClass)) {
tok = tok->link();
continue;
}
if (Token::simpleMatch(tok->astParent(), "return")) {
result.push_back(tok);
}
// Skip lambda functions since the scope may not be set correctly
const Token* lambdaEndToken = findLambdaEndToken(tok);
if (lambdaEndToken) {
tok = lambdaEndToken;
}
}
return result;
}
const Token * Function::constructorMemberInitialization() const
{
if (!isConstructor() || !arg)
return nullptr;
if (Token::simpleMatch(arg->link(), ") :"))
return arg->link()->next();
if (Token::simpleMatch(arg->link(), ") noexcept (") && arg->link()->linkAt(2)->strAt(1) == ":")
return arg->link()->linkAt(2)->next();
return nullptr;
}
bool Function::isSafe(const Settings &settings) const
{
if (settings.safeChecks.externalFunctions) {
if (nestedIn->type == Scope::ScopeType::eNamespace && token->fileIndex() != 0)
return true;
if (nestedIn->type == Scope::ScopeType::eGlobal && (token->fileIndex() != 0 || !isStatic()))
return true;
}
if (settings.safeChecks.internalFunctions) {
if (nestedIn->type == Scope::ScopeType::eNamespace && token->fileIndex() == 0)
return true;
if (nestedIn->type == Scope::ScopeType::eGlobal && (token->fileIndex() == 0 || isStatic()))
return true;
}
if (settings.safeChecks.classes && access == AccessControl::Public && (nestedIn->type == Scope::ScopeType::eClass || nestedIn->type == Scope::ScopeType::eStruct))
return true;
return false;
}
Function* SymbolDatabase::addGlobalFunction(Scope*& scope, const Token*& tok, const Token *argStart, const Token* funcStart)
{
Function* function = nullptr;
// Lambda functions are always unique
if (tok->str() != "[") {
auto range = scope->functionMap.equal_range(tok->str());
for (std::multimap<std::string, const Function*>::const_iterator it = range.first; it != range.second; ++it) {
const Function *f = it->second;
if (f->hasBody())
continue;
if (f->argsMatch(scope, f->argDef, argStart, emptyString, 0)) {
function = const_cast<Function *>(it->second);
break;
}
}
}
if (!function)
function = addGlobalFunctionDecl(scope, tok, argStart, funcStart);
function->arg = argStart;
function->token = funcStart;
function->hasBody(true);
addNewFunction(scope, tok);
if (scope) {
scope->function = function;
function->functionScope = scope;
return function;
}
return nullptr;
}
Function* SymbolDatabase::addGlobalFunctionDecl(Scope*& scope, const Token *tok, const Token *argStart, const Token* funcStart)
{
Function function(tok, scope, funcStart, argStart);
scope->addFunction(std::move(function));
return &scope->functionList.back();
}
void SymbolDatabase::addClassFunction(Scope *&scope, const Token *&tok, const Token *argStart)
{
const bool destructor(tok->strAt(-1) == "~");
const bool has_const(argStart->link()->strAt(1) == "const");
const bool lval(argStart->link()->strAt(has_const ? 2 : 1) == "&");
const bool rval(argStart->link()->strAt(has_const ? 2 : 1) == "&&");
int count = 0;
std::string path;
unsigned int path_length = 0;
const Token *tok1 = tok;
if (destructor)
tok1 = tok1->previous();
// back up to head of path
while (tok1 && tok1->previous() && tok1->strAt(-1) == "::" && tok1->tokAt(-2) &&
((tok1->tokAt(-2)->isName() && !tok1->tokAt(-2)->isStandardType()) ||
(tok1->strAt(-2) == ">" && tok1->linkAt(-2) && Token::Match(tok1->linkAt(-2)->previous(), "%name%")))) {
count++;
const Token * tok2 = tok1->tokAt(-2);
if (tok2->str() == ">")
tok2 = tok2->link()->previous();
if (tok2) {
do {
path = tok1->strAt(-1) + " " + path;
tok1 = tok1->previous();
path_length++;
} while (tok1 != tok2);
} else
return; // syntax error ?
}
// syntax error?
if (!tok1)
return;
// add global namespace if present
if (tok1->strAt(-1) == "::") {
path_length++;
path.insert(0, ":: ");
}
// search for match
for (std::list<Scope>::iterator it1 = scopeList.begin(); it1 != scopeList.end(); ++it1) {
Scope *scope1 = &(*it1);
bool match = false;
// check in namespace if using found
if (scope == scope1 && !scope1->usingList.empty()) {
std::vector<Scope::UsingInfo>::const_iterator it2;
for (it2 = scope1->usingList.cbegin(); it2 != scope1->usingList.cend(); ++it2) {
if (it2->scope) {
Function * func = findFunctionInScope(tok1, it2->scope, path, path_length);
if (func) {
if (!func->hasBody()) {
const Token *closeParen = tok->linkAt(1);
if (closeParen) {
const Token *eq = Tokenizer::isFunctionHead(closeParen, ";");
if (eq && Token::simpleMatch(eq->tokAt(-2), "= default ;")) {
func->isDefault(true);
return;
}
}
func->hasBody(true);
func->token = tok;
func->arg = argStart;
addNewFunction(scope, tok);
if (scope) {
scope->functionOf = func->nestedIn;
scope->function = func;
scope->function->functionScope = scope;
}
return;
}
}
}
}
}
const bool isAnonymousNamespace = (scope1->type == Scope::eNamespace && scope1->className.empty());
if ((scope1->className == tok1->str() && (scope1->type != Scope::eFunction)) || isAnonymousNamespace) {
// do the scopes match (same scope) or do their names match (multiple namespaces)
if ((scope == scope1->nestedIn) || (scope &&
scope->className == scope1->nestedIn->className &&
!scope->className.empty() &&
scope->type == scope1->nestedIn->type)) {
// nested scopes => check that they match
{
const Scope *s1 = scope;
const Scope *s2 = scope1->nestedIn;
while (s1 && s2) {
if (s1->className != s2->className)
break;
s1 = s1->nestedIn;
s2 = s2->nestedIn;
}
// Not matching scopes
if (s1 || s2)
continue;
}
Scope *scope2 = scope1;
while (scope2 && count > 1) {
count--;
if (tok1->strAt(1) == "<")
tok1 = tok1->linkAt(1)->tokAt(2);
else
tok1 = tok1->tokAt(2);
scope2 = scope2->findRecordInNestedList(tok1->str());
}
if (scope2 && isAnonymousNamespace)
scope2 = scope2->findRecordInNestedList(tok1->str());
if (count == 1 && scope2) {
match = true;
scope1 = scope2;
}
}
}
if (match) {
auto range = scope1->functionMap.equal_range(tok->str());
for (std::multimap<std::string, const Function*>::const_iterator it = range.first; it != range.second; ++it) {
auto * func = const_cast<Function *>(it->second);
if (destructor && func->type != Function::Type::eDestructor)
continue;
if (!func->hasBody()) {
if (func->argsMatch(scope1, func->argDef, tok->next(), path, path_length)) {
const Token *closeParen = tok->linkAt(1);
if (closeParen) {
const Token *eq = Tokenizer::isFunctionHead(closeParen, ";");
if (eq && Token::simpleMatch(eq->tokAt(-2), "= default ;")) {
func->isDefault(true);
return;
}
if (func->type == Function::eDestructor && destructor) {
func->hasBody(true);
} else if (func->type != Function::eDestructor && !destructor) {
// normal function?
const bool hasConstKeyword = closeParen->strAt(1) == "const";
if ((func->isConst() == hasConstKeyword) &&
(func->hasLvalRefQualifier() == lval) &&
(func->hasRvalRefQualifier() == rval)) {
func->hasBody(true);
}
}
}
if (func->hasBody()) {
func->token = tok;
func->arg = argStart;
addNewFunction(scope, tok);
if (scope) {
scope->functionOf = scope1;
scope->function = func;
scope->function->functionScope = scope;
}
return;
}
}
}
}
}
}
// class function of unknown class
addNewFunction(scope, tok);
}
void SymbolDatabase::addNewFunction(Scope *&scope, const Token *&tok)
{
const Token *tok1 = tok;
scopeList.emplace_back(this, tok1, scope);
Scope *newScope = &scopeList.back();
// find start of function '{'
bool foundInitList = false;
while (tok1 && tok1->str() != "{" && tok1->str() != ";") {
if (tok1->link() && Token::Match(tok1, "(|[|<")) {
tok1 = tok1->link();
} else if (foundInitList && Token::Match(tok1, "%name%|> {") && Token::Match(tok1->linkAt(1), "} ,|{")) {
tok1 = tok1->linkAt(1);
} else {
if (tok1->str() == ":")
foundInitList = true;
tok1 = tok1->next();
}
}
if (tok1 && tok1->str() == "{") {
newScope->setBodyStartEnd(tok1);
// syntax error?
if (!newScope->bodyEnd) {
mTokenizer.unmatchedToken(tok1);
} else {
scope->nestedList.push_back(newScope);
scope = newScope;
}
} else if (tok1 && Token::Match(tok1->tokAt(-2), "= default|delete ;")) {
scopeList.pop_back();
} else {
throw InternalError(tok, "Analysis failed (function not recognized). If the code is valid then please report this failure.");
}
tok = tok1;
}
bool Type::isClassType() const
{
return classScope && classScope->type == Scope::ScopeType::eClass;
}
bool Type::isEnumType() const
{
//We explicitly check for "enum" because a forward declared enum doesn't get its own scope
return (classDef && classDef->str() == "enum") ||
(classScope && classScope->type == Scope::ScopeType::eEnum);
}
bool Type::isStructType() const
{
return classScope && classScope->type == Scope::ScopeType::eStruct;
}
bool Type::isUnionType() const
{
return classScope && classScope->type == Scope::ScopeType::eUnion;
}
const Token *Type::initBaseInfo(const Token *tok, const Token *tok1)
{
// goto initial '{'
const Token *tok2 = tok1;
while (tok2 && tok2->str() != "{") {
// skip unsupported templates
if (tok2->str() == "<")
tok2 = tok2->link();
// check for base classes
else if (Token::Match(tok2, ":|,")) {
tok2 = tok2->next();
// check for invalid code
if (!tok2 || !tok2->next())
return nullptr;
Type::BaseInfo base;
if (tok2->str() == "virtual") {
base.isVirtual = true;
tok2 = tok2->next();
}
if (tok2->str() == "public") {
base.access = AccessControl::Public;
tok2 = tok2->next();
} else if (tok2->str() == "protected") {
base.access = AccessControl::Protected;
tok2 = tok2->next();
} else if (tok2->str() == "private") {
base.access = AccessControl::Private;
tok2 = tok2->next();
} else {
if (tok->str() == "class")
base.access = AccessControl::Private;
else if (tok->str() == "struct")
base.access = AccessControl::Public;
}
if (!tok2)
return nullptr;
if (tok2->str() == "virtual") {
base.isVirtual = true;
tok2 = tok2->next();
}
if (!tok2)
return nullptr;
base.nameTok = tok2;
// handle global namespace
if (tok2->str() == "::") {
tok2 = tok2->next();
}
// handle derived base classes
while (Token::Match(tok2, "%name% ::")) {
tok2 = tok2->tokAt(2);
}
if (!tok2)
return nullptr;
base.name = tok2->str();
tok2 = tok2->next();
// add unhandled templates
if (tok2 && tok2->link() && tok2->str() == "<") {
for (const Token* const end = tok2->link()->next(); tok2 != end; tok2 = tok2->next()) {
base.name += tok2->str();
}
}
const Type * baseType = classScope->check->findType(base.nameTok, enclosingScope);
if (baseType && !baseType->findDependency(this))
base.type = baseType;
// save pattern for base class name
derivedFrom.push_back(std::move(base));
} else
tok2 = tok2->next();
}
return tok2;
}
std::string Type::name() const
{
const Token* start = classDef->next();
if (classScope && classScope->enumClass && isEnumType())
start = start->tokAt(1);
else if (start->str() == "class")
start = start->tokAt(1);
else if (!start->isName())
return emptyString;
const Token* next = start;
while (Token::Match(next, "::|<|>|(|)|[|]|*|&|&&|%name%")) {
if (Token::Match(next, "<|(|[") && next->link())
next = next->link();
next = next->next();
}
std::string result;
for (const Token* tok = start; tok != next; tok = tok->next()) {
if (!result.empty())
result += ' ';
result += tok->str();
}
return result;
}
void SymbolDatabase::debugMessage(const Token *tok, const std::string &type, const std::string &msg) const
{
if (tok && mSettings.debugwarnings) {
const std::list<const Token*> locationList(1, tok);
const ErrorMessage errmsg(locationList, &mTokenizer.list,
Severity::debug,
type,
msg,
Certainty::normal);
mErrorLogger.reportErr(errmsg);
}
}
void SymbolDatabase::returnImplicitIntError(const Token *tok) const
{
if (tok && mSettings.severity.isEnabled(Severity::portability) && (tok->isC() && mSettings.standards.c != Standards::C89)) {
const std::list<const Token*> locationList(1, tok);
const ErrorMessage errmsg(locationList, &mTokenizer.list,
Severity::portability,
"returnImplicitInt",
"Omitted return type of function '" + tok->str() + "' defaults to int, this is not supported by ISO C99 and later standards.",
Certainty::normal);
mErrorLogger.reportErr(errmsg);
}
}
const Function* Type::getFunction(const std::string& funcName) const
{
if (classScope) {
const std::multimap<std::string, const Function *>::const_iterator it = classScope->functionMap.find(funcName);
if (it != classScope->functionMap.end())
return it->second;
}
for (const Type::BaseInfo & i : derivedFrom) {
if (i.type) {
const Function* const func = i.type->getFunction(funcName);
if (func)
return func;
}
}
return nullptr;
}
bool Type::hasCircularDependencies(std::set<BaseInfo>* ancestors) const
{
std::set<BaseInfo> knownAncestors;
if (!ancestors) {
ancestors=&knownAncestors;
}
for (auto parent=derivedFrom.cbegin(); parent!=derivedFrom.cend(); ++parent) {
if (!parent->type)
continue;
if (this==parent->type)
return true;
if (ancestors->find(*parent)!=ancestors->end())
return true;
ancestors->insert(*parent);
if (parent->type->hasCircularDependencies(ancestors))
return true;
}
return false;
}
bool Type::findDependency(const Type* ancestor) const
{
return this == ancestor || std::any_of(derivedFrom.cbegin(), derivedFrom.cend(), [&](const BaseInfo& d) {
return d.type && (d.type == this || d.type->findDependency(ancestor));
});
}
bool Type::isDerivedFrom(const std::string & ancestor) const
{
for (std::vector<BaseInfo>::const_iterator parent=derivedFrom.cbegin(); parent!=derivedFrom.cend(); ++parent) {
if (parent->name == ancestor)
return true;
if (parent->type && parent->type->isDerivedFrom(ancestor))
return true;
}
return false;
}
bool Variable::arrayDimensions(const Settings& settings, bool& isContainer)
{
isContainer = false;
const Library::Container* container = (mTypeStartToken && mTypeStartToken->isCpp()) ? settings.library.detectContainer(mTypeStartToken) : nullptr;
if (container && container->arrayLike_indexOp && container->size_templateArgNo > 0) {
const Token* tok = Token::findsimplematch(mTypeStartToken, "<");
if (tok) {
isContainer = true;
Dimension dimension_;
tok = tok->next();
for (int i = 0; i < container->size_templateArgNo && tok; i++) {
tok = tok->nextTemplateArgument();
}
if (Token::Match(tok, "%num% [,>]")) {
dimension_.tok = tok;
dimension_.known = true;
dimension_.num = MathLib::toBigNumber(tok->str());
} else if (tok) {
dimension_.tok = tok;
dimension_.known = false;
}
mDimensions.push_back(dimension_);
return true;
}
}
const Token *dim = mNameToken;
if (!dim) {
// Argument without name
dim = mTypeEndToken;
// back up to start of array dimensions
while (dim && dim->str() == "]")
dim = dim->link()->previous();
}
if (dim)
dim = dim->next();
if (dim && dim->str() == ")")
dim = dim->next();
bool arr = false;
while (dim && dim->next() && dim->str() == "[") {
Dimension dimension_;
dimension_.known = false;
// check for empty array dimension []
if (dim->strAt(1) != "]") {
dimension_.tok = dim->astOperand2();
// TODO: only perform when ValueFlow is enabled
// TODO: collect timing information for this call?
ValueFlow::valueFlowConstantFoldAST(const_cast<Token *>(dimension_.tok), settings);
if (dimension_.tok && dimension_.tok->hasKnownIntValue()) {
dimension_.num = dimension_.tok->getKnownIntValue();
dimension_.known = true;
}
}
mDimensions.push_back(dimension_);
dim = dim->link()->next();
arr = true;
}
return arr;
}
static std::string scopeTypeToString(Scope::ScopeType type)
{
switch (type) {
case Scope::ScopeType::eGlobal:
return "Global";
case Scope::ScopeType::eClass:
return "Class";
case Scope::ScopeType::eStruct:
return "Struct";
case Scope::ScopeType::eUnion:
return "Union";
case Scope::ScopeType::eNamespace:
return "Namespace";
case Scope::ScopeType::eFunction:
return "Function";
case Scope::ScopeType::eIf:
return "If";
case Scope::ScopeType::eElse:
return "Else";
case Scope::ScopeType::eFor:
return "For";
case Scope::ScopeType::eWhile:
return "While";
case Scope::ScopeType::eDo:
return "Do";
case Scope::ScopeType::eSwitch:
return "Switch";
case Scope::ScopeType::eTry:
return "Try";
case Scope::ScopeType::eCatch:
return "Catch";
case Scope::ScopeType::eUnconditional:
return "Unconditional";
case Scope::ScopeType::eLambda:
return "Lambda";
case Scope::ScopeType::eEnum:
return "Enum";
}
return "Unknown";
}
static std::ostream & operator << (std::ostream & s, Scope::ScopeType type)
{
s << scopeTypeToString(type);
return s;
}
static std::string accessControlToString(AccessControl access)
{
switch (access) {
case AccessControl::Public:
return "Public";
case AccessControl::Protected:
return "Protected";
case AccessControl::Private:
return "Private";
case AccessControl::Global:
return "Global";
case AccessControl::Namespace:
return "Namespace";
case AccessControl::Argument:
return "Argument";
case AccessControl::Local:
return "Local";
case AccessControl::Throw:
return "Throw";
}
return "Unknown";
}
static const char* functionTypeToString(Function::Type type)
{
switch (type) {
case Function::eConstructor:
return "Constructor";
case Function::eCopyConstructor:
return "CopyConstructor";
case Function::eMoveConstructor:
return "MoveConstructor";
case Function::eOperatorEqual:
return "OperatorEqual";
case Function::eDestructor:
return "Destructor";
case Function::eFunction:
return "Function";
case Function::eLambda:
return "Lambda";
default:
return "Unknown";
}
}
static std::string tokenToString(const Token* tok, const Tokenizer& tokenizer)
{
std::ostringstream oss;
if (tok) {
oss << tok->str() << " ";
oss << tokenizer.list.fileLine(tok) << " ";
}
oss << tok;
return oss.str();
}
static std::string scopeToString(const Scope* scope, const Tokenizer& tokenizer)
{
std::ostringstream oss;
if (scope) {
oss << scope->type << " ";
if (!scope->className.empty())
oss << scope->className << " ";
if (scope->classDef)
oss << tokenizer.list.fileLine(scope->classDef) << " ";
}
oss << scope;
return oss.str();
}
static std::string tokenType(const Token * tok)
{
std::ostringstream oss;
if (tok) {
if (tok->isUnsigned())
oss << "unsigned ";
else if (tok->isSigned())
oss << "signed ";
if (tok->isComplex())
oss << "_Complex ";
if (tok->isLong())
oss << "long ";
oss << tok->str();
}
return oss.str();
}
void SymbolDatabase::printVariable(const Variable *var, const char *indent) const
{
std::cout << indent << "mNameToken: " << tokenToString(var->nameToken(), mTokenizer) << std::endl;
if (var->nameToken()) {
std::cout << indent << " declarationId: " << var->declarationId() << std::endl;
}
std::cout << indent << "mTypeStartToken: " << tokenToString(var->typeStartToken(), mTokenizer) << std::endl;
std::cout << indent << "mTypeEndToken: " << tokenToString(var->typeEndToken(), mTokenizer) << std::endl;
if (var->typeStartToken()) {
const Token * autoTok = nullptr;
std::cout << indent << " ";
for (const Token * tok = var->typeStartToken(); tok != var->typeEndToken()->next(); tok = tok->next()) {
std::cout << " " << tokenType(tok);
if (tok->str() == "auto")
autoTok = tok;
}
std::cout << std::endl;
if (autoTok) {
const ValueType * valueType = autoTok->valueType();
std::cout << indent << " auto valueType: " << valueType << std::endl;
if (var->typeStartToken()->valueType()) {
std::cout << indent << " " << valueType->str() << std::endl;
}
}
} else if (var->valueType()) {
std::cout << indent << " " << var->valueType()->str() << std::endl;
}
std::cout << indent << "mIndex: " << var->index() << std::endl;
std::cout << indent << "mAccess: " << accessControlToString(var->accessControl()) << std::endl;
std::cout << indent << "mFlags: " << std::endl;
std::cout << indent << " isMutable: " << var->isMutable() << std::endl;
std::cout << indent << " isStatic: " << var->isStatic() << std::endl;
std::cout << indent << " isExtern: " << var->isExtern() << std::endl;
std::cout << indent << " isLocal: " << var->isLocal() << std::endl;
std::cout << indent << " isConst: " << var->isConst() << std::endl;
std::cout << indent << " isClass: " << var->isClass() << std::endl;
std::cout << indent << " isArray: " << var->isArray() << std::endl;
std::cout << indent << " isPointer: " << var->isPointer() << std::endl;
std::cout << indent << " isReference: " << var->isReference() << std::endl;
std::cout << indent << " isRValueRef: " << var->isRValueReference() << std::endl;
std::cout << indent << " hasDefault: " << var->hasDefault() << std::endl;
std::cout << indent << " isStlType: " << var->isStlType() << std::endl;
std::cout << indent << "mType: ";
if (var->type()) {
std::cout << var->type()->type() << " " << var->type()->name();
std::cout << " " << mTokenizer.list.fileLine(var->type()->classDef);
std::cout << " " << var->type() << std::endl;
} else
std::cout << "none" << std::endl;
if (var->nameToken()) {
const ValueType * valueType = var->nameToken()->valueType();
std::cout << indent << "valueType: " << valueType << std::endl;
if (valueType) {
std::cout << indent << " " << valueType->str() << std::endl;
}
}
std::cout << indent << "mScope: " << scopeToString(var->scope(), mTokenizer) << std::endl;
std::cout << indent << "mDimensions:";
for (std::size_t i = 0; i < var->dimensions().size(); i++) {
std::cout << " " << var->dimension(i);
if (!var->dimensions()[i].known)
std::cout << "?";
}
std::cout << std::endl;
}
void SymbolDatabase::printOut(const char *title) const
{
std::cout << std::setiosflags(std::ios::boolalpha);
if (title)
std::cout << "\n### " << title << " ###\n";
for (std::list<Scope>::const_iterator scope = scopeList.cbegin(); scope != scopeList.cend(); ++scope) {
std::cout << "Scope: " << &*scope << " " << scope->type << std::endl;
std::cout << " className: " << scope->className << std::endl;
std::cout << " classDef: " << tokenToString(scope->classDef, mTokenizer) << std::endl;
std::cout << " bodyStart: " << tokenToString(scope->bodyStart, mTokenizer) << std::endl;
std::cout << " bodyEnd: " << tokenToString(scope->bodyEnd, mTokenizer) << std::endl;
// find the function body if not implemented inline
for (auto func = scope->functionList.cbegin(); func != scope->functionList.cend(); ++func) {
std::cout << " Function: " << &*func << std::endl;
std::cout << " name: " << tokenToString(func->tokenDef, mTokenizer) << std::endl;
std::cout << " type: " << functionTypeToString(func->type) << std::endl;
std::cout << " access: " << accessControlToString(func->access) << std::endl;
std::cout << " hasBody: " << func->hasBody() << std::endl;
std::cout << " isInline: " << func->isInline() << std::endl;
std::cout << " isConst: " << func->isConst() << std::endl;
std::cout << " hasVirtualSpecifier: " << func->hasVirtualSpecifier() << std::endl;
std::cout << " isPure: " << func->isPure() << std::endl;
std::cout << " isStatic: " << func->isStatic() << std::endl;
std::cout << " isStaticLocal: " << func->isStaticLocal() << std::endl;
std::cout << " isExtern: " << func->isExtern() << std::endl;
std::cout << " isFriend: " << func->isFriend() << std::endl;
std::cout << " isExplicit: " << func->isExplicit() << std::endl;
std::cout << " isDefault: " << func->isDefault() << std::endl;
std::cout << " isDelete: " << func->isDelete() << std::endl;
std::cout << " hasOverrideSpecifier: " << func->hasOverrideSpecifier() << std::endl;
std::cout << " hasFinalSpecifier: " << func->hasFinalSpecifier() << std::endl;
std::cout << " isNoExcept: " << func->isNoExcept() << std::endl;
std::cout << " isThrow: " << func->isThrow() << std::endl;
std::cout << " isOperator: " << func->isOperator() << std::endl;
std::cout << " hasLvalRefQual: " << func->hasLvalRefQualifier() << std::endl;
std::cout << " hasRvalRefQual: " << func->hasRvalRefQualifier() << std::endl;
std::cout << " isVariadic: " << func->isVariadic() << std::endl;
std::cout << " isVolatile: " << func->isVolatile() << std::endl;
std::cout << " hasTrailingReturnType: " << func->hasTrailingReturnType() << std::endl;
std::cout << " attributes:";
if (func->isAttributeConst())
std::cout << " const ";
if (func->isAttributePure())
std::cout << " pure ";
if (func->isAttributeNoreturn())
std::cout << " noreturn ";
if (func->isAttributeNothrow())
std::cout << " nothrow ";
if (func->isAttributeConstructor())
std::cout << " constructor ";
if (func->isAttributeDestructor())
std::cout << " destructor ";
if (func->isAttributeNodiscard())
std::cout << " nodiscard ";
std::cout << std::endl;
std::cout << " noexceptArg: " << (func->noexceptArg ? func->noexceptArg->str() : "none") << std::endl;
std::cout << " throwArg: " << (func->throwArg ? func->throwArg->str() : "none") << std::endl;
std::cout << " tokenDef: " << tokenToString(func->tokenDef, mTokenizer) << std::endl;
std::cout << " argDef: " << tokenToString(func->argDef, mTokenizer) << std::endl;
if (!func->isConstructor() && !func->isDestructor())
std::cout << " retDef: " << tokenToString(func->retDef, mTokenizer) << std::endl;
if (func->retDef) {
std::cout << " ";
for (const Token * tok = func->retDef; tok && tok != func->tokenDef && !Token::Match(tok, "{|;|override|final"); tok = tok->next())
std::cout << " " << tokenType(tok);
std::cout << std::endl;
}
std::cout << " retType: " << func->retType << std::endl;
if (const ValueType* valueType = func->tokenDef->next()->valueType()) {
std::cout << " valueType: " << valueType << std::endl;
std::cout << " " << valueType->str() << std::endl;
}
if (func->hasBody()) {
std::cout << " token: " << tokenToString(func->token, mTokenizer) << std::endl;
std::cout << " arg: " << tokenToString(func->arg, mTokenizer) << std::endl;
}
std::cout << " nestedIn: " << scopeToString(func->nestedIn, mTokenizer) << std::endl;
std::cout << " functionScope: " << scopeToString(func->functionScope, mTokenizer) << std::endl;
for (auto var = func->argumentList.cbegin(); var != func->argumentList.cend(); ++var) {
std::cout << " Variable: " << &*var << std::endl;
printVariable(&*var, " ");
}
}
for (auto var = scope->varlist.cbegin(); var != scope->varlist.cend(); ++var) {
std::cout << " Variable: " << &*var << std::endl;
printVariable(&*var, " ");
}
if (scope->type == Scope::eEnum) {
std::cout << " enumType: ";
if (scope->enumType) {
std::cout << scope->enumType->stringify(false, true, false);
} else
std::cout << "int";
std::cout << std::endl;
std::cout << " enumClass: " << scope->enumClass << std::endl;
for (const Enumerator &enumerator : scope->enumeratorList) {
std::cout << " Enumerator: " << enumerator.name->str() << " = ";
if (enumerator.value_known)
std::cout << enumerator.value;
if (enumerator.start) {
const Token * tok = enumerator.start;
std::cout << (enumerator.value_known ? " " : "") << "[" << tok->str();
while (tok && tok != enumerator.end) {
if (tok->next())
std::cout << " " << tok->strAt(1);
tok = tok->next();
}
std::cout << "]";
}
std::cout << std::endl;
}
}
std::cout << " nestedIn: " << scope->nestedIn;
if (scope->nestedIn) {
std::cout << " " << scope->nestedIn->type << " "
<< scope->nestedIn->className;
}
std::cout << std::endl;
std::cout << " definedType: " << scope->definedType << std::endl;
std::cout << " nestedList[" << scope->nestedList.size() << "] = (";
std::size_t count = scope->nestedList.size();
for (std::vector<Scope*>::const_iterator nsi = scope->nestedList.cbegin(); nsi != scope->nestedList.cend(); ++nsi) {
std::cout << " " << (*nsi) << " " << (*nsi)->type << " " << (*nsi)->className;
if (count-- > 1)
std::cout << ",";
}
std::cout << " )" << std::endl;
for (auto use = scope->usingList.cbegin(); use != scope->usingList.cend(); ++use) {
std::cout << " using: " << use->scope << " " << use->start->strAt(2);
const Token *tok1 = use->start->tokAt(3);
while (tok1 && tok1->str() == "::") {
std::cout << "::" << tok1->strAt(1);
tok1 = tok1->tokAt(2);
}
std::cout << " " << mTokenizer.list.fileLine(use->start) << std::endl;
}
std::cout << " functionOf: " << scopeToString(scope->functionOf, mTokenizer) << std::endl;
std::cout << " function: " << scope->function;
if (scope->function)
std::cout << " " << scope->function->name();
std::cout << std::endl;
}
for (std::list<Type>::const_iterator type = typeList.cbegin(); type != typeList.cend(); ++type) {
std::cout << "Type: " << &(*type) << std::endl;
std::cout << " name: " << type->name() << std::endl;
std::cout << " classDef: " << tokenToString(type->classDef, mTokenizer) << std::endl;
std::cout << " classScope: " << type->classScope << std::endl;
std::cout << " enclosingScope: " << type->enclosingScope;
if (type->enclosingScope) {
std::cout << " " << type->enclosingScope->type << " "
<< type->enclosingScope->className;
}
std::cout << std::endl;
std::cout << " needInitialization: " << (type->needInitialization == Type::NeedInitialization::Unknown ? "Unknown" :
type->needInitialization == Type::NeedInitialization::True ? "True" :
type->needInitialization == Type::NeedInitialization::False ? "False" :
"Invalid") << std::endl;
std::cout << " derivedFrom[" << type->derivedFrom.size() << "] = (";
std::size_t count = type->derivedFrom.size();
for (const Type::BaseInfo & i : type->derivedFrom) {
if (i.isVirtual)
std::cout << "Virtual ";
std::cout << (i.access == AccessControl::Public ? " Public" :
i.access == AccessControl::Protected ? " Protected" :
i.access == AccessControl::Private ? " Private" :
" Unknown");
if (i.type)
std::cout << " " << i.type;
else
std::cout << " Unknown";
std::cout << " " << i.name;
if (count-- > 1)
std::cout << ",";
}
std::cout << " )" << std::endl;
std::cout << " friendList[" << type->friendList.size() << "] = (";
for (size_t i = 0; i < type->friendList.size(); i++) {
if (type->friendList[i].type)
std::cout << type->friendList[i].type;
else
std::cout << " Unknown";
std::cout << ' ';
if (type->friendList[i].nameEnd)
std::cout << type->friendList[i].nameEnd->str();
if (i+1 < type->friendList.size())
std::cout << ',';
}
std::cout << " )" << std::endl;
}
for (std::size_t i = 1; i < mVariableList.size(); i++) {
std::cout << "mVariableList[" << i << "]: " << mVariableList[i];
if (mVariableList[i]) {
std::cout << " " << mVariableList[i]->name() << " "
<< mTokenizer.list.fileLine(mVariableList[i]->nameToken());
}
std::cout << std::endl;
}
std::cout << std::resetiosflags(std::ios::boolalpha);
}
void SymbolDatabase::printXml(std::ostream &out) const
{
std::string outs;
std::set<const Variable *> variables;
// Scopes..
outs += " <scopes>\n";
for (std::list<Scope>::const_iterator scope = scopeList.cbegin(); scope != scopeList.cend(); ++scope) {
outs += " <scope";
outs += " id=\"";
outs += id_string(&*scope);
outs += "\"";
outs += " type=\"";
outs += scopeTypeToString(scope->type);
outs += "\"";
if (!scope->className.empty()) {
outs += " className=\"";
outs += ErrorLogger::toxml(scope->className);
outs += "\"";
}
if (scope->bodyStart) {
outs += " bodyStart=\"";
outs += id_string(scope->bodyStart);
outs += '\"';
}
if (scope->bodyEnd) {
outs += " bodyEnd=\"";
outs += id_string(scope->bodyEnd);
outs += '\"';
}
if (scope->nestedIn) {
outs += " nestedIn=\"";
outs += id_string(scope->nestedIn);
outs += "\"";
}
if (scope->function) {
outs += " function=\"";
outs += id_string(scope->function);
outs += "\"";
}
if (scope->definedType) {
outs += " definedType=\"";
outs += id_string(scope->definedType);
outs += "\"";
}
if (scope->functionList.empty() && scope->varlist.empty())
outs += "/>\n";
else {
outs += ">\n";
if (!scope->functionList.empty()) {
outs += " <functionList>\n";
for (std::list<Function>::const_iterator function = scope->functionList.cbegin(); function != scope->functionList.cend(); ++function) {
outs += " <function id=\"";
outs += id_string(&*function);
outs += "\" token=\"";
outs += id_string(function->token);
outs += "\" tokenDef=\"";
outs += id_string(function->tokenDef);
outs += "\" name=\"";
outs += ErrorLogger::toxml(function->name());
outs += '\"';
outs += " type=\"";
outs += functionTypeToString(function->type);
outs += '\"';
if (function->nestedIn->definedType) {
if (function->hasVirtualSpecifier())
outs += " hasVirtualSpecifier=\"true\"";
else if (function->isImplicitlyVirtual())
outs += " isImplicitlyVirtual=\"true\"";
}
if (function->access == AccessControl::Public || function->access == AccessControl::Protected || function->access == AccessControl::Private) {
outs += " access=\"";
outs += accessControlToString(function->access);
outs +="\"";
}
if (function->isOperator())
outs += " isOperator=\"true\"";
if (function->isExplicit())
outs += " isExplicit=\"true\"";
if (function->hasOverrideSpecifier())
outs += " hasOverrideSpecifier=\"true\"";
if (function->hasFinalSpecifier())
outs += " hasFinalSpecifier=\"true\"";
if (function->isInlineKeyword())
outs += " isInlineKeyword=\"true\"";
if (function->isStatic())
outs += " isStatic=\"true\"";
if (function->isAttributeNoreturn())
outs += " isAttributeNoreturn=\"true\"";
if (const Function* overriddenFunction = function->getOverriddenFunction()) {
outs += " overriddenFunction=\"";
outs += id_string(overriddenFunction);
outs += "\"";
}
if (function->isAttributeConst())
outs += " isAttributeConst=\"true\"";
if (function->isAttributePure())
outs += " isAttributePure=\"true\"";
if (function->argCount() == 0U)
outs += "/>\n";
else {
outs += ">\n";
for (unsigned int argnr = 0; argnr < function->argCount(); ++argnr) {
const Variable *arg = function->getArgumentVar(argnr);
outs += " <arg nr=\"";
outs += std::to_string(argnr+1);
outs += "\" variable=\"";
outs += id_string(arg);
outs += "\"/>\n";
variables.insert(arg);
}
outs += " </function>\n";
}
}
outs += " </functionList>\n";
}
if (!scope->varlist.empty()) {
outs += " <varlist>\n";
for (std::list<Variable>::const_iterator var = scope->varlist.cbegin(); var != scope->varlist.cend(); ++var) {
outs += " <var id=\"";
outs += id_string(&*var);
outs += "\"/>\n";
}
outs += " </varlist>\n";
}
outs += " </scope>\n";
}
}
outs += " </scopes>\n";
if (!typeList.empty()) {
outs += " <types>\n";
for (const Type& type:typeList) {
outs += " <type id=\"";
outs += id_string(&type);
outs += "\" classScope=\"";
outs += id_string(type.classScope);
outs += "\"";
if (type.derivedFrom.empty()) {
outs += "/>\n";
continue;
}
outs += ">\n";
for (const Type::BaseInfo& baseInfo: type.derivedFrom) {
outs += " <derivedFrom";
outs += " access=\"";
outs += accessControlToString(baseInfo.access);
outs += "\"";
outs += " type=\"";
outs += id_string(baseInfo.type);
outs += "\"";
outs += " isVirtual=\"";
outs += bool_to_string(baseInfo.isVirtual);
outs += "\"";
outs += " nameTok=\"";
outs += id_string(baseInfo.nameTok);
outs += "\"";
outs += "/>\n";
}
outs += " </type>\n";
}
outs += " </types>\n";
}
// Variables..
for (const Variable *var : mVariableList)
variables.insert(var);
outs += " <variables>\n";
for (const Variable *var : variables) {
if (!var)
continue;
outs += " <var id=\"";
outs += id_string(var);
outs += '\"';
outs += " nameToken=\"";
outs += id_string(var->nameToken());
outs += '\"';
outs += " typeStartToken=\"";
outs += id_string(var->typeStartToken());
outs += '\"';
outs += " typeEndToken=\"";
outs += id_string(var->typeEndToken());
outs += '\"';
outs += " access=\"";
outs += accessControlToString(var->mAccess);
outs += '\"';
outs += " scope=\"";
outs += id_string(var->scope());
outs += '\"';
if (var->valueType()) {
outs += " constness=\"";
outs += std::to_string(var->valueType()->constness);
outs += '\"';
outs += " volatileness=\"";
outs += std::to_string(var->valueType()->volatileness);
outs += '\"';
}
outs += " isArray=\"";
outs += bool_to_string(var->isArray());
outs += '\"';
outs += " isClass=\"";
outs += bool_to_string(var->isClass());
outs += '\"';
outs += " isConst=\"";
outs += bool_to_string(var->isConst());
outs += '\"';
outs += " isExtern=\"";
outs += bool_to_string(var->isExtern());
outs += '\"';
outs += " isPointer=\"";
outs += bool_to_string(var->isPointer());
outs += '\"';
outs += " isReference=\"";
outs += bool_to_string(var->isReference());
outs += '\"';
outs += " isStatic=\"";
outs += bool_to_string(var->isStatic());
outs += '\"';
outs += " isVolatile=\"";
outs += bool_to_string(var->isVolatile());
outs += '\"';
outs += "/>\n";
}
outs += " </variables>\n";
out << outs;
}
//---------------------------------------------------------------------------
static const Type* findVariableTypeIncludingUsedNamespaces(const SymbolDatabase* symbolDatabase, const Scope* scope, const Token* typeTok)
{
const Type* argType = symbolDatabase->findVariableType(scope, typeTok);
if (argType)
return argType;
// look for variable type in any using namespace in this scope or above
while (scope) {
for (const Scope::UsingInfo &ui : scope->usingList) {
if (ui.scope) {
argType = symbolDatabase->findVariableType(ui.scope, typeTok);
if (argType)
return argType;
}
}
scope = scope->nestedIn;
}
return nullptr;
}
//---------------------------------------------------------------------------
void Function::addArguments(const SymbolDatabase *symbolDatabase, const Scope *scope)
{
// check for non-empty argument list "( ... )"
const Token * start = arg ? arg : argDef;
if (!Token::simpleMatch(start, "("))
return;
if (!(start && start->link() != start->next() && !Token::simpleMatch(start, "( void )")))
return;
unsigned int count = 0;
for (const Token* tok = start->next(); tok; tok = tok->next()) {
if (Token::Match(tok, ",|)"))
return; // Syntax error
const Token* startTok = tok;
const Token* endTok = nullptr;
const Token* nameTok = nullptr;
do {
if (Token::simpleMatch(tok, "decltype (")) {
tok = tok->linkAt(1)->next();
continue;
}
if (tok != startTok && !nameTok && Token::Match(tok, "( & %var% ) [")) {
nameTok = tok->tokAt(2);
endTok = nameTok->previous();
tok = tok->link();
} else if (tok != startTok && !nameTok && Token::Match(tok, "( * %var% ) (") && Token::Match(tok->link()->linkAt(1), ") [,)]")) {
nameTok = tok->tokAt(2);
endTok = nameTok->previous();
tok = tok->link()->linkAt(1);
} else if (tok != startTok && !nameTok && Token::Match(tok, "( * %var% ) [")) {
nameTok = tok->tokAt(2);
endTok = nameTok->previous();
tok = tok->link();
} else if (tok->varId() != 0) {
nameTok = tok;
endTok = tok->previous();
} else if (tok->str() == "[") {
// skip array dimension(s)
tok = tok->link();
while (tok->strAt(1) == "[")
tok = tok->linkAt(1);
} else if (tok->str() == "<") {
tok = tok->link();
if (!tok) // something is wrong so just bail out
return;
}
tok = tok->next();
if (!tok) // something is wrong so just bail
return;
} while (tok->str() != "," && tok->str() != ")" && tok->str() != "=");
const Token *typeTok = startTok;
// skip over stuff to get to type
while (Token::Match(typeTok, "const|volatile|enum|struct|::"))
typeTok = typeTok->next();
if (Token::Match(typeTok, ",|)")) { // #8333
symbolDatabase->mTokenizer.syntaxError(typeTok);
}
if (Token::Match(typeTok, "%type% <") && Token::Match(typeTok->linkAt(1), "> :: %type%"))
typeTok = typeTok->linkAt(1)->tokAt(2);
// skip over qualification
while (Token::Match(typeTok, "%type% ::")) {
typeTok = typeTok->tokAt(2);
if (Token::Match(typeTok, "%type% <") && Token::Match(typeTok->linkAt(1), "> :: %type%"))
typeTok = typeTok->linkAt(1)->tokAt(2);
}
// check for argument with no name or missing varid
if (!endTok) {
if (tok->previous()->isName() && !Token::Match(tok->tokAt(-1), "const|volatile")) {
if (tok->previous() != typeTok) {
nameTok = tok->previous();
endTok = nameTok->previous();
if (hasBody())
symbolDatabase->debugMessage(nameTok, "varid0", "Function::addArguments found argument \'" + nameTok->str() + "\' with varid 0.");
} else
endTok = typeTok;
} else
endTok = tok->previous();
}
const ::Type *argType = nullptr;
if (!typeTok->isStandardType()) {
argType = findVariableTypeIncludingUsedNamespaces(symbolDatabase, scope, typeTok);
// save type
const_cast<Token *>(typeTok)->type(argType);
}
// skip default values
if (tok->str() == "=") {
do {
if (tok->link() && Token::Match(tok, "[{[(<]"))
tok = tok->link();
tok = tok->next();
} while (tok->str() != "," && tok->str() != ")");
}
// skip over stuff before type
while (Token::Match(startTok, "enum|struct|const|volatile"))
startTok = startTok->next();
if (startTok == nameTok)
break;
argumentList.emplace_back(nameTok, startTok, endTok, count++, AccessControl::Argument, argType, functionScope, symbolDatabase->mSettings);
if (tok->str() == ")") {
// check for a variadic function or a variadic template function
if (Token::simpleMatch(endTok, "..."))
isVariadic(true);
break;
}
}
// count default arguments
for (const Token* tok = argDef->next(); tok && tok != argDef->link(); tok = tok->next()) {
if (tok->str() == "=") {
initArgCount++;
if (tok->strAt(1) == "[") {
const Token* lambdaStart = tok->next();
if (type == eLambda)
tok = findLambdaEndTokenWithoutAST(lambdaStart);
else {
tok = findLambdaEndToken(lambdaStart);
if (!tok)
tok = findLambdaEndTokenWithoutAST(lambdaStart);
}
if (!tok)
throw InternalError(lambdaStart, "Analysis failed (lambda not recognized). If the code is valid then please report this failure.", InternalError::INTERNAL);
}
}
}
}
bool Function::isImplicitlyVirtual(bool defaultVal, bool* pFoundAllBaseClasses) const
{
if (hasVirtualSpecifier() || hasOverrideSpecifier() || hasFinalSpecifier())
return true;
bool foundAllBaseClasses = true;
if (getOverriddenFunction(&foundAllBaseClasses)) //If it overrides a base class's method then it's virtual
return true;
if (pFoundAllBaseClasses)
*pFoundAllBaseClasses = foundAllBaseClasses;
if (foundAllBaseClasses) //If we've seen all the base classes and none of the above were true then it must not be virtual
return false;
return defaultVal; //If we can't see all the bases classes then we can't say conclusively
}
std::vector<const Function*> Function::getOverloadedFunctions() const
{
std::vector<const Function*> result;
const Scope* scope = nestedIn;
while (scope) {
const bool isMemberFunction = scope->isClassOrStruct() && !isStatic();
for (std::multimap<std::string, const Function*>::const_iterator it = scope->functionMap.find(tokenDef->str());
it != scope->functionMap.end() && it->first == tokenDef->str();
++it) {
const Function* func = it->second;
if (isMemberFunction && isMemberFunction == func->isStatic())
continue;
result.push_back(func);
}
if (isMemberFunction)
break;
scope = scope->nestedIn;
}
return result;
}
const Function *Function::getOverriddenFunction(bool *foundAllBaseClasses) const
{
if (foundAllBaseClasses)
*foundAllBaseClasses = true;
if (!nestedIn->isClassOrStruct())
return nullptr;
return getOverriddenFunctionRecursive(nestedIn->definedType, foundAllBaseClasses);
}
// prevent recursion if base is the same except for different template parameters
static bool isDerivedFromItself(const std::string& thisName, const std::string& baseName)
{
if (thisName.back() != '>')
return false;
const auto pos = thisName.find('<');
if (pos == std::string::npos)
return false;
return thisName.compare(0, pos + 1, baseName, 0, pos + 1) == 0;
}
const Function * Function::getOverriddenFunctionRecursive(const ::Type* baseType, bool *foundAllBaseClasses) const
{
// check each base class
for (const ::Type::BaseInfo & i : baseType->derivedFrom) {
const ::Type* derivedFromType = i.type;
// check if base class exists in database
if (!derivedFromType || !derivedFromType->classScope) {
if (foundAllBaseClasses)
*foundAllBaseClasses = false;
continue;
}
const Scope *parent = derivedFromType->classScope;
// check if function defined in base class
auto range = parent->functionMap.equal_range(tokenDef->str());
for (std::multimap<std::string, const Function*>::const_iterator it = range.first; it != range.second; ++it) {
const Function * func = it->second;
if (func->isImplicitlyVirtual()) { // Base is virtual and of same name
const Token *temp1 = func->tokenDef->previous();
const Token *temp2 = tokenDef->previous();
bool match = true;
// check for matching return parameters
while (!Token::Match(temp1, "virtual|public:|private:|protected:|{|}|;")) {
if (temp1->str() != temp2->str() &&
!(temp1->type() && temp2->type() && temp2->type()->isDerivedFrom(temp1->type()->name()))) {
match = false;
break;
}
temp1 = temp1->previous();
temp2 = temp2->previous();
}
// check for matching function parameters
match = match && argsMatch(baseType->classScope, func->argDef, argDef, emptyString, 0);
// check for matching cv-ref qualifiers
match = match
&& isConst() == func->isConst()
&& isVolatile() == func->isVolatile()
&& hasRvalRefQualifier() == func->hasRvalRefQualifier()
&& hasLvalRefQualifier() == func->hasLvalRefQualifier();
// it's a match
if (match) {
return func;
}
}
}
if (isDestructor()) {
auto it = std::find_if(parent->functionList.begin(), parent->functionList.end(), [](const Function& f) {
return f.isDestructor() && f.isImplicitlyVirtual();
});
if (it != parent->functionList.end())
return &*it;
}
if (!derivedFromType->derivedFrom.empty() && !derivedFromType->hasCircularDependencies() && !isDerivedFromItself(baseType->classScope->className, i.name)) {
// avoid endless recursion, see #5289 Crash: Stack overflow in isImplicitlyVirtual_rec when checking SVN and
// #5590 with a loop within the class hierarchy.
const Function *func = getOverriddenFunctionRecursive(derivedFromType, foundAllBaseClasses);
if (func) {
return func;
}
}
}
return nullptr;
}
const Variable* Function::getArgumentVar(nonneg int num) const
{
if (num < argumentList.size()) {
auto it = argumentList.begin();
std::advance(it, num);
return &*it;
}
return nullptr;
}
//---------------------------------------------------------------------------
Scope::Scope(const SymbolDatabase *check_, const Token *classDef_, const Scope *nestedIn_, ScopeType type_, const Token *start_) :
check(check_),
classDef(classDef_),
nestedIn(nestedIn_),
type(type_)
{
setBodyStartEnd(start_);
}
Scope::Scope(const SymbolDatabase *check_, const Token *classDef_, const Scope *nestedIn_) :
check(check_),
classDef(classDef_),
nestedIn(nestedIn_)
{
const Token *nameTok = classDef;
if (!classDef) {
type = Scope::eGlobal;
} else if (classDef->str() == "class" && classDef->isCpp()) {
type = Scope::eClass;
nameTok = nameTok->next();
} else if (classDef->str() == "struct") {
type = Scope::eStruct;
nameTok = nameTok->next();
} else if (classDef->str() == "union") {
type = Scope::eUnion;
nameTok = nameTok->next();
} else if (classDef->str() == "namespace") {
type = Scope::eNamespace;
nameTok = nameTok->next();
} else if (classDef->str() == "enum") {
type = Scope::eEnum;
nameTok = nameTok->next();
if (nameTok->str() == "class") {
enumClass = true;
nameTok = nameTok->next();
}
} else if (classDef->str() == "[") {
type = Scope::eLambda;
} else {
type = Scope::eFunction;
}
// skip over qualification if present
nameTok = skipScopeIdentifiers(nameTok);
if (nameTok && ((type == Scope::eEnum && Token::Match(nameTok, ":|{")) || nameTok->str() != "{")) // anonymous and unnamed structs/unions don't have a name
className = nameTok->str();
}
AccessControl Scope::defaultAccess() const
{
switch (type) {
case eGlobal:
return AccessControl::Global;
case eClass:
return AccessControl::Private;
case eStruct:
return AccessControl::Public;
case eUnion:
return AccessControl::Public;
case eNamespace:
return AccessControl::Namespace;
default:
return AccessControl::Local;
}
}
void Scope::addVariable(const Token *token_, const Token *start_, const Token *end_,
AccessControl access_, const Type *type_, const Scope *scope_, const Settings& settings)
{
// keep possible size_t -> int truncation outside emplace_back() to have a single line
// C4267 VC++ warning instead of several dozens lines
const int varIndex = varlist.size();
varlist.emplace_back(token_, start_, end_, varIndex, access_, type_, scope_, settings);
}
// Get variable list..
void Scope::getVariableList(const Settings& settings)
{
if (!bodyStartList.empty()) {
for (const Token *bs: bodyStartList)
getVariableList(settings, bs->next(), bs->link());
}
// global scope
else if (type == Scope::eGlobal)
getVariableList(settings, check->mTokenizer.tokens(), nullptr);
// forward declaration
else
return;
}
void Scope::getVariableList(const Settings& settings, const Token* start, const Token* end)
{
// Variable declared in condition: if (auto x = bar())
if (Token::Match(classDef, "if|while ( %type%") && Token::simpleMatch(classDef->next()->astOperand2(), "=")) {
checkVariable(classDef->tokAt(2), defaultAccess(), settings);
}
AccessControl varaccess = defaultAccess();
for (const Token *tok = start; tok && tok != end; tok = tok->next()) {
// syntax error?
if (tok->next() == nullptr)
break;
// Is it a function?
if (tok->str() == "{") {
tok = tok->link();
continue;
}
// Is it a nested class or structure?
if (tok->isKeyword() && Token::Match(tok, "class|struct|union|namespace %type% :|{")) {
tok = tok->tokAt(2);
while (tok && tok->str() != "{")
tok = tok->next();
if (tok) {
// skip implementation
tok = tok->link();
continue;
}
break;
}
if (tok->isKeyword() && Token::Match(tok, "struct|union {")) {
if (Token::Match(tok->linkAt(1), "} %name% ;|[")) {
tok = tok->linkAt(1)->tokAt(2);
continue;
}
if (Token::simpleMatch(tok->linkAt(1), "} ;")) {
tok = tok->next();
continue;
}
}
// Borland C++: Skip all variables in the __published section.
// These are automatically initialized.
else if (tok->str() == "__published:") {
for (; tok; tok = tok->next()) {
if (tok->str() == "{")
tok = tok->link();
if (Token::Match(tok->next(), "private:|protected:|public:"))
break;
}
if (tok)
continue;
break;
}
// "private:" "public:" "protected:" etc
else if (tok->str() == "public:") {
varaccess = AccessControl::Public;
continue;
} else if (tok->str() == "protected:") {
varaccess = AccessControl::Protected;
continue;
} else if (tok->str() == "private:") {
varaccess = AccessControl::Private;
continue;
}
// Is it a forward declaration?
else if (tok->isKeyword() && Token::Match(tok, "class|struct|union %name% ;")) {
tok = tok->tokAt(2);
continue;
}
// Borland C++: Ignore properties..
else if (tok->str() == "__property")
continue;
// skip return, goto and delete
else if (tok->isKeyword() && Token::Match(tok, "return|delete|goto")) {
while (tok->next() &&
tok->strAt(1) != ";" &&
tok->strAt(1) != "}" /* ticket #4994 */) {
tok = tok->next();
}
continue;
}
// skip case/default
if (tok->isKeyword() && Token::Match(tok, "case|default")) {
while (tok->next() && !Token::Match(tok->next(), "[:;{}]"))
tok = tok->next();
continue;
}
// Search for start of statement..
if (tok->previous() && !Token::Match(tok->previous(), ";|{|}|public:|protected:|private:"))
continue;
if (tok->str() == ";")
continue;
tok = checkVariable(tok, varaccess, settings);
if (!tok)
break;
}
}
const Token *Scope::checkVariable(const Token *tok, AccessControl varaccess, const Settings& settings)
{
// Is it a throw..?
if (tok->isKeyword() && Token::Match(tok, "throw %any% (") &&
Token::simpleMatch(tok->linkAt(2), ") ;")) {
return tok->linkAt(2);
}
if (tok->isKeyword() && Token::Match(tok, "throw %any% :: %any% (") &&
Token::simpleMatch(tok->linkAt(4), ") ;")) {
return tok->linkAt(4);
}
// friend?
if (tok->isKeyword() && Token::Match(tok, "friend %type%") && tok->next()->varId() == 0) {
const Token *next = Token::findmatch(tok->tokAt(2), ";|{");
if (next && next->str() == "{")
next = next->link();
return next;
}
// skip const|volatile|static|mutable|extern
while (tok && tok->isKeyword() && Token::Match(tok, "const|constexpr|volatile|static|mutable|extern")) {
tok = tok->next();
}
// the start of the type tokens does not include the above modifiers
const Token *typestart = tok;
// C++17 structured bindings
if (tok && tok->isCpp() && (settings.standards.cpp >= Standards::CPP17) && Token::Match(tok, "auto &|&&| [")) {
const Token *typeend = Token::findsimplematch(typestart, "[")->previous();
for (tok = typeend->tokAt(2); Token::Match(tok, "%name%|,"); tok = tok->next()) {
if (tok->varId())
addVariable(tok, typestart, typeend, varaccess, nullptr, this, settings);
}
return typeend->linkAt(1);
}
while (tok && tok->isKeyword() && Token::Match(tok, "class|struct|union|enum")) {
tok = tok->next();
}
// This is the start of a statement
const Token *vartok = nullptr;
const Token *typetok = nullptr;
if (tok && isVariableDeclaration(tok, vartok, typetok)) {
// If the vartok was set in the if-blocks above, create a entry for this variable..
tok = vartok->next();
while (Token::Match(tok, "[|{"))
tok = tok->link()->next();
if (vartok->varId() == 0) {
if (!vartok->isBoolean())
check->debugMessage(vartok, "varid0", "Scope::checkVariable found variable \'" + vartok->str() + "\' with varid 0.");
return tok;
}
const Type *vType = nullptr;
if (typetok) {
vType = findVariableTypeIncludingUsedNamespaces(check, this, typetok);
const_cast<Token *>(typetok)->type(vType);
}
// skip "enum" or "struct"
if (Token::Match(typestart, "enum|struct"))
typestart = typestart->next();
addVariable(vartok, typestart, vartok->previous(), varaccess, vType, this, settings);
}
return tok;
}
const Variable *Scope::getVariable(const std::string &varname) const
{
auto it = std::find_if(varlist.begin(), varlist.end(), [&varname](const Variable& var) {
return var.name() == varname;
});
if (it != varlist.end())
return &*it;
if (definedType) {
for (const Type::BaseInfo& baseInfo: definedType->derivedFrom) {
if (baseInfo.type && baseInfo.type->classScope) {
if (const Variable* var = baseInfo.type->classScope->getVariable(varname))
return var;
}
}
}
return nullptr;
}
static const Token* skipPointers(const Token* tok)
{
while (Token::Match(tok, "*|&|&&") || (Token::Match(tok, "( [*&]") && Token::Match(tok->link()->next(), "(|["))) {
tok = tok->next();
if (tok && tok->strAt(-1) == "(" && Token::Match(tok, "%type% ::"))
tok = tok->tokAt(2);
}
if (Token::simpleMatch(tok, "( *") && Token::simpleMatch(tok->link()->previous(), "] ) ;") &&
(tok->tokAt(-1)->isStandardType() || tok->tokAt(-1)->isKeyword() || tok->strAt(-1) == "*")) {
const Token *tok2 = skipPointers(tok->next());
if (Token::Match(tok2, "%name% [") && Token::simpleMatch(tok2->linkAt(1), "] ) ;"))
return tok2;
}
return tok;
}
static const Token* skipPointersAndQualifiers(const Token* tok)
{
tok = skipPointers(tok);
while (Token::Match(tok, "const|static|volatile")) {
tok = tok->next();
tok = skipPointers(tok);
}
return tok;
}
bool Scope::isVariableDeclaration(const Token* const tok, const Token*& vartok, const Token*& typetok) const
{
if (!tok)
return false;
const bool isCPP = tok->isCpp();
if (isCPP && Token::Match(tok, "throw|new"))
return false;
const bool isCPP11 = isCPP && check->mSettings.standards.cpp >= Standards::CPP11;
if (isCPP11 && tok->str() == "using")
return false;
const Token* localTypeTok = skipScopeIdentifiers(tok);
const Token* localVarTok = nullptr;
while (Token::simpleMatch(localTypeTok, "alignas (") && Token::Match(localTypeTok->linkAt(1), ") %name%"))
localTypeTok = localTypeTok->linkAt(1)->next();
if (Token::Match(localTypeTok, "%type% <")) {
if (Token::Match(tok, "const_cast|dynamic_cast|reinterpret_cast|static_cast <"))
return false;
const Token* closeTok = localTypeTok->linkAt(1);
if (closeTok) {
localVarTok = skipPointers(closeTok->next());
if (Token::Match(localVarTok, ":: %type% %name% [;=({]")) {
if (localVarTok->strAt(3) != "(" ||
Token::Match(localVarTok->linkAt(3), "[)}] ;")) {
localTypeTok = localVarTok->next();
localVarTok = localVarTok->tokAt(2);
}
}
}
} else if (Token::Match(localTypeTok, "%type%")) {
if (isCPP11 && Token::simpleMatch(localTypeTok, "decltype (") && Token::Match(localTypeTok->linkAt(1), ") %name%|*|&|&&"))
localVarTok = skipPointersAndQualifiers(localTypeTok->linkAt(1)->next());
else {
localVarTok = skipPointersAndQualifiers(localTypeTok->next());
if (isCPP11 && Token::simpleMatch(localVarTok, "decltype (") && Token::Match(localVarTok->linkAt(1), ") %name%|*|&|&&"))
localVarTok = skipPointersAndQualifiers(localVarTok->linkAt(1)->next());
}
}
if (!localVarTok)
return false;
while (Token::Match(localVarTok, "const|*|&"))
localVarTok = localVarTok->next();
if (Token::Match(localVarTok, "%name% ;|=") || (localVarTok && localVarTok->varId() && localVarTok->strAt(1) == ":")) {
vartok = localVarTok;
typetok = localTypeTok;
} else if (Token::Match(localVarTok, "%name% )|[") && localVarTok->str() != "operator") {
vartok = localVarTok;
typetok = localTypeTok;
} else if (localVarTok && localVarTok->varId() && Token::Match(localVarTok, "%name% (|{") &&
Token::Match(localVarTok->linkAt(1), ")|} ;")) {
vartok = localVarTok;
typetok = localTypeTok;
} else if (type == eCatch &&
Token::Match(localVarTok, "%name% )")) {
vartok = localVarTok;
typetok = localTypeTok;
}
return nullptr != vartok;
}
const Token * Scope::addEnum(const Token * tok)
{
const Token * tok2 = tok->next();
// skip over class if present
if (tok2->isCpp() && tok2->str() == "class")
tok2 = tok2->next();
// skip over name
tok2 = tok2->next();
// save type if present
if (tok2->str() == ":") {
tok2 = tok2->next();
enumType = tok2;
while (Token::Match(tok2, "%name%|::"))
tok2 = tok2->next();
}
// add enumerators
if (tok2->str() == "{") {
const Token * end = tok2->link();
tok2 = tok2->next();
while (Token::Match(tok2, "%name% =|,|}") ||
(Token::Match(tok2, "%name% (") && Token::Match(tok2->linkAt(1), ") ,|}"))) {
Enumerator enumerator(this);
// save enumerator name
enumerator.name = tok2;
// skip over name
tok2 = tok2->next();
if (tok2->str() == "=") {
// skip over "="
tok2 = tok2->next();
if (tok2->str() == "}")
return nullptr;
enumerator.start = tok2;
while (!Token::Match(tok2, ",|}")) {
if (tok2->link())
tok2 = tok2->link();
enumerator.end = tok2;
tok2 = tok2->next();
}
} else if (tok2->str() == "(") {
// skip over unknown macro
tok2 = tok2->link()->next();
}
if (tok2->str() == ",") {
enumeratorList.push_back(enumerator);
tok2 = tok2->next();
} else if (tok2->str() == "}") {
enumeratorList.push_back(enumerator);
break;
}
}
if (tok2 == end) {
tok2 = tok2->next();
if (tok2 && tok2->str() != ";" && (tok2->isCpp() || tok2->str() != ")"))
tok2 = nullptr;
} else
tok2 = nullptr;
} else
tok2 = nullptr;
return tok2;
}
static const Scope* findEnumScopeInBase(const Scope* scope, const std::string& tokStr)
{
if (scope->definedType) {
const std::vector<Type::BaseInfo>& derivedFrom = scope->definedType->derivedFrom;
for (const Type::BaseInfo& i : derivedFrom) {
const Type *derivedFromType = i.type;
if (derivedFromType && derivedFromType->classScope) {
if (const Scope* enumScope = derivedFromType->classScope->findRecordInNestedList(tokStr))
return enumScope;
}
}
}
return nullptr;
}
static const Enumerator* findEnumeratorInUsingList(const Scope* scope, const std::string& name)
{
for (const auto& u : scope->usingList) {
if (!u.scope)
continue;
for (const Scope* nested : u.scope->nestedList) {
if (nested->type != Scope::eEnum)
continue;
const Enumerator* e = nested->findEnumerator(name);
if (e && !(e->scope && e->scope->enumClass))
return e;
}
}
return nullptr;
}
const Enumerator * SymbolDatabase::findEnumerator(const Token * tok, std::set<std::string>& tokensThatAreNotEnumeratorValues) const
{
if (tok->isKeyword())
return nullptr;
const std::string& tokStr = tok->str();
const Scope* scope = tok->scope();
// check for qualified name
if (tok->strAt(-1) == "::") {
// find first scope
const Token *tok1 = tok;
while (Token::Match(tok1->tokAt(-2), "%name% ::"))
tok1 = tok1->tokAt(-2);
if (tok1->strAt(-1) == "::")
scope = &scopeList.front();
else {
const Scope* temp = nullptr;
if (scope)
temp = scope->findRecordInNestedList(tok1->str());
// find first scope
while (scope && scope->nestedIn) {
if (!temp)
temp = scope->nestedIn->findRecordInNestedList(tok1->str());
if (!temp && scope->functionOf) {
temp = scope->functionOf->findRecordInNestedList(tok1->str());
const Scope* nested = scope->functionOf->nestedIn;
while (!temp && nested) {
temp = nested->findRecordInNestedList(tok1->str());
nested = nested->nestedIn;
}
}
if (!temp)
temp = findEnumScopeInBase(scope, tok1->str());
if (temp) {
scope = temp;
break;
}
scope = scope->nestedIn;
}
}
if (scope) {
tok1 = tok1->tokAt(2);
while (scope && Token::Match(tok1, "%name% ::")) {
scope = scope->findRecordInNestedList(tok1->str());
tok1 = tok1->tokAt(2);
}
if (scope) {
const Enumerator * enumerator = scope->findEnumerator(tokStr);
if (enumerator) // enum class
return enumerator;
// enum
for (std::vector<Scope *>::const_iterator it = scope->nestedList.cbegin(), end = scope->nestedList.cend(); it != end; ++it) {
enumerator = (*it)->findEnumerator(tokStr);
if (enumerator && !(enumerator->scope && enumerator->scope->enumClass))
return enumerator;
}
}
}
} else { // unqualified name
if (tokensThatAreNotEnumeratorValues.find(tokStr) != tokensThatAreNotEnumeratorValues.end())
return nullptr;
if (tok->scope()->type == Scope::eGlobal) {
const Token* astTop = tok->astTop();
if (Token::simpleMatch(astTop, ":") && Token::simpleMatch(astTop->astOperand1(), "(")) { // ctor init list
const Token* ctor = astTop->astOperand1()->previous();
if (ctor && ctor->function() && ctor->function()->nestedIn)
scope = ctor->function()->nestedIn;
}
}
const Enumerator * enumerator = scope->findEnumerator(tokStr);
if (!enumerator)
enumerator = findEnumeratorInUsingList(scope, tokStr);
if (enumerator && !(enumerator->scope && enumerator->scope->enumClass))
return enumerator;
if (Token::simpleMatch(tok->astParent(), ".")) {
const Token* varTok = tok->astParent()->astOperand1();
if (varTok && varTok->variable() && varTok->variable()->type() && varTok->variable()->type()->classScope)
scope = varTok->variable()->type()->classScope;
}
else if (Token::simpleMatch(tok->astParent(), "[")) {
const Token* varTok = tok->astParent()->previous();
if (varTok && varTok->variable() && varTok->variable()->scope() && Token::simpleMatch(tok->astParent()->astOperand1(), "::"))
scope = varTok->variable()->scope();
}
for (std::vector<Scope *>::const_iterator s = scope->nestedList.cbegin(); s != scope->nestedList.cend(); ++s) {
enumerator = (*s)->findEnumerator(tokStr);
if (enumerator && !(enumerator->scope && enumerator->scope->enumClass))
return enumerator;
}
if (scope->definedType) {
const std::vector<Type::BaseInfo> & derivedFrom = scope->definedType->derivedFrom;
for (const Type::BaseInfo & i : derivedFrom) {
const Type *derivedFromType = i.type;
if (derivedFromType && derivedFromType->classScope) {
enumerator = derivedFromType->classScope->findEnumerator(tokStr);
if (enumerator && !(enumerator->scope && enumerator->scope->enumClass))
return enumerator;
}
}
}
while (scope->nestedIn) {
if (scope->type == Scope::eFunction && scope->functionOf)
scope = scope->functionOf;
else
scope = scope->nestedIn;
enumerator = scope->findEnumerator(tokStr);
if (!enumerator)
enumerator = findEnumeratorInUsingList(scope, tokStr);
if (enumerator && !(enumerator->scope && enumerator->scope->enumClass))
return enumerator;
for (std::vector<Scope*>::const_iterator s = scope->nestedList.cbegin(); s != scope->nestedList.cend(); ++s) {
enumerator = (*s)->findEnumerator(tokStr);
if (enumerator && !(enumerator->scope && enumerator->scope->enumClass))
return enumerator;
if (tok->isCpp() && (*s)->type == Scope::eNamespace && Token::simpleMatch((*s)->classDef, "namespace {")) {
for (const Scope* nested : (*s)->nestedList) {
if (nested->type != Scope::eEnum)
continue;
enumerator = nested->findEnumerator(tokStr);
if (enumerator && !(enumerator->scope && enumerator->scope->enumClass))
return enumerator;
}
}
}
}
}
tokensThatAreNotEnumeratorValues.insert(tokStr);
return nullptr;
}
//---------------------------------------------------------------------------
const Type* SymbolDatabase::findVariableTypeInBase(const Scope* scope, const Token* typeTok)
{
if (scope && scope->definedType && !scope->definedType->derivedFrom.empty()) {
const std::vector<Type::BaseInfo> &derivedFrom = scope->definedType->derivedFrom;
for (const Type::BaseInfo & i : derivedFrom) {
const Type *base = i.type;
if (base && base->classScope) {
if (base->classScope == scope)
return nullptr;
const Type * type = base->classScope->findType(typeTok->str());
if (type)
return type;
type = findVariableTypeInBase(base->classScope, typeTok);
if (type)
return type;
}
}
}
return nullptr;
}
//---------------------------------------------------------------------------
const Type* SymbolDatabase::findVariableType(const Scope *start, const Token *typeTok) const
{
const Scope *scope = start;
// check if type does not have a namespace
if (typeTok->strAt(-1) != "::" && typeTok->strAt(1) != "::") {
// check if type same as scope
if (start->isClassOrStruct() && typeTok->str() == start->className)
return start->definedType;
while (scope) {
// look for type in this scope
const Type * type = scope->findType(typeTok->str());
if (type)
return type;
// look for type in base classes if possible
if (scope->isClassOrStruct()) {
type = findVariableTypeInBase(scope, typeTok);
if (type)
return type;
}
// check if in member function class to see if it's present in class
if (scope->type == Scope::eFunction && scope->functionOf) {
const Scope *scope1 = scope->functionOf;
type = scope1->findType(typeTok->str());
if (type)
return type;
type = findVariableTypeInBase(scope1, typeTok);
if (type)
return type;
}
scope = scope->nestedIn;
}
}
// check for a qualified name and use it when given
else if (typeTok->strAt(-1) == "::") {
// check if type is not part of qualification
if (typeTok->strAt(1) == "::")
return nullptr;
// find start of qualified function name
const Token *tok1 = typeTok;
while ((Token::Match(tok1->tokAt(-2), "%type% ::") && !tok1->tokAt(-2)->isKeyword()) ||
(Token::simpleMatch(tok1->tokAt(-2), "> ::") && tok1->linkAt(-2) && Token::Match(tok1->linkAt(-2)->tokAt(-1), "%type%"))) {
if (tok1->strAt(-1) == "::")
tok1 = tok1->tokAt(-2);
else
tok1 = tok1->linkAt(-2)->tokAt(-1);
}
// check for global scope
if (tok1->strAt(-1) == "::") {
scope = &scopeList.front();
scope = scope->findRecordInNestedList(tok1->str());
}
// find start of qualification
else {
while (scope) {
if (scope->className == tok1->str())
break;
const Scope *scope1 = scope->findRecordInNestedList(tok1->str());
if (scope1) {
scope = scope1;
break;
}
if (scope->type == Scope::eFunction && scope->functionOf)
scope = scope->functionOf;
else
scope = scope->nestedIn;
}
}
if (scope) {
// follow qualification
while (scope && (Token::Match(tok1, "%type% ::") ||
(Token::Match(tok1, "%type% <") && Token::simpleMatch(tok1->linkAt(1), "> ::")))) {
if (tok1->strAt(1) == "::")
tok1 = tok1->tokAt(2);
else
tok1 = tok1->linkAt(1)->tokAt(2);
const Scope * temp = scope->findRecordInNestedList(tok1->str());
if (!temp) {
// look in base classes
const Type * type = findVariableTypeInBase(scope, tok1);
if (type)
return type;
}
scope = temp;
}
if (scope && scope->definedType)
return scope->definedType;
}
}
return nullptr;
}
static bool hasEmptyCaptureList(const Token* tok) {
if (!Token::simpleMatch(tok, "{"))
return false;
const Token* listTok = tok->astParent();
if (Token::simpleMatch(listTok, "("))
listTok = listTok->astParent();
return Token::simpleMatch(listTok, "[ ]");
}
bool Scope::hasInlineOrLambdaFunction(const Token** tokStart) const
{
return std::any_of(nestedList.begin(), nestedList.end(), [&](const Scope* s) {
// Inline function
if (s->type == Scope::eUnconditional && Token::simpleMatch(s->bodyStart->previous(), ") {")) {
if (tokStart)
*tokStart = nullptr; // bailout for e.g. loop-like macros
return true;
}
// Lambda function
if (s->type == Scope::eLambda && !hasEmptyCaptureList(s->bodyStart)) {
if (tokStart)
*tokStart = s->bodyStart;
return true;
}
if (s->hasInlineOrLambdaFunction(tokStart))
return true;
return false;
});
}
void Scope::findFunctionInBase(const std::string & name, nonneg int args, std::vector<const Function *> & matches) const
{
if (isClassOrStruct() && definedType && !definedType->derivedFrom.empty()) {
const std::vector<Type::BaseInfo> &derivedFrom = definedType->derivedFrom;
for (const Type::BaseInfo & i : derivedFrom) {
const Type *base = i.type;
if (base && base->classScope) {
if (base->classScope == this) // Ticket #5120, #5125: Recursive class; tok should have been found already
continue;
auto range = base->classScope->functionMap.equal_range(name);
for (std::multimap<std::string, const Function*>::const_iterator it = range.first; it != range.second; ++it) {
const Function *func = it->second;
if ((func->isVariadic() && args >= (func->argCount() - 1)) ||
(args == func->argCount() || (args < func->argCount() && args >= func->minArgCount()))) {
matches.push_back(func);
}
}
base->classScope->findFunctionInBase(name, args, matches);
}
}
}
}
const Scope *Scope::findRecordInBase(const std::string & name) const
{
if (isClassOrStruct() && definedType && !definedType->derivedFrom.empty()) {
const std::vector<Type::BaseInfo> &derivedFrom = definedType->derivedFrom;
for (const Type::BaseInfo & i : derivedFrom) {
const Type *base = i.type;
if (base && base->classScope) {
if (base->classScope == this) // Recursive class; tok should have been found already
continue;
if (base->name() == name) {
return base->classScope;
}
const ::Type * t = base->classScope->findType(name);
if (t)
return t->classScope;
}
}
}
return nullptr;
}
std::vector<const Scope*> Scope::findAssociatedScopes() const
{
std::vector<const Scope*> result = {this};
if (isClassOrStruct() && definedType && !definedType->derivedFrom.empty()) {
const std::vector<Type::BaseInfo>& derivedFrom = definedType->derivedFrom;
for (const Type::BaseInfo& i : derivedFrom) {
const Type* base = i.type;
if (base && base->classScope) {
if (contains(result, base->classScope))
continue;
std::vector<const Scope*> baseScopes = base->classScope->findAssociatedScopes();
result.insert(result.end(), baseScopes.cbegin(), baseScopes.cend());
}
}
}
return result;
}
//---------------------------------------------------------------------------
static void checkVariableCallMatch(const Variable* callarg, const Variable* funcarg, size_t& same, size_t& fallback1, size_t& fallback2)
{
if (callarg) {
const ValueType::MatchResult res = ValueType::matchParameter(callarg->valueType(), callarg, funcarg);
if (res == ValueType::MatchResult::SAME) {
same++;
return;
}
if (res == ValueType::MatchResult::FALLBACK1) {
fallback1++;
return;
}
if (res == ValueType::MatchResult::FALLBACK2) {
fallback2++;
return;
}
if (res == ValueType::MatchResult::NOMATCH)
return;
const bool ptrequals = callarg->isArrayOrPointer() == funcarg->isArrayOrPointer();
const bool constEquals = !callarg->isArrayOrPointer() || ((callarg->typeStartToken()->strAt(-1) == "const") == (funcarg->typeStartToken()->strAt(-1) == "const"));
if (ptrequals && constEquals &&
callarg->typeStartToken()->str() == funcarg->typeStartToken()->str() &&
callarg->typeStartToken()->isUnsigned() == funcarg->typeStartToken()->isUnsigned() &&
callarg->typeStartToken()->isLong() == funcarg->typeStartToken()->isLong()) {
same++;
} else if (callarg->isArrayOrPointer()) {
if (ptrequals && constEquals && funcarg->typeStartToken()->str() == "void")
fallback1++;
else if (constEquals && funcarg->isStlStringType() && Token::Match(callarg->typeStartToken(), "char|wchar_t"))
fallback2++;
} else if (ptrequals) {
const bool takesInt = Token::Match(funcarg->typeStartToken(), "char|short|int|long");
const bool takesFloat = Token::Match(funcarg->typeStartToken(), "float|double");
const bool passesInt = Token::Match(callarg->typeStartToken(), "char|short|int|long");
const bool passesFloat = Token::Match(callarg->typeStartToken(), "float|double");
if ((takesInt && passesInt) || (takesFloat && passesFloat))
fallback1++;
else if ((takesInt && passesFloat) || (takesFloat && passesInt))
fallback2++;
}
}
}
static std::string getTypeString(const Token *typeToken)
{
if (!typeToken)
return "";
while (Token::Match(typeToken, "%name%|*|&|::")) {
if (typeToken->str() == "::") {
std::string ret;
while (Token::Match(typeToken, ":: %name%")) {
ret += "::" + typeToken->strAt(1);
typeToken = typeToken->tokAt(2);
if (typeToken->str() == "<") {
for (const Token *tok = typeToken; tok != typeToken->link(); tok = tok->next())
ret += tok->str();
ret += ">";
typeToken = typeToken->link()->next();
}
}
return ret;
}
if (Token::Match(typeToken, "%name% const| %var%|*|&")) {
return typeToken->str();
}
typeToken = typeToken->next();
}
return "";
}
static bool hasMatchingConstructor(const Scope* classScope, const ValueType* argType) {
if (!classScope || !argType)
return false;
return std::any_of(classScope->functionList.cbegin(),
classScope->functionList.cend(),
[&](const Function& f) {
if (!f.isConstructor() || f.argCount() != 1 || !f.getArgumentVar(0))
return false;
const ValueType* vt = f.getArgumentVar(0)->valueType();
return vt &&
vt->type == argType->type &&
(argType->sign == ValueType::Sign::UNKNOWN_SIGN || vt->sign == argType->sign) &&
vt->pointer == argType->pointer &&
(vt->constness & 1) >= (argType->constness & 1) &&
(vt->volatileness & 1) >= (argType->volatileness & 1);
});
}
const Function* Scope::findFunction(const Token *tok, bool requireConst, Reference ref) const
{
const bool isCall = Token::Match(tok->next(), "(|{");
const std::vector<const Token *> arguments = getArguments(tok);
std::vector<const Function *> matches;
// find all the possible functions that could match
const std::size_t args = arguments.size();
auto addMatchingFunctions = [&](const Scope *scope) {
auto range = scope->functionMap.equal_range(tok->str());
for (std::multimap<std::string, const Function *>::const_iterator it = range.first; it != range.second; ++it) {
const Function *func = it->second;
if (ref == Reference::LValue && func->hasRvalRefQualifier())
continue;
if (ref == Reference::None && func->hasRvalRefQualifier()) {
if (Token::simpleMatch(tok->astParent(), ".")) {
const Token* obj = tok->astParent()->astOperand1();
while (obj && obj->str() == "[")
obj = obj->astOperand1();
if (!obj || obj->isName())
continue;
}
}
if (func->isDestructor() && !Token::simpleMatch(tok->tokAt(-1), "~"))
continue;
if (!isCall || args == func->argCount() ||
(func->isVariadic() && args >= (func->minArgCount() - 1)) ||
(args < func->argCount() && args >= func->minArgCount())) {
matches.push_back(func);
}
}
};
addMatchingFunctions(this);
// check in anonymous namespaces
for (const Scope *nestedScope : nestedList) {
if (nestedScope->type == eNamespace && nestedScope->className.empty())
addMatchingFunctions(nestedScope);
}
const std::size_t numberOfMatchesNonBase = matches.size();
// check in base classes
findFunctionInBase(tok->str(), args, matches);
// Non-call => Do not match parameters
if (!isCall) {
return matches.empty() ? nullptr : matches[0];
}
std::vector<const Function*> fallback1Func, fallback2Func;
// check each function against the arguments in the function call for a match
for (std::size_t i = 0; i < matches.size();) {
if (i > 0 && i == numberOfMatchesNonBase && fallback1Func.empty() && !fallback2Func.empty())
break;
bool constFallback = false;
const Function * func = matches[i];
size_t same = 0;
if (requireConst && !func->isConst()) {
i++;
continue;
}
if (!requireConst || !func->isConst()) {
// get the function this call is in
const Scope * scope = tok->scope();
// check if this function is a member function
if (scope && scope->functionOf && scope->functionOf->isClassOrStruct() && scope->function &&
func->nestedIn == scope->functionOf) {
// check if isConst mismatches
if (scope->function->isConst() != func->isConst()) {
if (scope->function->isConst()) {
++i;
continue;
}
constFallback = true;
}
}
}
size_t fallback1 = 0;
size_t fallback2 = 0;
bool erased = false;
for (std::size_t j = 0; j < args; ++j) {
// don't check variadic arguments
if (func->isVariadic() && j > (func->argCount() - 1)) {
break;
}
const Variable *funcarg = func->getArgumentVar(j);
if (!arguments[j]->valueType()) {
const Token *vartok = arguments[j];
int pointer = 0;
while (vartok && (vartok->isUnaryOp("&") || vartok->isUnaryOp("*"))) {
pointer += vartok->isUnaryOp("&") ? 1 : -1;
vartok = vartok->astOperand1();
}
if (vartok && vartok->variable()) {
const Token *callArgTypeToken = vartok->variable()->typeStartToken();
const Token *funcArgTypeToken = funcarg->typeStartToken();
auto parseDecl = [](const Token *typeToken) -> ValueType {
ValueType ret;
while (Token::Match(typeToken->previous(), "%name%"))
typeToken = typeToken->previous();
while (Token::Match(typeToken, "%name%|*|&|::|<"))
{
if (typeToken->str() == "const")
ret.constness |= (1 << ret.pointer);
else if (typeToken->str() == "volatile")
ret.volatileness |= (1 << ret.pointer);
else if (typeToken->str() == "*")
ret.pointer++;
else if (typeToken->str() == "<") {
if (!typeToken->link())
break;
typeToken = typeToken->link();
}
typeToken = typeToken->next();
}
return ret;
};
const std::string type1 = getTypeString(callArgTypeToken);
const std::string type2 = getTypeString(funcArgTypeToken);
if (!type1.empty() && type1 == type2) {
ValueType callArgType = parseDecl(callArgTypeToken);
callArgType.pointer += pointer;
ValueType funcArgType = parseDecl(funcArgTypeToken);
callArgType.sign = funcArgType.sign = ValueType::Sign::SIGNED;
callArgType.type = funcArgType.type = ValueType::Type::INT;
const ValueType::MatchResult res = ValueType::matchParameter(&callArgType, &funcArgType);
if (res == ValueType::MatchResult::SAME)
++same;
else if (res == ValueType::MatchResult::FALLBACK1)
++fallback1;
else if (res == ValueType::MatchResult::FALLBACK2)
++fallback2;
continue;
}
}
}
// check for a match with a variable
if (Token::Match(arguments[j], "%var% ,|)")) {
const Variable * callarg = arguments[j]->variable();
checkVariableCallMatch(callarg, funcarg, same, fallback1, fallback2);
}
else if (funcarg->isStlStringType() && arguments[j]->valueType() && arguments[j]->valueType()->pointer == 1 && arguments[j]->valueType()->type == ValueType::Type::CHAR)
fallback2++;
// check for a match with nullptr
else if (funcarg->isPointer() && Token::Match(arguments[j], "nullptr|NULL ,|)"))
same++;
else if (funcarg->isPointer() && MathLib::isNullValue(arguments[j]->str()))
fallback1++;
else if (!funcarg->isPointer() && funcarg->type() && hasMatchingConstructor(funcarg->type()->classScope, arguments[j]->valueType()))
fallback2++;
// Try to evaluate the apparently more complex expression
else if (arguments[j]->isCpp()) {
const Token *vartok = arguments[j];
if (vartok->str() == ".") {
const Token* rml = nextAfterAstRightmostLeaf(vartok);
if (rml)
vartok = rml->previous();
}
while (vartok->isUnaryOp("&") || vartok->isUnaryOp("*"))
vartok = vartok->astOperand1();
const Variable* var = vartok->variable();
// smart pointer deref?
bool unknownDeref = false;
if (var && vartok->astParent() && vartok->astParent()->str() == "*") {
if (var->isSmartPointer() && var->valueType() && var->valueType()->smartPointerTypeToken)
var = var->valueType()->smartPointerTypeToken->variable();
else
unknownDeref = true;
}
const Token* valuetok = arguments[j];
if (valuetok->str() == "::") {
const Token* rml = nextAfterAstRightmostLeaf(valuetok);
if (rml)
valuetok = rml->previous();
}
if (vartok->isEnumerator())
valuetok = vartok;
const ValueType::MatchResult res = ValueType::matchParameter(valuetok->valueType(), var, funcarg);
if (res == ValueType::MatchResult::SAME)
++same;
else if (res == ValueType::MatchResult::FALLBACK1)
++fallback1;
else if (res == ValueType::MatchResult::FALLBACK2)
++fallback2;
else if (res == ValueType::MatchResult::NOMATCH) {
if (unknownDeref)
continue;
// can't match so remove this function from possible matches
matches.erase(matches.begin() + i);
erased = true;
break;
}
}
else
// C code: if number of arguments match then do not match types
fallback1++;
}
const size_t hasToBe = func->isVariadic() ? (func->argCount() - 1) : args;
// check if all arguments matched
if (same == hasToBe) {
if (constFallback || (!requireConst && func->isConst()))
fallback1Func.emplace_back(func);
else
return func;
}
else {
if (same + fallback1 == hasToBe)
fallback1Func.emplace_back(func);
else if (same + fallback2 + fallback1 == hasToBe)
fallback2Func.emplace_back(func);
}
if (!erased)
++i;
}
// Fallback cases
for (const auto& fb : { fallback1Func, fallback2Func }) {
if (fb.size() == 1)
return fb.front();
if (fb.size() == 2) {
if (fb[0]->isConst() && !fb[1]->isConst())
return fb[1];
if (fb[1]->isConst() && !fb[0]->isConst())
return fb[0];
}
}
// remove pure virtual function if there is an overrider
auto itPure = std::find_if(matches.begin(), matches.end(), [](const Function* m) {
return m->isPure();
});
if (itPure != matches.end() && std::any_of(matches.begin(), matches.end(), [&](const Function* m) {
return m->isImplicitlyVirtual() && m != *itPure;
}))
matches.erase(itPure);
// Only one candidate left
if (matches.size() == 1)
return matches[0];
// Prioritize matches in derived scopes
for (const auto& fb : { fallback1Func, fallback2Func }) {
const Function* ret = nullptr;
for (std::size_t i = 0; i < fb.size(); ++i) {
if (std::find(matches.cbegin(), matches.cend(), fb[i]) == matches.cend())
continue;
if (this == fb[i]->nestedIn) {
if (!ret)
ret = fb[i];
else {
ret = nullptr;
break;
}
}
}
if (ret)
return ret;
}
return nullptr;
}
//---------------------------------------------------------------------------
const Function* SymbolDatabase::findFunction(const Token* const tok) const
{
if (tok->tokType() == Token::Type::eEnumerator)
return nullptr;
// find the scope this function is in
const Scope *currScope = tok->scope();
while (currScope && currScope->isExecutable()) {
if (const Function* f = currScope->findFunction(tok)) {
return f;
}
if (currScope->functionOf)
currScope = currScope->functionOf;
else
currScope = currScope->nestedIn;
}
// check for a qualified name and use it when given
if (tok->strAt(-1) == "::") {
// find start of qualified function name
const Token *tok1 = tok;
while (Token::Match(tok1->tokAt(-2), ">|%type% ::")) {
if (tok1->strAt(-2) == ">") {
if (tok1->linkAt(-2))
tok1 = tok1->linkAt(-2)->tokAt(-1);
else
break;
} else
tok1 = tok1->tokAt(-2);
}
// check for global scope
if (tok1->strAt(-1) == "::") {
currScope = &scopeList.front();
if (const Function* f = currScope->findFunction(tok))
return f;
currScope = currScope->findRecordInNestedList(tok1->str());
}
// find start of qualification
else {
while (currScope) {
if (currScope->className == tok1->str())
break;
const Scope *scope = currScope->findRecordInNestedList(tok1->str());
if (scope) {
currScope = scope;
break;
}
currScope = currScope->nestedIn;
}
}
if (currScope) {
while (currScope && tok1 && !(Token::Match(tok1, "%type% :: %name% [(),>]") ||
(Token::Match(tok1, "%type% <") && Token::Match(tok1->linkAt(1), "> :: %name% (")))) {
if (tok1->strAt(1) == "::")
tok1 = tok1->tokAt(2);
else if (tok1->strAt(1) == "<")
tok1 = tok1->linkAt(1)->tokAt(2);
else
tok1 = nullptr;
if (tok1) {
const Function* func = currScope->findFunction(tok1);
if (func)
return func;
currScope = currScope->findRecordInNestedList(tok1->str());
}
}
if (tok1)
tok1 = tok1->tokAt(2);
if (currScope && tok1) {
const Function* func = currScope->findFunction(tok1);
if (func)
return func;
}
}
}
// check for member function
else if (Token::Match(tok->tokAt(-2), "!!this .")) {
const Token* tok1 = tok->previous()->astOperand1();
if (tok1 && tok1->valueType() && tok1->valueType()->typeScope)
return tok1->valueType()->typeScope->findFunction(tok, tok1->valueType()->constness == 1, tok1->valueType()->reference);
if (tok1 && Token::Match(tok1->previous(), "%name% (") && tok1->previous()->function() &&
tok1->previous()->function()->retDef) {
ValueType vt = ValueType::parseDecl(tok1->previous()->function()->retDef, mSettings);
if (vt.typeScope)
return vt.typeScope->findFunction(tok, vt.constness == 1);
} else if (Token::Match(tok1, "%var% .")) {
const Variable *var = getVariableFromVarId(tok1->varId());
if (var && var->typeScope())
return var->typeScope()->findFunction(tok, var->valueType()->constness == 1);
if (var && var->smartPointerType() && var->smartPointerType()->classScope && tok1->next()->originalName() == "->")
return var->smartPointerType()->classScope->findFunction(tok, var->valueType()->constness == 1);
if (var && var->iteratorType() && var->iteratorType()->classScope && tok1->next()->originalName() == "->")
return var->iteratorType()->classScope->findFunction(tok, var->valueType()->constness == 1);
} else if (Token::simpleMatch(tok->previous()->astOperand1(), "(")) {
const Token *castTok = tok->previous()->astOperand1();
if (castTok->isCast()) {
ValueType vt = ValueType::parseDecl(castTok->next(),mSettings);
if (vt.typeScope)
return vt.typeScope->findFunction(tok, vt.constness == 1);
}
}
}
// check in enclosing scopes
else {
while (currScope) {
const Function *func = currScope->findFunction(tok);
if (func)
return func;
currScope = currScope->nestedIn;
}
// check using namespace
currScope = tok->scope();
while (currScope) {
for (const auto& ul : currScope->usingList) {
if (ul.scope) {
const Function* func = ul.scope->findFunction(tok);
if (func)
return func;
}
}
currScope = currScope->nestedIn;
}
}
// Check for constructor
if (Token::Match(tok, "%name% (|{")) {
ValueType vt = ValueType::parseDecl(tok, mSettings);
if (vt.typeScope)
return vt.typeScope->findFunction(tok, false);
}
return nullptr;
}
//---------------------------------------------------------------------------
const Scope *SymbolDatabase::findScopeByName(const std::string& name) const
{
auto it = std::find_if(scopeList.cbegin(), scopeList.cend(), [&](const Scope& s) {
return s.className == name;
});
return it == scopeList.end() ? nullptr : &*it;
}
//---------------------------------------------------------------------------
template<class S, class T, REQUIRES("S must be a Scope class", std::is_convertible<S*, const Scope*> ), REQUIRES("T must be a Type class", std::is_convertible<T*, const Type*> )>
static S* findRecordInNestedListImpl(S& thisScope, const std::string& name, bool isC, std::set<const Scope*>& visited)
{
for (S* scope: thisScope.nestedList) {
if (scope->className == name && scope->type != Scope::eFunction)
return scope;
if (isC) {
S* nestedScope = scope->findRecordInNestedList(name, isC);
if (nestedScope)
return nestedScope;
}
}
for (const auto& u : thisScope.usingList) {
if (!u.scope || u.scope == &thisScope || visited.find(u.scope) != visited.end())
continue;
visited.emplace(u.scope);
S* nestedScope = findRecordInNestedListImpl<S, T>(const_cast<S&>(*u.scope), name, false, visited);
if (nestedScope)
return nestedScope;
}
T * nested_type = thisScope.findType(name);
if (nested_type) {
if (nested_type->isTypeAlias()) {
if (nested_type->typeStart == nested_type->typeEnd)
return thisScope.findRecordInNestedList(nested_type->typeStart->str()); // TODO: pass isC?
} else
return const_cast<S*>(nested_type->classScope);
}
return nullptr;
}
const Scope* Scope::findRecordInNestedList(const std::string & name, bool isC) const
{
std::set<const Scope*> visited;
return findRecordInNestedListImpl<const Scope, const Type>(*this, name, isC, visited);
}
Scope* Scope::findRecordInNestedList(const std::string & name, bool isC)
{
std::set<const Scope*> visited;
return findRecordInNestedListImpl<Scope, Type>(*this, name, isC, visited);
}
//---------------------------------------------------------------------------
template<class S, class T, REQUIRES("S must be a Scope class", std::is_convertible<S*, const Scope*> ), REQUIRES("T must be a Type class", std::is_convertible<T*, const Type*> )>
static T* findTypeImpl(S& thisScope, const std::string & name)
{
auto it = thisScope.definedTypesMap.find(name);
// Type was found
if (thisScope.definedTypesMap.end() != it)
return it->second;
// is type defined in anonymous namespace..
it = thisScope.definedTypesMap.find(emptyString);
if (it != thisScope.definedTypesMap.end()) {
for (S *scope : thisScope.nestedList) {
if (scope->className.empty() && (scope->type == thisScope.eNamespace || scope->isClassOrStructOrUnion())) {
T *t = scope->findType(name);
if (t)
return t;
}
}
}
// Type was not found
return nullptr;
}
const Type* Scope::findType(const std::string& name) const
{
return findTypeImpl<const Scope, const Type>(*this, name);
}
Type* Scope::findType(const std::string& name)
{
return findTypeImpl<Scope, Type>(*this, name);
}
//---------------------------------------------------------------------------
Scope *Scope::findInNestedListRecursive(const std::string & name)
{
auto it = std::find_if(nestedList.cbegin(), nestedList.cend(), [&](const Scope* s) {
return s->className == name;
});
if (it != nestedList.end())
return *it;
for (Scope* scope: nestedList) {
Scope *child = scope->findInNestedListRecursive(name);
if (child)
return child;
}
return nullptr;
}
//---------------------------------------------------------------------------
const Function *Scope::getDestructor() const
{
auto it = std::find_if(functionList.cbegin(), functionList.cend(), [](const Function& f) {
return f.type == Function::eDestructor;
});
return it == functionList.end() ? nullptr : &*it;
}
//---------------------------------------------------------------------------
const Scope *SymbolDatabase::findScope(const Token *tok, const Scope *startScope) const
{
const Scope *scope = nullptr;
// absolute path
if (tok->str() == "::") {
tok = tok->next();
scope = &scopeList.front();
}
// relative path
else if (tok->isName()) {
scope = startScope;
}
while (scope && tok && tok->isName()) {
if (tok->strAt(1) == "::") {
scope = scope->findRecordInNestedList(tok->str());
tok = tok->tokAt(2);
} else if (tok->strAt(1) == "<")
return nullptr;
else
return scope->findRecordInNestedList(tok->str());
}
// not a valid path
return nullptr;
}
//---------------------------------------------------------------------------
const Type* SymbolDatabase::findType(const Token *startTok, const Scope *startScope, bool lookOutside) const
{
// skip over struct or union
if (Token::Match(startTok, "struct|union"))
startTok = startTok->next();
// type same as scope
if (startTok->str() == startScope->className && startScope->isClassOrStruct() && startTok->strAt(1) != "::")
return startScope->definedType;
if (startTok->isC()) {
const Scope* scope = startScope;
while (scope) {
if (startTok->str() == scope->className && scope->isClassOrStruct())
return scope->definedType;
const Scope* typeScope = scope->findRecordInNestedList(startTok->str(), /*isC*/ true);
if (typeScope) {
if (startTok->str() == typeScope->className && typeScope->isClassOrStruct()) {
if (const Type* type = typeScope->definedType)
return type;
}
}
scope = scope->nestedIn;
}
return nullptr;
}
const Scope* start_scope = startScope;
// absolute path - directly start in global scope
if (startTok->str() == "::") {
startTok = startTok->next();
start_scope = &scopeList.front();
}
const Token* tok = startTok;
const Scope* scope = start_scope;
while (scope && tok && tok->isName()) {
if (tok->strAt(1) == "::" || (tok->strAt(1) == "<" && Token::simpleMatch(tok->linkAt(1), "> ::"))) {
scope = scope->findRecordInNestedList(tok->str());
if (scope) {
if (tok->strAt(1) == "::")
tok = tok->tokAt(2);
else
tok = tok->linkAt(1)->tokAt(2);
} else {
start_scope = start_scope->nestedIn;
if (!start_scope)
break;
scope = start_scope;
tok = startTok;
}
} else {
const Scope* scope1{};
const Type* type = scope->findType(tok->str());
if (type)
return type;
if (lookOutside && (scope1 = scope->findRecordInBase(tok->str()))) {
type = scope1->definedType;
if (type)
return type;
} else if (lookOutside && scope->type == Scope::ScopeType::eNamespace) {
scope = scope->nestedIn;
continue;
} else
break;
}
}
// check using namespaces
while (startScope) {
for (std::vector<Scope::UsingInfo>::const_iterator it = startScope->usingList.cbegin();
it != startScope->usingList.cend(); ++it) {
tok = startTok;
scope = it->scope;
start_scope = startScope;
while (scope && tok && tok->isName()) {
if (tok->strAt(1) == "::" || (tok->strAt(1) == "<" && Token::simpleMatch(tok->linkAt(1), "> ::"))) {
scope = scope->findRecordInNestedList(tok->str());
if (scope) {
if (tok->strAt(1) == "::")
tok = tok->tokAt(2);
else
tok = tok->linkAt(1)->tokAt(2);
} else {
start_scope = start_scope->nestedIn;
if (!start_scope)
break;
scope = start_scope;
tok = startTok;
}
} else {
const Type * type = scope->findType(tok->str());
if (type)
return type;
if (const Scope *scope1 = scope->findRecordInBase(tok->str())) {
type = scope1->definedType;
if (type)
return type;
} else
break;
}
}
}
startScope = startScope->nestedIn;
}
// not a valid path
return nullptr;
}
//---------------------------------------------------------------------------
const Type* SymbolDatabase::findTypeInNested(const Token *startTok, const Scope *startScope) const
{
// skip over struct or union
if (Token::Match(startTok, "struct|union|enum"))
startTok = startTok->next();
// type same as scope
if (startScope->isClassOrStruct() && startTok->str() == startScope->className && !Token::simpleMatch(startTok->next(), "::"))
return startScope->definedType;
bool hasPath = false;
// absolute path - directly start in global scope
if (startTok->str() == "::") {
hasPath = true;
startTok = startTok->next();
startScope = &scopeList.front();
}
const Token* tok = startTok;
const Scope* scope = startScope;
while (scope && tok && tok->isName()) {
if (tok->strAt(1) == "::" || (tok->strAt(1) == "<" && Token::simpleMatch(tok->linkAt(1), "> ::"))) {
hasPath = true;
scope = scope->findRecordInNestedList(tok->str());
if (scope) {
if (tok->strAt(1) == "::")
tok = tok->tokAt(2);
else
tok = tok->linkAt(1)->tokAt(2);
} else {
startScope = startScope->nestedIn;
if (!startScope)
break;
scope = startScope;
tok = startTok;
}
} else {
const Type * type = scope->findType(tok->str());
if (hasPath || type)
return type;
scope = scope->nestedIn;
if (!scope)
break;
}
}
// not a valid path
return nullptr;
}
//---------------------------------------------------------------------------
const Scope * SymbolDatabase::findNamespace(const Token * tok, const Scope * scope) const
{
const Scope * s = findScope(tok, scope);
if (s)
return s;
if (scope->nestedIn)
return findNamespace(tok, scope->nestedIn);
return nullptr;
}
//---------------------------------------------------------------------------
Function * SymbolDatabase::findFunctionInScope(const Token *func, const Scope *ns, const std::string & path, nonneg int path_length)
{
const Function * function = nullptr;
const bool destructor = func->strAt(-1) == "~";
auto range = ns->functionMap.equal_range(func->str());
for (std::multimap<std::string, const Function*>::const_iterator it = range.first; it != range.second; ++it) {
if (it->second->argsMatch(ns, it->second->argDef, func->next(), path, path_length) &&
it->second->isDestructor() == destructor) {
function = it->second;
break;
}
}
if (!function) {
const Scope * scope = ns->findRecordInNestedList(func->str());
if (scope && Token::Match(func->tokAt(1), "::|<")) {
if (func->strAt(1) == "::")
func = func->tokAt(2);
else if (func->linkAt(1))
func = func->linkAt(1)->tokAt(2);
else
return nullptr;
if (func->str() == "~")
func = func->next();
function = findFunctionInScope(func, scope, path, path_length);
}
}
return const_cast<Function *>(function);
}
//---------------------------------------------------------------------------
bool SymbolDatabase::isReservedName(const Token* tok)
{
const std::string& iName = tok->str();
if (tok->isCpp()) {
static const auto& cpp_keywords = Keywords::getAll(Standards::cppstd_t::CPPLatest);
return cpp_keywords.find(iName) != cpp_keywords.cend();
}
static const auto& c_keywords = Keywords::getAll(Standards::cstd_t::CLatest);
return c_keywords.find(iName) != c_keywords.cend();
}
nonneg int SymbolDatabase::sizeOfType(const Token *type) const
{
int size = mTokenizer.sizeOfType(type);
if (size == 0 && type->type() && type->type()->isEnumType() && type->type()->classScope) {
size = mSettings.platform.sizeof_int;
const Token * enum_type = type->type()->classScope->enumType;
if (enum_type)
size = mTokenizer.sizeOfType(enum_type);
}
return size;
}
static const Token* parsedecl(const Token* type,
ValueType* valuetype,
ValueType::Sign defaultSignedness,
const Settings& settings,
SourceLocation loc = SourceLocation::current());
void SymbolDatabase::setValueType(Token* tok, const Variable& var, const SourceLocation &loc)
{
ValueType valuetype;
if (mSettings.debugnormal || mSettings.debugwarnings)
valuetype.setDebugPath(tok, loc);
if (var.nameToken())
valuetype.bits = var.nameToken()->bits();
valuetype.pointer = var.dimensions().size();
// HACK: don't set pointer for plain std::array
if (var.valueType() && var.valueType()->container && Token::simpleMatch(var.typeStartToken(), "std :: array") && !Token::simpleMatch(var.nameToken()->next(), "["))
valuetype.pointer = 0;
valuetype.typeScope = var.typeScope();
if (var.valueType()) {
valuetype.container = var.valueType()->container;
valuetype.containerTypeToken = var.valueType()->containerTypeToken;
}
valuetype.smartPointerType = var.smartPointerType();
if (parsedecl(var.typeStartToken(), &valuetype, mDefaultSignedness, mSettings)) {
if (tok->str() == "." && tok->astOperand1()) {
const ValueType * const vt = tok->astOperand1()->valueType();
if (vt && (vt->constness & 1) != 0)
valuetype.constness |= 1;
if (vt && (vt->volatileness & 1) != 0)
valuetype.volatileness |= 1;
}
setValueType(tok, valuetype);
}
}
static ValueType::Type getEnumType(const Scope* scope, const Platform& platform);
void SymbolDatabase::setValueType(Token* tok, const Enumerator& enumerator, const SourceLocation &loc)
{
ValueType valuetype;
if (mSettings.debugnormal || mSettings.debugwarnings)
valuetype.setDebugPath(tok, loc);
valuetype.typeScope = enumerator.scope;
const Token * type = enumerator.scope->enumType;
if (type) {
valuetype.type = ValueType::typeFromString(type->str(), type->isLong());
if (valuetype.type == ValueType::Type::UNKNOWN_TYPE && type->isStandardType())
valuetype.fromLibraryType(type->str(), mSettings);
if (valuetype.isIntegral()) {
if (type->isSigned())
valuetype.sign = ValueType::Sign::SIGNED;
else if (type->isUnsigned())
valuetype.sign = ValueType::Sign::UNSIGNED;
else if (valuetype.type == ValueType::Type::CHAR)
valuetype.sign = mDefaultSignedness;
else
valuetype.sign = ValueType::Sign::SIGNED;
}
setValueType(tok, valuetype);
} else {
valuetype.sign = ValueType::SIGNED;
valuetype.type = getEnumType(enumerator.scope, mSettings.platform);
setValueType(tok, valuetype);
}
}
static void setAutoTokenProperties(Token * const autoTok)
{
const ValueType *valuetype = autoTok->valueType();
if (valuetype->isIntegral() || valuetype->isFloat())
autoTok->isStandardType(true);
}
static bool isContainerYieldElement(Library::Container::Yield yield)
{
return yield == Library::Container::Yield::ITEM || yield == Library::Container::Yield::AT_INDEX ||
yield == Library::Container::Yield::BUFFER || yield == Library::Container::Yield::BUFFER_NT;
}
static bool isContainerYieldPointer(Library::Container::Yield yield)
{
return yield == Library::Container::Yield::BUFFER || yield == Library::Container::Yield::BUFFER_NT;
}
void SymbolDatabase::setValueType(Token* tok, const ValueType& valuetype, const SourceLocation &loc)
{
auto* valuetypePtr = new ValueType(valuetype);
if (mSettings.debugnormal || mSettings.debugwarnings)
valuetypePtr->setDebugPath(tok, loc);
tok->setValueType(valuetypePtr);
Token *parent = tok->astParent();
if (!parent || parent->valueType())
return;
if (!parent->astOperand1())
return;
const ValueType *vt1 = parent->astOperand1()->valueType();
const ValueType *vt2 = parent->astOperand2() ? parent->astOperand2()->valueType() : nullptr;
if (vt1 && Token::Match(parent, "<<|>>")) {
if (!parent->isCpp() || (vt2 && vt2->isIntegral())) {
if (vt1->type < ValueType::Type::BOOL || vt1->type >= ValueType::Type::INT) {
ValueType vt(*vt1);
vt.reference = Reference::None;
setValueType(parent, vt);
} else {
ValueType vt(*vt1);
vt.type = ValueType::Type::INT; // Integer promotion
vt.sign = ValueType::Sign::SIGNED;
vt.reference = Reference::None;
setValueType(parent, vt);
}
}
return;
}
if (vt1 && vt1->container && vt1->containerTypeToken && Token::Match(parent, ". %name% (") &&
isContainerYieldElement(vt1->container->getYield(parent->strAt(1)))) {
ValueType item;
if (parsedecl(vt1->containerTypeToken, &item, mDefaultSignedness, mSettings)) {
if (item.constness == 0)
item.constness = vt1->constness;
if (item.volatileness == 0)
item.volatileness = vt1->volatileness;
if (isContainerYieldPointer(vt1->container->getYield(parent->strAt(1))))
item.pointer += 1;
else
item.reference = Reference::LValue;
setValueType(parent->tokAt(2), item);
}
}
if (vt1 && vt1->smartPointerType && Token::Match(parent, ". %name% (") && parent->originalName() == "->" && !parent->next()->function()) {
const Scope *scope = vt1->smartPointerType->classScope;
const Function *f = scope ? scope->findFunction(parent->next(), false) : nullptr;
if (f)
parent->next()->function(f);
}
if (parent->isAssignmentOp()) {
if (vt1) {
auto vt = *vt1;
vt.reference = Reference::None;
setValueType(parent, vt);
} else if (parent->isCpp() && ((Token::Match(parent->tokAt(-3), "%var% ; %var% =") && parent->strAt(-3) == parent->strAt(-1)) ||
Token::Match(parent->tokAt(-1), "%var% ="))) {
Token *var1Tok = parent->strAt(-2) == ";" ? parent->tokAt(-3) : parent->tokAt(-1);
Token *autoTok = nullptr;
if (Token::simpleMatch(var1Tok->tokAt(-1), "auto"))
autoTok = var1Tok->previous();
else if (Token::Match(var1Tok->tokAt(-2), "auto *|&|&&"))
autoTok = var1Tok->tokAt(-2);
else if (Token::simpleMatch(var1Tok->tokAt(-3), "auto * const"))
autoTok = var1Tok->tokAt(-3);
if (autoTok) {
ValueType vt(*vt2);
if (vt.constness & (1 << vt.pointer))
vt.constness &= ~(1 << vt.pointer);
if (vt.volatileness & (1 << vt.pointer))
vt.volatileness &= ~(1 << vt.pointer);
if (autoTok->strAt(1) == "*" && vt.pointer)
vt.pointer--;
if (Token::Match(autoTok->tokAt(-1), "const|constexpr"))
vt.constness |= (1 << vt.pointer);
if (Token::simpleMatch(autoTok->tokAt(-1), "volatile"))
vt.volatileness |= (1 << vt.pointer);
setValueType(autoTok, vt);
setAutoTokenProperties(autoTok);
if (vt2->pointer > vt.pointer)
vt.pointer++;
setValueType(var1Tok, vt);
if (var1Tok != parent->previous())
setValueType(parent->previous(), vt);
auto *var = const_cast<Variable *>(parent->previous()->variable());
if (var) {
ValueType vt2_(*vt2);
if (vt2_.pointer == 0 && autoTok->strAt(1) == "*")
vt2_.pointer = 1;
if ((vt.constness & (1 << vt2->pointer)) != 0)
vt2_.constness |= (1 << vt2->pointer);
if ((vt.volatileness & (1 << vt2->pointer)) != 0)
vt2_.volatileness |= (1 << vt2->pointer);
if (!Token::Match(autoTok->tokAt(1), "*|&")) {
vt2_.constness = vt.constness;
vt2_.volatileness = vt.volatileness;
}
if (Token::simpleMatch(autoTok->tokAt(1), "* const"))
vt2_.constness |= (1 << vt2->pointer);
if (Token::simpleMatch(autoTok->tokAt(1), "* volatile"))
vt2_.volatileness |= (1 << vt2->pointer);
var->setValueType(vt2_);
if (vt2->typeScope && vt2->typeScope->definedType) {
var->type(vt2->typeScope->definedType);
if (autoTok->valueType()->pointer == 0)
autoTok->type(vt2->typeScope->definedType);
}
}
}
}
return;
}
if (parent->str() == "[" && (!parent->isCpp() || parent->astOperand1() == tok) && valuetype.pointer > 0U && !Token::Match(parent->previous(), "[{,]")) {
const Token *op1 = parent->astOperand1();
while (op1 && op1->str() == "[")
op1 = op1->astOperand1();
ValueType vt(valuetype);
// the "[" is a dereference unless this is a variable declaration
if (!(op1 && op1->variable() && op1->variable()->nameToken() == op1))
vt.pointer -= 1U;
setValueType(parent, vt);
return;
}
if (Token::Match(parent->previous(), "%name% (") && parent->astOperand1() == tok && valuetype.pointer > 0U) {
ValueType vt(valuetype);
vt.pointer -= 1U;
setValueType(parent, vt);
return;
}
// std::move
if (vt2 && parent->str() == "(" && Token::simpleMatch(parent->tokAt(-3), "std :: move (")) {
ValueType vt = valuetype;
vt.reference = Reference::RValue;
setValueType(parent, vt);
return;
}
if (parent->str() == "*" && !parent->astOperand2() && valuetype.pointer > 0U) {
ValueType vt(valuetype);
vt.pointer -= 1U;
setValueType(parent, vt);
return;
}
// Dereference iterator
if (parent->str() == "*" && !parent->astOperand2() && valuetype.type == ValueType::Type::ITERATOR &&
valuetype.containerTypeToken) {
ValueType vt;
if (parsedecl(valuetype.containerTypeToken, &vt, mDefaultSignedness, mSettings)) {
if (vt.constness == 0)
vt.constness = valuetype.constness;
if (vt.volatileness == 0)
vt.volatileness = valuetype.volatileness;
vt.reference = Reference::LValue;
setValueType(parent, vt);
return;
}
}
// Dereference smart pointer
if (parent->str() == "*" && !parent->astOperand2() && valuetype.type == ValueType::Type::SMART_POINTER &&
valuetype.smartPointerTypeToken) {
ValueType vt;
if (parsedecl(valuetype.smartPointerTypeToken, &vt, mDefaultSignedness, mSettings)) {
if (vt.constness == 0)
vt.constness = valuetype.constness;
if (vt.volatileness == 0)
vt.volatileness = valuetype.volatileness;
setValueType(parent, vt);
return;
}
}
if (parent->str() == "*" && Token::simpleMatch(parent->astOperand2(), "[") && valuetype.pointer > 0U) {
const Token *op1 = parent->astOperand2()->astOperand1();
while (op1 && op1->str() == "[")
op1 = op1->astOperand1();
const ValueType& vt(valuetype);
if (op1 && op1->variable() && op1->variable()->nameToken() == op1) {
setValueType(parent, vt);
return;
}
}
if (parent->str() == "&" && !parent->astOperand2()) {
ValueType vt(valuetype);
vt.reference = Reference::None; //Given int& x; the type of &x is int* not int&*
bool isArrayToPointerDecay = false;
for (const Token* child = parent->astOperand1(); child;) {
if (Token::Match(child, ".|::"))
child = child->astOperand2();
else {
isArrayToPointerDecay = child->variable() && child->variable()->isArray();
break;
}
}
if (!isArrayToPointerDecay)
vt.pointer += 1U;
setValueType(parent, vt);
return;
}
if ((parent->str() == "." || parent->str() == "::") &&
parent->astOperand2() && parent->astOperand2()->isName()) {
const Variable* var = parent->astOperand2()->variable();
if (!var && valuetype.typeScope && vt1) {
const std::string &name = parent->astOperand2()->str();
const Scope *typeScope = vt1->typeScope;
if (!typeScope)
return;
auto it = std::find_if(typeScope->varlist.begin(), typeScope->varlist.end(), [&name](const Variable& v) {
return v.nameToken()->str() == name;
});
if (it != typeScope->varlist.end())
var = &*it;
}
if (var) {
setValueType(parent, *var);
return;
}
if (const Enumerator* enu = parent->astOperand2()->enumerator())
setValueType(parent, *enu);
return;
}
// range for loop, auto
if (vt2 &&
parent->str() == ":" &&
Token::Match(parent->astParent(), "( const| auto *|&|&&| %var% :") && // TODO: east-const, multiple const, ref to ptr
!parent->previous()->valueType() &&
Token::simpleMatch(parent->astParent()->astOperand1(), "for")) {
const bool isconst = Token::simpleMatch(parent->astParent()->next(), "const");
const bool isvolatile = Token::simpleMatch(parent->astParent()->next(), "volatile");
Token * const autoToken = parent->astParent()->tokAt(isconst ? 2 : 1);
if (vt2->pointer) {
ValueType autovt(*vt2);
autovt.pointer--;
autovt.constness = 0;
autovt.volatileness = 0;
setValueType(autoToken, autovt);
setAutoTokenProperties(autoToken);
ValueType varvt(*vt2);
varvt.pointer--;
if (Token::simpleMatch(autoToken->next(), "&"))
varvt.reference = Reference::LValue;
if (isconst) {
if (varvt.pointer && varvt.reference != Reference::None)
varvt.constness |= (1 << varvt.pointer);
else
varvt.constness |= 1;
}
if (isvolatile) {
if (varvt.pointer && varvt.reference != Reference::None)
varvt.volatileness |= (1 << varvt.pointer);
else
varvt.volatileness |= 1;
}
setValueType(parent->previous(), varvt);
auto *var = const_cast<Variable *>(parent->previous()->variable());
if (var) {
var->setValueType(varvt);
if (vt2->typeScope && vt2->typeScope->definedType) {
var->type(vt2->typeScope->definedType);
autoToken->type(vt2->typeScope->definedType);
}
}
} else if (vt2->container) {
// TODO: Determine exact type of RHS
const Token *typeStart = parent->astOperand2();
while (typeStart) {
if (typeStart->variable())
typeStart = typeStart->variable()->typeStartToken();
else if (typeStart->str() == "(" && typeStart->previous() && typeStart->previous()->function())
typeStart = typeStart->previous()->function()->retDef;
else
break;
}
// Try to determine type of "auto" token.
// TODO: Get type better
bool setType = false;
ValueType autovt;
const Type *templateArgType = nullptr; // container element type / smart pointer type
if (!vt2->container->rangeItemRecordType.empty()) {
setType = true;
autovt.type = ValueType::Type::RECORD;
} else if (vt2->containerTypeToken) {
if (mSettings.library.isSmartPointer(vt2->containerTypeToken)) {
const Token *smartPointerTypeTok = vt2->containerTypeToken;
while (Token::Match(smartPointerTypeTok, "%name%|::"))
smartPointerTypeTok = smartPointerTypeTok->next();
if (Token::simpleMatch(smartPointerTypeTok, "<")) {
if ((templateArgType = findTypeInNested(smartPointerTypeTok->next(), tok->scope()))) {
setType = true;
autovt.smartPointerType = templateArgType;
autovt.type = ValueType::Type::NONSTD;
}
}
} else if (parsedecl(vt2->containerTypeToken, &autovt, mDefaultSignedness, mSettings)) {
setType = true;
templateArgType = vt2->containerTypeToken->type();
if (Token::simpleMatch(autoToken->next(), "&"))
autovt.reference = Reference::LValue;
else if (Token::simpleMatch(autoToken->next(), "&&"))
autovt.reference = Reference::RValue;
if (autoToken->strAt(-1) == "const") {
if (autovt.pointer && autovt.reference != Reference::None)
autovt.constness |= 2;
else
autovt.constness |= 1;
}
if (autoToken->strAt(-1) == "volatile") {
if (autovt.pointer && autovt.reference != Reference::None)
autovt.volatileness |= 2;
else
autovt.volatileness |= 1;
}
}
}
if (setType) {
// Type of "auto" has been determined.. set type information for "auto" and variable tokens
setValueType(autoToken, autovt);
setAutoTokenProperties(autoToken);
ValueType varvt(autovt);
if (autoToken->strAt(1) == "*" && autovt.pointer)
autovt.pointer--;
if (isconst)
varvt.constness |= (1 << autovt.pointer);
if (isvolatile)
varvt.volatileness |= (1 << autovt.pointer);
setValueType(parent->previous(), varvt);
auto * var = const_cast<Variable *>(parent->previous()->variable());
if (var) {
var->setValueType(varvt);
if (templateArgType && templateArgType->classScope && templateArgType->classScope->definedType) {
autoToken->type(templateArgType->classScope->definedType);
var->type(templateArgType->classScope->definedType);
}
}
}
}
}
if (vt1 && vt1->containerTypeToken && parent->str() == "[") {
ValueType vtParent;
if (parsedecl(vt1->containerTypeToken, &vtParent, mDefaultSignedness, mSettings)) {
setValueType(parent, vtParent);
return;
}
}
if (parent->isCpp() && vt2 && Token::simpleMatch(parent->previous(), "decltype (")) {
setValueType(parent, *vt2);
return;
}
// c++17 auto type deduction of braced init list
if (parent->isCpp() && mSettings.standards.cpp >= Standards::CPP17 && vt2 && Token::Match(parent->tokAt(-2), "auto %var% {")) {
Token *autoTok = parent->tokAt(-2);
setValueType(autoTok, *vt2);
setAutoTokenProperties(autoTok);
if (parent->previous()->variable())
const_cast<Variable*>(parent->previous()->variable())->setValueType(*vt2);
else
debugMessage(parent->previous(), "debug", "Missing variable class for variable with varid");
return;
}
if (!vt1)
return;
if (parent->astOperand2() && !vt2)
return;
const bool ternary = parent->str() == ":" && parent->astParent() && parent->astParent()->str() == "?";
if (ternary) {
if (vt2 && vt1->pointer == vt2->pointer && vt1->type == vt2->type && vt1->sign == vt2->sign)
setValueType(parent, *vt2);
parent = parent->astParent();
}
if (ternary || parent->isArithmeticalOp() || parent->tokType() == Token::eIncDecOp) {
// CONTAINER + x => CONTAINER
if (parent->str() == "+" && vt1->type == ValueType::Type::CONTAINER && vt2 && vt2->isIntegral()) {
setValueType(parent, *vt1);
return;
}
// x + CONTAINER => CONTAINER
if (parent->str() == "+" && vt1->isIntegral() && vt2 && vt2->type == ValueType::Type::CONTAINER) {
setValueType(parent, *vt2);
return;
}
if (parent->isArithmeticalOp()) {
if (vt1->pointer != 0U && vt2 && vt2->pointer == 0U) {
setValueType(parent, *vt1);
return;
}
if (vt1->pointer == 0U && vt2 && vt2->pointer != 0U) {
setValueType(parent, *vt2);
return;
}
} else if (ternary) {
if (vt1->pointer != 0U && vt2 && vt2->pointer == 0U) {
if (vt2->isPrimitive())
setValueType(parent, *vt1);
else
setValueType(parent, *vt2);
return;
}
if (vt1->pointer == 0U && vt2 && vt2->pointer != 0U) {
if (vt1->isPrimitive())
setValueType(parent, *vt2);
else
setValueType(parent, *vt1);
return;
}
if (vt1->isTypeEqual(vt2)) {
setValueType(parent, *vt1);
return;
}
}
if (vt1->pointer != 0U) {
if (ternary || parent->tokType() == Token::eIncDecOp) // result is pointer
setValueType(parent, *vt1);
else // result is pointer diff
setValueType(parent, ValueType(ValueType::Sign::SIGNED, ValueType::Type::INT, 0U, 0U, "ptrdiff_t"));
return;
}
if (vt1->type == ValueType::Type::LONGDOUBLE || (vt2 && vt2->type == ValueType::Type::LONGDOUBLE)) {
setValueType(parent, ValueType(ValueType::Sign::UNKNOWN_SIGN, ValueType::Type::LONGDOUBLE, 0U));
return;
}
if (vt1->type == ValueType::Type::DOUBLE || (vt2 && vt2->type == ValueType::Type::DOUBLE)) {
setValueType(parent, ValueType(ValueType::Sign::UNKNOWN_SIGN, ValueType::Type::DOUBLE, 0U));
return;
}
if (vt1->type == ValueType::Type::FLOAT || (vt2 && vt2->type == ValueType::Type::FLOAT)) {
setValueType(parent, ValueType(ValueType::Sign::UNKNOWN_SIGN, ValueType::Type::FLOAT, 0U));
return;
}
// iterator +/- integral = iterator
if (vt1->type == ValueType::Type::ITERATOR && vt2 && vt2->isIntegral() &&
(parent->str() == "+" || parent->str() == "-")) {
setValueType(parent, *vt1);
return;
}
if (parent->str() == "+" && vt1->type == ValueType::Type::CONTAINER && vt2 && vt2->type == ValueType::Type::CONTAINER && vt1->container == vt2->container) {
setValueType(parent, *vt1);
return;
}
}
if (vt1->isIntegral() && vt1->pointer == 0U &&
(!vt2 || (vt2->isIntegral() && vt2->pointer == 0U)) &&
(ternary || parent->isArithmeticalOp() || parent->tokType() == Token::eBitOp || parent->tokType() == Token::eIncDecOp || parent->isAssignmentOp())) {
ValueType vt;
if (!vt2 || vt1->type > vt2->type) {
vt.type = vt1->type;
vt.sign = vt1->sign;
vt.originalTypeName = vt1->originalTypeName;
} else if (vt1->type == vt2->type) {
vt.type = vt1->type;
if (vt1->sign == ValueType::Sign::UNSIGNED || vt2->sign == ValueType::Sign::UNSIGNED)
vt.sign = ValueType::Sign::UNSIGNED;
else if (vt1->sign == ValueType::Sign::UNKNOWN_SIGN || vt2->sign == ValueType::Sign::UNKNOWN_SIGN)
vt.sign = ValueType::Sign::UNKNOWN_SIGN;
else
vt.sign = ValueType::Sign::SIGNED;
vt.originalTypeName = (vt1->originalTypeName.empty() ? vt2 : vt1)->originalTypeName;
} else {
vt.type = vt2->type;
vt.sign = vt2->sign;
vt.originalTypeName = vt2->originalTypeName;
}
if (vt.type < ValueType::Type::INT && !(ternary && vt.type==ValueType::Type::BOOL)) {
vt.type = ValueType::Type::INT;
vt.sign = ValueType::Sign::SIGNED;
vt.originalTypeName.clear();
}
setValueType(parent, vt);
return;
}
}
static ValueType::Type getEnumType(const Scope* scope, const Platform& platform) // TODO: also determine sign?
{
ValueType::Type type = ValueType::Type::INT;
for (const Token* tok = scope->bodyStart; tok && tok != scope->bodyEnd; tok = tok->next()) {
if (!tok->isAssignmentOp())
continue;
const Token* vTok = tok->astOperand2();
if (!vTok->hasKnownIntValue()) {
if (!vTok->isLiteral())
continue;
if (const ValueType* vt = vTok->valueType()) {
if ((vt->type > type && (vt->type == ValueType::Type::LONG || vt->type == ValueType::Type::LONGLONG)))
type = vt->type;
}
continue;
}
const MathLib::bigint value = vTok->getKnownIntValue();
if (!platform.isIntValue(value)) {
type = ValueType::Type::LONG;
if (!platform.isLongValue(value))
type = ValueType::Type::LONGLONG;
}
}
return type;
}
static const Token* parsedecl(const Token* type,
ValueType* const valuetype,
ValueType::Sign defaultSignedness,
const Settings& settings,
SourceLocation loc)
{
if (settings.debugnormal || settings.debugwarnings)
valuetype->setDebugPath(type, loc);
const Token * const previousType = type;
const int pointer0 = valuetype->pointer;
while (Token::Match(type->previous(), "%name%") && !endsWith(type->strAt(-1), ':'))
type = type->previous();
valuetype->sign = ValueType::Sign::UNKNOWN_SIGN;
if (!valuetype->typeScope && !valuetype->smartPointerType)
valuetype->type = ValueType::Type::UNKNOWN_TYPE;
else if (valuetype->smartPointerType)
valuetype->type = ValueType::Type::SMART_POINTER;
else if (valuetype->typeScope->type == Scope::eEnum) {
const Token * enum_type = valuetype->typeScope->enumType;
if (enum_type) {
if (enum_type->isSigned())
valuetype->sign = ValueType::Sign::SIGNED;
else if (enum_type->isUnsigned())
valuetype->sign = ValueType::Sign::UNSIGNED;
else
valuetype->sign = defaultSignedness;
const ValueType::Type t = ValueType::typeFromString(enum_type->str(), enum_type->isLong());
if (t != ValueType::Type::UNKNOWN_TYPE)
valuetype->type = t;
else if (enum_type->isStandardType())
valuetype->fromLibraryType(enum_type->str(), settings);
} else
valuetype->type = getEnumType(valuetype->typeScope, settings.platform);
} else
valuetype->type = ValueType::Type::RECORD;
const bool cpp = type->isCpp();
bool par = false;
while (Token::Match(type, "%name%|*|&|&&|::|(") && !Token::Match(type, "typename|template") && type->varId() == 0 &&
!type->variable() && !type->function()) {
bool isIterator = false;
if (type->str() == "(") {
if (!Token::simpleMatch(type, "( *"))
break;
if (Token::Match(type->link(), ") const| {"))
break;
if (par)
break;
par = true;
}
if (Token::simpleMatch(type, "decltype (") && type->next()->valueType()) {
const ValueType *vt2 = type->next()->valueType();
if (valuetype->sign == ValueType::Sign::UNKNOWN_SIGN)
valuetype->sign = vt2->sign;
if (valuetype->type == ValueType::Type::UNKNOWN_TYPE)
valuetype->type = vt2->type;
valuetype->constness += vt2->constness;
valuetype->pointer += vt2->pointer;
valuetype->reference = vt2->reference;
type = type->linkAt(1)->next();
continue;
}
if (type->isSigned())
valuetype->sign = ValueType::Sign::SIGNED;
else if (type->isUnsigned())
valuetype->sign = ValueType::Sign::UNSIGNED;
if (valuetype->type == ValueType::Type::UNKNOWN_TYPE &&
type->type() && type->type()->isTypeAlias() && type->type()->typeStart &&
type->type()->typeStart->str() != type->str() && type->type()->typeStart != previousType)
parsedecl(type->type()->typeStart, valuetype, defaultSignedness, settings);
else if (Token::Match(type, "const|constexpr"))
valuetype->constness |= (1 << (valuetype->pointer - pointer0));
else if (Token::simpleMatch(type, "volatile"))
valuetype->volatileness |= (1 << (valuetype->pointer - pointer0));
else if (settings.clang && type->str().size() > 2 && type->str().find("::") < type->str().find('<')) {
TokenList typeTokens(&settings);
std::string::size_type pos1 = 0;
do {
const std::string::size_type pos2 = type->str().find("::", pos1);
if (pos2 == std::string::npos) {
typeTokens.addtoken(type->str().substr(pos1), 0, 0, 0, false);
break;
}
typeTokens.addtoken(type->str().substr(pos1, pos2 - pos1), 0, 0, 0, false);
typeTokens.addtoken("::", 0, 0, 0, false);
pos1 = pos2 + 2;
} while (pos1 < type->str().size());
const Library::Container* container =
settings.library.detectContainerOrIterator(typeTokens.front(), &isIterator);
if (container) {
if (isIterator)
valuetype->type = ValueType::Type::ITERATOR;
else
valuetype->type = ValueType::Type::CONTAINER;
valuetype->container = container;
} else {
const Scope *scope = type->scope();
valuetype->typeScope = scope->check->findScope(typeTokens.front(), scope);
if (valuetype->typeScope)
valuetype->type = (scope->type == Scope::ScopeType::eClass) ? ValueType::Type::RECORD : ValueType::Type::NONSTD;
}
} else if (const Library::Container* container = (cpp ? settings.library.detectContainerOrIterator(type, &isIterator) : nullptr)) {
if (isIterator)
valuetype->type = ValueType::Type::ITERATOR;
else
valuetype->type = ValueType::Type::CONTAINER;
valuetype->container = container;
while (Token::Match(type, "%type%|::|<") && type->str() != "const") {
if (type->str() == "<" && type->link()) {
if (container->type_templateArgNo >= 0) {
const Token *templateType = type->next();
for (int j = 0; templateType && j < container->type_templateArgNo; j++)
templateType = templateType->nextTemplateArgument();
valuetype->containerTypeToken = templateType;
}
type = type->link();
}
type = type->next();
}
if (type && type->str() == "(" && type->previous()->function())
// we are past the end of the type
type = type->previous();
continue;
} else if (const Library::SmartPointer* smartPointer = (cpp ? settings.library.detectSmartPointer(type) : nullptr)) {
const Token* argTok = Token::findsimplematch(type, "<");
if (!argTok)
break;
valuetype->smartPointer = smartPointer;
valuetype->smartPointerTypeToken = argTok->next();
valuetype->smartPointerType = argTok->next()->type();
valuetype->type = ValueType::Type::SMART_POINTER;
type = argTok->link();
if (type)
type = type->next();
continue;
} else if (Token::Match(type, "%name% :: %name%")) {
std::string typestr;
const Token *end = type;
while (Token::Match(end, "%name% :: %name%")) {
typestr += end->str() + "::";
end = end->tokAt(2);
}
typestr += end->str();
if (valuetype->fromLibraryType(typestr, settings))
type = end;
} else if (ValueType::Type::UNKNOWN_TYPE != ValueType::typeFromString(type->str(), type->isLong())) {
const ValueType::Type t0 = valuetype->type;
valuetype->type = ValueType::typeFromString(type->str(), type->isLong());
if (t0 == ValueType::Type::LONG) {
if (valuetype->type == ValueType::Type::LONG)
valuetype->type = ValueType::Type::LONGLONG;
else if (valuetype->type == ValueType::Type::DOUBLE)
valuetype->type = ValueType::Type::LONGDOUBLE;
}
} else if (type->str() == "auto") {
const ValueType *vt = type->valueType();
if (!vt)
return nullptr;
valuetype->type = vt->type;
valuetype->pointer = vt->pointer;
valuetype->reference = vt->reference;
if (vt->sign != ValueType::Sign::UNKNOWN_SIGN)
valuetype->sign = vt->sign;
valuetype->constness = vt->constness;
valuetype->volatileness = vt->volatileness;
valuetype->originalTypeName = vt->originalTypeName;
const bool hasConst = Token::simpleMatch(type->previous(), "const");
const bool hasVolatile = Token::simpleMatch(type->previous(), "volatile");
while (Token::Match(type, "%name%|*|&|&&|::") && !type->variable()) {
if (type->str() == "*") {
valuetype->pointer = 1;
if (hasConst)
valuetype->constness = 1;
if (hasVolatile)
valuetype->volatileness = 1;
} else if (type->str() == "&") {
valuetype->reference = Reference::LValue;
} else if (type->str() == "&&") {
valuetype->reference = Reference::RValue;
}
if (type->str() == "const")
valuetype->constness |= (1 << valuetype->pointer);
if (type->str() == "volatile")
valuetype->volatileness |= (1 << valuetype->pointer);
type = type->next();
}
break;
} else if (!valuetype->typeScope && (type->str() == "struct" || type->str() == "enum") && valuetype->type != ValueType::Type::SMART_POINTER)
valuetype->type = type->str() == "struct" ? ValueType::Type::RECORD : ValueType::Type::NONSTD;
else if (!valuetype->typeScope && type->type() && type->type()->classScope && valuetype->type != ValueType::Type::SMART_POINTER) {
if (type->type()->classScope->type == Scope::ScopeType::eEnum) {
valuetype->sign = ValueType::Sign::SIGNED;
valuetype->type = getEnumType(type->type()->classScope, settings.platform);
} else {
valuetype->type = ValueType::Type::RECORD;
}
valuetype->typeScope = type->type()->classScope;
} else if (type->isName() && valuetype->sign != ValueType::Sign::UNKNOWN_SIGN && valuetype->pointer == 0U)
return nullptr;
else if (type->str() == "*")
valuetype->pointer++;
else if (type->str() == "&")
valuetype->reference = Reference::LValue;
else if (type->str() == "&&")
valuetype->reference = Reference::RValue;
else if (type->isStandardType())
valuetype->fromLibraryType(type->str(), settings);
else if (Token::Match(type->previous(), "!!:: %name% !!::"))
valuetype->fromLibraryType(type->str(), settings);
if (!type->originalName().empty())
valuetype->originalTypeName = type->originalName();
type = type->next();
if (type && type->link() && type->str() == "<")
type = type->link()->next();
}
// Set signedness for integral types..
if (valuetype->isIntegral() && valuetype->sign == ValueType::Sign::UNKNOWN_SIGN) {
if (valuetype->type == ValueType::Type::CHAR)
valuetype->sign = defaultSignedness;
else if (valuetype->type >= ValueType::Type::SHORT)
valuetype->sign = ValueType::Sign::SIGNED;
}
return (type && (valuetype->type != ValueType::Type::UNKNOWN_TYPE || valuetype->pointer > 0 || valuetype->reference != Reference::None)) ? type : nullptr;
}
static const Scope *getClassScope(const Token *tok)
{
return tok && tok->valueType() && tok->valueType()->typeScope && tok->valueType()->typeScope->isClassOrStruct() ?
tok->valueType()->typeScope :
nullptr;
}
static const Function *getOperatorFunction(const Token * const tok)
{
const std::string functionName("operator" + tok->str());
std::multimap<std::string, const Function *>::const_iterator it;
const Scope *classScope = getClassScope(tok->astOperand1());
if (classScope) {
it = classScope->functionMap.find(functionName);
if (it != classScope->functionMap.end())
return it->second;
}
classScope = getClassScope(tok->astOperand2());
if (classScope) {
it = classScope->functionMap.find(functionName);
if (it != classScope->functionMap.end())
return it->second;
}
return nullptr;
}
static const Function* getFunction(const Token* tok) {
if (!tok)
return nullptr;
if (tok->function() && tok->function()->retDef)
return tok->function();
if (const Variable* lvar = tok->variable()) { // lambda
const Function* lambda{};
if (Token::Match(lvar->nameToken()->next(), "; %varid% = [", lvar->declarationId()))
lambda = lvar->nameToken()->tokAt(4)->function();
else if (Token::simpleMatch(lvar->nameToken()->next(), "{ ["))
lambda = lvar->nameToken()->tokAt(2)->function();
if (lambda && lambda->retDef)
return lambda;
}
return nullptr;
}
void SymbolDatabase::setValueTypeInTokenList(bool reportDebugWarnings, Token *tokens)
{
if (!tokens)
tokens = mTokenizer.list.front();
for (Token *tok = tokens; tok; tok = tok->next())
tok->setValueType(nullptr);
for (Token *tok = tokens; tok; tok = tok->next()) {
if (tok->isNumber()) {
if (MathLib::isFloat(tok->str())) {
ValueType::Type type = ValueType::Type::DOUBLE;
const char suffix = tok->str()[tok->str().size() - 1];
if (suffix == 'f' || suffix == 'F')
type = ValueType::Type::FLOAT;
else if (suffix == 'L' || suffix == 'l')
type = ValueType::Type::LONGDOUBLE;
setValueType(tok, ValueType(ValueType::Sign::UNKNOWN_SIGN, type, 0U));
} else if (MathLib::isInt(tok->str())) {
const std::string tokStr = MathLib::abs(tok->str());
const bool unsignedSuffix = (tokStr.find_last_of("uU") != std::string::npos);
ValueType::Sign sign = unsignedSuffix ? ValueType::Sign::UNSIGNED : ValueType::Sign::SIGNED;
ValueType::Type type = ValueType::Type::INT;
const MathLib::biguint value = MathLib::toBigUNumber(tokStr);
for (std::size_t pos = tokStr.size() - 1U; pos > 0U; --pos) {
const char suffix = tokStr[pos];
if (suffix == 'u' || suffix == 'U')
sign = ValueType::Sign::UNSIGNED;
else if (suffix == 'l' || suffix == 'L')
type = (type == ValueType::Type::INT) ? ValueType::Type::LONG : ValueType::Type::LONGLONG;
else if (pos > 2U && suffix == '4' && tokStr[pos - 1] == '6' && tokStr[pos - 2] == 'i') {
type = ValueType::Type::LONGLONG;
pos -= 2;
} else break;
}
if (mSettings.platform.type != Platform::Type::Unspecified) {
if (type <= ValueType::Type::INT && mSettings.platform.isIntValue(unsignedSuffix ? (value >> 1) : value))
type = ValueType::Type::INT;
else if (type <= ValueType::Type::INT && !MathLib::isDec(tokStr) && mSettings.platform.isIntValue(value >> 2)) {
type = ValueType::Type::INT;
sign = ValueType::Sign::UNSIGNED;
} else if (type <= ValueType::Type::LONG && mSettings.platform.isLongValue(unsignedSuffix ? (value >> 1) : value))
type = ValueType::Type::LONG;
else if (type <= ValueType::Type::LONG && !MathLib::isDec(tokStr) && mSettings.platform.isLongValue(value >> 2)) {
type = ValueType::Type::LONG;
sign = ValueType::Sign::UNSIGNED;
} else if (mSettings.platform.isLongLongValue(unsignedSuffix ? (value >> 1) : value))
type = ValueType::Type::LONGLONG;
else {
type = ValueType::Type::LONGLONG;
sign = ValueType::Sign::UNSIGNED;
}
}
setValueType(tok, ValueType(sign, type, 0U));
}
} else if (tok->isComparisonOp() || tok->tokType() == Token::eLogicalOp) {
if (tok->isCpp() && tok->isComparisonOp() && (getClassScope(tok->astOperand1()) || getClassScope(tok->astOperand2()))) {
const Function *function = getOperatorFunction(tok);
if (function) {
ValueType vt;
parsedecl(function->retDef, &vt, mDefaultSignedness, mSettings);
setValueType(tok, vt);
continue;
}
}
setValueType(tok, ValueType(ValueType::Sign::UNKNOWN_SIGN, ValueType::Type::BOOL, 0U));
} else if (tok->isBoolean()) {
setValueType(tok, ValueType(ValueType::Sign::UNKNOWN_SIGN, ValueType::Type::BOOL, 0U));
} else if (tok->tokType() == Token::eChar || tok->tokType() == Token::eString) {
nonneg int const pointer = tok->tokType() == Token::eChar ? 0 : 1;
nonneg int const constness = tok->tokType() == Token::eChar ? 0 : 1;
nonneg int const volatileness = 0;
ValueType valuetype(ValueType::Sign::UNKNOWN_SIGN, ValueType::Type::CHAR, pointer, constness, volatileness);
if (tok->isCpp() && mSettings.standards.cpp >= Standards::CPP20 && tok->isUtf8()) {
valuetype.originalTypeName = "char8_t";
valuetype.fromLibraryType(valuetype.originalTypeName, mSettings);
} else if (tok->isUtf16()) {
valuetype.originalTypeName = "char16_t";
valuetype.fromLibraryType(valuetype.originalTypeName, mSettings);
} else if (tok->isUtf32()) {
valuetype.originalTypeName = "char32_t";
valuetype.fromLibraryType(valuetype.originalTypeName, mSettings);
} else if (tok->isLong()) {
valuetype.originalTypeName = "wchar_t";
valuetype.type = ValueType::Type::WCHAR_T;
} else if ((tok->tokType() == Token::eChar) && ((!tok->isCpp() && tok->isCChar()) || (tok->isCMultiChar()))) {
valuetype.type = ValueType::Type::INT;
valuetype.sign = ValueType::Sign::SIGNED;
}
setValueType(tok, valuetype);
} else if (tok->link() && Token::Match(tok, "(|{")) {
const Token* start = tok->astOperand1() ? tok->astOperand1()->findExpressionStartEndTokens().first : nullptr;
// cast
if (tok->isCast() && !tok->astOperand2() && Token::Match(tok, "( %name%")) {
ValueType valuetype;
if (Token::simpleMatch(parsedecl(tok->next(), &valuetype, mDefaultSignedness, mSettings), ")"))
setValueType(tok, valuetype);
}
// C++ cast
else if (tok->astOperand2() && Token::Match(tok->astOperand1(), "static_cast|const_cast|dynamic_cast|reinterpret_cast < %name%") && tok->astOperand1()->linkAt(1)) {
ValueType valuetype;
if (Token::simpleMatch(parsedecl(tok->astOperand1()->tokAt(2), &valuetype, mDefaultSignedness, mSettings), ">"))
setValueType(tok, valuetype);
}
// Construct smart pointer
else if (start && start->isCpp() && mSettings.library.isSmartPointer(start)) {
ValueType valuetype;
if (parsedecl(start, &valuetype, mDefaultSignedness, mSettings)) {
setValueType(tok, valuetype);
setValueType(tok->astOperand1(), valuetype);
}
}
// function or lambda
else if (const Function* f = getFunction(tok->previous())) {
ValueType valuetype;
if (parsedecl(f->retDef, &valuetype, mDefaultSignedness, mSettings))
setValueType(tok, valuetype);
}
else if (Token::simpleMatch(tok->previous(), "sizeof (")) {
ValueType valuetype(ValueType::Sign::UNSIGNED, ValueType::Type::LONG, 0U);
if (mSettings.platform.type == Platform::Type::Win64)
valuetype.type = ValueType::Type::LONGLONG;
valuetype.originalTypeName = "size_t";
setValueType(tok, valuetype);
if (Token::Match(tok, "( %type% %type%| *| *| )")) {
ValueType vt;
if (parsedecl(tok->next(), &vt, mDefaultSignedness, mSettings)) {
setValueType(tok->next(), vt);
}
}
}
// function style cast
else if (tok->previous() && tok->previous()->isStandardType()) {
ValueType valuetype;
if (tok->astOperand1() && valuetype.fromLibraryType(tok->astOperand1()->expressionString(), mSettings)) {
setValueType(tok, valuetype);
continue;
}
valuetype.type = ValueType::typeFromString(tok->strAt(-1), tok->previous()->isLong());
if (tok->previous()->isUnsigned())
valuetype.sign = ValueType::Sign::UNSIGNED;
else if (tok->previous()->isSigned())
valuetype.sign = ValueType::Sign::SIGNED;
else if (valuetype.isIntegral() && valuetype.type != ValueType::UNKNOWN_INT)
valuetype.sign = mDefaultSignedness;
setValueType(tok, valuetype);
}
// constructor call
else if (tok->previous() && tok->previous()->function() && tok->previous()->function()->isConstructor()) {
ValueType valuetype;
valuetype.type = ValueType::RECORD;
valuetype.typeScope = tok->previous()->function()->tokenDef->scope();
setValueType(tok, valuetype);
}
else if (Token::simpleMatch(tok->previous(), "= {") && tok->tokAt(-2) && tok->tokAt(-2)->valueType()) {
ValueType vt = *tok->tokAt(-2)->valueType();
setValueType(tok, vt);
}
// library type/function
else if (tok->previous()) {
// Aggregate constructor
if (Token::Match(tok->previous(), "%name%")) {
ValueType valuetype;
if (parsedecl(tok->previous(), &valuetype, mDefaultSignedness, mSettings)) {
if (valuetype.typeScope) {
setValueType(tok, valuetype);
continue;
}
}
}
if (tok->isCpp() && tok->astParent() && Token::Match(tok->astOperand1(), "%name%|::")) {
const Token *typeStartToken = tok->astOperand1();
while (typeStartToken && typeStartToken->str() == "::")
typeStartToken = typeStartToken->astOperand1();
if (mSettings.library.detectContainerOrIterator(typeStartToken) ||
mSettings.library.detectSmartPointer(typeStartToken)) {
ValueType vt;
if (parsedecl(typeStartToken, &vt, mDefaultSignedness, mSettings)) {
setValueType(tok, vt);
continue;
}
}
const std::string e = tok->astOperand1()->expressionString();
if ((e == "std::make_shared" || e == "std::make_unique") && Token::Match(tok->astOperand1(), ":: %name% < %name%")) {
ValueType vt;
parsedecl(tok->astOperand1()->tokAt(3), &vt, mDefaultSignedness, mSettings);
if (vt.typeScope) {
vt.smartPointerType = vt.typeScope->definedType;
vt.typeScope = nullptr;
}
if (e == "std::make_shared" && mSettings.library.smartPointers().count("std::shared_ptr") > 0)
vt.smartPointer = &mSettings.library.smartPointers().at("std::shared_ptr");
if (e == "std::make_unique" && mSettings.library.smartPointers().count("std::unique_ptr") > 0)
vt.smartPointer = &mSettings.library.smartPointers().at("std::unique_ptr");
vt.type = ValueType::Type::SMART_POINTER;
vt.smartPointerTypeToken = tok->astOperand1()->tokAt(3);
setValueType(tok, vt);
continue;
}
ValueType podtype;
if (podtype.fromLibraryType(e, mSettings)) {
setValueType(tok, podtype);
continue;
}
}
const std::string& typestr(mSettings.library.returnValueType(tok->previous()));
if (!typestr.empty()) {
ValueType valuetype;
TokenList tokenList(&mSettings);
std::istringstream istr(typestr+";");
tokenList.createTokens(istr, tok->isCpp() ? Standards::Language::CPP : Standards::Language::C); // TODO: check result?
tokenList.simplifyStdType();
if (parsedecl(tokenList.front(), &valuetype, mDefaultSignedness, mSettings)) {
valuetype.originalTypeName = typestr;
setValueType(tok, valuetype);
}
}
//Is iterator fetching function invoked on container?
const bool isReturnIter = typestr == "iterator";
if (typestr.empty() || isReturnIter) {
if (Token::simpleMatch(tok->astOperand1(), ".") &&
tok->astOperand1()->astOperand1() &&
tok->astOperand1()->astOperand2() &&
tok->astOperand1()->astOperand1()->valueType() &&
tok->astOperand1()->astOperand1()->valueType()->container) {
const Library::Container *cont = tok->astOperand1()->astOperand1()->valueType()->container;
const auto it = cont->functions.find(tok->astOperand1()->astOperand2()->str());
if (it != cont->functions.end()) {
if (it->second.yield == Library::Container::Yield::START_ITERATOR ||
it->second.yield == Library::Container::Yield::END_ITERATOR ||
it->second.yield == Library::Container::Yield::ITERATOR) {
ValueType vt;
vt.type = ValueType::Type::ITERATOR;
vt.container = cont;
vt.containerTypeToken =
tok->astOperand1()->astOperand1()->valueType()->containerTypeToken;
setValueType(tok, vt);
continue;
}
}
//Is iterator fetching function called?
} else if (Token::simpleMatch(tok->astOperand1(), "::") &&
tok->astOperand2() &&
tok->astOperand2()->isVariable()) {
const auto* const paramVariable = tok->astOperand2()->variable();
if (!paramVariable ||
!paramVariable->valueType() ||
!paramVariable->valueType()->container) {
continue;
}
const auto yield = astFunctionYield(tok->previous(), mSettings);
if (yield == Library::Container::Yield::START_ITERATOR ||
yield == Library::Container::Yield::END_ITERATOR ||
yield == Library::Container::Yield::ITERATOR) {
ValueType vt;
vt.type = ValueType::Type::ITERATOR;
vt.container = paramVariable->valueType()->container;
vt.containerTypeToken = paramVariable->valueType()->containerTypeToken;
setValueType(tok, vt);
}
}
if (isReturnIter) {
const std::vector<const Token*> args = getArguments(tok);
if (!args.empty()) {
const Library::ArgumentChecks::IteratorInfo* info = mSettings.library.getArgIteratorInfo(tok->previous(), 1);
if (info && info->it) {
const Token* contTok = args[0];
if (Token::simpleMatch(args[0]->astOperand1(), ".") && args[0]->astOperand1()->astOperand1()) // .begin()
contTok = args[0]->astOperand1()->astOperand1();
else if (Token::simpleMatch(args[0], "(") && args[0]->astOperand2()) // std::begin()
contTok = args[0]->astOperand2();
while (Token::simpleMatch(contTok, "[")) // move to container token
contTok = contTok->astOperand1();
if (Token::simpleMatch(contTok, "."))
contTok = contTok->astOperand2();
if (contTok && contTok->variable() && contTok->variable()->valueType() && contTok->variable()->valueType()->container) {
ValueType vt;
vt.type = ValueType::Type::ITERATOR;
vt.container = contTok->variable()->valueType()->container;
vt.containerTypeToken = contTok->variable()->valueType()->containerTypeToken;
setValueType(tok, vt);
} else if (Token::simpleMatch(contTok, "(") && contTok->astOperand1() && contTok->astOperand1()->function()) {
const Function* func = contTok->astOperand1()->function();
if (const ValueType* funcVt = func->tokenDef->next()->valueType()) {
ValueType vt;
vt.type = ValueType::Type::ITERATOR;
vt.container = funcVt->container;
vt.containerTypeToken = funcVt->containerTypeToken;
setValueType(tok, vt);
}
}
}
}
}
continue;
}
TokenList tokenList(&mSettings);
std::istringstream istr(typestr+";");
if (tokenList.createTokens(istr, tok->isCpp() ? Standards::Language::CPP : Standards::Language::C)) {
ValueType vt;
tokenList.simplifyPlatformTypes();
tokenList.simplifyStdType();
if (parsedecl(tokenList.front(), &vt, mDefaultSignedness, mSettings)) {
vt.originalTypeName = typestr;
setValueType(tok, vt);
}
}
}
} else if (tok->str() == "return") {
const Scope *functionScope = tok->scope();
while (functionScope && functionScope->isExecutable() && functionScope->type != Scope::eLambda && functionScope->type != Scope::eFunction)
functionScope = functionScope->nestedIn;
if (functionScope && functionScope->type == Scope::eFunction && functionScope->function &&
functionScope->function->retDef) {
ValueType vt = ValueType::parseDecl(functionScope->function->retDef, mSettings);
setValueType(tok, vt);
if (Token::simpleMatch(tok, "return {"))
setValueType(tok->next(), vt);
}
} else if (tok->variable()) {
setValueType(tok, *tok->variable());
if (!tok->variable()->valueType() && tok->valueType())
const_cast<Variable*>(tok->variable())->setValueType(*tok->valueType());
} else if (tok->enumerator()) {
setValueType(tok, *tok->enumerator());
} else if (tok->isKeyword() && tok->str() == "new") {
const Token *typeTok = tok->next();
if (Token::Match(typeTok, "( std| ::| nothrow )"))
typeTok = typeTok->link()->next();
bool isIterator = false;
if (const Library::Container* c = mSettings.library.detectContainerOrIterator(typeTok, &isIterator)) {
ValueType vt;
vt.pointer = 1;
vt.container = c;
vt.type = isIterator ? ValueType::Type::ITERATOR : ValueType::Type::CONTAINER;
setValueType(tok, vt);
continue;
}
std::string typestr;
while (Token::Match(typeTok, "%name% :: %name%")) {
typestr += typeTok->str() + "::";
typeTok = typeTok->tokAt(2);
}
if (!Token::Match(typeTok, "%type% ;|[|("))
continue;
typestr += typeTok->str();
ValueType vt;
vt.pointer = 1;
if (typeTok->type() && typeTok->type()->classScope) {
vt.type = ValueType::Type::RECORD;
vt.typeScope = typeTok->type()->classScope;
} else {
vt.type = ValueType::typeFromString(typestr, typeTok->isLong());
if (vt.type == ValueType::Type::UNKNOWN_TYPE)
vt.fromLibraryType(typestr, mSettings);
if (vt.type == ValueType::Type::UNKNOWN_TYPE)
continue;
if (typeTok->isUnsigned())
vt.sign = ValueType::Sign::UNSIGNED;
else if (typeTok->isSigned())
vt.sign = ValueType::Sign::SIGNED;
if (vt.sign == ValueType::Sign::UNKNOWN_SIGN && vt.isIntegral())
vt.sign = (vt.type == ValueType::Type::CHAR) ? mDefaultSignedness : ValueType::Sign::SIGNED;
}
setValueType(tok, vt);
if (Token::simpleMatch(tok->astOperand1(), "(")) {
vt.pointer--;
setValueType(tok->astOperand1(), vt);
}
} else if (tok->isKeyword() && tok->str() == "return" && tok->scope()) {
const Scope* fscope = tok->scope();
while (fscope && !fscope->function)
fscope = fscope->nestedIn;
if (fscope && fscope->function && fscope->function->retDef) {
ValueType vt;
parsedecl(fscope->function->retDef, &vt, mDefaultSignedness, mSettings);
setValueType(tok, vt);
}
} else if (tok->isKeyword() && tok->str() == "this" && tok->scope()->isExecutable()) {
const Scope* fscope = tok->scope();
while (fscope && !fscope->function)
fscope = fscope->nestedIn;
const Scope* defScope = fscope && fscope->function->tokenDef ? fscope->function->tokenDef->scope() : nullptr;
if (defScope && defScope->isClassOrStruct()) {
ValueType vt(ValueType::Sign::UNKNOWN_SIGN, ValueType::Type::RECORD, 1);
vt.typeScope = defScope;
if (fscope->function->isConst())
vt.constness = 1;
if (fscope->function->isVolatile())
vt.volatileness = 1;
setValueType(tok, vt);
}
}
}
if (reportDebugWarnings && mSettings.debugwarnings) {
for (Token *tok = tokens; tok; tok = tok->next()) {
if (tok->str() == "auto" && !tok->valueType()) {
if (Token::Match(tok->next(), "%name% ; %name% = [") && isLambdaCaptureList(tok->tokAt(5)))
continue;
if (Token::Match(tok->next(), "%name% {|= [") && isLambdaCaptureList(tok->tokAt(3)))
continue;
debugMessage(tok, "autoNoType", "auto token with no type.");
}
}
}
// Update functions with new type information.
createSymbolDatabaseSetFunctionPointers(false);
// Update auto variables with new type information.
createSymbolDatabaseSetVariablePointers();
}
ValueType ValueType::parseDecl(const Token *type, const Settings &settings)
{
ValueType vt;
parsedecl(type, &vt, settings.platform.defaultSign == 'u' ? Sign::UNSIGNED : Sign::SIGNED, settings);
return vt;
}
ValueType::Type ValueType::typeFromString(const std::string &typestr, bool longType)
{
if (typestr == "void")
return ValueType::Type::VOID;
if (typestr == "bool" || typestr == "_Bool")
return ValueType::Type::BOOL;
if (typestr== "char")
return ValueType::Type::CHAR;
if (typestr == "short")
return ValueType::Type::SHORT;
if (typestr == "wchar_t")
return ValueType::Type::WCHAR_T;
if (typestr == "int")
return ValueType::Type::INT;
if (typestr == "long")
return longType ? ValueType::Type::LONGLONG : ValueType::Type::LONG;
if (typestr == "float")
return ValueType::Type::FLOAT;
if (typestr == "double")
return longType ? ValueType::Type::LONGDOUBLE : ValueType::Type::DOUBLE;
return ValueType::Type::UNKNOWN_TYPE;
}
bool ValueType::fromLibraryType(const std::string &typestr, const Settings &settings)
{
const Library::PodType* podtype = settings.library.podtype(typestr);
if (podtype && (podtype->sign == 's' || podtype->sign == 'u')) {
if (podtype->size == 1)
type = ValueType::Type::CHAR;
else if (podtype->size == settings.platform.sizeof_int)
type = ValueType::Type::INT;
else if (podtype->size == settings.platform.sizeof_short)
type = ValueType::Type::SHORT;
else if (podtype->size == settings.platform.sizeof_long)
type = ValueType::Type::LONG;
else if (podtype->size == settings.platform.sizeof_long_long)
type = ValueType::Type::LONGLONG;
else if (podtype->stdtype == Library::PodType::Type::BOOL)
type = ValueType::Type::BOOL;
else if (podtype->stdtype == Library::PodType::Type::CHAR)
type = ValueType::Type::CHAR;
else if (podtype->stdtype == Library::PodType::Type::SHORT)
type = ValueType::Type::SHORT;
else if (podtype->stdtype == Library::PodType::Type::INT)
type = ValueType::Type::INT;
else if (podtype->stdtype == Library::PodType::Type::LONG)
type = ValueType::Type::LONG;
else if (podtype->stdtype == Library::PodType::Type::LONGLONG)
type = ValueType::Type::LONGLONG;
else
type = ValueType::Type::UNKNOWN_INT;
sign = (podtype->sign == 'u') ? ValueType::UNSIGNED : ValueType::SIGNED;
return true;
}
if (podtype && podtype->stdtype == Library::PodType::Type::NO) {
type = ValueType::Type::POD;
sign = ValueType::UNKNOWN_SIGN;
return true;
}
const Library::PlatformType *platformType = settings.library.platform_type(typestr, settings.platform.toString());
if (platformType) {
if (platformType->mType == "char")
type = ValueType::Type::CHAR;
else if (platformType->mType == "short")
type = ValueType::Type::SHORT;
else if (platformType->mType == "wchar_t")
type = ValueType::Type::WCHAR_T;
else if (platformType->mType == "int")
type = platformType->mLong ? ValueType::Type::LONG : ValueType::Type::INT;
else if (platformType->mType == "long")
type = platformType->mLong ? ValueType::Type::LONGLONG : ValueType::Type::LONG;
if (platformType->mSigned)
sign = ValueType::SIGNED;
else if (platformType->mUnsigned)
sign = ValueType::UNSIGNED;
if (platformType->mPointer)
pointer = 1;
if (platformType->mPtrPtr)
pointer = 2;
if (platformType->mConstPtr)
constness = 1;
return true;
}
if (!podtype && (typestr == "size_t" || typestr == "std::size_t")) {
originalTypeName = "size_t";
sign = ValueType::UNSIGNED;
if (settings.platform.sizeof_size_t == settings.platform.sizeof_long)
type = ValueType::Type::LONG;
else if (settings.platform.sizeof_size_t == settings.platform.sizeof_long_long)
type = ValueType::Type::LONGLONG;
else if (settings.platform.sizeof_size_t == settings.platform.sizeof_int)
type = ValueType::Type::INT;
else
type = ValueType::Type::UNKNOWN_INT;
return true;
}
return false;
}
std::string ValueType::dump() const
{
std::string ret;
switch (type) {
case UNKNOWN_TYPE:
return "";
case NONSTD:
ret += "valueType-type=\"nonstd\"";
break;
case POD:
ret += "valueType-type=\"pod\"";
break;
case RECORD:
ret += "valueType-type=\"record\"";
break;
case SMART_POINTER:
ret += "valueType-type=\"smart-pointer\"";
break;
case CONTAINER: {
ret += "valueType-type=\"container\"";
ret += " valueType-containerId=\"";
ret += id_string(container);
ret += "\"";
break;
}
case ITERATOR:
ret += "valueType-type=\"iterator\"";
break;
case VOID:
ret += "valueType-type=\"void\"";
break;
case BOOL:
ret += "valueType-type=\"bool\"";
break;
case CHAR:
ret += "valueType-type=\"char\"";
break;
case SHORT:
ret += "valueType-type=\"short\"";
break;
case WCHAR_T:
ret += "valueType-type=\"wchar_t\"";
break;
case INT:
ret += "valueType-type=\"int\"";
break;
case LONG:
ret += "valueType-type=\"long\"";
break;
case LONGLONG:
ret += "valueType-type=\"long long\"";
break;
case UNKNOWN_INT:
ret += "valueType-type=\"unknown int\"";
break;
case FLOAT:
ret += "valueType-type=\"float\"";
break;
case DOUBLE:
ret += "valueType-type=\"double\"";
break;
case LONGDOUBLE:
ret += "valueType-type=\"long double\"";
break;
}
switch (sign) {
case Sign::UNKNOWN_SIGN:
break;
case Sign::SIGNED:
ret += " valueType-sign=\"signed\"";
break;
case Sign::UNSIGNED:
ret += " valueType-sign=\"unsigned\"";
break;
}
if (bits > 0) {
ret += " valueType-bits=\"";
ret += std::to_string(bits);
ret += '\"';
}
if (pointer > 0) {
ret += " valueType-pointer=\"";
ret += std::to_string(pointer);
ret += '\"';
}
if (constness > 0) {
ret += " valueType-constness=\"";
ret += std::to_string(constness);
ret += '\"';
}
if (volatileness > 0) {
ret += " valueType-volatileness=\"";
ret += std::to_string(volatileness);
ret += '\"';
}
if (reference == Reference::None)
ret += " valueType-reference=\"None\"";
else if (reference == Reference::LValue)
ret += " valueType-reference=\"LValue\"";
else if (reference == Reference::RValue)
ret += " valueType-reference=\"RValue\"";
if (typeScope) {
ret += " valueType-typeScope=\"";
ret += id_string(typeScope);
ret += '\"';
}
if (!originalTypeName.empty()) {
ret += " valueType-originalTypeName=\"";
ret += ErrorLogger::toxml(originalTypeName);
ret += '\"';
}
return ret;
}
bool ValueType::isConst(nonneg int indirect) const
{
if (indirect > pointer)
return false;
return constness & (1 << (pointer - indirect));
}
bool ValueType::isVolatile(nonneg int indirect) const
{
if (indirect > pointer)
return false;
return volatileness & (1 << (pointer - indirect));
}
MathLib::bigint ValueType::typeSize(const Platform &platform, bool p) const
{
if (p && pointer)
return platform.sizeof_pointer;
if (typeScope && typeScope->definedType && typeScope->definedType->sizeOf)
return typeScope->definedType->sizeOf;
switch (type) {
case ValueType::Type::BOOL:
return platform.sizeof_bool;
case ValueType::Type::CHAR:
return 1;
case ValueType::Type::SHORT:
return platform.sizeof_short;
case ValueType::Type::WCHAR_T:
return platform.sizeof_wchar_t;
case ValueType::Type::INT:
return platform.sizeof_int;
case ValueType::Type::LONG:
return platform.sizeof_long;
case ValueType::Type::LONGLONG:
return platform.sizeof_long_long;
case ValueType::Type::FLOAT:
return platform.sizeof_float;
case ValueType::Type::DOUBLE:
return platform.sizeof_double;
case ValueType::Type::LONGDOUBLE:
return platform.sizeof_long_double;
default:
break;
}
// Unknown invalid size
return 0;
}
bool ValueType::isTypeEqual(const ValueType* that) const
{
if (!that)
return false;
auto tie = [](const ValueType* vt) {
return std::tie(vt->type, vt->container, vt->pointer, vt->typeScope, vt->smartPointer);
};
return tie(this) == tie(that);
}
std::string ValueType::str() const
{
std::string ret;
if (constness & 1)
ret = " const";
if (volatileness & 1)
ret = " volatile";
if (type == VOID)
ret += " void";
else if (isIntegral()) {
if (sign == SIGNED)
ret += " signed";
else if (sign == UNSIGNED)
ret += " unsigned";
if (type == BOOL)
ret += " bool";
else if (type == CHAR)
ret += " char";
else if (type == SHORT)
ret += " short";
else if (type == WCHAR_T)
ret += " wchar_t";
else if (type == INT)
ret += " int";
else if (type == LONG)
ret += " long";
else if (type == LONGLONG)
ret += " long long";
else if (type == UNKNOWN_INT)
ret += " unknown_int";
} else if (type == FLOAT)
ret += " float";
else if (type == DOUBLE)
ret += " double";
else if (type == LONGDOUBLE)
ret += " long double";
else if ((type == ValueType::Type::NONSTD || type == ValueType::Type::RECORD) && typeScope) {
std::string className(typeScope->className);
const Scope *scope = typeScope->definedType ? typeScope->definedType->enclosingScope : typeScope->nestedIn;
while (scope && scope->type != Scope::eGlobal) {
if (scope->type == Scope::eClass || scope->type == Scope::eStruct || scope->type == Scope::eNamespace)
className = scope->className + "::" + className;
scope = (scope->definedType && scope->definedType->enclosingScope) ? scope->definedType->enclosingScope : scope->nestedIn;
}
ret += ' ' + className;
} else if (type == ValueType::Type::CONTAINER && container) {
ret += " container(" + container->startPattern + ')';
} else if (type == ValueType::Type::ITERATOR && container) {
ret += " iterator(" + container->startPattern + ')';
} else if (type == ValueType::Type::SMART_POINTER && smartPointer) {
ret += " smart-pointer(" + smartPointer->name + ")";
}
for (unsigned int p = 0; p < pointer; p++) {
ret += " *";
if (constness & (2 << p))
ret += " const";
if (volatileness & (2 << p))
ret += " volatile";
}
if (reference == Reference::LValue)
ret += " &";
else if (reference == Reference::RValue)
ret += " &&";
if (ret.empty())
return ret;
return ret.substr(1);
}
void ValueType::setDebugPath(const Token* tok, SourceLocation ctx, const SourceLocation &local)
{
std::string file = ctx.file_name();
if (file.empty())
return;
std::string s = Path::stripDirectoryPart(file) + ":" + std::to_string(ctx.line()) + ": " + ctx.function_name() +
" => " + local.function_name();
debugPath.emplace_back(tok, std::move(s));
}
ValueType::MatchResult ValueType::matchParameter(const ValueType *call, const ValueType *func)
{
if (!call || !func)
return ValueType::MatchResult::UNKNOWN;
if (call->pointer != func->pointer) {
if (call->pointer > 1 && func->pointer == 1 && func->type == ValueType::Type::VOID)
return ValueType::MatchResult::FALLBACK1;
if (call->pointer == 1 && func->pointer == 0 && func->isIntegral() && func->sign != ValueType::Sign::SIGNED)
return ValueType::MatchResult::FALLBACK1;
if (call->pointer == 1 && call->type == ValueType::Type::CHAR && func->pointer == 0 && func->container && func->container->stdStringLike)
return ValueType::MatchResult::FALLBACK2;
return ValueType::MatchResult::NOMATCH; // TODO
}
if (call->pointer > 0) {
if ((call->constness | func->constness) != func->constness)
return ValueType::MatchResult::NOMATCH;
if ((call->volatileness | func->volatileness) != func->volatileness)
return ValueType::MatchResult::NOMATCH;
if (call->constness == 0 && func->constness != 0 && func->reference != Reference::None)
return ValueType::MatchResult::NOMATCH;
if (call->volatileness == 0 && func->volatileness != 0 && func->reference != Reference::None)
return ValueType::MatchResult::NOMATCH;
}
if (call->type != func->type || (call->isEnum() && !func->isEnum())) {
if (call->type == ValueType::Type::VOID || func->type == ValueType::Type::VOID)
return ValueType::MatchResult::FALLBACK1;
if (call->pointer > 0)
return func->type == ValueType::UNKNOWN_TYPE ? ValueType::MatchResult::UNKNOWN : ValueType::MatchResult::NOMATCH;
if (call->isIntegral() && func->isIntegral())
return call->type < func->type ?
ValueType::MatchResult::FALLBACK1 :
ValueType::MatchResult::FALLBACK2;
if (call->isFloat() && func->isFloat())
return ValueType::MatchResult::FALLBACK1;
if (call->isIntegral() && func->isFloat())
return ValueType::MatchResult::FALLBACK2;
if (call->isFloat() && func->isIntegral())
return ValueType::MatchResult::FALLBACK2;
return ValueType::MatchResult::UNKNOWN; // TODO
}
if (call->typeScope != nullptr || func->typeScope != nullptr) {
if (call->typeScope != func->typeScope &&
!(call->typeScope && func->typeScope && call->typeScope->definedType && call->typeScope->definedType->isDerivedFrom(func->typeScope->className)))
return ValueType::MatchResult::NOMATCH;
}
if (call->container != nullptr || func->container != nullptr) {
if (call->container != func->container)
return ValueType::MatchResult::NOMATCH;
}
if (func->typeScope != nullptr && func->container != nullptr) {
if (func->type < ValueType::Type::VOID || func->type == ValueType::Type::UNKNOWN_INT)
return ValueType::MatchResult::UNKNOWN;
}
if (call->isIntegral() && func->isIntegral() && call->sign != ValueType::Sign::UNKNOWN_SIGN && func->sign != ValueType::Sign::UNKNOWN_SIGN && call->sign != func->sign)
return ValueType::MatchResult::FALLBACK1;
if (func->reference != Reference::None && (func->constness > call->constness || func->volatileness > call->volatileness))
return ValueType::MatchResult::FALLBACK1;
return ValueType::MatchResult::SAME;
}
ValueType::MatchResult ValueType::matchParameter(const ValueType *call, const Variable *callVar, const Variable *funcVar)
{
ValueType vt;
const ValueType* pvt = funcVar->valueType();
if (pvt && funcVar->isArray() && !(funcVar->isStlType() && Token::simpleMatch(funcVar->typeStartToken(), "std :: array"))) { // std::array doesn't decay to a pointer
vt = *pvt;
if (vt.pointer == 0) // don't bump array of pointers
vt.pointer = funcVar->dimensions().size();
pvt = &vt;
}
ValueType cvt;
if (call && callVar && callVar->isArray() && !(callVar->isStlType() && Token::simpleMatch(callVar->typeStartToken(), "std :: array"))) {
cvt = *call;
if (cvt.pointer == 0) // don't bump array of pointers
cvt.pointer = callVar->dimensions().size();
call = &cvt;
}
const ValueType::MatchResult res = ValueType::matchParameter(call, pvt);
if (callVar && ((res == ValueType::MatchResult::SAME && call->container) || res == ValueType::MatchResult::UNKNOWN)) {
const std::string type1 = getTypeString(callVar->typeStartToken());
const std::string type2 = getTypeString(funcVar->typeStartToken());
const bool templateVar =
funcVar->scope() && funcVar->scope()->function && funcVar->scope()->function->templateDef;
if (type1 == type2)
return ValueType::MatchResult::SAME;
if (!templateVar && type1.find("auto") == std::string::npos && type2.find("auto") == std::string::npos)
return ValueType::MatchResult::NOMATCH;
}
return res;
}
| null |
919 | cpp | cppcheck | valueflow.h | lib/valueflow.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef valueflowH
#define valueflowH
//---------------------------------------------------------------------------
#include "config.h"
#include "errortypes.h"
#include "mathlib.h"
#include "vfvalue.h"
#include <cstdlib>
#include <functional>
#include <list>
#include <string>
#include <utility>
#include <vector>
class ErrorLogger;
class Settings;
class SymbolDatabase;
class TimerResultsIntf;
class Token;
class TokenList;
class ValueType;
class Variable;
class Scope;
namespace ValueFlow {
/// Constant folding of expression. This can be used before the full ValueFlow has been executed (ValueFlow::setValues).
const Value * valueFlowConstantFoldAST(Token *expr, const Settings &settings);
/// Perform valueflow analysis.
void setValues(TokenList& tokenlist,
SymbolDatabase& symboldatabase,
ErrorLogger& errorLogger,
const Settings& settings,
TimerResultsIntf* timerResults);
std::string eitherTheConditionIsRedundant(const Token *condition);
size_t getSizeOf(const ValueType &vt, const Settings &settings, int maxRecursion = 0);
const Value* findValue(const std::list<Value>& values,
const Settings& settings,
const std::function<bool(const Value&)> &pred);
std::vector<Value> isOutOfBounds(const Value& size, const Token* indexTok, bool possible = true);
Value asImpossible(Value v);
bool isContainerSizeChanged(const Token* tok, int indirect, const Settings& settings, int depth = 20);
struct LifetimeToken {
const Token* token{};
ErrorPath errorPath;
bool addressOf{};
bool inconclusive{};
LifetimeToken() = default;
LifetimeToken(const Token* token, ErrorPath errorPath)
: token(token), errorPath(std::move(errorPath))
{}
LifetimeToken(const Token* token, bool addressOf, ErrorPath errorPath)
: token(token), errorPath(std::move(errorPath)), addressOf(addressOf)
{}
static std::vector<LifetimeToken> setAddressOf(std::vector<LifetimeToken> v, bool b) {
for (LifetimeToken& x : v)
x.addressOf = b;
return v;
}
static std::vector<LifetimeToken> setInconclusive(std::vector<LifetimeToken> v, bool b) {
for (LifetimeToken& x : v)
x.inconclusive = b;
return v;
}
};
const Token *parseCompareInt(const Token *tok, Value &true_value, Value &false_value, const std::function<std::vector<MathLib::bigint>(const Token*)>& evaluate);
const Token *parseCompareInt(const Token *tok, Value &true_value, Value &false_value);
const Token* solveExprValue(const Token* expr,
const std::function<std::vector<MathLib::bigint>(const Token*)>& eval,
Value& value);
std::vector<LifetimeToken> getLifetimeTokens(const Token* tok,
const Settings& settings,
bool escape = false,
ErrorPath errorPath = ErrorPath{});
bool hasLifetimeToken(const Token* tok, const Token* lifetime, const Settings& settings);
const Variable* getLifetimeVariable(const Token* tok, ErrorPath& errorPath, const Settings& settings, bool* addressOf = nullptr);
const Variable* getLifetimeVariable(const Token* tok, const Settings& settings);
bool isLifetimeBorrowed(const Token *tok, const Settings &settings);
std::string lifetimeMessage(const Token *tok, const Value *val, ErrorPath &errorPath);
CPPCHECKLIB Value getLifetimeObjValue(const Token *tok, bool inconclusive = false);
CPPCHECKLIB std::vector<Value> getLifetimeObjValues(const Token* tok,
bool inconclusive = false,
MathLib::bigint path = 0);
const Token* getEndOfExprScope(const Token* tok, const Scope* defaultScope = nullptr, bool smallest = true);
void combineValueProperties(const Value& value1, const Value& value2, Value& result);
}
#endif // valueflowH
| null |
920 | cpp | cppcheck | checkinternal.cpp | lib/checkinternal.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef CHECK_INTERNAL
#include "checkinternal.h"
#include "astutils.h"
#include "symboldatabase.h"
#include "token.h"
#include "tokenize.h"
#include <cstring>
#include <set>
#include <vector>
// Register this check class (by creating a static instance of it).
// Disabled in release builds
namespace {
CheckInternal instance;
}
void CheckInternal::checkTokenMatchPatterns()
{
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope *scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (!Token::simpleMatch(tok, "Token :: Match (") && !Token::simpleMatch(tok, "Token :: findmatch ("))
continue;
const std::string& funcname = tok->strAt(2);
// Get pattern string
const Token *patternTok = tok->tokAt(4)->nextArgument();
if (!patternTok || patternTok->tokType() != Token::eString)
continue;
const std::string pattern = patternTok->strValue();
if (pattern.empty()) {
simplePatternError(tok, pattern, funcname);
continue;
}
if (pattern.find("||") != std::string::npos || pattern.find(" | ") != std::string::npos || pattern[0] == '|' || (pattern[pattern.length() - 1] == '|' && pattern[pattern.length() - 2] == ' '))
orInComplexPattern(tok, pattern, funcname);
// Check for signs of complex patterns
if (pattern.find_first_of("[|") != std::string::npos)
continue;
if (pattern.find("!!") != std::string::npos)
continue;
bool complex = false;
size_t index = pattern.find('%');
while (index != std::string::npos) {
if (pattern.length() <= index + 2) {
complex = true;
break;
}
if (pattern[index + 1] == 'o' && pattern[index + 2] == 'r') // %or% or %oror%
index = pattern.find('%', index + 1);
else {
complex = true;
break;
}
index = pattern.find('%', index + 1);
}
if (!complex)
simplePatternError(tok, pattern, funcname);
}
}
}
void CheckInternal::checkRedundantTokCheck()
{
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (Token::Match(tok, "&& Token :: simpleMatch|Match|findsimplematch|findmatch (")) {
// in code like
// if (tok->previous() && Token::match(tok->previous(), "bla")) {}
// the first tok->previous() check is redundant
const Token *astOp1 = tok->astOperand1();
const Token *astOp2 = getArguments(tok->tokAt(3))[0];
if (Token::simpleMatch(astOp1, "&&")) {
astOp1 = astOp1->astOperand2();
}
if (astOp1->expressionString() == astOp2->expressionString()) {
checkRedundantTokCheckError(astOp2);
}
// if (!tok || !Token::match(tok, "foo"))
} else if (Token::Match(tok, "%oror% ! Token :: simpleMatch|Match|findsimplematch|findmatch (")) {
const Token *negTok = tok->next()->astParent()->astOperand1();
if (Token::simpleMatch(negTok, "||")) {
negTok = negTok->astOperand2();
}
// the first tok condition is negated
if (Token::simpleMatch(negTok, "!")) {
const Token *astOp1 = negTok->astOperand1();
const Token *astOp2 = getArguments(tok->tokAt(4))[0];
if (astOp1->expressionString() == astOp2->expressionString()) {
checkRedundantTokCheckError(astOp2);
}
}
}
}
}
void CheckInternal::checkRedundantTokCheckError(const Token* tok)
{
reportError(tok, Severity::style, "redundantTokCheck",
"Unnecessary check of \"" + (tok? tok->expressionString(): emptyString) + "\", match-function already checks if it is null.");
}
void CheckInternal::checkTokenSimpleMatchPatterns()
{
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope* scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (!Token::simpleMatch(tok, "Token :: simpleMatch (") && !Token::simpleMatch(tok, "Token :: findsimplematch ("))
continue;
const std::string& funcname = tok->strAt(2);
// Get pattern string
const Token *patternTok = tok->tokAt(4)->nextArgument();
if (!patternTok || patternTok->tokType() != Token::eString)
continue;
const std::string pattern = patternTok->strValue();
if (pattern.empty()) {
complexPatternError(tok, pattern, funcname);
continue;
}
// Check for [xyz] usage - but exclude standalone square brackets
unsigned int char_count = 0;
for (const char c : pattern) {
if (c == ' ') {
char_count = 0;
} else if (c == ']') {
if (char_count > 0) {
complexPatternError(tok, pattern, funcname);
continue;
}
} else {
++char_count;
}
}
// Check | usage: Count characters before the symbol
char_count = 0;
for (const char c : pattern) {
if (c == ' ') {
char_count = 0;
} else if (c == '|') {
if (char_count > 0) {
complexPatternError(tok, pattern, funcname);
continue;
}
} else {
++char_count;
}
}
// Check for real errors
if (pattern.length() > 1) {
for (size_t j = 0; j < pattern.length() - 1; j++) {
if (pattern[j] == '%' && pattern[j + 1] != ' ')
complexPatternError(tok, pattern, funcname);
else if (pattern[j] == '!' && pattern[j + 1] == '!')
complexPatternError(tok, pattern, funcname);
}
}
}
}
}
namespace {
const std::set<std::string> knownPatterns = {
"%any%"
, "%assign%"
, "%bool%"
, "%char%"
, "%comp%"
, "%num%"
, "%op%"
, "%cop%"
, "%or%"
, "%oror%"
, "%str%"
, "%type%"
, "%name%"
, "%var%"
, "%varid%"
};
}
void CheckInternal::checkMissingPercentCharacter()
{
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope* scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (!Token::simpleMatch(tok, "Token :: Match (") && !Token::simpleMatch(tok, "Token :: findmatch ("))
continue;
const std::string& funcname = tok->strAt(2);
// Get pattern string
const Token *patternTok = tok->tokAt(4)->nextArgument();
if (!patternTok || patternTok->tokType() != Token::eString)
continue;
const std::string pattern = patternTok->strValue();
std::set<std::string>::const_iterator knownPattern, knownPatternsEnd = knownPatterns.cend();
for (knownPattern = knownPatterns.cbegin(); knownPattern != knownPatternsEnd; ++knownPattern) {
const std::string brokenPattern = knownPattern->substr(0, knownPattern->size() - 1);
std::string::size_type pos = 0;
while ((pos = pattern.find(brokenPattern, pos)) != std::string::npos) {
// Check if it's the full pattern
if (pattern.find(*knownPattern, pos) != pos) {
// Known whitelist of substrings
if ((brokenPattern == "%var" && pattern.find("%varid%", pos) == pos) ||
(brokenPattern == "%or" && pattern.find("%oror%", pos) == pos)) {
++pos;
continue;
}
missingPercentCharacterError(tok, pattern, funcname);
}
++pos;
}
}
}
}
}
void CheckInternal::checkUnknownPattern()
{
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope* scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (!Token::simpleMatch(tok, "Token :: Match (") && !Token::simpleMatch(tok, "Token :: findmatch ("))
continue;
// Get pattern string
const Token *patternTok = tok->tokAt(4)->nextArgument();
if (!patternTok || patternTok->tokType() != Token::eString)
continue;
const std::string pattern = patternTok->strValue();
bool inBrackets = false;
for (std::string::size_type j = 0; j < pattern.length() - 1; j++) {
if (pattern[j] == '[' && (j == 0 || pattern[j - 1] == ' '))
inBrackets = true;
else if (pattern[j] == ']')
inBrackets = false;
else if (pattern[j] == '%' && pattern[j + 1] != ' ' && pattern[j + 1] != '|' && !inBrackets) {
const std::string::size_type end = pattern.find('%', j + 1);
if (end != std::string::npos) {
const std::string s = pattern.substr(j, end - j + 1);
if (knownPatterns.find(s) == knownPatterns.end())
unknownPatternError(tok, s);
}
}
}
}
}
}
void CheckInternal::checkRedundantNextPrevious()
{
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope* scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (tok->str() != ".")
continue;
tok = tok->next();
if (Token::Match(tok, "previous ( ) . previous|next|tokAt|str|strAt|link|linkAt (") || Token::Match(tok, "next ( ) . previous|next|tokAt|str|strAt|link|linkAt (") ||
(Token::simpleMatch(tok, "tokAt (") && Token::Match(tok->linkAt(1), ") . previous|next|tokAt|strAt|linkAt|str|link ("))) {
const std::string& func1 = tok->str();
const std::string& func2 = tok->linkAt(1)->strAt(2);
if ((func2 == "previous" || func2 == "next" || func2 == "str" || func2 == "link") && tok->linkAt(1)->strAt(4) != ")")
continue;
redundantNextPreviousError(tok, func1, func2);
}
}
}
}
void CheckInternal::checkExtraWhitespace()
{
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope* scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (!Token::Match(tok, "Token :: simpleMatch|findsimplematch|Match|findmatch ("))
continue;
const std::string& funcname = tok->strAt(2);
// Get pattern string
const Token *patternTok = tok->tokAt(4)->nextArgument();
if (!patternTok || patternTok->tokType() != Token::eString)
continue;
const std::string pattern = patternTok->strValue();
if (!pattern.empty() && (pattern[0] == ' ' || *pattern.crbegin() == ' '))
extraWhitespaceError(tok, pattern, funcname);
// two whitespaces or more
if (pattern.find(" ") != std::string::npos)
extraWhitespaceError(tok, pattern, funcname);
}
}
}
void CheckInternal::multiComparePatternError(const Token* tok, const std::string& pattern, const std::string &funcname)
{
reportError(tok, Severity::error, "multiComparePatternError",
"Bad multicompare pattern (a %cmd% must be first unless it is %or%,%op%,%cop%,%name%,%oror%) inside Token::" + funcname + "() call: \"" + pattern + "\""
);
}
void CheckInternal::simplePatternError(const Token* tok, const std::string& pattern, const std::string &funcname)
{
reportError(tok, Severity::warning, "simplePatternError",
"Found simple pattern inside Token::" + funcname + "() call: \"" + pattern + "\""
);
}
void CheckInternal::complexPatternError(const Token* tok, const std::string& pattern, const std::string &funcname)
{
reportError(tok, Severity::error, "complexPatternError",
"Found complex pattern inside Token::" + funcname + "() call: \"" + pattern + "\""
);
}
void CheckInternal::missingPercentCharacterError(const Token* tok, const std::string& pattern, const std::string& funcname)
{
reportError(tok, Severity::error, "missingPercentCharacter",
"Missing percent end character in Token::" + funcname + "() pattern: \"" + pattern + "\""
);
}
void CheckInternal::unknownPatternError(const Token* tok, const std::string& pattern)
{
reportError(tok, Severity::error, "unknownPattern",
"Unknown pattern used: \"" + pattern + "\"");
}
void CheckInternal::redundantNextPreviousError(const Token* tok, const std::string& func1, const std::string& func2)
{
reportError(tok, Severity::style, "redundantNextPrevious",
"Call to 'Token::" + func1 + "()' followed by 'Token::" + func2 + "()' can be simplified.");
}
void CheckInternal::orInComplexPattern(const Token* tok, const std::string& pattern, const std::string &funcname)
{
reportError(tok, Severity::error, "orInComplexPattern",
"Token::" + funcname + "() pattern \"" + pattern + "\" contains \"||\" or \"|\". Replace it by \"%oror%\" or \"%or%\".");
}
void CheckInternal::extraWhitespaceError(const Token* tok, const std::string& pattern, const std::string &funcname)
{
reportError(tok, Severity::warning, "extraWhitespaceError",
"Found extra whitespace inside Token::" + funcname + "() call: \"" + pattern + "\""
);
}
#endif // #ifdef CHECK_INTERNAL
| null |
921 | cpp | cppcheck | token.h | lib/token.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef tokenH
#define tokenH
//---------------------------------------------------------------------------
#include "config.h"
#include "errortypes.h"
#include "mathlib.h"
#include "templatesimplifier.h"
#include "utils.h"
#include "vfvalue.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <cstddef>
#include <functional>
#include <list>
#include <memory>
#include <ostream>
#include <set>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
struct Enumerator;
class Function;
class Scope;
class Settings;
class Type;
class ValueType;
class Variable;
class ConstTokenRange;
class Token;
struct TokensFrontBack;
struct ScopeInfo2 {
ScopeInfo2(std::string name_, const Token *bodyEnd_, std::set<std::string> usingNamespaces_ = std::set<std::string>()) : name(std::move(name_)), bodyEnd(bodyEnd_), usingNamespaces(std::move(usingNamespaces_)) {}
std::string name;
const Token* const bodyEnd{};
std::set<std::string> usingNamespaces;
};
enum class TokenDebug : std::uint8_t { None, ValueFlow, ValueType };
struct TokenImpl {
nonneg int mVarId{};
nonneg int mFileIndex{};
nonneg int mLineNumber{};
nonneg int mColumn{};
nonneg int mExprId{};
/**
* A value from 0-100 that provides a rough idea about where in the token
* list this token is located.
*/
nonneg int mProgressValue{};
/**
* Token index. Position in token list
*/
nonneg int mIndex{};
/** Bitfield bit count. */
unsigned char mBits{};
// AST..
Token* mAstOperand1{};
Token* mAstOperand2{};
Token* mAstParent{};
// symbol database information
const Scope* mScope{};
union {
const Function *mFunction;
const Variable *mVariable;
const ::Type* mType;
const Enumerator *mEnumerator;
};
// original name like size_t
std::string* mOriginalName{};
// If this token came from a macro replacement list, this is the name of that macro
std::string mMacroName;
// ValueType
ValueType* mValueType{};
// ValueFlow
std::list<ValueFlow::Value>* mValues{};
static const std::list<ValueFlow::Value> mEmptyValueList;
// Pointer to a template in the template simplifier
std::set<TemplateSimplifier::TokenAndName*>* mTemplateSimplifierPointers{};
// Pointer to the object representing this token's scope
std::shared_ptr<ScopeInfo2> mScopeInfo;
// __cppcheck_in_range__
struct CppcheckAttributes {
enum Type : std::uint8_t { LOW, HIGH } type = LOW;
MathLib::bigint value{};
CppcheckAttributes* next{};
};
CppcheckAttributes* mCppcheckAttributes{};
// alignas expressions
std::unique_ptr<std::vector<std::string>> mAttributeAlignas;
void addAttributeAlignas(const std::string& a) {
if (!mAttributeAlignas)
mAttributeAlignas = std::unique_ptr<std::vector<std::string>>(new std::vector<std::string>());
if (std::find(mAttributeAlignas->cbegin(), mAttributeAlignas->cend(), a) == mAttributeAlignas->cend())
mAttributeAlignas->push_back(a);
}
std::string mAttributeCleanup;
// For memoization, to speed up parsing of huge arrays #8897
enum class Cpp11init : std::uint8_t { UNKNOWN, CPP11INIT, NOINIT } mCpp11init = Cpp11init::UNKNOWN;
TokenDebug mDebug{};
void setCppcheckAttribute(CppcheckAttributes::Type type, MathLib::bigint value);
bool getCppcheckAttribute(CppcheckAttributes::Type type, MathLib::bigint &value) const;
TokenImpl() : mFunction(nullptr) {}
~TokenImpl();
};
/// @addtogroup Core
/// @{
/**
* @brief The token list that the TokenList generates is a linked-list of this class.
*
* Tokens are stored as strings. The "if", "while", etc are stored in plain text.
* The reason the Token class is needed (instead of using the string class) is that some extra functionality is also needed for tokens:
* - location of the token is stored (fileIndex, linenr, column)
* - functions for classifying the token (isName, isNumber, isBoolean, isStandardType)
*
* The Token class also has other functions for management of token list, matching tokens, etc.
*/
class CPPCHECKLIB Token {
friend class TestToken;
private:
TokensFrontBack& mTokensFrontBack;
public:
Token(const Token &) = delete;
Token& operator=(const Token &) = delete;
enum Type : std::uint8_t {
eVariable, eType, eFunction, eKeyword, eName, // Names: Variable (varId), Type (typeId, later), Function (FuncId, later), Language keyword, Name (unknown identifier)
eNumber, eString, eChar, eBoolean, eLiteral, eEnumerator, // Literals: Number, String, Character, Boolean, User defined literal (C++11), Enumerator
eArithmeticalOp, eComparisonOp, eAssignmentOp, eLogicalOp, eBitOp, eIncDecOp, eExtendedOp, // Operators: Arithmetical, Comparison, Assignment, Logical, Bitwise, ++/--, Extended
eBracket, // {, }, <, >: < and > only if link() is set. Otherwise they are comparison operators.
eLambda, // A function without a name
eEllipsis, // "..."
eOther,
eNone
};
explicit Token(TokensFrontBack &tokensFrontBack);
// for usage in CheckIO::ArgumentInfo only
explicit Token(const Token *tok);
~Token();
ConstTokenRange until(const Token * t) const;
template<typename T>
void str(T&& s) {
mStr = s;
mImpl->mVarId = 0;
update_property_info();
}
/**
* Concatenate two (quoted) strings. Automatically cuts of the last/first character.
* Example: "hello ""world" -> "hello world". Used by the token simplifier.
*/
void concatStr(std::string const& b);
const std::string &str() const {
return mStr;
}
/**
* Unlink and delete the next 'count' tokens.
*/
void deleteNext(nonneg int count = 1);
/**
* Unlink and delete the previous 'count' tokens.
*/
void deletePrevious(nonneg int count = 1);
/**
* Swap the contents of this token with the next token.
*/
void swapWithNext();
/**
* @return token in given index, related to this token.
* For example index 1 would return next token, and 2
* would return next from that one.
*/
const Token *tokAt(int index) const
{
return tokAtImpl(this, index);
}
Token *tokAt(int index)
{
return tokAtImpl(this, index);
}
/**
* @return the link to the token in given index, related to this token.
* For example index 1 would return the link to next token.
*/
const Token *linkAt(int index) const
{
return linkAtImpl(this, index);
}
Token *linkAt(int index)
{
return linkAtImpl(this, index);
}
/**
* @return String of the token in given index, related to this token.
* If that token does not exist, an empty string is being returned.
*/
const std::string &strAt(int index) const
{
const Token *tok = this->tokAt(index);
return tok ? tok->mStr : emptyString;
}
/**
* Match given token (or list of tokens) to a pattern list.
*
* Possible patterns
* "someRandomText" If token contains "someRandomText".
* @note Use Match() if you want to use flags in patterns
*
* The patterns can be also combined to compare to multiple tokens at once
* by separating tokens with a space, e.g.
* ") void {" will return true if first token is ')' next token
* is "void" and token after that is '{'. If even one of the tokens does
* not match its pattern, false is returned.
*
* @param tok List of tokens to be compared to the pattern
* @param pattern The pattern against which the tokens are compared,
* e.g. "const" or ") void {".
* @return true if given token matches with given pattern
* false if given token does not match with given pattern
*/
template<size_t count>
static bool simpleMatch(const Token *tok, const char (&pattern)[count]) {
return simpleMatch(tok, pattern, count-1);
}
static bool simpleMatch(const Token *tok, const char pattern[], size_t pattern_len);
/**
* Match given token (or list of tokens) to a pattern list.
*
* Possible patterns
* - "%any%" any token
* - "%assign%" a assignment operand
* - "%bool%" true or false
* - "%char%" Any token enclosed in '-character.
* - "%comp%" Any token such that isComparisonOp() returns true.
* - "%cop%" Any token such that isConstOp() returns true.
* - "%name%" any token which is a name, variable or type e.g. "hello" or "int". Also matches keywords.
* - "%num%" Any numeric token, e.g. "23"
* - "%op%" Any token such that isOp() returns true.
* - "%or%" A bitwise-or operator '|'
* - "%oror%" A logical-or operator '||'
* - "%type%" Anything that can be a variable type, e.g. "int". Also matches keywords.
* - "%str%" Any token starting with "-character (C-string).
* - "%var%" Match with token with varId > 0
* - "%varid%" Match with parameter varid
* - "[abc]" Any of the characters 'a' or 'b' or 'c'
* - "int|void|char" Any of the strings, int, void or char
* - "int|void|char|" Any of the strings, int, void or char or no token
* - "!!else" No tokens or any token that is not "else".
* - "someRandomText" If token contains "someRandomText".
*
* multi-compare patterns such as "int|void|char" can contain %%or%, %%oror% and %%op%
* it is recommended to put such an %%cmd% as the first pattern.
* For example: "%var%|%num%|)" means yes to a variable, a number or ')'.
*
* The patterns can be also combined to compare to multiple tokens at once
* by separating tokens with a space, e.g.
* ") const|void {" will return true if first token is ')' next token is either
* "const" or "void" and token after that is '{'. If even one of the tokens does not
* match its pattern, false is returned.
*
* @param tok List of tokens to be compared to the pattern
* @param pattern The pattern against which the tokens are compared,
* e.g. "const" or ") const|volatile| {".
* @param varid if %%varid% is given in the pattern the Token::varId
* will be matched against this argument
* @return true if given token matches with given pattern
* false if given token does not match with given pattern
*/
static bool Match(const Token *tok, const char pattern[], nonneg int varid = 0);
/**
* @return length of C-string.
*
* Should be called for %%str%% tokens only.
*
* @param tok token with C-string
**/
static nonneg int getStrLength(const Token *tok);
/**
* @return array length of C-string.
*
* Should be called for %%str%% tokens only.
*
* @param tok token with C-string
**/
static nonneg int getStrArraySize(const Token *tok);
/**
* @return sizeof of C-string.
*
* Should be called for %%str%% tokens only.
*
* @param tok token with C-string
* @param settings Settings
**/
static nonneg int getStrSize(const Token *tok, const Settings & settings);
const ValueType *valueType() const {
return mImpl->mValueType;
}
void setValueType(ValueType *vt);
const ValueType *argumentType() const;
Token::Type tokType() const {
return mTokType;
}
void tokType(Token::Type t) {
mTokType = t;
const bool memoizedIsName = (mTokType == eName || mTokType == eType || mTokType == eVariable ||
mTokType == eFunction || mTokType == eKeyword || mTokType == eBoolean ||
mTokType == eEnumerator); // TODO: "true"/"false" aren't really a name...
setFlag(fIsName, memoizedIsName);
const bool memoizedIsLiteral = (mTokType == eNumber || mTokType == eString || mTokType == eChar ||
mTokType == eBoolean || mTokType == eLiteral || mTokType == eEnumerator);
setFlag(fIsLiteral, memoizedIsLiteral);
}
bool isKeyword() const {
return mTokType == eKeyword;
}
bool isName() const {
return getFlag(fIsName);
}
bool isNameOnly() const {
return mFlags == fIsName && mTokType == eName;
}
bool isUpperCaseName() const;
bool isLiteral() const {
return getFlag(fIsLiteral);
}
bool isNumber() const {
return mTokType == eNumber;
}
bool isEnumerator() const {
return mTokType == eEnumerator;
}
bool isVariable() const {
return mTokType == eVariable;
}
bool isOp() const {
return (isConstOp() ||
isAssignmentOp() ||
mTokType == eIncDecOp);
}
bool isConstOp() const {
return (isArithmeticalOp() ||
mTokType == eLogicalOp ||
mTokType == eComparisonOp ||
mTokType == eBitOp);
}
bool isExtendedOp() const {
return isConstOp() ||
mTokType == eExtendedOp;
}
bool isArithmeticalOp() const {
return mTokType == eArithmeticalOp;
}
bool isComparisonOp() const {
return mTokType == eComparisonOp;
}
bool isAssignmentOp() const {
return mTokType == eAssignmentOp;
}
bool isBoolean() const {
return mTokType == eBoolean;
}
bool isIncDecOp() const {
return mTokType == eIncDecOp;
}
bool isBinaryOp() const {
return astOperand1() != nullptr && astOperand2() != nullptr;
}
bool isUnaryOp(const std::string &s) const {
return s == mStr && astOperand1() != nullptr && astOperand2() == nullptr;
}
bool isUnaryPreOp() const;
uint64_t flags() const {
return mFlags;
}
void flags(const uint64_t flags_) {
mFlags = flags_;
}
bool isUnsigned() const {
return getFlag(fIsUnsigned);
}
void isUnsigned(const bool sign) {
setFlag(fIsUnsigned, sign);
}
bool isSigned() const {
return getFlag(fIsSigned);
}
void isSigned(const bool sign) {
setFlag(fIsSigned, sign);
}
// cppcheck-suppress unusedFunction
bool isPointerCompare() const {
return getFlag(fIsPointerCompare);
}
void isPointerCompare(const bool b) {
setFlag(fIsPointerCompare, b);
}
bool isLong() const {
return getFlag(fIsLong);
}
void isLong(bool size) {
setFlag(fIsLong, size);
}
bool isStandardType() const {
return getFlag(fIsStandardType);
}
void isStandardType(const bool b) {
setFlag(fIsStandardType, b);
}
bool isExpandedMacro() const {
return !mImpl->mMacroName.empty();
}
bool isCast() const {
return getFlag(fIsCast);
}
void isCast(bool c) {
setFlag(fIsCast, c);
}
bool isAttributeConstructor() const {
return getFlag(fIsAttributeConstructor);
}
void isAttributeConstructor(const bool ac) {
setFlag(fIsAttributeConstructor, ac);
}
bool isAttributeDestructor() const {
return getFlag(fIsAttributeDestructor);
}
void isAttributeDestructor(const bool value) {
setFlag(fIsAttributeDestructor, value);
}
bool isAttributeUnused() const {
return getFlag(fIsAttributeUnused);
}
void isAttributeUnused(bool unused) {
setFlag(fIsAttributeUnused, unused);
}
bool isAttributeUsed() const {
return getFlag(fIsAttributeUsed);
}
void isAttributeUsed(const bool unused) {
setFlag(fIsAttributeUsed, unused);
}
bool isAttributePure() const {
return getFlag(fIsAttributePure);
}
void isAttributePure(const bool value) {
setFlag(fIsAttributePure, value);
}
bool isAttributeConst() const {
return getFlag(fIsAttributeConst);
}
void isAttributeConst(bool value) {
setFlag(fIsAttributeConst, value);
}
bool isAttributeNoreturn() const {
return getFlag(fIsAttributeNoreturn);
}
void isAttributeNoreturn(const bool value) {
setFlag(fIsAttributeNoreturn, value);
}
bool isAttributeNothrow() const {
return getFlag(fIsAttributeNothrow);
}
void isAttributeNothrow(const bool value) {
setFlag(fIsAttributeNothrow, value);
}
bool isAttributeExport() const {
return getFlag(fIsAttributeExport);
}
void isAttributeExport(const bool value) {
setFlag(fIsAttributeExport, value);
}
bool isAttributePacked() const {
return getFlag(fIsAttributePacked);
}
void isAttributePacked(const bool value) {
setFlag(fIsAttributePacked, value);
}
bool isAttributeNodiscard() const {
return getFlag(fIsAttributeNodiscard);
}
void isAttributeNodiscard(const bool value) {
setFlag(fIsAttributeNodiscard, value);
}
bool isAttributeMaybeUnused() const {
return getFlag(fIsAttributeMaybeUnused);
}
void isAttributeMaybeUnused(const bool value) {
setFlag(fIsAttributeMaybeUnused, value);
}
std::vector<std::string> getAttributeAlignas() const {
return mImpl->mAttributeAlignas ? *mImpl->mAttributeAlignas : std::vector<std::string>();
}
bool hasAttributeAlignas() const {
return !!mImpl->mAttributeAlignas;
}
void addAttributeAlignas(const std::string& a) {
mImpl->addAttributeAlignas(a);
}
void addAttributeCleanup(const std::string& funcname) {
mImpl->mAttributeCleanup = funcname;
}
const std::string& getAttributeCleanup() const {
return mImpl->mAttributeCleanup;
}
bool hasAttributeCleanup() const {
return !mImpl->mAttributeCleanup.empty();
}
void setCppcheckAttribute(TokenImpl::CppcheckAttributes::Type type, MathLib::bigint value) {
mImpl->setCppcheckAttribute(type, value);
}
bool getCppcheckAttribute(TokenImpl::CppcheckAttributes::Type type, MathLib::bigint &value) const {
return mImpl->getCppcheckAttribute(type, value);
}
// cppcheck-suppress unusedFunction
bool hasCppcheckAttributes() const {
return nullptr != mImpl->mCppcheckAttributes;
}
bool isControlFlowKeyword() const {
return getFlag(fIsControlFlowKeyword);
}
bool isOperatorKeyword() const {
return getFlag(fIsOperatorKeyword);
}
void isOperatorKeyword(const bool value) {
setFlag(fIsOperatorKeyword, value);
}
bool isComplex() const {
return getFlag(fIsComplex);
}
void isComplex(const bool value) {
setFlag(fIsComplex, value);
}
bool isEnumType() const {
return getFlag(fIsEnumType);
}
void isEnumType(const bool value) {
setFlag(fIsEnumType, value);
}
bool isAtAddress() const {
return getFlag(fAtAddress);
}
void isAtAddress(bool b) {
setFlag(fAtAddress, b);
}
bool isIncompleteVar() const {
return getFlag(fIncompleteVar);
}
void isIncompleteVar(bool b) {
setFlag(fIncompleteVar, b);
}
bool isSimplifiedTypedef() const {
return getFlag(fIsSimplifiedTypedef);
}
void isSimplifiedTypedef(bool b) {
setFlag(fIsSimplifiedTypedef, b);
}
bool isIncompleteConstant() const {
return getFlag(fIsIncompleteConstant);
}
void isIncompleteConstant(bool b) {
setFlag(fIsIncompleteConstant, b);
}
bool isConstexpr() const {
return getFlag(fConstexpr);
}
void isConstexpr(bool b) {
setFlag(fConstexpr, b);
}
bool isExternC() const {
return getFlag(fExternC);
}
void isExternC(bool b) {
setFlag(fExternC, b);
}
bool isSplittedVarDeclComma() const {
return getFlag(fIsSplitVarDeclComma);
}
void isSplittedVarDeclComma(bool b) {
setFlag(fIsSplitVarDeclComma, b);
}
bool isSplittedVarDeclEq() const {
return getFlag(fIsSplitVarDeclEq);
}
void isSplittedVarDeclEq(bool b) {
setFlag(fIsSplitVarDeclEq, b);
}
bool isImplicitInt() const {
return getFlag(fIsImplicitInt);
}
void isImplicitInt(bool b) {
setFlag(fIsImplicitInt, b);
}
bool isInline() const {
return getFlag(fIsInline);
}
void isInline(bool b) {
setFlag(fIsInline, b);
}
bool isAtomic() const {
return getFlag(fIsAtomic);
}
void isAtomic(bool b) {
setFlag(fIsAtomic, b);
}
bool isRestrict() const {
return getFlag(fIsRestrict);
}
void isRestrict(bool b) {
setFlag(fIsRestrict, b);
}
bool isRemovedVoidParameter() const {
return getFlag(fIsRemovedVoidParameter);
}
void setRemovedVoidParameter(bool b) {
setFlag(fIsRemovedVoidParameter, b);
}
bool isTemplate() const {
return getFlag(fIsTemplate);
}
void isTemplate(bool b) {
setFlag(fIsTemplate, b);
}
bool isSimplifiedScope() const {
return getFlag(fIsSimplifedScope);
}
void isSimplifiedScope(bool b) {
setFlag(fIsSimplifedScope, b);
}
bool isFinalType() const {
return getFlag(fIsFinalType);
}
void isFinalType(bool b) {
setFlag(fIsFinalType, b);
}
bool isInitComma() const {
return getFlag(fIsInitComma);
}
void isInitComma(bool b) {
setFlag(fIsInitComma, b);
}
// cppcheck-suppress unusedFunction
bool isBitfield() const {
return mImpl->mBits > 0;
}
unsigned char bits() const {
return mImpl->mBits;
}
const std::set<TemplateSimplifier::TokenAndName*>* templateSimplifierPointers() const {
return mImpl->mTemplateSimplifierPointers;
}
std::set<TemplateSimplifier::TokenAndName*>* templateSimplifierPointers() {
return mImpl->mTemplateSimplifierPointers;
}
void templateSimplifierPointer(TemplateSimplifier::TokenAndName* tokenAndName) {
if (!mImpl->mTemplateSimplifierPointers)
mImpl->mTemplateSimplifierPointers = new std::set<TemplateSimplifier::TokenAndName*>;
mImpl->mTemplateSimplifierPointers->insert(tokenAndName);
}
void setBits(const unsigned char b) {
mImpl->mBits = b;
}
bool isUtf8() const {
return (((mTokType == eString) && isPrefixStringCharLiteral(mStr, '"', "u8")) ||
((mTokType == eChar) && isPrefixStringCharLiteral(mStr, '\'', "u8")));
}
bool isUtf16() const {
return (((mTokType == eString) && isPrefixStringCharLiteral(mStr, '"', "u")) ||
((mTokType == eChar) && isPrefixStringCharLiteral(mStr, '\'', "u")));
}
bool isUtf32() const {
return (((mTokType == eString) && isPrefixStringCharLiteral(mStr, '"', "U")) ||
((mTokType == eChar) && isPrefixStringCharLiteral(mStr, '\'', "U")));
}
bool isCChar() const {
return (((mTokType == eString) && isPrefixStringCharLiteral(mStr, '"', emptyString)) ||
((mTokType == eChar) && isPrefixStringCharLiteral(mStr, '\'', emptyString) && (replaceEscapeSequences(getCharLiteral(mStr)).size() == 1)));
}
bool isCMultiChar() const {
return (mTokType == eChar) && isPrefixStringCharLiteral(mStr, '\'', emptyString) && (replaceEscapeSequences(getCharLiteral(mStr)).size() > 1);
}
/**
* @brief Is current token a template argument?
*
* Original code:
*
* template<class C> struct S {
* C x;
* };
* S<int> s;
*
* Resulting code:
*
* struct S<int> {
* int x ; // <- "int" is a template argument
* }
* S<int> s;
*/
bool isTemplateArg() const {
return getFlag(fIsTemplateArg);
}
void isTemplateArg(const bool value) {
setFlag(fIsTemplateArg, value);
}
const std::string& getMacroName() const {
return mImpl->mMacroName;
}
void setMacroName(std::string name) {
mImpl->mMacroName = std::move(name);
}
template<size_t count>
static const Token *findsimplematch(const Token * const startTok, const char (&pattern)[count]) {
return findsimplematch(startTok, pattern, count-1);
}
static const Token *findsimplematch(const Token * startTok, const char pattern[], size_t pattern_len);
template<size_t count>
static const Token *findsimplematch(const Token * const startTok, const char (&pattern)[count], const Token * const end) {
return findsimplematch(startTok, pattern, count-1, end);
}
static const Token *findsimplematch(const Token * startTok, const char pattern[], size_t pattern_len, const Token * end);
static const Token *findmatch(const Token * startTok, const char pattern[], nonneg int varId = 0);
static const Token *findmatch(const Token * startTok, const char pattern[], const Token * end, nonneg int varId = 0);
template<size_t count>
static Token *findsimplematch(Token * const startTok, const char (&pattern)[count]) {
return findsimplematch(startTok, pattern, count-1);
}
static Token *findsimplematch(Token * startTok, const char pattern[], size_t pattern_len);
template<size_t count>
static Token *findsimplematch(Token * const startTok, const char (&pattern)[count], const Token * const end) {
return findsimplematch(startTok, pattern, count-1, end);
}
static Token *findsimplematch(Token * startTok, const char pattern[], size_t pattern_len, const Token * end);
static Token *findmatch(Token * startTok, const char pattern[], nonneg int varId = 0);
static Token *findmatch(Token * startTok, const char pattern[], const Token * end, nonneg int varId = 0);
private:
template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
static T *tokAtImpl(T *tok, int index)
{
while (index > 0 && tok) {
tok = tok->next();
--index;
}
while (index < 0 && tok) {
tok = tok->previous();
++index;
}
return tok;
}
template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
static T *linkAtImpl(T *thisTok, int index)
{
T *tok = thisTok->tokAt(index);
if (!tok) {
throw InternalError(thisTok, "Internal error. Token::linkAt called with index outside the tokens range.");
}
return tok->link();
}
/**
* Needle is build from multiple alternatives. If one of
* them is equal to haystack, return value is 1. If there
* are no matches, but one alternative to needle is empty
* string, return value is 0. If needle was not found, return
* value is -1.
*
* @param tok Current token (needle)
* @param haystack e.g. "one|two" or "|one|two"
* @param varid optional varid of token
* @return 1 if needle is found from the haystack
* 0 if needle was empty string
* -1 if needle was not found
*/
static int multiCompare(const Token *tok, const char *haystack, nonneg int varid);
public:
const std::string& fileName() const;
nonneg int fileIndex() const {
return mImpl->mFileIndex;
}
void fileIndex(nonneg int indexOfFile) {
mImpl->mFileIndex = indexOfFile;
}
nonneg int linenr() const {
return mImpl->mLineNumber;
}
void linenr(nonneg int lineNumber) {
mImpl->mLineNumber = lineNumber;
}
nonneg int column() const {
return mImpl->mColumn;
}
void column(nonneg int c) {
mImpl->mColumn = c;
}
Token* next() {
return mNext;
}
const Token* next() const {
return mNext;
}
/**
* Delete tokens between begin and end. E.g. if begin = 1
* and end = 5, tokens 2,3 and 4 would be erased.
*
* @param begin Tokens after this will be erased.
* @param end Tokens before this will be erased.
*/
static void eraseTokens(Token *begin, const Token *end);
/**
* Insert new token after this token. This function will handle
* relations between next and previous token also.
* @param tokenStr String for the new token.
* @param originalNameStr String used for Token::originalName().
* @param prepend Insert the new token before this token when it's not
* the first one on the tokens list.
*/
RET_NONNULL Token* insertToken(const std::string& tokenStr, const std::string& originalNameStr = emptyString, const std::string& macroNameStr = emptyString, bool prepend = false);
RET_NONNULL Token* insertTokenBefore(const std::string& tokenStr, const std::string& originalNameStr = emptyString, const std::string& macroNameStr = emptyString)
{
return insertToken(tokenStr, originalNameStr, macroNameStr, true);
}
Token* previous() {
return mPrevious;
}
const Token* previous() const {
return mPrevious;
}
nonneg int varId() const {
return mImpl->mVarId;
}
void varId(nonneg int id) {
mImpl->mVarId = id;
if (id != 0) {
tokType(eVariable);
isStandardType(false);
} else {
update_property_info();
}
}
nonneg int exprId() const {
if (mImpl->mExprId)
return mImpl->mExprId;
return mImpl->mVarId;
}
void exprId(nonneg int id) {
mImpl->mExprId = id;
}
void setUniqueExprId()
{
assert(mImpl->mExprId > 0);
mImpl->mExprId |= 1 << efIsUnique;
}
bool isUniqueExprId() const
{
return (mImpl->mExprId & (1 << efIsUnique)) != 0;
}
/**
* For debugging purposes, prints token and all tokens followed by it.
*/
void printOut() const;
/**
* For debugging purposes, prints token and all tokens followed by it.
* @param title Title for the printout or use default parameter or 0
* for no title.
*/
void printOut(std::ostream& out, const char *title = nullptr) const;
/**
* For debugging purposes, prints token and all tokens followed by it.
* @param title Title for the printout or use default parameter or 0
* for no title.
* @param fileNames Prints out file name instead of file index.
* File index should match the index of the string in this vector.
*/
void printOut(std::ostream& out, const char *title, const std::vector<std::string> &fileNames) const;
/**
* print out tokens - used for debugging
*/
void printLines(std::ostream& out, int lines=5) const;
/**
* Replace token replaceThis with tokens between start and end,
* including start and end. The replaceThis token is deleted.
* @param replaceThis This token will be deleted.
* @param start This will be in the place of replaceThis
* @param end This is also in the place of replaceThis
*/
static void replace(Token *replaceThis, Token *start, Token *end);
struct stringifyOptions {
bool varid = false;
bool exprid = false;
bool idtype = false; // distinguish varid / exprid
bool attributes = false;
bool macro = false;
bool linenumbers = false;
bool linebreaks = false;
bool files = false;
static stringifyOptions forDebug() {
stringifyOptions options;
options.attributes = true;
options.macro = true;
options.linenumbers = true;
options.linebreaks = true;
options.files = true;
return options;
}
// cppcheck-suppress unusedFunction
static stringifyOptions forDebugVarId() {
stringifyOptions options = forDebug();
options.varid = true;
return options;
}
static stringifyOptions forDebugExprId() {
stringifyOptions options = forDebug();
options.exprid = true;
return options;
}
static stringifyOptions forPrintOut() {
stringifyOptions options = forDebug();
options.exprid = true;
options.varid = true;
options.idtype = true;
return options;
}
};
std::string stringify(const stringifyOptions& options) const;
/**
* Stringify a token
* @param varid Print varids. (Style: "varname\@id")
* @param attributes Print attributes of tokens like "unsigned" in front of it.
* @param macro Prints $ in front of the token if it was expanded from a macro.
*/
std::string stringify(bool varid, bool attributes, bool macro) const;
std::string stringifyList(const stringifyOptions& options, const std::vector<std::string>* fileNames = nullptr, const Token* end = nullptr) const;
std::string stringifyList(const Token* end, bool attributes = true) const;
std::string stringifyList(bool varid = false) const;
/**
* Stringify a list of token, from current instance on.
* @param varid Print varids. (Style: "varname\@id")
* @param attributes Print attributes of tokens like "unsigned" in front of it.
* @param linenumbers Print line number in front of each line
* @param linebreaks Insert "\\n" into string when line number changes
* @param files print Files as numbers or as names (if fileNames is given)
* @param fileNames Vector of filenames. Used (if given) to print filenames as strings instead of numbers.
* @param end Stringification ends before this token is reached. 0 to stringify until end of list.
* @return Stringified token list as a string
*/
std::string stringifyList(bool varid, bool attributes, bool linenumbers, bool linebreaks, bool files, const std::vector<std::string>* fileNames = nullptr, const Token* end = nullptr) const;
/**
* Remove the contents for this token from the token list.
*
* The contents are replaced with the contents of the next token and
* the next token is unlinked and deleted from the token list.
*
* So this token will still be valid after the 'deleteThis()'.
*/
void deleteThis();
/**
* Create link to given token
* @param linkToToken The token where this token should link
* to.
*/
void link(Token *linkToToken) {
mLink = linkToToken;
if (mStr == "<" || mStr == ">")
update_property_info();
}
/**
* Return token where this token links to.
* Supported links are:
* "{" <-> "}"
* "(" <-> ")"
* "[" <-> "]"
*
* @return The token where this token links to.
*/
const Token* link() const {
return mLink;
}
Token* link() {
return mLink;
}
/**
* Associate this token with given scope
* @param s Scope to be associated
*/
void scope(const Scope *s) {
mImpl->mScope = s;
}
/**
* @return a pointer to the scope containing this token.
*/
const Scope *scope() const {
return mImpl->mScope;
}
/**
* Associate this token with given function
* @param f Function to be associated
*/
void function(const Function *f);
/**
* @return a pointer to the Function associated with this token.
*/
const Function *function() const {
return mTokType == eFunction || mTokType == eLambda ? mImpl->mFunction : nullptr;
}
/**
* Associate this token with given variable
* @param v Variable to be associated
*/
void variable(const Variable *v) {
mImpl->mVariable = v;
if (v || mImpl->mVarId)
tokType(eVariable);
else if (mTokType == eVariable)
tokType(eName);
}
/**
* @return a pointer to the variable associated with this token.
*/
const Variable *variable() const {
return mTokType == eVariable ? mImpl->mVariable : nullptr;
}
/**
* Associate this token with given type
* @param t Type to be associated
*/
void type(const ::Type *t);
/**
* @return a pointer to the type associated with this token.
*/
const ::Type *type() const {
return mTokType == eType ? mImpl->mType : nullptr;
}
static const ::Type* typeOf(const Token* tok, const Token** typeTok = nullptr);
/**
* @return the declaration associated with this token.
* @param pointedToType return the pointed-to type?
*/
static std::pair<const Token*, const Token*> typeDecl(const Token* tok, bool pointedToType = false);
static std::string typeStr(const Token* tok);
static bool isStandardType(const std::string& str);
/**
* @return a pointer to the Enumerator associated with this token.
*/
const Enumerator *enumerator() const {
return mTokType == eEnumerator ? mImpl->mEnumerator : nullptr;
}
/**
* Associate this token with given enumerator
* @param e Enumerator to be associated
*/
void enumerator(const Enumerator *e) {
mImpl->mEnumerator = e;
if (e)
tokType(eEnumerator);
else if (mTokType == eEnumerator)
tokType(eName);
}
/**
* Links two elements against each other.
**/
static void createMutualLinks(Token *begin, Token *end);
/**
* This can be called only for tokens that are strings, else
* the assert() is called. If Token is e.g. '"hello"', this will return
* 'hello' (removing the double quotes).
* @return String value
*/
std::string strValue() const;
/**
* Move srcStart and srcEnd tokens and all tokens between them
* into new a location. Only links between tokens are changed.
* @param srcStart This is the first token to be moved
* @param srcEnd The last token to be moved
* @param newLocation srcStart will be placed after this token.
*/
static void move(Token *srcStart, Token *srcEnd, Token *newLocation);
/** Get progressValue (0 - 100) */
nonneg int progressValue() const {
return mImpl->mProgressValue;
}
/** Calculate progress values for all tokens */
static void assignProgressValues(Token *tok);
/**
* @return the first token of the next argument. Does only work on argument
* lists. Requires that Tokenizer::createLinks2() has been called before.
* Returns nullptr, if there is no next argument.
*/
const Token* nextArgument() const;
Token *nextArgument();
/**
* @return the first token of the next argument. Does only work on argument
* lists. Should be used only before Tokenizer::createLinks2() was called.
* Returns nullptr, if there is no next argument.
*/
const Token* nextArgumentBeforeCreateLinks2() const;
/**
* @return the first token of the next template argument. Does only work on template argument
* lists. Requires that Tokenizer::createLinks2() has been called before.
* Returns nullptr, if there is no next argument.
*/
const Token* nextTemplateArgument() const;
/**
* Returns the closing bracket of opening '<'. Should only be used if link()
* is unavailable.
* @return closing '>', ')', ']' or '}'. if no closing bracket is found, NULL is returned
*/
const Token* findClosingBracket() const;
Token* findClosingBracket();
const Token* findOpeningBracket() const;
Token* findOpeningBracket();
/**
* @return the original name.
*/
const std::string & originalName() const {
return mImpl->mOriginalName ? *mImpl->mOriginalName : emptyString;
}
const std::list<ValueFlow::Value>& values() const {
return mImpl->mValues ? *mImpl->mValues : TokenImpl::mEmptyValueList;
}
/**
* Sets the original name.
*/
template<typename T>
void originalName(T&& name) {
if (!mImpl->mOriginalName)
mImpl->mOriginalName = new std::string(name);
else
*mImpl->mOriginalName = name;
}
bool hasKnownIntValue() const;
bool hasKnownValue() const;
bool hasKnownValue(ValueFlow::Value::ValueType t) const;
bool hasKnownSymbolicValue(const Token* tok) const;
const ValueFlow::Value* getKnownValue(ValueFlow::Value::ValueType t) const;
MathLib::bigint getKnownIntValue() const {
return mImpl->mValues->front().intvalue;
}
const ValueFlow::Value* getValue(MathLib::bigint val) const;
const ValueFlow::Value* getMaxValue(bool condition, MathLib::bigint path = 0) const;
const ValueFlow::Value* getMinValue(bool condition, MathLib::bigint path = 0) const;
const ValueFlow::Value* getMovedValue() const;
const ValueFlow::Value * getValueLE(MathLib::bigint val, const Settings &settings) const;
const ValueFlow::Value * getValueGE(MathLib::bigint val, const Settings &settings) const;
const ValueFlow::Value * getValueNE(MathLib::bigint val) const;
const ValueFlow::Value * getInvalidValue(const Token *ftok, nonneg int argnr, const Settings &settings) const;
const ValueFlow::Value* getContainerSizeValue(MathLib::bigint val) const;
const Token *getValueTokenMaxStrLength() const;
const Token *getValueTokenMinStrSize(const Settings &settings, MathLib::bigint* path = nullptr) const;
/** Add token value. Return true if value is added. */
bool addValue(const ValueFlow::Value &value);
void removeValues(std::function<bool(const ValueFlow::Value &)> pred) {
if (mImpl->mValues)
mImpl->mValues->remove_if(std::move(pred));
}
nonneg int index() const {
return mImpl->mIndex;
}
void assignIndexes();
private:
void next(Token *nextToken) {
mNext = nextToken;
}
void previous(Token *previousToken) {
mPrevious = previousToken;
}
/** used by deleteThis() to take data from token to delete */
void takeData(Token *fromToken);
/**
* Works almost like strcmp() except returns only true or false and
* if str has empty space ' ' character, that character is handled
* as if it were '\\0'
*/
static bool firstWordEquals(const char *str, const char *word);
/**
* Works almost like strchr() except
* if str has empty space ' ' character, that character is handled
* as if it were '\\0'
*/
static const char *chrInFirstWord(const char *str, char c);
std::string mStr;
Token* mNext{};
Token* mPrevious{};
Token* mLink{};
enum : uint64_t {
fIsUnsigned = (1ULL << 0),
fIsSigned = (1ULL << 1),
fIsPointerCompare = (1ULL << 2),
fIsLong = (1ULL << 3),
fIsStandardType = (1ULL << 4),
//fIsExpandedMacro = (1ULL << 5),
fIsCast = (1ULL << 6),
fIsAttributeConstructor = (1ULL << 7), // __attribute__((constructor)) __attribute__((constructor(priority)))
fIsAttributeDestructor = (1ULL << 8), // __attribute__((destructor)) __attribute__((destructor(priority)))
fIsAttributeUnused = (1ULL << 9), // __attribute__((unused))
fIsAttributePure = (1ULL << 10), // __attribute__((pure))
fIsAttributeConst = (1ULL << 11), // __attribute__((const))
fIsAttributeNoreturn = (1ULL << 12), // __attribute__((noreturn)), __declspec(noreturn)
fIsAttributeNothrow = (1ULL << 13), // __attribute__((nothrow)), __declspec(nothrow)
fIsAttributeUsed = (1ULL << 14), // __attribute__((used))
fIsAttributePacked = (1ULL << 15), // __attribute__((packed))
fIsAttributeExport = (1ULL << 16), // __attribute__((__visibility__("default"))), __declspec(dllexport)
fIsAttributeMaybeUnused = (1ULL << 17), // [[maybe_unused]]
fIsAttributeNodiscard = (1ULL << 18), // __attribute__ ((warn_unused_result)), [[nodiscard]]
fIsControlFlowKeyword = (1ULL << 19), // if/switch/while/...
fIsOperatorKeyword = (1ULL << 20), // operator=, etc
fIsComplex = (1ULL << 21), // complex/_Complex type
fIsEnumType = (1ULL << 22), // enumeration type
fIsName = (1ULL << 23),
fIsLiteral = (1ULL << 24),
fIsTemplateArg = (1ULL << 25),
fAtAddress = (1ULL << 26), // @ 0x4000
fIncompleteVar = (1ULL << 27),
fConstexpr = (1ULL << 28),
fExternC = (1ULL << 29),
fIsSplitVarDeclComma = (1ULL << 30), // set to true when variable declarations are split up ('int a,b;' => 'int a; int b;')
fIsSplitVarDeclEq = (1ULL << 31), // set to true when variable declaration with initialization is split up ('int a=5;' => 'int a; a=5;')
fIsImplicitInt = (1ULL << 32), // Is "int" token implicitly added?
fIsInline = (1ULL << 33), // Is this a inline type
fIsTemplate = (1ULL << 34),
fIsSimplifedScope = (1ULL << 35), // scope added when simplifying e.g. if (int i = ...; ...)
fIsRemovedVoidParameter = (1ULL << 36), // A void function parameter has been removed
fIsIncompleteConstant = (1ULL << 37),
fIsRestrict = (1ULL << 38), // Is this a restrict pointer type
fIsAtomic = (1ULL << 39), // Is this a _Atomic declaration
fIsSimplifiedTypedef = (1ULL << 40),
fIsFinalType = (1ULL << 41), // Is this a type with final specifier
fIsInitComma = (1ULL << 42), // Is this comma located inside some {..}. i.e: {1,2,3,4}
};
enum : std::uint8_t {
efMaxSize = sizeof(nonneg int) * 8,
efIsUnique = efMaxSize - 2,
};
Token::Type mTokType = eNone;
uint64_t mFlags{};
TokenImpl* mImpl{};
/**
* Get specified flag state.
* @param flag_ flag to get state of
* @return true if flag set or false in flag not set
*/
bool getFlag(uint64_t flag_) const {
return ((mFlags & flag_) != 0);
}
/**
* Set specified flag state.
* @param flag_ flag to set state
* @param state_ new state of flag
*/
void setFlag(uint64_t flag_, bool state_) {
mFlags = state_ ? mFlags | flag_ : mFlags & ~flag_;
}
/** Updates internal property cache like _isName or _isBoolean.
Called after any mStr() modification. */
void update_property_info();
/** Update internal property cache about isStandardType() */
void update_property_isStandardType();
/** Internal helper function to avoid excessive string allocations */
void astStringVerboseRecursive(std::string& ret, nonneg int indent1 = 0, nonneg int indent2 = 0) const;
// cppcheck-suppress premium-misra-cpp-2023-12.2.1
bool mIsC : 1;
bool mIsCpp : 1;
public:
void astOperand1(Token *tok);
void astOperand2(Token *tok);
void astParent(Token* tok);
Token * astOperand1() {
return mImpl->mAstOperand1;
}
const Token * astOperand1() const {
return mImpl->mAstOperand1;
}
Token * astOperand2() {
return mImpl->mAstOperand2;
}
const Token * astOperand2() const {
return mImpl->mAstOperand2;
}
Token * astParent() {
return mImpl->mAstParent;
}
const Token * astParent() const {
return mImpl->mAstParent;
}
Token * astSibling() {
if (!astParent())
return nullptr;
if (this == astParent()->astOperand1())
return astParent()->astOperand2();
if (this == astParent()->astOperand2())
return astParent()->astOperand1();
return nullptr;
}
const Token * astSibling() const {
if (!astParent())
return nullptr;
if (this == astParent()->astOperand1())
return astParent()->astOperand2();
if (this == astParent()->astOperand2())
return astParent()->astOperand1();
return nullptr;
}
RET_NONNULL Token *astTop() {
Token *ret = this;
while (ret->mImpl->mAstParent)
ret = ret->mImpl->mAstParent;
return ret;
}
RET_NONNULL const Token *astTop() const {
const Token *ret = this;
while (ret->mImpl->mAstParent)
ret = ret->mImpl->mAstParent;
return ret;
}
std::pair<const Token *, const Token *> findExpressionStartEndTokens() const;
/**
* Is current token a calculation? Only true for operands.
* For '*' and '&' tokens it is looked up if this is a
* dereference or address-of. A dereference or address-of is not
* counted as a calculation.
* @return returns true if current token is a calculation
*/
bool isCalculation() const;
void clearValueFlow() {
delete mImpl->mValues;
mImpl->mValues = nullptr;
}
std::string astString(const char *sep = "") const {
std::string ret;
if (mImpl->mAstOperand1)
ret = mImpl->mAstOperand1->astString(sep);
if (mImpl->mAstOperand2)
ret += mImpl->mAstOperand2->astString(sep);
return ret + sep + mStr;
}
std::string astStringVerbose() const;
std::string astStringZ3() const;
std::string expressionString() const;
void printAst(bool verbose, bool xml, const std::vector<std::string> &fileNames, std::ostream &out) const;
void printValueFlow(bool xml, std::ostream &out) const;
void scopeInfo(std::shared_ptr<ScopeInfo2> newScopeInfo);
std::shared_ptr<ScopeInfo2> scopeInfo() const;
void setCpp11init(bool cpp11init) const {
mImpl->mCpp11init=cpp11init ? TokenImpl::Cpp11init::CPP11INIT : TokenImpl::Cpp11init::NOINIT;
}
TokenImpl::Cpp11init isCpp11init() const {
return mImpl->mCpp11init;
}
TokenDebug getTokenDebug() const {
return mImpl->mDebug;
}
void setTokenDebug(TokenDebug td) {
mImpl->mDebug = td;
}
bool isCpp() const
{
return mIsCpp;
}
bool isC() const
{
return mIsC;
}
};
Token* findTypeEnd(Token* tok);
Token* findLambdaEndScope(Token* tok);
const Token* findLambdaEndScope(const Token* tok);
/// @}
//---------------------------------------------------------------------------
#endif // tokenH
| null |
922 | cpp | cppcheck | checkstring.h | lib/checkstring.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef checkstringH
#define checkstringH
//---------------------------------------------------------------------------
#include "check.h"
#include "config.h"
#include "tokenize.h"
#include <string>
class ErrorLogger;
class Settings;
class Token;
/// @addtogroup Checks
/// @{
/** @brief Detect misusage of C-style strings and related standard functions */
class CPPCHECKLIB CheckString : public Check {
public:
/** @brief This constructor is used when registering the CheckClass */
CheckString() : Check(myName()) {}
private:
/** @brief This constructor is used when running checks. */
CheckString(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {}
/** @brief Run checks against the normal token list */
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
CheckString checkString(&tokenizer, &tokenizer.getSettings(), errorLogger);
// Checks
checkString.strPlusChar();
checkString.checkSuspiciousStringCompare();
checkString.stringLiteralWrite();
checkString.overlappingStrcmp();
checkString.checkIncorrectStringCompare();
checkString.sprintfOverlappingData();
checkString.checkAlwaysTrueOrFalseStringCompare();
}
/** @brief undefined behaviour, writing string literal */
void stringLiteralWrite();
/** @brief str plus char (unusual pointer arithmetic) */
void strPlusChar();
/** @brief %Check for using bad usage of strncmp and substr */
void checkIncorrectStringCompare();
/** @brief %Check for comparison of a string literal with a char* variable */
void checkSuspiciousStringCompare();
/** @brief %Check for suspicious code that compares string literals for equality */
void checkAlwaysTrueOrFalseStringCompare();
/** @brief %Check for overlapping strcmp() */
void overlappingStrcmp();
/** @brief %Check for overlapping source and destination passed to sprintf() */
void sprintfOverlappingData();
void stringLiteralWriteError(const Token *tok, const Token *strValue);
void sprintfOverlappingDataError(const Token *funcTok, const Token *tok, const std::string &varname);
void strPlusCharError(const Token *tok);
void incorrectStringCompareError(const Token *tok, const std::string& func, const std::string &string);
void incorrectStringBooleanError(const Token *tok, const std::string& string);
void alwaysTrueFalseStringCompareError(const Token *tok, const std::string& str1, const std::string& str2);
void alwaysTrueStringVariableCompareError(const Token *tok, const std::string& str1, const std::string& str2);
void suspiciousStringCompareError(const Token* tok, const std::string& var, bool isLong);
void suspiciousStringCompareError_char(const Token* tok, const std::string& var);
void overlappingStrcmpError(const Token* eq0, const Token *ne0);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const override {
CheckString c(nullptr, settings, errorLogger);
c.stringLiteralWriteError(nullptr, nullptr);
c.sprintfOverlappingDataError(nullptr, nullptr, "varname");
c.strPlusCharError(nullptr);
c.incorrectStringCompareError(nullptr, "substr", "\"Hello World\"");
c.suspiciousStringCompareError(nullptr, "foo", false);
c.suspiciousStringCompareError_char(nullptr, "foo");
c.incorrectStringBooleanError(nullptr, "\"Hello World\"");
c.incorrectStringBooleanError(nullptr, "\'x\'");
c.alwaysTrueFalseStringCompareError(nullptr, "str1", "str2");
c.alwaysTrueStringVariableCompareError(nullptr, "varname1", "varname2");
c.overlappingStrcmpError(nullptr, nullptr);
}
static std::string myName() {
return "String";
}
std::string classInfo() const override {
return "Detect misusage of C-style strings:\n"
"- overlapping buffers passed to sprintf as source and destination\n"
"- incorrect length arguments for 'substr' and 'strncmp'\n"
"- suspicious condition (runtime comparison of string literals)\n"
"- suspicious condition (string/char literals as boolean)\n"
"- suspicious comparison of a string literal with a char\\* variable\n"
"- suspicious comparison of '\\0' with a char\\* variable\n"
"- overlapping strcmp() expression\n";
}
};
/// @}
//---------------------------------------------------------------------------
#endif // checkstringH
| null |
923 | cpp | cppcheck | checkio.cpp | lib/checkio.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#include "checkio.h"
#include "astutils.h"
#include "errortypes.h"
#include "library.h"
#include "mathlib.h"
#include "platform.h"
#include "settings.h"
#include "symboldatabase.h"
#include "token.h"
#include "tokenize.h"
#include "utils.h"
#include "vfvalue.h"
#include <algorithm>
#include <cctype>
#include <cstdlib>
#include <functional>
#include <list>
#include <map>
#include <set>
#include <sstream>
#include <unordered_set>
#include <utility>
#include <vector>
//---------------------------------------------------------------------------
// Register CheckIO..
namespace {
CheckIO instance;
}
// CVE ID used:
static const CWE CWE119(119U); // Improper Restriction of Operations within the Bounds of a Memory Buffer
static const CWE CWE398(398U); // Indicator of Poor Code Quality
static const CWE CWE664(664U); // Improper Control of a Resource Through its Lifetime
static const CWE CWE685(685U); // Function Call With Incorrect Number of Arguments
static const CWE CWE686(686U); // Function Call With Incorrect Argument Type
static const CWE CWE687(687U); // Function Call With Incorrectly Specified Argument Value
static const CWE CWE704(704U); // Incorrect Type Conversion or Cast
static const CWE CWE910(910U); // Use of Expired File Descriptor
//---------------------------------------------------------------------------
// std::cout << std::cout;
//---------------------------------------------------------------------------
void CheckIO::checkCoutCerrMisusage()
{
if (mTokenizer->isC())
return;
logChecker("CheckIO::checkCoutCerrMisusage"); // c
const SymbolDatabase * const symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token *tok = scope->bodyStart; tok && tok != scope->bodyEnd; tok = tok->next()) {
if (Token::Match(tok, "std :: cout|cerr !!.") && tok->next()->astParent() && tok->next()->astParent()->astOperand1() == tok->next()) {
const Token* tok2 = tok->next();
while (tok2->astParent() && tok2->astParent()->str() == "<<") {
tok2 = tok2->astParent();
if (tok2->astOperand2() && Token::Match(tok2->astOperand2()->previous(), "std :: cout|cerr"))
coutCerrMisusageError(tok, tok2->astOperand2()->strAt(1));
}
}
}
}
}
void CheckIO::coutCerrMisusageError(const Token* tok, const std::string& streamName)
{
reportError(tok, Severity::error, "coutCerrMisusage", "Invalid usage of output stream: '<< std::" + streamName + "'.", CWE398, Certainty::normal);
}
//---------------------------------------------------------------------------
// fflush(stdin) <- fflush only applies to output streams in ANSI C
// fread(); fwrite(); <- consecutive read/write statements require repositioning in between
// fopen("","r"); fwrite(); <- write to read-only file (or vice versa)
// fclose(); fread(); <- Use closed file
//---------------------------------------------------------------------------
enum class OpenMode : std::uint8_t { CLOSED, READ_MODE, WRITE_MODE, RW_MODE, UNKNOWN_OM };
static OpenMode getMode(const std::string& str)
{
if (str.find('+', 1) != std::string::npos)
return OpenMode::RW_MODE;
if (str.find('w') != std::string::npos || str.find('a') != std::string::npos)
return OpenMode::WRITE_MODE;
if (str.find('r') != std::string::npos)
return OpenMode::READ_MODE;
return OpenMode::UNKNOWN_OM;
}
namespace {
struct Filepointer {
OpenMode mode;
nonneg int mode_indent{};
enum class Operation : std::uint8_t {NONE, UNIMPORTANT, READ, WRITE, POSITIONING, OPEN, CLOSE, UNKNOWN_OP} lastOperation = Operation::NONE;
nonneg int op_indent{};
enum class AppendMode : std::uint8_t { UNKNOWN_AM, APPEND, APPEND_EX };
AppendMode append_mode = AppendMode::UNKNOWN_AM;
std::string filename;
explicit Filepointer(OpenMode mode_ = OpenMode::UNKNOWN_OM)
: mode(mode_) {}
};
const std::unordered_set<std::string> whitelist = { "clearerr", "feof", "ferror", "fgetpos", "ftell", "setbuf", "setvbuf", "ungetc", "ungetwc" };
}
void CheckIO::checkFileUsage()
{
const bool windows = mSettings->platform.isWindows();
const bool printPortability = mSettings->severity.isEnabled(Severity::portability);
const bool printWarnings = mSettings->severity.isEnabled(Severity::warning);
std::map<int, Filepointer> filepointers;
logChecker("CheckIO::checkFileUsage");
const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Variable* var : symbolDatabase->variableList()) {
if (!var || !var->declarationId() || var->isArray() || !Token::simpleMatch(var->typeStartToken(), "FILE *"))
continue;
if (var->isLocal()) {
if (var->nameToken()->strAt(1) == "(") // initialize by calling "ctor"
filepointers.emplace(var->declarationId(), Filepointer(OpenMode::UNKNOWN_OM));
else
filepointers.emplace(var->declarationId(), Filepointer(OpenMode::CLOSED));
} else {
filepointers.emplace(var->declarationId(), Filepointer(OpenMode::UNKNOWN_OM));
// TODO: If all fopen calls we find open the file in the same type, we can set Filepointer::mode
}
}
for (const Scope * scope : symbolDatabase->functionScopes) {
int indent = 0;
for (const Token *tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
if (Token::Match(tok, "%name% (") && isUnevaluated(tok)) {
tok = tok->linkAt(1);
continue;
}
if (tok->str() == "{")
indent++;
else if (tok->str() == "}") {
indent--;
for (std::pair<const int, Filepointer>& filepointer : filepointers) {
if (indent < filepointer.second.mode_indent) {
filepointer.second.mode_indent = 0;
filepointer.second.mode = OpenMode::UNKNOWN_OM;
}
if (indent < filepointer.second.op_indent) {
filepointer.second.op_indent = 0;
filepointer.second.lastOperation = Filepointer::Operation::UNKNOWN_OP;
}
}
} else if (tok->str() == "return" || tok->str() == "continue" || tok->str() == "break" || mSettings->library.isnoreturn(tok)) { // Reset upon return, continue or break
for (std::pair<const int, Filepointer>& filepointer : filepointers) {
filepointer.second.mode_indent = 0;
filepointer.second.mode = OpenMode::UNKNOWN_OM;
filepointer.second.op_indent = 0;
filepointer.second.lastOperation = Filepointer::Operation::UNKNOWN_OP;
}
} else if (Token::Match(tok, "%var% =") &&
(tok->strAt(2) != "fopen" && tok->strAt(2) != "freopen" && tok->strAt(2) != "tmpfile" &&
(windows ? (tok->str() != "_wfopen" && tok->str() != "_wfreopen") : true))) {
const std::map<int, Filepointer>::iterator i = filepointers.find(tok->varId());
if (i != filepointers.end()) {
i->second.mode = OpenMode::UNKNOWN_OM;
i->second.lastOperation = Filepointer::Operation::UNKNOWN_OP;
}
} else if (Token::Match(tok, "%name% (") && tok->previous() && (!tok->previous()->isName() || Token::Match(tok->previous(), "return|throw"))) {
std::string mode;
const Token* fileTok = nullptr;
const Token* fileNameTok = nullptr;
Filepointer::Operation operation = Filepointer::Operation::NONE;
if ((tok->str() == "fopen" || tok->str() == "freopen" || tok->str() == "tmpfile" ||
(windows && (tok->str() == "_wfopen" || tok->str() == "_wfreopen"))) &&
tok->strAt(-1) == "=") {
if (tok->str() != "tmpfile") {
const Token* modeTok = tok->tokAt(2)->nextArgument();
if (modeTok && modeTok->tokType() == Token::eString)
mode = modeTok->strValue();
} else
mode = "wb+";
fileTok = tok->tokAt(-2);
operation = Filepointer::Operation::OPEN;
if (Token::Match(tok, "fopen ( %str% ,"))
fileNameTok = tok->tokAt(2);
} else if (windows && Token::Match(tok, "fopen_s|freopen_s|_wfopen_s|_wfreopen_s ( & %name%")) {
const Token* modeTok = tok->tokAt(2)->nextArgument()->nextArgument();
if (modeTok && modeTok->tokType() == Token::eString)
mode = modeTok->strValue();
fileTok = tok->tokAt(3);
operation = Filepointer::Operation::OPEN;
} else if ((tok->str() == "rewind" || tok->str() == "fseek" || tok->str() == "fsetpos" || tok->str() == "fflush") ||
(windows && tok->str() == "_fseeki64")) {
fileTok = tok->tokAt(2);
if (printPortability && fileTok && tok->str() == "fflush") {
if (fileTok->str() == "stdin")
fflushOnInputStreamError(tok, fileTok->str());
else {
const Filepointer& f = filepointers[fileTok->varId()];
if (f.mode == OpenMode::READ_MODE)
fflushOnInputStreamError(tok, fileTok->str());
}
}
operation = Filepointer::Operation::POSITIONING;
} else if (tok->str() == "fgetc" || tok->str() == "fgetwc" ||
tok->str() == "fgets" || tok->str() == "fgetws" || tok->str() == "fread" ||
tok->str() == "fscanf" || tok->str() == "fwscanf" || tok->str() == "getc" ||
(windows && (tok->str() == "fscanf_s" || tok->str() == "fwscanf_s"))) {
if (tok->str().find("scanf") != std::string::npos)
fileTok = tok->tokAt(2);
else
fileTok = tok->linkAt(1)->previous();
operation = Filepointer::Operation::READ;
} else if (tok->str() == "fputc" || tok->str() == "fputwc" ||
tok->str() == "fputs" || tok->str() == "fputws" || tok->str() == "fwrite" ||
tok->str() == "fprintf" || tok->str() == "fwprintf" || tok->str() == "putcc" ||
(windows && (tok->str() == "fprintf_s" || tok->str() == "fwprintf_s"))) {
if (tok->str().find("printf") != std::string::npos)
fileTok = tok->tokAt(2);
else
fileTok = tok->linkAt(1)->previous();
operation = Filepointer::Operation::WRITE;
} else if (tok->str() == "fclose") {
fileTok = tok->tokAt(2);
operation = Filepointer::Operation::CLOSE;
} else if (whitelist.find(tok->str()) != whitelist.end()) {
fileTok = tok->tokAt(2);
if ((tok->str() == "ungetc" || tok->str() == "ungetwc") && fileTok)
fileTok = fileTok->nextArgument();
operation = Filepointer::Operation::UNIMPORTANT;
} else if (!Token::Match(tok, "if|for|while|catch|switch") && !mSettings->library.isFunctionConst(tok->str(), true)) {
const Token* const end2 = tok->linkAt(1);
if (scope->functionOf && scope->functionOf->isClassOrStruct() && !scope->function->isStatic() && ((tok->strAt(-1) != "::" && tok->strAt(-1) != ".") || tok->strAt(-2) == "this")) {
if (!tok->function() || (tok->function()->nestedIn && tok->function()->nestedIn->isClassOrStruct())) {
for (std::pair<const int, Filepointer>& filepointer : filepointers) {
const Variable* var = symbolDatabase->getVariableFromVarId(filepointer.first);
if (!var || !(var->isLocal() || var->isGlobal() || var->isStatic())) {
filepointer.second.mode = OpenMode::UNKNOWN_OM;
filepointer.second.mode_indent = 0;
filepointer.second.op_indent = indent;
filepointer.second.lastOperation = Filepointer::Operation::UNKNOWN_OP;
}
}
continue;
}
}
for (const Token* tok2 = tok->tokAt(2); tok2 != end2; tok2 = tok2->next()) {
if (tok2->varId() && filepointers.find(tok2->varId()) != filepointers.end()) {
fileTok = tok2;
operation = Filepointer::Operation::UNKNOWN_OP; // Assume that repositioning was last operation and that the file is opened now
break;
}
}
}
while (Token::Match(fileTok, "%name% ."))
fileTok = fileTok->tokAt(2);
if (!fileTok || !fileTok->varId() || fileTok->strAt(1) == "[")
continue;
// function call indicates: Its a File
filepointers.emplace(fileTok->varId(), Filepointer(OpenMode::UNKNOWN_OM));
Filepointer& f = filepointers[fileTok->varId()];
switch (operation) {
case Filepointer::Operation::OPEN:
if (fileNameTok) {
for (std::map<int, Filepointer>::const_iterator it = filepointers.cbegin(); it != filepointers.cend(); ++it) {
const Filepointer &fptr = it->second;
if (fptr.filename == fileNameTok->str() && (fptr.mode == OpenMode::RW_MODE || fptr.mode == OpenMode::WRITE_MODE))
incompatibleFileOpenError(tok, fileNameTok->str());
}
f.filename = fileNameTok->str();
}
f.mode = getMode(mode);
if (mode.find('a') != std::string::npos) {
if (f.mode == OpenMode::RW_MODE)
f.append_mode = Filepointer::AppendMode::APPEND_EX;
else
f.append_mode = Filepointer::AppendMode::APPEND;
} else
f.append_mode = Filepointer::AppendMode::UNKNOWN_AM;
f.mode_indent = indent;
break;
case Filepointer::Operation::POSITIONING:
if (f.mode == OpenMode::CLOSED)
useClosedFileError(tok);
else if (f.append_mode == Filepointer::AppendMode::APPEND && tok->str() != "fflush" && printWarnings)
seekOnAppendedFileError(tok);
break;
case Filepointer::Operation::READ:
if (f.mode == OpenMode::CLOSED)
useClosedFileError(tok);
else if (f.mode == OpenMode::WRITE_MODE)
readWriteOnlyFileError(tok);
else if (f.lastOperation == Filepointer::Operation::WRITE)
ioWithoutPositioningError(tok);
break;
case Filepointer::Operation::WRITE:
if (f.mode == OpenMode::CLOSED)
useClosedFileError(tok);
else if (f.mode == OpenMode::READ_MODE)
writeReadOnlyFileError(tok);
else if (f.lastOperation == Filepointer::Operation::READ)
ioWithoutPositioningError(tok);
break;
case Filepointer::Operation::CLOSE:
if (f.mode == OpenMode::CLOSED)
useClosedFileError(tok);
else
f.mode = OpenMode::CLOSED;
f.mode_indent = indent;
break;
case Filepointer::Operation::UNIMPORTANT:
if (f.mode == OpenMode::CLOSED)
useClosedFileError(tok);
break;
case Filepointer::Operation::UNKNOWN_OP:
f.mode = OpenMode::UNKNOWN_OM;
f.mode_indent = 0;
break;
default:
break;
}
if (operation != Filepointer::Operation::NONE && operation != Filepointer::Operation::UNIMPORTANT) {
f.op_indent = indent;
f.lastOperation = operation;
}
}
}
for (std::pair<const int, Filepointer>& filepointer : filepointers) {
filepointer.second.op_indent = 0;
filepointer.second.mode = OpenMode::UNKNOWN_OM;
filepointer.second.lastOperation = Filepointer::Operation::UNKNOWN_OP;
}
}
}
void CheckIO::fflushOnInputStreamError(const Token *tok, const std::string &varname)
{
reportError(tok, Severity::portability,
"fflushOnInputStream", "fflush() called on input stream '" + varname + "' may result in undefined behaviour on non-linux systems.", CWE398, Certainty::normal);
}
void CheckIO::ioWithoutPositioningError(const Token *tok)
{
reportError(tok, Severity::error,
"IOWithoutPositioning", "Read and write operations without a call to a positioning function (fseek, fsetpos or rewind) or fflush in between result in undefined behaviour.", CWE664, Certainty::normal);
}
void CheckIO::readWriteOnlyFileError(const Token *tok)
{
reportError(tok, Severity::error,
"readWriteOnlyFile", "Read operation on a file that was opened only for writing.", CWE664, Certainty::normal);
}
void CheckIO::writeReadOnlyFileError(const Token *tok)
{
reportError(tok, Severity::error,
"writeReadOnlyFile", "Write operation on a file that was opened only for reading.", CWE664, Certainty::normal);
}
void CheckIO::useClosedFileError(const Token *tok)
{
reportError(tok, Severity::error,
"useClosedFile", "Used file that is not opened.", CWE910, Certainty::normal);
}
void CheckIO::seekOnAppendedFileError(const Token *tok)
{
reportError(tok, Severity::warning,
"seekOnAppendedFile", "Repositioning operation performed on a file opened in append mode has no effect.", CWE398, Certainty::normal);
}
void CheckIO::incompatibleFileOpenError(const Token *tok, const std::string &filename)
{
reportError(tok, Severity::warning,
"incompatibleFileOpen", "The file '" + filename + "' is opened for read and write access at the same time on different streams", CWE664, Certainty::normal);
}
//---------------------------------------------------------------------------
// scanf without field width limits can crash with huge input data
//---------------------------------------------------------------------------
void CheckIO::invalidScanf()
{
if (!mSettings->severity.isEnabled(Severity::warning) && !mSettings->isPremiumEnabled("invalidscanf"))
return;
logChecker("CheckIO::invalidScanf");
const SymbolDatabase * const symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token *tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
const Token *formatToken = nullptr;
if (Token::Match(tok, "scanf|vscanf ( %str% ,"))
formatToken = tok->tokAt(2);
else if (Token::Match(tok, "sscanf|vsscanf|fscanf|vfscanf (")) {
const Token* nextArg = tok->tokAt(2)->nextArgument();
if (nextArg && nextArg->tokType() == Token::eString)
formatToken = nextArg;
else
continue;
} else
continue;
bool format = false;
// scan the string backwards, so we do not need to keep states
const std::string &formatstr(formatToken->str());
for (std::size_t i = 1; i < formatstr.length(); i++) {
if (formatstr[i] == '%')
format = !format;
else if (!format)
continue;
else if (std::isdigit(formatstr[i]) || formatstr[i] == '*') {
format = false;
}
else if (std::isalpha((unsigned char)formatstr[i]) || formatstr[i] == '[') {
if (formatstr[i] == 's' || formatstr[i] == '[' || formatstr[i] == 'S' || (formatstr[i] == 'l' && formatstr[i+1] == 's')) // #3490 - field width limits are only necessary for string input
invalidScanfError(tok);
format = false;
}
}
}
}
}
void CheckIO::invalidScanfError(const Token *tok)
{
const std::string fname = (tok ? tok->str() : std::string("scanf"));
reportError(tok, Severity::warning,
"invalidscanf", fname + "() without field width limits can crash with huge input data.\n" +
fname + "() without field width limits can crash with huge input data. Add a field width "
"specifier to fix this problem.\n"
"\n"
"Sample program that can crash:\n"
"\n"
"#include <stdio.h>\n"
"int main()\n"
"{\n"
" char c[5];\n"
" scanf(\"%s\", c);\n"
" return 0;\n"
"}\n"
"\n"
"Typing in 5 or more characters may make the program crash. The correct usage "
"here is 'scanf(\"%4s\", c);', as the maximum field width does not include the "
"terminating null byte.\n"
"Source: http://linux.die.net/man/3/scanf\n"
"Source: http://www.opensource.apple.com/source/xnu/xnu-1456.1.26/libkern/stdio/scanf.c",
CWE119, Certainty::normal);
}
//---------------------------------------------------------------------------
// printf("%u", "xyz"); // Wrong argument type
// printf("%u%s", 1); // Too few arguments
// printf("", 1); // Too much arguments
//---------------------------------------------------------------------------
static bool findFormat(nonneg int arg, const Token *firstArg,
const Token *&formatStringTok, const Token *&formatArgTok)
{
const Token* argTok = firstArg;
for (int i = 0; i < arg && argTok; ++i)
argTok = argTok->nextArgument();
if (Token::Match(argTok, "%str% [,)]")) {
formatArgTok = argTok->nextArgument();
formatStringTok = argTok;
return true;
}
if (Token::Match(argTok, "%var% [,)]") &&
argTok->variable() &&
Token::Match(argTok->variable()->typeStartToken(), "char|wchar_t") &&
(argTok->variable()->isPointer() ||
(argTok->variable()->dimensions().size() == 1 &&
argTok->variable()->dimensionKnown(0) &&
argTok->variable()->dimension(0) != 0))) {
formatArgTok = argTok->nextArgument();
if (!argTok->values().empty()) {
const std::list<ValueFlow::Value>::const_iterator value = std::find_if(
argTok->values().cbegin(), argTok->values().cend(), std::mem_fn(&ValueFlow::Value::isTokValue));
if (value != argTok->values().cend() && value->isTokValue() && value->tokvalue &&
value->tokvalue->tokType() == Token::eString) {
formatStringTok = value->tokvalue;
}
}
return true;
}
return false;
}
// Utility function returning whether iToTest equals iTypename or iOptionalPrefix+iTypename
static inline bool typesMatch(const std::string& iToTest, const std::string& iTypename, const std::string& iOptionalPrefix = "std::")
{
return (iToTest == iTypename) || (iToTest == iOptionalPrefix + iTypename);
}
void CheckIO::checkWrongPrintfScanfArguments()
{
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
const bool isWindows = mSettings->platform.isWindows();
logChecker("CheckIO::checkWrongPrintfScanfArguments");
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token *tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (!tok->isName()) continue;
const Token* argListTok = nullptr; // Points to first va_list argument
const Token* formatStringTok = nullptr; // Points to format string token
bool scan = false;
bool scanf_s = false;
int formatStringArgNo = -1;
if (tok->strAt(1) == "(" && mSettings->library.formatstr_function(tok)) {
formatStringArgNo = mSettings->library.formatstr_argno(tok);
scan = mSettings->library.formatstr_scan(tok);
scanf_s = mSettings->library.formatstr_secure(tok);
}
if (formatStringArgNo >= 0) {
// formatstring found in library. Find format string and first argument belonging to format string.
if (!findFormat(formatStringArgNo, tok->tokAt(2), formatStringTok, argListTok))
continue;
} else if (Token::simpleMatch(tok, "swprintf (")) {
if (Token::Match(tok->tokAt(2)->nextArgument(), "%str%")) {
// Find third parameter and format string
if (!findFormat(1, tok->tokAt(2), formatStringTok, argListTok))
continue;
} else {
// Find fourth parameter and format string
if (!findFormat(2, tok->tokAt(2), formatStringTok, argListTok))
continue;
}
} else if (isWindows && Token::Match(tok, "sprintf_s|swprintf_s (")) {
// template <size_t size> int sprintf_s(char (&buffer)[size], const char *format, ...);
if (findFormat(1, tok->tokAt(2), formatStringTok, argListTok)) {
if (!formatStringTok)
continue;
}
// int sprintf_s(char *buffer, size_t sizeOfBuffer, const char *format, ...);
else if (findFormat(2, tok->tokAt(2), formatStringTok, argListTok)) {
if (!formatStringTok)
continue;
}
} else if (isWindows && Token::Match(tok, "_snprintf_s|_snwprintf_s (")) {
// template <size_t size> int _snprintf_s(char (&buffer)[size], size_t count, const char *format, ...);
if (findFormat(2, tok->tokAt(2), formatStringTok, argListTok)) {
if (!formatStringTok)
continue;
}
// int _snprintf_s(char *buffer, size_t sizeOfBuffer, size_t count, const char *format, ...);
else if (findFormat(3, tok->tokAt(2), formatStringTok, argListTok)) {
if (!formatStringTok)
continue;
}
} else {
continue;
}
if (!formatStringTok)
continue;
checkFormatString(tok, formatStringTok, argListTok, scan, scanf_s);
}
}
}
void CheckIO::checkFormatString(const Token * const tok,
const Token * const formatStringTok,
const Token * argListTok,
const bool scan,
const bool scanf_s)
{
const bool isWindows = mSettings->platform.isWindows();
const bool printWarning = mSettings->severity.isEnabled(Severity::warning);
const std::string &formatString = formatStringTok->str();
// Count format string parameters..
int numFormat = 0;
int numSecure = 0;
bool percent = false;
const Token* argListTok2 = argListTok;
std::set<int> parameterPositionsUsed;
for (std::string::const_iterator i = formatString.cbegin(); i != formatString.cend(); ++i) {
if (*i == '%') {
percent = !percent;
} else if (percent && *i == '[') {
while (i != formatString.cend()) {
if (*i == ']') {
numFormat++;
if (argListTok)
argListTok = argListTok->nextArgument();
percent = false;
break;
}
++i;
}
if (scanf_s) {
numSecure++;
if (argListTok) {
argListTok = argListTok->nextArgument();
}
}
if (i == formatString.cend())
break;
} else if (percent) {
percent = false;
bool _continue = false;
bool skip = false;
std::string width;
int parameterPosition = 0;
bool hasParameterPosition = false;
while (i != formatString.cend() && *i != '[' && !std::isalpha((unsigned char)*i)) {
if (*i == '*') {
skip = true;
if (scan)
_continue = true;
else {
numFormat++;
if (argListTok)
argListTok = argListTok->nextArgument();
}
} else if (std::isdigit(*i)) {
width += *i;
} else if (*i == '$') {
parameterPosition = strToInt<int>(width);
hasParameterPosition = true;
width.clear();
}
++i;
}
auto bracketBeg = formatString.cend();
if (i != formatString.cend() && *i == '[') {
bracketBeg = i;
while (i != formatString.cend()) {
if (*i == ']')
break;
++i;
}
if (scanf_s && !skip) {
numSecure++;
if (argListTok) {
argListTok = argListTok->nextArgument();
}
}
}
if (i == formatString.cend())
break;
if (_continue)
continue;
if (scan || *i != 'm') { // %m is a non-standard extension that requires no parameter on print functions.
++numFormat;
// Handle parameter positions (POSIX extension) - Ticket #4900
if (hasParameterPosition) {
if (parameterPositionsUsed.find(parameterPosition) == parameterPositionsUsed.end())
parameterPositionsUsed.insert(parameterPosition);
else // Parameter already referenced, hence don't consider it a new format
--numFormat;
}
// Perform type checks
ArgumentInfo argInfo(argListTok, *mSettings, mTokenizer->isCPP());
if ((argInfo.typeToken && !argInfo.isLibraryType(*mSettings)) || *i == ']') {
if (scan) {
std::string specifier;
bool done = false;
while (!done) {
switch (*i) {
case 's':
case ']': // charset
specifier += (*i == 's' || bracketBeg == formatString.end()) ? std::string{ 's' } : std::string{ bracketBeg, i + 1 };
if (argInfo.variableInfo && argInfo.isKnownType() && argInfo.variableInfo->isArray() && (argInfo.variableInfo->dimensions().size() == 1) && argInfo.variableInfo->dimensions()[0].known) {
if (!width.empty()) {
const int numWidth = strToInt<int>(width);
if (numWidth != (argInfo.variableInfo->dimension(0) - 1))
invalidScanfFormatWidthError(tok, numFormat, numWidth, argInfo.variableInfo, specifier);
}
}
if (argListTok && argListTok->tokType() != Token::eString && argInfo.typeToken &&
argInfo.isKnownType() && argInfo.isArrayOrPointer() &&
(!Token::Match(argInfo.typeToken, "char|wchar_t") ||
argInfo.typeToken->strAt(-1) == "const")) {
if (!(argInfo.isArrayOrPointer() && argInfo.element && !argInfo.typeToken->isStandardType()))
invalidScanfArgTypeError_s(tok, numFormat, specifier, &argInfo);
}
if (scanf_s && argInfo.typeToken) {
numSecure++;
if (argListTok) {
argListTok = argListTok->nextArgument();
}
}
done = true;
break;
case 'c':
if (argInfo.variableInfo && argInfo.isKnownType() && argInfo.variableInfo->isArray() && (argInfo.variableInfo->dimensions().size() == 1) && argInfo.variableInfo->dimensions()[0].known) {
if (!width.empty()) {
const int numWidth = strToInt<int>(width);
if (numWidth > argInfo.variableInfo->dimension(0))
invalidScanfFormatWidthError(tok, numFormat, numWidth, argInfo.variableInfo, std::string(1, *i));
}
}
if (scanf_s) {
numSecure++;
if (argListTok) {
argListTok = argListTok->nextArgument();
}
}
done = true;
break;
case 'x':
case 'X':
case 'u':
case 'o':
specifier += *i;
if (argInfo.typeToken->tokType() == Token::eString)
invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, true);
else if (argInfo.isKnownType()) {
if (!Token::Match(argInfo.typeToken, "char|short|int|long")) {
if (argInfo.typeToken->isStandardType() || !argInfo.element)
invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, true);
} else if (!argInfo.typeToken->isUnsigned() ||
!argInfo.isArrayOrPointer() ||
argInfo.typeToken->strAt(-1) == "const") {
invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, true);
} else {
switch (specifier[0]) {
case 'h':
if (specifier[1] == 'h') {
if (argInfo.typeToken->str() != "char")
invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, true);
} else if (argInfo.typeToken->str() != "short")
invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, true);
break;
case 'l':
if (specifier[1] == 'l') {
if (argInfo.typeToken->str() != "long" || !argInfo.typeToken->isLong())
invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, true);
else if (typesMatch(argInfo.typeToken->originalName(), "size_t") ||
typesMatch(argInfo.typeToken->originalName(), "ptrdiff_t") ||
typesMatch(argInfo.typeToken->originalName(), "uintmax_t"))
invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, true);
} else if (argInfo.typeToken->str() != "long" || argInfo.typeToken->isLong())
invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, true);
else if (typesMatch(argInfo.typeToken->originalName(), "size_t") ||
typesMatch(argInfo.typeToken->originalName(), "ptrdiff_t") ||
typesMatch(argInfo.typeToken->originalName(), "uintmax_t"))
invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, true);
break;
case 'I':
if (specifier.find("I64") != std::string::npos) {
if (argInfo.typeToken->str() != "long" || !argInfo.typeToken->isLong())
invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, true);
} else if (specifier.find("I32") != std::string::npos) {
if (argInfo.typeToken->str() != "int" || argInfo.typeToken->isLong())
invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, true);
} else if (!typesMatch(argInfo.typeToken->originalName(), "size_t"))
invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, true);
break;
case 'j':
if (!typesMatch(argInfo.typeToken->originalName(), "uintmax_t"))
invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, true);
break;
case 'z':
if (!typesMatch(argInfo.typeToken->originalName(), "size_t"))
invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, true);
break;
case 't':
if (!typesMatch(argInfo.typeToken->originalName(), "ptrdiff_t"))
invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, true);
break;
case 'L':
if (argInfo.typeToken->str() != "long" || !argInfo.typeToken->isLong())
invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, true);
else if (typesMatch(argInfo.typeToken->originalName(), "size_t") ||
typesMatch(argInfo.typeToken->originalName(), "uintmax_t"))
invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, true);
break;
default:
if (argInfo.typeToken->str() != "int")
invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, true);
else if (typesMatch(argInfo.typeToken->originalName(), "size_t") ||
typesMatch(argInfo.typeToken->originalName(), "ptrdiff_t") ||
typesMatch(argInfo.typeToken->originalName(), "uintmax_t"))
invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, true);
break;
}
}
}
done = true;
break;
case 'n':
case 'd':
case 'i':
specifier += *i;
if (argInfo.typeToken->tokType() == Token::eString)
invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, false);
else if (argInfo.isKnownType()) {
if (!Token::Match(argInfo.typeToken, "char|short|int|long")) {
if (argInfo.typeToken->isStandardType() || !argInfo.element)
invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, false);
} else if (argInfo.typeToken->isUnsigned() ||
!argInfo.isArrayOrPointer() ||
argInfo.typeToken->strAt(-1) == "const") {
invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, false);
} else {
switch (specifier[0]) {
case 'h':
if (specifier[1] == 'h') {
if (argInfo.typeToken->str() != "char")
invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, false);
} else if (argInfo.typeToken->str() != "short")
invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, false);
break;
case 'l':
if (specifier[1] == 'l') {
if (argInfo.typeToken->str() != "long" || !argInfo.typeToken->isLong())
invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, false);
else if (typesMatch(argInfo.typeToken->originalName(), "ptrdiff_t") ||
typesMatch(argInfo.typeToken->originalName(), "intmax_t"))
invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, false);
} else if (argInfo.typeToken->str() != "long" || argInfo.typeToken->isLong())
invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, false);
else if (typesMatch(argInfo.typeToken->originalName(), "ptrdiff_t") ||
typesMatch(argInfo.typeToken->originalName(), "intmax_t"))
invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, false);
break;
case 'I':
if (specifier.find("I64") != std::string::npos) {
if (argInfo.typeToken->str() != "long" || !argInfo.typeToken->isLong())
invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, false);
} else if (specifier.find("I32") != std::string::npos) {
if (argInfo.typeToken->str() != "int" || argInfo.typeToken->isLong())
invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, false);
} else if (!typesMatch(argInfo.typeToken->originalName(), "ptrdiff_t"))
invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, false);
break;
case 'j':
if (!typesMatch(argInfo.typeToken->originalName(), "intmax_t"))
invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, false);
break;
case 'z':
if (!(typesMatch(argInfo.typeToken->originalName(), "ssize_t") ||
(isWindows && typesMatch(argInfo.typeToken->originalName(), "SSIZE_T"))))
invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, false);
break;
case 't':
if (!typesMatch(argInfo.typeToken->originalName(), "ptrdiff_t"))
invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, false);
break;
case 'L':
if (argInfo.typeToken->str() != "long" || !argInfo.typeToken->isLong())
invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, false);
break;
default:
if (argInfo.typeToken->str() != "int")
invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, false);
else if (typesMatch(argInfo.typeToken->originalName(), "ptrdiff_t") ||
argInfo.typeToken->originalName() == "intmax_t")
invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, false);
break;
}
}
}
done = true;
break;
case 'e':
case 'E':
case 'f':
case 'g':
case 'G':
case 'a':
specifier += *i;
if (argInfo.typeToken->tokType() == Token::eString)
invalidScanfArgTypeError_float(tok, numFormat, specifier, &argInfo);
else if (argInfo.isKnownType()) {
if (!Token::Match(argInfo.typeToken, "float|double")) {
if (argInfo.typeToken->isStandardType())
invalidScanfArgTypeError_float(tok, numFormat, specifier, &argInfo);
} else if (!argInfo.isArrayOrPointer() ||
argInfo.typeToken->strAt(-1) == "const") {
invalidScanfArgTypeError_float(tok, numFormat, specifier, &argInfo);
} else {
switch (specifier[0]) {
case 'l':
if (argInfo.typeToken->str() != "double" || argInfo.typeToken->isLong())
invalidScanfArgTypeError_float(tok, numFormat, specifier, &argInfo);
break;
case 'L':
if (argInfo.typeToken->str() != "double" || !argInfo.typeToken->isLong())
invalidScanfArgTypeError_float(tok, numFormat, specifier, &argInfo);
break;
default:
if (argInfo.typeToken->str() != "float")
invalidScanfArgTypeError_float(tok, numFormat, specifier, &argInfo);
break;
}
}
}
done = true;
break;
case 'I':
if ((i+1 != formatString.cend() && *(i+1) == '6' &&
i+2 != formatString.cend() && *(i+2) == '4') ||
(i+1 != formatString.cend() && *(i+1) == '3' &&
i+2 != formatString.cend() && *(i+2) == '2')) {
specifier += *i++;
specifier += *i++;
if ((i+1) != formatString.cend() && !isalpha(*(i+1))) {
specifier += *i;
invalidLengthModifierError(tok, numFormat, specifier);
done = true;
} else {
specifier += *i++;
}
} else {
if ((i+1) != formatString.cend() && !isalpha(*(i+1))) {
specifier += *i;
invalidLengthModifierError(tok, numFormat, specifier);
done = true;
} else {
specifier += *i++;
}
}
break;
case 'h':
case 'l':
if (i+1 != formatString.cend() && *(i+1) == *i)
specifier += *i++;
FALLTHROUGH;
case 'j':
case 'q':
case 't':
case 'z':
case 'L':
// Expect an alphabetical character after these specifiers
if ((i + 1) != formatString.end() && !isalpha(*(i+1))) {
specifier += *i;
invalidLengthModifierError(tok, numFormat, specifier);
done = true;
} else {
specifier += *i++;
}
break;
default:
done = true;
break;
}
}
} else if (printWarning) {
std::string specifier;
bool done = false;
while (!done) {
if (i == formatString.end()) {
break;
}
switch (*i) {
case 's':
if (argListTok->tokType() != Token::eString &&
argInfo.isKnownType() && !argInfo.isArrayOrPointer()) {
if (!Token::Match(argInfo.typeToken, "char|wchar_t")) {
if (!argInfo.element)
invalidPrintfArgTypeError_s(tok, numFormat, &argInfo);
}
}
done = true;
break;
case 'n':
if ((argInfo.isKnownType() && (!argInfo.isArrayOrPointer() || argInfo.typeToken->strAt(-1) == "const")) || argListTok->tokType() == Token::eString)
invalidPrintfArgTypeError_n(tok, numFormat, &argInfo);
done = true;
break;
case 'c':
case 'x':
case 'X':
case 'o':
specifier += *i;
if (argInfo.typeToken->tokType() == Token::eString)
invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo);
else if (argInfo.isArrayOrPointer() && !argInfo.element) {
// use %p on pointers and arrays
invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo);
} else if (argInfo.isKnownType()) {
if (!Token::Match(argInfo.typeToken, "bool|short|long|int|char|wchar_t")) {
if (!(!argInfo.isArrayOrPointer() && argInfo.element))
invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo);
} else {
switch (specifier[0]) {
case 'h':
if (specifier[1] == 'h') {
if (!(argInfo.typeToken->str() == "char" && argInfo.typeToken->isUnsigned()))
invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo);
} else if (!(argInfo.typeToken->str() == "short" && argInfo.typeToken->isUnsigned()))
invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo);
break;
case 'l':
if (specifier[1] == 'l') {
if (argInfo.typeToken->str() != "long" || !argInfo.typeToken->isLong())
invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo);
else if (typesMatch(argInfo.typeToken->originalName(), "size_t") ||
argInfo.typeToken->originalName() == "uintmax_t")
invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo);
} else if (argInfo.typeToken->str() != "long" || argInfo.typeToken->isLong())
invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo);
else if (typesMatch(argInfo.typeToken->originalName(), "size_t") ||
argInfo.typeToken->originalName() == "uintmax_t")
invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo);
break;
case 'j':
if (argInfo.typeToken->originalName() != "uintmax_t")
invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo);
break;
case 'z':
if (!typesMatch(argInfo.typeToken->originalName(), "size_t"))
invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo);
break;
case 't':
if (!typesMatch(argInfo.typeToken->originalName(), "ptrdiff_t"))
invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo);
break;
case 'I':
if (specifier.find("I64") != std::string::npos) {
if (argInfo.typeToken->str() != "long" || !argInfo.typeToken->isLong())
invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo);
} else if (specifier.find("I32") != std::string::npos) {
if (argInfo.typeToken->str() != "int" || argInfo.typeToken->isLong())
invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo);
} else if (!(typesMatch(argInfo.typeToken->originalName(), "size_t") ||
argInfo.typeToken->originalName() == "WPARAM" ||
argInfo.typeToken->originalName() == "UINT_PTR" ||
argInfo.typeToken->originalName() == "LONG_PTR" ||
argInfo.typeToken->originalName() == "LPARAM" ||
argInfo.typeToken->originalName() == "LRESULT"))
invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo);
break;
default:
if (!Token::Match(argInfo.typeToken, "bool|char|short|wchar_t|int"))
invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo);
break;
}
}
}
done = true;
break;
case 'd':
case 'i':
specifier += *i;
if (argInfo.typeToken->tokType() == Token::eString) {
invalidPrintfArgTypeError_sint(tok, numFormat, specifier, &argInfo);
} else if (argInfo.isArrayOrPointer() && !argInfo.element) {
// use %p on pointers and arrays
invalidPrintfArgTypeError_sint(tok, numFormat, specifier, &argInfo);
} else if (argInfo.isKnownType()) {
if (argInfo.typeToken->isUnsigned() && !Token::Match(argInfo.typeToken, "char|short")) {
if (!(!argInfo.isArrayOrPointer() && argInfo.element))
invalidPrintfArgTypeError_sint(tok, numFormat, specifier, &argInfo);
} else if (!Token::Match(argInfo.typeToken, "bool|char|short|int|long")) {
if (!(!argInfo.isArrayOrPointer() && argInfo.element))
invalidPrintfArgTypeError_sint(tok, numFormat, specifier, &argInfo);
} else {
switch (specifier[0]) {
case 'h':
if (specifier[1] == 'h') {
if (!(argInfo.typeToken->str() == "char" && !argInfo.typeToken->isUnsigned()))
invalidPrintfArgTypeError_sint(tok, numFormat, specifier, &argInfo);
} else if (!(argInfo.typeToken->str() == "short" && !argInfo.typeToken->isUnsigned()))
invalidPrintfArgTypeError_sint(tok, numFormat, specifier, &argInfo);
break;
case 'l':
if (specifier[1] == 'l') {
if (argInfo.typeToken->str() != "long" || !argInfo.typeToken->isLong())
invalidPrintfArgTypeError_sint(tok, numFormat, specifier, &argInfo);
else if (typesMatch(argInfo.typeToken->originalName(), "ptrdiff_t") ||
argInfo.typeToken->originalName() == "intmax_t")
invalidPrintfArgTypeError_sint(tok, numFormat, specifier, &argInfo);
} else if (argInfo.typeToken->str() != "long" || argInfo.typeToken->isLong())
invalidPrintfArgTypeError_sint(tok, numFormat, specifier, &argInfo);
else if (typesMatch(argInfo.typeToken->originalName(), "ptrdiff_t") ||
argInfo.typeToken->originalName() == "intmax_t")
invalidPrintfArgTypeError_sint(tok, numFormat, specifier, &argInfo);
break;
case 'j':
if (argInfo.typeToken->originalName() != "intmax_t")
invalidPrintfArgTypeError_sint(tok, numFormat, specifier, &argInfo);
break;
case 't':
if (!typesMatch(argInfo.typeToken->originalName(), "ptrdiff_t"))
invalidPrintfArgTypeError_sint(tok, numFormat, specifier, &argInfo);
break;
case 'I':
if (specifier.find("I64") != std::string::npos) {
if (argInfo.typeToken->str() != "long" || !argInfo.typeToken->isLong())
invalidPrintfArgTypeError_sint(tok, numFormat, specifier, &argInfo);
} else if (specifier.find("I32") != std::string::npos) {
if (argInfo.typeToken->str() != "int" || argInfo.typeToken->isLong())
invalidPrintfArgTypeError_sint(tok, numFormat, specifier, &argInfo);
} else if (!typesMatch(argInfo.typeToken->originalName(), "ptrdiff_t"))
invalidPrintfArgTypeError_sint(tok, numFormat, specifier, &argInfo);
break;
case 'z':
if (!(typesMatch(argInfo.typeToken->originalName(), "ssize_t") ||
(isWindows && typesMatch(argInfo.typeToken->originalName(), "SSIZE_T"))))
invalidPrintfArgTypeError_sint(tok, numFormat, specifier, &argInfo);
break;
case 'L':
if (argInfo.typeToken->str() != "long" || !argInfo.typeToken->isLong())
invalidPrintfArgTypeError_sint(tok, numFormat, specifier, &argInfo);
break;
default:
if (!Token::Match(argInfo.typeToken, "bool|char|short|int"))
invalidPrintfArgTypeError_sint(tok, numFormat, specifier, &argInfo);
else if (typesMatch(argInfo.typeToken->originalName(), "ptrdiff_t") ||
argInfo.typeToken->originalName() == "intmax_t")
invalidPrintfArgTypeError_sint(tok, numFormat, specifier, &argInfo);
break;
}
}
}
done = true;
break;
case 'u':
specifier += *i;
if (argInfo.typeToken->tokType() == Token::eString) {
invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo);
} else if (argInfo.isArrayOrPointer() && !argInfo.element) {
// use %p on pointers and arrays
invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo);
} else if (argInfo.isKnownType()) {
if (!argInfo.typeToken->isUnsigned() && !Token::Match(argInfo.typeToken, "bool|_Bool")) {
if (!(!argInfo.isArrayOrPointer() && argInfo.element))
invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo);
} else if (!Token::Match(argInfo.typeToken, "bool|char|short|long|int")) {
if (!(!argInfo.isArrayOrPointer() && argInfo.element))
invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo);
} else {
switch (specifier[0]) {
case 'h':
if (specifier[1] == 'h') {
if (!(argInfo.typeToken->str() == "char" && argInfo.typeToken->isUnsigned()))
invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo);
} else if (!(argInfo.typeToken->str() == "short" && argInfo.typeToken->isUnsigned()))
invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo);
break;
case 'l':
if (specifier[1] == 'l') {
if (argInfo.typeToken->str() != "long" || !argInfo.typeToken->isLong())
invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo);
else if (typesMatch(argInfo.typeToken->originalName(), "size_t") ||
argInfo.typeToken->originalName() == "uintmax_t")
invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo);
} else if (argInfo.typeToken->str() != "long" || argInfo.typeToken->isLong())
invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo);
else if (typesMatch(argInfo.typeToken->originalName(), "size_t") ||
argInfo.typeToken->originalName() == "uintmax_t")
invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo);
break;
case 'j':
if (argInfo.typeToken->originalName() != "uintmax_t")
invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo);
break;
case 'z':
if (!typesMatch(argInfo.typeToken->originalName(), "size_t"))
invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo);
break;
case 't':
if (!typesMatch(argInfo.typeToken->originalName(), "ptrdiff_t"))
invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo);
break;
case 'I':
if (specifier.find("I64") != std::string::npos) {
if (argInfo.typeToken->str() != "long" || !argInfo.typeToken->isLong())
invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo);
} else if (specifier.find("I32") != std::string::npos) {
if (argInfo.typeToken->str() != "int" || argInfo.typeToken->isLong())
invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo);
} else if (!typesMatch(argInfo.typeToken->originalName(), "size_t"))
invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo);
break;
case 'L':
if (argInfo.typeToken->str() != "long" || !argInfo.typeToken->isLong())
invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo);
break;
default:
if (!Token::Match(argInfo.typeToken, "bool|char|short|int"))
invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo);
else if (typesMatch(argInfo.typeToken->originalName(), "size_t") ||
argInfo.typeToken->originalName() == "intmax_t")
invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo);
break;
}
}
}
done = true;
break;
case 'p':
if (argInfo.typeToken->tokType() == Token::eString)
; // string literals are passed as pointers to literal start, okay
else if (argInfo.isKnownType() && !argInfo.isArrayOrPointer())
invalidPrintfArgTypeError_p(tok, numFormat, &argInfo);
done = true;
break;
case 'e':
case 'E':
case 'f':
case 'g':
case 'G':
specifier += *i;
if (argInfo.typeToken->tokType() == Token::eString)
invalidPrintfArgTypeError_float(tok, numFormat, specifier, &argInfo);
else if (argInfo.isArrayOrPointer() && !argInfo.element) {
// use %p on pointers and arrays
invalidPrintfArgTypeError_float(tok, numFormat, specifier, &argInfo);
} else if (argInfo.isKnownType()) {
if (!Token::Match(argInfo.typeToken, "float|double")) {
if (!(!argInfo.isArrayOrPointer() && argInfo.element))
invalidPrintfArgTypeError_float(tok, numFormat, specifier, &argInfo);
} else if ((specifier[0] == 'L' && (!argInfo.typeToken->isLong() || argInfo.typeToken->str() != "double")) ||
(specifier[0] != 'L' && argInfo.typeToken->isLong()))
invalidPrintfArgTypeError_float(tok, numFormat, specifier, &argInfo);
}
done = true;
break;
case 'h': // Can be 'hh' (signed char or unsigned char) or 'h' (short int or unsigned short int)
case 'l': { // Can be 'll' (long long int or unsigned long long int) or 'l' (long int or unsigned long int)
// If the next character is the same (which makes 'hh' or 'll') then expect another alphabetical character
if ((i + 1) != formatString.end() && *(i + 1) == *i) {
if ((i + 2) != formatString.end() && !isalpha(*(i + 2))) {
std::string modifier;
modifier += *i;
modifier += *(i + 1);
invalidLengthModifierError(tok, numFormat, modifier);
done = true;
} else {
specifier = *i++;
specifier += *i++;
}
} else {
if ((i + 1) != formatString.end() && !isalpha(*(i + 1))) {
std::string modifier;
modifier += *i;
invalidLengthModifierError(tok, numFormat, modifier);
done = true;
} else {
specifier = *i++;
}
}
}
break;
case 'I': // Microsoft extension: I for size_t and ptrdiff_t, I32 for __int32, and I64 for __int64
if ((*(i+1) == '3' && *(i+2) == '2') ||
(*(i+1) == '6' && *(i+2) == '4')) {
specifier += *i++;
specifier += *i++;
}
FALLTHROUGH;
case 'j': // intmax_t or uintmax_t
case 'z': // size_t
case 't': // ptrdiff_t
case 'L': // long double
// Expect an alphabetical character after these specifiers
if ((i + 1) != formatString.end() && !isalpha(*(i+1))) {
specifier += *i;
invalidLengthModifierError(tok, numFormat, specifier);
done = true;
} else {
specifier += *i++;
}
break;
default:
done = true;
break;
}
}
}
}
if (argListTok)
argListTok = argListTok->nextArgument(); // Find next argument
}
}
}
// Count printf/scanf parameters..
int numFunction = 0;
while (argListTok2) {
if (Token::Match(argListTok2, "%name% ...")) // bailout for parameter pack
return;
numFunction++;
argListTok2 = argListTok2->nextArgument(); // Find next argument
}
if (printWarning) {
// Check that all parameter positions reference an actual parameter
for (const int i : parameterPositionsUsed) {
if ((i == 0) || (i > numFormat))
wrongPrintfScanfPosixParameterPositionError(tok, tok->str(), i, numFormat);
}
}
// Mismatching number of parameters => warning
if ((numFormat + numSecure) != numFunction)
wrongPrintfScanfArgumentsError(tok, tok->originalName().empty() ? tok->str() : tok->originalName(), numFormat + numSecure, numFunction);
}
// We currently only support string literals, variables, and functions.
/// @todo add non-string literals, and generic expressions
CheckIO::ArgumentInfo::ArgumentInfo(const Token * arg, const Settings &settings, bool _isCPP)
: isCPP(_isCPP)
{
if (!arg)
return;
// Use AST type info
// TODO: This is a bailout so that old code is used in simple cases. Remove the old code and always use the AST type.
if (!Token::Match(arg, "%str% ,|)") && !(arg->variable() && arg->variable()->isArray())) {
const Token *top = arg;
while (top->str() == "(" && !top->isCast())
top = top->next();
while (top->astParent() && top->astParent()->str() != "," && top->astParent() != arg->previous())
top = top->astParent();
const ValueType *valuetype = top->argumentType();
if (valuetype && valuetype->type >= ValueType::Type::BOOL) {
typeToken = tempToken = new Token(top);
if (valuetype->pointer && valuetype->constness & 1) {
tempToken->str("const");
tempToken->insertToken("a");
tempToken = tempToken->next();
}
if (valuetype->type == ValueType::BOOL)
tempToken->str("bool");
else if (valuetype->type == ValueType::CHAR)
tempToken->str("char");
else if (valuetype->type == ValueType::SHORT)
tempToken->str("short");
else if (valuetype->type == ValueType::WCHAR_T)
tempToken->str("wchar_t");
else if (valuetype->type == ValueType::INT)
tempToken->str("int");
else if (valuetype->type == ValueType::LONG)
tempToken->str("long");
else if (valuetype->type == ValueType::LONGLONG) {
tempToken->str("long");
tempToken->isLong(true);
} else if (valuetype->type == ValueType::FLOAT)
tempToken->str("float");
else if (valuetype->type == ValueType::DOUBLE)
tempToken->str("double");
else if (valuetype->type == ValueType::LONGDOUBLE) {
tempToken->str("double");
tempToken->isLong(true);
}
if (valuetype->isIntegral()) {
if (valuetype->sign == ValueType::Sign::UNSIGNED)
tempToken->isUnsigned(true);
else if (valuetype->sign == ValueType::Sign::SIGNED)
tempToken->isSigned(true);
}
if (!valuetype->originalTypeName.empty())
tempToken->originalName(valuetype->originalTypeName);
for (int p = 0; p < valuetype->pointer; p++)
tempToken->insertToken("*");
tempToken = const_cast<Token*>(typeToken);
if (top->isBinaryOp() && valuetype->pointer == 1 && (valuetype->type == ValueType::CHAR || valuetype->type == ValueType::WCHAR_T))
tempToken->tokType(Token::eString);
return;
}
}
if (arg->tokType() == Token::eString) {
typeToken = arg;
return;
}
if (arg->str() == "&" || arg->tokType() == Token::eVariable ||
arg->tokType() == Token::eFunction || Token::Match(arg, "%type% ::") ||
(Token::Match(arg, "static_cast|reinterpret_cast|const_cast <") &&
Token::simpleMatch(arg->linkAt(1), "> (") &&
Token::Match(arg->linkAt(1)->linkAt(1), ") ,|)"))) {
if (Token::Match(arg, "static_cast|reinterpret_cast|const_cast")) {
typeToken = arg->tokAt(2);
while (typeToken->str() == "const" || typeToken->str() == "extern")
typeToken = typeToken->next();
return;
}
if (arg->str() == "&") {
address = true;
arg = arg->next();
}
while (Token::Match(arg, "%type% ::"))
arg = arg->tokAt(2);
if (!arg || !(arg->tokType() == Token::eVariable || arg->tokType() == Token::eFunction))
return;
const Token *varTok = nullptr;
const Token *tok1 = arg->next();
for (; tok1; tok1 = tok1->next()) {
if (tok1->str() == "," || tok1->str() == ")") {
if (tok1->strAt(-1) == "]") {
varTok = tok1->linkAt(-1)->previous();
if (varTok->str() == ")" && varTok->link()->previous()->tokType() == Token::eFunction) {
const Function * function = varTok->link()->previous()->function();
if (function && function->retType && function->retType->isEnumType()) {
if (function->retType->classScope->enumType)
typeToken = function->retType->classScope->enumType;
else {
tempToken = new Token(tok1);
tempToken->str("int");
typeToken = tempToken;
}
} else if (function && function->retDef) {
typeToken = function->retDef;
while (typeToken->str() == "const" || typeToken->str() == "extern")
typeToken = typeToken->next();
functionInfo = function;
element = true;
}
return;
}
} else if (tok1->strAt(-1) == ")" && tok1->linkAt(-1)->previous()->tokType() == Token::eFunction) {
const Function * function = tok1->linkAt(-1)->previous()->function();
if (function && function->retType && function->retType->isEnumType()) {
if (function->retType->classScope->enumType)
typeToken = function->retType->classScope->enumType;
else {
tempToken = new Token(tok1);
tempToken->str("int");
typeToken = tempToken;
}
} else if (function && function->retDef) {
typeToken = function->retDef;
while (typeToken->str() == "const" || typeToken->str() == "extern")
typeToken = typeToken->next();
functionInfo = function;
element = false;
}
return;
} else
varTok = tok1->previous();
break;
}
if (tok1->str() == "(" || tok1->str() == "{" || tok1->str() == "[")
tok1 = tok1->link();
else if (tok1->link() && tok1->str() == "<")
tok1 = tok1->link();
// check for some common well known functions
else if (isCPP && ((Token::Match(tok1->previous(), "%var% . size|empty|c_str ( ) [,)]") && isStdContainer(tok1->previous())) ||
(Token::Match(tok1->previous(), "] . size|empty|c_str ( ) [,)]") && isStdContainer(tok1->linkAt(-1)->previous())))) {
tempToken = new Token(tok1);
if (tok1->strAt(1) == "size") {
// size_t is platform dependent
if (settings.platform.sizeof_size_t == 8) {
tempToken->str("long");
if (settings.platform.sizeof_long != 8)
tempToken->isLong(true);
} else if (settings.platform.sizeof_size_t == 4) {
if (settings.platform.sizeof_long == 4) {
tempToken->str("long");
} else {
tempToken->str("int");
}
}
tempToken->originalName("size_t");
tempToken->isUnsigned(true);
} else if (tok1->strAt(1) == "empty") {
tempToken->str("bool");
} else if (tok1->strAt(1) == "c_str") {
tempToken->str("const");
tempToken->insertToken("*");
if (typeToken->strAt(2) == "string")
tempToken->insertToken("char");
else
tempToken->insertToken("wchar_t");
}
typeToken = tempToken;
return;
}
// check for std::vector::at() and std::string::at()
else if (Token::Match(tok1->previous(), "%var% . at (") &&
Token::Match(tok1->linkAt(2), ") [,)]")) {
varTok = tok1->previous();
variableInfo = varTok->variable();
if (!variableInfo || !isStdVectorOrString()) {
variableInfo = nullptr;
typeToken = nullptr;
}
return;
} else if (!(tok1->str() == "." || tok1->tokType() == Token::eVariable || tok1->tokType() == Token::eFunction))
return;
}
if (varTok) {
variableInfo = varTok->variable();
element = tok1->strAt(-1) == "]";
// look for std::vector operator [] and use template type as return type
if (variableInfo) {
if (element && isStdVectorOrString()) { // isStdVectorOrString sets type token if true
element = false; // not really an array element
} else if (variableInfo->isEnumType()) {
if (variableInfo->type() && variableInfo->type()->classScope && variableInfo->type()->classScope->enumType)
typeToken = variableInfo->type()->classScope->enumType;
else {
tempToken = new Token(tok1);
tempToken->str("int");
typeToken = tempToken;
}
} else
typeToken = variableInfo->typeStartToken();
}
return;
}
}
}
CheckIO::ArgumentInfo::~ArgumentInfo()
{
if (tempToken) {
while (tempToken->next())
tempToken->deleteNext();
delete tempToken;
}
}
namespace {
const std::set<std::string> stl_vector = { "array", "vector" };
const std::set<std::string> stl_string = { "string", "u16string", "u32string", "wstring" };
}
bool CheckIO::ArgumentInfo::isStdVectorOrString()
{
if (!isCPP)
return false;
if (variableInfo->isStlType(stl_vector)) {
typeToken = variableInfo->typeStartToken()->tokAt(4);
_template = true;
return true;
}
if (variableInfo->isStlType(stl_string)) {
tempToken = new Token(variableInfo->typeStartToken());
if (variableInfo->typeStartToken()->strAt(2) == "string")
tempToken->str("char");
else
tempToken->str("wchar_t");
typeToken = tempToken;
return true;
}
if (variableInfo->type() && !variableInfo->type()->derivedFrom.empty()) {
const std::vector<Type::BaseInfo>& derivedFrom = variableInfo->type()->derivedFrom;
for (const Type::BaseInfo & i : derivedFrom) {
const Token* nameTok = i.nameTok;
if (Token::Match(nameTok, "std :: vector|array <")) {
typeToken = nameTok->tokAt(4);
_template = true;
return true;
}
if (Token::Match(nameTok, "std :: string|wstring")) {
tempToken = new Token(variableInfo->typeStartToken());
if (nameTok->strAt(2) == "string")
tempToken->str("char");
else
tempToken->str("wchar_t");
typeToken = tempToken;
return true;
}
}
} else if (variableInfo->type()) {
const Scope * classScope = variableInfo->type()->classScope;
if (classScope) {
for (const Function &func : classScope->functionList) {
if (func.name() == "operator[]") {
if (Token::Match(func.retDef, "%type% &")) {
typeToken = func.retDef;
return true;
}
}
}
}
}
return false;
}
static const std::set<std::string> stl_container = {
"array", "bitset", "deque", "forward_list",
"hash_map", "hash_multimap", "hash_set",
"list", "map", "multimap", "multiset",
"priority_queue", "queue", "set", "stack",
"unordered_map", "unordered_multimap", "unordered_multiset", "unordered_set", "vector"
};
bool CheckIO::ArgumentInfo::isStdContainer(const Token *tok)
{
if (!isCPP)
return false;
if (tok && tok->variable()) {
const Variable* variable = tok->variable();
if (variable->isStlType(stl_container)) {
typeToken = variable->typeStartToken()->tokAt(4);
return true;
}
if (variable->isStlType(stl_string)) {
typeToken = variable->typeStartToken();
return true;
}
if (variable->type() && !variable->type()->derivedFrom.empty()) {
for (const Type::BaseInfo &baseInfo : variable->type()->derivedFrom) {
const Token* nameTok = baseInfo.nameTok;
if (Token::Match(nameTok, "std :: vector|array|bitset|deque|list|forward_list|map|multimap|multiset|priority_queue|queue|set|stack|hash_map|hash_multimap|hash_set|unordered_map|unordered_multimap|unordered_set|unordered_multiset <")) {
typeToken = nameTok->tokAt(4);
return true;
}
if (Token::Match(nameTok, "std :: string|wstring")) {
typeToken = nameTok;
return true;
}
}
}
}
return false;
}
bool CheckIO::ArgumentInfo::isArrayOrPointer() const
{
if (address)
return true;
if (variableInfo && !_template)
return variableInfo->isArrayOrPointer();
const Token *tok = typeToken;
while (Token::Match(tok, "const|struct"))
tok = tok->next();
return tok && tok->strAt(1) == "*";
}
bool CheckIO::ArgumentInfo::isComplexType() const
{
if (variableInfo->type())
return (true);
const Token* varTypeTok = typeToken;
if (varTypeTok->str() == "std")
varTypeTok = varTypeTok->tokAt(2);
return ((variableInfo->isStlStringType() || (varTypeTok->strAt(1) == "<" && varTypeTok->linkAt(1) && varTypeTok->linkAt(1)->strAt(1) != "::")) && !variableInfo->isArrayOrPointer());
}
bool CheckIO::ArgumentInfo::isKnownType() const
{
if (variableInfo)
return (typeToken->isStandardType() || typeToken->next()->isStandardType() || isComplexType());
if (functionInfo)
return (typeToken->isStandardType() || functionInfo->retType || Token::Match(typeToken, "std :: string|wstring"));
return typeToken->isStandardType() || Token::Match(typeToken, "std :: string|wstring");
}
bool CheckIO::ArgumentInfo::isLibraryType(const Settings &settings) const
{
return typeToken && typeToken->isStandardType() && settings.library.podtype(typeToken->str());
}
void CheckIO::wrongPrintfScanfArgumentsError(const Token* tok,
const std::string &functionName,
nonneg int numFormat,
nonneg int numFunction)
{
const Severity severity = numFormat > numFunction ? Severity::error : Severity::warning;
if (severity != Severity::error && !mSettings->severity.isEnabled(Severity::warning) && !mSettings->isPremiumEnabled("wrongPrintfScanfArgNum"))
return;
std::ostringstream errmsg;
errmsg << functionName
<< " format string requires "
<< numFormat
<< " parameter" << (numFormat != 1 ? "s" : "") << " but "
<< (numFormat > numFunction ? "only " : "")
<< numFunction
<< (numFunction != 1 ? " are" : " is")
<< " given.";
reportError(tok, severity, "wrongPrintfScanfArgNum", errmsg.str(), CWE685, Certainty::normal);
}
void CheckIO::wrongPrintfScanfPosixParameterPositionError(const Token* tok, const std::string& functionName,
nonneg int index, nonneg int numFunction)
{
if (!mSettings->severity.isEnabled(Severity::warning) && !mSettings->isPremiumEnabled("wrongPrintfScanfParameterPositionError"))
return;
std::ostringstream errmsg;
errmsg << functionName << ": ";
if (index == 0) {
errmsg << "parameter positions start at 1, not 0";
} else {
errmsg << "referencing parameter " << index << " while " << numFunction << " arguments given";
}
reportError(tok, Severity::warning, "wrongPrintfScanfParameterPositionError", errmsg.str(), CWE685, Certainty::normal);
}
void CheckIO::invalidScanfArgTypeError_s(const Token* tok, nonneg int numFormat, const std::string& specifier, const ArgumentInfo* argInfo)
{
const Severity severity = getSeverity(argInfo);
if (!mSettings->severity.isEnabled(severity))
return;
std::ostringstream errmsg;
errmsg << "%" << specifier << " in format string (no. " << numFormat << ") requires a \'";
if (specifier[0] == 's')
errmsg << "char";
else if (specifier[0] == 'S')
errmsg << "wchar_t";
errmsg << " *\' but the argument type is ";
argumentType(errmsg, argInfo);
errmsg << ".";
reportError(tok, severity, "invalidScanfArgType_s", errmsg.str(), CWE686, Certainty::normal);
}
void CheckIO::invalidScanfArgTypeError_int(const Token* tok, nonneg int numFormat, const std::string& specifier, const ArgumentInfo* argInfo, bool isUnsigned)
{
const Severity severity = getSeverity(argInfo);
if (!mSettings->severity.isEnabled(severity))
return;
std::ostringstream errmsg;
errmsg << "%" << specifier << " in format string (no. " << numFormat << ") requires \'";
if (specifier[0] == 'h') {
if (specifier[1] == 'h')
errmsg << (isUnsigned ? "unsigned " : "") << "char";
else
errmsg << (isUnsigned ? "unsigned " : "") << "short";
} else if (specifier[0] == 'l') {
if (specifier[1] == 'l')
errmsg << (isUnsigned ? "unsigned " : "") << "long long";
else
errmsg << (isUnsigned ? "unsigned " : "") << "long";
} else if (specifier.find("I32") != std::string::npos) {
errmsg << (isUnsigned ? "unsigned " : "") << "__int32";
} else if (specifier.find("I64") != std::string::npos) {
errmsg << (isUnsigned ? "unsigned " : "") << "__int64";
} else if (specifier[0] == 'I') {
errmsg << (isUnsigned ? "size_t" : "ptrdiff_t");
} else if (specifier[0] == 'j') {
if (isUnsigned)
errmsg << "uintmax_t";
else
errmsg << "intmax_t";
} else if (specifier[0] == 'z') {
if (specifier[1] == 'd' || specifier[1] == 'i')
errmsg << "ssize_t";
else
errmsg << "size_t";
} else if (specifier[0] == 't') {
errmsg << (isUnsigned ? "unsigned " : "") << "ptrdiff_t";
} else if (specifier[0] == 'L') {
errmsg << (isUnsigned ? "unsigned " : "") << "long long";
} else {
errmsg << (isUnsigned ? "unsigned " : "") << "int";
}
errmsg << " *\' but the argument type is ";
argumentType(errmsg, argInfo);
errmsg << ".";
reportError(tok, severity, "invalidScanfArgType_int", errmsg.str(), CWE686, Certainty::normal);
}
void CheckIO::invalidScanfArgTypeError_float(const Token* tok, nonneg int numFormat, const std::string& specifier, const ArgumentInfo* argInfo)
{
const Severity severity = getSeverity(argInfo);
if (!mSettings->severity.isEnabled(severity))
return;
std::ostringstream errmsg;
errmsg << "%" << specifier << " in format string (no. " << numFormat << ") requires \'";
if (specifier[0] == 'l' && specifier[1] != 'l')
errmsg << "double";
else if (specifier[0] == 'L')
errmsg << "long double";
else
errmsg << "float";
errmsg << " *\' but the argument type is ";
argumentType(errmsg, argInfo);
errmsg << ".";
reportError(tok, severity, "invalidScanfArgType_float", errmsg.str(), CWE686, Certainty::normal);
}
void CheckIO::invalidPrintfArgTypeError_s(const Token* tok, nonneg int numFormat, const ArgumentInfo* argInfo)
{
const Severity severity = getSeverity(argInfo);
if (!mSettings->severity.isEnabled(severity))
return;
std::ostringstream errmsg;
errmsg << "%s in format string (no. " << numFormat << ") requires \'char *\' but the argument type is ";
argumentType(errmsg, argInfo);
errmsg << ".";
reportError(tok, severity, "invalidPrintfArgType_s", errmsg.str(), CWE686, Certainty::normal);
}
void CheckIO::invalidPrintfArgTypeError_n(const Token* tok, nonneg int numFormat, const ArgumentInfo* argInfo)
{
const Severity severity = getSeverity(argInfo);
if (!mSettings->severity.isEnabled(severity))
return;
std::ostringstream errmsg;
errmsg << "%n in format string (no. " << numFormat << ") requires \'int *\' but the argument type is ";
argumentType(errmsg, argInfo);
errmsg << ".";
reportError(tok, severity, "invalidPrintfArgType_n", errmsg.str(), CWE686, Certainty::normal);
}
void CheckIO::invalidPrintfArgTypeError_p(const Token* tok, nonneg int numFormat, const ArgumentInfo* argInfo)
{
const Severity severity = getSeverity(argInfo);
if (!mSettings->severity.isEnabled(severity))
return;
std::ostringstream errmsg;
errmsg << "%p in format string (no. " << numFormat << ") requires an address but the argument type is ";
argumentType(errmsg, argInfo);
errmsg << ".";
reportError(tok, severity, "invalidPrintfArgType_p", errmsg.str(), CWE686, Certainty::normal);
}
static void printfFormatType(std::ostream& os, const std::string& specifier, bool isUnsigned)
{
os << "\'";
if (specifier[0] == 'l') {
if (specifier[1] == 'l')
os << (isUnsigned ? "unsigned " : "") << "long long";
else
os << (isUnsigned ? "unsigned " : "") << "long";
} else if (specifier[0] == 'h') {
if (specifier[1] == 'h')
os << (isUnsigned ? "unsigned " : "") << "char";
else
os << (isUnsigned ? "unsigned " : "") << "short";
} else if (specifier.find("I32") != std::string::npos) {
os << (isUnsigned ? "unsigned " : "") << "__int32";
} else if (specifier.find("I64") != std::string::npos) {
os << (isUnsigned ? "unsigned " : "") << "__int64";
} else if (specifier[0] == 'I') {
os << (isUnsigned ? "size_t" : "ptrdiff_t");
} else if (specifier[0] == 'j') {
if (isUnsigned)
os << "uintmax_t";
else
os << "intmax_t";
} else if (specifier[0] == 'z') {
if (specifier[1] == 'd' || specifier[1] == 'i')
os << "ssize_t";
else
os << "size_t";
} else if (specifier[0] == 't') {
os << (isUnsigned ? "unsigned " : "") << "ptrdiff_t";
} else if (specifier[0] == 'L') {
os << (isUnsigned ? "unsigned " : "") << "long long";
} else {
os << (isUnsigned ? "unsigned " : "") << "int";
}
os << "\'";
}
void CheckIO::invalidPrintfArgTypeError_uint(const Token* tok, nonneg int numFormat, const std::string& specifier, const ArgumentInfo* argInfo)
{
const Severity severity = getSeverity(argInfo);
if (!mSettings->severity.isEnabled(severity))
return;
std::ostringstream errmsg;
errmsg << "%" << specifier << " in format string (no. " << numFormat << ") requires ";
printfFormatType(errmsg, specifier, true);
errmsg << " but the argument type is ";
argumentType(errmsg, argInfo);
errmsg << ".";
reportError(tok, severity, "invalidPrintfArgType_uint", errmsg.str(), CWE686, Certainty::normal);
}
void CheckIO::invalidPrintfArgTypeError_sint(const Token* tok, nonneg int numFormat, const std::string& specifier, const ArgumentInfo* argInfo)
{
const Severity severity = getSeverity(argInfo);
if (!mSettings->severity.isEnabled(severity))
return;
std::ostringstream errmsg;
errmsg << "%" << specifier << " in format string (no. " << numFormat << ") requires ";
printfFormatType(errmsg, specifier, false);
errmsg << " but the argument type is ";
argumentType(errmsg, argInfo);
errmsg << ".";
reportError(tok, severity, "invalidPrintfArgType_sint", errmsg.str(), CWE686, Certainty::normal);
}
void CheckIO::invalidPrintfArgTypeError_float(const Token* tok, nonneg int numFormat, const std::string& specifier, const ArgumentInfo* argInfo)
{
const Severity severity = getSeverity(argInfo);
if (!mSettings->severity.isEnabled(severity))
return;
std::ostringstream errmsg;
errmsg << "%" << specifier << " in format string (no. " << numFormat << ") requires \'";
if (specifier[0] == 'L')
errmsg << "long ";
errmsg << "double\' but the argument type is ";
argumentType(errmsg, argInfo);
errmsg << ".";
reportError(tok, severity, "invalidPrintfArgType_float", errmsg.str(), CWE686, Certainty::normal);
}
Severity CheckIO::getSeverity(const CheckIO::ArgumentInfo *argInfo)
{
return (argInfo && argInfo->typeToken && !argInfo->typeToken->originalName().empty()) ? Severity::portability : Severity::warning;
}
void CheckIO::argumentType(std::ostream& os, const ArgumentInfo * argInfo)
{
if (argInfo) {
os << "\'";
const Token *type = argInfo->typeToken;
if (type->tokType() == Token::eString) {
if (type->isLong())
os << "const wchar_t *";
else
os << "const char *";
} else {
if (type->originalName().empty()) {
if (type->strAt(-1) == "const")
os << "const ";
while (Token::Match(type, "const|struct")) {
os << type->str() << " ";
type = type->next();
}
while (Token::Match(type, "%any% ::")) {
os << type->str() << "::";
type = type->tokAt(2);
}
os << type->stringify(false, true, false);
if (type->strAt(1) == "*" && !argInfo->element)
os << " *";
else if (argInfo->variableInfo && !argInfo->element && argInfo->variableInfo->isArray())
os << " *";
else if (type->strAt(1) == "*" && argInfo->variableInfo && argInfo->element && argInfo->variableInfo->isArray())
os << " *";
if (argInfo->address)
os << " *";
} else {
if (type->isUnsigned()) {
if (type->originalName() == "__int64" || type->originalName() == "__int32" || type->originalName() == "ptrdiff_t")
os << "unsigned ";
}
os << type->originalName();
if (type->strAt(1) == "*" || argInfo->address)
os << " *";
os << " {aka " << type->stringify(false, true, false);
if (type->strAt(1) == "*" || argInfo->address)
os << " *";
os << "}";
}
}
os << "\'";
} else
os << "Unknown";
}
void CheckIO::invalidLengthModifierError(const Token* tok, nonneg int numFormat, const std::string& modifier)
{
if (!mSettings->severity.isEnabled(Severity::warning) && !mSettings->isPremiumEnabled("invalidLengthModifierError"))
return;
std::ostringstream errmsg;
errmsg << "'" << modifier << "' in format string (no. " << numFormat << ") is a length modifier and cannot be used without a conversion specifier.";
reportError(tok, Severity::warning, "invalidLengthModifierError", errmsg.str(), CWE704, Certainty::normal);
}
void CheckIO::invalidScanfFormatWidthError(const Token* tok, nonneg int numFormat, int width, const Variable *var, const std::string& specifier)
{
MathLib::bigint arrlen = 0;
std::string varname;
if (var) {
arrlen = var->dimension(0);
varname = var->name();
}
std::ostringstream errmsg;
if (arrlen > width) {
if (tok != nullptr && (!mSettings->certainty.isEnabled(Certainty::inconclusive) || !mSettings->severity.isEnabled(Severity::warning)))
return;
errmsg << "Width " << width << " given in format string (no. " << numFormat << ") is smaller than destination buffer"
<< " '" << varname << "[" << arrlen << "]'.";
reportError(tok, Severity::warning, "invalidScanfFormatWidth_smaller", errmsg.str(), CWE(0U), Certainty::inconclusive);
} else {
errmsg << "Width " << width << " given in format string (no. " << numFormat << ") is larger than destination buffer '"
<< varname << "[" << arrlen << "]', use %" << (specifier == "c" ? arrlen : (arrlen - 1)) << specifier << " to prevent overflowing it.";
reportError(tok, Severity::error, "invalidScanfFormatWidth", errmsg.str(), CWE687, Certainty::normal);
}
}
| null |
924 | cpp | cppcheck | path.cpp | lib/path.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if defined(__GNUC__) && (defined(_WIN32) || defined(__CYGWIN__))
#undef __STRICT_ANSI__
#endif
//#define LOG_EMACS_MARKER
#include "path.h"
#include "utils.h"
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#ifdef LOG_EMACS_MARKER
#include <iostream>
#endif
#include <sys/stat.h>
#include <unordered_set>
#include <utility>
#include <simplecpp.h>
#ifndef _WIN32
#include <sys/types.h>
#include <unistd.h>
#else
#include <direct.h>
#include <windows.h>
#endif
#if defined(__CYGWIN__)
#include <strings.h>
#endif
#if defined(__APPLE__)
#include <mach-o/dyld.h>
#endif
/** Is the filesystem case insensitive? */
static constexpr bool caseInsensitiveFilesystem()
{
#if defined(_WIN32) || (defined(__APPLE__) && defined(__MACH__))
// Windows is case insensitive
// MacOS is case insensitive by default (also supports case sensitivity)
return true;
#else
// TODO: Non-windows filesystems might be case insensitive
// needs to be determined per filesystem and location - e.g. /sys/fs/ext4/features/casefold
return false;
#endif
}
std::string Path::toNativeSeparators(std::string path)
{
#if defined(_WIN32)
constexpr char separ = '/';
constexpr char native = '\\';
#else
constexpr char separ = '\\';
constexpr char native = '/';
#endif
std::replace(path.begin(), path.end(), separ, native);
return path;
}
std::string Path::fromNativeSeparators(std::string path)
{
constexpr char nonnative = '\\';
constexpr char newsepar = '/';
std::replace(path.begin(), path.end(), nonnative, newsepar);
return path;
}
std::string Path::simplifyPath(std::string originalPath)
{
return simplecpp::simplifyPath(std::move(originalPath));
}
std::string Path::getPathFromFilename(const std::string &filename)
{
const std::size_t pos = filename.find_last_of("\\/");
if (pos != std::string::npos)
return filename.substr(0, 1 + pos);
return "";
}
bool Path::sameFileName(const std::string &fname1, const std::string &fname2)
{
return caseInsensitiveFilesystem() ? (caseInsensitiveStringCompare(fname1, fname2) == 0) : (fname1 == fname2);
}
std::string Path::removeQuotationMarks(std::string path)
{
path.erase(std::remove(path.begin(), path.end(), '\"'), path.end());
return path;
}
std::string Path::getFilenameExtension(const std::string &path, bool lowercase)
{
const std::string::size_type dotLocation = path.find_last_of('.');
if (dotLocation == std::string::npos)
return "";
std::string extension = path.substr(dotLocation);
if (lowercase || caseInsensitiveFilesystem()) {
// on a case insensitive filesystem the case doesn't matter so
// let's return the extension in lowercase
strTolower(extension);
}
return extension;
}
std::string Path::getFilenameExtensionInLowerCase(const std::string &path)
{
return getFilenameExtension(path, true);
}
std::string Path::getCurrentPath()
{
char currentPath[4096];
#ifndef _WIN32
if (getcwd(currentPath, 4096) != nullptr)
#else
if (_getcwd(currentPath, 4096) != nullptr)
#endif
return std::string(currentPath);
return "";
}
std::string Path::getCurrentExecutablePath(const char* fallback)
{
char buf[4096] = {};
bool success{};
#ifdef _WIN32
success = (GetModuleFileNameA(nullptr, buf, sizeof(buf)) < sizeof(buf));
#elif defined(__APPLE__)
uint32_t size = sizeof(buf);
success = (_NSGetExecutablePath(buf, &size) == 0);
#else
const char* procPath =
#ifdef __SVR4 // Solaris
"/proc/self/path/a.out";
#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
"/proc/curproc/file";
#else // Linux
"/proc/self/exe";
#endif
// readlink does not null-terminate the string if the buffer is too small, therefore write bufsize - 1
success = (readlink(procPath, buf, sizeof(buf) - 1) != -1);
#endif
return success ? std::string(buf) : std::string(fallback);
}
bool Path::isAbsolute(const std::string& path)
{
const std::string& nativePath = toNativeSeparators(path);
#ifdef _WIN32
if (path.length() < 2)
return false;
// On Windows, 'C:\foo\bar' is an absolute path, while 'C:foo\bar' is not
return startsWith(nativePath, "\\\\") || (std::isalpha(nativePath[0]) != 0 && nativePath.compare(1, 2, ":\\") == 0);
#else
return !nativePath.empty() && nativePath[0] == '/';
#endif
}
std::string Path::getRelativePath(const std::string& absolutePath, const std::vector<std::string>& basePaths)
{
for (const std::string &bp : basePaths) {
if (absolutePath == bp || bp.empty()) // Seems to be a file, or path is empty
continue;
if (absolutePath.compare(0, bp.length(), bp) != 0)
continue;
if (endsWith(bp,'/'))
return absolutePath.substr(bp.length());
if (absolutePath.size() > bp.size() && absolutePath[bp.length()] == '/')
return absolutePath.substr(bp.length() + 1);
}
return absolutePath;
}
static const std::unordered_set<std::string> cpp_src_exts = {
".cpp", ".cxx", ".cc", ".c++", ".tpp", ".txx", ".ipp", ".ixx"
};
static const std::unordered_set<std::string> c_src_exts = {
".c", ".cl"
};
static const std::unordered_set<std::string> header_exts = {
".h", ".hpp", ".h++", ".hxx", ".hh"
};
bool Path::acceptFile(const std::string &path, const std::set<std::string> &extra)
{
bool header = false;
return (identify(path, false, &header) != Standards::Language::None && !header) || extra.find(getFilenameExtension(path)) != extra.end();
}
static bool hasEmacsCppMarker(const char* path)
{
// TODO: identify is called three times for each file
// Preprocessor::loadFiles() -> createDUI()
// Preprocessor::preprocess() -> createDUI()
// TokenList::createTokens() -> TokenList::determineCppC()
#ifdef LOG_EMACS_MARKER
std::cout << path << '\n';
#endif
FILE *fp = fopen(path, "rt");
if (!fp)
return false;
std::string buf(128, '\0');
{
// TODO: read the whole first line only
const char * const res = fgets(const_cast<char*>(buf.data()), buf.size(), fp);
fclose(fp);
fp = nullptr;
if (!res)
return false; // failed to read file
}
// TODO: replace with regular expression
const auto pos1 = buf.find("-*-");
if (pos1 == std::string::npos)
return false; // no start marker
const auto pos_nl = buf.find_first_of("\r\n");
if (pos_nl != std::string::npos && (pos_nl < pos1)) {
#ifdef LOG_EMACS_MARKER
std::cout << path << " - Emacs marker not on the first line" << '\n';
#endif
return false; // not on first line
}
const auto pos2 = buf.find("-*-", pos1 + 3);
// TODO: make sure we have read the whole line before bailing out
if (pos2 == std::string::npos) {
#ifdef LOG_EMACS_MARKER
std::cout << path << " - Emacs marker not terminated" << '\n';
#endif
return false; // no end marker
}
#ifdef LOG_EMACS_MARKER
std::cout << "Emacs marker: '" << buf.substr(pos1, (pos2 + 3) - pos1) << "'" << '\n';
#endif
// TODO: support /* */ comments
const std::string buf_trim = trim(buf); // trim whitespaces
if (buf_trim[0] == '/' && buf_trim[1] == '*') {
const auto pos_cmt = buf.find("*/", 2);
if (pos_cmt != std::string::npos && pos_cmt < (pos2 + 3))
{
#ifdef LOG_EMACS_MARKER
std::cout << path << " - Emacs marker not contained in C-style comment block: '" << buf.substr(pos1, (pos2 + 3) - pos1) << "'" << '\n';
#endif
return false; // not in a comment
}
}
else if (buf_trim[0] != '/' || buf_trim[1] != '/') {
#ifdef LOG_EMACS_MARKER
std::cout << path << " - Emacs marker not in a comment: '" << buf.substr(pos1, (pos2 + 3) - pos1) << "'" << '\n';
#endif
return false; // not in a comment
}
// there are more variations with lowercase and no whitespaces
// -*- C++ -*-
// -*- Mode: C++; -*-
// -*- Mode: C++; c-basic-offset: 8 -*-
std::string marker = trim(buf.substr(pos1 + 3, pos2 - pos1 - 3), " ;");
// cut off additional attributes
const auto pos_semi = marker.find(';');
if (pos_semi != std::string::npos)
marker.resize(pos_semi);
findAndReplace(marker, "mode:", "");
findAndReplace(marker, "Mode:", "");
marker = trim(marker);
if (marker == "C++" || marker == "c++") {
// NOLINTNEXTLINE(readability-simplify-boolean-expr) - TODO: FP
return true; // C++ marker found
}
//if (marker == "C" || marker == "c")
// return false;
#ifdef LOG_EMACS_MARKER
std::cout << path << " - unmatched Emacs marker: '" << marker << "'" << '\n';
#endif
return false; // marker is not a C++ one
}
Standards::Language Path::identify(const std::string &path, bool cppHeaderProbe, bool *header)
{
// cppcheck-suppress uninitvar - TODO: FP
if (header)
*header = false;
std::string ext = getFilenameExtension(path);
// standard library headers have no extension
if (cppHeaderProbe && ext.empty()) {
if (hasEmacsCppMarker(path.c_str())) {
if (header)
*header = true;
return Standards::Language::CPP;
}
return Standards::Language::None;
}
if (ext == ".C")
return Standards::Language::CPP;
if (c_src_exts.find(ext) != c_src_exts.end())
return Standards::Language::C;
// cppcheck-suppress knownConditionTrueFalse - TODO: FP
if (!caseInsensitiveFilesystem())
strTolower(ext);
if (ext == ".h") {
if (header)
*header = true;
if (cppHeaderProbe && hasEmacsCppMarker(path.c_str()))
return Standards::Language::CPP;
return Standards::Language::C;
}
if (cpp_src_exts.find(ext) != cpp_src_exts.end())
return Standards::Language::CPP;
if (header_exts.find(ext) != header_exts.end()) {
if (header)
*header = true;
return Standards::Language::CPP;
}
return Standards::Language::None;
}
bool Path::isHeader(const std::string &path)
{
bool header;
(void)identify(path, false, &header);
return header;
}
std::string Path::getAbsoluteFilePath(const std::string& filePath)
{
if (filePath.empty())
return "";
std::string absolute_path;
#ifdef _WIN32
char absolute[_MAX_PATH];
if (_fullpath(absolute, filePath.c_str(), _MAX_PATH))
absolute_path = absolute;
if (!absolute_path.empty() && absolute_path.back() == '\\')
absolute_path.pop_back();
#elif defined(__linux__) || defined(__sun) || defined(__hpux) || defined(__GNUC__) || defined(__CPPCHECK__)
// simplify the path since any non-existent part has to exist even if discarded by ".."
std::string spath = Path::simplifyPath(filePath);
char * absolute = realpath(spath.c_str(), nullptr);
if (absolute)
absolute_path = absolute;
free(absolute);
// only throw on realpath() fialure to resolve a path when the given one was non-existent
if (!spath.empty() && absolute_path.empty() && !exists(spath))
throw std::runtime_error("path '" + filePath + "' does not exist");
#else
#error Platform absolute path function needed
#endif
return absolute_path;
}
std::string Path::stripDirectoryPart(const std::string &file)
{
#if defined(_WIN32) && !defined(__MINGW32__)
constexpr char native = '\\';
#else
constexpr char native = '/';
#endif
const std::string::size_type p = file.rfind(native);
if (p != std::string::npos) {
return file.substr(p + 1);
}
return file;
}
#ifdef _WIN32
using mode_t = unsigned short;
#endif
static mode_t file_type(const std::string &path)
{
struct stat file_stat;
if (stat(path.c_str(), &file_stat) == -1)
return 0;
return file_stat.st_mode & S_IFMT;
}
bool Path::isFile(const std::string &path)
{
return file_type(path) == S_IFREG;
}
bool Path::isDirectory(const std::string &path)
{
return file_type(path) == S_IFDIR;
}
bool Path::exists(const std::string &path)
{
const auto type = file_type(path);
return type == S_IFREG || type == S_IFDIR;
}
std::string Path::join(const std::string& path1, const std::string& path2) {
if (path1.empty() || path2.empty())
return path1 + path2;
if (path2.front() == '/')
return path2;
return ((path1.back() == '/') ? path1 : (path1 + "/")) + path2;
}
| null |
925 | cpp | cppcheck | check.cpp | lib/check.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2023 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#include "check.h"
#include "errorlogger.h"
#include "settings.h"
#include "token.h"
#include "tokenize.h"
#include "vfvalue.h"
#include <algorithm>
#include <cctype>
#include <iostream>
#include <stdexcept>
#include <utility>
//---------------------------------------------------------------------------
Check::Check(const std::string &aname)
: mName(aname)
{
{
const auto it = std::find_if(instances().begin(), instances().end(), [&](const Check *i) {
return i->name() == aname;
});
if (it != instances().end())
throw std::runtime_error("'" + aname + "' instance already exists");
}
// make sure the instances are sorted
const auto it = std::find_if(instances().begin(), instances().end(), [&](const Check* i) {
return i->name() > aname;
});
if (it == instances().end())
instances().push_back(this);
else
instances().insert(it, this);
}
void Check::writeToErrorList(const ErrorMessage &errmsg)
{
std::cout << errmsg.toXML() << std::endl;
}
void Check::reportError(const std::list<const Token *> &callstack, Severity severity, const std::string &id, const std::string &msg, const CWE &cwe, Certainty certainty)
{
// TODO: report debug warning when error is for a disabled severity
const ErrorMessage errmsg(callstack, mTokenizer ? &mTokenizer->list : nullptr, severity, id, msg, cwe, certainty);
if (mErrorLogger)
mErrorLogger->reportErr(errmsg);
else
writeToErrorList(errmsg);
}
void Check::reportError(const ErrorPath &errorPath, Severity severity, const char id[], const std::string &msg, const CWE &cwe, Certainty certainty)
{
// TODO: report debug warning when error is for a disabled severity
const ErrorMessage errmsg(errorPath, mTokenizer ? &mTokenizer->list : nullptr, severity, id, msg, cwe, certainty);
if (mErrorLogger)
mErrorLogger->reportErr(errmsg);
else
writeToErrorList(errmsg);
}
bool Check::wrongData(const Token *tok, const char *str)
{
if (mSettings->daca)
reportError(tok, Severity::debug, "DacaWrongData", "Wrong data detected by condition " + std::string(str));
return true;
}
std::list<Check *> &Check::instances()
{
#ifdef __SVR4
// Under Solaris, destructors are called in wrong order which causes a segmentation fault.
// This fix ensures pointer remains valid and reachable until program terminates.
static std::list<Check *> *_instances= new std::list<Check *>;
return *_instances;
#else
static std::list<Check *> _instances;
return _instances;
#endif
}
std::string Check::getMessageId(const ValueFlow::Value &value, const char id[])
{
if (value.condition != nullptr)
return id + std::string("Cond");
if (value.safe)
return std::string("safe") + (char)std::toupper(id[0]) + (id + 1);
return id;
}
ErrorPath Check::getErrorPath(const Token* errtok, const ValueFlow::Value* value, std::string bug) const
{
ErrorPath errorPath;
if (!value) {
errorPath.emplace_back(errtok, std::move(bug));
} else if (mSettings->verbose || mSettings->xml || !mSettings->templateLocation.empty()) {
errorPath = value->errorPath;
errorPath.emplace_back(errtok, std::move(bug));
} else {
if (value->condition)
errorPath.emplace_back(value->condition, "condition '" + value->condition->expressionString() + "'");
//else if (!value->isKnown() || value->defaultArg)
// errorPath = value->callstack;
errorPath.emplace_back(errtok, std::move(bug));
}
return errorPath;
}
void Check::logChecker(const char id[])
{
reportError(nullptr, Severity::internal, "logChecker", id);
}
| null |
926 | cpp | cppcheck | sourcelocation.h | lib/sourcelocation.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef sourcelocationH
#define sourcelocationH
#include "config.h"
#ifdef __CPPCHECK__
#define CPPCHECK_HAS_SOURCE_LOCATION 0
#define CPPCHECK_HAS_SOURCE_LOCATION_TS 0
#define CPPCHECK_HAS_SOURCE_LOCATION_INTRINSICS 0
#else
#if __has_include(<source_location>) && __cplusplus >= 202003L
#define CPPCHECK_HAS_SOURCE_LOCATION 1
#else
#define CPPCHECK_HAS_SOURCE_LOCATION 0
#endif
#if __has_include(<experimental/source_location>) && __cplusplus >= 201402L
#define CPPCHECK_HAS_SOURCE_LOCATION_TS 1
#else
#define CPPCHECK_HAS_SOURCE_LOCATION_TS 0
#endif
#if __has_builtin(__builtin_FILE)
#define CPPCHECK_HAS_SOURCE_LOCATION_INTRINSICS 1
#if !__has_builtin(__builtin_COLUMN)
#define __builtin_COLUMN() 0
#endif
#else
#define CPPCHECK_HAS_SOURCE_LOCATION_INTRINSICS 0
#endif
#endif
#if CPPCHECK_HAS_SOURCE_LOCATION
#include <source_location>
using SourceLocation = std::source_location;
#elif CPPCHECK_HAS_SOURCE_LOCATION_TS
#include <experimental/source_location>
using SourceLocation = std::experimental::source_location;
#else
#include <cstdint>
struct SourceLocation {
#if CPPCHECK_HAS_SOURCE_LOCATION_INTRINSICS
static SourceLocation current(std::uint_least32_t line = __builtin_LINE(),
std::uint_least32_t column = __builtin_COLUMN(),
const char* file_name = __builtin_FILE(),
const char* function_name = __builtin_FUNCTION())
{
SourceLocation result{};
result.m_line = line;
result.m_column = column;
result.m_file_name = file_name;
result.m_function_name = function_name;
return result;
}
#else
static SourceLocation current() {
return SourceLocation();
}
#endif
std::uint_least32_t m_line = 0;
std::uint_least32_t m_column = 0;
const char* m_file_name = "";
const char* m_function_name = "";
std::uint_least32_t line() const {
return m_line;
}
std::uint_least32_t column() const {
return m_column;
}
const char* file_name() const {
return m_file_name;
}
const char* function_name() const {
return m_function_name;
}
};
#endif
#endif
| null |
927 | cpp | cppcheck | forwardanalyzer.h | lib/forwardanalyzer.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef forwardanalyzerH
#define forwardanalyzerH
#include "analyzer.h"
class ErrorLogger;
class Settings;
class Token;
class TokenList;
template<class T> class ValuePtr;
Analyzer::Result valueFlowGenericForward(Token* start,
const Token* end,
const ValuePtr<Analyzer>& a,
const TokenList& tokenList,
ErrorLogger& errorLogger,
const Settings& settings);
Analyzer::Result valueFlowGenericForward(Token* start, const ValuePtr<Analyzer>& a, const TokenList& tokenList, ErrorLogger& errorLogger, const Settings& settings);
#endif
| null |
928 | cpp | cppcheck | checkautovariables.cpp | lib/checkautovariables.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
// Auto variables checks
//---------------------------------------------------------------------------
#include "checkautovariables.h"
#include "astutils.h"
#include "library.h"
#include "settings.h"
#include "symboldatabase.h"
#include "token.h"
#include "tokenize.h"
#include "valueflow.h"
#include "vfvalue.h"
#include <algorithm>
#include <list>
#include <unordered_set>
#include <utility>
#include <vector>
//---------------------------------------------------------------------------
// Register this check class into cppcheck by creating a static instance of it..
namespace {
CheckAutoVariables instance;
}
static const CWE CWE398(398U); // Indicator of Poor Code Quality
static const CWE CWE562(562U); // Return of Stack Variable Address
static const CWE CWE590(590U); // Free of Memory not on the Heap
static bool isPtrArg(const Token *tok)
{
const Variable *var = tok->variable();
return (var && var->isArgument() && var->isPointer());
}
static bool isArrayArg(const Token *tok, const Settings& settings)
{
const Variable *var = tok->variable();
return (var && var->isArgument() && var->isArray() && !settings.library.isentrypoint(var->scope()->className));
}
static bool isArrayVar(const Token *tok)
{
const Variable *var = tok->variable();
return (var && var->isArray() && !var->isArgument());
}
static bool isRefPtrArg(const Token *tok)
{
const Variable *var = tok->variable();
return (var && var->isArgument() && var->isReference() && var->isPointer());
}
static bool isNonReferenceArg(const Token *tok)
{
const Variable *var = tok->variable();
return (var && var->isArgument() && !var->isReference() && (var->isPointer() || (var->valueType() && var->valueType()->type >= ValueType::Type::CONTAINER) || var->type()));
}
static bool isAutoVar(const Token *tok)
{
const Variable *var = tok->variable();
if (!var || !var->isLocal() || var->isStatic())
return false;
if (var->isReference()) {
// address of reference variable can be taken if the address
// of the variable it points at is not a auto-var
// TODO: check what the reference variable references.
return false;
}
if (Token::Match(tok, "%name% .|::")) {
do {
tok = tok->tokAt(2);
} while (Token::Match(tok, "%name% .|::"));
if (Token::Match(tok, "%name% ("))
return false;
}
return true;
}
static bool isAutoVarArray(const Token *tok)
{
if (!tok)
return false;
// &x[..]
if (tok->isUnaryOp("&") && Token::simpleMatch(tok->astOperand1(), "["))
return isAutoVarArray(tok->astOperand1()->astOperand1());
// x+y
if (tok->str() == "+")
return isAutoVarArray(tok->astOperand1()) || isAutoVarArray(tok->astOperand2());
// x-intexpr
if (tok->str() == "-")
return isAutoVarArray(tok->astOperand1()) &&
tok->astOperand2() &&
tok->astOperand2()->valueType() &&
tok->astOperand2()->valueType()->isIntegral();
const Variable *var = tok->variable();
if (!var)
return false;
// Variable
if (var->isLocal() && !var->isStatic() && var->isArray() && !var->isPointer())
return true;
// ValueFlow
if (var->isPointer() && !var->isArgument()) {
for (std::list<ValueFlow::Value>::const_iterator it = tok->values().cbegin(); it != tok->values().cend(); ++it) {
const ValueFlow::Value &val = *it;
if (val.isTokValue() && isAutoVarArray(val.tokvalue))
return true;
}
}
return false;
}
static bool isLocalContainerBuffer(const Token* tok)
{
if (!tok)
return false;
// x+y
if (tok->str() == "+")
return isLocalContainerBuffer(tok->astOperand1()) || isLocalContainerBuffer(tok->astOperand2());
if (tok->str() != "(" || !Token::simpleMatch(tok->astOperand1(), "."))
return false;
tok = tok->astOperand1()->astOperand1();
const Variable* var = tok->variable();
if (!var || !var->isLocal() || var->isStatic())
return false;
const Library::Container::Yield yield = astContainerYield(tok);
return yield == Library::Container::Yield::BUFFER || yield == Library::Container::Yield::BUFFER_NT;
}
static bool isAddressOfLocalVariable(const Token *expr)
{
if (!expr)
return false;
if (Token::Match(expr, "+|-"))
return isAddressOfLocalVariable(expr->astOperand1()) || isAddressOfLocalVariable(expr->astOperand2());
if (expr->isCast())
return isAddressOfLocalVariable(expr->astOperand2() ? expr->astOperand2() : expr->astOperand1());
if (expr->isUnaryOp("&")) {
const Token *op = expr->astOperand1();
bool deref = false;
while (Token::Match(op, ".|[")) {
if (op->originalName() == "->")
return false;
if (op->str() == "[")
deref = true;
op = op->astOperand1();
}
return op && isAutoVar(op) && (!deref || !op->variable()->isPointer());
}
return false;
}
static bool variableIsUsedInScope(const Token* start, nonneg int varId, const Scope *scope)
{
if (!start) // Ticket #5024
return false;
for (const Token *tok = start; tok && tok != scope->bodyEnd; tok = tok->next()) {
if (tok->varId() == varId)
return true;
const Scope::ScopeType scopeType = tok->scope()->type;
if (scopeType == Scope::eFor || scopeType == Scope::eDo || scopeType == Scope::eWhile) // In case of loops, better checking would be necessary
return true;
if (Token::simpleMatch(tok, "asm ("))
return true;
}
return false;
}
void CheckAutoVariables::assignFunctionArg()
{
const bool printStyle = mSettings->severity.isEnabled(Severity::style);
const bool printWarning = mSettings->severity.isEnabled(Severity::warning);
if (!printStyle && !printWarning && !mSettings->isPremiumEnabled("uselessAssignmentPtrArg"))
return;
logChecker("CheckAutoVariables::assignFunctionArg"); // style,warning
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token *tok = scope->bodyStart; tok && tok != scope->bodyEnd; tok = tok->next()) {
// TODO: What happens if this is removed?
if (tok->astParent())
continue;
if (!(tok->isAssignmentOp() || tok->tokType() == Token::eIncDecOp) || !Token::Match(tok->astOperand1(), "%var%"))
continue;
const Token* const vartok = tok->astOperand1();
if (isNonReferenceArg(vartok) &&
!Token::Match(vartok->next(), "= %varid% ;", vartok->varId()) &&
!variableIsUsedInScope(Token::findsimplematch(vartok->next(), ";"), vartok->varId(), scope) &&
!Token::findsimplematch(vartok, "goto", scope->bodyEnd)) {
if (vartok->variable()->isPointer() && printWarning)
errorUselessAssignmentPtrArg(vartok);
else if (printStyle)
errorUselessAssignmentArg(vartok);
}
}
}
}
static bool isAutoVariableRHS(const Token* tok) {
return isAddressOfLocalVariable(tok) || isAutoVarArray(tok) || isLocalContainerBuffer(tok);
}
static bool hasOverloadedAssignment(const Token* tok, bool& inconclusive)
{
inconclusive = false;
if (tok->isC())
return false;
if (const ValueType* vt = tok->valueType()) {
if (vt->pointer && !Token::simpleMatch(tok->astParent(), "*"))
return false;
if (vt->container && vt->container->stdStringLike)
return true;
if (vt->typeScope)
return std::any_of(vt->typeScope->functionList.begin(), vt->typeScope->functionList.end(), [](const Function& f) { // TODO: compare argument type
return f.name() == "operator=";
});
return false;
}
inconclusive = true;
return true;
}
void CheckAutoVariables::autoVariables()
{
logChecker("CheckAutoVariables::autoVariables");
const bool printInconclusive = mSettings->certainty.isEnabled(Certainty::inconclusive);
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token *tok = scope->bodyStart; tok && tok != scope->bodyEnd; tok = tok->next()) {
// Skip lambda..
if (const Token *lambdaEndToken = findLambdaEndToken(tok)) {
tok = lambdaEndToken;
continue;
}
// Critical assignment
if (Token::Match(tok, "[;{}] %var% =") && isRefPtrArg(tok->next()) && isAutoVariableRHS(tok->tokAt(2)->astOperand2())) {
checkAutoVariableAssignment(tok->next(), false);
} else if (Token::Match(tok, "[;{}] * %var% =") && isPtrArg(tok->tokAt(2)) && isAutoVariableRHS(tok->tokAt(3)->astOperand2())) {
const Token* lhs = tok->tokAt(2);
bool inconclusive = false;
if (!hasOverloadedAssignment(lhs, inconclusive) || (printInconclusive && inconclusive))
checkAutoVariableAssignment(tok->next(), inconclusive);
tok = tok->tokAt(4);
} else if (Token::Match(tok, "[;{}] %var% . %var% =") && isPtrArg(tok->next()) && isAutoVariableRHS(tok->tokAt(4)->astOperand2())) {
const Token* lhs = tok->tokAt(3);
bool inconclusive = false;
if (!hasOverloadedAssignment(lhs, inconclusive) || (printInconclusive && inconclusive))
checkAutoVariableAssignment(tok->next(), inconclusive);
tok = tok->tokAt(5);
} else if (Token::Match(tok, "[;{}] %var% [") && Token::simpleMatch(tok->linkAt(2), "] =") &&
(isPtrArg(tok->next()) || isArrayArg(tok->next(), *mSettings)) &&
isAutoVariableRHS(tok->linkAt(2)->next()->astOperand2())) {
errorAutoVariableAssignment(tok->next(), false);
}
// Invalid pointer deallocation
else if ((Token::Match(tok, "%name% ( %var%|%str% ) ;") && mSettings->library.getDeallocFuncInfo(tok)) ||
(tok->isCpp() && Token::Match(tok, "delete [| ]| (| %var%|%str% !!["))) {
tok = Token::findmatch(tok->next(), "%var%|%str%");
if (Token::simpleMatch(tok->astParent(), "."))
continue;
if (isArrayVar(tok) || tok->tokType() == Token::eString)
errorInvalidDeallocation(tok, nullptr);
else if (tok->variable() && tok->variable()->isPointer()) {
for (const ValueFlow::Value &v : tok->values()) {
if (v.isImpossible())
continue;
if ((v.isTokValue() && (isArrayVar(v.tokvalue) || ((v.tokvalue->tokType() == Token::eString)))) ||
(v.isLocalLifetimeValue() && v.lifetimeKind == ValueFlow::Value::LifetimeKind::Address && !Token::simpleMatch(v.tokvalue, "("))) {
errorInvalidDeallocation(tok, &v);
break;
}
}
}
} else if ((Token::Match(tok, "%name% ( & %var% ) ;") && mSettings->library.getDeallocFuncInfo(tok)) ||
(tok->isCpp() && Token::Match(tok, "delete [| ]| (| & %var% !!["))) {
tok = Token::findmatch(tok->next(), "%var%");
if (isAutoVar(tok))
errorInvalidDeallocation(tok, nullptr);
}
}
}
}
bool CheckAutoVariables::checkAutoVariableAssignment(const Token *expr, bool inconclusive, const Token *startToken)
{
if (!startToken)
startToken = Token::findsimplematch(expr, "=")->next();
for (const Token *tok = startToken; tok; tok = tok->next()) {
if (tok->str() == "}" && tok->scope()->type == Scope::ScopeType::eFunction)
errorAutoVariableAssignment(expr, inconclusive);
if (Token::Match(tok, "return|throw|break|continue")) {
errorAutoVariableAssignment(expr, inconclusive);
return true;
}
if (Token::simpleMatch(tok, "=")) {
const Token *lhs = tok;
while (Token::Match(lhs->previous(), "%name%|.|*|]")) {
if (lhs->linkAt(-1))
lhs = lhs->linkAt(-1);
else
lhs = lhs->previous();
}
const Token *e = expr;
while (e->str() != "=" && lhs->str() == e->str()) {
e = e->next();
lhs = lhs->next();
}
if (lhs->str() == "=")
return false;
}
if (Token::simpleMatch(tok, "if (")) {
const Token *ifStart = tok->linkAt(1)->next();
return checkAutoVariableAssignment(expr, inconclusive, ifStart) || checkAutoVariableAssignment(expr, inconclusive, ifStart->link()->next());
}
if (Token::simpleMatch(tok, "} else {"))
tok = tok->linkAt(2);
}
return false;
}
//---------------------------------------------------------------------------
void CheckAutoVariables::errorAutoVariableAssignment(const Token *tok, bool inconclusive)
{
if (!inconclusive) {
reportError(tok, Severity::error, "autoVariables",
"Address of local auto-variable assigned to a function parameter.\n"
"Dangerous assignment - the function parameter is assigned the address of a local "
"auto-variable. Local auto-variables are reserved from the stack which "
"is freed when the function ends. So the pointer to a local variable "
"is invalid after the function ends.", CWE562, Certainty::normal);
} else {
reportError(tok, Severity::error, "autoVariables",
"Address of local auto-variable assigned to a function parameter.\n"
"Function parameter is assigned the address of a local auto-variable. "
"Local auto-variables are reserved from the stack which is freed when "
"the function ends. The address is invalid after the function ends and it "
"might 'leak' from the function through the parameter.",
CWE562,
Certainty::inconclusive);
}
}
void CheckAutoVariables::errorUselessAssignmentArg(const Token *tok)
{
reportError(tok,
Severity::style,
"uselessAssignmentArg",
"Assignment of function parameter has no effect outside the function.", CWE398, Certainty::normal);
}
void CheckAutoVariables::errorUselessAssignmentPtrArg(const Token *tok)
{
reportError(tok,
Severity::warning,
"uselessAssignmentPtrArg",
"Assignment of function parameter has no effect outside the function. Did you forget dereferencing it?", CWE398, Certainty::normal);
}
bool CheckAutoVariables::diag(const Token* tokvalue)
{
if (!tokvalue)
return true;
return !mDiagDanglingTemp.insert(tokvalue).second;
}
//---------------------------------------------------------------------------
static bool isInScope(const Token * tok, const Scope * scope)
{
if (!tok)
return false;
if (!scope)
return false;
const Variable * var = tok->variable();
if (var && (var->isGlobal() || var->isStatic() || var->isExtern()))
return false;
if (tok->scope() && !tok->scope()->isClassOrStructOrUnion() && tok->scope()->isNestedIn(scope))
return true;
if (!var)
return false;
if (var->isArgument() && !var->isReference()) {
const Scope * tokScope = tok->scope();
if (!tokScope)
return false;
if (std::any_of(tokScope->nestedList.cbegin(), tokScope->nestedList.cend(), [&](const Scope* argScope) {
return argScope && argScope->isNestedIn(scope);
}))
return true;
}
return false;
}
static bool isDeadScope(const Token * tok, const Scope * scope)
{
if (!tok)
return false;
if (!scope)
return false;
const Variable * var = tok->variable();
if (var && (!var->isLocal() || var->isStatic() || var->isExtern()))
return false;
if (tok->scope() && tok->scope()->bodyEnd != scope->bodyEnd && precedes(tok->scope()->bodyEnd, scope->bodyEnd))
return true;
return false;
}
static int getPointerDepth(const Token *tok)
{
if (!tok)
return 0;
if (tok->valueType())
return tok->valueType()->pointer;
int n = 0;
std::pair<const Token*, const Token*> decl = Token::typeDecl(tok);
for (const Token* tok2 = decl.first; tok2 != decl.second; tok2 = tok2->next())
if (Token::simpleMatch(tok2, "*"))
n++;
return n;
}
static bool isDeadTemporary(const Token* tok, const Token* expr, const Library* library)
{
if (!isTemporary(tok, library))
return false;
if (expr) {
if (!precedes(nextAfterAstRightmostLeaf(tok->astTop()), nextAfterAstRightmostLeaf(expr->astTop())))
return false;
const Token* parent = tok->astParent();
if (Token::simpleMatch(parent, "{") && Token::simpleMatch(parent->astParent(), ":"))
parent = parent->astParent();
// Is in a for loop
if (astIsRHS(tok) && Token::simpleMatch(parent, ":") && Token::simpleMatch(parent->astParent(), "(") && Token::simpleMatch(parent->astParent()->previous(), "for (")) {
const Token* braces = parent->astParent()->link()->next();
if (precedes(braces, expr) && precedes(expr, braces->link()))
return false;
}
}
return true;
}
static bool isEscapedReference(const Variable* var)
{
if (!var)
return false;
if (!var->isReference())
return false;
const Token * const varDeclEndToken = var->declEndToken();
if (!varDeclEndToken)
return false;
if (!Token::simpleMatch(varDeclEndToken, "="))
return false;
const Token* vartok = varDeclEndToken->astOperand2();
return !isTemporary(vartok, nullptr, false);
}
static bool isDanglingSubFunction(const Token* tokvalue, const Token* tok)
{
if (!tokvalue)
return false;
const Variable* var = tokvalue->variable();
if (!var->isLocal())
return false;
const Function* f = Scope::nestedInFunction(tok->scope());
if (!f)
return false;
const Token* parent = tokvalue->astParent();
while (parent && !Token::Match(parent->previous(), "%name% (")) {
parent = parent->astParent();
}
if (!Token::simpleMatch(parent, "("))
return false;
return exprDependsOnThis(parent);
}
static const Variable* getParentVar(const Token* tok)
{
if (!tok)
return nullptr;
if (Token::simpleMatch(tok, "."))
return getParentVar(tok->astOperand1());
return tok->variable();
}
static bool isAssignedToNonLocal(const Token* tok)
{
if (!Token::simpleMatch(tok->astParent(), "="))
return false;
if (!astIsRHS(tok))
return false;
const Variable* var = getParentVar(tok->astParent()->astOperand1());
if (!var)
return false;
return !var->isLocal() || var->isStatic();
}
void CheckAutoVariables::checkVarLifetimeScope(const Token * start, const Token * end)
{
const bool printInconclusive = mSettings->certainty.isEnabled(Certainty::inconclusive);
if (!start)
return;
const Scope * scope = start->scope();
if (!scope)
return;
// If the scope is not set correctly then skip checking it
if (scope->bodyStart != start)
return;
const bool returnRef = Function::returnsReference(scope->function);
for (const Token *tok = start; tok && tok != end; tok = tok->next()) {
// Return reference from function
if (returnRef && Token::simpleMatch(tok->astParent(), "return")) {
for (const ValueFlow::LifetimeToken& lt : ValueFlow::getLifetimeTokens(tok, *mSettings, true)) {
if (!printInconclusive && lt.inconclusive)
continue;
const Variable* var = lt.token->variable();
if (var && !var->isGlobal() && !var->isStatic() && !var->isReference() && !var->isRValueReference() &&
isInScope(var->nameToken(), tok->scope())) {
errorReturnReference(tok, lt.errorPath, lt.inconclusive);
break;
}
if (isDeadTemporary(lt.token, nullptr, &mSettings->library)) {
errorReturnTempReference(tok, lt.errorPath, lt.inconclusive);
break;
}
}
// Assign reference to non-local variable
} else if (Token::Match(tok->previous(), "&|&& %var% =") && tok->astParent() == tok->next() &&
tok->variable() && tok->variable()->nameToken() == tok &&
tok->variable()->declarationId() == tok->varId() && tok->variable()->isStatic() &&
!tok->variable()->isArgument()) {
ErrorPath errorPath;
const Variable *var = ValueFlow::getLifetimeVariable(tok, errorPath, *mSettings);
if (var && isInScope(var->nameToken(), tok->scope())) {
errorDanglingReference(tok, var, std::move(errorPath));
continue;
}
// Reference to temporary
} else if (tok->variable() && (tok->variable()->isReference() || tok->variable()->isRValueReference())) {
for (const ValueFlow::LifetimeToken& lt : ValueFlow::getLifetimeTokens(getParentLifetime(tok), *mSettings)) {
if (!printInconclusive && lt.inconclusive)
continue;
const Token * tokvalue = lt.token;
if (isDeadTemporary(tokvalue, tok, &mSettings->library)) {
errorDanglingTempReference(tok, lt.errorPath, lt.inconclusive);
break;
}
}
}
const bool escape = Token::simpleMatch(tok->astParent(), "throw") ||
(Token::simpleMatch(tok->astParent(), "return") && !Function::returnsStandardType(scope->function));
std::unordered_set<const Token*> exprs;
for (const ValueFlow::Value& val:tok->values()) {
if (!val.isLocalLifetimeValue() && !val.isSubFunctionLifetimeValue())
continue;
if (!printInconclusive && val.isInconclusive())
continue;
const Token* parent = getParentLifetime(val.tokvalue, mSettings->library);
if (!exprs.insert(parent).second)
continue;
for (const ValueFlow::LifetimeToken& lt : ValueFlow::getLifetimeTokens(parent, *mSettings, escape || isAssignedToNonLocal(tok))) {
const Token * tokvalue = lt.token;
if (val.isLocalLifetimeValue()) {
if (escape) {
if (getPointerDepth(tok) < getPointerDepth(tokvalue))
continue;
if (!ValueFlow::isLifetimeBorrowed(tok, *mSettings))
continue;
if (tokvalue->exprId() == tok->exprId() && !(tok->variable() && tok->variable()->isArray()) &&
!astIsContainerView(tok->astParent()))
continue;
if ((tokvalue->variable() && !isEscapedReference(tokvalue->variable()) &&
isInScope(tokvalue->variable()->nameToken(), scope)) ||
isDeadTemporary(tokvalue, nullptr, &mSettings->library)) {
errorReturnDanglingLifetime(tok, &val);
break;
}
} else if (tokvalue->variable() && isDeadScope(tokvalue->variable()->nameToken(), tok->scope())) {
errorInvalidLifetime(tok, &val);
break;
} else if (!tokvalue->variable() &&
isDeadTemporary(tokvalue, tok, &mSettings->library)) {
if (!diag(tokvalue))
errorDanglingTemporaryLifetime(tok, &val, tokvalue);
break;
}
}
if (tokvalue->variable() && (isInScope(tokvalue->variable()->nameToken(), tok->scope()) ||
(val.isSubFunctionLifetimeValue() && isDanglingSubFunction(tokvalue, tok)))) {
const Variable * var = nullptr;
const Token * tok2 = tok;
if (Token::simpleMatch(tok->astParent(), "=")) {
if (astIsRHS(tok)) {
var = getParentVar(tok->astParent()->astOperand1());
tok2 = tok->astParent()->astOperand1();
}
} else if (tok->variable() && tok->variable()->declarationId() == tok->varId()) {
var = tok->variable();
}
if (!ValueFlow::isLifetimeBorrowed(tok, *mSettings))
continue;
const Token* nextTok = nextAfterAstRightmostLeaf(tok->astTop());
if (!nextTok)
nextTok = tok->next();
if (var && !var->isLocal() && !var->isArgument() && !(val.tokvalue && val.tokvalue->variable() && val.tokvalue->variable()->isStatic()) &&
!isVariableChanged(nextTok,
tok->scope()->bodyEnd,
var->declarationId(),
var->isGlobal(),
*mSettings)) {
errorDanglngLifetime(tok2, &val);
break;
}
}
}
}
const Token *lambdaEndToken = findLambdaEndToken(tok);
if (lambdaEndToken) {
checkVarLifetimeScope(lambdaEndToken->link(), lambdaEndToken);
tok = lambdaEndToken;
}
if (tok->str() == "{" && tok->scope()) {
// Check functions in local classes
if (tok->scope()->type == Scope::eClass ||
tok->scope()->type == Scope::eStruct ||
tok->scope()->type == Scope::eUnion) {
for (const Function& f:tok->scope()->functionList) {
if (f.functionScope)
checkVarLifetimeScope(f.functionScope->bodyStart, f.functionScope->bodyEnd);
}
tok = tok->link();
}
}
}
}
void CheckAutoVariables::checkVarLifetime()
{
logChecker("CheckAutoVariables::checkVarLifetime");
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
if (!scope->function)
continue;
checkVarLifetimeScope(scope->bodyStart, scope->bodyEnd);
}
}
void CheckAutoVariables::errorReturnDanglingLifetime(const Token *tok, const ValueFlow::Value *val)
{
const bool inconclusive = val ? val->isInconclusive() : false;
ErrorPath errorPath = val ? val->errorPath : ErrorPath();
std::string msg = "Returning " + lifetimeMessage(tok, val, errorPath);
errorPath.emplace_back(tok, "");
reportError(errorPath, Severity::error, "returnDanglingLifetime", msg + " that will be invalid when returning.", CWE562, inconclusive ? Certainty::inconclusive : Certainty::normal);
}
void CheckAutoVariables::errorInvalidLifetime(const Token *tok, const ValueFlow::Value* val)
{
const bool inconclusive = val ? val->isInconclusive() : false;
ErrorPath errorPath = val ? val->errorPath : ErrorPath();
std::string msg = "Using " + lifetimeMessage(tok, val, errorPath);
errorPath.emplace_back(tok, "");
reportError(errorPath, Severity::error, "invalidLifetime", msg + " that is out of scope.", CWE562, inconclusive ? Certainty::inconclusive : Certainty::normal);
}
void CheckAutoVariables::errorDanglingTemporaryLifetime(const Token* tok, const ValueFlow::Value* val, const Token* tempTok)
{
const bool inconclusive = val ? val->isInconclusive() : false;
ErrorPath errorPath = val ? val->errorPath : ErrorPath();
std::string msg = "Using " + lifetimeMessage(tok, val, errorPath);
errorPath.emplace_back(tempTok, "Temporary created here.");
errorPath.emplace_back(tok, "");
reportError(errorPath,
Severity::error,
"danglingTemporaryLifetime",
msg + " that is a temporary.",
CWE562,
inconclusive ? Certainty::inconclusive : Certainty::normal);
}
void CheckAutoVariables::errorDanglngLifetime(const Token *tok, const ValueFlow::Value *val)
{
const bool inconclusive = val ? val->isInconclusive() : false;
ErrorPath errorPath = val ? val->errorPath : ErrorPath();
std::string tokName = tok ? tok->expressionString() : "x";
std::string msg = "Non-local variable '" + tokName + "' will use " + lifetimeMessage(tok, val, errorPath);
errorPath.emplace_back(tok, "");
reportError(errorPath, Severity::error, "danglingLifetime", msg + ".", CWE562, inconclusive ? Certainty::inconclusive : Certainty::normal);
}
void CheckAutoVariables::errorDanglingTempReference(const Token* tok, ErrorPath errorPath, bool inconclusive)
{
errorPath.emplace_back(tok, "");
reportError(
errorPath, Severity::error, "danglingTempReference", "Using reference to dangling temporary.", CWE562, inconclusive ? Certainty::inconclusive : Certainty::normal);
}
void CheckAutoVariables::errorReturnReference(const Token* tok, ErrorPath errorPath, bool inconclusive)
{
errorPath.emplace_back(tok, "");
reportError(
errorPath, Severity::error, "returnReference", "Reference to local variable returned.", CWE562, inconclusive ? Certainty::inconclusive : Certainty::normal);
}
void CheckAutoVariables::errorDanglingReference(const Token *tok, const Variable *var, ErrorPath errorPath)
{
std::string tokName = tok ? tok->str() : "x";
std::string varName = var ? var->name() : "y";
std::string msg = "Non-local reference variable '" + tokName + "' to local variable '" + varName + "'";
errorPath.emplace_back(tok, "");
reportError(errorPath, Severity::error, "danglingReference", msg, CWE562, Certainty::normal);
}
void CheckAutoVariables::errorReturnTempReference(const Token* tok, ErrorPath errorPath, bool inconclusive)
{
errorPath.emplace_back(tok, "");
reportError(
errorPath, Severity::error, "returnTempReference", "Reference to temporary returned.", CWE562, inconclusive ? Certainty::inconclusive : Certainty::normal);
}
void CheckAutoVariables::errorInvalidDeallocation(const Token *tok, const ValueFlow::Value *val)
{
const Variable *var = val ? val->tokvalue->variable() : (tok ? tok->variable() : nullptr);
std::string type = "an auto-variable";
if (tok && tok->tokType() == Token::eString)
type = "a string literal";
else if (val && val->tokvalue->tokType() == Token::eString)
type = "a pointer pointing to a string literal";
else if (var) {
if (var->isGlobal())
type = "a global variable";
else if (var->isStatic())
type = "a static variable";
}
if (val)
type += " (" + val->tokvalue->str() + ")";
reportError(getErrorPath(tok, val, "Deallocating memory that was not dynamically allocated"),
Severity::error,
"autovarInvalidDeallocation",
"Deallocation of " + type + " results in undefined behaviour.\n"
"The deallocation of " + type + " results in undefined behaviour. You should only free memory "
"that has been allocated dynamically.", CWE590, Certainty::normal);
}
| null |
929 | cpp | cppcheck | preprocessor.h | lib/preprocessor.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef preprocessorH
#define preprocessorH
//---------------------------------------------------------------------------
#include "config.h"
#include <cstddef>
#include <cstdint>
#include <istream>
#include <list>
#include <map>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include <simplecpp.h>
class ErrorLogger;
class Settings;
class SuppressionList;
/**
* @brief A preprocessor directive
* Each preprocessor directive (\#include, \#define, \#undef, \#if, \#ifdef, \#else, \#endif)
* will be recorded as an instance of this class.
*
* file and linenr denote the location where the directive is defined.
*
*/
struct CPPCHECKLIB Directive {
/** name of (possibly included) file where directive is defined */
std::string file;
/** line number in (possibly included) file where directive is defined */
unsigned int linenr;
/** the actual directive text */
std::string str;
struct DirectiveToken {
explicit DirectiveToken(const simplecpp::Token & _tok);
int line;
int column;
std::string tokStr;
};
std::vector<DirectiveToken> strTokens;
/** record a directive (possibly filtering src) */
Directive(const simplecpp::Location & _loc, std::string _str);
Directive(std::string _file, int _linenr, std::string _str);
};
class CPPCHECKLIB RemarkComment {
public:
RemarkComment(std::string file, unsigned int lineNumber, std::string str)
: file(std::move(file))
, lineNumber(lineNumber)
, str(std::move(str))
{}
/** name of file */
std::string file;
/** line number for the code that the remark comment is about */
unsigned int lineNumber;
/** remark text */
std::string str;
};
/// @addtogroup Core
/// @{
/**
* @brief The cppcheck preprocessor.
* The preprocessor has special functionality for extracting the various ifdef
* configurations that exist in a source file.
*/
class CPPCHECKLIB WARN_UNUSED Preprocessor {
// TODO: get rid of this
friend class PreprocessorHelper;
friend class TestPreprocessor;
friend class TestUnusedVar;
public:
/** character that is inserted in expanded macros */
static char macroChar;
explicit Preprocessor(const Settings& settings, ErrorLogger &errorLogger);
virtual ~Preprocessor();
void inlineSuppressions(const simplecpp::TokenList &tokens, SuppressionList &suppressions);
std::list<Directive> createDirectives(const simplecpp::TokenList &tokens) const;
std::set<std::string> getConfigs(const simplecpp::TokenList &tokens) const;
std::vector<RemarkComment> getRemarkComments(const simplecpp::TokenList &tokens) const;
bool loadFiles(const simplecpp::TokenList &rawtokens, std::vector<std::string> &files);
void removeComments(simplecpp::TokenList &tokens);
static void setPlatformInfo(simplecpp::TokenList &tokens, const Settings& settings);
simplecpp::TokenList preprocess(const simplecpp::TokenList &tokens1, const std::string &cfg, std::vector<std::string> &files, bool throwError = false);
std::string getcode(const simplecpp::TokenList &tokens1, const std::string &cfg, std::vector<std::string> &files, bool writeLocations);
/**
* Calculate HASH. Using toolinfo, tokens1, filedata.
*
* @param tokens1 Sourcefile tokens
* @param toolinfo Arbitrary extra toolinfo
* @return HASH
*/
std::size_t calculateHash(const simplecpp::TokenList &tokens1, const std::string &toolinfo) const;
void simplifyPragmaAsm(simplecpp::TokenList &tokenList) const;
static void getErrorMessages(ErrorLogger &errorLogger, const Settings &settings);
/**
* dump all directives present in source file
*/
void dump(std::ostream &out) const;
static bool hasErrors(const simplecpp::Output &output);
private:
void handleErrors(const simplecpp::OutputList &outputList, bool throwError);
void reportOutput(const simplecpp::OutputList &outputList, bool showerror);
static void simplifyPragmaAsmPrivate(simplecpp::TokenList &tokenList);
/**
* Include file types.
*/
enum HeaderTypes : std::uint8_t {
UserHeader = 1,
SystemHeader
};
void missingInclude(const std::string &filename, unsigned int linenr, const std::string &header, HeaderTypes headerType);
void error(const std::string &filename, unsigned int linenr, const std::string &msg);
static bool hasErrors(const simplecpp::OutputList &outputList);
void addRemarkComments(const simplecpp::TokenList &tokens, std::vector<RemarkComment> &remarkComments) const;
const Settings& mSettings;
ErrorLogger &mErrorLogger;
/** list of all directives met while preprocessing file */
std::map<std::string, simplecpp::TokenList *> mTokenLists;
/** filename for cpp/c file - useful when reporting errors */
std::string mFile0;
/** simplecpp tracking info */
std::list<simplecpp::MacroUsage> mMacroUsage;
std::list<simplecpp::IfCond> mIfCond;
};
/// @}
//---------------------------------------------------------------------------
#endif // preprocessorH
| null |
930 | cpp | cppcheck | utils.cpp | lib/utils.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "utils.h"
#include <algorithm>
#include <cctype>
#include <cstring>
#include <iterator>
#include <stack>
#include <utility>
int caseInsensitiveStringCompare(const std::string &lhs, const std::string &rhs)
{
if (lhs.size() != rhs.size())
return (lhs.size() < rhs.size()) ? -1 : 1;
for (unsigned int i = 0; i < lhs.size(); ++i) {
const int c1 = std::toupper(lhs[i]);
const int c2 = std::toupper(rhs[i]);
if (c1 != c2)
return (c1 < c2) ? -1 : 1;
}
return 0;
}
bool isValidGlobPattern(const std::string& pattern)
{
for (std::string::const_iterator i = pattern.cbegin(); i != pattern.cend(); ++i) {
if (*i == '*' || *i == '?') {
const std::string::const_iterator j = i + 1;
if (j != pattern.cend() && (*j == '*' || *j == '?')) {
return false;
}
}
}
return true;
}
bool matchglob(const std::string& pattern, const std::string& name)
{
const char* p = pattern.c_str();
const char* n = name.c_str();
std::stack<std::pair<const char*, const char*>, std::vector<std::pair<const char*, const char*>>> backtrack;
for (;;) {
bool matching = true;
while (*p != '\0' && matching) {
switch (*p) {
case '*':
// Step forward until we match the next character after *
while (*n != '\0' && *n != p[1]) {
n++;
}
if (*n != '\0') {
// If this isn't the last possibility, save it for later
backtrack.emplace(p, n);
}
break;
case '?':
// Any character matches unless we're at the end of the name
if (*n != '\0') {
n++;
} else {
matching = false;
}
break;
default:
// Non-wildcard characters match literally
if (*n == *p) {
n++;
} else if (*n == '\\' && *p == '/') {
n++;
} else if (*n == '/' && *p == '\\') {
n++;
} else {
matching = false;
}
break;
}
p++;
}
// If we haven't failed matching and we've reached the end of the name, then success
if (matching && *n == '\0') {
return true;
}
// If there are no other paths to try, then fail
if (backtrack.empty()) {
return false;
}
// Restore pointers from backtrack stack
p = backtrack.top().first;
n = backtrack.top().second;
backtrack.pop();
// Advance name pointer by one because the current position didn't work
n++;
}
}
bool matchglobs(const std::vector<std::string> &patterns, const std::string &name) {
return std::any_of(begin(patterns), end(patterns), [&name](const std::string &pattern) {
return matchglob(pattern, name);
});
}
void strTolower(std::string& str)
{
// This wrapper exists because Sun's CC does not allow a static_cast
// from extern "C" int(*)(int) to int(*)(int).
std::transform(str.cbegin(), str.cend(), str.begin(), [](int c) {
return std::tolower(c);
});
}
std::string trim(const std::string& s, const std::string& t)
{
const std::string::size_type beg = s.find_first_not_of(t);
if (beg == std::string::npos)
return "";
const std::string::size_type end = s.find_last_not_of(t);
return s.substr(beg, end - beg + 1);
}
void findAndReplace(std::string &source, const std::string &searchFor, const std::string &replaceWith)
{
std::string::size_type index = 0;
while ((index = source.find(searchFor, index)) != std::string::npos) {
source.replace(index, searchFor.length(), replaceWith);
index += replaceWith.length();
}
}
std::string replaceEscapeSequences(const std::string &source) {
std::string result;
result.reserve(source.size());
for (std::size_t i = 0; i < source.size(); ++i) {
if (source[i] != '\\' || i + 1 >= source.size())
result += source[i];
else {
++i;
if (source[i] == 'n') {
result += '\n';
} else if (source[i] == 'r') {
result += '\r';
} else if (source[i] == 't') {
result += '\t';
} else if (source[i] == 'x') {
std::string value = "0";
if (i + 1 < source.size() && std::isxdigit(source[i+1]))
value += source[i++ + 1];
if (i + 1 < source.size() && std::isxdigit(source[i+1]))
value += source[i++ + 1];
result += static_cast<char>(std::stoi(value, nullptr, 16));
} else if (source[i] == '0') {
std::string value = "0";
if (i + 1 < source.size() && source[i+1] >= '0' && source[i+1] <= '7')
value += source[i++ + 1];
if (i + 1 < source.size() && source[i+1] >= '0' && source[i+1] <= '7')
value += source[i++ + 1];
result += static_cast<char>(std::stoi(value, nullptr, 8));
} else {
result += source[i];
}
}
}
return result;
}
std::list<std::string> splitString(const std::string& str, char sep)
{
if (std::strchr(str.c_str(), sep) == nullptr)
return {str};
std::list<std::string> l;
std::string p(str);
for (;;) {
const std::string::size_type pos = p.find(sep);
if (pos == std::string::npos)
break;
l.push_back(p.substr(0,pos));
p = p.substr(pos+1);
}
l.push_back(std::move(p));
return l;
}
| null |
931 | cpp | cppcheck | checkersreport.h | lib/checkersreport.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef checkersReportH
#define checkersReportH
#include "config.h"
#include <set>
#include <string>
class Settings;
class CPPCHECKLIB CheckersReport {
public:
CheckersReport(const Settings& settings, const std::set<std::string>& activeCheckers);
int getActiveCheckersCount();
int getAllCheckersCount();
std::string getReport(const std::string& criticalErrors) const;
std::string getXmlReport(const std::string& criticalErrors) const;
private:
const Settings& mSettings;
const std::set<std::string>& mActiveCheckers;
void countCheckers();
int mActiveCheckersCount = 0;
int mAllCheckersCount = 0;
};
#endif
| null |
932 | cpp | cppcheck | checkboost.cpp | lib/checkboost.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "checkboost.h"
#include "errortypes.h"
#include "symboldatabase.h"
#include "token.h"
#include <vector>
// Register this check class (by creating a static instance of it)
namespace {
CheckBoost instance;
}
static const CWE CWE664(664);
void CheckBoost::checkBoostForeachModification()
{
logChecker("CheckBoost::checkBoostForeachModification");
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token *tok = scope->bodyStart->next(); tok && tok != scope->bodyEnd; tok = tok->next()) {
if (!Token::simpleMatch(tok, "BOOST_FOREACH ("))
continue;
const Token *containerTok = tok->linkAt(1)->previous();
if (!Token::Match(containerTok, "%var% ) {"))
continue;
const Token *tok2 = containerTok->tokAt(2);
const Token *end = tok2->link();
for (; tok2 != end; tok2 = tok2->next()) {
if (Token::Match(tok2, "%varid% . insert|erase|push_back|push_front|pop_front|pop_back|clear|swap|resize|assign|merge|remove|remove_if|reverse|sort|splice|unique|pop|push", containerTok->varId())) {
const Token* nextStatement = Token::findsimplematch(tok2->linkAt(3), ";", end);
if (!Token::Match(nextStatement, "; break|return|throw"))
boostForeachError(tok2);
break;
}
}
}
}
}
void CheckBoost::boostForeachError(const Token *tok)
{
reportError(tok, Severity::error, "boostForeachError",
"BOOST_FOREACH caches the end() iterator. It's undefined behavior if you modify the container inside.", CWE664, Certainty::normal
);
}
| null |
933 | cpp | cppcheck | precompiled.h | lib/precompiled.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
// IWYU pragma: begin_keep
#include "astutils.h"
#include "errorlogger.h"
#include "library.h"
//#include "matchcompiler.h"
#include "mathlib.h"
#include "token.h"
#include "settings.h"
#include "suppressions.h"
#include "utils.h"
#include "valueflow.h"
// IWYU pragma: end_keep
| null |
934 | cpp | cppcheck | ctu.cpp | lib/ctu.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#include "ctu.h"
#include "astutils.h"
#include "errortypes.h"
#include "settings.h"
#include "symboldatabase.h"
#include "token.h"
#include "tokenize.h"
#include "tokenlist.h"
#include "utils.h"
#include <algorithm>
#include <cstdint>
#include <cstring>
#include <iterator> // back_inserter
#include <sstream>
#include <utility>
#include "xml.h"
//---------------------------------------------------------------------------
static constexpr char ATTR_CALL_ID[] = "call-id";
static constexpr char ATTR_CALL_FUNCNAME[] = "call-funcname";
static constexpr char ATTR_CALL_ARGNR[] = "call-argnr";
static constexpr char ATTR_CALL_ARGEXPR[] = "call-argexpr";
static constexpr char ATTR_CALL_ARGVALUETYPE[] = "call-argvaluetype";
static constexpr char ATTR_CALL_ARGVALUE[] = "call-argvalue";
static constexpr char ATTR_WARNING[] = "warning";
static constexpr char ATTR_LOC_FILENAME[] = "file";
static constexpr char ATTR_LOC_LINENR[] = "line";
static constexpr char ATTR_LOC_COLUMN[] = "col";
static constexpr char ATTR_INFO[] = "info";
static constexpr char ATTR_MY_ID[] = "my-id";
static constexpr char ATTR_MY_ARGNR[] = "my-argnr";
static constexpr char ATTR_MY_ARGNAME[] = "my-argname";
static constexpr char ATTR_VALUE[] = "value";
std::string CTU::getFunctionId(const Tokenizer &tokenizer, const Function *function)
{
return tokenizer.list.file(function->tokenDef) + ':' + std::to_string(function->tokenDef->linenr()) + ':' + std::to_string(function->tokenDef->column());
}
CTU::FileInfo::Location::Location(const Tokenizer &tokenizer, const Token *tok)
: fileName(tokenizer.list.file(tok))
, lineNumber(tok->linenr())
, column(tok->column())
{}
std::string CTU::FileInfo::toString() const
{
std::ostringstream out;
// Function calls..
for (const CTU::FileInfo::FunctionCall &functionCall : functionCalls) {
out << functionCall.toXmlString();
}
// Nested calls..
for (const CTU::FileInfo::NestedCall &nestedCall : nestedCalls) {
out << nestedCall.toXmlString() << "\n";
}
return out.str();
}
std::string CTU::FileInfo::CallBase::toBaseXmlString() const
{
std::ostringstream out;
out << " " << ATTR_CALL_ID << "=\"" << callId << "\""
<< " " << ATTR_CALL_FUNCNAME << "=\"" << ErrorLogger::toxml(callFunctionName) << "\""
<< " " << ATTR_CALL_ARGNR << "=\"" << callArgNr << "\""
<< " " << ATTR_LOC_FILENAME << "=\"" << ErrorLogger::toxml(location.fileName) << "\""
<< " " << ATTR_LOC_LINENR << "=\"" << location.lineNumber << "\""
<< " " << ATTR_LOC_COLUMN << "=\"" << location.column << "\"";
return out.str();
}
std::string CTU::FileInfo::FunctionCall::toXmlString() const
{
std::ostringstream out;
out << "<function-call"
<< toBaseXmlString()
<< " " << ATTR_CALL_ARGEXPR << "=\"" << ErrorLogger::toxml(callArgumentExpression) << "\""
<< " " << ATTR_CALL_ARGVALUETYPE << "=\"" << static_cast<int>(callValueType) << "\""
<< " " << ATTR_CALL_ARGVALUE << "=\"" << callArgValue << "\"";
if (warning)
out << " " << ATTR_WARNING << "=\"true\"";
if (callValuePath.empty())
out << "/>";
else {
out << ">\n";
for (const ErrorMessage::FileLocation &loc : callValuePath)
out << " <path"
<< " " << ATTR_LOC_FILENAME << "=\"" << ErrorLogger::toxml(loc.getfile()) << "\""
<< " " << ATTR_LOC_LINENR << "=\"" << loc.line << "\""
<< " " << ATTR_LOC_COLUMN << "=\"" << loc.column << "\""
<< " " << ATTR_INFO << "=\"" << ErrorLogger::toxml(loc.getinfo()) << "\"/>\n";
out << "</function-call>";
}
return out.str();
}
std::string CTU::FileInfo::NestedCall::toXmlString() const
{
std::ostringstream out;
out << "<function-call"
<< toBaseXmlString()
<< " " << ATTR_MY_ID << "=\"" << myId << "\""
<< " " << ATTR_MY_ARGNR << "=\"" << myArgNr << "\""
<< "/>";
return out.str();
}
std::string CTU::FileInfo::UnsafeUsage::toString() const
{
std::ostringstream out;
out << " <unsafe-usage"
<< " " << ATTR_MY_ID << "=\"" << myId << '\"'
<< " " << ATTR_MY_ARGNR << "=\"" << myArgNr << '\"'
<< " " << ATTR_MY_ARGNAME << "=\"" << myArgumentName << '\"'
<< " " << ATTR_LOC_FILENAME << "=\"" << ErrorLogger::toxml(location.fileName) << '\"'
<< " " << ATTR_LOC_LINENR << "=\"" << location.lineNumber << '\"'
<< " " << ATTR_LOC_COLUMN << "=\"" << location.column << '\"'
<< " " << ATTR_VALUE << "=\"" << value << "\""
<< "/>\n";
return out.str();
}
std::string CTU::toString(const std::list<CTU::FileInfo::UnsafeUsage> &unsafeUsage)
{
std::ostringstream ret;
for (const CTU::FileInfo::UnsafeUsage &u : unsafeUsage)
ret << u.toString();
return ret.str();
}
CTU::FileInfo::CallBase::CallBase(const Tokenizer &tokenizer, const Token *callToken)
: callId(getFunctionId(tokenizer, callToken->function()))
, callFunctionName(callToken->next()->astOperand1()->expressionString())
, location(CTU::FileInfo::Location(tokenizer, callToken))
{}
CTU::FileInfo::NestedCall::NestedCall(const Tokenizer &tokenizer, const Function *myFunction, const Token *callToken)
: CallBase(tokenizer, callToken)
, myId(getFunctionId(tokenizer, myFunction))
{}
static std::string readAttrString(const tinyxml2::XMLElement *e, const char *attr, bool *error)
{
const char *value = e->Attribute(attr);
if (!value && error)
*error = true;
return empty_if_null(value);
}
static long long readAttrInt(const tinyxml2::XMLElement *e, const char *attr, bool *error)
{
int64_t value = 0;
const bool err = (e->QueryInt64Attribute(attr, &value) != tinyxml2::XML_SUCCESS);
if (error)
*error = err;
return value;
}
bool CTU::FileInfo::CallBase::loadBaseFromXml(const tinyxml2::XMLElement *xmlElement)
{
bool error = false;
callId = readAttrString(xmlElement, ATTR_CALL_ID, &error);
callFunctionName = readAttrString(xmlElement, ATTR_CALL_FUNCNAME, &error);
callArgNr = readAttrInt(xmlElement, ATTR_CALL_ARGNR, &error);
location.fileName = readAttrString(xmlElement, ATTR_LOC_FILENAME, &error);
location.lineNumber = readAttrInt(xmlElement, ATTR_LOC_LINENR, &error);
location.column = readAttrInt(xmlElement, ATTR_LOC_COLUMN, &error);
return !error;
}
bool CTU::FileInfo::FunctionCall::loadFromXml(const tinyxml2::XMLElement *xmlElement)
{
if (!loadBaseFromXml(xmlElement))
return false;
bool error=false;
callArgumentExpression = readAttrString(xmlElement, ATTR_CALL_ARGEXPR, &error);
callValueType = (ValueFlow::Value::ValueType)readAttrInt(xmlElement, ATTR_CALL_ARGVALUETYPE, &error);
callArgValue = readAttrInt(xmlElement, ATTR_CALL_ARGVALUE, &error);
const char *w = xmlElement->Attribute(ATTR_WARNING);
warning = w && std::strcmp(w, "true") == 0;
for (const tinyxml2::XMLElement *e2 = xmlElement->FirstChildElement(); !error && e2; e2 = e2->NextSiblingElement()) {
if (std::strcmp(e2->Name(), "path") != 0)
continue;
std::string file = readAttrString(e2, ATTR_LOC_FILENAME, &error);
std::string info = readAttrString(e2, ATTR_INFO, &error);
const int line = readAttrInt(e2, ATTR_LOC_LINENR, &error);
const int column = readAttrInt(e2, ATTR_LOC_COLUMN, &error);
ErrorMessage::FileLocation loc(file, std::move(info), line, column);
(void)loc; // TODO: loc is unused
}
return !error;
}
bool CTU::FileInfo::NestedCall::loadFromXml(const tinyxml2::XMLElement *xmlElement)
{
if (!loadBaseFromXml(xmlElement))
return false;
bool error = false;
myId = readAttrString(xmlElement, ATTR_MY_ID, &error);
myArgNr = readAttrInt(xmlElement, ATTR_MY_ARGNR, &error);
return !error;
}
void CTU::FileInfo::loadFromXml(const tinyxml2::XMLElement *xmlElement)
{
for (const tinyxml2::XMLElement *e = xmlElement->FirstChildElement(); e; e = e->NextSiblingElement()) {
const char* name = e->Name();
if (std::strcmp(name, "function-call") == 0) {
FunctionCall functionCall;
if (functionCall.loadFromXml(e))
functionCalls.push_back(std::move(functionCall));
} else if (std::strcmp(name, "nested-call") == 0) {
NestedCall nestedCall;
if (nestedCall.loadFromXml(e))
nestedCalls.push_back(std::move(nestedCall));
}
}
}
std::map<std::string, std::list<const CTU::FileInfo::CallBase *>> CTU::FileInfo::getCallsMap() const
{
std::map<std::string, std::list<const CTU::FileInfo::CallBase *>> ret;
for (const CTU::FileInfo::NestedCall &nc : nestedCalls)
ret[nc.callId].push_back(&nc);
for (const CTU::FileInfo::FunctionCall &fc : functionCalls)
ret[fc.callId].push_back(&fc);
return ret;
}
std::list<CTU::FileInfo::UnsafeUsage> CTU::loadUnsafeUsageListFromXml(const tinyxml2::XMLElement *xmlElement)
{
std::list<CTU::FileInfo::UnsafeUsage> ret;
for (const tinyxml2::XMLElement *e = xmlElement->FirstChildElement(); e; e = e->NextSiblingElement()) {
if (std::strcmp(e->Name(), "unsafe-usage") != 0)
continue;
bool error = false;
FileInfo::UnsafeUsage unsafeUsage;
unsafeUsage.myId = readAttrString(e, ATTR_MY_ID, &error);
unsafeUsage.myArgNr = readAttrInt(e, ATTR_MY_ARGNR, &error);
unsafeUsage.myArgumentName = readAttrString(e, ATTR_MY_ARGNAME, &error);
unsafeUsage.location.fileName = readAttrString(e, ATTR_LOC_FILENAME, &error);
unsafeUsage.location.lineNumber = readAttrInt(e, ATTR_LOC_LINENR, &error);
unsafeUsage.location.column = readAttrInt(e, ATTR_LOC_COLUMN, &error);
unsafeUsage.value = readAttrInt(e, ATTR_VALUE, &error);
if (!error)
ret.push_back(std::move(unsafeUsage));
}
return ret;
}
static int isCallFunction(const Scope *scope, int argnr, const Token *&tok)
{
const Variable * const argvar = scope->function->getArgumentVar(argnr);
if (!argvar->isPointer())
return -1;
for (const Token *tok2 = scope->bodyStart; tok2 != scope->bodyEnd; tok2 = tok2->next()) {
if (tok2->variable() != argvar)
continue;
if (!Token::Match(tok2->previous(), "[(,] %var% [,)]"))
break;
int argnr2 = 1;
const Token *prev = tok2;
while (prev && prev->str() != "(") {
if (Token::Match(prev,"]|)"))
prev = prev->link();
else if (prev->str() == ",")
++argnr2;
prev = prev->previous();
}
if (!prev || !Token::Match(prev->previous(), "%name% ("))
break;
if (!prev->astOperand1() || !prev->astOperand1()->function())
break;
tok = prev->previous();
return argnr2;
}
return -1;
}
CTU::FileInfo *CTU::getFileInfo(const Tokenizer &tokenizer)
{
const SymbolDatabase * const symbolDatabase = tokenizer.getSymbolDatabase();
auto *fileInfo = new FileInfo;
// Parse all functions in TU
for (const Scope &scope : symbolDatabase->scopeList) {
if (!scope.isExecutable() || scope.type != Scope::eFunction || !scope.function)
continue;
const Function *const scopeFunction = scope.function;
// source function calls
for (const Token *tok = scope.bodyStart; tok != scope.bodyEnd; tok = tok->next()) {
if (tok->str() != "(" || !tok->astOperand1() || !tok->astOperand2())
continue;
const Function* tokFunction = tok->astOperand1()->function();
if (!tokFunction)
continue;
const std::vector<const Token *> args(getArguments(tok->previous()));
for (int argnr = 0; argnr < args.size(); ++argnr) {
const Token *argtok = args[argnr];
if (!argtok)
continue;
for (const ValueFlow::Value &value : argtok->values()) {
if ((!value.isIntValue() || value.intvalue != 0 || value.isInconclusive()) && !value.isBufferSizeValue())
continue;
// Skip impossible values since they cannot be represented
if (value.isImpossible())
continue;
FileInfo::FunctionCall functionCall;
functionCall.callValueType = value.valueType;
functionCall.callId = getFunctionId(tokenizer, tokFunction);
functionCall.callFunctionName = tok->astOperand1()->expressionString();
functionCall.location = FileInfo::Location(tokenizer,tok);
functionCall.callArgNr = argnr + 1;
functionCall.callArgumentExpression = argtok->expressionString();
functionCall.callArgValue = value.intvalue;
functionCall.warning = !value.errorSeverity();
for (const ErrorPathItem &i : value.errorPath) {
const std::string& file = tokenizer.list.file(i.first);
const std::string& info = i.second;
const int line = i.first->linenr();
const int column = i.first->column();
ErrorMessage::FileLocation loc(file, info, line, column);
functionCall.callValuePath.push_back(std::move(loc));
}
fileInfo->functionCalls.push_back(std::move(functionCall));
}
// array
if (argtok->variable() && argtok->variable()->isArray() && argtok->variable()->dimensions().size() == 1 && argtok->variable()->dimensionKnown(0)) {
FileInfo::FunctionCall functionCall;
functionCall.callValueType = ValueFlow::Value::ValueType::BUFFER_SIZE;
functionCall.callId = getFunctionId(tokenizer, tokFunction);
functionCall.callFunctionName = tok->astOperand1()->expressionString();
functionCall.location = FileInfo::Location(tokenizer, tok);
functionCall.callArgNr = argnr + 1;
functionCall.callArgumentExpression = argtok->expressionString();
const auto typeSize = argtok->valueType()->typeSize(tokenizer.getSettings().platform);
functionCall.callArgValue = typeSize > 0 ? argtok->variable()->dimension(0) * typeSize : -1;
functionCall.warning = false;
fileInfo->functionCalls.push_back(std::move(functionCall));
}
// &var => buffer
if (argtok->isUnaryOp("&") && argtok->astOperand1()->variable() && argtok->astOperand1()->valueType() && !argtok->astOperand1()->variable()->isArray()) {
FileInfo::FunctionCall functionCall;
functionCall.callValueType = ValueFlow::Value::ValueType::BUFFER_SIZE;
functionCall.callId = getFunctionId(tokenizer, tokFunction);
functionCall.callFunctionName = tok->astOperand1()->expressionString();
functionCall.location = FileInfo::Location(tokenizer, tok);
functionCall.callArgNr = argnr + 1;
functionCall.callArgumentExpression = argtok->expressionString();
functionCall.callArgValue = argtok->astOperand1()->valueType()->typeSize(tokenizer.getSettings().platform);
functionCall.warning = false;
fileInfo->functionCalls.push_back(std::move(functionCall));
}
// pointer/reference to uninitialized data
auto isAddressOfArg = [](const Token* argtok) -> const Token* {
if (!argtok->isUnaryOp("&"))
return nullptr;
argtok = argtok->astOperand1();
if (!argtok || !argtok->valueType() || argtok->valueType()->pointer != 0)
return nullptr;
return argtok;
};
auto isReferenceArg = [&](const Token* argtok) -> const Token* {
const Variable* argvar = tokFunction->getArgumentVar(argnr);
if (!argvar || !argvar->valueType() || argvar->valueType()->reference == Reference::None)
return nullptr;
return argtok;
};
const Token* addr = isAddressOfArg(argtok);
argtok = addr ? addr : isReferenceArg(argtok);
if (!argtok || argtok->values().size() != 1U)
continue;
if (argtok->variable() && argtok->variable()->isClass())
continue;
const ValueFlow::Value &v = argtok->values().front();
if (v.valueType == ValueFlow::Value::ValueType::UNINIT && !v.isInconclusive()) {
FileInfo::FunctionCall functionCall;
functionCall.callValueType = ValueFlow::Value::ValueType::UNINIT;
functionCall.callId = getFunctionId(tokenizer, tokFunction);
functionCall.callFunctionName = tok->astOperand1()->expressionString();
functionCall.location = FileInfo::Location(tokenizer, tok);
functionCall.callArgNr = argnr + 1;
functionCall.callArgValue = 0;
functionCall.callArgumentExpression = argtok->expressionString();
functionCall.warning = false;
fileInfo->functionCalls.push_back(std::move(functionCall));
continue;
}
}
}
// Nested function calls
for (int argnr = 0; argnr < scopeFunction->argCount(); ++argnr) {
const Token *tok;
const int argnr2 = isCallFunction(&scope, argnr, tok);
if (argnr2 > 0) {
FileInfo::NestedCall nestedCall(tokenizer, scopeFunction, tok);
nestedCall.myArgNr = argnr + 1;
nestedCall.callArgNr = argnr2;
fileInfo->nestedCalls.push_back(std::move(nestedCall));
}
}
}
return fileInfo;
}
static std::list<std::pair<const Token *, MathLib::bigint>> getUnsafeFunction(const Settings &settings, const Scope *scope, int argnr, bool (*isUnsafeUsage)(const Settings &settings, const Token *argtok, MathLib::bigint *value))
{
std::list<std::pair<const Token *, MathLib::bigint>> ret;
const Variable * const argvar = scope->function->getArgumentVar(argnr);
if (!argvar->isArrayOrPointer() && !argvar->isReference())
return ret;
for (const Token *tok2 = scope->bodyStart; tok2 != scope->bodyEnd; tok2 = tok2->next()) {
if (Token::Match(tok2, ")|else {")) {
tok2 = tok2->linkAt(1);
if (Token::findmatch(tok2->link(), "return|throw", tok2))
return ret;
int indirect = 0;
if (argvar->valueType())
indirect = argvar->valueType()->pointer;
if (isVariableChanged(tok2->link(), tok2, indirect, argvar->declarationId(), false, settings))
return ret;
}
if (Token::Match(tok2, "%oror%|&&|?")) {
tok2 = tok2->findExpressionStartEndTokens().second;
continue;
}
if (tok2->variable() != argvar)
continue;
MathLib::bigint value = 0;
if (!isUnsafeUsage(settings, tok2, &value))
return ret; // TODO: Is this a read? then continue..
ret.emplace_back(tok2, value);
return ret;
}
return ret;
}
std::list<CTU::FileInfo::UnsafeUsage> CTU::getUnsafeUsage(const Tokenizer &tokenizer, const Settings &settings, bool (*isUnsafeUsage)(const Settings &settings, const Token *argtok, MathLib::bigint *value))
{
std::list<CTU::FileInfo::UnsafeUsage> unsafeUsage;
// Parse all functions in TU
const SymbolDatabase * const symbolDatabase = tokenizer.getSymbolDatabase();
for (const Scope &scope : symbolDatabase->scopeList) {
if (!scope.isExecutable() || scope.type != Scope::eFunction || !scope.function)
continue;
const Function *const function = scope.function;
// "Unsafe" functions unconditionally reads data before it is written..
for (int argnr = 0; argnr < function->argCount(); ++argnr) {
for (const std::pair<const Token *, MathLib::bigint> &v : getUnsafeFunction(settings, &scope, argnr, isUnsafeUsage)) {
const Token *tok = v.first;
const MathLib::bigint val = v.second;
unsafeUsage.emplace_back(CTU::getFunctionId(tokenizer, function), argnr+1, tok->str(), CTU::FileInfo::Location(tokenizer,tok), val);
}
}
}
return unsafeUsage;
}
static bool findPath(const std::string &callId,
nonneg int callArgNr,
MathLib::bigint unsafeValue,
CTU::FileInfo::InvalidValueType invalidValue,
const std::map<std::string, std::list<const CTU::FileInfo::CallBase *>> &callsMap,
const CTU::FileInfo::CallBase *path[10],
int index,
bool warning,
int maxCtuDepth)
{
if (index >= maxCtuDepth)
return false; // TODO: add bailout message?
const std::map<std::string, std::list<const CTU::FileInfo::CallBase *>>::const_iterator it = callsMap.find(callId);
if (it == callsMap.end())
return false;
for (const CTU::FileInfo::CallBase *c : it->second) {
if (c->callArgNr != callArgNr)
continue;
const auto *functionCall = dynamic_cast<const CTU::FileInfo::FunctionCall *>(c);
if (functionCall) {
if (!warning && functionCall->warning)
continue;
switch (invalidValue) {
case CTU::FileInfo::InvalidValueType::null:
if (functionCall->callValueType != ValueFlow::Value::ValueType::INT || functionCall->callArgValue != 0)
continue;
break;
case CTU::FileInfo::InvalidValueType::uninit:
if (functionCall->callValueType != ValueFlow::Value::ValueType::UNINIT)
continue;
break;
case CTU::FileInfo::InvalidValueType::bufferOverflow:
if (functionCall->callValueType != ValueFlow::Value::ValueType::BUFFER_SIZE)
continue;
if (unsafeValue < 0 || (unsafeValue >= functionCall->callArgValue && functionCall->callArgValue >= 0))
break;
continue;
}
path[index] = functionCall;
return true;
}
const auto *nestedCall = dynamic_cast<const CTU::FileInfo::NestedCall *>(c);
if (!nestedCall)
continue;
if (findPath(nestedCall->myId, nestedCall->myArgNr, unsafeValue, invalidValue, callsMap, path, index + 1, warning, maxCtuDepth)) {
path[index] = nestedCall;
return true;
}
}
return false;
}
std::list<ErrorMessage::FileLocation> CTU::FileInfo::getErrorPath(InvalidValueType invalidValue,
const CTU::FileInfo::UnsafeUsage &unsafeUsage,
const std::map<std::string, std::list<const CTU::FileInfo::CallBase *>> &callsMap,
const char info[],
const FunctionCall ** const functionCallPtr,
bool warning,
int maxCtuDepth)
{
std::list<ErrorMessage::FileLocation> locationList;
const CTU::FileInfo::CallBase *path[10] = {nullptr};
if (!findPath(unsafeUsage.myId, unsafeUsage.myArgNr, unsafeUsage.value, invalidValue, callsMap, path, 0, warning, maxCtuDepth))
return locationList;
const std::string value1 = (invalidValue == InvalidValueType::null) ? "null" : "uninitialized";
for (int index = 9; index >= 0; index--) {
if (!path[index])
continue;
const auto *functionCall = dynamic_cast<const CTU::FileInfo::FunctionCall *>(path[index]);
if (functionCall) {
if (functionCallPtr)
*functionCallPtr = functionCall;
std::copy(functionCall->callValuePath.cbegin(), functionCall->callValuePath.cend(), std::back_inserter(locationList));
}
std::string info_s = "Calling function " + path[index]->callFunctionName + ", " + std::to_string(path[index]->callArgNr) + getOrdinalText(path[index]->callArgNr) + " argument is " + value1;
ErrorMessage::FileLocation fileLoc(path[index]->location.fileName, std::move(info_s), path[index]->location.lineNumber, path[index]->location.column);
locationList.push_back(std::move(fileLoc));
}
std::string info_s = replaceStr(info, "ARG", unsafeUsage.myArgumentName);
ErrorMessage::FileLocation fileLoc2(unsafeUsage.location.fileName, std::move(info_s), unsafeUsage.location.lineNumber, unsafeUsage.location.column);
locationList.push_back(std::move(fileLoc2));
return locationList;
}
| null |
935 | cpp | cppcheck | path.h | lib/path.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef pathH
#define pathH
//---------------------------------------------------------------------------
#include "config.h"
#include "standards.h"
#include <set>
#include <string>
#include <vector>
/// @addtogroup Core
/// @{
/**
* @brief Path handling routines.
* Internally cppcheck wants to store paths with / separator which is also
* native separator for Unix-derived systems. When giving path to user
* or for other functions we convert path separators back to native type.
*/
class CPPCHECKLIB Path {
public:
/**
* Convert path to use native separators.
* @param path Path string to convert.
* @return converted path.
*/
static std::string toNativeSeparators(std::string path);
/**
* Convert path to use internal path separators.
* @param path Path string to convert.
* @return converted path.
*/
static std::string fromNativeSeparators(std::string path);
/**
* @brief Simplify path "foo/bar/.." => "foo"
* @param originalPath path to be simplified, must have / -separators.
* @return simplified path
*/
static std::string simplifyPath(std::string originalPath);
/**
* @brief Lookup the path part from a filename (e.g., '/tmp/a.h' -> '/tmp/', 'a.h' -> '')
* @param filename filename to lookup, must have / -separators.
* @return path part of the filename
*/
static std::string getPathFromFilename(const std::string &filename);
/**
* @brief Compare filenames to see if they are the same.
* On Linux the comparison is case-sensitive. On Windows it is case-insensitive.
* @param fname1 one filename
* @param fname2 other filename
* @return true if the filenames match on the current platform
*/
static bool sameFileName(const std::string &fname1, const std::string &fname2);
/**
* @brief Remove quotation marks (") from the path.
* @param path path to be cleaned.
* @return Cleaned path without quotation marks.
*/
static std::string removeQuotationMarks(std::string path);
/**
* @brief Get an extension of the filename.
* @param path Path containing filename.
* @param lowercase Return the extension in lower case
* @return Filename extension (containing the dot, e.g. ".h" or ".CPP").
*/
static std::string getFilenameExtension(const std::string &path, bool lowercase = false);
/**
* @brief Get an extension of the filename in lower case.
* @param path Path containing filename.
* @return Filename extension (containing the dot, e.g. ".h").
*/
static std::string getFilenameExtensionInLowerCase(const std::string &path);
/**
* @brief Returns the absolute path of current working directory
* @return absolute path of current working directory
*/
static std::string getCurrentPath();
/**
* @brief Returns the absolute path to the current executable
* @return absolute path to the current executable
*/
static std::string getCurrentExecutablePath(const char* fallback);
/**
* @brief Check if given path is absolute
* @param path Path to check
* @return true if given path is absolute
*/
static bool isAbsolute(const std::string& path);
/**
* @brief Create a relative path from an absolute one, if absolute path is inside the basePaths.
* @param absolutePath Path to be made relative.
* @param basePaths Paths to which it may be made relative.
* @return relative path, if possible. Otherwise absolutePath is returned unchanged
*/
static std::string getRelativePath(const std::string& absolutePath, const std::vector<std::string>& basePaths);
/**
* @brief Get an absolute file path from a relative one.
* @param filePath File path to be made absolute.
* @return absolute path, if possible. Otherwise an empty path is returned
*/
static std::string getAbsoluteFilePath(const std::string& filePath);
/**
* @brief Check if the file extension indicates that it's a C/C++ source file.
* Check if the file has source file extension: *.c;*.cpp;*.cxx;*.c++;*.cc;*.txx
* @param filename filename to check. path info is optional
* @return true if the file extension indicates it should be checked
*/
static bool acceptFile(const std::string &filename) {
const std::set<std::string> extra;
return acceptFile(filename, extra);
}
/**
* @brief Check if the file extension indicates that it's a C/C++ source file.
* Check if the file has source file extension: *.c;*.cpp;*.cxx;*.c++;*.cc;*.txx
* @param path filename to check. path info is optional
* @param extra extra file extensions
* @return true if the file extension indicates it should be checked
*/
static bool acceptFile(const std::string &path, const std::set<std::string> &extra);
/**
* @brief Is filename a header based on file extension
* @param path filename to check. path info is optional
* @return true if filename extension is meant for headers
*/
static bool isHeader(const std::string &path);
/**
* @brief Identify the language based on the file extension
* @param path filename to check. path info is optional
* @param cppHeaderProbe check optional Emacs marker to identify extension-less and *.h files as C++
* @param header if provided indicates if the file is a header
* @return the language type
*/
static Standards::Language identify(const std::string &path, bool cppHeaderProbe, bool *header = nullptr);
/**
* @brief Get filename without a directory path part.
* @param file filename to be stripped. path info is optional
* @return filename without directory path part.
*/
static std::string stripDirectoryPart(const std::string &file);
/**
* @brief Checks if given path is a file
* @param path Path to be checked
* @return true if given path is a file
*/
static bool isFile(const std::string &path);
/**
* @brief Checks if a given path is a directory
* @param path Path to be checked
* @return true if given path is a directory
*/
static bool isDirectory(const std::string &path);
/**
* @brief Checks if a given path exists (i.e. is a file or directory)
* @param path Path to be checked
* @return true if given path exists
*/
static bool exists(const std::string &path);
/**
* join 2 paths with '/' separators
*/
static std::string join(const std::string& path1, const std::string& path2);
};
/// @}
//---------------------------------------------------------------------------
#endif // pathH
| null |
936 | cpp | cppcheck | importproject.cpp | lib/importproject.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "importproject.h"
#include "path.h"
#include "settings.h"
#include "standards.h"
#include "suppressions.h"
#include "token.h"
#include "tokenlist.h"
#include "utils.h"
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <iterator>
#include <sstream>
#include <stack>
#include <unordered_set>
#include <utility>
#include "xml.h"
#include "json.h"
// TODO: align the exclusion logic with PathMatch
void ImportProject::ignorePaths(const std::vector<std::string> &ipaths)
{
for (std::list<FileSettings>::const_iterator it = fileSettings.cbegin(); it != fileSettings.cend();) {
bool ignore = false;
for (std::string i : ipaths) {
if (it->filename().size() > i.size() && it->filename().compare(0,i.size(),i)==0) {
ignore = true;
break;
}
if (isValidGlobPattern(i) && matchglob(i, it->filename())) {
ignore = true;
break;
}
if (!Path::isAbsolute(i)) {
i = mPath + i;
if (it->filename().size() > i.size() && it->filename().compare(0,i.size(),i)==0) {
ignore = true;
break;
}
}
}
if (ignore)
it = fileSettings.erase(it);
else
++it;
}
}
void ImportProject::ignoreOtherConfigs(const std::string &cfg)
{
for (std::list<FileSettings>::const_iterator it = fileSettings.cbegin(); it != fileSettings.cend();) {
if (it->cfg != cfg)
it = fileSettings.erase(it);
else
++it;
}
}
void ImportProject::fsSetDefines(FileSettings& fs, std::string defs)
{
while (defs.find(";%(") != std::string::npos) {
const std::string::size_type pos1 = defs.find(";%(");
const std::string::size_type pos2 = defs.find(';', pos1+1);
defs.erase(pos1, pos2 == std::string::npos ? pos2 : (pos2-pos1));
}
while (defs.find(";;") != std::string::npos)
defs.erase(defs.find(";;"),1);
while (!defs.empty() && defs[0] == ';')
defs.erase(0, 1);
while (!defs.empty() && endsWith(defs,';'))
defs.erase(defs.size() - 1U); // TODO: Use std::string::pop_back() as soon as travis supports it
bool eq = false;
for (std::size_t pos = 0; pos < defs.size(); ++pos) {
if (defs[pos] == '(' || defs[pos] == '=')
eq = true;
else if (defs[pos] == ';') {
if (!eq) {
defs.insert(pos,"=1");
pos += 3;
}
if (pos < defs.size())
eq = false;
}
}
if (!eq && !defs.empty())
defs += "=1";
fs.defines.swap(defs);
}
static bool simplifyPathWithVariables(std::string &s, std::map<std::string, std::string, cppcheck::stricmp> &variables)
{
std::set<std::string, cppcheck::stricmp> expanded;
std::string::size_type start = 0;
while ((start = s.find("$(")) != std::string::npos) {
const std::string::size_type end = s.find(')',start);
if (end == std::string::npos)
break;
const std::string var = s.substr(start+2,end-start-2);
if (expanded.find(var) != expanded.end())
break;
expanded.insert(var);
std::map<std::string, std::string, cppcheck::stricmp>::const_iterator it1 = variables.find(var);
// variable was not found within defined variables
if (it1 == variables.end()) {
const char *envValue = std::getenv(var.c_str());
if (!envValue) {
//! \todo generate a debug/info message about undefined variable
break;
}
variables[var] = std::string(envValue);
it1 = variables.find(var);
}
s.replace(start, end - start + 1, it1->second);
}
if (s.find("$(") != std::string::npos)
return false;
s = Path::simplifyPath(std::move(s));
return true;
}
void ImportProject::fsSetIncludePaths(FileSettings& fs, const std::string &basepath, const std::list<std::string> &in, std::map<std::string, std::string, cppcheck::stricmp> &variables)
{
std::set<std::string> found;
// NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
const std::list<std::string> copyIn(in);
fs.includePaths.clear();
for (const std::string &ipath : copyIn) {
if (ipath.empty())
continue;
if (startsWith(ipath,"%("))
continue;
std::string s(Path::fromNativeSeparators(ipath));
if (!found.insert(s).second)
continue;
if (s[0] == '/' || (s.size() > 1U && s.compare(1,2,":/") == 0)) {
if (!endsWith(s,'/'))
s += '/';
fs.includePaths.push_back(std::move(s));
continue;
}
if (endsWith(s,'/')) // this is a temporary hack, simplifyPath can crash if path ends with '/'
s.pop_back();
if (s.find("$(") == std::string::npos) {
s = Path::simplifyPath(basepath + s);
} else {
if (!simplifyPathWithVariables(s, variables))
continue;
}
if (s.empty())
continue;
fs.includePaths.push_back(s.back() == '/' ? s : (s + '/'));
}
}
ImportProject::Type ImportProject::import(const std::string &filename, Settings *settings)
{
std::ifstream fin(filename);
if (!fin.is_open())
return ImportProject::Type::MISSING;
mPath = Path::getPathFromFilename(Path::fromNativeSeparators(filename));
if (!mPath.empty() && !endsWith(mPath,'/'))
mPath += '/';
const std::vector<std::string> fileFilters =
settings ? settings->fileFilters : std::vector<std::string>();
if (endsWith(filename, ".json")) {
if (importCompileCommands(fin)) {
setRelativePaths(filename);
return ImportProject::Type::COMPILE_DB;
}
} else if (endsWith(filename, ".sln")) {
if (importSln(fin, mPath, fileFilters)) {
setRelativePaths(filename);
return ImportProject::Type::VS_SLN;
}
} else if (endsWith(filename, ".vcxproj")) {
std::map<std::string, std::string, cppcheck::stricmp> variables;
std::vector<SharedItemsProject> sharedItemsProjects;
if (importVcxproj(filename, variables, emptyString, fileFilters, sharedItemsProjects)) {
setRelativePaths(filename);
return ImportProject::Type::VS_VCXPROJ;
}
} else if (endsWith(filename, ".bpr")) {
if (importBcb6Prj(filename)) {
setRelativePaths(filename);
return ImportProject::Type::BORLAND;
}
} else if (settings && endsWith(filename, ".cppcheck")) {
if (importCppcheckGuiProject(fin, settings)) {
setRelativePaths(filename);
return ImportProject::Type::CPPCHECK_GUI;
}
} else {
return ImportProject::Type::UNKNOWN;
}
return ImportProject::Type::FAILURE;
}
static std::string readUntil(const std::string &command, std::string::size_type *pos, const char until[])
{
std::string ret;
bool escapedString = false;
bool str = false;
bool escape = false;
for (; *pos < command.size() && (str || !std::strchr(until, command[*pos])); (*pos)++) {
if (escape)
escape = false;
else if (command[*pos] == '\\') {
if (str)
escape = true;
else if (command[*pos + 1] == '"') {
if (escapedString)
return ret + "\\\"";
escapedString = true;
ret += "\\\"";
(*pos)++;
continue;
}
} else if (command[*pos] == '\"')
str = !str;
ret += command[*pos];
}
return ret;
}
static std::string unescape(const std::string &in)
{
std::string out;
bool escape = false;
for (const char c: in) {
if (escape) {
escape = false;
if (!std::strchr("\\\"\'",c))
out += "\\";
out += c;
} else if (c == '\\')
escape = true;
else
out += c;
}
return out;
}
void ImportProject::fsParseCommand(FileSettings& fs, const std::string& command)
{
std::string defs;
// Parse command..
std::string::size_type pos = 0;
while (std::string::npos != (pos = command.find(' ',pos))) {
while (pos < command.size() && command[pos] == ' ')
pos++;
if (pos >= command.size())
break;
if (command[pos] != '/' && command[pos] != '-')
continue;
pos++;
if (pos >= command.size())
break;
const char F = command[pos++];
if (std::strchr("DUI", F)) {
while (pos < command.size() && command[pos] == ' ')
++pos;
}
const std::string fval = readUntil(command, &pos, " =");
if (F=='D') {
std::string defval = readUntil(command, &pos, " ");
defs += fval;
if (defval.size() >= 3 && startsWith(defval,"=\"") && defval.back()=='\"')
defval = "=" + unescape(defval.substr(2, defval.size() - 3));
else if (defval.size() >= 5 && startsWith(defval, "=\\\"") && endsWith(defval, "\\\""))
defval = "=\"" + unescape(defval.substr(3, defval.size() - 5)) + "\"";
if (!defval.empty())
defs += defval;
defs += ';';
} else if (F=='U')
fs.undefs.insert(fval);
else if (F=='I') {
std::string i = fval;
if (i.size() > 1 && i[0] == '\"' && i.back() == '\"')
i = unescape(i.substr(1, i.size() - 2));
if (std::find(fs.includePaths.cbegin(), fs.includePaths.cend(), i) == fs.includePaths.cend())
fs.includePaths.push_back(std::move(i));
} else if (F=='s' && startsWith(fval,"td")) {
++pos;
fs.standard = readUntil(command, &pos, " ");
} else if (F == 'i' && fval == "system") {
++pos;
std::string isystem = readUntil(command, &pos, " ");
fs.systemIncludePaths.push_back(std::move(isystem));
} else if (F=='m') {
if (fval == "unicode") {
defs += "UNICODE";
defs += ";";
}
} else if (F=='f') {
if (fval == "pic") {
defs += "__pic__";
defs += ";";
} else if (fval == "PIC") {
defs += "__PIC__";
defs += ";";
} else if (fval == "pie") {
defs += "__pie__";
defs += ";";
} else if (fval == "PIE") {
defs += "__PIE__";
defs += ";";
}
// TODO: support -fsigned-char and -funsigned-char?
// we can only set it globally but in this context it needs to be treated per file
}
}
fsSetDefines(fs, std::move(defs));
}
bool ImportProject::importCompileCommands(std::istream &istr)
{
picojson::value compileCommands;
istr >> compileCommands;
if (!compileCommands.is<picojson::array>()) {
printError("compilation database is not a JSON array");
return false;
}
for (const picojson::value &fileInfo : compileCommands.get<picojson::array>()) {
picojson::object obj = fileInfo.get<picojson::object>();
std::string dirpath = Path::fromNativeSeparators(obj["directory"].get<std::string>());
/* CMAKE produces the directory without trailing / so add it if not
* there - it is needed by setIncludePaths() */
if (!endsWith(dirpath, '/'))
dirpath += '/';
const std::string directory = std::move(dirpath);
std::string command;
if (obj.count("arguments")) {
if (obj["arguments"].is<picojson::array>()) {
for (const picojson::value& arg : obj["arguments"].get<picojson::array>()) {
if (arg.is<std::string>()) {
std::string str = arg.get<std::string>();
if (str.find(' ') != std::string::npos)
str = "\"" + str + "\"";
command += str + " ";
}
}
} else {
printError("'arguments' field in compilation database entry is not a JSON array");
return false;
}
} else if (obj.count("command")) {
if (obj["command"].is<std::string>()) {
command = obj["command"].get<std::string>();
} else {
printError("'command' field in compilation database entry is not a string");
return false;
}
} else {
printError("no 'arguments' or 'command' field found in compilation database entry");
return false;
}
if (!obj.count("file") || !obj["file"].is<std::string>()) {
printError("skip compilation database entry because it does not have a proper 'file' field");
continue;
}
const std::string file = Path::fromNativeSeparators(obj["file"].get<std::string>());
// Accept file?
if (!Path::acceptFile(file))
continue;
std::string path;
if (Path::isAbsolute(file))
path = Path::simplifyPath(file);
#ifdef _WIN32
else if (file[0] == '/' && directory.size() > 2 && std::isalpha(directory[0]) && directory[1] == ':')
// directory: C:\foo\bar
// file: /xy/z.c
// => c:/xy/z.c
path = Path::simplifyPath(directory.substr(0,2) + file);
#endif
else
path = Path::simplifyPath(directory + file);
if (!sourceFileExists(path)) {
printError("'" + path + "' from compilation database does not exist");
return false;
}
FileSettings fs{std::move(path)};
fsParseCommand(fs, command); // read settings; -D, -I, -U, -std, -m*, -f*
std::map<std::string, std::string, cppcheck::stricmp> variables;
fsSetIncludePaths(fs, directory, fs.includePaths, variables);
fileSettings.push_back(std::move(fs));
}
return true;
}
bool ImportProject::importSln(std::istream &istr, const std::string &path, const std::vector<std::string> &fileFilters)
{
std::string line;
if (!std::getline(istr,line)) {
printError("Visual Studio solution file is empty");
return false;
}
if (!startsWith(line, "Microsoft Visual Studio Solution File")) {
// Skip BOM
if (!std::getline(istr, line) || !startsWith(line, "Microsoft Visual Studio Solution File")) {
printError("Visual Studio solution file header not found");
return false;
}
}
std::map<std::string,std::string,cppcheck::stricmp> variables;
variables["SolutionDir"] = path;
bool found = false;
std::vector<SharedItemsProject> sharedItemsProjects;
while (std::getline(istr,line)) {
if (!startsWith(line,"Project("))
continue;
const std::string::size_type pos = line.find(".vcxproj");
if (pos == std::string::npos)
continue;
const std::string::size_type pos1 = line.rfind('\"',pos);
if (pos1 == std::string::npos)
continue;
std::string vcxproj(line.substr(pos1+1, pos-pos1+7));
vcxproj = Path::toNativeSeparators(std::move(vcxproj));
if (!Path::isAbsolute(vcxproj))
vcxproj = path + vcxproj;
vcxproj = Path::fromNativeSeparators(std::move(vcxproj));
if (!importVcxproj(vcxproj, variables, emptyString, fileFilters, sharedItemsProjects)) {
printError("failed to load '" + vcxproj + "' from Visual Studio solution");
return false;
}
found = true;
}
if (!found) {
printError("no projects found in Visual Studio solution file");
return false;
}
return true;
}
namespace {
struct ProjectConfiguration {
explicit ProjectConfiguration(const tinyxml2::XMLElement *cfg) {
const char *a = cfg->Attribute("Include");
if (a)
name = a;
for (const tinyxml2::XMLElement *e = cfg->FirstChildElement(); e; e = e->NextSiblingElement()) {
const char * const text = e->GetText();
if (!text)
continue;
const char * ename = e->Name();
if (std::strcmp(ename,"Configuration")==0)
configuration = text;
else if (std::strcmp(ename,"Platform")==0) {
platformStr = text;
if (platformStr == "Win32")
platform = Win32;
else if (platformStr == "x64")
platform = x64;
else
platform = Unknown;
}
}
}
std::string name;
std::string configuration;
enum : std::uint8_t { Win32, x64, Unknown } platform = Unknown;
std::string platformStr;
};
struct ItemDefinitionGroup {
explicit ItemDefinitionGroup(const tinyxml2::XMLElement *idg, std::string includePaths) : additionalIncludePaths(std::move(includePaths)) {
const char *condAttr = idg->Attribute("Condition");
if (condAttr)
condition = condAttr;
for (const tinyxml2::XMLElement *e1 = idg->FirstChildElement(); e1; e1 = e1->NextSiblingElement()) {
const char* name = e1->Name();
if (std::strcmp(name, "ClCompile") == 0) {
enhancedInstructionSet = "StreamingSIMDExtensions2";
for (const tinyxml2::XMLElement *e = e1->FirstChildElement(); e; e = e->NextSiblingElement()) {
const char * const text = e->GetText();
if (!text)
continue;
const char * const ename = e->Name();
if (std::strcmp(ename, "PreprocessorDefinitions") == 0)
preprocessorDefinitions = text;
else if (std::strcmp(ename, "AdditionalIncludeDirectories") == 0) {
if (!additionalIncludePaths.empty())
additionalIncludePaths += ';';
additionalIncludePaths += text;
} else if (std::strcmp(ename, "LanguageStandard") == 0) {
if (std::strcmp(text, "stdcpp14") == 0)
cppstd = Standards::CPP14;
else if (std::strcmp(text, "stdcpp17") == 0)
cppstd = Standards::CPP17;
else if (std::strcmp(text, "stdcpp20") == 0)
cppstd = Standards::CPP20;
else if (std::strcmp(text, "stdcpplatest") == 0)
cppstd = Standards::CPPLatest;
} else if (std::strcmp(ename, "EnableEnhancedInstructionSet") == 0) {
enhancedInstructionSet = text;
}
}
}
else if (std::strcmp(name, "Link") == 0) {
for (const tinyxml2::XMLElement *e = e1->FirstChildElement(); e; e = e->NextSiblingElement()) {
const char * const text = e->GetText();
if (!text)
continue;
if (std::strcmp(e->Name(), "EntryPointSymbol") == 0) {
entryPointSymbol = text;
}
}
}
}
}
static void replaceAll(std::string &c, const std::string &from, const std::string &to) {
std::string::size_type pos;
while ((pos = c.find(from)) != std::string::npos) {
c.erase(pos,from.size());
c.insert(pos,to);
}
}
// see https://learn.microsoft.com/en-us/visualstudio/msbuild/msbuild-conditions
// properties are .NET String objects and you can call any of its members on them
bool conditionIsTrue(const ProjectConfiguration &p) const {
if (condition.empty())
return true;
std::string c = '(' + condition + ");";
replaceAll(c, "$(Configuration)", p.configuration);
replaceAll(c, "$(Platform)", p.platformStr);
// TODO: improve evaluation
const Settings s;
TokenList tokenlist(&s);
std::istringstream istr(c);
tokenlist.createTokens(istr, Standards::Language::C); // TODO: check result
// TODO: put in a helper
// generate links
{
std::stack<Token*> lpar;
for (Token* tok2 = tokenlist.front(); tok2; tok2 = tok2->next()) {
if (tok2->str() == "(")
lpar.push(tok2);
else if (tok2->str() == ")") {
if (lpar.empty())
break;
Token::createMutualLinks(lpar.top(), tok2);
lpar.pop();
}
}
}
tokenlist.createAst();
for (const Token *tok = tokenlist.front(); tok; tok = tok->next()) {
if (tok->str() == "(" && tok->astOperand1() && tok->astOperand2()) {
// TODO: this is wrong - it is Contains() not Equals()
if (tok->astOperand1()->expressionString() == "Configuration.Contains")
return ('\'' + p.configuration + '\'') == tok->astOperand2()->str();
}
if (tok->str() == "==" && tok->astOperand1() && tok->astOperand2() && tok->astOperand1()->str() == tok->astOperand2()->str())
return true;
}
return false;
}
std::string condition;
std::string enhancedInstructionSet;
std::string preprocessorDefinitions;
std::string additionalIncludePaths;
std::string entryPointSymbol; // TODO: use this
Standards::cppstd_t cppstd = Standards::CPPLatest;
};
}
static std::list<std::string> toStringList(const std::string &s)
{
std::list<std::string> ret;
std::string::size_type pos1 = 0;
std::string::size_type pos2;
while ((pos2 = s.find(';',pos1)) != std::string::npos) {
ret.push_back(s.substr(pos1, pos2-pos1));
pos1 = pos2 + 1;
if (pos1 >= s.size())
break;
}
if (pos1 < s.size())
ret.push_back(s.substr(pos1));
return ret;
}
static void importPropertyGroup(const tinyxml2::XMLElement *node, std::map<std::string,std::string,cppcheck::stricmp> &variables, std::string &includePath, bool *useOfMfc)
{
if (useOfMfc) {
for (const tinyxml2::XMLElement *e = node->FirstChildElement(); e; e = e->NextSiblingElement()) {
if (std::strcmp(e->Name(), "UseOfMfc") == 0) {
*useOfMfc = true;
break;
}
}
}
const char* labelAttribute = node->Attribute("Label");
if (labelAttribute && std::strcmp(labelAttribute, "UserMacros") == 0) {
for (const tinyxml2::XMLElement *propertyGroup = node->FirstChildElement(); propertyGroup; propertyGroup = propertyGroup->NextSiblingElement()) {
const char* name = propertyGroup->Name();
const char *text = empty_if_null(propertyGroup->GetText());
variables[name] = text;
}
} else if (!labelAttribute) {
for (const tinyxml2::XMLElement *propertyGroup = node->FirstChildElement(); propertyGroup; propertyGroup = propertyGroup->NextSiblingElement()) {
if (std::strcmp(propertyGroup->Name(), "IncludePath") != 0)
continue;
const char *text = propertyGroup->GetText();
if (!text)
continue;
std::string path(text);
const std::string::size_type pos = path.find("$(IncludePath)");
if (pos != std::string::npos)
path.replace(pos, 14U, includePath);
includePath = std::move(path);
}
}
}
static void loadVisualStudioProperties(const std::string &props, std::map<std::string,std::string,cppcheck::stricmp> &variables, std::string &includePath, const std::string &additionalIncludeDirectories, std::list<ItemDefinitionGroup> &itemDefinitionGroupList)
{
std::string filename(props);
// variables can't be resolved
if (!simplifyPathWithVariables(filename, variables))
return;
// prepend project dir (if it exists) to transform relative paths into absolute ones
if (!Path::isAbsolute(filename) && variables.count("ProjectDir") > 0)
filename = Path::getAbsoluteFilePath(variables.at("ProjectDir") + filename);
tinyxml2::XMLDocument doc;
if (doc.LoadFile(filename.c_str()) != tinyxml2::XML_SUCCESS)
return;
const tinyxml2::XMLElement * const rootnode = doc.FirstChildElement();
if (rootnode == nullptr)
return;
for (const tinyxml2::XMLElement *node = rootnode->FirstChildElement(); node; node = node->NextSiblingElement()) {
const char* name = node->Name();
if (std::strcmp(name, "ImportGroup") == 0) {
const char *labelAttribute = node->Attribute("Label");
if (labelAttribute == nullptr || std::strcmp(labelAttribute, "PropertySheets") != 0)
continue;
for (const tinyxml2::XMLElement *importGroup = node->FirstChildElement(); importGroup; importGroup = importGroup->NextSiblingElement()) {
if (std::strcmp(importGroup->Name(), "Import") == 0) {
const char *projectAttribute = importGroup->Attribute("Project");
if (projectAttribute == nullptr)
continue;
std::string loadprj(projectAttribute);
if (loadprj.find('$') == std::string::npos) {
loadprj = Path::getPathFromFilename(filename) + loadprj;
}
loadVisualStudioProperties(loadprj, variables, includePath, additionalIncludeDirectories, itemDefinitionGroupList);
}
}
} else if (std::strcmp(name,"PropertyGroup")==0) {
importPropertyGroup(node, variables, includePath, nullptr);
} else if (std::strcmp(name,"ItemDefinitionGroup")==0) {
itemDefinitionGroupList.emplace_back(node, additionalIncludeDirectories);
}
}
}
bool ImportProject::importVcxproj(const std::string &filename, std::map<std::string, std::string, cppcheck::stricmp> &variables, const std::string &additionalIncludeDirectories, const std::vector<std::string> &fileFilters, std::vector<SharedItemsProject> &cache)
{
variables["ProjectDir"] = Path::simplifyPath(Path::getPathFromFilename(filename));
std::list<ProjectConfiguration> projectConfigurationList;
std::list<std::string> compileList;
std::list<ItemDefinitionGroup> itemDefinitionGroupList;
std::string includePath;
std::vector<SharedItemsProject> sharedItemsProjects;
bool useOfMfc = false;
tinyxml2::XMLDocument doc;
const tinyxml2::XMLError error = doc.LoadFile(filename.c_str());
if (error != tinyxml2::XML_SUCCESS) {
printError(std::string("Visual Studio project file is not a valid XML - ") + tinyxml2::XMLDocument::ErrorIDToName(error));
return false;
}
const tinyxml2::XMLElement * const rootnode = doc.FirstChildElement();
if (rootnode == nullptr) {
printError("Visual Studio project file has no XML root node");
return false;
}
for (const tinyxml2::XMLElement *node = rootnode->FirstChildElement(); node; node = node->NextSiblingElement()) {
const char* name = node->Name();
if (std::strcmp(name, "ItemGroup") == 0) {
const char *labelAttribute = node->Attribute("Label");
if (labelAttribute && std::strcmp(labelAttribute, "ProjectConfigurations") == 0) {
for (const tinyxml2::XMLElement *cfg = node->FirstChildElement(); cfg; cfg = cfg->NextSiblingElement()) {
if (std::strcmp(cfg->Name(), "ProjectConfiguration") == 0) {
const ProjectConfiguration p(cfg);
if (p.platform != ProjectConfiguration::Unknown) {
projectConfigurationList.emplace_back(cfg);
mAllVSConfigs.insert(p.configuration);
}
}
}
} else {
for (const tinyxml2::XMLElement *e = node->FirstChildElement(); e; e = e->NextSiblingElement()) {
if (std::strcmp(e->Name(), "ClCompile") == 0) {
const char *include = e->Attribute("Include");
if (include && Path::acceptFile(include)) {
std::string toInclude = Path::simplifyPath(Path::isAbsolute(include) ? include : Path::getPathFromFilename(filename) + include);
compileList.emplace_back(toInclude);
}
}
}
}
} else if (std::strcmp(name, "ItemDefinitionGroup") == 0) {
itemDefinitionGroupList.emplace_back(node, additionalIncludeDirectories);
} else if (std::strcmp(name, "PropertyGroup") == 0) {
importPropertyGroup(node, variables, includePath, &useOfMfc);
} else if (std::strcmp(name, "ImportGroup") == 0) {
const char *labelAttribute = node->Attribute("Label");
if (labelAttribute && std::strcmp(labelAttribute, "PropertySheets") == 0) {
for (const tinyxml2::XMLElement *e = node->FirstChildElement(); e; e = e->NextSiblingElement()) {
if (std::strcmp(e->Name(), "Import") == 0) {
const char *projectAttribute = e->Attribute("Project");
if (projectAttribute)
loadVisualStudioProperties(projectAttribute, variables, includePath, additionalIncludeDirectories, itemDefinitionGroupList);
}
}
} else if (labelAttribute && std::strcmp(labelAttribute, "Shared") == 0) {
for (const tinyxml2::XMLElement *e = node->FirstChildElement(); e; e = e->NextSiblingElement()) {
if (std::strcmp(e->Name(), "Import") == 0) {
const char *projectAttribute = e->Attribute("Project");
if (projectAttribute) {
// Path to shared items project is relative to current project directory,
// unless the string starts with $(SolutionDir)
std::string pathToSharedItemsFile;
if (std::string(projectAttribute).rfind("$(SolutionDir)", 0) == 0) {
pathToSharedItemsFile = projectAttribute;
} else {
pathToSharedItemsFile = variables["ProjectDir"] + projectAttribute;
}
if (!simplifyPathWithVariables(pathToSharedItemsFile, variables)) {
printError("Could not simplify path to referenced shared items project");
return false;
}
SharedItemsProject toAdd = importVcxitems(pathToSharedItemsFile, fileFilters, cache);
if (!toAdd.successful) {
printError("Could not load shared items project \"" + pathToSharedItemsFile + "\" from original path \"" + std::string(projectAttribute) + "\".");
return false;
}
sharedItemsProjects.emplace_back(toAdd);
}
}
}
}
}
}
// # TODO: support signedness of char via /J (and potential XML option for it)?
// we can only set it globally but in this context it needs to be treated per file
// Include shared items project files
std::vector<std::string> sharedItemsIncludePaths;
for (const auto& sharedProject : sharedItemsProjects) {
for (const auto &file : sharedProject.sourceFiles) {
std::string pathToFile = Path::simplifyPath(Path::getPathFromFilename(sharedProject.pathToProjectFile) + file);
compileList.emplace_back(std::move(pathToFile));
}
for (const auto &p : sharedProject.includePaths) {
std::string path = Path::simplifyPath(Path::getPathFromFilename(sharedProject.pathToProjectFile) + p);
sharedItemsIncludePaths.emplace_back(std::move(path));
}
}
// Project files
for (const std::string &cfilename : compileList) {
if (!fileFilters.empty() && !matchglobs(fileFilters, cfilename))
continue;
for (const ProjectConfiguration &p : projectConfigurationList) {
if (!guiProject.checkVsConfigs.empty()) {
const bool doChecking = std::any_of(guiProject.checkVsConfigs.cbegin(), guiProject.checkVsConfigs.cend(), [&](const std::string& c) {
return c == p.configuration;
});
if (!doChecking)
continue;
}
FileSettings fs{cfilename};
fs.cfg = p.name;
// TODO: detect actual MSC version
fs.msc = true;
fs.useMfc = useOfMfc;
fs.defines = "_WIN32=1";
if (p.platform == ProjectConfiguration::Win32)
fs.platformType = Platform::Type::Win32W;
else if (p.platform == ProjectConfiguration::x64) {
fs.platformType = Platform::Type::Win64;
fs.defines += ";_WIN64=1";
}
std::string additionalIncludePaths;
for (const ItemDefinitionGroup &i : itemDefinitionGroupList) {
if (!i.conditionIsTrue(p))
continue;
fs.standard = Standards::getCPP(i.cppstd);
fs.defines += ';' + i.preprocessorDefinitions;
if (i.enhancedInstructionSet == "StreamingSIMDExtensions")
fs.defines += ";__SSE__";
else if (i.enhancedInstructionSet == "StreamingSIMDExtensions2")
fs.defines += ";__SSE2__";
else if (i.enhancedInstructionSet == "AdvancedVectorExtensions")
fs.defines += ";__AVX__";
else if (i.enhancedInstructionSet == "AdvancedVectorExtensions2")
fs.defines += ";__AVX2__";
else if (i.enhancedInstructionSet == "AdvancedVectorExtensions512")
fs.defines += ";__AVX512__";
additionalIncludePaths += ';' + i.additionalIncludePaths;
}
fsSetDefines(fs, fs.defines);
fsSetIncludePaths(fs, Path::getPathFromFilename(filename), toStringList(includePath + ';' + additionalIncludePaths), variables);
for (const auto &path : sharedItemsIncludePaths) {
fs.includePaths.emplace_back(path);
}
fileSettings.push_back(std::move(fs));
}
}
return true;
}
ImportProject::SharedItemsProject ImportProject::importVcxitems(const std::string& filename, const std::vector<std::string>& fileFilters, std::vector<SharedItemsProject> &cache)
{
auto isInCacheCheck = [filename](const ImportProject::SharedItemsProject& e) -> bool {
return filename == e.pathToProjectFile;
};
const auto iterator = std::find_if(cache.begin(), cache.end(), isInCacheCheck);
if (iterator != std::end(cache)) {
return *iterator;
}
SharedItemsProject result;
result.pathToProjectFile = filename;
tinyxml2::XMLDocument doc;
const tinyxml2::XMLError error = doc.LoadFile(filename.c_str());
if (error != tinyxml2::XML_SUCCESS) {
printError(std::string("Visual Studio project file is not a valid XML - ") + tinyxml2::XMLDocument::ErrorIDToName(error));
return result;
}
const tinyxml2::XMLElement * const rootnode = doc.FirstChildElement();
if (rootnode == nullptr) {
printError("Visual Studio project file has no XML root node");
return result;
}
for (const tinyxml2::XMLElement *node = rootnode->FirstChildElement(); node; node = node->NextSiblingElement()) {
if (std::strcmp(node->Name(), "ItemGroup") == 0) {
for (const tinyxml2::XMLElement *e = node->FirstChildElement(); e; e = e->NextSiblingElement()) {
if (std::strcmp(e->Name(), "ClCompile") == 0) {
const char* include = e->Attribute("Include");
if (include && Path::acceptFile(include)) {
std::string file(include);
findAndReplace(file, "$(MSBuildThisFileDirectory)", "./");
// Don't include file if it matches the filter
if (!fileFilters.empty() && !matchglobs(fileFilters, file))
continue;
result.sourceFiles.emplace_back(file);
} else {
printError("Could not find shared items source file");
return result;
}
}
}
} else if (std::strcmp(node->Name(), "ItemDefinitionGroup") == 0) {
ItemDefinitionGroup temp(node, "");
for (const auto& includePath : toStringList(temp.additionalIncludePaths)) {
if (includePath == "%(AdditionalIncludeDirectories)")
continue;
std::string toAdd(includePath);
findAndReplace(toAdd, "$(MSBuildThisFileDirectory)", "./");
result.includePaths.emplace_back(toAdd);
}
}
}
result.successful = true;
cache.emplace_back(result);
return result;
}
bool ImportProject::importBcb6Prj(const std::string &projectFilename)
{
tinyxml2::XMLDocument doc;
const tinyxml2::XMLError error = doc.LoadFile(projectFilename.c_str());
if (error != tinyxml2::XML_SUCCESS) {
printError(std::string("Borland project file is not a valid XML - ") + tinyxml2::XMLDocument::ErrorIDToName(error));
return false;
}
const tinyxml2::XMLElement * const rootnode = doc.FirstChildElement();
if (rootnode == nullptr) {
printError("Borland project file has no XML root node");
return false;
}
const std::string& projectDir = Path::simplifyPath(Path::getPathFromFilename(projectFilename));
std::list<std::string> compileList;
std::string includePath;
std::string userdefines;
std::string sysdefines;
std::string cflag1;
for (const tinyxml2::XMLElement *node = rootnode->FirstChildElement(); node; node = node->NextSiblingElement()) {
const char* name = node->Name();
if (std::strcmp(name, "FILELIST") == 0) {
for (const tinyxml2::XMLElement *f = node->FirstChildElement(); f; f = f->NextSiblingElement()) {
if (std::strcmp(f->Name(), "FILE") == 0) {
const char *filename = f->Attribute("FILENAME");
if (filename && Path::acceptFile(filename))
compileList.emplace_back(filename);
}
}
} else if (std::strcmp(name, "MACROS") == 0) {
for (const tinyxml2::XMLElement *m = node->FirstChildElement(); m; m = m->NextSiblingElement()) {
const char* mname = m->Name();
if (std::strcmp(mname, "INCLUDEPATH") == 0) {
const char *v = m->Attribute("value");
if (v)
includePath = v;
} else if (std::strcmp(mname, "USERDEFINES") == 0) {
const char *v = m->Attribute("value");
if (v)
userdefines = v;
} else if (std::strcmp(mname, "SYSDEFINES") == 0) {
const char *v = m->Attribute("value");
if (v)
sysdefines = v;
}
}
} else if (std::strcmp(name, "OPTIONS") == 0) {
for (const tinyxml2::XMLElement *m = node->FirstChildElement(); m; m = m->NextSiblingElement()) {
if (std::strcmp(m->Name(), "CFLAG1") == 0) {
const char *v = m->Attribute("value");
if (v)
cflag1 = v;
}
}
}
}
std::set<std::string> cflags;
// parse cflag1 and fill the cflags set
{
std::string arg;
for (const char i : cflag1) {
if (i == ' ' && !arg.empty()) {
cflags.insert(arg);
arg.clear();
continue;
}
arg += i;
}
if (!arg.empty()) {
cflags.insert(arg);
}
// cleanup: -t is "An alternate name for the -Wxxx switches; there is no difference"
// -> Remove every known -txxx argument and replace it with its -Wxxx counterpart.
// This way, we know what we have to check for later on.
static const std::map<std::string, std::string> synonyms = {
{ "-tC","-WC" },
{ "-tCDR","-WCDR" },
{ "-tCDV","-WCDV" },
{ "-tW","-W" },
{ "-tWC","-WC" },
{ "-tWCDR","-WCDR" },
{ "-tWCDV","-WCDV" },
{ "-tWD","-WD" },
{ "-tWDR","-WDR" },
{ "-tWDV","-WDV" },
{ "-tWM","-WM" },
{ "-tWP","-WP" },
{ "-tWR","-WR" },
{ "-tWU","-WU" },
{ "-tWV","-WV" }
};
for (std::map<std::string, std::string>::const_iterator i = synonyms.cbegin(); i != synonyms.cend(); ++i) {
if (cflags.erase(i->first) > 0) {
cflags.insert(i->second);
}
}
}
std::string predefines;
std::string cppPredefines;
// Collecting predefines. See BCB6 help topic "Predefined macros"
{
cppPredefines +=
// Defined if you've selected C++ compilation; will increase in later releases.
// value 0x0560 (but 0x0564 for our BCB6 SP4)
// @see http://docwiki.embarcadero.com/RADStudio/Tokyo/en/Predefined_Macros#C.2B.2B_Compiler_Versions_in_Predefined_Macros
";__BCPLUSPLUS__=0x0560"
// Defined if in C++ mode; otherwise, undefined.
";__cplusplus=1"
// Defined as 1 for C++ files(meaning that templates are supported); otherwise, it is undefined.
";__TEMPLATES__=1"
// Defined only for C++ programs to indicate that wchar_t is an intrinsically defined data type.
";_WCHAR_T"
// Defined only for C++ programs to indicate that wchar_t is an intrinsically defined data type.
";_WCHAR_T_DEFINED"
// Defined in any compiler that has an optimizer.
";__BCOPT__=1"
// Version number.
// BCB6 is 0x056X (SP4 is 0x0564)
// @see http://docwiki.embarcadero.com/RADStudio/Tokyo/en/Predefined_Macros#C.2B.2B_Compiler_Versions_in_Predefined_Macros
";__BORLANDC__=0x0560"
";__TCPLUSPLUS__=0x0560"
";__TURBOC__=0x0560";
// Defined if Calling Convention is set to cdecl; otherwise undefined.
const bool useCdecl = (cflags.find("-p") == cflags.end()
&& cflags.find("-pm") == cflags.end()
&& cflags.find("-pr") == cflags.end()
&& cflags.find("-ps") == cflags.end());
if (useCdecl)
predefines += ";__CDECL=1";
// Defined by default indicating that the default char is unsigned char. Use the -K compiler option to undefine this macro.
const bool treatCharAsUnsignedChar = (cflags.find("-K") != cflags.end());
if (treatCharAsUnsignedChar)
predefines += ";_CHAR_UNSIGNED=1";
// Defined whenever one of the CodeGuard compiler options is used; otherwise it is undefined.
const bool codeguardUsed = (cflags.find("-vGd") != cflags.end()
|| cflags.find("-vGt") != cflags.end()
|| cflags.find("-vGc") != cflags.end());
if (codeguardUsed)
predefines += ";__CODEGUARD__";
// When defined, the macro indicates that the program is a console application.
const bool isConsoleApp = (cflags.find("-WC") != cflags.end());
if (isConsoleApp)
predefines += ";__CONSOLE__=1";
// Enable stack unwinding. This is true by default; use -xd- to disable.
const bool enableStackUnwinding = (cflags.find("-xd-") == cflags.end());
if (enableStackUnwinding)
predefines += ";_CPPUNWIND=1";
// Defined whenever the -WD compiler option is used; otherwise it is undefined.
const bool isDLL = (cflags.find("-WD") != cflags.end());
if (isDLL)
predefines += ";__DLL__=1";
// Defined when compiling in 32-bit flat memory model.
// TODO: not sure how to switch to another memory model or how to read configuration from project file
predefines += ";__FLAT__=1";
// Always defined. The default value is 300. You can change the value to 400 or 500 by using the /4 or /5 compiler options.
if (cflags.find("-6") != cflags.end())
predefines += ";_M_IX86=600";
else if (cflags.find("-5") != cflags.end())
predefines += ";_M_IX86=500";
else if (cflags.find("-4") != cflags.end())
predefines += ";_M_IX86=400";
else
predefines += ";_M_IX86=300";
// Defined only if the -WM option is used. It specifies that the multithread library is to be linked.
const bool linkMtLib = (cflags.find("-WM") != cflags.end());
if (linkMtLib)
predefines += ";__MT__=1";
// Defined if Calling Convention is set to Pascal; otherwise undefined.
const bool usePascalCallingConvention = (cflags.find("-p") != cflags.end());
if (usePascalCallingConvention)
predefines += ";__PASCAL__=1";
// Defined if you compile with the -A compiler option; otherwise, it is undefined.
const bool useAnsiKeywordExtensions = (cflags.find("-A") != cflags.end());
if (useAnsiKeywordExtensions)
predefines += ";__STDC__=1";
// Thread Local Storage. Always true in C++Builder.
predefines += ";__TLC__=1";
// Defined for Windows-only code.
const bool isWindowsTarget = (cflags.find("-WC") != cflags.end()
|| cflags.find("-WCDR") != cflags.end()
|| cflags.find("-WCDV") != cflags.end()
|| cflags.find("-WD") != cflags.end()
|| cflags.find("-WDR") != cflags.end()
|| cflags.find("-WDV") != cflags.end()
|| cflags.find("-WM") != cflags.end()
|| cflags.find("-WP") != cflags.end()
|| cflags.find("-WR") != cflags.end()
|| cflags.find("-WU") != cflags.end()
|| cflags.find("-WV") != cflags.end());
if (isWindowsTarget)
predefines += ";_Windows";
// Defined for console and GUI applications.
// TODO: I'm not sure about the difference to define "_Windows".
// From description, I would assume __WIN32__ is only defined for
// executables, while _Windows would also be defined for DLLs, etc.
// However, in a newly created DLL project, both __WIN32__ and
// _Windows are defined. -> treating them the same for now.
// Also boost uses __WIN32__ for OS identification.
const bool isConsoleOrGuiApp = isWindowsTarget;
if (isConsoleOrGuiApp)
predefines += ";__WIN32__=1";
}
// Include paths may contain variables like "$(BCB)\include" or "$(BCB)\include\vcl".
// Those get resolved by ImportProject::FileSettings::setIncludePaths by
// 1. checking the provided variables map ("BCB" => "C:\\Program Files (x86)\\Borland\\CBuilder6")
// 2. checking env variables as a fallback
// Setting env is always possible. Configuring the variables via cli might be an addition.
// Reading the BCB6 install location from registry in windows environments would also be possible,
// but I didn't see any such functionality around the source. Not in favor of adding it only
// for the BCB6 project loading.
std::map<std::string, std::string, cppcheck::stricmp> variables;
const std::string defines = predefines + ";" + sysdefines + ";" + userdefines;
const std::string cppDefines = cppPredefines + ";" + defines;
const bool forceCppMode = (cflags.find("-P") != cflags.end());
for (const std::string &c : compileList) {
// C++ compilation is selected by file extension by default, so these
// defines have to be configured on a per-file base.
//
// > Files with the .CPP extension compile as C++ files. Files with a .C
// > extension, with no extension, or with extensions other than .CPP,
// > .OBJ, .LIB, or .ASM compile as C files.
// (http://docwiki.embarcadero.com/RADStudio/Tokyo/en/BCC32.EXE,_the_C%2B%2B_32-bit_Command-Line_Compiler)
//
// We can also force C++ compilation for all files using the -P command line switch.
const bool cppMode = forceCppMode || Path::getFilenameExtensionInLowerCase(c) == ".cpp";
FileSettings fs{Path::simplifyPath(Path::isAbsolute(c) ? c : projectDir + c)};
fsSetIncludePaths(fs, projectDir, toStringList(includePath), variables);
fsSetDefines(fs, cppMode ? cppDefines : defines);
fileSettings.push_back(std::move(fs));
}
return true;
}
static std::string joinRelativePath(const std::string &path1, const std::string &path2)
{
if (!path1.empty() && !Path::isAbsolute(path2))
return path1 + path2;
return path2;
}
static std::list<std::string> readXmlStringList(const tinyxml2::XMLElement *node, const std::string &path, const char name[], const char attribute[])
{
std::list<std::string> ret;
for (const tinyxml2::XMLElement *child = node->FirstChildElement(); child; child = child->NextSiblingElement()) {
if (strcmp(child->Name(), name) != 0)
continue;
const char *attr = attribute ? child->Attribute(attribute) : child->GetText();
if (attr)
ret.push_back(joinRelativePath(path, attr));
}
return ret;
}
static std::string join(const std::list<std::string> &strlist, const char *sep)
{
std::string ret;
for (const std::string &s : strlist) {
ret += (ret.empty() ? "" : sep) + s;
}
return ret;
}
static std::string istream_to_string(std::istream &istr)
{
std::istreambuf_iterator<char> eos;
return std::string(std::istreambuf_iterator<char>(istr), eos);
}
bool ImportProject::importCppcheckGuiProject(std::istream &istr, Settings *settings)
{
tinyxml2::XMLDocument doc;
const std::string xmldata = istream_to_string(istr);
const tinyxml2::XMLError error = doc.Parse(xmldata.data(), xmldata.size());
if (error != tinyxml2::XML_SUCCESS) {
printError(std::string("Cppcheck GUI project file is not a valid XML - ") + tinyxml2::XMLDocument::ErrorIDToName(error));
return false;
}
const tinyxml2::XMLElement * const rootnode = doc.FirstChildElement();
if (rootnode == nullptr || strcmp(rootnode->Name(), CppcheckXml::ProjectElementName) != 0) {
printError("Cppcheck GUI project file has no XML root node");
return false;
}
const std::string &path = mPath;
std::list<std::string> paths;
std::list<SuppressionList::Suppression> suppressions;
Settings temp;
// default to --check-level=normal for import for now
temp.setCheckLevel(Settings::CheckLevel::normal);
guiProject.analyzeAllVsConfigs.clear();
// TODO: this should support all available command-line options
for (const tinyxml2::XMLElement *node = rootnode->FirstChildElement(); node; node = node->NextSiblingElement()) {
const char* name = node->Name();
if (strcmp(name, CppcheckXml::RootPathName) == 0) {
const char* attr = node->Attribute(CppcheckXml::RootPathNameAttrib);
if (attr) {
temp.basePaths.push_back(Path::fromNativeSeparators(joinRelativePath(path, attr)));
temp.relativePaths = true;
}
} else if (strcmp(name, CppcheckXml::BuildDirElementName) == 0)
temp.buildDir = joinRelativePath(path, empty_if_null(node->GetText()));
else if (strcmp(name, CppcheckXml::IncludeDirElementName) == 0)
temp.includePaths = readXmlStringList(node, path, CppcheckXml::DirElementName, CppcheckXml::DirNameAttrib);
else if (strcmp(name, CppcheckXml::DefinesElementName) == 0)
temp.userDefines = join(readXmlStringList(node, "", CppcheckXml::DefineName, CppcheckXml::DefineNameAttrib), ";");
else if (strcmp(name, CppcheckXml::UndefinesElementName) == 0) {
for (const std::string &u : readXmlStringList(node, "", CppcheckXml::UndefineName, nullptr))
temp.userUndefs.insert(u);
} else if (strcmp(name, CppcheckXml::ImportProjectElementName) == 0) {
const std::string t_str = empty_if_null(node->GetText());
if (!t_str.empty())
guiProject.projectFile = path + t_str;
}
else if (strcmp(name, CppcheckXml::PathsElementName) == 0)
paths = readXmlStringList(node, path, CppcheckXml::PathName, CppcheckXml::PathNameAttrib);
else if (strcmp(name, CppcheckXml::ExcludeElementName) == 0)
guiProject.excludedPaths = readXmlStringList(node, "", CppcheckXml::ExcludePathName, CppcheckXml::ExcludePathNameAttrib);
else if (strcmp(name, CppcheckXml::FunctionContracts) == 0)
;
else if (strcmp(name, CppcheckXml::VariableContractsElementName) == 0)
;
else if (strcmp(name, CppcheckXml::IgnoreElementName) == 0)
guiProject.excludedPaths = readXmlStringList(node, "", CppcheckXml::IgnorePathName, CppcheckXml::IgnorePathNameAttrib);
else if (strcmp(name, CppcheckXml::LibrariesElementName) == 0)
guiProject.libraries = readXmlStringList(node, "", CppcheckXml::LibraryElementName, nullptr);
else if (strcmp(name, CppcheckXml::SuppressionsElementName) == 0) {
for (const tinyxml2::XMLElement *child = node->FirstChildElement(); child; child = child->NextSiblingElement()) {
if (strcmp(child->Name(), CppcheckXml::SuppressionElementName) != 0)
continue;
SuppressionList::Suppression s;
s.errorId = empty_if_null(child->GetText());
s.fileName = empty_if_null(child->Attribute("fileName"));
if (!s.fileName.empty())
s.fileName = joinRelativePath(path, s.fileName);
s.lineNumber = child->IntAttribute("lineNumber", SuppressionList::Suppression::NO_LINE);
s.symbolName = empty_if_null(child->Attribute("symbolName"));
s.hash = strToInt<std::size_t>(default_if_null(child->Attribute("hash"), "0"));
suppressions.push_back(std::move(s));
}
} else if (strcmp(name, CppcheckXml::VSConfigurationElementName) == 0)
guiProject.checkVsConfigs = readXmlStringList(node, emptyString, CppcheckXml::VSConfigurationName, nullptr);
else if (strcmp(name, CppcheckXml::PlatformElementName) == 0)
guiProject.platform = empty_if_null(node->GetText());
else if (strcmp(name, CppcheckXml::AnalyzeAllVsConfigsElementName) == 0)
guiProject.analyzeAllVsConfigs = empty_if_null(node->GetText());
else if (strcmp(name, CppcheckXml::Parser) == 0)
temp.clang = true;
else if (strcmp(name, CppcheckXml::AddonsElementName) == 0) {
const auto& addons = readXmlStringList(node, emptyString, CppcheckXml::AddonElementName, nullptr);
temp.addons.insert(addons.cbegin(), addons.cend());
}
else if (strcmp(name, CppcheckXml::TagsElementName) == 0)
node->Attribute(CppcheckXml::TagElementName); // FIXME: Write some warning
else if (strcmp(name, CppcheckXml::ToolsElementName) == 0) {
const std::list<std::string> toolList = readXmlStringList(node, emptyString, CppcheckXml::ToolElementName, nullptr);
for (const std::string &toolName : toolList) {
if (toolName == CppcheckXml::ClangTidy)
temp.clangTidy = true;
}
} else if (strcmp(name, CppcheckXml::CheckHeadersElementName) == 0)
temp.checkHeaders = (strcmp(default_if_null(node->GetText(), ""), "true") == 0);
else if (strcmp(name, CppcheckXml::CheckLevelReducedElementName) == 0)
temp.setCheckLevel(Settings::CheckLevel::reduced);
else if (strcmp(name, CppcheckXml::CheckLevelNormalElementName) == 0)
temp.setCheckLevel(Settings::CheckLevel::normal);
else if (strcmp(name, CppcheckXml::CheckLevelExhaustiveElementName) == 0)
temp.setCheckLevel(Settings::CheckLevel::exhaustive);
else if (strcmp(name, CppcheckXml::CheckUnusedTemplatesElementName) == 0)
temp.checkUnusedTemplates = (strcmp(default_if_null(node->GetText(), ""), "true") == 0);
else if (strcmp(name, CppcheckXml::InlineSuppression) == 0)
temp.inlineSuppressions = (strcmp(default_if_null(node->GetText(), ""), "true") == 0);
else if (strcmp(name, CppcheckXml::MaxCtuDepthElementName) == 0)
temp.maxCtuDepth = strToInt<int>(default_if_null(node->GetText(), "2")); // TODO: bail out when missing?
else if (strcmp(name, CppcheckXml::MaxTemplateRecursionElementName) == 0)
temp.maxTemplateRecursion = strToInt<int>(default_if_null(node->GetText(), "100")); // TODO: bail out when missing?
else if (strcmp(name, CppcheckXml::CheckUnknownFunctionReturn) == 0)
; // TODO
else if (strcmp(name, Settings::SafeChecks::XmlRootName) == 0) {
for (const tinyxml2::XMLElement *child = node->FirstChildElement(); child; child = child->NextSiblingElement()) {
const char* childname = child->Name();
if (strcmp(childname, Settings::SafeChecks::XmlClasses) == 0)
temp.safeChecks.classes = true;
else if (strcmp(childname, Settings::SafeChecks::XmlExternalFunctions) == 0)
temp.safeChecks.externalFunctions = true;
else if (strcmp(childname, Settings::SafeChecks::XmlInternalFunctions) == 0)
temp.safeChecks.internalFunctions = true;
else if (strcmp(childname, Settings::SafeChecks::XmlExternalVariables) == 0)
temp.safeChecks.externalVariables = true;
else {
printError("Unknown '" + std::string(Settings::SafeChecks::XmlRootName) + "' element '" + childname + "' in Cppcheck project file");
return false;
}
}
} else if (strcmp(name, CppcheckXml::TagWarningsElementName) == 0)
; // TODO
// Cppcheck Premium features
else if (strcmp(name, CppcheckXml::BughuntingElementName) == 0)
temp.premiumArgs += " --bughunting";
else if (strcmp(name, CppcheckXml::CertIntPrecisionElementName) == 0)
temp.premiumArgs += std::string(" --cert-c-int-precision=") + default_if_null(node->GetText(), "0");
else if (strcmp(name, CppcheckXml::CodingStandardsElementName) == 0) {
for (const tinyxml2::XMLElement *child = node->FirstChildElement(); child; child = child->NextSiblingElement()) {
if (strcmp(child->Name(), CppcheckXml::CodingStandardElementName) == 0) {
const char* text = child->GetText();
if (text)
temp.premiumArgs += std::string(" --") + text;
}
}
}
else if (strcmp(name, CppcheckXml::ProjectNameElementName) == 0)
; // no-op
else {
printError("Unknown element '" + std::string(name) + "' in Cppcheck project file");
return false;
}
}
settings->basePaths = temp.basePaths;
settings->relativePaths |= temp.relativePaths;
settings->buildDir = temp.buildDir;
settings->includePaths = temp.includePaths;
settings->userDefines = temp.userDefines;
settings->userUndefs = temp.userUndefs;
settings->addons = temp.addons;
settings->clang = temp.clang;
settings->clangTidy = temp.clangTidy;
if (!settings->premiumArgs.empty())
settings->premiumArgs += temp.premiumArgs;
else if (!temp.premiumArgs.empty())
settings->premiumArgs = temp.premiumArgs.substr(1);
for (const std::string &p : paths)
guiProject.pathNames.push_back(Path::fromNativeSeparators(p));
settings->supprs.nomsg.addSuppressions(std::move(suppressions));
settings->checkHeaders = temp.checkHeaders;
settings->checkUnusedTemplates = temp.checkUnusedTemplates;
settings->maxCtuDepth = temp.maxCtuDepth;
settings->maxTemplateRecursion = temp.maxTemplateRecursion;
settings->inlineSuppressions |= temp.inlineSuppressions;
settings->safeChecks = temp.safeChecks;
settings->setCheckLevel(temp.checkLevel);
return true;
}
void ImportProject::selectOneVsConfig(Platform::Type platform)
{
std::set<std::string> filenames;
for (std::list<FileSettings>::const_iterator it = fileSettings.cbegin(); it != fileSettings.cend();) {
if (it->cfg.empty()) {
++it;
continue;
}
const FileSettings &fs = *it;
bool remove = false;
if (!startsWith(fs.cfg,"Debug"))
remove = true;
if (platform == Platform::Type::Win64 && fs.platformType != platform)
remove = true;
else if ((platform == Platform::Type::Win32A || platform == Platform::Type::Win32W) && fs.platformType == Platform::Type::Win64)
remove = true;
else if (filenames.find(fs.filename()) != filenames.end())
remove = true;
if (remove) {
it = fileSettings.erase(it);
} else {
filenames.insert(fs.filename());
++it;
}
}
}
// cppcheck-suppress unusedFunction - used by GUI only
void ImportProject::selectVsConfigurations(Platform::Type platform, const std::vector<std::string> &configurations)
{
for (std::list<FileSettings>::const_iterator it = fileSettings.cbegin(); it != fileSettings.cend();) {
if (it->cfg.empty()) {
++it;
continue;
}
const FileSettings &fs = *it;
const auto config = fs.cfg.substr(0, fs.cfg.find('|'));
bool remove = false;
if (std::find(configurations.begin(), configurations.end(), config) == configurations.end())
remove = true;
if (platform == Platform::Type::Win64 && fs.platformType != platform)
remove = true;
else if ((platform == Platform::Type::Win32A || platform == Platform::Type::Win32W) && fs.platformType == Platform::Type::Win64)
remove = true;
if (remove) {
it = fileSettings.erase(it);
} else {
++it;
}
}
}
// cppcheck-suppress unusedFunction - used by GUI only
std::list<std::string> ImportProject::getVSConfigs()
{
return std::list<std::string>(mAllVSConfigs.cbegin(), mAllVSConfigs.cend());
}
void ImportProject::setRelativePaths(const std::string &filename)
{
if (Path::isAbsolute(filename))
return;
const std::vector<std::string> basePaths{Path::fromNativeSeparators(Path::getCurrentPath())};
for (auto &fs: fileSettings) {
fs.file = FileWithDetails{Path::getRelativePath(fs.filename(), basePaths)};
for (auto &includePath: fs.includePaths)
includePath = Path::getRelativePath(includePath, basePaths);
}
}
void ImportProject::printError(const std::string &message)
{
std::cout << "cppcheck: error: " << message << std::endl;
}
bool ImportProject::sourceFileExists(const std::string &file)
{
return Path::isFile(file);
}
| null |
937 | cpp | cppcheck | version.h | lib/version.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// For a release version x.y.z the MAJOR should be x and both MINOR and DEVMINOR should be y.
// After a release the DEVMINOR is incremented. MAJOR=x MINOR=y, DEVMINOR=y+1
#ifndef versionH
#define versionH
#define CPPCHECK_MAJOR_VERSION 2
#define CPPCHECK_MINOR_VERSION 16
#define CPPCHECK_DEVMINOR_VERSION 17
#define CPPCHECK_BUGFIX_VERSION 99
#define STRINGIFY(x) STRING(x)
#define STRING(VER) #VER
#if CPPCHECK_BUGFIX_VERSION < 99
#define CPPCHECK_VERSION_STRING STRINGIFY(CPPCHECK_MAJOR_VERSION) "." STRINGIFY(CPPCHECK_MINOR_VERSION) "." STRINGIFY(CPPCHECK_BUGFIX_VERSION)
#define CPPCHECK_VERSION CPPCHECK_MAJOR_VERSION,CPPCHECK_MINOR_VERSION,CPPCHECK_BUGFIX_VERSION,0
#else
#define CPPCHECK_VERSION_STRING STRINGIFY(CPPCHECK_MAJOR_VERSION) "." STRINGIFY(CPPCHECK_DEVMINOR_VERSION) " dev"
#define CPPCHECK_VERSION CPPCHECK_MAJOR_VERSION,CPPCHECK_MINOR_VERSION,99,0
#endif
#define LEGALCOPYRIGHT L"Copyright (C) 2007-2024 Cppcheck team."
#endif
| null |
938 | cpp | cppcheck | astutils.h | lib/astutils.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef astutilsH
#define astutilsH
//---------------------------------------------------------------------------
#include <cstdint>
#include <functional>
#include <list>
#include <stack>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
#include "config.h"
#include "errortypes.h"
#include "library.h"
#include "mathlib.h"
#include "smallvector.h"
#include "symboldatabase.h"
#include "token.h"
class Settings;
enum class ChildrenToVisit : std::uint8_t {
none,
op1,
op2,
op1_and_op2,
done // found what we looked for, don't visit any more children
};
/**
* Visit AST nodes recursively. The order is not "well defined"
*/
template<class T, class TFunc, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
void visitAstNodes(T *ast, const TFunc &visitor)
{
if (!ast)
return;
// the size of 8 was determined in tests to be sufficient to avoid excess allocations. also add 1 as a buffer.
// we might need to increase that value in the future.
std::stack<T *, SmallVector<T *, 8 + 1>> tokens;
T *tok = ast;
do {
const ChildrenToVisit c = visitor(tok);
if (c == ChildrenToVisit::done)
break;
if (c == ChildrenToVisit::op2 || c == ChildrenToVisit::op1_and_op2) {
T *t2 = tok->astOperand2();
if (t2)
tokens.push(t2);
}
if (c == ChildrenToVisit::op1 || c == ChildrenToVisit::op1_and_op2) {
T *t1 = tok->astOperand1();
if (t1)
tokens.push(t1);
}
if (tokens.empty())
break;
tok = tokens.top();
tokens.pop();
} while (true);
}
template<class TFunc>
const Token* findAstNode(const Token* ast, const TFunc& pred)
{
const Token* result = nullptr;
visitAstNodes(ast, [&](const Token* tok) {
if (pred(tok)) {
result = tok;
return ChildrenToVisit::done;
}
return ChildrenToVisit::op1_and_op2;
});
return result;
}
template<class TFunc>
const Token* findParent(const Token* tok, const TFunc& pred)
{
if (!tok)
return nullptr;
const Token* parent = tok->astParent();
while (parent && !pred(parent)) {
parent = parent->astParent();
}
return parent;
}
const Token* findExpression(nonneg int exprid,
const Token* start,
const Token* end,
const std::function<bool(const Token*)>& pred);
const Token* findExpression(const Token* start, nonneg int exprid);
/** Does code execution escape from the given scope? */
const Token* findEscapeStatement(const Scope* scope, const Library* library);
std::vector<const Token*> astFlatten(const Token* tok, const char* op);
std::vector<Token*> astFlatten(Token* tok, const char* op);
nonneg int astCount(const Token* tok, const char* op, int depth = 100);
bool astHasToken(const Token* root, const Token * tok);
bool astHasExpr(const Token* tok, nonneg int exprid);
bool astHasVar(const Token * tok, nonneg int varid);
bool astIsPrimitive(const Token* tok);
/** Is expression a 'signed char' if no promotion is used */
bool astIsSignedChar(const Token *tok);
/** Is expression a 'char' if no promotion is used? */
bool astIsUnknownSignChar(const Token *tok);
/** Is expression a char according to valueType? */
bool astIsGenericChar(const Token* tok);
/** Is expression of integral type? */
bool astIsIntegral(const Token *tok, bool unknown);
bool astIsUnsigned(const Token* tok);
/** Is expression of floating point type? */
bool astIsFloat(const Token *tok, bool unknown);
/** Is expression of boolean type? */
bool astIsBool(const Token *tok);
bool astIsPointer(const Token *tok);
bool astIsSmartPointer(const Token* tok);
bool astIsUniqueSmartPointer(const Token* tok);
bool astIsIterator(const Token *tok);
bool astIsContainer(const Token *tok);
bool astIsNonStringContainer(const Token *tok);
bool astIsContainerView(const Token* tok);
bool astIsContainerOwned(const Token* tok);
bool astIsContainerString(const Token* tok);
Library::Container::Action astContainerAction(const Token* tok, const Token** ftok = nullptr, const Settings* settings = nullptr);
Library::Container::Yield astContainerYield(const Token* tok, const Token** ftok = nullptr, const Settings* settings = nullptr);
Library::Container::Yield astFunctionYield(const Token* tok, const Settings& settings, const Token** ftok = nullptr);
/** Is given token a range-declaration in a range-based for loop */
bool astIsRangeBasedForDecl(const Token* tok);
/**
* Get canonical type of expression. const/static/etc are not included and neither *&.
* For example:
* Expression type Return
* std::string std::string
* int * int
* static const int int
* std::vector<T> std::vector
*/
std::string astCanonicalType(const Token *expr, bool pointedToType);
/** Is given syntax tree a variable comparison against value */
const Token * astIsVariableComparison(const Token *tok, const std::string &comp, const std::string &rhs, const Token **vartok=nullptr);
bool isVariableDecl(const Token* tok);
bool isStlStringType(const Token* tok);
bool isTemporary(const Token* tok, const Library* library, bool unknown = false);
const Token* previousBeforeAstLeftmostLeaf(const Token* tok);
Token* previousBeforeAstLeftmostLeaf(Token* tok);
CPPCHECKLIB const Token * nextAfterAstRightmostLeaf(const Token * tok);
Token* nextAfterAstRightmostLeaf(Token* tok);
Token* astParentSkipParens(Token* tok);
const Token* astParentSkipParens(const Token* tok);
const Token* getParentMember(const Token * tok);
const Token* getParentLifetime(const Token* tok);
const Token* getParentLifetime(const Token* tok, const Library& library);
std::vector<ValueType> getParentValueTypes(const Token* tok,
const Settings& settings,
const Token** parent = nullptr);
bool astIsLHS(const Token* tok);
bool astIsRHS(const Token* tok);
Token* getCondTok(Token* tok);
const Token* getCondTok(const Token* tok);
Token* getInitTok(Token* tok);
const Token* getInitTok(const Token* tok);
Token* getStepTok(Token* tok);
const Token* getStepTok(const Token* tok);
Token* getCondTokFromEnd(Token* endBlock);
const Token* getCondTokFromEnd(const Token* endBlock);
/// For a "break" token, locate the next token to execute. The token will
/// be either a "}" or a ";".
const Token *findNextTokenFromBreak(const Token *breakToken);
/**
* Extract for loop values: loopvar varid, init value, step value, last value (inclusive)
*/
bool extractForLoopValues(const Token *forToken,
nonneg int &varid,
bool &knownInitValue,
MathLib::bigint &initValue,
bool &partialCond,
MathLib::bigint &stepValue,
MathLib::bigint &lastValue);
bool precedes(const Token * tok1, const Token * tok2);
bool succeeds(const Token* tok1, const Token* tok2);
bool exprDependsOnThis(const Token* expr, bool onVar = true, nonneg int depth = 0);
struct ReferenceToken {
ReferenceToken(const Token* t, ErrorPath e)
: token(t)
, errors(std::move(e))
{}
const Token* token;
ErrorPath errors;
};
SmallVector<ReferenceToken> followAllReferences(const Token* tok,
bool temporary = true,
bool inconclusive = true,
ErrorPath errors = ErrorPath{},
int depth = 20);
const Token* followReferences(const Token* tok, ErrorPath* errors = nullptr);
CPPCHECKLIB bool isSameExpression(bool macro, const Token *tok1, const Token *tok2, const Settings& settings, bool pure, bool followVar, ErrorPath* errors=nullptr);
bool isEqualKnownValue(const Token * tok1, const Token * tok2);
bool isStructuredBindingVariable(const Variable* var);
const Token* isInLoopCondition(const Token* tok);
/**
* Is token used as boolean, that is to say cast to a bool, or used as a condition in a if/while/for
*/
CPPCHECKLIB bool isUsedAsBool(const Token* tok, const Settings& settings);
/**
* Are the tokens' flags equal?
*/
bool compareTokenFlags(const Token* tok1, const Token* tok2, bool macro);
/**
* Are two conditions opposite
* @param isNot do you want to know if cond1 is !cond2 or if cond1 and cond2 are non-overlapping. true: cond1==!cond2 false: cond1==true => cond2==false
* @param cond1 condition1
* @param cond2 condition2
* @param settings settings
* @param pure boolean
*/
bool isOppositeCond(bool isNot, const Token * cond1, const Token * cond2, const Settings& settings, bool pure, bool followVar, ErrorPath* errors=nullptr);
bool isOppositeExpression(const Token * tok1, const Token * tok2, const Settings& settings, bool pure, bool followVar, ErrorPath* errors=nullptr);
bool isConstFunctionCall(const Token* ftok, const Library& library);
bool isConstExpression(const Token *tok, const Library& library);
bool isWithoutSideEffects(const Token* tok, bool checkArrayAccess = false, bool checkReference = true);
bool isUniqueExpression(const Token* tok);
bool isEscapeFunction(const Token* ftok, const Library* library);
/** Is scope a return scope (scope will unconditionally return) */
CPPCHECKLIB bool isReturnScope(const Token* endToken,
const Library& library,
const Token** unknownFunc = nullptr,
bool functionScope = false);
/** Is tok within a scope of the given type, nested within var's scope? */
bool isWithinScope(const Token* tok,
const Variable* var,
Scope::ScopeType type);
/// Return the token to the function and the argument number
const Token * getTokenArgumentFunction(const Token * tok, int& argn);
Token* getTokenArgumentFunction(Token* tok, int& argn);
std::vector<const Variable*> getArgumentVars(const Token* tok, int argnr);
/** Is variable changed by function call?
* In case the answer of the question is inconclusive, e.g. because the function declaration is not known
* the return value is false and the output parameter inconclusive is set to true
*
* @param tok ast tree
* @param varid Variable Id
* @param settings program settings
* @param inconclusive pointer to output variable which indicates that the answer of the question is inconclusive
*/
bool isVariableChangedByFunctionCall(const Token *tok, int indirect, nonneg int varid, const Settings &settings, bool *inconclusive);
/** Is variable changed by function call?
* In case the answer of the question is inconclusive, e.g. because the function declaration is not known
* the return value is false and the output parameter inconclusive is set to true
*
* @param tok token of variable in function call
* @param settings program settings
* @param inconclusive pointer to output variable which indicates that the answer of the question is inconclusive
*/
CPPCHECKLIB bool isVariableChangedByFunctionCall(const Token *tok, int indirect, const Settings &settings, bool *inconclusive);
/** Is variable changed in block of code? */
CPPCHECKLIB bool isVariableChanged(const Token *start, const Token *end, nonneg int exprid, bool globalvar, const Settings &settings, int depth = 20);
bool isVariableChanged(const Token *start, const Token *end, int indirect, nonneg int exprid, bool globalvar, const Settings &settings, int depth = 20);
bool isVariableChanged(const Token *tok, int indirect, const Settings &settings, int depth = 20);
bool isVariableChanged(const Variable * var, const Settings &settings, int depth = 20);
bool isVariablesChanged(const Token* start,
const Token* end,
int indirect,
const std::vector<const Variable*> &vars,
const Settings& settings);
bool isThisChanged(const Token* tok, int indirect, const Settings& settings);
const Token* findVariableChanged(const Token *start, const Token *end, int indirect, nonneg int exprid, bool globalvar, const Settings &settings, int depth = 20);
Token* findVariableChanged(Token *start, const Token *end, int indirect, nonneg int exprid, bool globalvar, const Settings &settings, int depth = 20);
CPPCHECKLIB const Token* findExpressionChanged(const Token* expr,
const Token* start,
const Token* end,
const Settings& settings,
int depth = 20);
const Token* findExpressionChangedSkipDeadCode(const Token* expr,
const Token* start,
const Token* end,
const Settings& settings,
const std::function<std::vector<MathLib::bigint>(const Token* tok)>& evaluate,
int depth = 20);
bool isExpressionChangedAt(const Token* expr,
const Token* tok,
int indirect,
bool globalvar,
const Settings& settings,
int depth = 20);
/// If token is an alias if another variable
bool isAliasOf(const Token *tok, nonneg int varid, bool* inconclusive = nullptr);
bool isAliasOf(const Token* tok, const Token* expr, int* indirect = nullptr);
const Token* getArgumentStart(const Token* ftok);
/** Determines the number of arguments - if token is a function call or macro
* @param ftok start token which is supposed to be the function/macro name.
* @return Number of arguments
*/
int numberOfArguments(const Token* ftok);
/// Get number of arguments without using AST
int numberOfArgumentsWithoutAst(const Token* start);
/**
* Get arguments (AST)
*/
std::vector<const Token *> getArguments(const Token *ftok);
int getArgumentPos(const Variable* var, const Function* f);
const Token* getIteratorExpression(const Token* tok);
/**
* Are the arguments a pair of iterators/pointers?
*/
bool isIteratorPair(const std::vector<const Token*>& args);
CPPCHECKLIB const Token *findLambdaStartToken(const Token *last);
/**
* find lambda function end token
* \param first The [ token
* \return nullptr or the }
*/
CPPCHECKLIB const Token *findLambdaEndToken(const Token *first);
CPPCHECKLIB Token* findLambdaEndToken(Token* first);
bool isLikelyStream(const Token *stream);
/**
* do we see a likely write of rhs through overloaded operator
* s >> x;
* a & x;
*/
bool isLikelyStreamRead(const Token *op);
bool isCPPCast(const Token* tok);
bool isConstVarExpression(const Token* tok, const std::function<bool(const Token*)>& skipPredicate = nullptr);
bool isLeafDot(const Token* tok);
enum class ExprUsage : std::uint8_t { None, NotUsed, PassedByReference, Used, Inconclusive };
ExprUsage getExprUsage(const Token* tok, int indirect, const Settings& settings);
const Variable *getLHSVariable(const Token *tok);
const Token* getLHSVariableToken(const Token* tok);
std::vector<const Variable*> getLHSVariables(const Token* tok);
/** Find a allocation function call in expression, so result of expression is allocated memory/resource. */
const Token* findAllocFuncCallToken(const Token *expr, const Library &library);
bool isScopeBracket(const Token* tok);
CPPCHECKLIB bool isNullOperand(const Token *expr);
bool isGlobalData(const Token *expr);
bool isUnevaluated(const Token *tok);
bool isExhaustiveSwitch(const Token *startbrace);
bool isUnreachableOperand(const Token *tok);
const Token *skipUnreachableBranch(const Token *tok);
#endif // astutilsH
| null |
939 | cpp | cppcheck | vf_analyzers.cpp | lib/vf_analyzers.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "vf_analyzers.h"
#include "analyzer.h"
#include "astutils.h"
#include "calculate.h"
#include "config.h"
#include "library.h"
#include "mathlib.h"
#include "programmemory.h"
#include "smallvector.h"
#include "settings.h"
#include "symboldatabase.h"
#include "token.h"
#include "utils.h"
#include "vfvalue.h"
#include "valueptr.h"
#include "valueflow.h"
#include "vf_common.h"
#include "vf_settokenvalue.h"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <functional>
#include <initializer_list>
#include <iterator>
#include <list>
#include <set>
#include <type_traits>
struct ValueFlowAnalyzer : Analyzer {
const Settings& settings;
ProgramMemoryState pms;
explicit ValueFlowAnalyzer(const Settings& s) : settings(s), pms(settings) {}
virtual const ValueFlow::Value* getValue(const Token* tok) const = 0;
virtual ValueFlow::Value* getValue(const Token* tok) = 0;
virtual void makeConditional() = 0;
virtual void addErrorPath(const Token* tok, const std::string& s) = 0;
virtual bool match(const Token* tok) const = 0;
virtual bool internalMatch(const Token* /*tok*/) const {
return false;
}
virtual bool isAlias(const Token* tok, bool& inconclusive) const = 0;
using ProgramState = ProgramMemory::Map;
virtual ProgramState getProgramState() const = 0;
virtual int getIndirect(const Token* tok) const {
const ValueFlow::Value* value = getValue(tok);
if (value)
return value->indirect;
return 0;
}
virtual bool isGlobal() const {
return false;
}
virtual bool dependsOnThis() const {
return false;
}
virtual bool isVariable() const {
return false;
}
const Settings& getSettings() const {
return settings;
}
struct ConditionState {
bool dependent = true;
bool unknown = true;
bool isUnknownDependent() const {
return unknown && dependent;
}
};
ConditionState analyzeCondition(const Token* tok, int depth = 20) const
{
ConditionState result;
if (!tok)
return result;
if (depth < 0)
return result;
depth--;
if (analyze(tok, Direction::Forward).isRead()) {
result.dependent = true;
result.unknown = false;
return result;
}
if (tok->hasKnownIntValue() || tok->isLiteral()) {
result.dependent = false;
result.unknown = false;
return result;
}
if (Token::Match(tok, "%cop%")) {
if (isLikelyStream(tok->astOperand1())) {
result.dependent = false;
return result;
}
ConditionState lhs = analyzeCondition(tok->astOperand1(), depth - 1);
if (lhs.isUnknownDependent())
return lhs;
ConditionState rhs = analyzeCondition(tok->astOperand2(), depth - 1);
if (rhs.isUnknownDependent())
return rhs;
if (Token::Match(tok, "%comp%"))
result.dependent = lhs.dependent && rhs.dependent;
else
result.dependent = lhs.dependent || rhs.dependent;
result.unknown = lhs.unknown || rhs.unknown;
return result;
}
if (Token::Match(tok->previous(), "%name% (")) {
std::vector<const Token*> args = getArguments(tok->previous());
if (Token::Match(tok->tokAt(-2), ". %name% (")) {
args.push_back(tok->tokAt(-2)->astOperand1());
}
result.dependent = std::any_of(args.cbegin(), args.cend(), [&](const Token* arg) {
ConditionState cs = analyzeCondition(arg, depth - 1);
return cs.dependent;
});
if (result.dependent) {
// Check if we can evaluate the function
if (!evaluate(Evaluate::Integral, tok).empty())
result.unknown = false;
}
return result;
}
std::unordered_map<nonneg int, const Token*> symbols = getSymbols(tok);
result.dependent = false;
for (auto&& p : symbols) {
const Token* arg = p.second;
ConditionState cs = analyzeCondition(arg, depth - 1);
result.dependent = cs.dependent;
if (result.dependent)
break;
}
if (result.dependent) {
// Check if we can evaluate the token
if (!evaluate(Evaluate::Integral, tok).empty())
result.unknown = false;
}
return result;
}
static ValueFlow::Value::MoveKind isMoveOrForward(const Token* tok)
{
if (!tok)
return ValueFlow::Value::MoveKind::NonMovedVariable;
const Token* parent = tok->astParent();
if (!Token::simpleMatch(parent, "("))
return ValueFlow::Value::MoveKind::NonMovedVariable;
const Token* ftok = parent->astOperand1();
if (!ftok)
return ValueFlow::Value::MoveKind::NonMovedVariable;
if (Token::simpleMatch(ftok->astOperand1(), "std :: move"))
return ValueFlow::Value::MoveKind::MovedVariable;
if (Token::simpleMatch(ftok->astOperand1(), "std :: forward"))
return ValueFlow::Value::MoveKind::ForwardedVariable;
// TODO: Check for cast
return ValueFlow::Value::MoveKind::NonMovedVariable;
}
virtual Action isModified(const Token* tok) const {
const Action read = Action::Read;
const ValueFlow::Value* value = getValue(tok);
if (value) {
// Moving a moved value won't change the moved value
if (value->isMovedValue() && isMoveOrForward(tok) != ValueFlow::Value::MoveKind::NonMovedVariable)
return read;
// Inserting elements to container won't change the lifetime
if (astIsContainer(tok) && value->isLifetimeValue() &&
contains({Library::Container::Action::PUSH,
Library::Container::Action::INSERT,
Library::Container::Action::APPEND,
Library::Container::Action::CHANGE_INTERNAL},
astContainerAction(tok)))
return read;
}
bool inconclusive = false;
if (isVariableChangedByFunctionCall(tok, getIndirect(tok), getSettings(), &inconclusive))
return read | Action::Invalid;
if (inconclusive)
return read | Action::Inconclusive;
if (isVariableChanged(tok, getIndirect(tok), getSettings())) {
if (Token::Match(tok->astParent(), "*|[|.|++|--"))
return read | Action::Invalid;
// Check if its assigned to the same value
if (value && !value->isImpossible() && Token::simpleMatch(tok->astParent(), "=") && astIsLHS(tok) &&
astIsIntegral(tok->astParent()->astOperand2(), false)) {
std::vector<MathLib::bigint> result = evaluateInt(tok->astParent()->astOperand2());
if (!result.empty() && value->equalTo(result.front()))
return Action::Idempotent;
}
return Action::Invalid;
}
return read;
}
virtual Action isAliasModified(const Token* tok, int indirect = -1) const {
// Lambda function call
if (Token::Match(tok, "%var% ("))
// TODO: Check if modified in the lambda function
return Action::Invalid;
if (indirect == -1) {
indirect = 0;
if (const ValueType* vt = tok->valueType()) {
indirect = vt->pointer;
if (vt->type == ValueType::ITERATOR)
++indirect;
const Token* tok2 = tok;
while (Token::simpleMatch(tok2->astParent(), "[")) {
tok2 = tok2->astParent();
--indirect;
}
indirect = std::max(indirect, 0);
}
}
for (int i = 0; i <= indirect; ++i)
if (isVariableChanged(tok, i, getSettings()))
return Action::Invalid;
return Action::None;
}
virtual Action isThisModified(const Token* tok) const {
if (isThisChanged(tok, 0, getSettings()))
return Action::Invalid;
return Action::None;
}
virtual Action isWritable(const Token* tok, Direction d) const {
const ValueFlow::Value* value = getValue(tok);
if (!value)
return Action::None;
if (!(value->isIntValue() || value->isFloatValue() || value->isSymbolicValue() || value->isLifetimeValue()))
return Action::None;
const Token* parent = tok->astParent();
// Only if its invertible
if (value->isImpossible() && !Token::Match(parent, "+=|-=|*=|++|--"))
return Action::None;
if (value->isLifetimeValue()) {
if (value->lifetimeKind != ValueFlow::Value::LifetimeKind::Iterator)
return Action::None;
if (!Token::Match(parent, "++|--|+="))
return Action::None;
return Action::Read | Action::Write;
}
if (parent && parent->isAssignmentOp() && astIsLHS(tok)) {
const Token* rhs = parent->astOperand2();
std::vector<MathLib::bigint> result = evaluateInt(rhs);
if (!result.empty()) {
ValueFlow::Value rhsValue{result.front()};
Action a;
if (!evalAssignment(*value, getAssign(parent, d), rhsValue))
a = Action::Invalid;
else
a = Action::Write;
if (parent->str() != "=") {
a |= Action::Read | Action::Incremental;
} else {
if (!value->isImpossible() && value->equalValue(rhsValue))
a = Action::Idempotent;
if (tok->exprId() != 0 &&
findAstNode(rhs, [&](const Token* child) {
return tok->exprId() == child->exprId();
}))
a |= Action::Incremental;
}
return a;
}
}
// increment/decrement
if (Token::Match(tok->astParent(), "++|--")) {
return Action::Read | Action::Write | Action::Incremental;
}
return Action::None;
}
virtual void writeValue(ValueFlow::Value* value, const Token* tok, Direction d) const {
if (!value)
return;
if (!tok->astParent())
return;
// Lifetime value doesn't change
if (value->isLifetimeValue())
return;
if (tok->astParent()->isAssignmentOp()) {
const Token* rhs = tok->astParent()->astOperand2();
std::vector<MathLib::bigint> result = evaluateInt(rhs);
assert(!result.empty());
ValueFlow::Value rhsValue{result.front()};
if (evalAssignment(*value, getAssign(tok->astParent(), d), rhsValue)) {
std::string info("Compound assignment '" + tok->astParent()->str() + "', assigned value is " +
value->infoString());
if (tok->astParent()->str() == "=")
value->errorPath.clear();
value->errorPath.emplace_back(tok, std::move(info));
} else {
assert(false && "Writable value cannot be evaluated");
// TODO: Don't set to zero
value->intvalue = 0;
}
} else if (tok->astParent()->tokType() == Token::eIncDecOp) {
bool inc = tok->astParent()->str() == "++";
const std::string opName(inc ? "incremented" : "decremented");
if (d == Direction::Reverse)
inc = !inc;
value->intvalue += (inc ? 1 : -1);
/* Truncate value */
const ValueType *dst = tok->valueType();
if (dst) {
const size_t sz = ValueFlow::getSizeOf(*dst, settings);
if (sz > 0 && sz < sizeof(MathLib::biguint)) {
MathLib::bigint newvalue = ValueFlow::truncateIntValue(value->intvalue, sz, dst->sign);
/* Handle overflow/underflow for value bounds */
if (value->bound != ValueFlow::Value::Bound::Point) {
if ((newvalue > value->intvalue && !inc) || (newvalue < value->intvalue && inc))
value->invertBound();
}
value->intvalue = newvalue;
}
value->errorPath.emplace_back(tok, tok->str() + " is " + opName + "', new value is " + value->infoString());
}
}
}
virtual bool useSymbolicValues() const {
return true;
}
virtual void internalUpdate(Token* /*tok*/, const ValueFlow::Value& /*v*/, Direction /*d*/)
{
assert(false && "Internal update unimplemented.");
}
private:
// Returns Action::Match if its an exact match, return Action::Read if it partially matches the lifetime
Action analyzeLifetime(const Token* tok) const
{
if (!tok)
return Action::None;
if (match(tok))
return Action::Match;
if (Token::simpleMatch(tok, ".") && analyzeLifetime(tok->astOperand1()) != Action::None)
return Action::Read;
if (astIsRHS(tok) && Token::simpleMatch(tok->astParent(), "."))
return analyzeLifetime(tok->astParent());
return Action::None;
}
std::unordered_map<nonneg int, const Token*> getSymbols(const Token* tok) const
{
std::unordered_map<nonneg int, const Token*> result;
if (!tok)
return result;
for (const ValueFlow::Value& v : tok->values()) {
if (!v.isSymbolicValue())
continue;
if (v.isImpossible())
continue;
if (!v.tokvalue)
continue;
if (v.tokvalue->exprId() == 0)
continue;
if (match(v.tokvalue))
continue;
result[v.tokvalue->exprId()] = v.tokvalue;
}
return result;
}
Action isGlobalModified(const Token* tok) const
{
if (tok->function()) {
if (!tok->function()->isConstexpr() && !isConstFunctionCall(tok, getSettings().library))
return Action::Invalid;
} else if (getSettings().library.getFunction(tok)) {
// Assume library function doesn't modify user-global variables
return Action::None;
} else if (Token::simpleMatch(tok->astParent(), ".") && astIsContainer(tok->astParent()->astOperand1())) {
// Assume container member function doesn't modify user-global variables
return Action::None;
} else if (tok->tokType() == Token::eType && astIsPrimitive(tok->next())) {
// Function cast does not modify global variables
return Action::None;
} else if (!tok->isKeyword() && Token::Match(tok, "%name% (")) {
return Action::Invalid;
}
return Action::None;
}
static const std::string& invertAssign(const std::string& assign)
{
static std::unordered_map<std::string, std::string> lookup = {{"=", "="},
{"+=", "-="},
{"-=", "+="},
{"*=", "/="},
{"/=", "*="},
{"<<=", ">>="},
{">>=", "<<="},
{"^=", "^="}};
auto it = lookup.find(assign);
if (it == lookup.end()) {
return emptyString;
}
return it->second;
}
static const std::string& getAssign(const Token* tok, Direction d)
{
if (d == Direction::Forward)
return tok->str();
return invertAssign(tok->str());
}
template<class T, class U>
static void assignValueIfMutable(T& x, const U& y)
{
x = y;
}
template<class T, class U>
static void assignValueIfMutable(const T& /*unused*/, const U& /*unused*/)
{}
static std::string removeAssign(const std::string& assign) {
return std::string{assign.cbegin(), assign.cend() - 1};
}
template<class T, class U>
static T calculateAssign(const std::string& assign, const T& x, const U& y, bool* error = nullptr)
{
if (assign.empty() || assign.back() != '=') {
if (error)
*error = true;
return T{};
}
if (assign == "=")
return y;
return calculate<T, T>(removeAssign(assign), x, y, error);
}
template<class Value, REQUIRES("Value must ValueFlow::Value", std::is_convertible<Value&, const ValueFlow::Value&> )>
static bool evalAssignment(Value& lhsValue, const std::string& assign, const ValueFlow::Value& rhsValue)
{
bool error = false;
if (lhsValue.isSymbolicValue() && rhsValue.isIntValue()) {
if (assign != "+=" && assign != "-=")
return false;
assignValueIfMutable(lhsValue.intvalue, calculateAssign(assign, lhsValue.intvalue, rhsValue.intvalue, &error));
} else if (lhsValue.isIntValue() && rhsValue.isIntValue()) {
assignValueIfMutable(lhsValue.intvalue, calculateAssign(assign, lhsValue.intvalue, rhsValue.intvalue, &error));
} else if (lhsValue.isFloatValue() && rhsValue.isIntValue()) {
assignValueIfMutable(lhsValue.floatValue,
calculateAssign(assign, lhsValue.floatValue, rhsValue.intvalue, &error));
} else {
return false;
}
return !error;
}
const Token* findMatch(const Token* tok) const
{
return findAstNode(tok, [&](const Token* child) {
return match(child);
});
}
bool isSameSymbolicValue(const Token* tok, ValueFlow::Value* value = nullptr) const
{
if (!useSymbolicValues())
return false;
if (Token::Match(tok, "%assign%"))
return false;
const ValueFlow::Value* currValue = getValue(tok);
if (!currValue)
return false;
// If the same symbolic value is already there then skip
if (currValue->isSymbolicValue() &&
std::any_of(tok->values().cbegin(), tok->values().cend(), [&](const ValueFlow::Value& v) {
return v.isSymbolicValue() && currValue->equalValue(v);
}))
return false;
const bool isPoint = currValue->bound == ValueFlow::Value::Bound::Point && currValue->isIntValue();
const bool exact = !currValue->isIntValue() || currValue->isImpossible();
for (const ValueFlow::Value& v : tok->values()) {
if (!v.isSymbolicValue())
continue;
if (currValue->equalValue(v))
continue;
const bool toImpossible = v.isImpossible() && currValue->isKnown();
if (!v.isKnown() && !toImpossible)
continue;
if (exact && v.intvalue != 0 && !isPoint)
continue;
std::vector<MathLib::bigint> r;
ValueFlow::Value::Bound bound = currValue->bound;
if (match(v.tokvalue)) {
r = {currValue->intvalue};
} else if (!exact && findMatch(v.tokvalue)) {
r = evaluate(Evaluate::Integral, v.tokvalue, tok);
if (bound == ValueFlow::Value::Bound::Point)
bound = v.bound;
}
if (!r.empty()) {
if (value) {
value->errorPath.insert(value->errorPath.end(), v.errorPath.cbegin(), v.errorPath.cend());
value->intvalue = r.front() + v.intvalue;
if (toImpossible)
value->setImpossible();
value->bound = bound;
}
return true;
}
}
return false;
}
Action analyzeMatch(const Token* tok, Direction d) const {
const Token* parent = tok->astParent();
if (d == Direction::Reverse && isGlobal() && !dependsOnThis() && Token::Match(parent, ". %name% (")) {
Action a = isGlobalModified(parent->next());
if (a != Action::None)
return a;
}
if ((astIsPointer(tok) || astIsSmartPointer(tok)) &&
(Token::Match(parent, "*|[") || (parent && parent->originalName() == "->")) && getIndirect(tok) <= 0)
return Action::Read;
Action w = isWritable(tok, d);
if (w != Action::None)
return w;
// Check for modifications by function calls
return isModified(tok);
}
Action analyzeToken(const Token* ref, const Token* tok, Direction d, bool inconclusiveRef) const {
if (!ref)
return Action::None;
// If its an inconclusiveRef then ref != tok
assert(!inconclusiveRef || ref != tok);
bool inconclusive = false;
if (match(ref)) {
if (inconclusiveRef) {
Action a = isModified(tok);
if (a.isModified() || a.isInconclusive())
return Action::Inconclusive;
} else {
return analyzeMatch(tok, d) | Action::Match;
}
} else if (ref->isUnaryOp("*") && !match(ref->astOperand1())) {
const Token* lifeTok = nullptr;
for (const ValueFlow::Value& v:ref->astOperand1()->values()) {
if (!v.isLocalLifetimeValue())
continue;
if (lifeTok)
return Action::None;
lifeTok = v.tokvalue;
}
if (!lifeTok)
return Action::None;
Action la = analyzeLifetime(lifeTok);
if (la.matches()) {
Action a = Action::Read;
if (isModified(tok).isModified())
a = Action::Invalid;
if (Token::Match(tok->astParent(), "%assign%") && astIsLHS(tok))
a |= Action::Invalid;
if (inconclusiveRef && a.isModified())
return Action::Inconclusive;
return a;
}
if (la.isRead()) {
return isAliasModified(tok);
}
return Action::None;
} else if (isAlias(ref, inconclusive)) {
inconclusive |= inconclusiveRef;
Action a = isAliasModified(tok);
if (inconclusive && a.isModified())
return Action::Inconclusive;
return a;
}
if (isSameSymbolicValue(ref))
return Action::Read | Action::SymbolicMatch;
return Action::None;
}
Action analyze(const Token* tok, Direction d) const override {
if (invalid())
return Action::Invalid;
// Follow references
auto refs = followAllReferences(tok);
const bool inconclusiveRefs = refs.size() != 1;
if (std::none_of(refs.cbegin(), refs.cend(), [&](const ReferenceToken& ref) {
return tok == ref.token;
}))
refs.emplace_back(ReferenceToken{tok, {}});
for (const ReferenceToken& ref:refs) {
Action a = analyzeToken(ref.token, tok, d, inconclusiveRefs && ref.token != tok);
if (internalMatch(ref.token))
a |= Action::Internal;
if (a != Action::None)
return a;
}
if (dependsOnThis() && exprDependsOnThis(tok, !isVariable()))
return isThisModified(tok);
// bailout: global non-const variables
if (isGlobal() && !dependsOnThis() && Token::Match(tok, "%name% (") && !tok->variable() &&
!Token::simpleMatch(tok->linkAt(1), ") {")) {
return isGlobalModified(tok);
}
return Action::None;
}
template<class F>
std::vector<MathLib::bigint> evaluateInt(const Token* tok, F getProgramMemory) const
{
if (tok->hasKnownIntValue())
return {static_cast<int>(tok->values().front().intvalue)};
std::vector<MathLib::bigint> result;
ProgramMemory pm = getProgramMemory();
if (Token::Match(tok, "&&|%oror%")) {
if (conditionIsTrue(tok, pm, getSettings()))
result.push_back(1);
if (conditionIsFalse(tok, std::move(pm), getSettings()))
result.push_back(0);
} else {
MathLib::bigint out = 0;
bool error = false;
execute(tok, pm, &out, &error, getSettings());
if (!error)
result.push_back(out);
}
return result;
}
std::vector<MathLib::bigint> evaluateInt(const Token* tok) const
{
return evaluateInt(tok, [&] {
return ProgramMemory{getProgramState()};
});
}
std::vector<MathLib::bigint> evaluate(Evaluate e, const Token* tok, const Token* ctx = nullptr) const override
{
if (e == Evaluate::Integral) {
return evaluateInt(tok, [&] {
return pms.get(tok, ctx, getProgramState());
});
}
if (e == Evaluate::ContainerEmpty) {
const ValueFlow::Value* value = ValueFlow::findValue(tok->values(), settings, [](const ValueFlow::Value& v) {
return v.isKnown() && v.isContainerSizeValue();
});
if (value)
return {value->intvalue == 0};
ProgramMemory pm = pms.get(tok, ctx, getProgramState());
MathLib::bigint out = 0;
if (pm.getContainerEmptyValue(tok->exprId(), out))
return {static_cast<int>(out)};
return {};
}
return {};
}
void assume(const Token* tok, bool state, unsigned int flags) override {
// Update program state
pms.removeModifiedVars(tok);
pms.addState(tok, getProgramState());
pms.assume(tok, state, flags & Assume::ContainerEmpty);
bool isCondBlock = false;
const Token* parent = tok->astParent();
if (parent) {
isCondBlock = Token::Match(parent->previous(), "if|while (");
}
if (isCondBlock) {
const Token* startBlock = parent->link()->next();
if (Token::simpleMatch(startBlock, ";") && Token::simpleMatch(parent->tokAt(-2), "} while ("))
startBlock = parent->linkAt(-2);
const Token* endBlock = startBlock->link();
if (state) {
pms.removeModifiedVars(endBlock);
pms.addState(endBlock->previous(), getProgramState());
} else {
if (Token::simpleMatch(endBlock, "} else {"))
pms.addState(endBlock->linkAt(2)->previous(), getProgramState());
}
}
if (!(flags & Assume::Quiet)) {
if (flags & Assume::ContainerEmpty) {
std::string s = state ? "empty" : "not empty";
addErrorPath(tok, "Assuming container is " + s);
} else {
std::string s = bool_to_string(state);
addErrorPath(tok, "Assuming condition is " + s);
}
}
if (!(flags & Assume::Absolute))
makeConditional();
}
void updateState(const Token* tok) override
{
// Update program state
pms.removeModifiedVars(tok);
pms.addState(tok, getProgramState());
}
void update(Token* tok, Action a, Direction d) override {
ValueFlow::Value* value = getValue(tok);
if (!value)
return;
ValueFlow::Value localValue;
if (a.isSymbolicMatch()) {
// Make a copy of the value to modify it
localValue = *value;
value = &localValue;
isSameSymbolicValue(tok, &localValue);
}
if (a.isInternal())
internalUpdate(tok, *value, d);
// Read first when moving forward
if (d == Direction::Forward && a.isRead())
setTokenValue(tok, *value, getSettings());
if (a.isInconclusive())
(void)lowerToInconclusive();
if (a.isWrite() && tok->astParent()) {
writeValue(value, tok, d);
}
// Read last when moving in reverse
if (d == Direction::Reverse && a.isRead())
setTokenValue(tok, *value, getSettings());
}
ValuePtr<Analyzer> reanalyze(Token* /*tok*/, const std::string& /*msg*/) const override {
return {};
}
};
static bool bifurcate(const Token* tok, const std::set<nonneg int>& varids, const Settings& settings, int depth = 20);
static bool bifurcateVariableChanged(const Variable* var,
const std::set<nonneg int>& varids,
const Token* start,
const Token* end,
const Settings& settings,
int depth = 20)
{
bool result = false;
const Token* tok = start;
while ((tok = findVariableChanged(
tok->next(), end, var->isPointer(), var->declarationId(), var->isGlobal(), settings))) {
if (Token::Match(tok->astParent(), "%assign%")) {
if (!bifurcate(tok->astParent()->astOperand2(), varids, settings, depth - 1))
return true;
} else {
result = true;
}
}
return result;
}
static bool bifurcate(const Token* tok, const std::set<nonneg int>& varids, const Settings& settings, int depth)
{
if (depth < 0)
return false;
if (!tok)
return true;
if (tok->hasKnownIntValue())
return true;
if (tok->isConstOp())
return bifurcate(tok->astOperand1(), varids, settings, depth) && bifurcate(tok->astOperand2(), varids, settings, depth);
if (tok->varId() != 0) {
if (varids.count(tok->varId()) > 0)
return true;
const Variable* var = tok->variable();
if (!var)
return false;
const Token* start = var->declEndToken();
if (!start)
return false;
if (start->strAt(-1) == ")" || start->strAt(-1) == "}")
return false;
if (Token::Match(start, "; %varid% =", var->declarationId()))
start = start->tokAt(2);
if (var->isConst() || !bifurcateVariableChanged(var, varids, start, tok, settings, depth))
return var->isArgument() || bifurcate(start->astOperand2(), varids, settings, depth - 1);
return false;
}
return false;
}
// Check if its an alias of the variable or is being aliased to this variable
template<typename V>
static bool isAliasOf(const Variable * var, const Token *tok, nonneg int varid, const V& values, bool* inconclusive = nullptr)
{
if (tok->varId() == varid)
return false;
if (tok->varId() == 0)
return false;
if (isAliasOf(tok, varid, inconclusive))
return true;
if (var && !var->isPointer())
return false;
// Search through non value aliases
return std::any_of(values.begin(), values.end(), [&](const ValueFlow::Value& val) {
if (!val.isNonValue())
return false;
if (val.isInconclusive())
return false;
if (val.isLifetimeValue() && !val.isLocalLifetimeValue())
return false;
if (val.isLifetimeValue() && val.lifetimeKind != ValueFlow::Value::LifetimeKind::Address)
return false;
if (!Token::Match(val.tokvalue, ".|&|*|%var%"))
return false;
return astHasVar(val.tokvalue, tok->varId());
});
}
struct MultiValueFlowAnalyzer : ValueFlowAnalyzer {
class SelectValueFromVarIdMapRange {
using M = std::unordered_map<nonneg int, ValueFlow::Value>;
struct Iterator {
using iterator_category = std::forward_iterator_tag;
using value_type = const ValueFlow::Value;
using pointer = value_type *;
using reference = value_type &;
using difference_type = std::ptrdiff_t;
explicit Iterator(const M::const_iterator & it)
: mIt(it) {}
reference operator*() const {
return mIt->second;
}
pointer operator->() const {
return &mIt->second;
}
Iterator &operator++() {
// cppcheck-suppress postfixOperator - forward iterator needs to perform post-increment
mIt++;
return *this;
}
friend bool operator==(const Iterator &a, const Iterator &b) {
return a.mIt == b.mIt;
}
friend bool operator!=(const Iterator &a, const Iterator &b) {
return a.mIt != b.mIt;
}
private:
M::const_iterator mIt;
};
public:
explicit SelectValueFromVarIdMapRange(const M *m)
: mMap(m) {}
Iterator begin() const {
return Iterator(mMap->begin());
}
Iterator end() const {
return Iterator(mMap->end());
}
private:
const M *mMap;
};
std::unordered_map<nonneg int, ValueFlow::Value> values;
std::unordered_map<nonneg int, const Variable*> vars;
MultiValueFlowAnalyzer(const std::unordered_map<const Variable*, ValueFlow::Value>& args, const Settings& set)
: ValueFlowAnalyzer(set) {
for (const auto& p:args) {
values[p.first->declarationId()] = p.second;
vars[p.first->declarationId()] = p.first;
}
}
virtual const std::unordered_map<nonneg int, const Variable*>& getVars() const {
return vars;
}
const ValueFlow::Value* getValue(const Token* tok) const override {
if (tok->varId() == 0)
return nullptr;
auto it = values.find(tok->varId());
if (it == values.end())
return nullptr;
return &it->second;
}
ValueFlow::Value* getValue(const Token* tok) override {
if (tok->varId() == 0)
return nullptr;
auto it = values.find(tok->varId());
if (it == values.end())
return nullptr;
return &it->second;
}
void makeConditional() override {
for (auto&& p:values) {
p.second.conditional = true;
}
}
void addErrorPath(const Token* tok, const std::string& s) override {
for (auto&& p:values) {
p.second.errorPath.emplace_back(tok, s);
}
}
bool isAlias(const Token* tok, bool& inconclusive) const override {
const auto range = SelectValueFromVarIdMapRange(&values);
for (const auto& p:getVars()) {
nonneg int const varid = p.first;
const Variable* var = p.second;
if (tok->varId() == varid)
return true;
if (isAliasOf(var, tok, varid, range, &inconclusive))
return true;
}
return false;
}
bool lowerToPossible() override {
for (auto&& p:values) {
if (p.second.isImpossible())
return false;
p.second.changeKnownToPossible();
}
return true;
}
bool lowerToInconclusive() override {
for (auto&& p:values) {
if (p.second.isImpossible())
return false;
p.second.setInconclusive();
}
return true;
}
bool isConditional() const override {
for (auto&& p:values) {
if (p.second.conditional)
return true;
if (p.second.condition)
return !p.second.isImpossible();
}
return false;
}
bool stopOnCondition(const Token* condTok) const override {
if (isConditional())
return true;
if (!condTok->hasKnownIntValue() && values.count(condTok->varId()) == 0) {
const auto& values_ = condTok->values();
return std::any_of(values_.cbegin(), values_.cend(), [](const ValueFlow::Value& v) {
return v.isSymbolicValue() && Token::Match(v.tokvalue, "%oror%|&&");
});
}
return false;
}
bool updateScope(const Token* endBlock, bool /*modified*/) const override {
const Scope* scope = endBlock->scope();
if (!scope)
return false;
if (scope->type == Scope::eLambda) {
return std::all_of(values.cbegin(), values.cend(), [](const std::pair<nonneg int, ValueFlow::Value>& p) {
return p.second.isLifetimeValue();
});
}
if (scope->type == Scope::eIf || scope->type == Scope::eElse || scope->type == Scope::eWhile ||
scope->type == Scope::eFor) {
auto pred = [](const ValueFlow::Value& value) {
if (value.isKnown())
return true;
if (value.isImpossible())
return true;
if (value.isLifetimeValue())
return true;
return false;
};
if (std::all_of(values.cbegin(), values.cend(), std::bind(pred, std::bind(SelectMapValues{}, std::placeholders::_1))))
return true;
if (isConditional())
return false;
const Token* condTok = getCondTokFromEnd(endBlock);
std::set<nonneg int> varids;
std::transform(getVars().cbegin(), getVars().cend(), std::inserter(varids, varids.begin()), SelectMapKeys{});
return bifurcate(condTok, varids, getSettings());
}
return false;
}
bool match(const Token* tok) const override {
return values.count(tok->varId()) > 0;
}
ProgramState getProgramState() const override {
ProgramState ps;
for (const auto& p : values) {
const Variable* var = vars.at(p.first);
if (!var)
continue;
ps[var->nameToken()] = p.second;
}
return ps;
}
};
ValuePtr<Analyzer> makeMultiValueFlowAnalyzer(const std::unordered_map<const Variable*, ValueFlow::Value>& args, const Settings& settings)
{
return MultiValueFlowAnalyzer{args, settings};
}
struct SingleValueFlowAnalyzer : ValueFlowAnalyzer {
std::unordered_map<nonneg int, const Variable*> varids;
std::unordered_map<nonneg int, const Variable*> aliases;
ValueFlow::Value value;
SingleValueFlowAnalyzer(ValueFlow::Value v, const Settings& s) : ValueFlowAnalyzer(s), value(std::move(v)) {}
const std::unordered_map<nonneg int, const Variable*>& getVars() const {
return varids;
}
const std::unordered_map<nonneg int, const Variable*>& getAliasedVars() const {
return aliases;
}
const ValueFlow::Value* getValue(const Token* /*tok*/) const override {
return &value;
}
ValueFlow::Value* getValue(const Token* /*tok*/) override {
return &value;
}
void makeConditional() override {
value.conditional = true;
}
bool useSymbolicValues() const override
{
if (value.isUninitValue())
return false;
if (value.isLifetimeValue())
return false;
return true;
}
void addErrorPath(const Token* tok, const std::string& s) override {
value.errorPath.emplace_back(tok, s);
}
template<class T>
struct SingleRange {
T* x;
T* begin() const {
return x;
}
T* end() const {
return x+1;
}
};
template<class T>
static SingleRange<T> MakeSingleRange(T& x)
{
return {&x};
}
bool isAlias(const Token* tok, bool& inconclusive) const override {
if (value.isLifetimeValue())
return false;
for (const auto& m: {
std::ref(getVars()), std::ref(getAliasedVars())
}) {
for (const auto& p:m.get()) {
nonneg int const varid = p.first;
const Variable* var = p.second;
if (tok->varId() == varid)
return true;
if (isAliasOf(var, tok, varid, MakeSingleRange(value), &inconclusive))
return true;
}
}
return false;
}
bool isGlobal() const override {
const auto& vars = getVars();
return std::any_of(vars.cbegin(), vars.cend(), [] (const std::pair<nonneg int, const Variable*>& p) {
const Variable* var = p.second;
return !var->isLocal() && !var->isArgument() && !var->isConst();
});
}
bool lowerToPossible() override {
if (value.isImpossible())
return false;
value.changeKnownToPossible();
return true;
}
bool lowerToInconclusive() override {
if (value.isImpossible())
return false;
value.setInconclusive();
return true;
}
bool isConditional() const override {
if (value.conditional)
return true;
if (value.condition)
return !value.isKnown() && !value.isImpossible();
return false;
}
bool stopOnCondition(const Token* condTok) const override
{
if (value.isNonValue())
return false;
if (value.isImpossible())
return false;
if (isConditional() && !value.isKnown() && !value.isImpossible())
return true;
if (value.isSymbolicValue())
return false;
ConditionState cs = analyzeCondition(condTok);
return cs.isUnknownDependent();
}
bool updateScope(const Token* endBlock, bool /*modified*/) const override {
const Scope* scope = endBlock->scope();
if (!scope)
return false;
if (scope->type == Scope::eLambda)
return value.isLifetimeValue();
if (scope->type == Scope::eIf || scope->type == Scope::eElse || scope->type == Scope::eWhile ||
scope->type == Scope::eFor) {
if (value.isKnown() || value.isImpossible())
return true;
if (value.isLifetimeValue())
return true;
if (isConditional())
return false;
const Token* condTok = getCondTokFromEnd(endBlock);
std::set<nonneg int> varids2;
std::transform(getVars().cbegin(), getVars().cend(), std::inserter(varids2, varids2.begin()), SelectMapKeys{});
return bifurcate(condTok, varids2, getSettings());
}
return false;
}
ValuePtr<Analyzer> reanalyze(Token* tok, const std::string& msg) const override {
ValueFlow::Value newValue = value;
newValue.errorPath.emplace_back(tok, msg);
return makeAnalyzer(tok, std::move(newValue), settings);
}
};
struct ExpressionAnalyzer : SingleValueFlowAnalyzer {
const Token* expr;
bool local = true;
bool unknown{};
bool dependOnThis{};
bool uniqueExprId{};
ExpressionAnalyzer(const Token* e, ValueFlow::Value val, const Settings& s)
: SingleValueFlowAnalyzer(std::move(val), s),
expr(e)
{
assert(e && e->exprId() != 0 && "Not a valid expression");
dependOnThis = exprDependsOnThis(expr);
setupExprVarIds(expr);
if (value.isSymbolicValue()) {
dependOnThis |= exprDependsOnThis(value.tokvalue);
setupExprVarIds(value.tokvalue);
}
uniqueExprId =
expr->isUniqueExprId() && (Token::Match(expr, "%cop%") || !isVariableChanged(expr, 0, s));
}
static bool nonLocal(const Variable* var, bool deref) {
return !var || (!var->isLocal() && !var->isArgument()) || (deref && var->isArgument() && var->isPointer()) ||
var->isStatic() || var->isReference() || var->isExtern();
}
void setupExprVarIds(const Token* start, int depth = 0) {
if (depth > settings.vfOptions.maxExprVarIdDepth) {
// TODO: add bailout message
return;
}
visitAstNodes(start, [&](const Token* tok) {
const bool top = depth == 0 && tok == start;
const bool ispointer = astIsPointer(tok) || astIsSmartPointer(tok) || astIsIterator(tok);
if (!top || !ispointer || value.indirect != 0) {
for (const ValueFlow::Value& v : tok->values()) {
if (!(v.isLocalLifetimeValue() || (ispointer && v.isSymbolicValue() && v.isKnown())))
continue;
if (!v.tokvalue)
continue;
if (v.tokvalue == tok)
continue;
setupExprVarIds(v.tokvalue, depth + 1);
}
}
if (depth == 0 && tok->isIncompleteVar()) {
// TODO: Treat incomplete var as global, but we need to update
// the alias variables to just expr ids instead of requiring
// Variable
unknown = true;
return ChildrenToVisit::none;
}
if (tok->varId() > 0) {
varids[tok->varId()] = tok->variable();
if (!Token::simpleMatch(tok->previous(), ".")) {
const Variable* var = tok->variable();
if (var && var->isReference() && var->isLocal() && Token::Match(var->nameToken(), "%var% [=(]") &&
!isGlobalData(var->nameToken()->next()->astOperand2()))
return ChildrenToVisit::none;
const bool deref = tok->astParent() &&
(tok->astParent()->isUnaryOp("*") ||
(tok->astParent()->str() == "[" && tok == tok->astParent()->astOperand1()));
local &= !nonLocal(tok->variable(), deref);
}
}
return ChildrenToVisit::op1_and_op2;
});
}
virtual bool skipUniqueExprIds() const {
return true;
}
bool invalid() const override {
if (skipUniqueExprIds() && uniqueExprId)
return true;
return unknown;
}
ProgramState getProgramState() const override {
ProgramState ps;
ps[expr] = value;
return ps;
}
bool match(const Token* tok) const override {
return tok->exprId() == expr->exprId();
}
bool dependsOnThis() const override {
return dependOnThis;
}
bool isGlobal() const override {
return !local;
}
bool isVariable() const override {
return expr->varId() > 0;
}
Action isAliasModified(const Token* tok, int indirect) const override {
if (value.isSymbolicValue() && tok->exprId() == value.tokvalue->exprId())
indirect = 0;
return SingleValueFlowAnalyzer::isAliasModified(tok, indirect);
}
};
struct SameExpressionAnalyzer : ExpressionAnalyzer {
SameExpressionAnalyzer(const Token* e, ValueFlow::Value val, const Settings& s)
: ExpressionAnalyzer(e, std::move(val), s)
{}
bool skipUniqueExprIds() const override {
return false;
}
bool match(const Token* tok) const override
{
return isSameExpression(true, expr, tok, getSettings(), true, true);
}
};
ValuePtr<Analyzer> makeSameExpressionAnalyzer(const Token* e, ValueFlow::Value val, const Settings& s)
{
return SameExpressionAnalyzer{e, std::move(val), s};
}
struct OppositeExpressionAnalyzer : ExpressionAnalyzer {
bool isNot{};
OppositeExpressionAnalyzer(bool pIsNot, const Token* e, ValueFlow::Value val, const Settings& s)
: ExpressionAnalyzer(e, std::move(val), s), isNot(pIsNot)
{}
bool skipUniqueExprIds() const override {
return false;
}
bool match(const Token* tok) const override {
return isOppositeCond(isNot, expr, tok, getSettings(), true, true);
}
};
ValuePtr<Analyzer> makeOppositeExpressionAnalyzer(bool pIsNot, const Token* e, ValueFlow::Value val, const Settings& s)
{
return OppositeExpressionAnalyzer{pIsNot, e, std::move(val), s};
}
struct SubExpressionAnalyzer : ExpressionAnalyzer {
using PartialReadContainer = std::vector<std::pair<Token *, ValueFlow::Value>>;
// A shared_ptr is used so partial reads can be captured even after forking
std::shared_ptr<PartialReadContainer> partialReads;
SubExpressionAnalyzer(const Token* e, ValueFlow::Value val, const Settings& s)
: ExpressionAnalyzer(e, std::move(val), s), partialReads(std::make_shared<PartialReadContainer>())
{}
SubExpressionAnalyzer(const Token* e, ValueFlow::Value val, const std::shared_ptr<PartialReadContainer>& p, const Settings& s)
: ExpressionAnalyzer(e, std::move(val), s), partialReads(p)
{}
virtual bool submatch(const Token* tok, bool exact = true) const = 0;
bool isAlias(const Token* tok, bool& inconclusive) const override
{
if (tok->exprId() == expr->exprId() && tok->astParent() && submatch(tok->astParent(), false))
return false;
return ExpressionAnalyzer::isAlias(tok, inconclusive);
}
bool match(const Token* tok) const override
{
return tok->astOperand1() && tok->astOperand1()->exprId() == expr->exprId() && submatch(tok);
}
bool internalMatch(const Token* tok) const override
{
return tok->exprId() == expr->exprId() && !(astIsLHS(tok) && submatch(tok->astParent(), false));
}
void internalUpdate(Token* tok, const ValueFlow::Value& v, Direction /*d*/) override
{
partialReads->emplace_back(tok, v);
}
// No reanalysis for subexpression
ValuePtr<Analyzer> reanalyze(Token* /*tok*/, const std::string& /*msg*/) const override {
return {};
}
};
struct MemberExpressionAnalyzer : SubExpressionAnalyzer {
std::string varname;
MemberExpressionAnalyzer(std::string varname, const Token* e, ValueFlow::Value val, const std::shared_ptr<PartialReadContainer>& p, const Settings& s)
: SubExpressionAnalyzer(e, std::move(val), p, s), varname(std::move(varname))
{}
bool submatch(const Token* tok, bool exact) const override
{
if (!Token::Match(tok, ". %var%"))
return false;
if (!exact)
return true;
return tok->strAt(1) == varname;
}
};
ValuePtr<Analyzer> makeMemberExpressionAnalyzer(std::string varname, const Token* e, ValueFlow::Value val, const std::shared_ptr<PartialReadContainer>& p, const Settings& s)
{
return MemberExpressionAnalyzer{std::move(varname), e, std::move(val), p, s};
}
struct ContainerExpressionAnalyzer : ExpressionAnalyzer {
ContainerExpressionAnalyzer(const Token* expr, ValueFlow::Value val, const Settings& s)
: ExpressionAnalyzer(expr, std::move(val), s)
{}
bool match(const Token* tok) const override {
return tok->exprId() == expr->exprId() || (astIsIterator(tok) && isAliasOf(tok, expr->exprId()));
}
Action isWritable(const Token* tok, Direction /*d*/) const override
{
if (astIsIterator(tok))
return Action::None;
if (!getValue(tok))
return Action::None;
if (!tok->valueType())
return Action::None;
if (!astIsContainer(tok))
return Action::None;
const Token* parent = tok->astParent();
const Library::Container* container = getLibraryContainer(tok);
if (container->stdStringLike && Token::simpleMatch(parent, "+=") && astIsLHS(tok) && parent->astOperand2()) {
const Token* rhs = parent->astOperand2();
if (rhs->tokType() == Token::eString)
return Action::Read | Action::Write | Action::Incremental;
const Library::Container* rhsContainer = getLibraryContainer(rhs);
if (rhsContainer && rhsContainer->stdStringLike) {
if (std::any_of(rhs->values().cbegin(), rhs->values().cend(), [&](const ValueFlow::Value &rhsval) {
return rhsval.isKnown() && rhsval.isContainerSizeValue();
}))
return Action::Read | Action::Write | Action::Incremental;
}
} else if (astIsLHS(tok) && Token::Match(tok->astParent(), ". %name% (")) {
const Library::Container::Action action = container->getAction(tok->astParent()->strAt(1));
if (action == Library::Container::Action::PUSH || action == Library::Container::Action::POP || action == Library::Container::Action::APPEND) { // TODO: handle more actions?
std::vector<const Token*> args = getArguments(tok->tokAt(3));
if (args.size() < 2 || action == Library::Container::Action::APPEND)
return Action::Read | Action::Write | Action::Incremental;
}
}
return Action::None;
}
void writeValue(ValueFlow::Value* val, const Token* tok, Direction d) const override {
if (!val)
return;
if (!tok->astParent())
return;
if (!tok->valueType())
return;
if (!astIsContainer(tok))
return;
const Token* parent = tok->astParent();
const Library::Container* container = getLibraryContainer(tok);
MathLib::bigint n = 0;
if (container->stdStringLike && Token::simpleMatch(parent, "+=") && parent->astOperand2()) {
const Token* rhs = parent->astOperand2();
const Library::Container* rhsContainer = getLibraryContainer(rhs);
if (rhs->tokType() == Token::eString)
n = Token::getStrLength(rhs);
else if (rhsContainer && rhsContainer->stdStringLike) {
auto it = std::find_if(rhs->values().begin(), rhs->values().end(), [&](const ValueFlow::Value& rhsval) {
return rhsval.isKnown() && rhsval.isContainerSizeValue();
});
if (it != rhs->values().end())
n = it->intvalue;
}
} else if (astIsLHS(tok) && Token::Match(tok->astParent(), ". %name% (")) {
const Library::Container::Action action = container->getAction(tok->astParent()->strAt(1));
switch (action) {
case Library::Container::Action::PUSH:
n = 1;
break;
case Library::Container::Action::POP:
n = -1;
break;
case Library::Container::Action::APPEND: {
std::vector<const Token*> args = getArguments(tok->astParent()->tokAt(2));
if (args.size() == 1) // TODO: handle overloads
n = ValueFlow::valueFlowGetStrLength(tok->astParent()->tokAt(3));
if (n == 0) // TODO: handle known empty append
val->setPossible();
break;
}
default:
break;
}
}
if (d == Direction::Reverse)
val->intvalue -= n;
else
val->intvalue += n;
}
int getIndirect(const Token* tok) const override
{
if (tok->valueType()) {
return tok->valueType()->pointer;
}
return ValueFlowAnalyzer::getIndirect(tok);
}
Action isModified(const Token* tok) const override {
Action read = Action::Read;
// An iterator won't change the container size
if (astIsIterator(tok))
return read;
if (Token::Match(tok->astParent(), "%assign%") && astIsLHS(tok))
return Action::Invalid;
if (isLikelyStreamRead(tok->astParent()))
return Action::Invalid;
if (astIsContainer(tok) && ValueFlow::isContainerSizeChanged(tok, getIndirect(tok), getSettings()))
return read | Action::Invalid;
return read;
}
};
static const Token* solveExprValue(const Token* expr, ValueFlow::Value& value)
{
return ValueFlow::solveExprValue(
expr,
[](const Token* tok) -> std::vector<MathLib::bigint> {
if (tok->hasKnownIntValue())
return {tok->values().front().intvalue};
return {};
},
value);
}
ValuePtr<Analyzer> makeAnalyzer(const Token* exprTok, ValueFlow::Value value, const Settings& settings)
{
if (value.isContainerSizeValue())
return ContainerExpressionAnalyzer(exprTok, std::move(value), settings);
const Token* expr = solveExprValue(exprTok, value);
return ExpressionAnalyzer(expr, std::move(value), settings);
}
ValuePtr<Analyzer> makeReverseAnalyzer(const Token* exprTok, ValueFlow::Value value, const Settings& settings)
{
if (value.isContainerSizeValue())
return ContainerExpressionAnalyzer(exprTok, std::move(value), settings);
return ExpressionAnalyzer(exprTok, std::move(value), settings);
}
| null |
940 | cpp | cppcheck | cppcheck.h | lib/cppcheck.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef cppcheckH
#define cppcheckH
//---------------------------------------------------------------------------
#include "check.h"
#include "config.h"
#include "settings.h"
#include <cstdint>
#include <fstream>
#include <functional>
#include <list>
#include <memory>
#include <string>
#include <vector>
class TokenList;
enum class SHOWTIME_MODES : std::uint8_t;
struct FileSettings;
class CheckUnusedFunctions;
class Tokenizer;
class FileWithDetails;
class AnalyzerInformation;
class ErrorLogger;
namespace simplecpp { class TokenList; }
/// @addtogroup Core
/// @{
/**
* @brief This is the base class which will use other classes to do
* static code analysis for C and C++ code to find possible
* errors or places that could be improved.
* Usage: See check() for more info.
*/
class CPPCHECKLIB CppCheck {
public:
using ExecuteCmdFn = std::function<int (std::string,std::vector<std::string>,std::string,std::string&)>;
/**
* @brief Constructor.
*/
CppCheck(ErrorLogger &errorLogger,
bool useGlobalSuppressions,
ExecuteCmdFn executeCommand);
/**
* @brief Destructor.
*/
~CppCheck();
/**
* @brief This starts the actual checking. Note that you must call
* parseFromArgs() or settings() and addFile() before calling this.
* @return amount of errors found or 0 if none were found.
*/
/**
* @brief Check the file.
* This function checks one given file for errors.
* @param file The file to check.
* @return amount of errors found or 0 if none were found.
* @note You must set settings before calling this function (by calling
* settings()).
*/
unsigned int check(const FileWithDetails &file);
unsigned int check(const FileSettings &fs);
/**
* @brief Check the file.
* This function checks one "virtual" file. The file is not read from
* the disk but the content is given in @p content. In errors the @p path
* is used as a filename.
* @param file The file to check.
* @param content File content as a string.
* @return amount of errors found or 0 if none were found.
* @note You must set settings before calling this function (by calling
* settings()).
*/
unsigned int check(const FileWithDetails &file, const std::string &content);
/**
* @brief Get reference to current settings.
* @return a reference to current settings
*/
Settings &settings();
/**
* @brief Returns current version number as a string.
* @return version, e.g. "1.38"
*/
RET_NONNULL static const char * version();
/**
* @brief Returns extra version info as a string.
* This is for returning extra version info, like Git commit id, build
* time/date etc.
* @return extra version info, e.g. "04d42151" (Git commit id).
*/
RET_NONNULL static const char * extraVersion();
/**
* @brief Call all "getErrorMessages" in all registered Check classes.
* Also print out XML header and footer.
*/
static void getErrorMessages(ErrorLogger &errorlogger);
void tooManyConfigsError(const std::string &file, int numberOfConfigurations);
void purgedConfigurationMessage(const std::string &file, const std::string& configuration);
/** Analyse whole program, run this after all TUs has been scanned.
* This is deprecated and the plan is to remove this when
* .analyzeinfo is good enough.
* Return true if an error is reported.
*/
bool analyseWholeProgram();
/** Analyze all files using clang-tidy */
void analyseClangTidy(const FileSettings &fileSettings);
/** analyse whole program use .analyzeinfo files or ctuinfo string */
unsigned int analyseWholeProgram(const std::string &buildDir, const std::list<FileWithDetails> &files, const std::list<FileSettings>& fileSettings, const std::string& ctuInfo);
static void resetTimerResults();
static void printTimerResults(SHOWTIME_MODES mode);
bool isPremiumCodingStandardId(const std::string& id) const;
/**
* @brief Get dumpfile <rawtokens> contents, this is only public for testing purposes
*/
std::string getDumpFileContentsRawTokens(const std::vector<std::string>& files, const simplecpp::TokenList& tokens1) const;
std::string getLibraryDumpData() const;
/**
* @brief Get the clang command line flags using the Settings
* @param fileLang language guessed from filename
* @return Clang command line flags
*/
std::string getClangFlags(Standards::Language fileLang) const;
private:
#ifdef HAVE_RULES
/** Are there "simple" rules */
bool hasRule(const std::string &tokenlist) const;
#endif
/** @brief There has been an internal error => Report information message */
void internalError(const std::string &filename, const std::string &msg);
/**
* @brief Check a file using stream
* @param file the file
* @param cfgname cfg name
* @param fileStream stream the file content can be read from
* @return number of errors found
*/
unsigned int checkFile(const FileWithDetails& file, const std::string &cfgname, std::istream* fileStream = nullptr);
/**
* @brief Check normal tokens
* @param tokenizer tokenizer instance
* @param analyzerInformation the analyzer infomation
*/
void checkNormalTokens(const Tokenizer &tokenizer, AnalyzerInformation* analyzerInformation);
/**
* Execute addons
*/
void executeAddons(const std::vector<std::string>& files, const std::string& file0);
void executeAddons(const std::string &dumpFile, const FileWithDetails& file);
/**
* Execute addons
*/
void executeAddonsWholeProgram(const std::list<FileWithDetails> &files, const std::list<FileSettings>& fileSettings, const std::string& ctuInfo);
#ifdef HAVE_RULES
/**
* @brief Execute rules, if any
* @param tokenlist token list to use (define / normal / raw)
* @param list token list
*/
void executeRules(const std::string &tokenlist, const TokenList &list);
#endif
unsigned int checkClang(const FileWithDetails &file);
Settings mSettings;
class CppCheckLogger;
std::unique_ptr<CppCheckLogger> mLogger;
/** the internal ErrorLogger */
ErrorLogger& mErrorLogger;
/** the ErrorLogger provided to this instance */
ErrorLogger& mErrorLoggerDirect;
/** @brief Current preprocessor configuration */
std::string mCurrentConfig;
bool mUseGlobalSuppressions;
/** Are there too many configs? */
bool mTooManyConfigs{};
/** File info used for whole program analysis */
std::list<Check::FileInfo*> mFileInfo;
/** Callback for executing a shell command (exe, args, output) */
ExecuteCmdFn mExecuteCommand;
std::unique_ptr<CheckUnusedFunctions> mUnusedFunctionsCheck;
};
/// @}
//---------------------------------------------------------------------------
#endif // cppcheckH
| null |
941 | cpp | cppcheck | standards.cpp | lib/standards.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "standards.h"
#include "utils.h"
#include <utility>
#include <simplecpp.h>
static Standards::cstd_t mapC(simplecpp::cstd_t cstd) {
switch (cstd)
{
case simplecpp::C89:
return Standards::C89;
case simplecpp::C99:
return Standards::C99;
case simplecpp::C11:
return Standards::C11;
case simplecpp::C17:
return Standards::C17;
case simplecpp::C23:
return Standards::C23;
case simplecpp::CUnknown:
return Standards::CLatest;
}
cppcheck::unreachable();
}
bool Standards::setC(std::string str)
{
if (str.empty())
return false;
const simplecpp::cstd_t c_new = simplecpp::getCStd(str);
const bool b = (c_new != simplecpp::CUnknown);
if (b) {
c = mapC(c_new);
stdValueC = std::move(str);
}
return b;
}
std::string Standards::getC() const
{
return getC(c);
}
std::string Standards::getC(cstd_t c_std)
{
switch (c_std) {
case C89:
return "c89";
case C99:
return "c99";
case C11:
return "c11";
case C17:
return "c17";
case C23:
return "c23";
}
return "";
}
Standards::cstd_t Standards::getC(const std::string &std)
{
return mapC(simplecpp::getCStd(std));
}
static Standards::cppstd_t mapCPP(simplecpp::cppstd_t cppstd) {
switch (cppstd)
{
case simplecpp::CPP03:
return Standards::CPP03;
case simplecpp::CPP11:
return Standards::CPP11;
case simplecpp::CPP14:
return Standards::CPP14;
case simplecpp::CPP17:
return Standards::CPP17;
case simplecpp::CPP20:
return Standards::CPP20;
case simplecpp::CPP23:
return Standards::CPP23;
case simplecpp::CPP26:
return Standards::CPP26;
case simplecpp::CPPUnknown:
return Standards::CPPLatest;
}
cppcheck::unreachable();
}
bool Standards::setCPP(std::string str)
{
if (str.empty())
return false;
const simplecpp::cppstd_t cpp_new = simplecpp::getCppStd(str);
const bool b = (cpp_new != simplecpp::CPPUnknown);
if (b) {
cpp = mapCPP(cpp_new);
stdValueCPP = std::move(str);
}
return b;
}
std::string Standards::getCPP() const
{
return getCPP(cpp);
}
std::string Standards::getCPP(cppstd_t std)
{
switch (std) {
case CPP03:
return "c++03";
case CPP11:
return "c++11";
case CPP14:
return "c++14";
case CPP17:
return "c++17";
case CPP20:
return "c++20";
case CPP23:
return "c++23";
case CPP26:
return "c++26";
}
return "";
}
Standards::cppstd_t Standards::getCPP(const std::string &std)
{
return mapCPP(simplecpp::getCppStd(std));
}
bool Standards::setStd(const std::string& str)
{
return setC(str) || setCPP(str);
}
| null |
942 | cpp | cppcheck | pathanalysis.cpp | lib/pathanalysis.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "pathanalysis.h"
#include "astutils.h"
#include "symboldatabase.h"
#include "token.h"
#include "vfvalue.h"
#include <algorithm>
#include <string>
#include <tuple>
const Scope* PathAnalysis::findOuterScope(const Scope * scope)
{
if (!scope)
return nullptr;
if (scope->isLocal() && scope->type != Scope::eSwitch)
return findOuterScope(scope->nestedIn);
return scope;
}
static const Token* assignExpr(const Token* tok)
{
while (tok->astParent() && astIsLHS(tok)) {
if (Token::Match(tok->astParent(), "%assign%"))
return tok->astParent();
tok = tok->astParent();
}
return nullptr;
}
std::pair<bool, bool> PathAnalysis::checkCond(const Token * tok, bool& known)
{
if (tok->hasKnownIntValue()) {
known = true;
return std::make_pair(tok->values().front().intvalue, !tok->values().front().intvalue);
}
auto it = std::find_if(tok->values().cbegin(), tok->values().cend(), [](const ValueFlow::Value& v) {
return v.isIntValue();
});
// If all possible values are the same, then assume all paths have the same value
if (it != tok->values().cend() && std::all_of(it, tok->values().cend(), [&](const ValueFlow::Value& v) {
if (v.isIntValue())
return v.intvalue == it->intvalue;
return true;
})) {
known = false;
return std::make_pair(it->intvalue, !it->intvalue);
}
return std::make_pair(true, true);
}
PathAnalysis::Progress PathAnalysis::forwardRecursive(const Token* tok, Info info, const std::function<PathAnalysis::Progress(const Info&)>& f)
{
if (!tok)
return Progress::Continue;
if (tok->astOperand1() && forwardRecursive(tok->astOperand1(), info, f) == Progress::Break)
return Progress::Break;
info.tok = tok;
if (f(info) == Progress::Break)
return Progress::Break;
if (tok->astOperand2() && forwardRecursive(tok->astOperand2(), std::move(info), f) == Progress::Break)
return Progress::Break;
return Progress::Continue;
}
PathAnalysis::Progress PathAnalysis::forwardRange(const Token* startToken, const Token* endToken, Info info, const std::function<PathAnalysis::Progress(const Info&)>& f) const
{
for (const Token *tok = startToken; precedes(tok, endToken); tok = tok->next()) {
if (Token::Match(tok, "asm|goto|break|continue"))
return Progress::Break;
if (Token::Match(tok, "return|throw")) {
forwardRecursive(tok, std::move(info), f);
return Progress::Break;
// Evaluate RHS of assignment before LHS
}
if (const Token* assignTok = assignExpr(tok)) {
if (forwardRecursive(assignTok->astOperand2(), info, f) == Progress::Break)
return Progress::Break;
if (forwardRecursive(assignTok->astOperand1(), info, f) == Progress::Break)
return Progress::Break;
tok = nextAfterAstRightmostLeaf(assignTok);
if (!tok)
return Progress::Break;
} else if (Token::simpleMatch(tok, "}") && Token::simpleMatch(tok->link()->previous(), ") {") && Token::Match(tok->link()->linkAt(-1)->previous(), "if|while|for (")) {
const Token * blockStart = tok->link()->linkAt(-1)->previous();
const Token * condTok = getCondTok(blockStart);
if (!condTok)
continue;
info.errorPath.emplace_back(condTok, "Assuming condition is true.");
// Traverse a loop a second time
if (Token::Match(blockStart, "for|while (")) {
const Token* endCond = blockStart->linkAt(1);
bool traverseLoop = true;
// Only traverse simple for loops
if (Token::simpleMatch(blockStart, "for") && !Token::Match(endCond->tokAt(-3), "; ++|--|%var% %var%|++|-- ) {"))
traverseLoop = false;
// Traverse loop a second time
if (traverseLoop) {
// Traverse condition
if (forwardRecursive(condTok, info, f) == Progress::Break)
return Progress::Break;
// TODO: Should we traverse the body: forwardRange(tok->link(), tok, info, f)?
}
}
if (Token::simpleMatch(tok, "} else {")) {
tok = tok->linkAt(2);
}
} else if (Token::Match(tok, "if|while|for (") && Token::simpleMatch(tok->linkAt(1), ") {")) {
const Token * endCond = tok->linkAt(1);
const Token * endBlock = endCond->linkAt(1);
const Token * condTok = getCondTok(tok);
if (!condTok)
continue;
// Traverse condition
if (forwardRange(tok->next(), tok->linkAt(1), info, f) == Progress::Break)
return Progress::Break;
Info i = info;
i.known = false;
i.errorPath.emplace_back(condTok, "Assuming condition is true.");
// Check if condition is true or false
bool checkThen = false;
bool checkElse = false;
std::tie(checkThen, checkElse) = checkCond(condTok, i.known);
// Traverse then block
if (checkThen) {
if (forwardRange(endCond->next(), endBlock, i, f) == Progress::Break)
return Progress::Break;
}
// Traverse else block
if (Token::simpleMatch(endBlock, "} else {")) {
if (checkElse) {
i.errorPath.back().second = "Assuming condition is false.";
const Progress result = forwardRange(endCond->next(), endBlock, std::move(i), f);
if (result == Progress::Break)
return Progress::Break;
}
tok = endBlock->linkAt(2);
} else {
tok = endBlock;
}
} else if (Token::simpleMatch(tok, "} else {")) {
tok = tok->linkAt(2);
} else {
info.tok = tok;
if (f(info) == Progress::Break)
return Progress::Break;
}
// Prevent infinite recursion
if (tok->next() == start)
break;
}
return Progress::Continue;
}
void PathAnalysis::forward(const std::function<Progress(const Info&)>& f) const
{
const Scope * endScope = findOuterScope(start->scope());
if (!endScope)
return;
const Token * endToken = endScope->bodyEnd;
Info info{start, ErrorPath{}, true};
forwardRange(start, endToken, std::move(info), f);
}
bool reaches(const Token * start, const Token * dest, const Library& library, ErrorPath* errorPath)
{
PathAnalysis::Info info = PathAnalysis{start, library}.forwardFind([&](const PathAnalysis::Info& i) {
return (i.tok == dest);
});
if (!info.tok)
return false;
if (errorPath)
errorPath->insert(errorPath->end(), info.errorPath.cbegin(), info.errorPath.cend());
return true;
}
| null |
943 | cpp | cppcheck | vf_common.h | lib/vf_common.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef vfCommonH
#define vfCommonH
#include "config.h"
#include "mathlib.h"
#include "sourcelocation.h"
#include "symboldatabase.h"
#include "vfvalue.h"
#include <cstddef>
#include <string>
class Token;
class Settings;
class Platform;
namespace ValueFlow
{
bool getMinMaxValues(const ValueType* vt, const Platform& platform, MathLib::bigint& minValue, MathLib::bigint& maxValue);
MathLib::bigint truncateIntValue(MathLib::bigint value, size_t value_size, const ValueType::Sign dst_sign);
Token * valueFlowSetConstantValue(Token *tok, const Settings &settings);
Value castValue(Value value, const ValueType::Sign sign, nonneg int bit);
std::string debugString(const Value& v);
void setSourceLocation(Value& v,
SourceLocation ctx,
const Token* tok,
SourceLocation local = SourceLocation::current());
MathLib::bigint valueFlowGetStrLength(const Token* tok);
}
#endif // vfCommonH
| null |
944 | cpp | cppcheck | valueflow.cpp | lib/valueflow.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @brief This is the ValueFlow component in Cppcheck.
*
* Each @sa Token in the token list has a list of values. These are
* the "possible" values for the Token at runtime.
*
* In the --debug and --debug-normal output you can see the ValueFlow data. For example:
*
* int f()
* {
* int x = 10;
* return 4 * x + 2;
* }
*
* The --debug-normal output says:
*
* ##Value flow
* Line 3
* 10 always 10
* Line 4
* 4 always 4
* * always 40
* x always 10
* + always 42
* 2 always 2
*
* All value flow analysis is executed in the ValueFlow::setValues() function. The ValueFlow analysis is executed after
* the tokenizer/ast/symboldatabase/etc.. The ValueFlow analysis is done in a series of valueFlow* function calls, where
* each such function call can only use results from previous function calls. The function calls should be arranged so
* that valueFlow* that do not require previous ValueFlow information should be first.
*
* Type of analysis
* ================
*
* This is "flow sensitive" value flow analysis. We _usually_ track the value for 1 variable at a time.
*
* How are calculations handled
* ============================
*
* Here is an example code:
*
* x = 3 + 4;
*
* The valueFlowNumber set the values for the "3" and "4" tokens by calling setTokenValue().
* The setTokenValue() handle the calculations automatically. When both "3" and "4" have values, the "+" can be
* calculated. setTokenValue() recursively calls itself when parents in calculations can be calculated.
*
* Forward / Reverse flow analysis
* ===============================
*
* In forward value flow analysis we know a value and see what happens when we are stepping the program forward. Like
* normal execution. The valueFlowForward is used in this analysis.
*
* In reverse value flow analysis we know the value of a variable at line X. And try to "execute backwards" to determine
* possible values before line X. The valueFlowReverse is used in this analysis.
*
*
*/
#include "valueflow.h"
#include "analyzer.h"
#include "astutils.h"
#include "calculate.h"
#include "checkuninitvar.h"
#include "config.h"
#include "errorlogger.h"
#include "errortypes.h"
#include "findtoken.h"
#include "forwardanalyzer.h"
#include "infer.h"
#include "library.h"
#include "mathlib.h"
#include "path.h"
#include "platform.h"
#include "programmemory.h"
#include "reverseanalyzer.h"
#include "settings.h"
#include "smallvector.h"
#include "sourcelocation.h"
#include "standards.h"
#include "symboldatabase.h"
#include "timer.h"
#include "token.h"
#include "tokenlist.h"
#include "utils.h"
#include "valueptr.h"
#include "vfvalue.h"
#include "vf_analyzers.h"
#include "vf_common.h"
#include "vf_settokenvalue.h"
#include <algorithm>
#include <array>
#include <cassert>
#include <chrono>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <initializer_list>
#include <iterator>
#include <limits>
#include <map>
#include <memory>
#include <numeric>
#include <set>
#include <sstream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
static void bailoutInternal(const std::string& type,
const TokenList& tokenlist,
ErrorLogger& errorLogger,
const Token* tok,
const std::string& what,
const std::string& file,
int line,
std::string function)
{
if (function.find("operator") != std::string::npos)
function = "(valueFlow)";
ErrorMessage::FileLocation loc(tok, &tokenlist);
const std::string location = Path::stripDirectoryPart(file) + ":" + std::to_string(line) + ":";
ErrorMessage errmsg({std::move(loc)},
tokenlist.getSourceFilePath(),
Severity::debug,
(file.empty() ? "" : location) + function + " bailout: " + what,
type,
Certainty::normal);
errorLogger.reportErr(errmsg);
}
#define bailout2(type, tokenlist, errorLogger, tok, what) \
bailoutInternal((type), (tokenlist), (errorLogger), (tok), (what), __FILE__, __LINE__, __func__)
#define bailout(tokenlist, errorLogger, tok, what) \
bailout2("valueFlowBailout", (tokenlist), (errorLogger), (tok), (what))
#define bailoutIncompleteVar(tokenlist, errorLogger, tok, what) \
bailoutInternal("valueFlowBailoutIncompleteVar", (tokenlist), (errorLogger), (tok), (what), "", 0, __func__)
static void changeKnownToPossible(std::list<ValueFlow::Value>& values, int indirect = -1)
{
for (ValueFlow::Value& v : values) {
if (indirect >= 0 && v.indirect != indirect)
continue;
v.changeKnownToPossible();
}
}
static void removeImpossible(std::list<ValueFlow::Value>& values, int indirect = -1)
{
values.remove_if([&](const ValueFlow::Value& v) {
if (indirect >= 0 && v.indirect != indirect)
return false;
return v.isImpossible();
});
}
static void lowerToPossible(std::list<ValueFlow::Value>& values, int indirect = -1)
{
changeKnownToPossible(values, indirect);
removeImpossible(values, indirect);
}
static void changePossibleToKnown(std::list<ValueFlow::Value>& values, int indirect = -1)
{
for (ValueFlow::Value& v : values) {
if (indirect >= 0 && v.indirect != indirect)
continue;
if (!v.isPossible())
continue;
if (v.bound != ValueFlow::Value::Bound::Point)
continue;
v.setKnown();
}
}
static bool isNonConditionalPossibleIntValue(const ValueFlow::Value& v)
{
if (v.conditional)
return false;
if (v.condition)
return false;
if (!v.isPossible())
return false;
if (!v.isIntValue())
return false;
return true;
}
static void setValueUpperBound(ValueFlow::Value& value, bool upper)
{
if (upper)
value.bound = ValueFlow::Value::Bound::Upper;
else
value.bound = ValueFlow::Value::Bound::Lower;
}
static void setValueBound(ValueFlow::Value& value, const Token* tok, bool invert)
{
if (Token::Match(tok, "<|<=")) {
setValueUpperBound(value, !invert);
} else if (Token::Match(tok, ">|>=")) {
setValueUpperBound(value, invert);
}
}
static void setConditionalValue(ValueFlow::Value& value, const Token* tok, MathLib::bigint i)
{
assert(value.isIntValue());
value.intvalue = i;
value.assumeCondition(tok);
value.setPossible();
}
static void setConditionalValues(const Token* tok,
bool lhs,
MathLib::bigint value,
ValueFlow::Value& true_value,
ValueFlow::Value& false_value)
{
if (Token::Match(tok, "==|!=|>=|<=")) {
setConditionalValue(true_value, tok, value);
const char* greaterThan = ">=";
const char* lessThan = "<=";
if (lhs)
std::swap(greaterThan, lessThan);
if (Token::simpleMatch(tok, greaterThan, strlen(greaterThan))) {
setConditionalValue(false_value, tok, value - 1);
} else if (Token::simpleMatch(tok, lessThan, strlen(lessThan))) {
setConditionalValue(false_value, tok, value + 1);
} else {
setConditionalValue(false_value, tok, value);
}
} else {
const char* greaterThan = ">";
const char* lessThan = "<";
if (lhs)
std::swap(greaterThan, lessThan);
if (Token::simpleMatch(tok, greaterThan, strlen(greaterThan))) {
setConditionalValue(true_value, tok, value + 1);
setConditionalValue(false_value, tok, value);
} else if (Token::simpleMatch(tok, lessThan, strlen(lessThan))) {
setConditionalValue(true_value, tok, value - 1);
setConditionalValue(false_value, tok, value);
}
}
setValueBound(true_value, tok, lhs);
setValueBound(false_value, tok, !lhs);
}
static bool isSaturated(MathLib::bigint value)
{
return value == std::numeric_limits<MathLib::bigint>::max() || value == std::numeric_limits<MathLib::bigint>::min();
}
static void parseCompareEachInt(
const Token* tok,
const std::function<void(const Token* varTok, ValueFlow::Value true_value, ValueFlow::Value false_value)>& each,
const std::function<std::vector<ValueFlow::Value>(const Token*)>& evaluate)
{
if (!tok->astOperand1() || !tok->astOperand2())
return;
if (tok->isComparisonOp()) {
std::vector<ValueFlow::Value> value1 = evaluate(tok->astOperand1());
std::vector<ValueFlow::Value> value2 = evaluate(tok->astOperand2());
if (!value1.empty() && !value2.empty()) {
if (tok->astOperand1()->hasKnownIntValue())
value2.clear();
if (tok->astOperand2()->hasKnownIntValue())
value1.clear();
}
for (const ValueFlow::Value& v1 : value1) {
if (isSaturated(v1.intvalue) || astIsFloat(tok->astOperand2(), /*unknown*/ false))
continue;
ValueFlow::Value true_value = v1;
ValueFlow::Value false_value = v1;
setConditionalValues(tok, true, v1.intvalue, true_value, false_value);
each(tok->astOperand2(), std::move(true_value), std::move(false_value));
}
for (const ValueFlow::Value& v2 : value2) {
if (isSaturated(v2.intvalue) || astIsFloat(tok->astOperand1(), /*unknown*/ false))
continue;
ValueFlow::Value true_value = v2;
ValueFlow::Value false_value = v2;
setConditionalValues(tok, false, v2.intvalue, true_value, false_value);
each(tok->astOperand1(), std::move(true_value), std::move(false_value));
}
}
}
static void parseCompareEachInt(
const Token* tok,
const std::function<void(const Token* varTok, ValueFlow::Value true_value, ValueFlow::Value false_value)>& each)
{
parseCompareEachInt(tok, each, [](const Token* t) -> std::vector<ValueFlow::Value> {
if (t->hasKnownIntValue())
return {t->values().front()};
std::vector<ValueFlow::Value> result;
std::copy_if(t->values().cbegin(), t->values().cend(), std::back_inserter(result), [&](const ValueFlow::Value& v) {
if (v.path < 1)
return false;
if (!isNonConditionalPossibleIntValue(v))
return false;
return true;
});
return result;
});
}
const Token* ValueFlow::parseCompareInt(const Token* tok,
ValueFlow::Value& true_value,
ValueFlow::Value& false_value,
const std::function<std::vector<MathLib::bigint>(const Token*)>& evaluate)
{
const Token* result = nullptr;
parseCompareEachInt(
tok,
[&](const Token* vartok, ValueFlow::Value true_value2, ValueFlow::Value false_value2) {
if (result)
return;
result = vartok;
true_value = std::move(true_value2);
false_value = std::move(false_value2);
},
[&](const Token* t) -> std::vector<ValueFlow::Value> {
std::vector<ValueFlow::Value> r;
std::vector<MathLib::bigint> v = evaluate(t);
std::transform(v.cbegin(), v.cend(), std::back_inserter(r), [&](MathLib::bigint i) {
return ValueFlow::Value{i};
});
return r;
});
return result;
}
const Token *ValueFlow::parseCompareInt(const Token *tok, ValueFlow::Value &true_value, ValueFlow::Value &false_value)
{
return parseCompareInt(tok, true_value, false_value, [](const Token* t) -> std::vector<MathLib::bigint> {
if (t->hasKnownIntValue())
return {t->values().front().intvalue};
return std::vector<MathLib::bigint>{};
});
}
static bool isEscapeScope(const Token* tok, const Settings& settings, bool unknown = false)
{
if (!Token::simpleMatch(tok, "{"))
return false;
// TODO this search for termTok in all subscopes. It should check the end of the scope.
const Token* termTok = Token::findmatch(tok, "return|continue|break|throw|goto", tok->link());
if (termTok && termTok->scope() == tok->scope())
return true;
std::string unknownFunction;
if (settings.library.isScopeNoReturn(tok->link(), &unknownFunction))
return unknownFunction.empty() || unknown;
return false;
}
void ValueFlow::combineValueProperties(const ValueFlow::Value &value1, const ValueFlow::Value &value2, ValueFlow::Value &result)
{
if (value1.isKnown() && value2.isKnown())
result.setKnown();
else if (value1.isImpossible() || value2.isImpossible())
result.setImpossible();
else if (value1.isInconclusive() || value2.isInconclusive())
result.setInconclusive();
else
result.setPossible();
if (value1.tokvalue)
result.tokvalue = value1.tokvalue;
else if (value2.tokvalue)
result.tokvalue = value2.tokvalue;
if (value1.isSymbolicValue()) {
result.valueType = value1.valueType;
result.tokvalue = value1.tokvalue;
}
if (value2.isSymbolicValue()) {
result.valueType = value2.valueType;
result.tokvalue = value2.tokvalue;
}
if (value1.isIteratorValue())
result.valueType = value1.valueType;
if (value2.isIteratorValue())
result.valueType = value2.valueType;
result.condition = value1.condition ? value1.condition : value2.condition;
result.varId = (value1.varId != 0) ? value1.varId : value2.varId;
result.varvalue = (result.varId == value1.varId) ? value1.varvalue : value2.varvalue;
result.errorPath = (value1.errorPath.empty() ? value2 : value1).errorPath;
result.safe = value1.safe || value2.safe;
if (value1.bound == ValueFlow::Value::Bound::Point || value2.bound == ValueFlow::Value::Bound::Point) {
if (value1.bound == ValueFlow::Value::Bound::Upper || value2.bound == ValueFlow::Value::Bound::Upper)
result.bound = ValueFlow::Value::Bound::Upper;
if (value1.bound == ValueFlow::Value::Bound::Lower || value2.bound == ValueFlow::Value::Bound::Lower)
result.bound = ValueFlow::Value::Bound::Lower;
}
if (value1.path != value2.path)
result.path = -1;
else
result.path = value1.path;
}
template<class F>
static size_t accumulateStructMembers(const Scope* scope, F f)
{
size_t total = 0;
std::set<const Scope*> anonScopes;
for (const Variable& var : scope->varlist) {
if (var.isStatic())
continue;
if (const ValueType* vt = var.valueType()) {
if (vt->type == ValueType::Type::RECORD && vt->typeScope == scope)
return 0;
const MathLib::bigint dim = std::accumulate(var.dimensions().cbegin(), var.dimensions().cend(), 1LL, [](MathLib::bigint i1, const Dimension& dim) {
return i1 * dim.num;
});
if (var.nameToken()->scope() != scope && var.nameToken()->scope()->definedType) { // anonymous union
const auto ret = anonScopes.insert(var.nameToken()->scope());
if (ret.second)
total = f(total, *vt, dim);
}
else
total = f(total, *vt, dim);
}
if (total == 0)
return 0;
}
return total;
}
static size_t bitCeil(size_t x)
{
if (x <= 1)
return 1;
--x;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
x |= x >> 32;
return x + 1;
}
static size_t getAlignOf(const ValueType& vt, const Settings& settings, int maxRecursion = 0)
{
if (maxRecursion == settings.vfOptions.maxAlignOfRecursion) {
// TODO: add bailout message
return 0;
}
if (vt.pointer || vt.reference != Reference::None || vt.isPrimitive()) {
auto align = ValueFlow::getSizeOf(vt, settings);
return align == 0 ? 0 : bitCeil(align);
}
if (vt.type == ValueType::Type::RECORD && vt.typeScope) {
auto accHelper = [&](size_t max, const ValueType& vt2, size_t /*dim*/) {
size_t a = getAlignOf(vt2, settings, ++maxRecursion);
return std::max(max, a);
};
size_t total = 0;
if (const Type* dt = vt.typeScope->definedType) {
total = std::accumulate(dt->derivedFrom.begin(), dt->derivedFrom.end(), total, [&](size_t v, const Type::BaseInfo& bi) {
if (bi.type && bi.type->classScope)
v += accumulateStructMembers(bi.type->classScope, accHelper);
return v;
});
}
return total + accumulateStructMembers(vt.typeScope, accHelper);
}
if (vt.type == ValueType::Type::CONTAINER)
return settings.platform.sizeof_pointer; // Just guess
return 0;
}
size_t ValueFlow::getSizeOf(const ValueType &vt, const Settings &settings, int maxRecursion)
{
if (maxRecursion == settings.vfOptions.maxSizeOfRecursion) {
// TODO: add bailout message
return 0;
}
if (vt.pointer || vt.reference != Reference::None)
return settings.platform.sizeof_pointer;
if (vt.type == ValueType::Type::BOOL || vt.type == ValueType::Type::CHAR)
return 1;
if (vt.type == ValueType::Type::SHORT)
return settings.platform.sizeof_short;
if (vt.type == ValueType::Type::WCHAR_T)
return settings.platform.sizeof_wchar_t;
if (vt.type == ValueType::Type::INT)
return settings.platform.sizeof_int;
if (vt.type == ValueType::Type::LONG)
return settings.platform.sizeof_long;
if (vt.type == ValueType::Type::LONGLONG)
return settings.platform.sizeof_long_long;
if (vt.type == ValueType::Type::FLOAT)
return settings.platform.sizeof_float;
if (vt.type == ValueType::Type::DOUBLE)
return settings.platform.sizeof_double;
if (vt.type == ValueType::Type::LONGDOUBLE)
return settings.platform.sizeof_long_double;
if (vt.type == ValueType::Type::CONTAINER)
return 3 * settings.platform.sizeof_pointer; // Just guess
if (vt.type == ValueType::Type::RECORD && vt.typeScope) {
auto accHelper = [&](size_t total, const ValueType& vt2, size_t dim) -> size_t {
size_t n = ValueFlow::getSizeOf(vt2, settings, ++maxRecursion);
size_t a = getAlignOf(vt2, settings);
if (n == 0 || a == 0)
return 0;
n *= dim;
size_t padding = (a - (total % a)) % a;
return vt.typeScope->type == Scope::eUnion ? std::max(total, n) : total + padding + n;
};
size_t total = accumulateStructMembers(vt.typeScope, accHelper);
if (const Type* dt = vt.typeScope->definedType) {
total = std::accumulate(dt->derivedFrom.begin(), dt->derivedFrom.end(), total, [&](size_t v, const Type::BaseInfo& bi) {
if (bi.type && bi.type->classScope)
v += accumulateStructMembers(bi.type->classScope, accHelper);
return v;
});
}
if (total == 0)
return 0;
size_t align = getAlignOf(vt, settings);
if (align == 0)
return 0;
total += (align - (total % align)) % align;
return total;
}
return 0;
}
static void valueFlowNumber(TokenList &tokenlist, const Settings& settings)
{
for (Token *tok = tokenlist.front(); tok;) {
tok = ValueFlow::valueFlowSetConstantValue(tok, settings);
}
if (tokenlist.isCPP() || settings.standards.c >= Standards::C23) {
for (Token *tok = tokenlist.front(); tok; tok = tok->next()) {
if (tok->isName() && !tok->varId() && Token::Match(tok, "false|true")) {
ValueFlow::Value value(tok->str() == "true");
if (!tok->isTemplateArg())
value.setKnown();
setTokenValue(tok, std::move(value), settings);
} else if (Token::Match(tok, "[(,] NULL [,)]")) {
// NULL function parameters are not simplified in the
// normal tokenlist
ValueFlow::Value value(0);
if (!tok->isTemplateArg())
value.setKnown();
setTokenValue(tok->next(), std::move(value), settings);
}
}
}
}
static void valueFlowString(TokenList& tokenlist, const Settings& settings)
{
for (Token* tok = tokenlist.front(); tok; tok = tok->next()) {
if (tok->tokType() == Token::eString) {
ValueFlow::Value strvalue;
strvalue.valueType = ValueFlow::Value::ValueType::TOK;
strvalue.tokvalue = tok;
strvalue.setKnown();
setTokenValue(tok, std::move(strvalue), settings);
}
}
}
static void valueFlowArray(TokenList& tokenlist, const Settings& settings)
{
std::map<nonneg int, const Token*> constantArrays;
for (Token* tok = tokenlist.front(); tok; tok = tok->next()) {
if (tok->varId() > 0) {
// array
const std::map<nonneg int, const Token*>::const_iterator it = constantArrays.find(tok->varId());
if (it != constantArrays.end()) {
ValueFlow::Value value;
value.valueType = ValueFlow::Value::ValueType::TOK;
value.tokvalue = it->second;
value.setKnown();
setTokenValue(tok, std::move(value), settings);
}
// const array decl
else if (tok->variable() && tok->variable()->isArray() && tok->variable()->isConst() &&
tok->variable()->nameToken() == tok && Token::Match(tok, "%var% [ %num%| ] = {")) {
Token* rhstok = tok->linkAt(1)->tokAt(2);
constantArrays[tok->varId()] = rhstok;
tok = rhstok->link();
}
// pointer = array
else if (tok->variable() && tok->variable()->isArray() && Token::simpleMatch(tok->astParent(), "=") &&
astIsRHS(tok) && tok->astParent()->astOperand1() && tok->astParent()->astOperand1()->variable() &&
tok->astParent()->astOperand1()->variable()->isPointer()) {
ValueFlow::Value value;
value.valueType = ValueFlow::Value::ValueType::TOK;
value.tokvalue = tok;
value.setKnown();
setTokenValue(tok, std::move(value), settings);
}
continue;
}
if (Token::Match(tok, "const %type% %var% [ %num%| ] = {")) {
Token* vartok = tok->tokAt(2);
Token* rhstok = vartok->linkAt(1)->tokAt(2);
constantArrays[vartok->varId()] = rhstok;
tok = rhstok->link();
continue;
}
if (Token::Match(tok, "const char %var% [ %num%| ] = %str% ;")) {
Token* vartok = tok->tokAt(2);
Token* strtok = vartok->linkAt(1)->tokAt(2);
constantArrays[vartok->varId()] = strtok;
tok = strtok->next();
continue;
}
}
}
static bool isNonZero(const Token* tok)
{
return tok && (!tok->hasKnownIntValue() || tok->values().front().intvalue != 0);
}
static const Token* getOtherOperand(const Token* tok)
{
if (!tok)
return nullptr;
if (!tok->astParent())
return nullptr;
if (tok->astParent()->astOperand1() != tok)
return tok->astParent()->astOperand1();
if (tok->astParent()->astOperand2() != tok)
return tok->astParent()->astOperand2();
return nullptr;
}
static void valueFlowArrayBool(TokenList& tokenlist, const Settings& settings)
{
for (Token* tok = tokenlist.front(); tok; tok = tok->next()) {
if (tok->hasKnownIntValue())
continue;
const Variable* var = nullptr;
bool known = false;
const std::list<ValueFlow::Value>::const_iterator val =
std::find_if(tok->values().cbegin(), tok->values().cend(), std::mem_fn(&ValueFlow::Value::isTokValue));
if (val == tok->values().end()) {
var = tok->variable();
known = true;
} else {
var = val->tokvalue->variable();
known = val->isKnown();
}
if (!var)
continue;
if (!var->isArray() || var->isArgument() || var->isStlType())
continue;
if (isNonZero(getOtherOperand(tok)) && Token::Match(tok->astParent(), "%comp%"))
continue;
// TODO: Check for function argument
if ((astIsBool(tok->astParent()) && !Token::Match(tok->astParent(), "(|%name%")) ||
(tok->astParent() && Token::Match(tok->astParent()->previous(), "if|while|for ("))) {
ValueFlow::Value value{1};
if (known)
value.setKnown();
setTokenValue(tok, std::move(value), settings);
}
}
}
static void valueFlowArrayElement(TokenList& tokenlist, const Settings& settings)
{
for (Token* tok = tokenlist.front(); tok; tok = tok->next()) {
if (tok->hasKnownIntValue())
continue;
const Token* indexTok = nullptr;
const Token* arrayTok = nullptr;
if (Token::simpleMatch(tok, "[") && tok->isBinaryOp()) {
indexTok = tok->astOperand2();
arrayTok = tok->astOperand1();
} else if (Token::Match(tok->tokAt(-2), ". %name% (") && astIsContainer(tok->tokAt(-2)->astOperand1())) {
arrayTok = tok->tokAt(-2)->astOperand1();
const Library::Container* container = getLibraryContainer(arrayTok);
if (!container || container->stdAssociativeLike)
continue;
const Library::Container::Yield yield = container->getYield(tok->strAt(-1));
if (yield != Library::Container::Yield::AT_INDEX)
continue;
indexTok = tok->astOperand2();
}
if (!indexTok || !arrayTok)
continue;
for (const ValueFlow::Value& arrayValue : arrayTok->values()) {
if (!arrayValue.isTokValue())
continue;
if (arrayValue.isImpossible())
continue;
for (const ValueFlow::Value& indexValue : indexTok->values()) {
if (!indexValue.isIntValue())
continue;
if (indexValue.isImpossible())
continue;
if (!arrayValue.isKnown() && !indexValue.isKnown() && arrayValue.varId != 0 && indexValue.varId != 0 &&
!(arrayValue.varId == indexValue.varId && arrayValue.varvalue == indexValue.varvalue))
continue;
ValueFlow::Value result(0);
result.condition = arrayValue.condition ? arrayValue.condition : indexValue.condition;
result.setInconclusive(arrayValue.isInconclusive() || indexValue.isInconclusive());
result.varId = (arrayValue.varId != 0) ? arrayValue.varId : indexValue.varId;
result.varvalue = (result.varId == arrayValue.varId) ? arrayValue.intvalue : indexValue.intvalue;
if (arrayValue.valueKind == indexValue.valueKind)
result.valueKind = arrayValue.valueKind;
result.errorPath.insert(result.errorPath.end(),
arrayValue.errorPath.cbegin(),
arrayValue.errorPath.cend());
result.errorPath.insert(result.errorPath.end(),
indexValue.errorPath.cbegin(),
indexValue.errorPath.cend());
const MathLib::bigint index = indexValue.intvalue;
if (arrayValue.tokvalue->tokType() == Token::eString) {
const std::string s = arrayValue.tokvalue->strValue();
if (index == s.size()) {
result.intvalue = 0;
setTokenValue(tok, std::move(result), settings);
} else if (index >= 0 && index < s.size()) {
result.intvalue = s[index];
setTokenValue(tok, std::move(result), settings);
}
} else if (Token::simpleMatch(arrayValue.tokvalue, "{")) {
std::vector<const Token*> args = getArguments(arrayValue.tokvalue);
if (index < 0 || index >= args.size())
continue;
const Token* arg = args[index];
if (!arg->hasKnownIntValue())
continue;
const ValueFlow::Value& v = arg->values().front();
result.intvalue = v.intvalue;
result.errorPath.insert(result.errorPath.end(), v.errorPath.cbegin(), v.errorPath.cend());
setTokenValue(tok, std::move(result), settings);
}
}
}
}
}
static void valueFlowPointerAlias(TokenList& tokenlist, const Settings& settings)
{
for (Token* tok = tokenlist.front(); tok; tok = tok->next()) {
// not address of
if (!tok->isUnaryOp("&"))
continue;
// parent should be a '='
if (!Token::simpleMatch(tok->astParent(), "="))
continue;
// child should be some buffer or variable
const Token* vartok = tok->astOperand1();
while (vartok) {
if (vartok->str() == "[")
vartok = vartok->astOperand1();
else if (vartok->str() == "." || vartok->str() == "::")
vartok = vartok->astOperand2();
else
break;
}
if (!(vartok && vartok->variable() && !vartok->variable()->isPointer()))
continue;
ValueFlow::Value value;
value.valueType = ValueFlow::Value::ValueType::TOK;
value.tokvalue = tok;
setTokenValue(tok, std::move(value), settings);
}
}
static void valueFlowBitAnd(TokenList& tokenlist, const Settings& settings)
{
for (Token* tok = tokenlist.front(); tok; tok = tok->next()) {
if (tok->str() != "&")
continue;
if (tok->hasKnownValue())
continue;
if (!tok->astOperand1() || !tok->astOperand2())
continue;
MathLib::bigint number;
if (MathLib::isInt(tok->astOperand1()->str()))
number = MathLib::toBigNumber(tok->astOperand1()->str());
else if (MathLib::isInt(tok->astOperand2()->str()))
number = MathLib::toBigNumber(tok->astOperand2()->str());
else
continue;
int bit = 0;
while (bit <= (MathLib::bigint_bits - 2) && ((((MathLib::bigint)1) << bit) < number))
++bit;
if ((((MathLib::bigint)1) << bit) == number) {
setTokenValue(tok, ValueFlow::Value(0), settings);
setTokenValue(tok, ValueFlow::Value(number), settings);
}
}
}
static void valueFlowSameExpressions(TokenList& tokenlist, const Settings& settings)
{
for (Token* tok = tokenlist.front(); tok; tok = tok->next()) {
if (tok->hasKnownIntValue())
continue;
if (!tok->astOperand1() || !tok->astOperand2())
continue;
if (tok->astOperand1()->isLiteral() || tok->astOperand2()->isLiteral())
continue;
if (!astIsIntegral(tok->astOperand1(), false) && !astIsIntegral(tok->astOperand2(), false))
continue;
long long val;
if (Token::Match(tok, "==|>=|<=|/")) {
val = 1;
}
else if (Token::Match(tok, "!=|>|<|%|-")) {
val = 0;
}
else
continue;
ValueFlow::Value value(val);
value.setKnown();
if (isSameExpression(false, tok->astOperand1(), tok->astOperand2(), settings, true, true, &value.errorPath)) {
setTokenValue(tok, std::move(value), settings);
}
}
}
static bool getExpressionRange(const Token* expr, MathLib::bigint* minvalue, MathLib::bigint* maxvalue)
{
if (expr->hasKnownIntValue()) {
if (minvalue)
*minvalue = expr->values().front().intvalue;
if (maxvalue)
*maxvalue = expr->values().front().intvalue;
return true;
}
if (expr->str() == "&" && expr->astOperand1() && expr->astOperand2()) {
MathLib::bigint vals[4];
const bool lhsHasKnownRange = getExpressionRange(expr->astOperand1(), &vals[0], &vals[1]);
const bool rhsHasKnownRange = getExpressionRange(expr->astOperand2(), &vals[2], &vals[3]);
if (!lhsHasKnownRange && !rhsHasKnownRange)
return false;
if (!lhsHasKnownRange || !rhsHasKnownRange) {
if (minvalue)
*minvalue = lhsHasKnownRange ? vals[0] : vals[2];
if (maxvalue)
*maxvalue = lhsHasKnownRange ? vals[1] : vals[3];
} else {
if (minvalue)
*minvalue = vals[0] & vals[2];
if (maxvalue)
*maxvalue = vals[1] & vals[3];
}
return true;
}
if (expr->str() == "%" && expr->astOperand1() && expr->astOperand2()) {
MathLib::bigint vals[4];
if (!getExpressionRange(expr->astOperand2(), &vals[2], &vals[3]))
return false;
if (vals[2] <= 0)
return false;
const bool lhsHasKnownRange = getExpressionRange(expr->astOperand1(), &vals[0], &vals[1]);
if (lhsHasKnownRange && vals[0] < 0)
return false;
// If lhs has unknown value, it must be unsigned
if (!lhsHasKnownRange &&
(!expr->astOperand1()->valueType() || expr->astOperand1()->valueType()->sign != ValueType::Sign::UNSIGNED))
return false;
if (minvalue)
*minvalue = 0;
if (maxvalue)
*maxvalue = vals[3] - 1;
return true;
}
return false;
}
static void valueFlowRightShift(TokenList& tokenList, const Settings& settings)
{
for (Token* tok = tokenList.front(); tok; tok = tok->next()) {
if (tok->str() != ">>")
continue;
if (tok->hasKnownValue())
continue;
if (!tok->astOperand1() || !tok->astOperand2())
continue;
if (!tok->astOperand2()->hasKnownValue())
continue;
const MathLib::bigint rhsvalue = tok->astOperand2()->values().front().intvalue;
if (rhsvalue < 0)
continue;
if (!tok->astOperand1()->valueType() || !tok->astOperand1()->valueType()->isIntegral())
continue;
if (!tok->astOperand2()->valueType() || !tok->astOperand2()->valueType()->isIntegral())
continue;
MathLib::bigint lhsmax = 0;
if (!getExpressionRange(tok->astOperand1(), nullptr, &lhsmax))
continue;
if (lhsmax < 0)
continue;
int lhsbits;
if ((tok->astOperand1()->valueType()->type == ValueType::Type::CHAR) ||
(tok->astOperand1()->valueType()->type == ValueType::Type::SHORT) ||
(tok->astOperand1()->valueType()->type == ValueType::Type::WCHAR_T) ||
(tok->astOperand1()->valueType()->type == ValueType::Type::BOOL) ||
(tok->astOperand1()->valueType()->type == ValueType::Type::INT))
lhsbits = settings.platform.int_bit;
else if (tok->astOperand1()->valueType()->type == ValueType::Type::LONG)
lhsbits = settings.platform.long_bit;
else if (tok->astOperand1()->valueType()->type == ValueType::Type::LONGLONG)
lhsbits = settings.platform.long_long_bit;
else
continue;
if (rhsvalue >= lhsbits || rhsvalue >= MathLib::bigint_bits || (1ULL << rhsvalue) <= lhsmax)
continue;
ValueFlow::Value val(0);
val.setKnown();
setTokenValue(tok, std::move(val), settings);
}
}
static std::vector<MathLib::bigint> minUnsignedValue(const Token* tok, int depth = 8)
{
std::vector<MathLib::bigint> result;
if (!tok)
return result;
if (depth < 0)
return result;
if (tok->hasKnownIntValue()) {
result = {tok->values().front().intvalue};
} else if (!Token::Match(tok, "-|%|&|^") && tok->isConstOp() && tok->astOperand1() && tok->astOperand2()) {
std::vector<MathLib::bigint> op1 = minUnsignedValue(tok->astOperand1(), depth - 1);
if (!op1.empty()) {
std::vector<MathLib::bigint> op2 = minUnsignedValue(tok->astOperand2(), depth - 1);
if (!op2.empty()) {
result = calculate<std::vector<MathLib::bigint>>(tok->str(), op1.front(), op2.front());
}
}
}
if (result.empty() && astIsUnsigned(tok))
result = {0};
return result;
}
static bool isConvertedToIntegral(const Token* tok, const Settings& settings)
{
if (!tok)
return false;
std::vector<ValueType> parentTypes = getParentValueTypes(tok, settings);
if (parentTypes.empty())
return false;
const ValueType& vt = parentTypes.front();
return vt.type != ValueType::UNKNOWN_INT && vt.isIntegral();
}
static bool isSameToken(const Token* tok1, const Token* tok2)
{
if (!tok1 || !tok2)
return false;
if (tok1->exprId() != 0 && tok1->exprId() == tok2->exprId())
return true;
if (tok1->hasKnownIntValue() && tok2->hasKnownIntValue())
return tok1->values().front().intvalue == tok2->values().front().intvalue;
return false;
}
static void valueFlowImpossibleValues(TokenList& tokenList, const Settings& settings)
{
for (Token* tok = tokenList.front(); tok; tok = tok->next()) {
if (tok->hasKnownIntValue())
continue;
if (Token::Match(tok, "true|false"))
continue;
if (astIsBool(tok) || Token::Match(tok, "%comp%")) {
ValueFlow::Value lower{-1};
lower.bound = ValueFlow::Value::Bound::Upper;
lower.setImpossible();
setTokenValue(tok, std::move(lower), settings);
ValueFlow::Value upper{2};
upper.bound = ValueFlow::Value::Bound::Lower;
upper.setImpossible();
setTokenValue(tok, std::move(upper), settings);
} else if (astIsUnsigned(tok) && !astIsPointer(tok)) {
std::vector<MathLib::bigint> minvalue = minUnsignedValue(tok);
if (minvalue.empty())
continue;
ValueFlow::Value value{std::max<MathLib::bigint>(0, minvalue.front()) - 1};
value.bound = ValueFlow::Value::Bound::Upper;
value.setImpossible();
setTokenValue(tok, std::move(value), settings);
}
if (Token::simpleMatch(tok, "?") && Token::Match(tok->astOperand1(), "<|<=|>|>=")) {
const Token* condTok = tok->astOperand1();
const Token* branchesTok = tok->astOperand2();
auto tokens = makeArray(condTok->astOperand1(), condTok->astOperand2());
auto branches = makeArray(branchesTok->astOperand1(), branchesTok->astOperand2());
bool flipped = false;
if (std::equal(tokens.cbegin(), tokens.cend(), branches.crbegin(), &isSameToken))
flipped = true;
else if (!std::equal(tokens.cbegin(), tokens.cend(), branches.cbegin(), &isSameToken))
continue;
std::vector<ValueFlow::Value> values;
for (const Token* tok2 : tokens) {
if (tok2->hasKnownIntValue()) {
values.emplace_back(tok2->values().front());
} else {
ValueFlow::Value symValue{};
symValue.valueType = ValueFlow::Value::ValueType::SYMBOLIC;
symValue.tokvalue = tok2;
values.push_back(symValue);
std::copy_if(tok2->values().cbegin(),
tok2->values().cend(),
std::back_inserter(values),
[](const ValueFlow::Value& v) {
if (!v.isKnown())
return false;
return v.isSymbolicValue();
});
}
}
const bool isMin = Token::Match(condTok, "<|<=") ^ flipped;
for (ValueFlow::Value& value : values) {
value.setImpossible();
if (isMin) {
value.intvalue++;
value.bound = ValueFlow::Value::Bound::Lower;
} else {
value.intvalue--;
value.bound = ValueFlow::Value::Bound::Upper;
}
setTokenValue(tok, std::move(value), settings);
}
} else if (Token::simpleMatch(tok, "%") && tok->astOperand2() && tok->astOperand2()->hasKnownIntValue()) {
ValueFlow::Value value{tok->astOperand2()->values().front()};
value.bound = ValueFlow::Value::Bound::Lower;
value.setImpossible();
setTokenValue(tok, std::move(value), settings);
} else if (Token::Match(tok, "abs|labs|llabs|fabs|fabsf|fabsl (")) {
ValueFlow::Value value{-1};
value.bound = ValueFlow::Value::Bound::Upper;
value.setImpossible();
setTokenValue(tok->next(), std::move(value), settings);
} else if (Token::Match(tok, ". data|c_str (") && astIsContainerOwned(tok->astOperand1())) {
const Library::Container* container = getLibraryContainer(tok->astOperand1());
if (!container)
continue;
if (!container->stdStringLike)
continue;
if (container->view)
continue;
ValueFlow::Value value{0};
value.setImpossible();
setTokenValue(tok->tokAt(2), std::move(value), settings);
} else if (Token::Match(tok, "make_shared|make_unique <") && Token::simpleMatch(tok->linkAt(1), "> (")) {
ValueFlow::Value value{0};
value.setImpossible();
setTokenValue(tok->linkAt(1)->next(), std::move(value), settings);
} else if ((tokenList.isCPP() && Token::simpleMatch(tok, "this")) || tok->isUnaryOp("&")) {
ValueFlow::Value value{0};
value.setImpossible();
setTokenValue(tok, std::move(value), settings);
} else if (tok->variable() && tok->variable()->isArray() && !tok->variable()->isArgument() &&
!tok->variable()->isStlType()) {
ValueFlow::Value value{0};
value.setImpossible();
setTokenValue(tok, std::move(value), settings);
} else if (tok->isIncompleteVar() && tok->astParent() && tok->astParent()->isUnaryOp("-") &&
isConvertedToIntegral(tok->astParent(), settings)) {
ValueFlow::Value value{0};
value.setImpossible();
setTokenValue(tok, std::move(value), settings);
}
}
}
static void valueFlowEnumValue(SymbolDatabase & symboldatabase, const Settings & settings)
{
for (Scope & scope : symboldatabase.scopeList) {
if (scope.type != Scope::eEnum)
continue;
MathLib::bigint value = 0;
bool prev_enum_is_known = true;
for (Enumerator & enumerator : scope.enumeratorList) {
if (enumerator.start) {
auto* rhs = const_cast<Token*>(enumerator.start->previous()->astOperand2());
ValueFlow::valueFlowConstantFoldAST(rhs, settings);
if (rhs && rhs->hasKnownIntValue()) {
enumerator.value = rhs->values().front().intvalue;
enumerator.value_known = true;
value = enumerator.value + 1;
prev_enum_is_known = true;
} else
prev_enum_is_known = false;
} else if (prev_enum_is_known) {
enumerator.value = value++;
enumerator.value_known = true;
}
}
}
}
static void valueFlowGlobalConstVar(TokenList& tokenList, const Settings& settings)
{
// Get variable values...
std::map<const Variable*, ValueFlow::Value> vars;
for (const Token* tok = tokenList.front(); tok; tok = tok->next()) {
if (!tok->variable())
continue;
// Initialization...
if (tok == tok->variable()->nameToken() && !tok->variable()->isVolatile() && !tok->variable()->isArgument() &&
tok->variable()->isConst() && tok->valueType() && tok->valueType()->isIntegral() &&
tok->valueType()->pointer == 0 && tok->valueType()->constness == 1 && Token::Match(tok, "%name% =") &&
tok->next()->astOperand2() && tok->next()->astOperand2()->hasKnownIntValue()) {
vars[tok->variable()] = tok->next()->astOperand2()->values().front();
}
}
// Set values..
for (Token* tok = tokenList.front(); tok; tok = tok->next()) {
if (!tok->variable())
continue;
const std::map<const Variable*, ValueFlow::Value>::const_iterator var = vars.find(tok->variable());
if (var == vars.end())
continue;
setTokenValue(tok, var->second, settings);
}
}
static void valueFlowGlobalStaticVar(TokenList& tokenList, const Settings& settings)
{
// Get variable values...
std::map<const Variable*, ValueFlow::Value> vars;
for (const Token* tok = tokenList.front(); tok; tok = tok->next()) {
if (!tok->variable())
continue;
// Initialization...
if (tok == tok->variable()->nameToken() && tok->variable()->isStatic() && !tok->variable()->isConst() &&
tok->valueType() && tok->valueType()->isIntegral() && tok->valueType()->pointer == 0 &&
tok->valueType()->constness == 0 && Token::Match(tok, "%name% =") && tok->next()->astOperand2() &&
tok->next()->astOperand2()->hasKnownIntValue()) {
vars[tok->variable()] = tok->next()->astOperand2()->values().front();
} else {
// If variable is written anywhere in TU then remove it from vars
if (!tok->astParent())
continue;
if (Token::Match(tok->astParent(), "++|--|&") && !tok->astParent()->astOperand2())
vars.erase(tok->variable());
else if (tok->astParent()->isAssignmentOp()) {
if (tok == tok->astParent()->astOperand1())
vars.erase(tok->variable());
else if (tok->isCpp() && Token::Match(tok->astParent()->tokAt(-2), "& %name% ="))
vars.erase(tok->variable());
} else if (isLikelyStreamRead(tok->astParent())) {
vars.erase(tok->variable());
} else if (Token::Match(tok->astParent(), "[(,]"))
vars.erase(tok->variable());
}
}
// Set values..
for (Token* tok = tokenList.front(); tok; tok = tok->next()) {
if (!tok->variable())
continue;
const std::map<const Variable*, ValueFlow::Value>::const_iterator var = vars.find(tok->variable());
if (var == vars.end())
continue;
setTokenValue(tok, var->second, settings);
}
}
static Analyzer::Result valueFlowForward(Token* startToken,
const Token* endToken,
const Token* exprTok,
ValueFlow::Value value,
const TokenList& tokenlist,
ErrorLogger& errorLogger,
const Settings& settings,
SourceLocation loc = SourceLocation::current())
{
if (settings.debugnormal)
setSourceLocation(value, loc, startToken);
return valueFlowGenericForward(startToken,
endToken,
makeAnalyzer(exprTok, std::move(value), settings),
tokenlist,
errorLogger,
settings);
}
static Analyzer::Result valueFlowForward(Token* startToken,
const Token* endToken,
const Token* exprTok,
std::list<ValueFlow::Value> values,
const TokenList& tokenlist,
ErrorLogger& errorLogger,
const Settings& settings,
SourceLocation loc = SourceLocation::current())
{
Analyzer::Result result{};
for (ValueFlow::Value& v : values) {
result.update(valueFlowForward(startToken, endToken, exprTok, std::move(v), tokenlist, errorLogger, settings, loc));
}
return result;
}
template<class ValueOrValues>
static Analyzer::Result valueFlowForward(Token* startToken,
const Token* exprTok,
ValueOrValues v,
const TokenList& tokenlist,
ErrorLogger& errorLogger,
const Settings& settings,
SourceLocation loc = SourceLocation::current())
{
const Token* endToken = nullptr;
const Function* f = Scope::nestedInFunction(startToken->scope());
if (f && f->functionScope)
endToken = f->functionScope->bodyEnd;
if (!endToken && exprTok && exprTok->variable() && !exprTok->variable()->isLocal())
endToken = startToken->scope()->bodyEnd;
return valueFlowForward(startToken, endToken, exprTok, std::move(v), tokenlist, errorLogger, settings, loc);
}
static Analyzer::Result valueFlowForwardRecursive(Token* top,
const Token* exprTok,
std::list<ValueFlow::Value> values,
const TokenList& tokenlist,
ErrorLogger& errorLogger,
const Settings& settings,
SourceLocation loc = SourceLocation::current())
{
Analyzer::Result result{};
for (ValueFlow::Value& v : values) {
if (settings.debugnormal)
setSourceLocation(v, loc, top);
result.update(
valueFlowGenericForward(top, makeAnalyzer(exprTok, std::move(v), settings), tokenlist, errorLogger, settings));
}
return result;
}
static void valueFlowReverse(Token* tok,
const Token* const endToken,
const Token* const varToken,
std::list<ValueFlow::Value> values,
const TokenList& tokenlist,
ErrorLogger& errorLogger,
const Settings& settings,
SourceLocation loc = SourceLocation::current())
{
for (ValueFlow::Value& v : values) {
if (settings.debugnormal)
setSourceLocation(v, loc, tok);
valueFlowGenericReverse(tok,
endToken,
makeReverseAnalyzer(varToken, std::move(v), settings),
tokenlist,
errorLogger,
settings);
}
}
// Deprecated
static void valueFlowReverse(const TokenList& tokenlist,
Token* tok,
const Token* const varToken,
ValueFlow::Value val,
ErrorLogger& errorLogger,
const Settings& settings,
SourceLocation loc = SourceLocation::current())
{
valueFlowReverse(tok, nullptr, varToken, {std::move(val)}, tokenlist, errorLogger, settings, loc);
}
static bool isConditionKnown(const Token* tok, bool then)
{
const char* op = "||";
if (then)
op = "&&";
const Token* parent = tok->astParent();
while (parent && (parent->str() == op || parent->str() == "!" || parent->isCast()))
parent = parent->astParent();
const Token* top = tok->astTop();
if (Token::Match(top->previous(), "if|while|for ("))
return parent == top || Token::simpleMatch(parent, ";");
return parent && parent->str() != op;
}
enum class LifetimeCapture : std::uint8_t { Undefined, ByValue, ByReference };
static std::string lifetimeType(const Token *tok, const ValueFlow::Value *val)
{
std::string result;
if (!val)
return "object";
switch (val->lifetimeKind) {
case ValueFlow::Value::LifetimeKind::Lambda:
result = "lambda";
break;
case ValueFlow::Value::LifetimeKind::Iterator:
result = "iterator";
break;
case ValueFlow::Value::LifetimeKind::Object:
case ValueFlow::Value::LifetimeKind::SubObject:
case ValueFlow::Value::LifetimeKind::Address:
if (astIsPointer(tok))
result = "pointer";
else if (Token::simpleMatch(tok, "=") && astIsPointer(tok->astOperand2()))
result = "pointer";
else
result = "object";
break;
}
return result;
}
std::string ValueFlow::lifetimeMessage(const Token *tok, const ValueFlow::Value *val, ErrorPath &errorPath)
{
const Token *tokvalue = val ? val->tokvalue : nullptr;
const Variable *tokvar = tokvalue ? tokvalue->variable() : nullptr;
const Token *vartok = tokvar ? tokvar->nameToken() : nullptr;
const bool classVar = tokvar ? (!tokvar->isLocal() && !tokvar->isArgument() && !tokvar->isGlobal()) : false;
std::string type = lifetimeType(tok, val);
std::string msg = type;
if (vartok) {
if (!classVar)
errorPath.emplace_back(vartok, "Variable created here.");
const Variable * var = vartok->variable();
if (var) {
std::string submessage;
switch (val->lifetimeKind) {
case ValueFlow::Value::LifetimeKind::SubObject:
case ValueFlow::Value::LifetimeKind::Object:
case ValueFlow::Value::LifetimeKind::Address:
if (type == "pointer")
submessage = " to local variable";
else
submessage = " that points to local variable";
break;
case ValueFlow::Value::LifetimeKind::Lambda:
submessage = " that captures local variable";
break;
case ValueFlow::Value::LifetimeKind::Iterator:
submessage = " to local container";
break;
}
if (classVar)
submessage.replace(submessage.find("local"), 5, "member");
msg += submessage + " '" + var->name() + "'";
}
}
return msg;
}
std::vector<ValueFlow::Value> ValueFlow::getLifetimeObjValues(const Token* tok, bool inconclusive, MathLib::bigint path)
{
std::vector<ValueFlow::Value> result;
auto pred = [&](const ValueFlow::Value& v) {
if (!v.isLocalLifetimeValue() && !(path != 0 && v.isSubFunctionLifetimeValue()))
return false;
if (!inconclusive && v.isInconclusive())
return false;
if (!v.tokvalue)
return false;
if (path >= 0 && v.path != 0 && v.path != path)
return false;
return true;
};
std::copy_if(tok->values().cbegin(), tok->values().cend(), std::back_inserter(result), pred);
return result;
}
static bool hasUniqueOwnership(const Token* tok)
{
if (!tok)
return false;
const Variable* var = tok->variable();
if (var && var->isArray() && !var->isArgument())
return true;
if (astIsPointer(tok))
return false;
if (astIsUniqueSmartPointer(tok))
return true;
if (astIsContainerOwned(tok))
return true;
return false;
}
// Check if dereferencing an object that doesn't have unique ownership
static bool derefShared(const Token* tok)
{
if (!tok)
return false;
if (!tok->isUnaryOp("*") && tok->str() != "[" && tok->str() != ".")
return false;
if (tok->str() == "." && tok->originalName() != "->")
return false;
const Token* ptrTok = tok->astOperand1();
return !hasUniqueOwnership(ptrTok);
}
ValueFlow::Value ValueFlow::getLifetimeObjValue(const Token *tok, bool inconclusive)
{
std::vector<ValueFlow::Value> values = ValueFlow::getLifetimeObjValues(tok, inconclusive);
// There should only be one lifetime
if (values.size() != 1)
return ValueFlow::Value{};
return values.front();
}
template<class Predicate>
static std::vector<ValueFlow::LifetimeToken> getLifetimeTokens(const Token* tok,
bool escape,
ErrorPath errorPath,
Predicate pred,
const Settings& settings,
int depth = 20)
{
if (!tok)
return std::vector<ValueFlow::LifetimeToken> {};
if (Token::simpleMatch(tok, "..."))
return std::vector<ValueFlow::LifetimeToken>{};
const Variable *var = tok->variable();
if (pred(tok))
return {{tok, std::move(errorPath)}};
if (depth < 0)
return {{tok, std::move(errorPath)}};
if (var && var->declarationId() == tok->varId()) {
if (var->isReference() || var->isRValueReference()) {
const Token * const varDeclEndToken = var->declEndToken();
if (!varDeclEndToken)
return {{tok, true, std::move(errorPath)}};
if (var->isArgument()) {
errorPath.emplace_back(varDeclEndToken, "Passed to reference.");
return {{tok, true, std::move(errorPath)}};
}
if (Token::Match(varDeclEndToken, "=|{")) {
errorPath.emplace_back(varDeclEndToken, "Assigned to reference.");
const Token *vartok = varDeclEndToken->astOperand2();
const bool temporary = isTemporary(vartok, nullptr, true);
const bool nonlocal = var->isStatic() || var->isGlobal();
if (vartok == tok || (nonlocal && temporary) ||
(!escape && (var->isConst() || var->isRValueReference()) && temporary))
return {{tok, true, std::move(errorPath)}};
if (vartok)
return getLifetimeTokens(vartok, escape, std::move(errorPath), pred, settings, depth - 1);
} else if (Token::simpleMatch(var->nameToken()->astParent(), ":") &&
var->nameToken()->astParent()->astParent() &&
Token::simpleMatch(var->nameToken()->astParent()->astParent()->previous(), "for (")) {
errorPath.emplace_back(var->nameToken(), "Assigned to reference.");
const Token* vartok = var->nameToken();
if (vartok == tok)
return {{tok, true, std::move(errorPath)}};
const Token* contok = var->nameToken()->astParent()->astOperand2();
if (astIsContainer(contok))
return ValueFlow::LifetimeToken::setAddressOf(
getLifetimeTokens(contok, escape, std::move(errorPath), pred, settings, depth - 1),
false);
return std::vector<ValueFlow::LifetimeToken>{};
} else {
return std::vector<ValueFlow::LifetimeToken> {};
}
}
} else if (Token::Match(tok->previous(), "%name% (")) {
const Function *f = tok->previous()->function();
if (f) {
if (!Function::returnsReference(f))
return {{tok, std::move(errorPath)}};
std::vector<ValueFlow::LifetimeToken> result;
std::vector<const Token*> returns = Function::findReturns(f);
for (const Token* returnTok : returns) {
if (returnTok == tok)
continue;
for (ValueFlow::LifetimeToken& lt : getLifetimeTokens(returnTok, escape, errorPath, pred, settings, depth - returns.size())) {
const Token* argvarTok = lt.token;
const Variable* argvar = argvarTok->variable();
if (!argvar)
continue;
const Token* argTok = nullptr;
if (argvar->isArgument() && (argvar->isReference() || argvar->isRValueReference())) {
const int n = getArgumentPos(argvar, f);
if (n < 0)
return std::vector<ValueFlow::LifetimeToken> {};
std::vector<const Token*> args = getArguments(tok->previous());
// TODO: Track lifetimes of default parameters
if (n >= args.size())
return std::vector<ValueFlow::LifetimeToken> {};
argTok = args[n];
lt.errorPath.emplace_back(returnTok, "Return reference.");
lt.errorPath.emplace_back(tok->previous(), "Called function passing '" + argTok->expressionString() + "'.");
} else if (Token::Match(tok->tokAt(-2), ". %name% (") && !derefShared(tok->tokAt(-2)) &&
exprDependsOnThis(argvarTok)) {
argTok = tok->tokAt(-2)->astOperand1();
lt.errorPath.emplace_back(returnTok, "Return reference that depends on 'this'.");
lt.errorPath.emplace_back(tok->previous(),
"Calling member function on '" + argTok->expressionString() + "'.");
}
if (argTok) {
std::vector<ValueFlow::LifetimeToken> arglts = ValueFlow::LifetimeToken::setInconclusive(
getLifetimeTokens(argTok, escape, std::move(lt.errorPath), pred, settings, depth - returns.size()),
returns.size() > 1);
result.insert(result.end(), arglts.cbegin(), arglts.cend());
}
}
}
return result;
}
if (Token::Match(tok->tokAt(-2), ". %name% (") && tok->tokAt(-2)->originalName() != "->" && astIsContainer(tok->tokAt(-2)->astOperand1())) {
const Library::Container* library = getLibraryContainer(tok->tokAt(-2)->astOperand1());
const Library::Container::Yield y = library->getYield(tok->strAt(-1));
if (y == Library::Container::Yield::AT_INDEX || y == Library::Container::Yield::ITEM) {
errorPath.emplace_back(tok->previous(), "Accessing container.");
return ValueFlow::LifetimeToken::setAddressOf(
getLifetimeTokens(tok->tokAt(-2)->astOperand1(), escape, std::move(errorPath), pred, settings, depth - 1),
false);
}
}
} else if (Token::Match(tok, ".|::|[") || tok->isUnaryOp("*")) {
const Token *vartok = tok;
while (vartok) {
if (vartok->str() == "[" || vartok->isUnaryOp("*"))
vartok = vartok->astOperand1();
else if (vartok->str() == ".") {
if (!Token::simpleMatch(vartok->astOperand1(), ".") &&
!(vartok->astOperand2() && vartok->astOperand2()->valueType() && vartok->astOperand2()->valueType()->reference != Reference::None))
vartok = vartok->astOperand1();
else
break;
}
else if (vartok->str() == "::")
vartok = vartok->astOperand2();
else
break;
}
if (!vartok)
return {{tok, std::move(errorPath)}};
if (derefShared(vartok->astParent())) {
for (const ValueFlow::Value &v : vartok->values()) {
if (!v.isLocalLifetimeValue())
continue;
if (v.tokvalue == tok)
continue;
errorPath.insert(errorPath.end(), v.errorPath.cbegin(), v.errorPath.cend());
return ValueFlow::LifetimeToken::setAddressOf(
getLifetimeTokens(v.tokvalue, escape, std::move(errorPath), pred, settings, depth - 1),
false);
}
} else {
return ValueFlow::LifetimeToken::setAddressOf(getLifetimeTokens(vartok, escape, std::move(errorPath), pred, settings, depth - 1),
!(astIsContainer(vartok) && Token::simpleMatch(vartok->astParent(), "[")));
}
} else if (Token::simpleMatch(tok, "{") && getArgumentStart(tok) &&
!Token::simpleMatch(getArgumentStart(tok), ",") && getArgumentStart(tok)->valueType()) {
const Token* vartok = getArgumentStart(tok);
auto vts = getParentValueTypes(tok, settings);
auto it = std::find_if(vts.cbegin(), vts.cend(), [&](const ValueType& vt) {
return vt.isTypeEqual(vartok->valueType());
});
if (it != vts.end())
return getLifetimeTokens(vartok, escape, std::move(errorPath), pred, settings, depth - 1);
}
return {{tok, std::move(errorPath)}};
}
std::vector<ValueFlow::LifetimeToken> ValueFlow::getLifetimeTokens(const Token* tok, const Settings& settings, bool escape, ErrorPath errorPath)
{
return getLifetimeTokens(tok, escape, std::move(errorPath), [](const Token*) {
return false;
}, settings);
}
bool ValueFlow::hasLifetimeToken(const Token* tok, const Token* lifetime, const Settings& settings)
{
bool result = false;
getLifetimeTokens(tok, false, ErrorPath{}, [&](const Token* tok2) {
result = tok2->exprId() == lifetime->exprId();
return result;
}, settings);
return result;
}
static const Token* getLifetimeToken(const Token* tok, ErrorPath& errorPath, const Settings& settings, bool* addressOf = nullptr)
{
std::vector<ValueFlow::LifetimeToken> lts = ValueFlow::getLifetimeTokens(tok, settings);
if (lts.size() != 1)
return nullptr;
if (lts.front().inconclusive)
return nullptr;
if (addressOf)
*addressOf = lts.front().addressOf;
errorPath.insert(errorPath.end(), lts.front().errorPath.cbegin(), lts.front().errorPath.cend());
return lts.front().token;
}
const Variable* ValueFlow::getLifetimeVariable(const Token* tok, ErrorPath& errorPath, const Settings& settings, bool* addressOf)
{
const Token* tok2 = getLifetimeToken(tok, errorPath, settings, addressOf);
if (tok2 && tok2->variable())
return tok2->variable();
return nullptr;
}
const Variable* ValueFlow::getLifetimeVariable(const Token* tok, const Settings& settings)
{
ErrorPath errorPath;
return getLifetimeVariable(tok, errorPath, settings, nullptr);
}
static bool isNotLifetimeValue(const ValueFlow::Value& val)
{
return !val.isLifetimeValue();
}
static bool isLifetimeOwned(const ValueType* vtParent)
{
if (vtParent->container)
return !vtParent->container->view;
return vtParent->type == ValueType::CONTAINER;
}
static bool isLifetimeOwned(const ValueType *vt, const ValueType *vtParent)
{
if (!vtParent)
return false;
if (isLifetimeOwned(vtParent))
return true;
if (!vt)
return false;
// If converted from iterator to pointer then the iterator is most likely a pointer
if (vtParent->pointer == 1 && vt->pointer == 0 && vt->type == ValueType::ITERATOR)
return false;
if (vt->type != ValueType::UNKNOWN_TYPE && vtParent->type != ValueType::UNKNOWN_TYPE) {
if (vt->pointer != vtParent->pointer)
return true;
if (vt->type != vtParent->type) {
if (vtParent->type == ValueType::RECORD)
return true;
if (isLifetimeOwned(vtParent))
return true;
}
}
return false;
}
static bool isLifetimeBorrowed(const ValueType *vt, const ValueType *vtParent)
{
if (!vtParent)
return false;
if (!vt)
return false;
if (vt->pointer > 0 && vt->pointer == vtParent->pointer)
return true;
if (vtParent->container && vtParent->container->view)
return true;
if (vt->type != ValueType::UNKNOWN_TYPE && vtParent->type != ValueType::UNKNOWN_TYPE && vtParent->container == vt->container) {
if (vtParent->pointer > vt->pointer)
return true;
if (vtParent->pointer < vt->pointer && vtParent->isIntegral())
return true;
if (vtParent->str() == vt->str())
return true;
}
return false;
}
static const Token* skipCVRefs(const Token* tok, const Token* endTok)
{
while (tok != endTok && Token::Match(tok, "const|volatile|auto|&|&&"))
tok = tok->next();
return tok;
}
static bool isNotEqual(std::pair<const Token*, const Token*> x, std::pair<const Token*, const Token*> y)
{
const Token* start1 = x.first;
const Token* start2 = y.first;
if (start1 == nullptr || start2 == nullptr)
return false;
while (start1 != x.second && start2 != y.second) {
const Token* tok1 = skipCVRefs(start1, x.second);
if (tok1 != start1) {
start1 = tok1;
continue;
}
const Token* tok2 = skipCVRefs(start2, y.second);
if (tok2 != start2) {
start2 = tok2;
continue;
}
if (start1->str() != start2->str())
return true;
start1 = start1->next();
start2 = start2->next();
}
start1 = skipCVRefs(start1, x.second);
start2 = skipCVRefs(start2, y.second);
return !(start1 == x.second && start2 == y.second);
}
static bool isNotEqual(std::pair<const Token*, const Token*> x, const std::string& y, bool cpp)
{
TokenList tokenList(nullptr);
std::istringstream istr(y);
tokenList.createTokens(istr, cpp ? Standards::Language::CPP : Standards::Language::C); // TODO: check result?
return isNotEqual(x, std::make_pair(tokenList.front(), tokenList.back()));
}
static bool isNotEqual(std::pair<const Token*, const Token*> x, const ValueType* y, bool cpp)
{
if (y == nullptr)
return false;
if (y->originalTypeName.empty())
return false;
return isNotEqual(x, y->originalTypeName, cpp);
}
static bool isDifferentType(const Token* src, const Token* dst)
{
const Type* t = Token::typeOf(src);
const Type* parentT = Token::typeOf(dst);
if (t && parentT) {
if (t->classDef && parentT->classDef && t->classDef != parentT->classDef)
return true;
} else {
std::pair<const Token*, const Token*> decl = Token::typeDecl(src);
std::pair<const Token*, const Token*> parentdecl = Token::typeDecl(dst);
if (isNotEqual(decl, parentdecl))
return true;
if (isNotEqual(decl, dst->valueType(), dst->isCpp()))
return true;
if (isNotEqual(parentdecl, src->valueType(), src->isCpp()))
return true;
}
return false;
}
bool ValueFlow::isLifetimeBorrowed(const Token *tok, const Settings &settings)
{
if (!tok)
return true;
if (tok->str() == ",")
return true;
if (!tok->astParent())
return true;
const Token* parent = nullptr;
const ValueType* vt = tok->valueType();
std::vector<ValueType> vtParents = getParentValueTypes(tok, settings, &parent);
for (const ValueType& vtParent : vtParents) {
if (isLifetimeBorrowed(vt, &vtParent))
return true;
if (isLifetimeOwned(vt, &vtParent))
return false;
}
if (parent) {
if (isDifferentType(tok, parent))
return false;
}
return true;
}
static void valueFlowLifetimeFunction(Token *tok, const TokenList &tokenlist, ErrorLogger &errorLogger, const Settings &settings);
static void valueFlowLifetimeConstructor(Token *tok,
const TokenList &tokenlist,
ErrorLogger &errorLogger,
const Settings &settings);
static bool isRangeForScope(const Scope* scope)
{
if (!scope)
return false;
if (scope->type != Scope::eFor)
return false;
if (!scope->bodyStart)
return false;
if (!Token::simpleMatch(scope->bodyStart->previous(), ") {"))
return false;
return Token::simpleMatch(scope->bodyStart->linkAt(-1)->astOperand2(), ":");
}
static const Token* getEndOfVarScope(const Variable* var)
{
if (!var)
return nullptr;
const Scope* innerScope = var->scope();
const Scope* outerScope = innerScope;
if (var->typeStartToken() && var->typeStartToken()->scope())
outerScope = var->typeStartToken()->scope();
if (!innerScope && outerScope)
innerScope = outerScope;
if (!innerScope || !outerScope)
return nullptr;
if (!innerScope->isExecutable())
return nullptr;
// If the variable is defined in a for/while initializer then we want to
// pick one token after the end so forward analysis can analyze the exit
// conditions
if (innerScope != outerScope && outerScope->isExecutable() && innerScope->isLoopScope() &&
!isRangeForScope(innerScope))
return innerScope->bodyEnd->next();
return innerScope->bodyEnd;
}
const Token* ValueFlow::getEndOfExprScope(const Token* tok, const Scope* defaultScope, bool smallest)
{
const Token* end = nullptr;
bool local = false;
visitAstNodes(tok, [&](const Token* child) {
if (const Variable* var = child->variable()) {
local |= var->isLocal();
if (var->isLocal() || var->isArgument()) {
const Token* varEnd = getEndOfVarScope(var);
if (!end || (smallest ? precedes(varEnd, end) : succeeds(varEnd, end)))
end = varEnd;
const Token* top = var->nameToken()->astTop();
if (Token::simpleMatch(top->tokAt(-1), "if (")) { // variable declared in if (...)
const Token* elseTok = top->link()->linkAt(1);
if (Token::simpleMatch(elseTok, "} else {") && tok->scope()->isNestedIn(elseTok->tokAt(2)->scope()))
end = tok->scope()->bodyEnd;
}
}
}
return ChildrenToVisit::op1_and_op2;
});
if (!end && defaultScope)
end = defaultScope->bodyEnd;
if (!end) {
const Scope* scope = tok->scope();
if (scope)
end = scope->bodyEnd;
// If there is no local variables then pick the function scope
if (!local) {
while (scope && scope->isLocal())
scope = scope->nestedIn;
if (scope && scope->isExecutable())
end = scope->bodyEnd;
}
}
return end;
}
static void valueFlowForwardLifetime(Token * tok, const TokenList &tokenlist, ErrorLogger &errorLogger, const Settings &settings)
{
// Forward lifetimes to constructed variable
if (Token::Match(tok->previous(), "%var% {|(") && isVariableDecl(tok->previous())) {
std::list<ValueFlow::Value> values = tok->values();
values.remove_if(&isNotLifetimeValue);
valueFlowForward(nextAfterAstRightmostLeaf(tok), ValueFlow::getEndOfExprScope(tok), tok->previous(), std::move(values), tokenlist, errorLogger, settings);
return;
}
Token *parent = tok->astParent();
while (parent && parent->str() == ",")
parent = parent->astParent();
if (!parent)
return;
// Assignment
if (parent->str() == "=" && (!parent->astParent() || Token::simpleMatch(parent->astParent(), ";"))) {
// Rhs values..
if (!parent->astOperand2() || parent->astOperand2()->values().empty())
return;
if (!ValueFlow::isLifetimeBorrowed(parent->astOperand2(), settings))
return;
const Token* expr = getLHSVariableToken(parent);
if (!expr)
return;
if (expr->exprId() == 0)
return;
const Token* endOfVarScope = ValueFlow::getEndOfExprScope(expr);
// Only forward lifetime values
std::list<ValueFlow::Value> values = parent->astOperand2()->values();
values.remove_if(&isNotLifetimeValue);
// Dont forward lifetimes that overlap
values.remove_if([&](const ValueFlow::Value& value) {
return findAstNode(value.tokvalue, [&](const Token* child) {
return child->exprId() == expr->exprId();
});
});
// Skip RHS
Token* nextExpression = nextAfterAstRightmostLeaf(parent);
if (expr->exprId() > 0) {
valueFlowForward(nextExpression, endOfVarScope->next(), expr, values, tokenlist, errorLogger, settings);
for (ValueFlow::Value& val : values) {
if (val.lifetimeKind == ValueFlow::Value::LifetimeKind::Address)
val.lifetimeKind = ValueFlow::Value::LifetimeKind::SubObject;
}
// TODO: handle `[`
if (Token::simpleMatch(parent->astOperand1(), ".")) {
const Token* parentLifetime =
getParentLifetime(parent->astOperand1()->astOperand2(), settings.library);
if (parentLifetime && parentLifetime->exprId() > 0) {
valueFlowForward(nextExpression, endOfVarScope, parentLifetime, std::move(values), tokenlist, errorLogger, settings);
}
}
}
// Constructor
} else if (Token::simpleMatch(parent, "{") && !isScopeBracket(parent)) {
valueFlowLifetimeConstructor(parent, tokenlist, errorLogger, settings);
valueFlowForwardLifetime(parent, tokenlist, errorLogger, settings);
// Function call
} else if (Token::Match(parent->previous(), "%name% (")) {
valueFlowLifetimeFunction(parent->previous(), tokenlist, errorLogger, settings);
valueFlowForwardLifetime(parent, tokenlist, errorLogger, settings);
// Variable
} else if (tok->variable() && tok->variable()->scope()) {
const Variable *var = tok->variable();
const Token *endOfVarScope = var->scope()->bodyEnd;
std::list<ValueFlow::Value> values = tok->values();
Token *nextExpression = nextAfterAstRightmostLeaf(parent);
// Only forward lifetime values
values.remove_if(&isNotLifetimeValue);
valueFlowForward(nextExpression, endOfVarScope, tok, std::move(values), tokenlist, errorLogger, settings);
// Cast
} else if (parent->isCast()) {
std::list<ValueFlow::Value> values = tok->values();
// Only forward lifetime values
values.remove_if(&isNotLifetimeValue);
for (ValueFlow::Value& value:values)
setTokenValue(parent, std::move(value), settings);
valueFlowForwardLifetime(parent, tokenlist, errorLogger, settings);
}
}
struct LifetimeStore {
const Token* argtok{};
std::string message;
ValueFlow::Value::LifetimeKind type = ValueFlow::Value::LifetimeKind::Object;
ErrorPath errorPath;
bool inconclusive{};
bool forward = true;
LifetimeStore() = default;
LifetimeStore(const Token* argtok,
std::string message,
ValueFlow::Value::LifetimeKind type = ValueFlow::Value::LifetimeKind::Object,
bool inconclusive = false)
: argtok(argtok),
message(std::move(message)),
type(type),
inconclusive(inconclusive)
{}
template<class F>
static void forEach(const TokenList& tokenlist,
ErrorLogger& errorLogger,
const Settings& settings,
const std::vector<const Token*>& argtoks,
const std::string& message,
ValueFlow::Value::LifetimeKind type,
F f) {
std::set<Token*> forwardToks;
for (const Token* arg : argtoks) {
LifetimeStore ls{arg, message, type};
ls.forward = false;
f(ls);
if (ls.forwardTok)
forwardToks.emplace(ls.forwardTok);
}
for (auto* tok : forwardToks) {
valueFlowForwardLifetime(tok, tokenlist, errorLogger, settings);
}
}
static LifetimeStore fromFunctionArg(const Function * f, const Token *tok, const Variable *var, const TokenList &tokenlist, const Settings& settings, ErrorLogger &errorLogger) {
if (!var)
return LifetimeStore{};
if (!var->isArgument())
return LifetimeStore{};
const int n = getArgumentPos(var, f);
if (n < 0)
return LifetimeStore{};
std::vector<const Token *> args = getArguments(tok);
if (n >= args.size()) {
if (settings.debugwarnings)
bailout(tokenlist,
errorLogger,
tok,
"Argument mismatch: Function '" + tok->str() + "' returning lifetime from argument index " +
std::to_string(n) + " but only " + std::to_string(args.size()) +
" arguments are available.");
return LifetimeStore{};
}
const Token *argtok2 = args[n];
return LifetimeStore{argtok2, "Passed to '" + tok->expressionString() + "'.", ValueFlow::Value::LifetimeKind::Object};
}
template<class Predicate>
bool byRef(Token* tok,
const TokenList& tokenlist,
ErrorLogger& errorLogger,
const Settings& settings,
const Predicate& pred,
SourceLocation loc = SourceLocation::current())
{
if (!argtok)
return false;
bool update = false;
for (const ValueFlow::LifetimeToken& lt : ValueFlow::getLifetimeTokens(argtok, settings)) {
if (!settings.certainty.isEnabled(Certainty::inconclusive) && lt.inconclusive)
continue;
if (!lt.token)
return false;
if (!pred(lt.token))
return false;
ErrorPath er = errorPath;
er.insert(er.end(), lt.errorPath.cbegin(), lt.errorPath.cend());
er.emplace_back(argtok, message);
ValueFlow::Value value;
value.valueType = ValueFlow::Value::ValueType::LIFETIME;
value.lifetimeScope = ValueFlow::Value::LifetimeScope::Local;
value.tokvalue = lt.token;
value.errorPath = std::move(er);
value.lifetimeKind = type;
value.setInconclusive(lt.inconclusive || inconclusive);
// Don't add the value a second time
if (std::find(tok->values().cbegin(), tok->values().cend(), value) != tok->values().cend())
return false;
if (settings.debugnormal)
setSourceLocation(value, loc, tok);
setTokenValue(tok, std::move(value), settings);
update = true;
}
if (update && forward)
forwardLifetime(tok, tokenlist, errorLogger, settings);
return update;
}
bool byRef(Token* tok,
const TokenList& tokenlist,
ErrorLogger& errorLogger,
const Settings& settings,
SourceLocation loc = SourceLocation::current())
{
return byRef(
tok,
tokenlist,
errorLogger,
settings,
[](const Token*) {
return true;
},
loc);
}
template<class Predicate>
bool byVal(Token* tok,
const TokenList& tokenlist,
ErrorLogger& errorLogger,
const Settings& settings,
const Predicate& pred,
SourceLocation loc = SourceLocation::current())
{
if (!argtok)
return false;
bool update = false;
if (argtok->values().empty()) {
ErrorPath er;
er.emplace_back(argtok, message);
for (const ValueFlow::LifetimeToken& lt : ValueFlow::getLifetimeTokens(argtok, settings)) {
if (!settings.certainty.isEnabled(Certainty::inconclusive) && lt.inconclusive)
continue;
ValueFlow::Value value;
value.valueType = ValueFlow::Value::ValueType::LIFETIME;
value.tokvalue = lt.token;
value.capturetok = argtok;
value.errorPath = er;
value.lifetimeKind = type;
value.setInconclusive(inconclusive || lt.inconclusive);
const Variable* var = lt.token->variable();
if (var && var->isArgument()) {
value.lifetimeScope = ValueFlow::Value::LifetimeScope::Argument;
} else {
continue;
}
// Don't add the value a second time
if (std::find(tok->values().cbegin(), tok->values().cend(), value) != tok->values().cend())
continue;
if (settings.debugnormal)
setSourceLocation(value, loc, tok);
setTokenValue(tok, std::move(value), settings);
update = true;
}
}
for (const ValueFlow::Value &v : argtok->values()) {
if (!v.isLifetimeValue())
continue;
const Token *tok3 = v.tokvalue;
for (const ValueFlow::LifetimeToken& lt : ValueFlow::getLifetimeTokens(tok3, settings)) {
if (!settings.certainty.isEnabled(Certainty::inconclusive) && lt.inconclusive)
continue;
ErrorPath er = v.errorPath;
er.insert(er.end(), lt.errorPath.cbegin(), lt.errorPath.cend());
if (!lt.token)
return false;
if (!pred(lt.token))
return false;
er.emplace_back(argtok, message);
er.insert(er.end(), errorPath.cbegin(), errorPath.cend());
ValueFlow::Value value;
value.valueType = ValueFlow::Value::ValueType::LIFETIME;
value.lifetimeScope = v.lifetimeScope;
value.path = v.path;
value.tokvalue = lt.token;
value.capturetok = argtok;
value.errorPath = std::move(er);
value.lifetimeKind = type;
value.setInconclusive(lt.inconclusive || v.isInconclusive() || inconclusive);
// Don't add the value a second time
if (std::find(tok->values().cbegin(), tok->values().cend(), value) != tok->values().cend())
continue;
if (settings.debugnormal)
setSourceLocation(value, loc, tok);
setTokenValue(tok, std::move(value), settings);
update = true;
}
}
if (update && forward)
forwardLifetime(tok, tokenlist, errorLogger, settings);
return update;
}
bool byVal(Token* tok,
const TokenList& tokenlist,
ErrorLogger& errorLogger,
const Settings& settings,
SourceLocation loc = SourceLocation::current())
{
return byVal(
tok,
tokenlist,
errorLogger,
settings,
[](const Token*) {
return true;
},
loc);
}
template<class Predicate>
bool byDerefCopy(Token* tok,
const TokenList& tokenlist,
ErrorLogger& errorLogger,
const Settings& settings,
Predicate pred,
SourceLocation loc = SourceLocation::current()) const
{
bool update = false;
if (!settings.certainty.isEnabled(Certainty::inconclusive) && inconclusive)
return update;
if (!argtok)
return update;
if (!tok)
return update;
for (const ValueFlow::Value &v : argtok->values()) {
if (!v.isLifetimeValue())
continue;
const Token *tok2 = v.tokvalue;
ErrorPath er = v.errorPath;
const Variable *var = ValueFlow::getLifetimeVariable(tok2, er, settings);
// TODO: the inserted data is never used
er.insert(er.end(), errorPath.cbegin(), errorPath.cend());
if (!var)
continue;
const Token * const varDeclEndToken = var->declEndToken();
for (const Token *tok3 = tok; tok3 && tok3 != varDeclEndToken; tok3 = tok3->previous()) {
if (tok3->varId() == var->declarationId()) {
update |= LifetimeStore{tok3, message, type, inconclusive}
.byVal(tok, tokenlist, errorLogger, settings, pred, loc);
break;
}
}
}
return update;
}
bool byDerefCopy(Token* tok,
const TokenList& tokenlist,
ErrorLogger& errorLogger,
const Settings& settings,
SourceLocation loc = SourceLocation::current()) const
{
return byDerefCopy(
tok,
tokenlist,
errorLogger,
settings,
[](const Token*) {
return true;
},
loc);
}
private:
// cppcheck-suppress naming-privateMemberVariable
Token* forwardTok{};
void forwardLifetime(Token* tok, const TokenList& tokenlist, ErrorLogger& errorLogger, const Settings& settings) {
forwardTok = tok;
valueFlowForwardLifetime(tok, tokenlist, errorLogger, settings);
}
};
static bool hasBorrowingVariables(const std::list<Variable>& vars, const std::vector<const Token*>& args, int depth = 10)
{
if (depth < 0)
return true;
return std::any_of(vars.cbegin(), vars.cend(), [&](const Variable& var) {
if (const ValueType* vt = var.valueType()) {
if (vt->pointer > 0 &&
std::none_of(args.begin(), args.end(), [vt](const Token* arg) {
return arg->valueType() && arg->valueType()->type == vt->type;
}))
return false;
if (vt->pointer > 0)
return true;
if (vt->reference != Reference::None)
return true;
if (vt->isPrimitive())
return false;
if (vt->isEnum())
return false;
// TODO: Check container inner type
if (vt->type == ValueType::CONTAINER && vt->container)
return vt->container->view;
if (vt->typeScope)
return hasBorrowingVariables(vt->typeScope->varlist, args, depth - 1);
}
return true;
});
}
static void valueFlowLifetimeUserConstructor(Token* tok,
const Function* constructor,
const std::string& name,
const std::vector<const Token*>& args,
const TokenList& tokenlist,
ErrorLogger& errorLogger,
const Settings& settings)
{
if (!constructor)
return;
std::unordered_map<const Token*, const Variable*> argToParam;
for (std::size_t i = 0; i < args.size(); i++)
argToParam[args[i]] = constructor->getArgumentVar(i);
if (const Token* initList = constructor->constructorMemberInitialization()) {
std::unordered_map<const Variable*, LifetimeCapture> paramCapture;
for (const Token* tok2 : astFlatten(initList->astOperand2(), ",")) {
if (!Token::simpleMatch(tok2, "("))
continue;
if (!tok2->astOperand1())
continue;
if (!tok2->astOperand2())
continue;
const Variable* var = tok2->astOperand1()->variable();
const Token* expr = tok2->astOperand2();
if (!var)
continue;
if (!ValueFlow::isLifetimeBorrowed(expr, settings))
continue;
const Variable* argvar = ValueFlow::getLifetimeVariable(expr, settings);
if (var->isReference() || var->isRValueReference()) {
if (argvar && argvar->isArgument() && (argvar->isReference() || argvar->isRValueReference())) {
paramCapture[argvar] = LifetimeCapture::ByReference;
}
} else {
bool found = false;
for (const ValueFlow::Value& v : expr->values()) {
if (!v.isLifetimeValue())
continue;
if (v.path > 0)
continue;
if (!v.tokvalue)
continue;
const Variable* lifeVar = v.tokvalue->variable();
if (!lifeVar)
continue;
LifetimeCapture c = LifetimeCapture::Undefined;
if (!v.isArgumentLifetimeValue() && (lifeVar->isReference() || lifeVar->isRValueReference()))
c = LifetimeCapture::ByReference;
else if (v.isArgumentLifetimeValue())
c = LifetimeCapture::ByValue;
if (c != LifetimeCapture::Undefined) {
paramCapture[lifeVar] = c;
found = true;
}
}
if (!found && argvar && argvar->isArgument())
paramCapture[argvar] = LifetimeCapture::ByValue;
}
}
// TODO: Use SubExpressionAnalyzer for members
LifetimeStore::forEach(tokenlist,
errorLogger,
settings,
args,
"Passed to constructor of '" + name + "'.",
ValueFlow::Value::LifetimeKind::SubObject,
[&](LifetimeStore& ls) {
const Variable* paramVar = argToParam.at(ls.argtok);
if (paramCapture.count(paramVar) == 0)
return;
const LifetimeCapture c = paramCapture.at(paramVar);
if (c == LifetimeCapture::ByReference)
ls.byRef(tok, tokenlist, errorLogger, settings);
else
ls.byVal(tok, tokenlist, errorLogger, settings);
});
} else if (hasBorrowingVariables(constructor->nestedIn->varlist, args)) {
LifetimeStore::forEach(tokenlist,
errorLogger,
settings,
args,
"Passed to constructor of '" + name + "'.",
ValueFlow::Value::LifetimeKind::SubObject,
[&](LifetimeStore& ls) {
ls.inconclusive = true;
const Variable* var = argToParam.at(ls.argtok);
if (var && !var->isConst() && var->isReference())
ls.byRef(tok, tokenlist, errorLogger, settings);
else
ls.byVal(tok, tokenlist, errorLogger, settings);
});
}
}
static void valueFlowLifetimeFunction(Token *tok, const TokenList &tokenlist, ErrorLogger &errorLogger, const Settings &settings)
{
if (!Token::Match(tok, "%name% ("))
return;
Token* memtok = nullptr;
if (Token::Match(tok->astParent(), ". %name% (") && astIsRHS(tok))
memtok = tok->astParent()->astOperand1();
const int returnContainer = settings.library.returnValueContainer(tok);
if (returnContainer >= 0) {
std::vector<const Token *> args = getArguments(tok);
for (int argnr = 1; argnr <= args.size(); ++argnr) {
const Library::ArgumentChecks::IteratorInfo *i = settings.library.getArgIteratorInfo(tok, argnr);
if (!i)
continue;
if (i->container != returnContainer)
continue;
const Token * const argTok = args[argnr - 1];
bool forward = false;
for (ValueFlow::Value val : argTok->values()) {
if (!val.isLifetimeValue())
continue;
val.errorPath.emplace_back(argTok, "Passed to '" + tok->str() + "'.");
setTokenValue(tok->next(), std::move(val), settings);
forward = true;
}
// Check if lifetime is available to avoid adding the lifetime twice
if (forward) {
valueFlowForwardLifetime(tok, tokenlist, errorLogger, settings);
break;
}
}
} else if (Token::Match(tok->tokAt(-2), "std :: ref|cref|tie|front_inserter|back_inserter")) {
for (const Token *argtok : getArguments(tok)) {
LifetimeStore{argtok, "Passed to '" + tok->str() + "'.", ValueFlow::Value::LifetimeKind::Object}.byRef(
tok->next(), tokenlist, errorLogger, settings);
}
} else if (Token::Match(tok->tokAt(-2), "std :: make_tuple|tuple_cat|make_pair|make_reverse_iterator|next|prev|move|bind")) {
for (const Token *argtok : getArguments(tok)) {
LifetimeStore{argtok, "Passed to '" + tok->str() + "'.", ValueFlow::Value::LifetimeKind::Object}.byVal(
tok->next(), tokenlist, errorLogger, settings);
}
} else if (memtok && Token::Match(tok->astParent(), ". push_back|push_front|insert|push|assign") &&
astIsNonStringContainer(memtok)) {
std::vector<const Token *> args = getArguments(tok);
const std::size_t n = args.size();
if (n > 1 && Token::typeStr(args[n - 2]) == Token::typeStr(args[n - 1]) &&
(((astIsIterator(args[n - 2]) && astIsIterator(args[n - 1])) ||
(astIsPointer(args[n - 2]) && astIsPointer(args[n - 1]))))) {
LifetimeStore{
args.back(), "Added to container '" + memtok->str() + "'.", ValueFlow::Value::LifetimeKind::Object}
.byDerefCopy(memtok, tokenlist, errorLogger, settings);
} else if (!args.empty() && ValueFlow::isLifetimeBorrowed(args.back(), settings)) {
LifetimeStore{
args.back(), "Added to container '" + memtok->str() + "'.", ValueFlow::Value::LifetimeKind::Object}
.byVal(memtok, tokenlist, errorLogger, settings);
}
} else if (tok->function()) {
const Function *f = tok->function();
if (f->isConstructor()) {
valueFlowLifetimeUserConstructor(tok->next(), f, tok->str(), getArguments(tok), tokenlist, errorLogger, settings);
return;
}
if (Function::returnsReference(f))
return;
std::vector<const Token*> returns = Function::findReturns(f);
const bool inconclusive = returns.size() > 1;
bool update = false;
for (const Token* returnTok : returns) {
if (returnTok == tok)
continue;
const Variable *returnVar = ValueFlow::getLifetimeVariable(returnTok, settings);
if (returnVar && returnVar->isArgument() && (returnVar->isConst() || !isVariableChanged(returnVar, settings))) {
LifetimeStore ls = LifetimeStore::fromFunctionArg(f, tok, returnVar, tokenlist, settings, errorLogger);
ls.inconclusive = inconclusive;
ls.forward = false;
update |= ls.byVal(tok->next(), tokenlist, errorLogger, settings);
}
for (const ValueFlow::Value &v : returnTok->values()) {
if (!v.isLifetimeValue())
continue;
if (!v.tokvalue)
continue;
if (memtok &&
(contains({ValueFlow::Value::LifetimeScope::ThisPointer, ValueFlow::Value::LifetimeScope::ThisValue},
v.lifetimeScope) ||
exprDependsOnThis(v.tokvalue))) {
LifetimeStore ls = LifetimeStore{memtok,
"Passed to member function '" + tok->expressionString() + "'.",
ValueFlow::Value::LifetimeKind::Object};
ls.inconclusive = inconclusive;
ls.forward = false;
ls.errorPath = v.errorPath;
ls.errorPath.emplace_front(returnTok, "Return " + lifetimeType(returnTok, &v) + ".");
int thisIndirect = v.lifetimeScope == ValueFlow::Value::LifetimeScope::ThisValue ? 0 : 1;
if (derefShared(memtok->astParent()))
thisIndirect--;
if (thisIndirect == -1)
update |= ls.byDerefCopy(tok->next(), tokenlist, errorLogger, settings);
else if (thisIndirect == 0)
update |= ls.byVal(tok->next(), tokenlist, errorLogger, settings);
else if (thisIndirect == 1)
update |= ls.byRef(tok->next(), tokenlist, errorLogger, settings);
continue;
}
const Variable *var = v.tokvalue->variable();
LifetimeStore ls = LifetimeStore::fromFunctionArg(f, tok, var, tokenlist, settings, errorLogger);
if (!ls.argtok)
continue;
ls.forward = false;
ls.inconclusive = inconclusive;
ls.errorPath = v.errorPath;
ls.errorPath.emplace_front(returnTok, "Return " + lifetimeType(returnTok, &v) + ".");
if (!v.isArgumentLifetimeValue() && (var->isReference() || var->isRValueReference())) {
update |= ls.byRef(tok->next(), tokenlist, errorLogger, settings);
} else if (v.isArgumentLifetimeValue()) {
update |= ls.byVal(tok->next(), tokenlist, errorLogger, settings);
}
}
}
if (update)
valueFlowForwardLifetime(tok->next(), tokenlist, errorLogger, settings);
} else if (tok->valueType()) {
// TODO: Propagate lifetimes with library functions
if (settings.library.getFunction(tok->previous()))
return;
if (Token::simpleMatch(tok->astParent(), "."))
return;
// Assume constructing the valueType
valueFlowLifetimeConstructor(tok->next(), tokenlist, errorLogger, settings);
valueFlowForwardLifetime(tok->next(), tokenlist, errorLogger, settings);
} else {
const std::string& retVal = settings.library.returnValue(tok);
if (startsWith(retVal, "arg")) {
std::size_t iArg{};
try {
iArg = strToInt<std::size_t>(retVal.substr(3));
} catch (...) {
return;
}
std::vector<const Token*> args = getArguments(tok);
if (iArg > 0 && iArg <= args.size()) {
const Token* varTok = args[iArg - 1];
if (varTok->variable() && varTok->variable()->isLocal())
LifetimeStore{ varTok, "Passed to '" + tok->str() + "'.", ValueFlow::Value::LifetimeKind::Address }.byRef(
tok->next(), tokenlist, errorLogger, settings);
}
}
}
}
static bool isScope(const Token* tok)
{
if (!tok)
return false;
if (!Token::simpleMatch(tok, "{"))
return false;
const Scope* scope = tok->scope();
if (!scope)
return false;
if (!scope->bodyStart)
return false;
return scope->bodyStart == tok;
}
static const Function* findConstructor(const Scope* scope, const Token* tok, const std::vector<const Token*>& args)
{
if (!tok)
return nullptr;
const Function* f = tok->function();
if (!f && tok->astOperand1())
f = tok->astOperand1()->function();
// Search for a constructor
if (!f || !f->isConstructor()) {
f = nullptr;
std::vector<const Function*> candidates;
for (const Function& function : scope->functionList) {
if (function.minArgCount() > args.size())
continue;
if (!function.isConstructor())
continue;
candidates.push_back(&function);
}
// TODO: Narrow the candidates
if (candidates.size() == 1)
f = candidates.front();
}
if (!f)
return nullptr;
return f;
}
static void valueFlowLifetimeClassConstructor(Token* tok,
const Type* t,
const TokenList& tokenlist,
ErrorLogger& errorLogger,
const Settings& settings)
{
if (!Token::Match(tok, "(|{"))
return;
if (isScope(tok))
return;
if (!t) {
if (tok->valueType() && tok->valueType()->type != ValueType::RECORD)
return;
if (tok->str() != "{" && !Token::Match(tok->previous(), "%var% (") && !isVariableDecl(tok->previous()))
return;
// If the type is unknown then assume it captures by value in the
// constructor, but make each lifetime inconclusive
std::vector<const Token*> args = getArguments(tok);
LifetimeStore::forEach(tokenlist,
errorLogger,
settings,
args,
"Passed to initializer list.",
ValueFlow::Value::LifetimeKind::SubObject,
[&](LifetimeStore& ls) {
ls.inconclusive = true;
ls.byVal(tok, tokenlist, errorLogger, settings);
});
return;
}
const Scope* scope = t->classScope;
if (!scope)
return;
// Aggregate constructor
if (t->derivedFrom.empty() && (t->isClassType() || t->isStructType())) {
std::vector<const Token*> args = getArguments(tok);
if (scope->numConstructors == 0) {
auto it = scope->varlist.cbegin();
LifetimeStore::forEach(
tokenlist,
errorLogger,
settings,
args,
"Passed to constructor of '" + t->name() + "'.",
ValueFlow::Value::LifetimeKind::SubObject,
[&](LifetimeStore& ls) {
// Skip static variable
it = std::find_if(it, scope->varlist.cend(), [](const Variable& var) {
return !var.isStatic();
});
if (it == scope->varlist.cend())
return;
const Variable& var = *it;
if (var.isReference() || var.isRValueReference()) {
ls.byRef(tok, tokenlist, errorLogger, settings);
} else if (ValueFlow::isLifetimeBorrowed(ls.argtok, settings)) {
ls.byVal(tok, tokenlist, errorLogger, settings);
}
it++;
});
} else {
const Function* constructor = findConstructor(scope, tok, args);
valueFlowLifetimeUserConstructor(tok, constructor, t->name(), args, tokenlist, errorLogger, settings);
}
}
}
static void valueFlowLifetimeConstructor(Token* tok, const TokenList& tokenlist, ErrorLogger& errorLogger, const Settings& settings)
{
if (!Token::Match(tok, "(|{"))
return;
if (isScope(tok))
return;
std::vector<ValueType> vts;
if (tok->valueType()) {
vts = {*tok->valueType()};
} else if (Token::Match(tok->previous(), "%var% {|(") && isVariableDecl(tok->previous()) &&
tok->previous()->valueType()) {
vts = {*tok->previous()->valueType()};
} else if (Token::simpleMatch(tok, "{") && !Token::Match(tok->previous(), "%name%")) {
vts = getParentValueTypes(tok, settings);
}
for (const ValueType& vt : vts) {
if (vt.pointer > 0) {
std::vector<const Token*> args = getArguments(tok);
LifetimeStore::forEach(tokenlist,
errorLogger,
settings,
args,
"Passed to initializer list.",
ValueFlow::Value::LifetimeKind::SubObject,
[&](LifetimeStore& ls) {
ls.byVal(tok, tokenlist, errorLogger, settings);
});
} else if (vt.container && vt.type == ValueType::CONTAINER) {
std::vector<const Token*> args = getArguments(tok);
if (args.size() == 1 && vt.container->view && astIsContainerOwned(args.front())) {
LifetimeStore{args.front(), "Passed to container view.", ValueFlow::Value::LifetimeKind::SubObject}
.byRef(tok, tokenlist, errorLogger, settings);
} else if (args.size() == 2 && (astIsIterator(args[0]) || astIsIterator(args[1]))) {
LifetimeStore::forEach(
tokenlist,
errorLogger,
settings,
args,
"Passed to initializer list.",
ValueFlow::Value::LifetimeKind::SubObject,
[&](const LifetimeStore& ls) {
ls.byDerefCopy(tok, tokenlist, errorLogger, settings);
});
} else if (vt.container->hasInitializerListConstructor) {
LifetimeStore::forEach(tokenlist,
errorLogger,
settings,
args,
"Passed to initializer list.",
ValueFlow::Value::LifetimeKind::SubObject,
[&](LifetimeStore& ls) {
ls.byVal(tok, tokenlist, errorLogger, settings);
});
}
} else {
const Type* t = nullptr;
if (vt.typeScope && vt.typeScope->definedType)
t = vt.typeScope->definedType;
else
t = Token::typeOf(tok->previous());
valueFlowLifetimeClassConstructor(tok, t, tokenlist, errorLogger, settings);
}
}
}
struct Lambda {
explicit Lambda(const Token* tok)
{
if (!Token::simpleMatch(tok, "[") || !tok->link())
return;
capture = tok;
if (Token::simpleMatch(capture->link(), "] (")) {
arguments = capture->link()->next();
}
const Token * afterArguments = arguments ? arguments->link()->next() : capture->link()->next();
if (afterArguments && afterArguments->originalName() == "->") {
returnTok = afterArguments->next();
bodyTok = Token::findsimplematch(returnTok, "{");
} else if (Token::simpleMatch(afterArguments, "{")) {
bodyTok = afterArguments;
}
for (const Token* c:getCaptures()) {
if (Token::Match(c, "this !!.")) {
explicitCaptures[c->variable()] = std::make_pair(c, LifetimeCapture::ByReference);
} else if (Token::simpleMatch(c, "* this")) {
explicitCaptures[c->next()->variable()] = std::make_pair(c->next(), LifetimeCapture::ByValue);
} else if (c->variable()) {
explicitCaptures[c->variable()] = std::make_pair(c, LifetimeCapture::ByValue);
} else if (c->isUnaryOp("&") && Token::Match(c->astOperand1(), "%var%")) {
explicitCaptures[c->astOperand1()->variable()] =
std::make_pair(c->astOperand1(), LifetimeCapture::ByReference);
} else {
const std::string& s = c->expressionString();
if (s == "=")
implicitCapture = LifetimeCapture::ByValue;
else if (s == "&")
implicitCapture = LifetimeCapture::ByReference;
}
}
}
const Token* capture{};
const Token* arguments{};
const Token* returnTok{};
const Token* bodyTok{};
std::unordered_map<const Variable*, std::pair<const Token*, LifetimeCapture>> explicitCaptures;
LifetimeCapture implicitCapture = LifetimeCapture::Undefined;
std::vector<const Token*> getCaptures() const {
return getArguments(capture);
}
bool isLambda() const {
return capture && bodyTok;
}
};
static bool isDecayedPointer(const Token *tok)
{
if (!tok)
return false;
if (!tok->astParent())
return false;
if (astIsPointer(tok->astParent()) && !Token::simpleMatch(tok->astParent(), "return"))
return true;
if (tok->astParent()->isConstOp())
return true;
if (!Token::simpleMatch(tok->astParent(), "return"))
return false;
return astIsPointer(tok->astParent()) || astIsContainerView(tok->astParent());
}
static bool isConvertedToView(const Token* tok, const Settings& settings)
{
std::vector<ValueType> vtParents = getParentValueTypes(tok, settings);
return std::any_of(vtParents.cbegin(), vtParents.cend(), [&](const ValueType& vt) {
if (!vt.container)
return false;
return vt.container->view;
});
}
static bool isContainerOfPointers(const Token* tok, const Settings& settings)
{
if (!tok)
{
return true;
}
ValueType vt = ValueType::parseDecl(tok, settings);
return vt.pointer > 0;
}
static void valueFlowLifetime(TokenList &tokenlist, ErrorLogger &errorLogger, const Settings &settings)
{
for (Token *tok = tokenlist.front(); tok; tok = tok->next()) {
if (!tok->scope())
continue;
if (tok->scope()->type == Scope::eGlobal)
continue;
Lambda lam(tok);
// Lambdas
if (lam.isLambda()) {
const Scope * bodyScope = lam.bodyTok->scope();
std::set<const Scope *> scopes;
// Avoid capturing a variable twice
std::set<nonneg int> varids;
bool capturedThis = false;
auto isImplicitCapturingVariable = [&](const Token *varTok) {
const Variable *var = varTok->variable();
if (!var)
return false;
if (varids.count(var->declarationId()) > 0)
return false;
if (!var->isLocal() && !var->isArgument())
return false;
const Scope *scope = var->scope();
if (!scope)
return false;
if (scopes.count(scope) > 0)
return false;
if (scope->isNestedIn(bodyScope))
return false;
scopes.insert(scope);
varids.insert(var->declarationId());
return true;
};
bool update = false;
auto captureVariable = [&](const Token* tok2, LifetimeCapture c, const std::function<bool(const Token*)> &pred) {
if (varids.count(tok->varId()) > 0)
return;
if (c == LifetimeCapture::ByReference) {
LifetimeStore ls{
tok2, "Lambda captures variable by reference here.", ValueFlow::Value::LifetimeKind::Lambda};
ls.forward = false;
update |= ls.byRef(tok, tokenlist, errorLogger, settings, pred);
} else if (c == LifetimeCapture::ByValue) {
LifetimeStore ls{
tok2, "Lambda captures variable by value here.", ValueFlow::Value::LifetimeKind::Lambda};
ls.forward = false;
update |= ls.byVal(tok, tokenlist, errorLogger, settings, pred);
pred(tok2);
}
};
auto captureThisVariable = [&](const Token* tok2, LifetimeCapture c) {
ValueFlow::Value value;
value.valueType = ValueFlow::Value::ValueType::LIFETIME;
if (c == LifetimeCapture::ByReference)
value.lifetimeScope = ValueFlow::Value::LifetimeScope::ThisPointer;
else if (c == LifetimeCapture::ByValue)
value.lifetimeScope = ValueFlow::Value::LifetimeScope::ThisValue;
value.tokvalue = tok2;
value.errorPath.emplace_back(tok2, "Lambda captures the 'this' variable here.");
value.lifetimeKind = ValueFlow::Value::LifetimeKind::Lambda;
capturedThis = true;
// Don't add the value a second time
if (std::find(tok->values().cbegin(), tok->values().cend(), value) != tok->values().cend())
return;
setTokenValue(tok, std::move(value), settings);
update |= true;
};
// Handle explicit capture
for (const auto& p:lam.explicitCaptures) {
const Variable* var = p.first;
const Token* tok2 = p.second.first;
const LifetimeCapture c = p.second.second;
if (Token::Match(tok2, "this !!.")) {
captureThisVariable(tok2, c);
} else if (var) {
captureVariable(tok2, c, [](const Token*) {
return true;
});
varids.insert(var->declarationId());
}
}
auto isImplicitCapturingThis = [&](const Token* tok2) {
if (capturedThis)
return false;
if (Token::simpleMatch(tok2, "this"))
return true;
if (tok2->variable()) {
if (Token::simpleMatch(tok2->previous(), "."))
return false;
const Variable* var = tok2->variable();
if (var->isLocal())
return false;
if (var->isArgument())
return false;
return exprDependsOnThis(tok2);
}
if (Token::simpleMatch(tok2, "("))
return exprDependsOnThis(tok2);
return false;
};
for (const Token * tok2 = lam.bodyTok; tok2 != lam.bodyTok->link(); tok2 = tok2->next()) {
if (isImplicitCapturingThis(tok2)) {
captureThisVariable(tok2, LifetimeCapture::ByReference);
} else if (tok2->variable()) {
captureVariable(tok2, lam.implicitCapture, isImplicitCapturingVariable);
}
}
if (update)
valueFlowForwardLifetime(tok, tokenlist, errorLogger, settings);
}
// address of
else if (tok->isUnaryOp("&")) {
if (Token::simpleMatch(tok->astParent(), "*"))
continue;
for (const ValueFlow::LifetimeToken& lt : ValueFlow::getLifetimeTokens(tok->astOperand1(), settings)) {
if (!settings.certainty.isEnabled(Certainty::inconclusive) && lt.inconclusive)
continue;
ErrorPath errorPath = lt.errorPath;
errorPath.emplace_back(tok, "Address of variable taken here.");
ValueFlow::Value value;
value.valueType = ValueFlow::Value::ValueType::LIFETIME;
value.lifetimeScope = ValueFlow::Value::LifetimeScope::Local;
value.tokvalue = lt.token;
value.errorPath = std::move(errorPath);
if (lt.addressOf || astIsPointer(lt.token) || !Token::Match(lt.token->astParent(), ".|["))
value.lifetimeKind = ValueFlow::Value::LifetimeKind::Address;
value.setInconclusive(lt.inconclusive);
setTokenValue(tok, std::move(value), settings);
valueFlowForwardLifetime(tok, tokenlist, errorLogger, settings);
}
}
// Converting to container view
else if (astIsContainerOwned(tok) && isConvertedToView(tok, settings)) {
LifetimeStore ls =
LifetimeStore{tok, "Converted to container view", ValueFlow::Value::LifetimeKind::SubObject};
ls.byRef(tok, tokenlist, errorLogger, settings);
valueFlowForwardLifetime(tok, tokenlist, errorLogger, settings);
}
// container lifetimes
else if (astIsContainer(tok)) {
Token * parent = astParentSkipParens(tok);
if (!parent)
continue;
if (!Token::Match(parent, ". %name% (") && !Token::Match(parent->previous(), "%name% ("))
continue;
// Skip if its a free function that doesnt yield an iterator to the container
if (Token::Match(parent->previous(), "%name% (") &&
!contains({Library::Container::Yield::START_ITERATOR, Library::Container::Yield::END_ITERATOR},
astFunctionYield(parent->previous(), settings)))
continue;
ValueFlow::Value master;
master.valueType = ValueFlow::Value::ValueType::LIFETIME;
master.lifetimeScope = ValueFlow::Value::LifetimeScope::Local;
if (astIsIterator(parent->tokAt(2))) {
master.errorPath.emplace_back(parent->tokAt(2), "Iterator to container is created here.");
master.lifetimeKind = ValueFlow::Value::LifetimeKind::Iterator;
} else if (astIsIterator(parent) && Token::Match(parent->previous(), "%name% (") &&
contains({Library::Container::Yield::START_ITERATOR, Library::Container::Yield::END_ITERATOR},
astFunctionYield(parent->previous(), settings))) {
master.errorPath.emplace_back(parent, "Iterator to container is created here.");
master.lifetimeKind = ValueFlow::Value::LifetimeKind::Iterator;
} else if ((astIsPointer(parent->tokAt(2)) &&
!isContainerOfPointers(tok->valueType()->containerTypeToken, settings)) ||
Token::Match(parent->next(), "data|c_str")) {
master.errorPath.emplace_back(parent->tokAt(2), "Pointer to container is created here.");
master.lifetimeKind = ValueFlow::Value::LifetimeKind::Object;
} else {
continue;
}
std::vector<const Token*> toks;
if (tok->isUnaryOp("*") || parent->originalName() == "->") {
for (const ValueFlow::Value& v : tok->values()) {
if (!v.isLocalLifetimeValue())
continue;
if (v.lifetimeKind != ValueFlow::Value::LifetimeKind::Address)
continue;
if (!v.tokvalue)
continue;
toks.push_back(v.tokvalue);
}
} else if (astIsContainerView(tok)) {
for (const ValueFlow::Value& v : tok->values()) {
if (!v.isLocalLifetimeValue())
continue;
if (!v.tokvalue)
continue;
if (!astIsContainerOwned(v.tokvalue))
continue;
toks.push_back(v.tokvalue);
}
} else {
toks = {tok};
}
for (const Token* tok2 : toks) {
for (const ReferenceToken& rt : followAllReferences(tok2, false)) {
ValueFlow::Value value = master;
value.tokvalue = rt.token;
value.errorPath.insert(value.errorPath.begin(), rt.errors.cbegin(), rt.errors.cend());
if (Token::simpleMatch(parent, "("))
setTokenValue(parent, std::move(value), settings);
else
setTokenValue(parent->tokAt(2), std::move(value), settings);
if (!rt.token->variable()) {
LifetimeStore ls = LifetimeStore{
rt.token, master.errorPath.back().second, ValueFlow::Value::LifetimeKind::Object};
ls.byRef(parent->tokAt(2), tokenlist, errorLogger, settings);
}
}
}
valueFlowForwardLifetime(parent->tokAt(2), tokenlist, errorLogger, settings);
}
// Check constructors
else if (Token::Match(tok, "=|return|%name%|{|,|> {") && !isScope(tok->next())) {
valueFlowLifetimeConstructor(tok->next(), tokenlist, errorLogger, settings);
}
// Check function calls
else if (Token::Match(tok, "%name% (") && !Token::simpleMatch(tok->linkAt(1), ") {")) {
valueFlowLifetimeFunction(tok, tokenlist, errorLogger, settings);
}
// Unique pointer lifetimes
else if (astIsUniqueSmartPointer(tok) && astIsLHS(tok) && Token::simpleMatch(tok->astParent(), ". get ( )")) {
Token* ptok = tok->astParent()->tokAt(2);
ErrorPath errorPath = {{ptok, "Raw pointer to smart pointer created here."}};
ValueFlow::Value value;
value.valueType = ValueFlow::Value::ValueType::LIFETIME;
value.lifetimeScope = ValueFlow::Value::LifetimeScope::Local;
value.lifetimeKind = ValueFlow::Value::LifetimeKind::SubObject;
value.tokvalue = tok;
value.errorPath = std::move(errorPath);
setTokenValue(ptok, std::move(value), settings);
valueFlowForwardLifetime(ptok, tokenlist, errorLogger, settings);
}
// Check variables
else if (tok->variable()) {
ErrorPath errorPath;
const Variable * var = ValueFlow::getLifetimeVariable(tok, errorPath, settings);
if (!var)
continue;
if (var->nameToken() == tok)
continue;
if (var->isArray() && !var->isStlType() && !var->isArgument() && isDecayedPointer(tok)) {
errorPath.emplace_back(tok, "Array decayed to pointer here.");
ValueFlow::Value value;
value.valueType = ValueFlow::Value::ValueType::LIFETIME;
value.lifetimeScope = ValueFlow::Value::LifetimeScope::Local;
value.tokvalue = var->nameToken();
value.errorPath = std::move(errorPath);
setTokenValue(tok, std::move(value), settings);
valueFlowForwardLifetime(tok, tokenlist, errorLogger, settings);
}
}
// Forward any lifetimes
else if (std::any_of(tok->values().cbegin(), tok->values().cend(), std::mem_fn(&ValueFlow::Value::isLifetimeValue))) {
valueFlowForwardLifetime(tok, tokenlist, errorLogger, settings);
}
}
}
static bool isStdMoveOrStdForwarded(Token * tok, ValueFlow::Value::MoveKind * moveKind, Token ** varTok = nullptr)
{
if (tok->str() != "std")
return false;
ValueFlow::Value::MoveKind kind = ValueFlow::Value::MoveKind::NonMovedVariable;
Token * variableToken = nullptr;
if (Token::Match(tok, "std :: move ( %var% )")) {
variableToken = tok->tokAt(4);
kind = ValueFlow::Value::MoveKind::MovedVariable;
} else if (Token::simpleMatch(tok, "std :: forward <")) {
Token * const leftAngle = tok->tokAt(3);
Token * rightAngle = leftAngle->link();
if (Token::Match(rightAngle, "> ( %var% )")) {
variableToken = rightAngle->tokAt(2);
kind = ValueFlow::Value::MoveKind::ForwardedVariable;
}
}
if (!variableToken)
return false;
if (variableToken->strAt(2) == ".") // Only partially moved
return false;
if (variableToken->valueType() && variableToken->valueType()->type >= ValueType::Type::VOID)
return false;
if (moveKind != nullptr)
*moveKind = kind;
if (varTok != nullptr)
*varTok = variableToken;
return true;
}
static bool isOpenParenthesisMemberFunctionCallOfVarId(const Token * openParenthesisToken, nonneg int varId)
{
const Token * varTok = openParenthesisToken->tokAt(-3);
return Token::Match(varTok, "%varid% . %name% (", varId) &&
varTok->next()->originalName().empty();
}
static Token* findOpenParentesisOfMove(Token* moveVarTok)
{
Token* tok = moveVarTok;
while (tok && tok->str() != "(")
tok = tok->previous();
return tok;
}
static Token* findEndOfFunctionCallForParameter(Token* parameterToken)
{
if (!parameterToken)
return nullptr;
Token* parent = parameterToken->astParent();
while (parent && !parent->isOp() && !Token::Match(parent, "[({]"))
parent = parent->astParent();
if (!parent)
return nullptr;
return nextAfterAstRightmostLeaf(parent);
}
static void valueFlowAfterMove(const TokenList& tokenlist, const SymbolDatabase& symboldatabase, ErrorLogger& errorLogger, const Settings& settings)
{
if (!tokenlist.isCPP() || settings.standards.cpp < Standards::CPP11)
return;
for (const Scope * scope : symboldatabase.functionScopes) {
if (!scope)
continue;
const Token * start = scope->bodyStart;
if (scope->function) {
const Token * memberInitializationTok = scope->function->constructorMemberInitialization();
if (memberInitializationTok)
start = memberInitializationTok;
}
for (auto* tok = const_cast<Token*>(start); tok != scope->bodyEnd; tok = tok->next()) {
Token * varTok;
if (Token::Match(tok, "%var% . reset|clear (") && tok->next()->originalName().empty()) {
varTok = tok;
const Variable *var = tok->variable();
if (!var || (!var->isLocal() && !var->isArgument()))
continue;
ValueFlow::Value value;
value.valueType = ValueFlow::Value::ValueType::MOVED;
value.moveKind = ValueFlow::Value::MoveKind::NonMovedVariable;
value.errorPath.emplace_back(tok, "Calling " + tok->next()->expressionString() + " makes " + tok->str() + " 'non-moved'");
value.setKnown();
setTokenValue(tok, value, settings);
if (var->scope()) {
const Token* const endOfVarScope = var->scope()->bodyEnd;
valueFlowForward(tok->next(), endOfVarScope, tok, std::move(value), tokenlist, errorLogger, settings);
}
continue;
}
ValueFlow::Value::MoveKind moveKind;
if (!isStdMoveOrStdForwarded(tok, &moveKind, &varTok))
continue;
const nonneg int varId = varTok->varId();
// x is not MOVED after assignment if code is: x = ... std::move(x) .. ;
const Token *parent = tok->astParent();
while (parent && parent->str() != "=" && parent->str() != "return" &&
!(parent->str() == "(" && isOpenParenthesisMemberFunctionCallOfVarId(parent, varId)))
parent = parent->astParent();
if (parent &&
(parent->str() == "return" || // MOVED in return statement
parent->str() == "(")) // MOVED in self assignment, isOpenParenthesisMemberFunctionCallOfVarId == true
continue;
if (parent && parent->astOperand1() && parent->astOperand1()->varId() == varId)
continue;
const Token* const endOfVarScope = ValueFlow::getEndOfExprScope(varTok);
Token* openParentesisOfMove = findOpenParentesisOfMove(varTok);
Token* endOfFunctionCall = findEndOfFunctionCallForParameter(openParentesisOfMove);
if (endOfFunctionCall) {
if (endOfFunctionCall->str() == ")") {
Token* ternaryColon = endOfFunctionCall->link()->astParent();
while (Token::simpleMatch(ternaryColon, "("))
ternaryColon = ternaryColon->astParent();
if (Token::simpleMatch(ternaryColon, ":")) {
endOfFunctionCall = ternaryColon->astOperand2();
if (Token::simpleMatch(endOfFunctionCall, "("))
endOfFunctionCall = endOfFunctionCall->link();
}
}
ValueFlow::Value value;
value.valueType = ValueFlow::Value::ValueType::MOVED;
value.moveKind = moveKind;
if (moveKind == ValueFlow::Value::MoveKind::MovedVariable)
value.errorPath.emplace_back(tok, "Calling std::move(" + varTok->str() + ")");
else // if (moveKind == ValueFlow::Value::ForwardedVariable)
value.errorPath.emplace_back(tok, "Calling std::forward(" + varTok->str() + ")");
value.setKnown();
valueFlowForward(endOfFunctionCall, endOfVarScope, varTok, std::move(value), tokenlist, errorLogger, settings);
}
}
}
}
static const Token* findIncompleteVar(const Token* start, const Token* end)
{
for (const Token* tok = start; tok != end; tok = tok->next()) {
if (tok->isIncompleteVar())
return tok;
}
return nullptr;
}
static ValueFlow::Value makeConditionValue(long long val,
const Token* condTok,
bool assume,
bool impossible,
const Settings& settings,
SourceLocation loc = SourceLocation::current())
{
ValueFlow::Value v(val);
v.setKnown();
if (impossible) {
v.intvalue = !v.intvalue;
v.setImpossible();
}
v.condition = condTok;
if (assume)
v.errorPath.emplace_back(condTok, "Assuming condition '" + condTok->expressionString() + "' is true");
else
v.errorPath.emplace_back(condTok, "Assuming condition '" + condTok->expressionString() + "' is false");
if (settings.debugnormal)
setSourceLocation(v, loc, condTok);
return v;
}
static std::vector<const Token*> getConditions(const Token* tok, const char* op)
{
std::vector<const Token*> conds = {tok};
if (tok->str() == op) {
std::vector<const Token*> args = astFlatten(tok, op);
std::copy_if(args.cbegin(), args.cend(), std::back_inserter(conds), [&](const Token* tok2) {
if (tok2->exprId() == 0)
return false;
if (tok2->hasKnownIntValue())
return false;
if (Token::Match(tok2, "%var%|.") && !astIsBool(tok2))
return false;
return true;
});
}
return conds;
}
static bool isBreakOrContinueScope(const Token* endToken)
{
if (!Token::simpleMatch(endToken, "}"))
return false;
return Token::Match(endToken->tokAt(-2), "break|continue ;");
}
static const Scope* getLoopScope(const Token* tok)
{
if (!tok)
return nullptr;
const Scope* scope = tok->scope();
while (scope && scope->type != Scope::eWhile && scope->type != Scope::eFor && scope->type != Scope::eDo)
scope = scope->nestedIn;
return scope;
}
//
static void valueFlowConditionExpressions(const TokenList& tokenlist,
const SymbolDatabase& symboldatabase,
ErrorLogger& errorLogger,
const Settings& settings)
{
if (!settings.daca && !settings.vfOptions.doConditionExpressionAnalysis) {
if (settings.debugwarnings) {
ErrorMessage::FileLocation loc(tokenlist.getSourceFilePath(), 0, 0);
const ErrorMessage errmsg(
{std::move(loc)},
tokenlist.getSourceFilePath(),
Severity::debug,
"Analysis of condition expressions is disabled. Use --check-level=exhaustive to enable it.",
"normalCheckLevelConditionExpressions",
Certainty::normal);
errorLogger.reportErr(errmsg);
}
return;
}
for (const Scope* scope : symboldatabase.functionScopes) {
if (const Token* incompleteTok = findIncompleteVar(scope->bodyStart, scope->bodyEnd)) {
if (settings.debugwarnings)
bailoutIncompleteVar(tokenlist,
errorLogger,
incompleteTok,
"Skipping function due to incomplete variable " + incompleteTok->str());
continue;
}
if (settings.daca && !settings.vfOptions.doConditionExpressionAnalysis)
continue;
for (auto* tok = const_cast<Token*>(scope->bodyStart); tok != scope->bodyEnd; tok = tok->next()) {
if (!Token::simpleMatch(tok, "if ("))
continue;
Token* parenTok = tok->next();
if (!Token::simpleMatch(parenTok->link(), ") {"))
continue;
const Token* condTok = parenTok->astOperand2();
if (condTok->exprId() == 0)
continue;
if (condTok->hasKnownIntValue())
continue;
if (!isConstExpression(condTok, settings.library))
continue;
const bool isOp = condTok->isComparisonOp() || condTok->tokType() == Token::eLogicalOp;
const bool is1 = isOp || astIsBool(condTok);
Token* blockTok = parenTok->link()->tokAt(1);
Token* startTok = blockTok;
// Inner condition
{
for (const Token* condTok2 : getConditions(condTok, "&&")) {
if (is1) {
const bool isBool = astIsBool(condTok2) || Token::Match(condTok2, "%comp%|%oror%|&&");
auto a1 = makeSameExpressionAnalyzer(
condTok2,
makeConditionValue(1, condTok2, /*assume*/ true, !isBool, settings),
settings); // don't set '1' for non-boolean expressions
valueFlowGenericForward(startTok, startTok->link(), a1, tokenlist, errorLogger, settings);
}
auto a2 = makeOppositeExpressionAnalyzer(true,
condTok2,
makeConditionValue(0, condTok2, true, false, settings),
settings);
valueFlowGenericForward(startTok, startTok->link(), a2, tokenlist, errorLogger, settings);
}
}
std::vector<const Token*> conds = getConditions(condTok, "||");
if (conds.empty())
continue;
// Check else block
if (Token::simpleMatch(startTok->link(), "} else {")) {
startTok = startTok->link()->tokAt(2);
for (const Token* condTok2 : conds) {
auto a1 = makeSameExpressionAnalyzer(condTok2,
makeConditionValue(0, condTok2, false, false, settings),
settings);
valueFlowGenericForward(startTok, startTok->link(), a1, tokenlist, errorLogger, settings);
if (is1) {
auto a2 =
makeOppositeExpressionAnalyzer(true,
condTok2,
makeConditionValue(isOp, condTok2, false, false, settings),
settings);
valueFlowGenericForward(startTok, startTok->link(), a2, tokenlist, errorLogger, settings);
}
}
}
// Check if the block terminates early
if (isEscapeScope(blockTok, settings)) {
const Scope* scope2 = scope;
// If escaping a loop then only use the loop scope
if (isBreakOrContinueScope(blockTok->link())) {
scope2 = getLoopScope(blockTok->link());
if (!scope2)
continue;
}
for (const Token* condTok2 : conds) {
auto a1 = makeSameExpressionAnalyzer(condTok2,
makeConditionValue(0, condTok2, false, false, settings),
settings);
valueFlowGenericForward(startTok->link()->next(), scope2->bodyEnd, a1, tokenlist, errorLogger, settings);
if (is1) {
auto a2 = makeOppositeExpressionAnalyzer(true,
condTok2,
makeConditionValue(1, condTok2, false, false, settings),
settings);
valueFlowGenericForward(startTok->link()->next(),
scope2->bodyEnd,
a2,
tokenlist,
errorLogger,
settings);
}
}
}
}
}
}
static bool isTruncated(const ValueType* src, const ValueType* dst, const Settings& settings)
{
if (src->pointer > 0 || dst->pointer > 0)
return src->pointer != dst->pointer;
if (src->smartPointer && dst->smartPointer)
return false;
if ((src->isIntegral() && dst->isIntegral()) || (src->isFloat() && dst->isFloat())) {
const size_t srcSize = ValueFlow::getSizeOf(*src, settings);
const size_t dstSize = ValueFlow::getSizeOf(*dst, settings);
if (srcSize > dstSize)
return true;
if (srcSize == dstSize && src->sign != dst->sign)
return true;
} else if (src->type == dst->type) {
if (src->type == ValueType::Type::RECORD)
return src->typeScope != dst->typeScope;
} else {
return true;
}
return false;
}
static void setSymbolic(ValueFlow::Value& value, const Token* tok)
{
assert(tok && tok->exprId() > 0 && "Missing expr id for symbolic value");
value.valueType = ValueFlow::Value::ValueType::SYMBOLIC;
value.tokvalue = tok;
}
static ValueFlow::Value makeSymbolic(const Token* tok, MathLib::bigint delta = 0)
{
ValueFlow::Value value;
value.setKnown();
setSymbolic(value, tok);
value.intvalue = delta;
return value;
}
static std::set<nonneg int> getVarIds(const Token* tok)
{
std::set<nonneg int> result;
visitAstNodes(tok, [&](const Token* child) {
if (child->varId() > 0)
result.insert(child->varId());
return ChildrenToVisit::op1_and_op2;
});
return result;
}
static void valueFlowSymbolic(const TokenList& tokenlist, const SymbolDatabase& symboldatabase, ErrorLogger& errorLogger, const Settings& settings)
{
for (const Scope* scope : symboldatabase.functionScopes) {
for (auto* tok = const_cast<Token*>(scope->bodyStart); tok != scope->bodyEnd; tok = tok->next()) {
if (!Token::simpleMatch(tok, "="))
continue;
if (tok->astParent())
continue;
if (!tok->astOperand1())
continue;
if (!tok->astOperand2())
continue;
if (tok->astOperand1()->hasKnownIntValue())
continue;
if (tok->astOperand2()->hasKnownIntValue())
continue;
if (tok->astOperand1()->exprId() == 0)
continue;
if (tok->astOperand2()->exprId() == 0)
continue;
if (!isConstExpression(tok->astOperand2(), settings.library))
continue;
if (tok->astOperand1()->valueType() && tok->astOperand2()->valueType()) {
if (isTruncated(
tok->astOperand2()->valueType(), tok->astOperand1()->valueType(), settings))
continue;
} else if (isDifferentType(tok->astOperand2(), tok->astOperand1())) {
continue;
}
const std::set<nonneg int> rhsVarIds = getVarIds(tok->astOperand2());
const std::vector<const Variable*> vars = getLHSVariables(tok);
if (std::any_of(vars.cbegin(), vars.cend(), [&](const Variable* var) {
if (rhsVarIds.count(var->declarationId()) > 0)
return true;
if (var->isLocal())
return var->isStatic();
return !var->isArgument();
}))
continue;
if (findAstNode(tok, [](const Token* child) {
return child->isIncompleteVar();
}))
continue;
Token* start = nextAfterAstRightmostLeaf(tok);
const Token* end = ValueFlow::getEndOfExprScope(tok->astOperand1(), scope);
ValueFlow::Value rhs = makeSymbolic(tok->astOperand2());
rhs.errorPath.emplace_back(tok,
tok->astOperand1()->expressionString() + " is assigned '" +
tok->astOperand2()->expressionString() + "' here.");
valueFlowForward(start, end, tok->astOperand1(), std::move(rhs), tokenlist, errorLogger, settings);
ValueFlow::Value lhs = makeSymbolic(tok->astOperand1());
lhs.errorPath.emplace_back(tok,
tok->astOperand1()->expressionString() + " is assigned '" +
tok->astOperand2()->expressionString() + "' here.");
valueFlowForward(start, end, tok->astOperand2(), std::move(lhs), tokenlist, errorLogger, settings);
}
}
}
static const Token* isStrlenOf(const Token* tok, const Token* expr, int depth = 10)
{
if (depth < 0)
return nullptr;
if (!tok)
return nullptr;
if (!expr)
return nullptr;
if (expr->exprId() == 0)
return nullptr;
if (Token::simpleMatch(tok->previous(), "strlen (")) {
if (tok->astOperand2()->exprId() == expr->exprId())
return tok;
} else {
for (const ValueFlow::Value& v : tok->values()) {
if (!v.isSymbolicValue())
continue;
if (!v.isKnown())
continue;
if (v.intvalue != 0)
continue;
if (const Token* next = isStrlenOf(v.tokvalue, expr, depth - 1))
return next;
}
}
return nullptr;
}
static void valueFlowSymbolicOperators(const SymbolDatabase& symboldatabase, const Settings& settings)
{
for (const Scope* scope : symboldatabase.functionScopes) {
for (auto* tok = const_cast<Token*>(scope->bodyStart); tok != scope->bodyEnd; tok = tok->next()) {
if (tok->hasKnownIntValue())
continue;
if (Token::Match(tok, "abs|labs|llabs|fabs|fabsf|fabsl (")) {
const Token* arg = tok->next()->astOperand2();
if (!arg)
continue;
if (arg->exprId() == 0)
continue;
ValueFlow::Value c = inferCondition(">=", arg, 0);
if (!c.isKnown())
continue;
ValueFlow::Value v = makeSymbolic(arg);
v.errorPath = c.errorPath;
v.errorPath.emplace_back(tok, "Passed to " + tok->str());
if (c.intvalue == 0)
v.setImpossible();
else
v.setKnown();
setTokenValue(tok->next(), std::move(v), settings);
} else if (Token::Match(tok, "*|/|<<|>>|^|+|-|%or%")) {
if (!tok->astOperand1())
continue;
if (!tok->astOperand2())
continue;
if (!astIsIntegral(tok->astOperand1(), false) && !astIsIntegral(tok->astOperand2(), false))
continue;
const ValueFlow::Value* constant = nullptr;
const Token* vartok = nullptr;
if (tok->astOperand1()->hasKnownIntValue()) {
constant = &tok->astOperand1()->values().front();
vartok = tok->astOperand2();
}
if (tok->astOperand2()->hasKnownIntValue()) {
constant = &tok->astOperand2()->values().front();
vartok = tok->astOperand1();
}
if (!constant)
continue;
if (!vartok)
continue;
if (vartok->exprId() == 0)
continue;
if (Token::Match(tok, "<<|>>|/") && !astIsLHS(vartok))
continue;
if (Token::Match(tok, "<<|>>|^|+|-|%or%") && constant->intvalue != 0)
continue;
if (Token::Match(tok, "*|/") && constant->intvalue != 1)
continue;
std::vector<ValueFlow::Value> values = {makeSymbolic(vartok)};
std::unordered_set<nonneg int> ids = {vartok->exprId()};
std::copy_if(vartok->values().cbegin(),
vartok->values().cend(),
std::back_inserter(values),
[&](const ValueFlow::Value& v) {
if (!v.isSymbolicValue())
return false;
if (!v.tokvalue)
return false;
return ids.insert(v.tokvalue->exprId()).second;
});
for (ValueFlow::Value& v : values)
setTokenValue(tok, std::move(v), settings);
} else if (Token::simpleMatch(tok, "[")) {
const Token* arrayTok = tok->astOperand1();
const Token* indexTok = tok->astOperand2();
if (!arrayTok)
continue;
if (!indexTok)
continue;
for (const ValueFlow::Value& value : indexTok->values()) {
if (!value.isSymbolicValue())
continue;
if (value.intvalue != 0)
continue;
const Token* strlenTok = isStrlenOf(value.tokvalue, arrayTok);
if (!strlenTok)
continue;
ValueFlow::Value v = value;
v.bound = ValueFlow::Value::Bound::Point;
v.valueType = ValueFlow::Value::ValueType::INT;
v.errorPath.emplace_back(strlenTok, "Return index of first '\\0' character in string");
setTokenValue(tok, std::move(v), settings);
}
}
}
}
}
struct SymbolicInferModel : InferModel {
const Token* expr;
explicit SymbolicInferModel(const Token* tok) : expr(tok) {
assert(expr->exprId() != 0);
}
bool match(const ValueFlow::Value& value) const override
{
return value.isSymbolicValue() && value.tokvalue && value.tokvalue->exprId() == expr->exprId();
}
ValueFlow::Value yield(MathLib::bigint value) const override
{
ValueFlow::Value result(value);
result.valueType = ValueFlow::Value::ValueType::SYMBOLIC;
result.tokvalue = expr;
result.setKnown();
return result;
}
};
static void valueFlowSymbolicInfer(const SymbolDatabase& symboldatabase, const Settings& settings)
{
for (const Scope* scope : symboldatabase.functionScopes) {
for (auto* tok = const_cast<Token*>(scope->bodyStart); tok != scope->bodyEnd; tok = tok->next()) {
if (!Token::Match(tok, "-|%comp%"))
continue;
if (tok->hasKnownIntValue())
continue;
if (!tok->astOperand1())
continue;
if (!tok->astOperand2())
continue;
if (tok->astOperand1()->exprId() == 0)
continue;
if (tok->astOperand2()->exprId() == 0)
continue;
if (tok->astOperand1()->hasKnownIntValue())
continue;
if (tok->astOperand2()->hasKnownIntValue())
continue;
if (astIsFloat(tok->astOperand1(), false))
continue;
if (astIsFloat(tok->astOperand2(), false))
continue;
std::vector<ValueFlow::Value> values;
{
SymbolicInferModel leftModel{tok->astOperand1()};
values = infer(leftModel, tok->str(), 0, tok->astOperand2()->values());
}
if (values.empty()) {
SymbolicInferModel rightModel{tok->astOperand2()};
values = infer(rightModel, tok->str(), tok->astOperand1()->values(), 0);
}
for (ValueFlow::Value& value : values) {
setTokenValue(tok, std::move(value), settings);
}
}
}
}
template<class ContainerOfValue>
static void valueFlowForwardConst(Token* start,
const Token* end,
const Variable* var,
const ContainerOfValue& values,
const Settings& settings,
int /*unused*/ = 0)
{
if (!precedes(start, end))
throw InternalError(var->nameToken(), "valueFlowForwardConst: start token does not precede the end token.");
for (Token* tok = start; tok != end; tok = tok->next()) {
if (tok->varId() == var->declarationId()) {
for (const ValueFlow::Value& value : values)
setTokenValue(tok, value, settings);
} else {
[&] {
// Follow references
auto refs = followAllReferences(tok);
auto it = std::find_if(refs.cbegin(), refs.cend(), [&](const ReferenceToken& ref) {
return ref.token->varId() == var->declarationId();
});
if (it != refs.end()) {
for (ValueFlow::Value value : values) {
if (refs.size() > 1)
value.setInconclusive();
value.errorPath.insert(value.errorPath.end(), it->errors.cbegin(), it->errors.cend());
setTokenValue(tok, std::move(value), settings);
}
return;
}
// Follow symbolic values
for (const ValueFlow::Value& v : tok->values()) {
if (!v.isSymbolicValue())
continue;
if (!v.tokvalue)
continue;
if (v.tokvalue->varId() != var->declarationId())
continue;
for (ValueFlow::Value value : values) {
if (!v.isKnown() && value.isImpossible())
continue;
if (v.intvalue != 0) {
if (!value.isIntValue())
continue;
value.intvalue += v.intvalue;
}
if (!value.isImpossible())
value.valueKind = v.valueKind;
value.bound = v.bound;
value.errorPath.insert(value.errorPath.end(), v.errorPath.cbegin(), v.errorPath.cend());
setTokenValue(tok, std::move(value), settings);
}
}
}();
}
}
}
static void valueFlowForwardConst(Token* start,
const Token* end,
const Variable* var,
const std::initializer_list<ValueFlow::Value>& values,
const Settings& settings)
{
valueFlowForwardConst(start, end, var, values, settings, 0);
}
static ValueFlow::Value::Bound findVarBound(const Variable* var,
const Token* start,
const Token* end,
const Settings& settings)
{
ValueFlow::Value::Bound result = ValueFlow::Value::Bound::Point;
const Token* next = start;
while ((next = findExpressionChangedSkipDeadCode(
var->nameToken(), next->next(), end, settings, &evaluateKnownValues))) {
ValueFlow::Value::Bound b = ValueFlow::Value::Bound::Point;
if (next->varId() != var->declarationId())
return ValueFlow::Value::Bound::Point;
if (Token::simpleMatch(next->astParent(), "++"))
b = ValueFlow::Value::Bound::Lower;
else if (Token::simpleMatch(next->astParent(), "--"))
b = ValueFlow::Value::Bound::Upper;
else
return ValueFlow::Value::Bound::Point;
if (result == ValueFlow::Value::Bound::Point)
result = b;
else if (result != b)
return ValueFlow::Value::Bound::Point;
}
return result;
}
static bool isInitialVarAssign(const Token* tok)
{
if (!tok)
return false;
if (!tok->variable())
return false;
if (tok->variable()->nameToken() == tok)
return true;
const Token* prev = tok->tokAt(2);
if (!Token::Match(prev, "%var% ; %var%"))
return false;
return tok->varId() == prev->varId() && tok->variable()->nameToken() == prev;
}
static void valueFlowForwardAssign(Token* const tok,
const Token* expr,
std::vector<const Variable*> vars,
std::list<ValueFlow::Value> values,
const bool init,
const TokenList& tokenlist,
ErrorLogger& errorLogger,
const Settings& settings)
{
if (Token::simpleMatch(tok->astParent(), "return"))
return;
const Token* endOfVarScope = ValueFlow::getEndOfExprScope(expr);
if (std::any_of(values.cbegin(), values.cend(), std::mem_fn(&ValueFlow::Value::isLifetimeValue))) {
valueFlowForwardLifetime(tok, tokenlist, errorLogger, settings);
values.remove_if(std::mem_fn(&ValueFlow::Value::isLifetimeValue));
}
if (std::all_of(
vars.cbegin(), vars.cend(), [&](const Variable* var) {
return !var->isPointer() && !var->isSmartPointer();
}))
values.remove_if(std::mem_fn(&ValueFlow::Value::isTokValue));
if (tok->astParent()) {
for (ValueFlow::Value& value : values) {
std::string valueKind;
if (value.valueKind == ValueFlow::Value::ValueKind::Impossible) {
if (value.bound == ValueFlow::Value::Bound::Point)
valueKind = "never ";
else if (value.bound == ValueFlow::Value::Bound::Lower)
valueKind = "less than ";
else if (value.bound == ValueFlow::Value::Bound::Upper)
valueKind = "greater than ";
}
std::string info = "Assignment '" + tok->astParent()->expressionString() + "', assigned value is " + valueKind + value.infoString();
value.errorPath.emplace_back(tok, std::move(info));
}
}
if (tokenlist.isCPP() && vars.size() == 1 && Token::Match(vars.front()->typeStartToken(), "bool|_Bool")) {
for (ValueFlow::Value& value : values) {
if (value.isImpossible())
continue;
if (value.isIntValue())
value.intvalue = (value.intvalue != 0);
if (value.isTokValue())
value.intvalue = (value.tokvalue != nullptr);
}
}
// Static variable initialisation?
if (vars.size() == 1 && vars.front()->isStatic() && !vars.front()->isConst() && init)
lowerToPossible(values);
// is volatile
if (std::any_of(vars.cbegin(), vars.cend(), [&](const Variable* var) {
return var->isVolatile();
}))
lowerToPossible(values);
// Skip RHS
Token* nextExpression = tok->astParent() ? nextAfterAstRightmostLeaf(tok->astParent()) : tok->next();
if (!nextExpression)
return;
for (ValueFlow::Value& value : values) {
if (value.isSymbolicValue())
continue;
if (value.isTokValue())
continue;
value.tokvalue = tok;
}
// Const variable
if (expr->variable() && expr->variable()->isConst() && !expr->variable()->isReference()) {
auto it = std::remove_if(values.begin(), values.end(), [](const ValueFlow::Value& value) {
if (!value.isKnown())
return false;
if (value.isIntValue())
return true;
if (value.isFloatValue())
return true;
if (value.isContainerSizeValue())
return true;
if (value.isIteratorValue())
return true;
return false;
});
std::list<ValueFlow::Value> constValues;
constValues.splice(constValues.end(), values, it, values.end());
valueFlowForwardConst(nextExpression, endOfVarScope, expr->variable(), constValues, settings);
}
if (isInitialVarAssign(expr)) {
// Check if variable is only incremented or decremented
ValueFlow::Value::Bound b = findVarBound(expr->variable(), nextExpression, endOfVarScope, settings);
if (b != ValueFlow::Value::Bound::Point) {
auto knownValueIt = std::find_if(values.begin(), values.end(), [](const ValueFlow::Value& value) {
if (!value.isKnown())
return false;
return value.isIntValue();
});
if (knownValueIt != values.end()) {
ValueFlow::Value value = *knownValueIt;
value.bound = b;
value.invertRange();
value.setImpossible();
valueFlowForwardConst(nextExpression, endOfVarScope, expr->variable(), {std::move(value)}, settings);
}
}
}
valueFlowForward(nextExpression, endOfVarScope, expr, std::move(values), tokenlist, errorLogger, settings);
}
static void valueFlowForwardAssign(Token* const tok,
const Variable* const var,
const std::list<ValueFlow::Value>& values,
const bool /*unused*/,
const bool init,
const TokenList& tokenlist,
ErrorLogger& errorLogger,
const Settings& settings)
{
valueFlowForwardAssign(tok, var->nameToken(), {var}, values, init, tokenlist, errorLogger, settings);
}
static std::list<ValueFlow::Value> truncateValues(std::list<ValueFlow::Value> values,
const ValueType* dst,
const ValueType* src,
const Settings& settings)
{
if (!dst || !dst->isIntegral())
return values;
const size_t sz = ValueFlow::getSizeOf(*dst, settings);
if (src) {
const size_t osz = ValueFlow::getSizeOf(*src, settings);
if (osz >= sz && dst->sign == ValueType::Sign::SIGNED && src->sign == ValueType::Sign::UNSIGNED) {
values.remove_if([&](const ValueFlow::Value& value) {
if (!value.isIntValue())
return false;
if (!value.isImpossible())
return false;
if (value.bound != ValueFlow::Value::Bound::Upper)
return false;
if (osz == sz && value.intvalue < 0)
return true;
if (osz > sz)
return true;
return false;
});
}
}
for (ValueFlow::Value &value : values) {
// Don't truncate impossible values since those can be outside of the valid range
if (value.isImpossible())
continue;
if (value.isFloatValue()) {
value.intvalue = value.floatValue;
value.valueType = ValueFlow::Value::ValueType::INT;
}
if (value.isIntValue() && sz > 0 && sz < sizeof(MathLib::biguint))
value.intvalue = ValueFlow::truncateIntValue(value.intvalue, sz, dst->sign);
}
return values;
}
static bool isVariableInit(const Token *tok)
{
if (!tok)
return false;
if (!Token::Match(tok->previous(), "%var% (|{"))
return false;
if (!tok->isBinaryOp() && !(tok->astOperand1() && tok->link() == tok->next()))
return false;
if (Token::simpleMatch(tok->astOperand2(), ","))
return false;
const Variable* var = tok->astOperand1()->variable();
if (!var)
return false;
if (var->nameToken() != tok->astOperand1())
return false;
const ValueType* vt = var->valueType();
if (!vt)
return false;
if (vt->type < ValueType::Type::VOID)
return false;
return true;
}
// Return true if two associative containers intersect
template<class C1, class C2>
static bool intersects(const C1& c1, const C2& c2)
{
if (c1.size() > c2.size())
return intersects(c2, c1);
// NOLINTNEXTLINE(readability-use-anyofallof) - TODO: fix if possible / also Cppcheck false negative
for (auto&& x : c1) {
if (c2.find(x) != c2.end())
return true;
}
return false;
}
static void valueFlowAfterAssign(TokenList &tokenlist,
const SymbolDatabase& symboldatabase,
ErrorLogger &errorLogger,
const Settings &settings,
const std::set<const Scope*>& skippedFunctions)
{
for (const Scope * scope : symboldatabase.functionScopes) {
if (skippedFunctions.count(scope))
continue;
std::unordered_map<nonneg int, std::unordered_set<nonneg int>> backAssigns;
for (auto* tok = const_cast<Token*>(scope->bodyStart); tok != scope->bodyEnd; tok = tok->next()) {
if (!tok->scope()->isExecutable()) {
tok = const_cast<Token*>(tok->scope()->bodyEnd); // skip local type definition
continue;
}
// Assignment
bool isInit = false;
if (tok->str() != "=" && !(isInit = isVariableInit(tok)))
continue;
if (tok->astParent() && !((tok->astParent()->str() == ";" && astIsLHS(tok)) || tok->astParent()->str() == "*"))
continue;
// Lhs should be a variable
if (!tok->astOperand1() || !tok->astOperand1()->exprId())
continue;
std::vector<const Variable*> vars = getLHSVariables(tok);
// Rhs values..
Token* rhs = tok->astOperand2();
if (!rhs && isInit)
rhs = tok;
if (!rhs || rhs->values().empty())
continue;
std::list<ValueFlow::Value> values = truncateValues(
rhs->values(), tok->astOperand1()->valueType(), rhs->valueType(), settings);
// Remove known values
std::set<ValueFlow::Value::ValueType> types;
if (tok->astOperand1()->hasKnownValue()) {
for (const ValueFlow::Value& value:tok->astOperand1()->values()) {
if (value.isKnown() && !value.isSymbolicValue())
types.insert(value.valueType);
}
}
values.remove_if([&](const ValueFlow::Value& value) {
return types.count(value.valueType) > 0;
});
// Remove container size if its not a container
if (!astIsContainer(tok->astOperand2()))
values.remove_if([&](const ValueFlow::Value& value) {
return value.valueType == ValueFlow::Value::ValueType::CONTAINER_SIZE;
});
// Remove symbolic values that are the same as the LHS
values.remove_if([&](const ValueFlow::Value& value) {
if (value.isSymbolicValue() && value.tokvalue)
return value.tokvalue->exprId() == tok->astOperand1()->exprId();
return false;
});
// Find references to LHS in RHS
auto isIncremental = [&](const Token* tok2) -> bool {
return findAstNode(tok2,
[&](const Token* child) {
return child->exprId() == tok->astOperand1()->exprId();
});
};
// Check symbolic values as well
const bool incremental = isIncremental(tok->astOperand2()) ||
std::any_of(values.cbegin(), values.cend(), [&](const ValueFlow::Value& value) {
if (!value.isSymbolicValue())
return false;
return isIncremental(value.tokvalue);
});
// Remove values from the same assignment if it is incremental
if (incremental) {
values.remove_if([&](const ValueFlow::Value& value) {
if (value.tokvalue)
return value.tokvalue == tok->astOperand2();
return false;
});
}
// If assignment copy by value, remove Uninit values..
if ((tok->astOperand1()->valueType() && tok->astOperand1()->valueType()->pointer == 0) ||
(tok->astOperand1()->variable() && tok->astOperand1()->variable()->isReference() && tok->astOperand1()->variable()->nameToken() == tok->astOperand1()))
values.remove_if([&](const ValueFlow::Value& value) {
return value.isUninitValue();
});
if (values.empty())
continue;
const bool init = vars.size() == 1 && (vars.front()->nameToken() == tok->astOperand1() || tok->isSplittedVarDeclEq());
valueFlowForwardAssign(
rhs, tok->astOperand1(), std::move(vars), values, init, tokenlist, errorLogger, settings);
// Back propagate symbolic values
if (tok->astOperand1()->exprId() > 0) {
Token* start = nextAfterAstRightmostLeaf(tok);
const Token* end = scope->bodyEnd;
// Collect symbolic ids
std::unordered_set<nonneg int> ids;
for (const ValueFlow::Value& value : values) {
if (!value.isSymbolicValue())
continue;
if (!value.tokvalue)
continue;
if (value.tokvalue->exprId() == 0)
continue;
ids.insert(value.tokvalue->exprId());
}
for (ValueFlow::Value value : values) {
if (!value.isSymbolicValue())
continue;
const Token* expr = value.tokvalue;
value.intvalue = -value.intvalue;
value.tokvalue = tok->astOperand1();
// Skip if it intersects with an already assigned symbol
auto& s = backAssigns[value.tokvalue->exprId()];
if (intersects(s, ids))
continue;
s.insert(expr->exprId());
value.errorPath.emplace_back(tok,
tok->astOperand1()->expressionString() + " is assigned '" +
tok->astOperand2()->expressionString() + "' here.");
valueFlowForward(start, end, expr, std::move(value), tokenlist, errorLogger, settings);
}
}
}
}
}
static std::vector<const Variable*> getVariables(const Token* tok)
{
std::vector<const Variable*> result;
visitAstNodes(tok, [&](const Token* child) {
if (child->variable())
result.push_back(child->variable());
return ChildrenToVisit::op1_and_op2;
});
return result;
}
static void valueFlowAfterSwap(const TokenList& tokenlist,
const SymbolDatabase& symboldatabase,
ErrorLogger& errorLogger,
const Settings& settings)
{
for (const Scope* scope : symboldatabase.functionScopes) {
for (auto* tok = const_cast<Token*>(scope->bodyStart); tok != scope->bodyEnd; tok = tok->next()) {
if (!Token::simpleMatch(tok, "swap ("))
continue;
if (!Token::simpleMatch(tok->next()->astOperand2(), ","))
continue;
std::vector<Token*> args = astFlatten(tok->next()->astOperand2(), ",");
if (args.size() != 2)
continue;
if (args[0]->exprId() == 0)
continue;
if (args[1]->exprId() == 0)
continue;
for (int i = 0; i < 2; i++) {
std::vector<const Variable*> vars = getVariables(args[0]);
const std::list<ValueFlow::Value>& values = args[0]->values();
valueFlowForwardAssign(args[0], args[1], std::move(vars), values, false, tokenlist, errorLogger, settings);
std::swap(args[0], args[1]);
}
}
}
}
static void valueFlowSetConditionToKnown(const Token* tok, std::list<ValueFlow::Value>& values, bool then)
{
if (values.empty())
return;
if (then && !Token::Match(tok, "==|!|("))
return;
if (!then && !Token::Match(tok, "!=|%var%|("))
return;
if (isConditionKnown(tok, then))
changePossibleToKnown(values);
}
static bool isBreakScope(const Token* const endToken)
{
if (!Token::simpleMatch(endToken, "}"))
return false;
if (!Token::simpleMatch(endToken->link(), "{"))
return false;
return Token::findmatch(endToken->link(), "break|goto", endToken);
}
ValueFlow::Value ValueFlow::asImpossible(ValueFlow::Value v)
{
v.invertRange();
v.setImpossible();
return v;
}
static void insertImpossible(std::list<ValueFlow::Value>& values, const std::list<ValueFlow::Value>& input)
{
std::transform(input.cbegin(), input.cend(), std::back_inserter(values), &ValueFlow::asImpossible);
}
static void insertNegateKnown(std::list<ValueFlow::Value>& values, const std::list<ValueFlow::Value>& input)
{
for (ValueFlow::Value value:input) {
if (!value.isIntValue() && !value.isContainerSizeValue())
continue;
value.intvalue = !value.intvalue;
value.setKnown();
values.push_back(std::move(value));
}
}
struct ConditionHandler {
struct Condition {
const Token* vartok{};
std::list<ValueFlow::Value> true_values;
std::list<ValueFlow::Value> false_values;
bool inverted = false;
// Whether to insert impossible values for the condition or only use possible values
bool impossible = true;
bool isBool() const {
return astIsBool(vartok);
}
static MathLib::bigint findPath(const std::list<ValueFlow::Value>& values)
{
auto it = std::find_if(values.cbegin(), values.cend(), [](const ValueFlow::Value& v) {
return v.path > 0;
});
if (it == values.end())
return 0;
assert(std::all_of(it, values.end(), [&](const ValueFlow::Value& v) {
return v.path == 0 || v.path == it->path;
}));
return it->path;
}
MathLib::bigint getPath() const
{
assert(std::abs(findPath(true_values) - findPath(false_values)) == 0);
return findPath(true_values) | findPath(false_values);
}
Token* getContextAndValues(Token* condTok,
std::list<ValueFlow::Value>& thenValues,
std::list<ValueFlow::Value>& elseValues,
bool known = false) const
{
const MathLib::bigint path = getPath();
const bool allowKnown = path == 0;
const bool allowImpossible = impossible && allowKnown;
bool inverted2 = inverted;
Token* ctx = skipNotAndCasts(condTok, &inverted2);
bool then = !inverted || !inverted2;
if (!Token::Match(condTok, "!=|=|(|.") && condTok != vartok) {
thenValues.insert(thenValues.end(), true_values.cbegin(), true_values.cend());
if (allowImpossible && (known || isConditionKnown(ctx, !then)))
insertImpossible(elseValues, false_values);
}
if (!Token::Match(condTok, "==|!")) {
elseValues.insert(elseValues.end(), false_values.cbegin(), false_values.cend());
if (allowImpossible && (known || isConditionKnown(ctx, then))) {
insertImpossible(thenValues, true_values);
if (isBool())
insertNegateKnown(thenValues, true_values);
}
}
if (inverted2)
std::swap(thenValues, elseValues);
return ctx;
}
};
virtual std::vector<Condition> parse(const Token* tok, const Settings& settings) const = 0;
virtual Analyzer::Result forward(Token* start,
const Token* stop,
const Token* exprTok,
const std::list<ValueFlow::Value>& values,
TokenList& tokenlist,
ErrorLogger& errorLogger,
const Settings& settings,
SourceLocation loc = SourceLocation::current()) const
{
return valueFlowForward(start->next(), stop, exprTok, values, tokenlist, errorLogger, settings, loc);
}
virtual Analyzer::Result forward(Token* top,
const Token* exprTok,
const std::list<ValueFlow::Value>& values,
TokenList& tokenlist,
ErrorLogger& errorLogger,
const Settings& settings,
SourceLocation loc = SourceLocation::current()) const
{
return valueFlowForwardRecursive(top, exprTok, values, tokenlist, errorLogger, settings, loc);
}
virtual void reverse(Token* start,
const Token* endToken,
const Token* exprTok,
const std::list<ValueFlow::Value>& values,
TokenList& tokenlist,
ErrorLogger& errorLogger,
const Settings& settings,
SourceLocation loc = SourceLocation::current()) const
{
valueFlowReverse(start, endToken, exprTok, values, tokenlist, errorLogger, settings, loc);
}
void traverseCondition(const SymbolDatabase& symboldatabase,
const Settings& settings,
const std::set<const Scope*>& skippedFunctions,
const std::function<void(const Condition& cond, Token* tok, const Scope* scope)>& f) const
{
for (const Scope *scope : symboldatabase.functionScopes) {
if (skippedFunctions.count(scope))
continue;
for (auto *tok = const_cast<Token *>(scope->bodyStart); tok != scope->bodyEnd; tok = tok->next()) {
if (Token::Match(tok, "if|while|for ("))
continue;
if (Token::Match(tok, ":|;|,"))
continue;
const Token* top = tok->astTop();
if (!Token::Match(top->previous(), "if|while|for (") && !Token::Match(tok->astParent(), "&&|%oror%|?|!"))
continue;
for (const Condition& cond : parse(tok, settings)) {
if (!cond.vartok)
continue;
if (cond.vartok->exprId() == 0)
continue;
if (cond.vartok->hasKnownIntValue())
continue;
if (cond.true_values.empty() || cond.false_values.empty())
continue;
if (!isConstExpression(cond.vartok, settings.library))
continue;
f(cond, tok, scope);
}
}
}
}
void beforeCondition(TokenList& tokenlist,
const SymbolDatabase& symboldatabase,
ErrorLogger& errorLogger,
const Settings& settings,
const std::set<const Scope*>& skippedFunctions) const {
traverseCondition(symboldatabase, settings, skippedFunctions, [&](const Condition& cond, Token* tok, const Scope*) {
if (cond.vartok->exprId() == 0)
return;
// If condition is known then don't propagate value
if (tok->hasKnownIntValue())
return;
Token* top = tok->astTop();
if (Token::Match(top, "%assign%"))
return;
if (Token::Match(cond.vartok->astParent(), "%assign%|++|--"))
return;
if (Token::simpleMatch(tok->astParent(), "?") && tok->astParent()->isExpandedMacro()) {
if (settings.debugwarnings)
bailout(tokenlist,
errorLogger,
tok,
"variable '" + cond.vartok->expressionString() + "', condition is defined in macro");
return;
}
// if,macro => bailout
if (Token::simpleMatch(top->previous(), "if (") && top->previous()->isExpandedMacro()) {
if (settings.debugwarnings)
bailout(tokenlist,
errorLogger,
tok,
"variable '" + cond.vartok->expressionString() + "', condition is defined in macro");
return;
}
if (cond.true_values.empty() && cond.false_values.empty())
return;
std::list<ValueFlow::Value> values = cond.true_values;
if (cond.true_values != cond.false_values)
values.insert(values.end(), cond.false_values.cbegin(), cond.false_values.cend());
// extra logic for unsigned variables 'i>=1' => possible value can also be 0
if (Token::Match(tok, "<|>|<=|>=")) {
if (cond.vartok->valueType() && cond.vartok->valueType()->sign != ValueType::Sign::UNSIGNED)
return;
values.remove_if([](const ValueFlow::Value& v) {
if (v.isIntValue())
return v.intvalue != 0;
return false;
});
}
if (values.empty())
return;
// bailout: for/while-condition, variable is changed in while loop
if (Token::Match(top->previous(), "for|while (") && Token::simpleMatch(top->link(), ") {")) {
// Variable changed in 3rd for-expression
if (Token::simpleMatch(top->previous(), "for (")) {
if (top->astOperand2() && top->astOperand2()->astOperand2() &&
findExpressionChanged(
cond.vartok, top->astOperand2()->astOperand2(), top->link(), settings)) {
if (settings.debugwarnings)
bailout(tokenlist,
errorLogger,
tok,
"variable '" + cond.vartok->expressionString() + "' used in loop");
return;
}
}
// Variable changed in loop code
const Token* const start = top;
const Token* const block = top->link()->next();
const Token* const end = block->link();
if (findExpressionChanged(cond.vartok, start, end, settings)) {
// If its reassigned in loop then analyze from the end
if (!Token::Match(tok, "%assign%|++|--") &&
findExpression(cond.vartok->exprId(), start, end, [&](const Token* tok2) {
return Token::Match(tok2->astParent(), "%assign%") && astIsLHS(tok2);
}) && !findEscapeStatement(block->scope(), &settings.library)) {
// Start at the end of the loop body
Token* bodyTok = top->link()->next();
reverse(bodyTok->link(), bodyTok, cond.vartok, values, tokenlist, errorLogger, settings);
}
if (settings.debugwarnings)
bailout(tokenlist,
errorLogger,
tok,
"variable '" + cond.vartok->expressionString() + "' used in loop");
return;
}
}
Token* startTok = nullptr;
if (astIsRHS(tok))
startTok = tok->astParent();
else if (astIsLHS(tok))
startTok = previousBeforeAstLeftmostLeaf(tok->astParent());
if (!startTok)
startTok = tok->previous();
reverse(startTok, nullptr, cond.vartok, values, tokenlist, errorLogger, settings);
});
}
static Token* skipNotAndCasts(Token* tok, bool* inverted = nullptr)
{
for (; tok->astParent(); tok = tok->astParent()) {
if (Token::simpleMatch(tok->astParent(), "!")) {
if (inverted)
*inverted ^= true;
continue;
}
if (Token::Match(tok->astParent(), "==|!=")) {
const Token* sibling = tok->astSibling();
if (sibling->hasKnownIntValue() && (astIsBool(tok) || astIsBool(sibling))) {
const bool value = sibling->values().front().intvalue;
if (inverted)
*inverted ^= value == Token::simpleMatch(tok->astParent(), "!=");
continue;
}
}
if (tok->astParent()->isCast() && astIsBool(tok->astParent()))
continue;
return tok;
}
return tok;
}
static void fillFromPath(ProgramMemory& pm, const Token* top, MathLib::bigint path, const Settings& settings)
{
if (path < 1)
return;
visitAstNodes(top, [&](const Token* tok) {
const ValueFlow::Value* v = ValueFlow::findValue(tok->values(), settings, [&](const ValueFlow::Value& v) {
return v.path == path && isNonConditionalPossibleIntValue(v);
});
if (v == nullptr)
return ChildrenToVisit::op1_and_op2;
pm.setValue(tok, *v);
return ChildrenToVisit::op1_and_op2;
});
}
void afterCondition(TokenList& tokenlist,
const SymbolDatabase& symboldatabase,
ErrorLogger& errorLogger,
const Settings& settings,
const std::set<const Scope*>& skippedFunctions) const {
traverseCondition(symboldatabase, settings, skippedFunctions, [&](const Condition& cond, Token* condTok, const Scope* scope) {
const MathLib::bigint path = cond.getPath();
const bool allowKnown = path == 0;
std::list<ValueFlow::Value> thenValues;
std::list<ValueFlow::Value> elseValues;
Token* ctx = cond.getContextAndValues(condTok, thenValues, elseValues);
if (Token::Match(ctx->astParent(), "%oror%|&&")) {
Token* parent = ctx->astParent();
if (astIsRHS(ctx) && astIsLHS(parent) && parent->astParent() &&
parent->str() == parent->astParent()->str())
parent = parent->astParent();
else if (!astIsLHS(ctx)) {
parent = nullptr;
}
if (parent) {
std::vector<Token*> nextExprs = {parent->astOperand2()};
if (astIsLHS(parent) && parent->astParent() && parent->astParent()->str() == parent->str()) {
nextExprs.push_back(parent->astParent()->astOperand2());
}
std::list<ValueFlow::Value> andValues;
std::list<ValueFlow::Value> orValues;
cond.getContextAndValues(condTok, andValues, orValues, true);
const std::string& op(parent->str());
std::list<ValueFlow::Value> values;
if (op == "&&")
values = std::move(andValues);
else if (op == "||")
values = std::move(orValues);
if (allowKnown && (Token::Match(condTok, "==|!=") || cond.isBool()))
changePossibleToKnown(values);
if (astIsFloat(cond.vartok, false) ||
(!cond.vartok->valueType() &&
std::all_of(values.cbegin(), values.cend(), [](const ValueFlow::Value& v) {
return v.isIntValue() || v.isFloatValue();
})))
values.remove_if([&](const ValueFlow::Value& v) {
return v.isImpossible();
});
for (Token* start:nextExprs) {
Analyzer::Result r = forward(start, cond.vartok, values, tokenlist, errorLogger, settings);
if (r.terminate != Analyzer::Terminate::None || r.action.isModified())
return;
}
}
}
{
const Token* tok2 = condTok;
std::string op;
bool mixedOperators = false;
while (tok2->astParent()) {
const Token* parent = tok2->astParent();
if (Token::Match(parent, "%oror%|&&")) {
if (op.empty()) {
op = parent->str();
} else if (op != parent->str()) {
mixedOperators = true;
break;
}
}
if (parent->str() == "!") {
op = (op == "&&" ? "||" : "&&");
}
tok2 = parent;
}
if (mixedOperators) {
return;
}
}
Token* top = condTok->astTop();
if (top->previous()->isExpandedMacro()) {
for (std::list<ValueFlow::Value>* values : {&thenValues, &elseValues}) {
for (ValueFlow::Value& v : *values)
v.macro = true;
}
}
Token* condTop = ctx->astParent();
{
bool inverted2 = false;
while (Token::Match(condTop, "%oror%|&&")) {
Token* parent = skipNotAndCasts(condTop, &inverted2)->astParent();
if (!parent)
break;
condTop = parent;
}
if (inverted2)
std::swap(thenValues, elseValues);
}
if (!condTop)
return;
if (Token::simpleMatch(condTop, "?")) {
Token* colon = condTop->astOperand2();
forward(colon->astOperand1(), cond.vartok, thenValues, tokenlist, errorLogger, settings);
forward(colon->astOperand2(), cond.vartok, elseValues, tokenlist, errorLogger, settings);
// TODO: Handle after condition
return;
}
if (condTop != top && condTop->str() != ";")
return;
if (!Token::Match(top->previous(), "if|while|for ("))
return;
if (top->strAt(-1) == "for") {
if (!Token::Match(condTok, "%comp%"))
return;
if (!Token::simpleMatch(condTok->astParent(), ";"))
return;
const Token* stepTok = getStepTok(top);
if (cond.vartok->varId() == 0)
return;
if (!cond.vartok->variable())
return;
if (!Token::Match(stepTok, "++|--"))
return;
std::set<ValueFlow::Value::Bound> bounds;
for (const ValueFlow::Value& v : thenValues) {
if (v.bound != ValueFlow::Value::Bound::Point && v.isImpossible())
continue;
bounds.insert(v.bound);
}
if (Token::simpleMatch(stepTok, "++") && bounds.count(ValueFlow::Value::Bound::Lower) > 0)
return;
if (Token::simpleMatch(stepTok, "--") && bounds.count(ValueFlow::Value::Bound::Upper) > 0)
return;
const Token* childTok = condTok->astOperand1();
if (!childTok)
childTok = condTok->astOperand2();
if (!childTok)
return;
if (childTok->varId() != cond.vartok->varId())
return;
const Token* startBlock = top->link()->next();
if (isVariableChanged(startBlock,
startBlock->link(),
cond.vartok->varId(),
cond.vartok->variable()->isGlobal(),
settings))
return;
// Check if condition in for loop is always false
const Token* initTok = getInitTok(top);
ProgramMemory pm;
fillFromPath(pm, initTok, path, settings);
fillFromPath(pm, condTok, path, settings);
execute(initTok, pm, nullptr, nullptr, settings);
MathLib::bigint result = 1;
execute(condTok, pm, &result, nullptr, settings);
if (result == 0)
return;
// Remove condition since for condition is not redundant
for (std::list<ValueFlow::Value>* values : {&thenValues, &elseValues}) {
for (ValueFlow::Value& v : *values) {
v.condition = nullptr;
v.conditional = true;
}
}
}
bool deadBranch[] = {false, false};
// start token of conditional code
Token* startTokens[] = {nullptr, nullptr};
// determine startToken(s)
if (Token::simpleMatch(top->link(), ") {"))
startTokens[0] = top->link()->next();
if (Token::simpleMatch(top->link()->linkAt(1), "} else {"))
startTokens[1] = top->link()->linkAt(1)->tokAt(2);
int changeBlock = -1;
int bailBlock = -1;
for (int i = 0; i < 2; i++) {
const Token* const startToken = startTokens[i];
if (!startToken)
continue;
std::list<ValueFlow::Value>& values = (i == 0 ? thenValues : elseValues);
if (allowKnown)
valueFlowSetConditionToKnown(condTok, values, i == 0);
Analyzer::Result r = forward(startTokens[i], startTokens[i]->link(), cond.vartok, values, tokenlist, errorLogger, settings);
deadBranch[i] = r.terminate == Analyzer::Terminate::Escape;
if (r.action.isModified() && !deadBranch[i])
changeBlock = i;
if (r.terminate != Analyzer::Terminate::None && r.terminate != Analyzer::Terminate::Escape &&
r.terminate != Analyzer::Terminate::Modified)
bailBlock = i;
changeKnownToPossible(values);
}
if (changeBlock >= 0 && !Token::simpleMatch(top->previous(), "while (")) {
if (settings.debugwarnings)
bailout(tokenlist,
errorLogger,
startTokens[changeBlock]->link(),
"valueFlowAfterCondition: " + cond.vartok->expressionString() +
" is changed in conditional block");
return;
}
if (bailBlock >= 0) {
if (settings.debugwarnings)
bailout(tokenlist,
errorLogger,
startTokens[bailBlock]->link(),
"valueFlowAfterCondition: bailing in conditional block");
return;
}
// After conditional code..
if (Token::simpleMatch(top->link(), ") {")) {
Token* after = top->link()->linkAt(1);
bool dead_if = deadBranch[0];
bool dead_else = deadBranch[1];
const Token* unknownFunction = nullptr;
if (condTok->astParent() && Token::Match(top->previous(), "while|for ("))
dead_if = !isBreakScope(after);
else if (!dead_if)
dead_if = isReturnScope(after, settings.library, &unknownFunction);
if (!dead_if && unknownFunction) {
if (settings.debugwarnings)
bailout(tokenlist, errorLogger, unknownFunction, "possible noreturn scope");
return;
}
if (Token::simpleMatch(after, "} else {")) {
after = after->linkAt(2);
unknownFunction = nullptr;
if (!dead_else)
dead_else = isReturnScope(after, settings.library, &unknownFunction);
if (!dead_else && unknownFunction) {
if (settings.debugwarnings)
bailout(tokenlist, errorLogger, unknownFunction, "possible noreturn scope");
return;
}
}
if (dead_if && dead_else)
return;
std::list<ValueFlow::Value> values;
if (dead_if) {
values = std::move(elseValues);
} else if (dead_else) {
values = std::move(thenValues);
} else {
std::copy_if(thenValues.cbegin(),
thenValues.cend(),
std::back_inserter(values),
std::mem_fn(&ValueFlow::Value::isPossible));
std::copy_if(elseValues.cbegin(),
elseValues.cend(),
std::back_inserter(values),
std::mem_fn(&ValueFlow::Value::isPossible));
}
if (values.empty())
return;
if (dead_if || dead_else) {
const Token* parent = condTok->astParent();
// Skip the not operator
while (Token::simpleMatch(parent, "!"))
parent = parent->astParent();
bool possible = false;
if (Token::Match(parent, "&&|%oror%")) {
const std::string& op(parent->str());
while (parent && parent->str() == op)
parent = parent->astParent();
if (Token::simpleMatch(parent, "!") || Token::simpleMatch(parent, "== false"))
possible = op == "||";
else
possible = op == "&&";
}
if (possible) {
values.remove_if(std::mem_fn(&ValueFlow::Value::isImpossible));
changeKnownToPossible(values);
} else if (allowKnown) {
valueFlowSetConditionToKnown(condTok, values, true);
valueFlowSetConditionToKnown(condTok, values, false);
}
}
if (values.empty())
return;
const bool isKnown = std::any_of(values.cbegin(), values.cend(), [&](const ValueFlow::Value& v) {
return v.isKnown() || v.isImpossible();
});
if (isKnown && isBreakOrContinueScope(after)) {
const Scope* loopScope = getLoopScope(cond.vartok);
if (loopScope) {
Analyzer::Result r = forward(after, loopScope->bodyEnd, cond.vartok, values, tokenlist, errorLogger, settings);
if (r.terminate != Analyzer::Terminate::None)
return;
if (r.action.isModified())
return;
auto* start = const_cast<Token*>(loopScope->bodyEnd);
if (Token::simpleMatch(start, "} while (")) {
start = start->tokAt(2);
forward(start, start->link(), cond.vartok, values, tokenlist, errorLogger, settings);
start = start->link();
}
values.remove_if(std::mem_fn(&ValueFlow::Value::isImpossible));
changeKnownToPossible(values);
}
}
forward(after, ValueFlow::getEndOfExprScope(cond.vartok, scope), cond.vartok, values, tokenlist, errorLogger, settings);
}
});
}
virtual ~ConditionHandler() = default;
ConditionHandler(const ConditionHandler&) = default;
protected:
ConditionHandler() = default;
};
static void valueFlowCondition(const ValuePtr<ConditionHandler>& handler,
TokenList& tokenlist,
SymbolDatabase& symboldatabase,
ErrorLogger& errorLogger,
const Settings& settings,
const std::set<const Scope*>& skippedFunctions)
{
handler->beforeCondition(tokenlist, symboldatabase, errorLogger, settings, skippedFunctions);
handler->afterCondition(tokenlist, symboldatabase, errorLogger, settings, skippedFunctions);
}
struct SimpleConditionHandler : ConditionHandler {
std::vector<Condition> parse(const Token* tok, const Settings& /*settings*/) const override {
std::vector<Condition> conds;
parseCompareEachInt(tok, [&](const Token* vartok, ValueFlow::Value true_value, ValueFlow::Value false_value) {
if (vartok->hasKnownIntValue())
return;
if (vartok->str() == "=" && vartok->astOperand1() && vartok->astOperand2())
vartok = vartok->astOperand1();
Condition cond;
cond.true_values.push_back(std::move(true_value));
cond.false_values.push_back(std::move(false_value));
cond.vartok = vartok;
conds.push_back(std::move(cond));
});
if (!conds.empty())
return conds;
const Token* vartok = nullptr;
if (tok->str() == "!") {
vartok = tok->astOperand1();
} else if (tok->astParent() && (Token::Match(tok->astParent(), "%oror%|&&|?") ||
Token::Match(tok->astParent()->previous(), "if|while ("))) {
if (Token::simpleMatch(tok, "="))
vartok = tok->astOperand1();
else if (!Token::Match(tok, "%comp%|%assign%"))
vartok = tok;
}
if (!vartok)
return {};
Condition cond;
cond.true_values.emplace_back(tok, 0LL);
cond.false_values.emplace_back(tok, 0LL);
cond.vartok = vartok;
return {std::move(cond)};
}
};
struct IteratorInferModel : InferModel {
virtual ValueFlow::Value::ValueType getType() const = 0;
bool match(const ValueFlow::Value& value) const override {
return value.valueType == getType();
}
ValueFlow::Value yield(MathLib::bigint value) const override
{
ValueFlow::Value result(value);
result.valueType = getType();
result.setKnown();
return result;
}
};
struct EndIteratorInferModel : IteratorInferModel {
ValueFlow::Value::ValueType getType() const override {
return ValueFlow::Value::ValueType::ITERATOR_END;
}
};
struct StartIteratorInferModel : IteratorInferModel {
ValueFlow::Value::ValueType getType() const override {
return ValueFlow::Value::ValueType::ITERATOR_END;
}
};
static bool isIntegralOnlyOperator(const Token* tok) {
return Token::Match(tok, "%|<<|>>|&|^|~|%or%");
}
static bool isIntegralOrPointer(const Token* tok)
{
if (!tok)
return false;
if (astIsIntegral(tok, false))
return true;
if (astIsPointer(tok))
return true;
if (Token::Match(tok, "NULL|nullptr"))
return true;
if (tok->valueType())
return false;
// These operators only work on integers
if (isIntegralOnlyOperator(tok))
return true;
if (isIntegralOnlyOperator(tok->astParent()))
return true;
if (Token::Match(tok, "+|-|*|/") && tok->isBinaryOp())
return isIntegralOrPointer(tok->astOperand1()) && isIntegralOrPointer(tok->astOperand2());
return false;
}
static void valueFlowInferCondition(TokenList& tokenlist, const Settings& settings)
{
for (Token* tok = tokenlist.front(); tok; tok = tok->next()) {
if (!tok->astParent())
continue;
if (tok->hasKnownIntValue())
continue;
if (Token::Match(tok, "%comp%|-") && tok->astOperand1() && tok->astOperand2()) {
if (astIsIterator(tok->astOperand1()) || astIsIterator(tok->astOperand2())) {
static const std::array<ValuePtr<InferModel>, 2> iteratorModels = {EndIteratorInferModel{},
StartIteratorInferModel{}};
for (const ValuePtr<InferModel>& model : iteratorModels) {
std::vector<ValueFlow::Value> result =
infer(model, tok->str(), tok->astOperand1()->values(), tok->astOperand2()->values());
for (ValueFlow::Value value : result) {
value.valueType = ValueFlow::Value::ValueType::INT;
setTokenValue(tok, std::move(value), settings);
}
}
} else if (isIntegralOrPointer(tok->astOperand1()) && isIntegralOrPointer(tok->astOperand2())) {
std::vector<ValueFlow::Value> result =
infer(makeIntegralInferModel(), tok->str(), tok->astOperand1()->values(), tok->astOperand2()->values());
for (ValueFlow::Value& value : result) {
setTokenValue(tok, std::move(value), settings);
}
}
} else if (Token::Match(tok->astParent(), "?|&&|!|%oror%") ||
Token::Match(tok->astParent()->previous(), "if|while (") ||
(astIsPointer(tok) && isUsedAsBool(tok, settings))) {
std::vector<ValueFlow::Value> result = infer(makeIntegralInferModel(), "!=", tok->values(), 0);
if (result.size() != 1)
continue;
ValueFlow::Value value = result.front();
setTokenValue(tok, std::move(value), settings);
}
}
}
struct SymbolicConditionHandler : SimpleConditionHandler {
static bool isNegatedBool(const Token* tok)
{
if (!Token::simpleMatch(tok, "!"))
return false;
return (astIsBool(tok->astOperand1()));
}
static const Token* skipNot(const Token* tok)
{
if (!Token::simpleMatch(tok, "!"))
return tok;
return tok->astOperand1();
}
std::vector<Condition> parse(const Token* tok, const Settings& settings) const override
{
if (!Token::Match(tok, "%comp%"))
return {};
if (tok->hasKnownIntValue())
return {};
if (!tok->astOperand1() || tok->astOperand1()->hasKnownIntValue() || tok->astOperand1()->isLiteral())
return {};
if (!tok->astOperand2() || tok->astOperand2()->hasKnownIntValue() || tok->astOperand2()->isLiteral())
return {};
if (!isConstExpression(tok, settings.library))
return {};
std::vector<Condition> result;
auto addCond = [&](const Token* lhsTok, const Token* rhsTok, bool inverted) {
for (int i = 0; i < 2; i++) {
const bool lhs = i == 0;
const Token* vartok = lhs ? lhsTok : rhsTok;
const Token* valuetok = lhs ? rhsTok : lhsTok;
if (valuetok->exprId() == 0)
continue;
if (valuetok->hasKnownSymbolicValue(vartok))
continue;
if (vartok->hasKnownSymbolicValue(valuetok))
continue;
ValueFlow::Value true_value;
ValueFlow::Value false_value;
setConditionalValues(tok, !lhs, 0, true_value, false_value);
setSymbolic(true_value, valuetok);
setSymbolic(false_value, valuetok);
Condition cond;
cond.true_values = {std::move(true_value)};
cond.false_values = {std::move(false_value)};
cond.vartok = vartok;
cond.inverted = inverted;
result.push_back(std::move(cond));
}
};
addCond(tok->astOperand1(), tok->astOperand2(), false);
if (Token::Match(tok, "==|!=") && (isNegatedBool(tok->astOperand1()) || isNegatedBool(tok->astOperand2()))) {
const Token* lhsTok = skipNot(tok->astOperand1());
const Token* rhsTok = skipNot(tok->astOperand2());
addCond(lhsTok, rhsTok, !(isNegatedBool(tok->astOperand1()) && isNegatedBool(tok->astOperand2())));
}
return result;
}
};
static bool valueFlowForLoop2(const Token *tok,
ProgramMemory *memory1,
ProgramMemory *memory2,
ProgramMemory *memoryAfter,
const Settings& settings)
{
// for ( firstExpression ; secondExpression ; thirdExpression )
const Token *firstExpression = tok->next()->astOperand2()->astOperand1();
const Token *secondExpression = tok->next()->astOperand2()->astOperand2()->astOperand1();
const Token *thirdExpression = tok->next()->astOperand2()->astOperand2()->astOperand2();
ProgramMemory programMemory;
MathLib::bigint result(0);
bool error = false;
execute(firstExpression, programMemory, &result, &error, settings);
if (error)
return false;
execute(secondExpression, programMemory, &result, &error, settings);
if (result == 0) // 2nd expression is false => no looping
return false;
if (error) {
// If a variable is reassigned in second expression, return false
bool reassign = false;
visitAstNodes(secondExpression,
[&](const Token *t) {
if (t->str() == "=" && t->astOperand1() && programMemory.hasValue(t->astOperand1()->varId()))
// TODO: investigate what variable is assigned.
reassign = true;
return reassign ? ChildrenToVisit::done : ChildrenToVisit::op1_and_op2;
});
if (reassign)
return false;
}
ProgramMemory startMemory(programMemory);
ProgramMemory endMemory;
int maxcount = settings.vfOptions.maxForLoopCount;
while (result != 0 && !error && --maxcount > 0) {
endMemory = programMemory;
execute(thirdExpression, programMemory, &result, &error, settings);
if (!error)
execute(secondExpression, programMemory, &result, &error, settings);
}
// TODO: add bailout message
if (memory1)
memory1->swap(startMemory);
if (!error) {
if (memory2)
memory2->swap(endMemory);
if (memoryAfter)
memoryAfter->swap(programMemory);
}
return true;
}
static void valueFlowForLoopSimplify(Token* const bodyStart,
const Token* expr,
bool globalvar,
const MathLib::bigint value,
const TokenList& tokenlist,
ErrorLogger& errorLogger,
const Settings& settings)
{
// TODO: Refactor this to use arbitrary expressions
assert(expr->varId() > 0);
const Token * const bodyEnd = bodyStart->link();
// Is variable modified inside for loop
if (isVariableChanged(bodyStart, bodyEnd, expr->varId(), globalvar, settings))
return;
if (const Token* escape = findEscapeStatement(bodyStart->scope(), &settings.library)) {
if (settings.debugwarnings)
bailout(tokenlist, errorLogger, escape, "For loop variable bailout on escape statement");
return;
}
for (Token *tok2 = bodyStart->next(); tok2 != bodyEnd; tok2 = tok2->next()) {
if (tok2->varId() == expr->varId()) {
const Token * parent = tok2->astParent();
while (parent) {
const Token * const p = parent;
parent = parent->astParent();
if (!parent || parent->str() == ":")
break;
if (parent->str() == "?") {
if (parent->astOperand2() != p)
parent = nullptr;
break;
}
}
if (parent) {
if (settings.debugwarnings)
bailout(tokenlist, errorLogger, tok2, "For loop variable " + tok2->str() + " stopping on ?");
continue;
}
ValueFlow::Value value1(value);
value1.varId = tok2->varId();
setTokenValue(tok2, std::move(value1), settings);
}
if (Token::Match(tok2, "%oror%|&&")) {
const ProgramMemory programMemory(getProgramMemory(tok2->astTop(), expr, ValueFlow::Value(value), settings));
if ((tok2->str() == "&&" && !conditionIsTrue(tok2->astOperand1(), programMemory, settings)) ||
(tok2->str() == "||" && !conditionIsFalse(tok2->astOperand1(), programMemory, settings))) {
// Skip second expression..
Token *parent = tok2;
while (parent && parent->str() == tok2->str())
parent = parent->astParent();
// Jump to end of condition
if (parent && parent->str() == "(") {
tok2 = parent->link();
// cast
if (Token::simpleMatch(tok2, ") ("))
tok2 = tok2->linkAt(1);
}
}
}
const Token* vartok = expr;
const Token* rml = nextAfterAstRightmostLeaf(vartok);
if (rml)
vartok = rml->str() == "]" ? rml : rml->previous();
if (vartok->str() == "]" && vartok->link()->previous())
vartok = vartok->link()->previous();
if ((tok2->str() == "&&" &&
conditionIsFalse(tok2->astOperand1(),
getProgramMemory(tok2->astTop(), expr, ValueFlow::Value(value), settings),
settings)) ||
(tok2->str() == "||" &&
conditionIsTrue(tok2->astOperand1(),
getProgramMemory(tok2->astTop(), expr, ValueFlow::Value(value), settings),
settings)))
break;
if (Token::simpleMatch(tok2, ") {")) {
if (vartok->varId() && Token::findmatch(tok2->link(), "%varid%", tok2, vartok->varId())) {
if (settings.debugwarnings)
bailout(tokenlist, errorLogger, tok2, "For loop variable skipping conditional scope");
tok2 = tok2->linkAt(1);
if (Token::simpleMatch(tok2, "} else {")) {
tok2 = tok2->linkAt(2);
}
}
else {
if (settings.debugwarnings)
bailout(tokenlist, errorLogger, tok2, "For loop skipping {} code");
tok2 = tok2->linkAt(1);
if (Token::simpleMatch(tok2, "} else {"))
tok2 = tok2->linkAt(2);
}
}
}
}
static void valueFlowForLoopSimplifyAfter(Token* fortok, nonneg int varid, const MathLib::bigint num, const TokenList& tokenlist, ErrorLogger & errorLogger, const Settings& settings)
{
const Token *vartok = nullptr;
for (const Token *tok = fortok; tok; tok = tok->next()) {
if (tok->varId() == varid) {
vartok = tok;
break;
}
}
if (!vartok || !vartok->variable())
return;
const Variable *var = vartok->variable();
const Token *endToken = nullptr;
if (var->isLocal())
endToken = var->scope()->bodyEnd;
else
endToken = fortok->scope()->bodyEnd;
Token* blockTok = fortok->linkAt(1)->linkAt(1);
if (blockTok != endToken) {
ValueFlow::Value v{num};
v.errorPath.emplace_back(fortok,"After for loop, " + var->name() + " has value " + v.infoString());
valueFlowForward(blockTok->next(), endToken, vartok, std::move(v), tokenlist, errorLogger, settings);
}
}
static void valueFlowForLoop(TokenList &tokenlist, const SymbolDatabase& symboldatabase, ErrorLogger &errorLogger, const Settings &settings)
{
for (const Scope &scope : symboldatabase.scopeList) {
if (scope.type != Scope::eFor)
continue;
auto* tok = const_cast<Token*>(scope.classDef);
auto* const bodyStart = const_cast<Token*>(scope.bodyStart);
if (!Token::simpleMatch(tok->next()->astOperand2(), ";") ||
!Token::simpleMatch(tok->next()->astOperand2()->astOperand2(), ";"))
continue;
nonneg int varid;
bool knownInitValue, partialCond;
MathLib::bigint initValue, stepValue, lastValue;
if (extractForLoopValues(tok, varid, knownInitValue, initValue, partialCond, stepValue, lastValue)) {
const bool executeBody = !knownInitValue || initValue <= lastValue;
const Token* vartok = Token::findmatch(tok, "%varid%", bodyStart, varid);
if (executeBody && vartok) {
std::list<ValueFlow::Value> initValues;
initValues.emplace_back(initValue, ValueFlow::Value::Bound::Lower);
initValues.push_back(ValueFlow::asImpossible(initValues.back()));
Analyzer::Result result = valueFlowForward(bodyStart, bodyStart->link(), vartok, std::move(initValues), tokenlist, errorLogger, settings);
if (!result.action.isModified()) {
std::list<ValueFlow::Value> lastValues;
lastValues.emplace_back(lastValue, ValueFlow::Value::Bound::Upper);
lastValues.back().conditional = true;
lastValues.push_back(ValueFlow::asImpossible(lastValues.back()));
if (stepValue != 1)
lastValues.pop_front();
valueFlowForward(bodyStart, bodyStart->link(), vartok, std::move(lastValues), tokenlist, errorLogger, settings);
}
}
const MathLib::bigint afterValue = executeBody ? lastValue + stepValue : initValue;
valueFlowForLoopSimplifyAfter(tok, varid, afterValue, tokenlist, errorLogger, settings);
} else {
ProgramMemory mem1, mem2, memAfter;
if (valueFlowForLoop2(tok, &mem1, &mem2, &memAfter, settings)) {
for (const auto& p : mem1) {
if (!p.second.isIntValue())
continue;
if (p.second.isImpossible())
continue;
if (p.first.tok->varId() == 0)
continue;
valueFlowForLoopSimplify(bodyStart, p.first.tok, false, p.second.intvalue, tokenlist, errorLogger, settings);
}
for (const auto& p : mem2) {
if (!p.second.isIntValue())
continue;
if (p.second.isImpossible())
continue;
if (p.first.tok->varId() == 0)
continue;
valueFlowForLoopSimplify(bodyStart, p.first.tok, false, p.second.intvalue, tokenlist, errorLogger, settings);
}
for (const auto& p : memAfter) {
if (!p.second.isIntValue())
continue;
if (p.second.isImpossible())
continue;
if (p.first.tok->varId() == 0)
continue;
valueFlowForLoopSimplifyAfter(tok, p.first.getExpressionId(), p.second.intvalue, tokenlist, errorLogger, settings);
}
}
}
}
}
template<class Key, class F>
static bool productParams(const Settings& settings, const std::unordered_map<Key, std::list<ValueFlow::Value>>& vars, F f)
{
using Args = std::vector<std::unordered_map<Key, ValueFlow::Value>>;
Args args(1);
// Compute cartesian product of all arguments
for (const auto& p : vars) {
if (p.second.empty())
continue;
args.back()[p.first] = p.second.front();
}
bool bail = false;
int max = settings.vfOptions.maxSubFunctionArgs;
for (const auto& p : vars) {
if (args.size() > max) {
bail = true;
break;
}
if (p.second.empty())
continue;
std::for_each(std::next(p.second.begin()), p.second.end(), [&](const ValueFlow::Value& value) {
Args new_args;
for (auto arg : args) {
if (value.path != 0) {
for (const auto& q : arg) {
if (q.first == p.first)
continue;
if (q.second.path == 0)
continue;
if (q.second.path != value.path)
return;
}
}
arg[p.first] = value;
new_args.push_back(std::move(arg));
}
std::copy(new_args.cbegin(), new_args.cend(), std::back_inserter(args));
});
}
if (args.size() > max) {
bail = true;
args.resize(max);
// TODO: add bailout message
}
for (const auto& arg : args) {
if (arg.empty())
continue;
// Make sure all arguments are the same path
const MathLib::bigint path = arg.cbegin()->second.path;
if (std::any_of(arg.cbegin(), arg.cend(), [&](const std::pair<Key, ValueFlow::Value>& p) {
return p.second.path != path;
}))
continue;
f(arg);
}
return !bail;
}
static void valueFlowInjectParameter(const TokenList& tokenlist,
ErrorLogger& errorLogger,
const Settings& settings,
const Scope* functionScope,
const std::unordered_map<const Variable*, std::list<ValueFlow::Value>>& vars)
{
const bool r = productParams(settings, vars, [&](const std::unordered_map<const Variable*, ValueFlow::Value>& arg) {
auto a = makeMultiValueFlowAnalyzer(arg, settings);
valueFlowGenericForward(const_cast<Token*>(functionScope->bodyStart),
functionScope->bodyEnd,
a,
tokenlist,
errorLogger,
settings);
});
if (!r) {
std::string fname = "<unknown>";
if (const Function* f = functionScope->function)
fname = f->name();
if (settings.debugwarnings)
bailout(tokenlist, errorLogger, functionScope->bodyStart, "Too many argument passed to " + fname);
}
}
static void valueFlowInjectParameter(const TokenList& tokenlist,
ErrorLogger& errorLogger,
const Settings& settings,
const Variable* arg,
const Scope* functionScope,
const std::list<ValueFlow::Value>& argvalues)
{
// Is argument passed by value or const reference, and is it a known non-class type?
if (arg->isReference() && !arg->isConst() && !arg->isClass())
return;
// Set value in function scope..
const nonneg int varid2 = arg->declarationId();
if (!varid2)
return;
valueFlowForward(const_cast<Token*>(functionScope->bodyStart->next()),
functionScope->bodyEnd,
arg->nameToken(),
argvalues,
tokenlist,
errorLogger,
settings);
}
static void valueFlowSwitchVariable(const TokenList& tokenlist,
const SymbolDatabase& symboldatabase,
ErrorLogger& errorLogger,
const Settings& settings)
{
for (const Scope& scope : symboldatabase.scopeList) {
if (scope.type != Scope::ScopeType::eSwitch)
continue;
if (!Token::Match(scope.classDef, "switch ( %var% ) {"))
continue;
const Token* vartok = scope.classDef->tokAt(2);
const Variable* var = vartok->variable();
if (!var)
continue;
// bailout: global non-const variables
if (!(var->isLocal() || var->isArgument()) && !var->isConst()) {
if (settings.debugwarnings)
bailout(tokenlist, errorLogger, vartok, "switch variable " + var->name() + " is global");
continue;
}
for (const Token* tok = scope.bodyStart->next(); tok != scope.bodyEnd; tok = tok->next()) {
if (tok->str() == "{") {
tok = tok->link();
continue;
}
if (Token::Match(tok, "case %num% :")) {
std::list<ValueFlow::Value> values;
values.emplace_back(MathLib::toBigNumber(tok->strAt(1)));
values.back().condition = tok;
values.back().errorPath.emplace_back(tok,
"case " + tok->strAt(1) + ": " + vartok->str() + " is " +
tok->strAt(1) + " here.");
bool known = false;
if ((Token::simpleMatch(tok->previous(), "{") || Token::simpleMatch(tok->tokAt(-2), "break ;")) &&
!Token::Match(tok->tokAt(3), ";| case"))
known = true;
while (Token::Match(tok->tokAt(3), ";| case %num% :")) {
known = false;
tok = tok->tokAt(3);
if (!tok->isName())
tok = tok->next();
values.emplace_back(MathLib::toBigNumber(tok->strAt(1)));
values.back().condition = tok;
values.back().errorPath.emplace_back(tok,
"case " + tok->strAt(1) + ": " + vartok->str() + " is " +
tok->strAt(1) + " here.");
}
for (auto val = values.cbegin(); val != values.cend(); ++val) {
valueFlowReverse(tokenlist, const_cast<Token*>(scope.classDef), vartok, *val, errorLogger, settings);
}
if (vartok->variable()->scope()) {
if (known)
values.back().setKnown();
// FIXME We must check if there is a return. See #9276
/*
valueFlowForwardVariable(tok->tokAt(3),
vartok->variable()->scope()->bodyEnd,
vartok->variable(),
vartok->varId(),
values,
values.back().isKnown(),
false,
tokenlist,
errorLogger,
settings);
*/
}
}
}
}
}
static std::list<ValueFlow::Value> getFunctionArgumentValues(const Token* argtok)
{
std::list<ValueFlow::Value> argvalues(argtok->values());
removeImpossible(argvalues);
if (argvalues.empty() && Token::Match(argtok, "%comp%|%oror%|&&|!")) {
argvalues.emplace_back(0);
argvalues.emplace_back(1);
}
return argvalues;
}
static void valueFlowLibraryFunction(Token* tok, const std::string& returnValue, const Settings& settings)
{
std::unordered_map<nonneg int, std::list<ValueFlow::Value>> argValues;
int argn = 1;
for (const Token* argtok : getArguments(tok->previous())) {
argValues[argn] = getFunctionArgumentValues(argtok);
argn++;
}
if (returnValue.find("arg") != std::string::npos && argValues.empty())
return;
productParams(settings, argValues, [&](const std::unordered_map<nonneg int, ValueFlow::Value>& arg) {
ValueFlow::Value value = evaluateLibraryFunction(arg, returnValue, settings, tok->isCpp());
if (value.isUninitValue())
return;
ValueFlow::Value::ValueKind kind = ValueFlow::Value::ValueKind::Known;
for (auto&& p : arg) {
if (p.second.isPossible())
kind = p.second.valueKind;
if (p.second.isInconclusive()) {
kind = p.second.valueKind;
break;
}
}
if (value.isImpossible() && kind != ValueFlow::Value::ValueKind::Known)
return;
if (!value.isImpossible())
value.valueKind = kind;
setTokenValue(tok, std::move(value), settings);
});
}
static void valueFlowSubFunction(const TokenList& tokenlist,
const SymbolDatabase& symboldatabase,
ErrorLogger& errorLogger,
const Settings& settings)
{
int id = 0;
for (auto it = symboldatabase.functionScopes.crbegin(); it != symboldatabase.functionScopes.crend(); ++it) {
const Scope* scope = *it;
const Function* function = scope->function;
if (!function)
continue;
for (auto* tok = const_cast<Token*>(scope->bodyStart); tok != scope->bodyEnd; tok = tok->next()) {
if (tok->isKeyword() || !Token::Match(tok, "%name% ("))
continue;
const Function* const calledFunction = tok->function();
if (!calledFunction) {
// library function?
const std::string& returnValue(settings.library.returnValue(tok));
if (!returnValue.empty())
valueFlowLibraryFunction(tok->next(), returnValue, settings);
continue;
}
const Scope* const calledFunctionScope = calledFunction->functionScope;
if (!calledFunctionScope)
continue;
id++;
std::unordered_map<const Variable*, std::list<ValueFlow::Value>> argvars;
// TODO: Rewrite this. It does not work well to inject 1 argument at a time.
const std::vector<const Token*>& callArguments = getArguments(tok);
for (int argnr = 0U; argnr < callArguments.size(); ++argnr) {
const Token* argtok = callArguments[argnr];
// Get function argument
const Variable* const argvar = calledFunction->getArgumentVar(argnr);
if (!argvar)
break;
// passing value(s) to function
std::list<ValueFlow::Value> argvalues(getFunctionArgumentValues(argtok));
// Remove non-local lifetimes
argvalues.remove_if([](const ValueFlow::Value& v) {
if (v.isLifetimeValue())
return !v.isLocalLifetimeValue() && !v.isSubFunctionLifetimeValue();
return false;
});
// Remove uninit values if argument is passed by value
if (argtok->variable() && !argtok->variable()->isPointer() && argvalues.size() == 1 &&
argvalues.front().isUninitValue()) {
if (CheckUninitVar::isVariableUsage(argtok, settings.library, false, CheckUninitVar::Alloc::NO_ALLOC, 0))
continue;
}
if (argvalues.empty())
continue;
// Error path..
for (ValueFlow::Value& v : argvalues) {
const std::string nr = std::to_string(argnr + 1) + getOrdinalText(argnr + 1);
v.errorPath.emplace_back(argtok,
"Calling function '" + calledFunction->name() + "', " + nr + " argument '" +
argtok->expressionString() + "' value is " + v.infoString());
v.path = 256 * v.path + id % 256;
// Change scope of lifetime values
if (v.isLifetimeValue())
v.lifetimeScope = ValueFlow::Value::LifetimeScope::SubFunction;
}
// passed values are not "known"..
lowerToPossible(argvalues);
argvars[argvar] = std::move(argvalues);
}
valueFlowInjectParameter(tokenlist, errorLogger, settings, calledFunctionScope, argvars);
}
}
}
static void valueFlowFunctionDefaultParameter(const TokenList& tokenlist, const SymbolDatabase& symboldatabase, ErrorLogger& errorLogger, const Settings& settings)
{
if (!tokenlist.isCPP())
return;
for (const Scope* scope : symboldatabase.functionScopes) {
const Function* function = scope->function;
if (!function)
continue;
for (nonneg int arg = function->minArgCount(); arg < function->argCount(); arg++) {
const Variable* var = function->getArgumentVar(arg);
if (var && var->hasDefault() && Token::Match(var->nameToken(), "%var% = %num%|%str%|%char%|%name% [,)]")) {
const std::list<ValueFlow::Value> &values = var->nameToken()->tokAt(2)->values();
std::list<ValueFlow::Value> argvalues;
for (const ValueFlow::Value &value : values) {
ValueFlow::Value v(value);
v.defaultArg = true;
v.changeKnownToPossible();
if (v.isPossible())
argvalues.push_back(std::move(v));
}
if (!argvalues.empty())
valueFlowInjectParameter(tokenlist, errorLogger, settings, var, scope, argvalues);
}
}
}
}
static const ValueFlow::Value* getKnownValueFromToken(const Token* tok)
{
if (!tok)
return nullptr;
auto it = std::find_if(tok->values().begin(), tok->values().end(), [&](const ValueFlow::Value& v) {
return (v.isIntValue() || v.isContainerSizeValue() || v.isFloatValue()) && v.isKnown();
});
if (it == tok->values().end())
return nullptr;
return std::addressof(*it);
}
static const ValueFlow::Value* getKnownValueFromTokens(const std::vector<const Token*>& toks)
{
if (toks.empty())
return nullptr;
const ValueFlow::Value* result = getKnownValueFromToken(toks.front());
if (!result)
return nullptr;
if (!std::all_of(std::next(toks.begin()), toks.end(), [&](const Token* tok) {
return std::any_of(tok->values().begin(), tok->values().end(), [&](const ValueFlow::Value& v) {
return v.equalValue(*result) && v.valueKind == result->valueKind;
});
}))
return nullptr;
return result;
}
static void setFunctionReturnValue(const Function* f, Token* tok, ValueFlow::Value v, const Settings& settings)
{
if (f->hasVirtualSpecifier()) {
if (v.isImpossible())
return;
v.setPossible();
} else if (!v.isImpossible()) {
v.setKnown();
}
v.errorPath.emplace_back(tok, "Calling function '" + f->name() + "' returns " + v.toString());
setTokenValue(tok, std::move(v), settings);
}
static void valueFlowFunctionReturn(TokenList& tokenlist, ErrorLogger& errorLogger, const Settings& settings)
{
for (Token* tok = tokenlist.back(); tok; tok = tok->previous()) {
if (tok->str() != "(" || !tok->astOperand1() || tok->isCast())
continue;
const Function* function = nullptr;
if (Token::Match(tok->previous(), "%name% ("))
function = tok->previous()->function();
else
function = tok->astOperand1()->function();
if (!function)
continue;
// TODO: Check if member variable is a pointer or reference
if (function->isImplicitlyVirtual() && !function->hasFinalSpecifier())
continue;
if (tok->hasKnownValue())
continue;
std::vector<const Token*> returns = Function::findReturns(function);
if (returns.empty())
continue;
if (const ValueFlow::Value* v = getKnownValueFromTokens(returns)) {
setFunctionReturnValue(function, tok, *v, settings);
continue;
}
// Arguments..
std::vector<const Token*> arguments = getArguments(tok);
ProgramMemory programMemory;
for (std::size_t i = 0; i < arguments.size(); ++i) {
const Variable* const arg = function->getArgumentVar(i);
if (!arg) {
if (settings.debugwarnings)
bailout(tokenlist, errorLogger, tok, "function return; unhandled argument type");
programMemory.clear();
break;
}
const ValueFlow::Value* v = getKnownValueFromToken(arguments[i]);
if (!v)
continue;
programMemory.setValue(arg->nameToken(), *v);
}
if (programMemory.empty() && !arguments.empty())
continue;
std::vector<ValueFlow::Value> values = execute(function->functionScope, programMemory, settings);
for (const ValueFlow::Value& v : values) {
if (v.isUninitValue())
continue;
setFunctionReturnValue(function, tok, v, settings);
}
}
}
static bool needsInitialization(const Variable* var)
{
if (!var)
return false;
if (var->hasDefault())
return false;
if (var->isPointer())
return true;
if (var->type() && var->type()->isUnionType())
return false;
if (!var->nameToken()->isCpp())
return true;
if (var->type() && var->type()->needInitialization == Type::NeedInitialization::True)
return true;
if (var->valueType()) {
if (var->valueType()->isPrimitive())
return true;
if (var->valueType()->type == ValueType::Type::POD)
return true;
if (var->valueType()->type == ValueType::Type::ITERATOR)
return true;
if (var->isStlType() && var->isArray()) {
if (const Token* ctt = var->valueType()->containerTypeToken) {
if (ctt->isStandardType())
return true;
const Type* ct = ctt->type();
if (ct && ct->needInitialization == Type::NeedInitialization::True)
return true;
}
}
}
return false;
}
static void addToErrorPath(ValueFlow::Value& value, const ValueFlow::Value& from)
{
std::unordered_set<const Token*> locations;
std::transform(value.errorPath.cbegin(),
value.errorPath.cend(),
std::inserter(locations, locations.begin()),
[](const ErrorPathItem& e) {
return e.first;
});
if (from.condition && !value.condition)
value.condition = from.condition;
std::copy_if(from.errorPath.cbegin(),
from.errorPath.cend(),
std::back_inserter(value.errorPath),
[&](const ErrorPathItem& e) {
return locations.insert(e.first).second;
});
}
static std::vector<Token*> findAllUsages(const Variable* var,
Token* start, // cppcheck-suppress constParameterPointer // FP
const Library& library)
{
// std::vector<Token*> result;
const Scope* scope = var->scope();
if (!scope)
return {};
return findTokensSkipDeadCode(library, start, scope->bodyEnd, [&](const Token* tok) {
return tok->varId() == var->declarationId();
});
}
static Token* findStartToken(const Variable* var, Token* start, const Library& library)
{
std::vector<Token*> uses = findAllUsages(var, start, library);
if (uses.empty())
return start;
Token* first = uses.front();
if (Token::findmatch(start, "goto|asm|setjmp|longjmp", first))
return start;
if (first != var->nameToken()) {
// if this is lhs in assignment then set first to the first token in LHS expression
Token* temp = first;
while (Token::Match(temp->astParent(), "[&*(]") && precedes(temp->astParent(), temp))
temp = temp->astParent();
if (Token::simpleMatch(temp->astParent(), "=") && precedes(temp, temp->astParent()))
first = temp;
}
// If there is only one usage
if (uses.size() == 1)
return first->previous();
const Scope* scope = first->scope();
// If first usage is in variable scope
if (scope == var->scope()) {
bool isLoopExpression = false;
for (const Token* parent = first; parent; parent = parent->astParent()) {
if (Token::simpleMatch(parent->astParent(), ";") &&
Token::simpleMatch(parent->astParent()->astParent(), ";") &&
Token::simpleMatch(parent->astParent()->astParent()->astParent(), "(") &&
Token::simpleMatch(parent->astParent()->astParent()->astParent()->astOperand1(), "for (") &&
parent == parent->astParent()->astParent()->astParent()->astOperand2()->astOperand2()->astOperand2()) {
isLoopExpression = true;
}
}
return isLoopExpression ? start : first->previous();
}
// If all uses are in the same scope
if (std::all_of(uses.begin() + 1, uses.end(), [&](const Token* tok) {
return tok->scope() == scope;
}))
return first->previous();
// Compute the outer scope
while (scope && scope->nestedIn != var->scope())
scope = scope->nestedIn;
if (!scope)
return start;
auto* tok = const_cast<Token*>(scope->bodyStart);
if (!tok)
return start;
if (Token::simpleMatch(tok->tokAt(-2), "} else {"))
tok = tok->linkAt(-2);
if (Token::simpleMatch(tok->previous(), ") {"))
return tok->linkAt(-1)->previous();
return tok;
}
static void valueFlowUninit(TokenList& tokenlist, ErrorLogger& errorLogger, const Settings& settings)
{
for (Token *tok = tokenlist.front(); tok; tok = tok->next()) {
if (!tok->scope()->isExecutable())
continue;
if (!Token::Match(tok, "%var% ;|["))
continue;
const Variable* var = tok->variable();
if (!var)
continue;
if (var->nameToken() != tok || var->isInit())
continue;
if (!needsInitialization(var))
continue;
if (!var->isLocal() || var->isStatic() || var->isExtern() || var->isReference() || var->isThrow())
continue;
ValueFlow::Value uninitValue;
uninitValue.setKnown();
uninitValue.valueType = ValueFlow::Value::ValueType::UNINIT;
uninitValue.tokvalue = tok;
if (var->isArray())
uninitValue.indirect = var->dimensions().size();
bool partial = false;
Token* start = findStartToken(var, tok->next(), settings.library);
std::map<Token*, ValueFlow::Value> partialReads;
if (const Scope* scope = var->typeScope()) {
if (Token::findsimplematch(scope->bodyStart, "union", scope->bodyEnd))
continue;
for (const Variable& memVar : scope->varlist) {
if (!memVar.isPublic())
continue;
// Skip array since we can't track partial initialization from nested subexpressions
if (memVar.isArray())
continue;
if (!needsInitialization(&memVar)) {
if (!var->isPointer())
partial = true;
continue;
}
auto partialReadsAnalyzer = std::make_shared<PartialReadContainer>();
auto analyzer = makeMemberExpressionAnalyzer(memVar.nameToken()->str(), tok, uninitValue, partialReadsAnalyzer, settings);
valueFlowGenericForward(start, tok->scope()->bodyEnd, analyzer, tokenlist, errorLogger, settings);
for (auto&& p : *partialReadsAnalyzer) {
Token* tok2 = p.first;
const ValueFlow::Value& v = p.second;
// Try to insert into map
auto pp = partialReads.emplace(tok2, v);
ValueFlow::Value& v2 = pp.first->second;
const bool inserted = pp.second;
// Merge the two values if it is already in map
if (!inserted) {
if (v.valueType != v2.valueType)
continue;
addToErrorPath(v2, v);
}
v2.subexpressions.push_back(memVar.nameToken()->str());
}
}
}
for (auto&& p : partialReads) {
Token* tok2 = p.first;
ValueFlow::Value& v = p.second;
setTokenValue(tok2, std::move(v), settings);
}
if (partial)
continue;
valueFlowForward(start, tok->scope()->bodyEnd, var->nameToken(), std::move(uninitValue), tokenlist, errorLogger, settings);
}
}
static bool isContainerSizeChanged(const Token* expr,
const Token* start,
const Token* end,
int indirect,
const Settings& settings,
int depth = 20);
static bool isContainerSizeChangedByFunction(const Token* tok,
int indirect,
const Settings& settings,
int depth = 20)
{
if (!tok->valueType())
return false;
if (!astIsContainer(tok))
return false;
// If we are accessing an element then we are not changing the container size
if (Token::Match(tok, "%name% . %name% (")) {
const Library::Container::Yield yield = getLibraryContainer(tok)->getYield(tok->strAt(2));
if (yield != Library::Container::Yield::NO_YIELD)
return false;
}
if (Token::simpleMatch(tok->astParent(), "["))
return false;
// address of variable
const bool addressOf = tok->valueType()->pointer || (tok->astParent() && tok->astParent()->isUnaryOp("&"));
int narg;
const Token * ftok = getTokenArgumentFunction(tok, narg);
if (!ftok)
return false; // not a function => variable not changed
const Function * fun = ftok->function();
if (fun && !fun->isImplicitlyVirtual()) {
const Variable *arg = fun->getArgumentVar(narg);
if (arg) {
const bool isPointer = addressOf || indirect > 0;
if (!arg->isReference() && !isPointer)
return false;
if (!isPointer && arg->isConst())
return false;
if (arg->valueType() && arg->valueType()->constness == 1)
return false;
const Scope * scope = fun->functionScope;
if (scope) {
// Argument not used
if (!arg->nameToken())
return false;
if (depth > 0)
return isContainerSizeChanged(arg->nameToken(),
scope->bodyStart,
scope->bodyEnd,
addressOf ? indirect + 1 : indirect,
settings,
depth - 1);
}
// Don't know => Safe guess
return true;
}
}
bool inconclusive = false;
const bool isChanged = isVariableChangedByFunctionCall(tok, indirect, settings, &inconclusive);
return (isChanged || inconclusive);
}
static const Token* parseBinaryIntOp(const Token* expr,
const std::function<std::vector<MathLib::bigint>(const Token*)>& eval,
MathLib::bigint& known)
{
if (!expr)
return nullptr;
if (!expr->astOperand1() || !expr->astOperand2())
return nullptr;
if (expr->astOperand1()->exprId() == 0 && expr->astOperand2()->exprId() == 0)
return nullptr;
std::vector<MathLib::bigint> x1 = eval(expr->astOperand1());
if (expr->astOperand1()->exprId() == 0 && x1.empty())
return nullptr;
std::vector<MathLib::bigint> x2 = eval(expr->astOperand2());
if (expr->astOperand2()->exprId() == 0 && x2.empty())
return nullptr;
const Token* varTok = nullptr;
if (!x1.empty() && x2.empty()) {
varTok = expr->astOperand2();
known = x1.front();
} else if (x1.empty() && !x2.empty()) {
varTok = expr->astOperand1();
known = x2.front();
}
return varTok;
}
const Token* ValueFlow::solveExprValue(const Token* expr,
const std::function<std::vector<MathLib::bigint>(const Token*)>& eval,
ValueFlow::Value& value)
{
if (!value.isIntValue() && !value.isIteratorValue() && !value.isSymbolicValue())
return expr;
if (value.isSymbolicValue() && !Token::Match(expr, "+|-"))
return expr;
MathLib::bigint intval = 0;
const Token* binaryTok = parseBinaryIntOp(expr, eval, intval);
const bool rhs = astIsRHS(binaryTok);
// If its on the rhs, then -1 multiplication is needed, which is not possible with simple delta analysis used currently for symbolic values
if (value.isSymbolicValue() && rhs && Token::simpleMatch(expr, "-"))
return expr;
if (binaryTok && expr->str().size() == 1) {
switch (expr->str()[0]) {
case '+': {
value.intvalue -= intval;
return ValueFlow::solveExprValue(binaryTok, eval, value);
}
case '-': {
if (rhs)
value.intvalue = intval - value.intvalue;
else
value.intvalue += intval;
return ValueFlow::solveExprValue(binaryTok, eval, value);
}
case '*': {
if (intval == 0)
break;
value.intvalue /= intval;
return ValueFlow::solveExprValue(binaryTok, eval, value);
}
case '^': {
value.intvalue ^= intval;
return ValueFlow::solveExprValue(binaryTok, eval, value);
}
}
}
return expr;
}
bool ValueFlow::isContainerSizeChanged(const Token* tok, int indirect, const Settings& settings, int depth)
{
if (!tok)
return false;
if (!tok->valueType() || !tok->valueType()->container)
return true;
if (astIsLHS(tok) && Token::Match(tok->astParent(), "%assign%|<<"))
return true;
if (astIsLHS(tok) && Token::simpleMatch(tok->astParent(), "["))
return tok->valueType()->container->stdAssociativeLike;
const Library::Container::Action action = astContainerAction(tok);
switch (action) {
case Library::Container::Action::RESIZE:
case Library::Container::Action::CLEAR:
case Library::Container::Action::PUSH:
case Library::Container::Action::POP:
case Library::Container::Action::CHANGE:
case Library::Container::Action::INSERT:
case Library::Container::Action::ERASE:
case Library::Container::Action::APPEND:
return true;
case Library::Container::Action::NO_ACTION:
// Is this an unknown member function call?
if (astIsLHS(tok) && Token::Match(tok->astParent(), ". %name% (")) {
const Library::Container::Yield yield = astContainerYield(tok);
return yield == Library::Container::Yield::NO_YIELD;
}
break;
case Library::Container::Action::FIND:
case Library::Container::Action::FIND_CONST:
case Library::Container::Action::CHANGE_CONTENT:
case Library::Container::Action::CHANGE_INTERNAL:
break;
}
return isContainerSizeChangedByFunction(tok, indirect, settings, depth);
}
static bool isContainerSizeChanged(const Token* expr,
const Token* start,
const Token* end,
int indirect,
const Settings& settings,
int depth)
{
for (const Token *tok = start; tok != end; tok = tok->next()) {
if (tok->exprId() != expr->exprId() && !isAliasOf(tok, expr))
continue;
if (ValueFlow::isContainerSizeChanged(tok, indirect, settings, depth))
return true;
}
return false;
}
static void valueFlowSmartPointer(TokenList &tokenlist, ErrorLogger & errorLogger, const Settings &settings)
{
for (Token *tok = tokenlist.front(); tok; tok = tok->next()) {
if (!tok->scope())
continue;
if (!tok->scope()->isExecutable())
continue;
if (!astIsSmartPointer(tok))
continue;
if (tok->variable() && Token::Match(tok, "%var% (|{|;")) {
const Variable* var = tok->variable();
if (!var->isSmartPointer())
continue;
if (var->nameToken() == tok) {
if (Token::Match(tok, "%var% (|{") && tok->next()->astOperand2() &&
tok->next()->astOperand2()->str() != ",") {
Token* inTok = tok->next()->astOperand2();
const std::list<ValueFlow::Value>& values = inTok->values();
const bool constValue = inTok->isNumber();
valueFlowForwardAssign(inTok, var, values, constValue, true, tokenlist, errorLogger, settings);
} else if (Token::Match(tok, "%var% ;")) {
ValueFlow::Value v(0);
v.setKnown();
valueFlowForwardAssign(tok, var, {std::move(v)}, false, true, tokenlist, errorLogger, settings);
}
}
} else if (astIsLHS(tok) && Token::Match(tok->astParent(), ". %name% (") &&
tok->astParent()->originalName() != "->") {
std::vector<const Variable*> vars = getVariables(tok);
Token* ftok = tok->astParent()->tokAt(2);
if (Token::simpleMatch(tok->astParent(), ". reset (")) {
if (Token::simpleMatch(ftok, "( )")) {
ValueFlow::Value v(0);
v.setKnown();
valueFlowForwardAssign(ftok, tok, std::move(vars), {std::move(v)}, false, tokenlist, errorLogger, settings);
} else {
tok->removeValues(std::mem_fn(&ValueFlow::Value::isIntValue));
Token* inTok = ftok->astOperand2();
if (!inTok)
continue;
const std::list<ValueFlow::Value>& values = inTok->values();
valueFlowForwardAssign(inTok, tok, std::move(vars), values, false, tokenlist, errorLogger, settings);
}
} else if (Token::simpleMatch(tok->astParent(), ". release ( )")) {
const Token* parent = ftok->astParent();
bool hasParentReset = false;
while (parent) {
if (Token::Match(parent->tokAt(-2), ". release|reset (") &&
parent->tokAt(-2)->astOperand1()->exprId() == tok->exprId()) {
hasParentReset = true;
break;
}
parent = parent->astParent();
}
if (hasParentReset)
continue;
ValueFlow::Value v(0);
v.setKnown();
valueFlowForwardAssign(ftok, tok, std::move(vars), {std::move(v)}, false, tokenlist, errorLogger, settings);
} else if (Token::simpleMatch(tok->astParent(), ". get ( )")) {
ValueFlow::Value v = makeSymbolic(tok);
setTokenValue(tok->astParent()->tokAt(2), std::move(v), settings);
}
} else if (Token::Match(tok->previous(), "%name%|> (|{") && astIsSmartPointer(tok) &&
astIsSmartPointer(tok->astOperand1())) {
std::vector<const Token*> args = getArguments(tok);
if (args.empty())
continue;
for (const ValueFlow::Value& v : args.front()->values())
setTokenValue(tok, v, settings);
}
}
}
static Library::Container::Yield findIteratorYield(Token* tok, const Token*& ftok, const Settings& settings)
{
auto yield = astContainerYield(tok, &ftok);
if (ftok)
return yield;
if (!tok->astParent())
return yield;
// begin/end free functions
return astFunctionYield(tok->astParent()->previous(), settings, &ftok);
}
static void valueFlowIterators(TokenList& tokenlist, const Settings& settings)
{
for (Token* tok = tokenlist.front(); tok; tok = tok->next()) {
if (!tok->scope())
continue;
if (!tok->scope()->isExecutable())
continue;
if (!astIsContainer(tok))
continue;
const Token* ftok = nullptr;
const Library::Container::Yield yield = findIteratorYield(tok, ftok, settings);
if (!ftok)
continue;
if (yield == Library::Container::Yield::START_ITERATOR) {
ValueFlow::Value v(0);
v.setKnown();
v.valueType = ValueFlow::Value::ValueType::ITERATOR_START;
setTokenValue(const_cast<Token*>(ftok)->next(), std::move(v), settings);
} else if (yield == Library::Container::Yield::END_ITERATOR) {
ValueFlow::Value v(0);
v.setKnown();
v.valueType = ValueFlow::Value::ValueType::ITERATOR_END;
setTokenValue(const_cast<Token*>(ftok)->next(), std::move(v), settings);
}
}
}
static std::list<ValueFlow::Value> getIteratorValues(std::list<ValueFlow::Value> values,
const ValueFlow::Value::ValueKind* kind = nullptr)
{
values.remove_if([&](const ValueFlow::Value& v) {
if (kind && v.valueKind != *kind)
return true;
return !v.isIteratorValue();
});
return values;
}
struct IteratorConditionHandler : SimpleConditionHandler {
std::vector<Condition> parse(const Token* tok, const Settings& /*settings*/) const override {
Condition cond;
if (Token::Match(tok, "==|!=")) {
if (!tok->astOperand1() || !tok->astOperand2())
return {};
constexpr ValueFlow::Value::ValueKind kind = ValueFlow::Value::ValueKind::Known;
std::list<ValueFlow::Value> values = getIteratorValues(tok->astOperand1()->values(), &kind);
if (!values.empty()) {
cond.vartok = tok->astOperand2();
} else {
values = getIteratorValues(tok->astOperand2()->values(), &kind);
if (!values.empty())
cond.vartok = tok->astOperand1();
}
for (ValueFlow::Value& v:values) {
v.setPossible();
v.assumeCondition(tok);
}
cond.true_values = values;
cond.false_values = std::move(values);
}
return {std::move(cond)};
}
};
static void valueFlowIteratorInfer(TokenList& tokenlist, const Settings& settings)
{
for (Token* tok = tokenlist.front(); tok; tok = tok->next()) {
if (!tok->scope())
continue;
if (!tok->scope()->isExecutable())
continue;
std::list<ValueFlow::Value> values = getIteratorValues(tok->values());
values.remove_if([&](const ValueFlow::Value& v) {
if (!v.isImpossible())
return true;
if (!v.condition)
return true;
if (v.bound != ValueFlow::Value::Bound::Point)
return true;
if (v.isIteratorEndValue() && v.intvalue <= 0)
return true;
if (v.isIteratorStartValue() && v.intvalue >= 0)
return true;
return false;
});
for (ValueFlow::Value& v : values) {
v.setPossible();
if (v.isIteratorStartValue())
v.intvalue++;
if (v.isIteratorEndValue())
v.intvalue--;
setTokenValue(tok, std::move(v), settings);
}
}
}
static std::vector<ValueFlow::Value> getContainerValues(const Token* tok)
{
std::vector<ValueFlow::Value> values;
if (tok) {
std::copy_if(tok->values().cbegin(),
tok->values().cend(),
std::back_inserter(values),
std::mem_fn(&ValueFlow::Value::isContainerSizeValue));
}
return values;
}
static ValueFlow::Value makeContainerSizeValue(MathLib::bigint s, bool known = true)
{
ValueFlow::Value value(s);
value.valueType = ValueFlow::Value::ValueType::CONTAINER_SIZE;
if (known)
value.setKnown();
return value;
}
static std::vector<ValueFlow::Value> makeContainerSizeValue(const Token* tok, bool known = true)
{
if (tok->hasKnownIntValue())
return {makeContainerSizeValue(tok->values().front().intvalue, known)};
return {};
}
static std::vector<ValueFlow::Value> getContainerSizeFromConstructorArgs(const std::vector<const Token*>& args,
const Library::Container* container,
bool known)
{
if (astIsIntegral(args[0], false)) { // { count, i } or { count }
if (args.size() == 1 || (args.size() > 1 && !astIsIntegral(args[1], false)))
return {makeContainerSizeValue(args[0], known)};
} else if (astIsContainer(args[0]) && args.size() == 1) { // copy constructor
return getContainerValues(args[0]);
} else if (isIteratorPair(args)) {
std::vector<ValueFlow::Value> result = getContainerValues(args[0]);
if (!result.empty())
return result;
// (ptr, ptr + size)
if (astIsPointer(args[0]) && args[0]->exprId() != 0) {
// (ptr, ptr) is empty
// TODO: Use lifetime values to check if it points to the same address
if (args[0]->exprId() == args[1]->exprId())
return {makeContainerSizeValue(MathLib::bigint{0}, known)};
// TODO: Insert iterator positions for pointers
if (Token::simpleMatch(args[1], "+")) {
nonneg int const eid = args[0]->exprId();
const Token* vartok = args[1]->astOperand1();
const Token* sizetok = args[1]->astOperand2();
if (sizetok->exprId() == eid)
std::swap(vartok, sizetok);
if (vartok->exprId() == eid && sizetok->hasKnownIntValue())
return {makeContainerSizeValue(sizetok, known)};
}
}
} else if (container->stdStringLike) {
if (astIsPointer(args[0])) {
if (args.size() == 1 && args[0]->tokType() == Token::Type::eString)
return {makeContainerSizeValue(Token::getStrLength(args[0]), known)};
if (args.size() == 2 && astIsIntegral(args[1], false)) // { char*, count }
return {makeContainerSizeValue(args[1], known)};
} else if (astIsContainer(args[0])) {
if (args.size() == 1) // copy constructor { str }
return getContainerValues(args[0]);
if (args.size() == 3) // { str, pos, count }
return {makeContainerSizeValue(args[2], known)};
// TODO: { str, pos }, { ..., alloc }
}
}
return {};
}
static bool valueFlowIsSameContainerType(const ValueType& contType, const Token* tok, const Settings& settings)
{
if (!tok || !tok->valueType() || !tok->valueType()->containerTypeToken)
return true;
const ValueType tokType = ValueType::parseDecl(tok->valueType()->containerTypeToken, settings);
return contType.isTypeEqual(&tokType) || tokType.type == ValueType::Type::UNKNOWN_TYPE;
}
static std::vector<ValueFlow::Value> getInitListSize(const Token* tok,
const ValueType* valueType,
const Settings& settings,
bool known = true)
{
std::vector<const Token*> args = getArguments(tok);
if (args.empty())
return {makeContainerSizeValue(MathLib::bigint{0}, known)};
bool initList = tok->str() == "{";
// Try to disambiguate init list from constructor
if (initList && args.size() < 4) {
initList = !isIteratorPair(args);
const Token* containerTypeToken = valueType->containerTypeToken;
if (valueType->container->stdStringLike) {
initList = astIsGenericChar(args[0]) && !astIsPointer(args[0]);
} else if (containerTypeToken) {
ValueType vt = ValueType::parseDecl(containerTypeToken, settings);
if (vt.pointer > 0 && astIsPointer(args[0]))
initList = true;
else if (vt.type == ValueType::ITERATOR && astIsIterator(args[0]))
initList = true;
else if (vt.isIntegral() && astIsIntegral(args[0], false))
initList = true;
else if (args.size() == 1 && valueFlowIsSameContainerType(vt, tok->astOperand2(), settings))
initList = false; // copy ctor
else if (args.size() == 2 && (!args[0]->valueType() || !args[1]->valueType())) // might be unknown iterators
initList = false;
}
}
if (!initList)
return getContainerSizeFromConstructorArgs(args, valueType->container, known);
return {makeContainerSizeValue(args.size(), known)};
}
static std::vector<ValueFlow::Value> getContainerSizeFromConstructor(const Token* tok,
const ValueType* valueType,
const Settings& settings,
bool known = true)
{
std::vector<const Token*> args = getArguments(tok);
if (args.empty())
return {makeContainerSizeValue(MathLib::bigint{0}, known)};
// Init list in constructor
if (args.size() == 1 && Token::simpleMatch(args[0], "{"))
return getInitListSize(args[0], valueType, settings, known);
return getContainerSizeFromConstructorArgs(args, valueType->container, known);
}
static void valueFlowContainerSetTokValue(const TokenList& tokenlist, ErrorLogger& errorLogger, const Settings& settings, const Token* tok, Token* initList)
{
ValueFlow::Value value;
value.valueType = ValueFlow::Value::ValueType::TOK;
value.tokvalue = initList;
if (astIsContainerString(tok) && Token::simpleMatch(initList, "{") && Token::Match(initList->astOperand2(), "%str%")) {
value.tokvalue = initList->astOperand2();
}
value.setKnown();
Token* start = initList->link() ? initList->link() : initList->next();
if (tok->variable() && tok->variable()->isConst()) {
valueFlowForwardConst(start, tok->variable()->scope()->bodyEnd, tok->variable(), {std::move(value)}, settings);
} else {
valueFlowForward(start, tok, std::move(value), tokenlist, errorLogger, settings);
}
}
static const Scope* getFunctionScope(const Scope* scope) {
while (scope && scope->type != Scope::ScopeType::eFunction)
scope = scope->nestedIn;
return scope;
}
static void valueFlowContainerSize(const TokenList& tokenlist,
const SymbolDatabase& symboldatabase,
ErrorLogger& errorLogger,
const Settings& settings,
const std::set<const Scope*>& skippedFunctions)
{
// declaration
for (const Variable *var : symboldatabase.variableList()) {
if (!var)
continue;
if (!var->scope() || !var->scope()->bodyEnd || !var->scope()->bodyStart)
continue;
if (!var->valueType() || !var->valueType()->container)
continue;
if (!astIsContainer(var->nameToken()))
continue;
if (skippedFunctions.count(getFunctionScope(var->scope())))
continue;
bool known = true;
MathLib::bigint size = 0;
const bool nonLocal = !var->isLocal() || var->isPointer() || var->isReference() || var->isStatic();
bool constSize = var->isConst() && !nonLocal;
bool staticSize = false;
if (var->valueType()->container->size_templateArgNo >= 0) {
staticSize = true;
constSize = true;
size = -1;
if (var->dimensions().size() == 1) {
const Dimension& dim = var->dimensions().front();
if (dim.known) {
size = dim.num;
} else if (dim.tok && dim.tok->hasKnownIntValue()) {
size = dim.tok->values().front().intvalue;
}
}
if (size < 0)
continue;
}
if (!staticSize && nonLocal)
continue;
auto* nameToken = const_cast<Token*>(var->nameToken());
if (nameToken->hasKnownValue(ValueFlow::Value::ValueType::CONTAINER_SIZE))
continue;
if (!staticSize) {
if (!Token::Match(nameToken, "%name% ;") &&
!(Token::Match(nameToken, "%name% {") && Token::simpleMatch(nameToken->linkAt(1), "} ;")) &&
!Token::Match(nameToken, "%name% ("))
continue;
}
if (Token::Match(nameToken->astTop()->previous(), "for|while"))
known = !isVariableChanged(var, settings);
std::vector<ValueFlow::Value> values{ValueFlow::Value{size}};
values.back().valueType = ValueFlow::Value::ValueType::CONTAINER_SIZE;
if (known)
values.back().setKnown();
if (!staticSize) {
if (Token::simpleMatch(nameToken->next(), "{")) {
Token* initList = nameToken->next();
valueFlowContainerSetTokValue(tokenlist, errorLogger, settings, nameToken, initList);
values = getInitListSize(initList, var->valueType(), settings, known);
} else if (Token::simpleMatch(nameToken->next(), "(")) {
const Token* constructorArgs = nameToken->next();
values = getContainerSizeFromConstructor(constructorArgs, var->valueType(), settings, known);
}
}
if (constSize) {
valueFlowForwardConst(nameToken->next(), var->scope()->bodyEnd, var, values, settings);
continue;
}
for (const ValueFlow::Value& value : values) {
valueFlowForward(nameToken->next(), var->nameToken(), value, tokenlist, errorLogger, settings);
}
}
auto forwardMinimumContainerSize = [&](MathLib::bigint size, Token* opTok, const Token* exprTok) -> void {
if (size == 0)
return;
ValueFlow::Value value(size - 1);
value.valueType = ValueFlow::Value::ValueType::CONTAINER_SIZE;
value.bound = ValueFlow::Value::Bound::Upper;
value.setImpossible();
Token* next = nextAfterAstRightmostLeaf(opTok);
if (!next)
next = opTok->next();
valueFlowForward(next, exprTok, std::move(value), tokenlist, errorLogger, settings);
};
// after assignment
for (const Scope *functionScope : symboldatabase.functionScopes) {
for (auto* tok = const_cast<Token*>(functionScope->bodyStart); tok != functionScope->bodyEnd; tok = tok->next()) {
if (Token::Match(tok, "%name%|;|{|} %var% = %str% ;")) {
Token* containerTok = tok->next();
if (containerTok->exprId() == 0)
continue;
if (containerTok->valueType() && containerTok->valueType()->container &&
containerTok->valueType()->container->stdStringLike) {
valueFlowContainerSetTokValue(tokenlist, errorLogger, settings, containerTok, containerTok->tokAt(2));
ValueFlow::Value value(Token::getStrLength(containerTok->tokAt(2)));
value.valueType = ValueFlow::Value::ValueType::CONTAINER_SIZE;
value.setKnown();
valueFlowForward(containerTok->next(), containerTok, std::move(value), tokenlist, errorLogger, settings);
}
} else if (Token::Match(tok->previous(), ">|return (|{") && astIsContainer(tok) && getLibraryContainer(tok)->size_templateArgNo < 0) {
std::vector<ValueFlow::Value> values;
if (Token::simpleMatch(tok, "{")) {
values = getInitListSize(tok, tok->valueType(), settings, true);
ValueFlow::Value value;
value.valueType = ValueFlow::Value::ValueType::TOK;
value.tokvalue = tok;
value.setKnown();
values.push_back(value);
} else if (Token::simpleMatch(tok, "(")) {
const Token* constructorArgs = tok;
values = getContainerSizeFromConstructor(constructorArgs, tok->valueType(), settings, true);
}
for (const ValueFlow::Value& value : values)
setTokenValue(tok, value, settings);
} else if (Token::Match(tok, ";|{|} %var% =") && Token::Match(tok->tokAt(2)->astOperand2(), "[({]") &&
// init list
((tok->tokAt(2) == tok->tokAt(2)->astOperand2()->astParent() && !tok->tokAt(2)->astOperand2()->astOperand2() && tok->tokAt(2)->astOperand2()->str() == "{") ||
// constructor
(!Token::simpleMatch(tok->tokAt(2)->astOperand2()->astOperand1(), ".") && settings.library.detectContainer(tok->tokAt(3))))) {
Token* containerTok = tok->next();
if (containerTok->exprId() == 0)
continue;
if (astIsContainer(containerTok) && containerTok->valueType()->container->size_templateArgNo < 0) {
Token* rhs = tok->tokAt(2)->astOperand2();
std::vector<ValueFlow::Value> values = getInitListSize(rhs, containerTok->valueType(), settings);
valueFlowContainerSetTokValue(tokenlist, errorLogger, settings, containerTok, rhs);
for (const ValueFlow::Value& value : values)
valueFlowForward(containerTok->next(), containerTok, value, tokenlist, errorLogger, settings);
}
} else if (Token::Match(tok, ". %name% (") && tok->astOperand1() && tok->astOperand1()->valueType() &&
tok->astOperand1()->valueType()->container) {
const Token* containerTok = tok->astOperand1();
if (containerTok->exprId() == 0)
continue;
if (containerTok->variable() && containerTok->variable()->isArray())
continue;
const Library::Container::Action action = containerTok->valueType()->container->getAction(tok->strAt(1));
if (action == Library::Container::Action::CLEAR) {
ValueFlow::Value value(0);
value.valueType = ValueFlow::Value::ValueType::CONTAINER_SIZE;
value.setKnown();
valueFlowForward(tok->next(), containerTok, std::move(value), tokenlist, errorLogger, settings);
} else if (action == Library::Container::Action::RESIZE && tok->tokAt(2)->astOperand2() &&
tok->tokAt(2)->astOperand2()->hasKnownIntValue()) {
ValueFlow::Value value(tok->tokAt(2)->astOperand2()->values().front());
value.valueType = ValueFlow::Value::ValueType::CONTAINER_SIZE;
value.setKnown();
valueFlowForward(tok->linkAt(2), containerTok, std::move(value), tokenlist, errorLogger, settings);
} else if (action == Library::Container::Action::PUSH && !isIteratorPair(getArguments(tok->tokAt(2)))) {
ValueFlow::Value value(0);
value.valueType = ValueFlow::Value::ValueType::CONTAINER_SIZE;
value.setImpossible();
valueFlowForward(tok->linkAt(2), containerTok, std::move(value), tokenlist, errorLogger, settings);
}
// TODO: handle more actions?
} else if (tok->str() == "+=" && astIsContainer(tok->astOperand1())) {
const Token* containerTok = tok->astOperand1();
const Token* valueTok = tok->astOperand2();
const MathLib::bigint size = ValueFlow::valueFlowGetStrLength(valueTok);
forwardMinimumContainerSize(size, tok, containerTok);
} else if (tok->str() == "=" && Token::simpleMatch(tok->astOperand2(), "+") && astIsContainerString(tok)) {
const Token* tok2 = tok->astOperand2();
MathLib::bigint size = 0;
while (Token::simpleMatch(tok2, "+") && tok2->astOperand2()) {
size += ValueFlow::valueFlowGetStrLength(tok2->astOperand2());
tok2 = tok2->astOperand1();
}
size += ValueFlow::valueFlowGetStrLength(tok2);
forwardMinimumContainerSize(size, tok, tok->astOperand1());
}
}
}
}
struct ContainerConditionHandler : ConditionHandler {
std::vector<Condition> parse(const Token* tok, const Settings& settings) const override
{
std::vector<Condition> conds;
parseCompareEachInt(tok, [&](const Token* vartok, ValueFlow::Value true_value, ValueFlow::Value false_value) {
vartok = settings.library.getContainerFromYield(vartok, Library::Container::Yield::SIZE);
if (!vartok)
return;
true_value.valueType = ValueFlow::Value::ValueType::CONTAINER_SIZE;
false_value.valueType = ValueFlow::Value::ValueType::CONTAINER_SIZE;
Condition cond;
cond.true_values.push_back(std::move(true_value));
cond.false_values.push_back(std::move(false_value));
cond.vartok = vartok;
conds.push_back(std::move(cond));
});
if (!conds.empty())
return conds;
const Token* vartok = nullptr;
// Empty check
if (tok->str() == "(") {
vartok = settings.library.getContainerFromYield(tok, Library::Container::Yield::EMPTY);
// TODO: Handle .size()
if (!vartok)
return {};
const Token *parent = tok->astParent();
while (parent) {
if (Token::Match(parent, "%comp%"))
return {};
parent = parent->astParent();
}
ValueFlow::Value value(tok, 0LL);
value.valueType = ValueFlow::Value::ValueType::CONTAINER_SIZE;
Condition cond;
cond.true_values.emplace_back(value);
cond.false_values.emplace_back(std::move(value));
cond.vartok = vartok;
cond.inverted = true;
return {std::move(cond)};
}
// String compare
if (Token::Match(tok, "==|!=")) {
const Token *strtok = nullptr;
if (Token::Match(tok->astOperand1(), "%str%")) {
strtok = tok->astOperand1();
vartok = tok->astOperand2();
} else if (Token::Match(tok->astOperand2(), "%str%")) {
strtok = tok->astOperand2();
vartok = tok->astOperand1();
}
if (!strtok)
return {};
if (!astIsContainer(vartok))
return {};
ValueFlow::Value value(tok, Token::getStrLength(strtok));
value.valueType = ValueFlow::Value::ValueType::CONTAINER_SIZE;
Condition cond;
cond.false_values.emplace_back(value);
cond.true_values.emplace_back(std::move(value));
cond.vartok = vartok;
cond.impossible = false;
return {std::move(cond)};
}
return {};
}
};
static void valueFlowDynamicBufferSize(const TokenList& tokenlist, const SymbolDatabase& symboldatabase, ErrorLogger& errorLogger, const Settings& settings)
{
auto getBufferSizeFromAllocFunc = [&](const Token* funcTok) -> MathLib::bigint {
MathLib::bigint sizeValue = -1;
const Library::AllocFunc* allocFunc = settings.library.getAllocFuncInfo(funcTok);
if (!allocFunc)
allocFunc = settings.library.getReallocFuncInfo(funcTok);
if (!allocFunc || allocFunc->bufferSize == Library::AllocFunc::BufferSize::none)
return sizeValue;
const std::vector<const Token*> args = getArguments(funcTok);
const Token* const arg1 = (args.size() >= allocFunc->bufferSizeArg1) ? args[allocFunc->bufferSizeArg1 - 1] : nullptr;
const Token* const arg2 = (args.size() >= allocFunc->bufferSizeArg2) ? args[allocFunc->bufferSizeArg2 - 1] : nullptr;
switch (allocFunc->bufferSize) {
case Library::AllocFunc::BufferSize::none:
break;
case Library::AllocFunc::BufferSize::malloc:
if (arg1 && arg1->hasKnownIntValue())
sizeValue = arg1->getKnownIntValue();
break;
case Library::AllocFunc::BufferSize::calloc:
if (arg1 && arg2 && arg1->hasKnownIntValue() && arg2->hasKnownIntValue())
sizeValue = arg1->getKnownIntValue() * arg2->getKnownIntValue();
break;
case Library::AllocFunc::BufferSize::strdup:
if (arg1 && arg1->hasKnownValue()) {
const ValueFlow::Value& value = arg1->values().back();
if (value.isTokValue() && value.tokvalue->tokType() == Token::eString)
sizeValue = Token::getStrLength(value.tokvalue) + 1; // Add one for the null terminator
}
break;
}
return sizeValue;
};
auto getBufferSizeFromNew = [&](const Token* newTok) -> MathLib::bigint {
MathLib::bigint sizeValue = -1, numElem = -1;
if (newTok && newTok->astOperand1()) { // number of elements
const Token* bracTok = nullptr, *typeTok = nullptr;
if (newTok->astOperand1()->str() == "[")
bracTok = newTok->astOperand1();
else if (Token::Match(newTok->astOperand1(), "(|{")) {
if (newTok->astOperand1()->astOperand1() && newTok->astOperand1()->astOperand1()->str() == "[")
bracTok = newTok->astOperand1()->astOperand1();
else
typeTok = newTok->astOperand1()->astOperand1();
}
else
typeTok = newTok->astOperand1();
if (bracTok && bracTok->astOperand2() && bracTok->astOperand2()->hasKnownIntValue())
numElem = bracTok->astOperand2()->getKnownIntValue();
else if (Token::Match(typeTok, "%type%"))
numElem = 1;
}
if (numElem >= 0 && newTok->astParent() && newTok->astParent()->isAssignmentOp()) { // size of the allocated type
const Token* typeTok = newTok->astParent()->astOperand1(); // TODO: implement fallback for e.g. "auto p = new Type;"
if (!typeTok || !typeTok->varId())
typeTok = newTok->astParent()->previous(); // hack for "int** z = ..."
if (typeTok && typeTok->valueType()) {
const MathLib::bigint typeSize = typeTok->valueType()->typeSize(settings.platform, typeTok->valueType()->pointer > 1);
if (typeSize >= 0)
sizeValue = numElem * typeSize;
}
}
return sizeValue;
};
for (const Scope *functionScope : symboldatabase.functionScopes) {
for (const Token *tok = functionScope->bodyStart; tok != functionScope->bodyEnd; tok = tok->next()) {
if (!Token::Match(tok, "[;{}] %var% ="))
continue;
if (!tok->next()->variable())
continue;
const Token *rhs = tok->tokAt(2)->astOperand2();
while (rhs && rhs->isCast())
rhs = rhs->astOperand2() ? rhs->astOperand2() : rhs->astOperand1();
if (!rhs)
continue;
const bool isNew = rhs->isCpp() && rhs->str() == "new";
if (!isNew && !Token::Match(rhs->previous(), "%name% ("))
continue;
const MathLib::bigint sizeValue = isNew ? getBufferSizeFromNew(rhs) : getBufferSizeFromAllocFunc(rhs->previous());
if (sizeValue < 0)
continue;
ValueFlow::Value value(sizeValue);
value.errorPath.emplace_back(tok->tokAt(2), "Assign " + tok->strAt(1) + ", buffer with size " + std::to_string(sizeValue));
value.valueType = ValueFlow::Value::ValueType::BUFFER_SIZE;
value.setKnown();
valueFlowForward(const_cast<Token*>(rhs), functionScope->bodyEnd, tok->next(), std::move(value), tokenlist, errorLogger, settings);
}
}
}
static bool getMinMaxValues(const std::string& typestr,
const Settings& settings,
bool cpp,
MathLib::bigint& minvalue,
MathLib::bigint& maxvalue)
{
TokenList typeTokens(&settings);
std::istringstream istr(typestr + ";");
if (!typeTokens.createTokens(istr, cpp ? Standards::Language::CPP : Standards::Language::C))
return false;
typeTokens.simplifyPlatformTypes();
typeTokens.simplifyStdType();
const ValueType& vt = ValueType::parseDecl(typeTokens.front(), settings);
return ValueFlow::getMinMaxValues(&vt, settings.platform, minvalue, maxvalue);
}
static void valueFlowSafeFunctions(const TokenList& tokenlist, const SymbolDatabase& symboldatabase, ErrorLogger& errorLogger, const Settings& settings)
{
for (const Scope *functionScope : symboldatabase.functionScopes) {
if (!functionScope->bodyStart)
continue;
const Function *function = functionScope->function;
if (!function)
continue;
const bool safe = function->isSafe(settings);
const bool all = safe && settings.platform.type != Platform::Type::Unspecified;
for (const Variable &arg : function->argumentList) {
if (!arg.nameToken() || !arg.valueType())
continue;
if (arg.valueType()->type == ValueType::Type::CONTAINER) {
if (!safe)
continue;
std::list<ValueFlow::Value> argValues;
argValues.emplace_back(0);
argValues.back().valueType = ValueFlow::Value::ValueType::CONTAINER_SIZE;
argValues.back().errorPath.emplace_back(arg.nameToken(), "Assuming " + arg.name() + " is empty");
argValues.back().safe = true;
argValues.emplace_back(1000000);
argValues.back().valueType = ValueFlow::Value::ValueType::CONTAINER_SIZE;
argValues.back().errorPath.emplace_back(arg.nameToken(), "Assuming " + arg.name() + " size is 1000000");
argValues.back().safe = true;
for (const ValueFlow::Value &value : argValues)
valueFlowForward(const_cast<Token*>(functionScope->bodyStart), arg.nameToken(), value, tokenlist, errorLogger, settings);
continue;
}
MathLib::bigint low, high;
bool isLow = arg.nameToken()->getCppcheckAttribute(TokenImpl::CppcheckAttributes::Type::LOW, low);
bool isHigh = arg.nameToken()->getCppcheckAttribute(TokenImpl::CppcheckAttributes::Type::HIGH, high);
if (!isLow && !isHigh && !all)
continue;
const bool safeLow = !isLow;
const bool safeHigh = !isHigh;
if ((!isLow || !isHigh) && all) {
MathLib::bigint minValue, maxValue;
if (ValueFlow::getMinMaxValues(arg.valueType(), settings.platform, minValue, maxValue)) {
if (!isLow)
low = minValue;
if (!isHigh)
high = maxValue;
isLow = isHigh = true;
} else if (arg.valueType()->type == ValueType::Type::FLOAT || arg.valueType()->type == ValueType::Type::DOUBLE || arg.valueType()->type == ValueType::Type::LONGDOUBLE) {
std::list<ValueFlow::Value> argValues;
argValues.emplace_back(0);
argValues.back().valueType = ValueFlow::Value::ValueType::FLOAT;
argValues.back().floatValue = isLow ? low : -1E25;
argValues.back().errorPath.emplace_back(arg.nameToken(), "Safe checks: Assuming argument has value " + MathLib::toString(argValues.back().floatValue));
argValues.back().safe = true;
argValues.emplace_back(0);
argValues.back().valueType = ValueFlow::Value::ValueType::FLOAT;
argValues.back().floatValue = isHigh ? high : 1E25;
argValues.back().errorPath.emplace_back(arg.nameToken(), "Safe checks: Assuming argument has value " + MathLib::toString(argValues.back().floatValue));
argValues.back().safe = true;
valueFlowForward(const_cast<Token*>(functionScope->bodyStart->next()),
functionScope->bodyEnd,
arg.nameToken(),
std::move(argValues),
tokenlist,
errorLogger,
settings);
continue;
}
}
std::list<ValueFlow::Value> argValues;
if (isLow) {
argValues.emplace_back(low);
argValues.back().errorPath.emplace_back(arg.nameToken(), std::string(safeLow ? "Safe checks: " : "") + "Assuming argument has value " + std::to_string(low));
argValues.back().safe = safeLow;
}
if (isHigh) {
argValues.emplace_back(high);
argValues.back().errorPath.emplace_back(arg.nameToken(), std::string(safeHigh ? "Safe checks: " : "") + "Assuming argument has value " + std::to_string(high));
argValues.back().safe = safeHigh;
}
if (!argValues.empty())
valueFlowForward(const_cast<Token*>(functionScope->bodyStart->next()),
functionScope->bodyEnd,
arg.nameToken(),
std::move(argValues),
tokenlist,
errorLogger,
settings);
}
}
}
static void valueFlowUnknownFunctionReturn(TokenList& tokenlist, const Settings& settings)
{
if (!tokenlist.front())
return;
for (Token* tok = tokenlist.front()->next(); tok; tok = tok->next()) {
if (!tok->astParent() || tok->str() != "(" || !tok->previous()->isName())
continue;
if (const auto* f = settings.library.getAllocFuncInfo(tok->astOperand1())) {
if (settings.library.returnValueType(tok->astOperand1()).find('*') != std::string::npos) {
// Allocation function that returns a pointer
ValueFlow::Value value(0);
value.setPossible();
value.errorPath.emplace_back(tok, "Assuming allocation function fails");
if (Library::ismemory(f->groupId))
value.unknownFunctionReturn = ValueFlow::Value::UnknownFunctionReturn::outOfMemory;
else
value.unknownFunctionReturn = ValueFlow::Value::UnknownFunctionReturn::outOfResources;
setTokenValue(tok, std::move(value), settings);
continue;
}
}
if (settings.checkUnknownFunctionReturn.find(tok->strAt(-1)) == settings.checkUnknownFunctionReturn.end())
continue;
std::vector<MathLib::bigint> unknownValues = settings.library.unknownReturnValues(tok->astOperand1());
if (unknownValues.empty())
continue;
// Get min/max values for return type
const std::string& typestr = settings.library.returnValueType(tok->previous());
MathLib::bigint minvalue, maxvalue;
if (!getMinMaxValues(typestr, settings, tok->isCpp(), minvalue, maxvalue))
continue;
for (MathLib::bigint value : unknownValues) {
if (value < minvalue)
value = minvalue;
else if (value > maxvalue)
value = maxvalue;
setTokenValue(tok, ValueFlow::Value(value), settings);
}
}
}
static void valueFlowDebug(TokenList& tokenlist, ErrorLogger& errorLogger, const Settings& settings)
{
if (!settings.debugnormal && !settings.debugwarnings)
return;
for (Token* tok = tokenlist.front(); tok; tok = tok->next()) {
if (tok->getTokenDebug() != TokenDebug::ValueFlow)
continue;
if (tok->astParent() && tok->astParent()->getTokenDebug() == TokenDebug::ValueFlow)
continue;
for (const ValueFlow::Value& v : tok->values()) {
std::string msg = "The value is " + debugString(v);
ErrorPath errorPath = v.errorPath;
errorPath.insert(errorPath.end(), v.debugPath.cbegin(), v.debugPath.cend());
errorPath.emplace_back(tok, "");
errorLogger.reportErr({errorPath, &tokenlist, Severity::debug, "valueFlow", msg, CWE{0}, Certainty::normal});
}
}
}
const ValueFlow::Value *ValueFlow::valueFlowConstantFoldAST(Token *expr, const Settings &settings)
{
if (expr && expr->values().empty()) {
valueFlowConstantFoldAST(expr->astOperand1(), settings);
valueFlowConstantFoldAST(expr->astOperand2(), settings);
valueFlowSetConstantValue(expr, settings);
}
return expr && expr->hasKnownValue() ? &expr->values().front() : nullptr;
}
struct ValueFlowState {
explicit ValueFlowState(TokenList& tokenlist,
SymbolDatabase& symboldatabase,
ErrorLogger& errorLogger,
const Settings& settings)
: tokenlist(tokenlist), symboldatabase(symboldatabase), errorLogger(errorLogger), settings(settings)
{}
TokenList& tokenlist;
SymbolDatabase& symboldatabase;
ErrorLogger& errorLogger;
const Settings& settings;
std::set<const Scope*> skippedFunctions;
};
struct ValueFlowPass {
ValueFlowPass() = default;
ValueFlowPass(const ValueFlowPass&) = default;
// Name of pass
virtual const char* name() const = 0;
// Run the pass
virtual void run(const ValueFlowState& state) const = 0;
// Returns true if pass needs C++
virtual bool cpp() const = 0;
virtual ~ValueFlowPass() noexcept = default;
};
struct ValueFlowPassRunner {
using Clock = std::chrono::steady_clock;
using TimePoint = std::chrono::time_point<Clock>;
explicit ValueFlowPassRunner(ValueFlowState state, TimerResultsIntf* timerResults = nullptr)
: state(std::move(state)), stop(TimePoint::max()), timerResults(timerResults)
{
setSkippedFunctions();
setStopTime();
}
bool run_once(std::initializer_list<ValuePtr<ValueFlowPass>> passes) const
{
return std::any_of(passes.begin(), passes.end(), [&](const ValuePtr<ValueFlowPass>& pass) {
return run(pass);
});
}
bool run(std::initializer_list<ValuePtr<ValueFlowPass>> passes) const
{
std::size_t values = 0;
std::size_t n = state.settings.vfOptions.maxIterations;
while (n > 0 && values != getTotalValues()) {
values = getTotalValues();
if (std::any_of(passes.begin(), passes.end(), [&](const ValuePtr<ValueFlowPass>& pass) {
return run(pass);
}))
return true;
--n;
}
if (state.settings.debugwarnings) {
if (n == 0 && values != getTotalValues()) {
ErrorMessage::FileLocation loc(state.tokenlist.getFiles()[0], 0, 0);
ErrorMessage errmsg({std::move(loc)},
emptyString,
Severity::debug,
"ValueFlow maximum iterations exceeded",
"valueFlowMaxIterations",
Certainty::normal);
state.errorLogger.reportErr(errmsg);
}
}
return false;
}
bool run(const ValuePtr<ValueFlowPass>& pass) const
{
auto start = Clock::now();
if (start > stop) {
// TODO: add bailout message
return true;
}
if (!state.tokenlist.isCPP() && pass->cpp())
return false;
if (timerResults) {
Timer t(pass->name(), state.settings.showtime, timerResults);
pass->run(state);
} else {
pass->run(state);
}
return false;
}
std::size_t getTotalValues() const
{
std::size_t n = 1;
for (Token* tok = state.tokenlist.front(); tok; tok = tok->next())
n += tok->values().size();
return n;
}
void setSkippedFunctions()
{
if (state.settings.vfOptions.maxIfCount > 0) {
for (const Scope* functionScope : state.symboldatabase.functionScopes) {
int countIfScopes = 0;
std::vector<const Scope*> scopes{functionScope};
while (!scopes.empty()) {
const Scope* s = scopes.back();
scopes.pop_back();
for (const Scope* s2 : s->nestedList) {
scopes.emplace_back(s2);
if (s2->type == Scope::ScopeType::eIf)
++countIfScopes;
}
}
if (countIfScopes > state.settings.vfOptions.maxIfCount) {
state.skippedFunctions.emplace(functionScope);
if (state.settings.severity.isEnabled(Severity::information)) {
const std::string& functionName = functionScope->className;
const std::list<ErrorMessage::FileLocation> callstack(
1,
ErrorMessage::FileLocation(functionScope->bodyStart, &state.tokenlist));
const ErrorMessage errmsg(callstack,
state.tokenlist.getSourceFilePath(),
Severity::information,
"Limiting ValueFlow analysis in function '" + functionName + "' since it is too complex. "
"Please specify --check-level=exhaustive to perform full analysis.",
"checkLevelNormal", // TODO: use more specific ID
Certainty::normal);
state.errorLogger.reportErr(errmsg);
}
}
}
}
}
void setStopTime()
{
if (state.settings.vfOptions.maxTime >= 0)
stop = Clock::now() + std::chrono::seconds{state.settings.vfOptions.maxTime};
}
ValueFlowState state;
TimePoint stop;
TimerResultsIntf* timerResults;
};
template<class F>
struct ValueFlowPassAdaptor : ValueFlowPass {
const char* mName = nullptr;
bool mCPP = false;
F mRun;
ValueFlowPassAdaptor(const char* pname, bool pcpp, F prun) : ValueFlowPass(), mName(pname), mCPP(pcpp), mRun(prun) {}
const char* name() const override {
return mName;
}
void run(const ValueFlowState& state) const override
{
mRun(state.tokenlist, state.symboldatabase, state.errorLogger, state.settings, state.skippedFunctions);
}
bool cpp() const override {
return mCPP;
}
};
template<class F>
static ValueFlowPassAdaptor<F> makeValueFlowPassAdaptor(const char* name, bool cpp, F run)
{
return {name, cpp, run};
}
#define VALUEFLOW_ADAPTOR(cpp, ...) \
makeValueFlowPassAdaptor(#__VA_ARGS__, \
(cpp), \
[](TokenList& tokenlist, \
SymbolDatabase& symboldatabase, \
ErrorLogger& errorLogger, \
const Settings& settings, \
const std::set<const Scope*>& skippedFunctions) { \
(void)tokenlist; \
(void)symboldatabase; \
(void)errorLogger; \
(void)settings; \
(void)skippedFunctions; \
__VA_ARGS__; \
})
#define VFA(...) VALUEFLOW_ADAPTOR(false, __VA_ARGS__)
#define VFA_CPP(...) VALUEFLOW_ADAPTOR(true, __VA_ARGS__)
void ValueFlow::setValues(TokenList& tokenlist,
SymbolDatabase& symboldatabase,
ErrorLogger& errorLogger,
const Settings& settings,
TimerResultsIntf* timerResults)
{
for (Token* tok = tokenlist.front(); tok; tok = tok->next())
tok->clearValueFlow();
// commas in init..
for (Token* tok = tokenlist.front(); tok; tok = tok->next()) {
if (tok->str() != "{" || !tok->astOperand1())
continue;
for (Token* tok2 = tok->next(); tok2 != tok->link(); tok2 = tok2->next()) {
if (tok2->link() && Token::Match(tok2, "[{[(<]"))
tok2 = tok2->link();
else if (tok2->str() == ",")
tok2->isInitComma(true);
}
}
ValueFlowPassRunner runner{ValueFlowState{tokenlist, symboldatabase, errorLogger, settings}, timerResults};
runner.run_once({
VFA(valueFlowEnumValue(symboldatabase, settings)),
VFA(valueFlowNumber(tokenlist, settings)),
VFA(valueFlowString(tokenlist, settings)),
VFA(valueFlowArray(tokenlist, settings)),
VFA(valueFlowUnknownFunctionReturn(tokenlist, settings)),
VFA(valueFlowGlobalConstVar(tokenlist, settings)),
VFA(valueFlowEnumValue(symboldatabase, settings)),
VFA(valueFlowGlobalStaticVar(tokenlist, settings)),
VFA(valueFlowPointerAlias(tokenlist, settings)),
VFA(valueFlowLifetime(tokenlist, errorLogger, settings)),
VFA(valueFlowSymbolic(tokenlist, symboldatabase, errorLogger, settings)),
VFA(valueFlowBitAnd(tokenlist, settings)),
VFA(valueFlowSameExpressions(tokenlist, settings)),
VFA(valueFlowConditionExpressions(tokenlist, symboldatabase, errorLogger, settings)),
});
runner.run({
VFA(valueFlowImpossibleValues(tokenlist, settings)),
VFA(valueFlowSymbolicOperators(symboldatabase, settings)),
VFA(valueFlowCondition(SymbolicConditionHandler{}, tokenlist, symboldatabase, errorLogger, settings, skippedFunctions)),
VFA(valueFlowSymbolicInfer(symboldatabase, settings)),
VFA(valueFlowArrayBool(tokenlist, settings)),
VFA(valueFlowArrayElement(tokenlist, settings)),
VFA(valueFlowRightShift(tokenlist, settings)),
VFA_CPP(
valueFlowCondition(ContainerConditionHandler{}, tokenlist, symboldatabase, errorLogger, settings, skippedFunctions)),
VFA(valueFlowAfterAssign(tokenlist, symboldatabase, errorLogger, settings, skippedFunctions)),
VFA_CPP(valueFlowAfterSwap(tokenlist, symboldatabase, errorLogger, settings)),
VFA(valueFlowCondition(SimpleConditionHandler{}, tokenlist, symboldatabase, errorLogger, settings, skippedFunctions)),
VFA(valueFlowInferCondition(tokenlist, settings)),
VFA(valueFlowSwitchVariable(tokenlist, symboldatabase, errorLogger, settings)),
VFA(valueFlowForLoop(tokenlist, symboldatabase, errorLogger, settings)),
VFA(valueFlowSubFunction(tokenlist, symboldatabase, errorLogger, settings)),
VFA(valueFlowFunctionReturn(tokenlist, errorLogger, settings)),
VFA(valueFlowLifetime(tokenlist, errorLogger, settings)),
VFA(valueFlowFunctionDefaultParameter(tokenlist, symboldatabase, errorLogger, settings)),
VFA(valueFlowUninit(tokenlist, errorLogger, settings)),
VFA_CPP(valueFlowAfterMove(tokenlist, symboldatabase, errorLogger, settings)),
VFA_CPP(valueFlowSmartPointer(tokenlist, errorLogger, settings)),
VFA_CPP(valueFlowIterators(tokenlist, settings)),
VFA_CPP(
valueFlowCondition(IteratorConditionHandler{}, tokenlist, symboldatabase, errorLogger, settings, skippedFunctions)),
VFA_CPP(valueFlowIteratorInfer(tokenlist, settings)),
VFA_CPP(valueFlowContainerSize(tokenlist, symboldatabase, errorLogger, settings, skippedFunctions)),
VFA(valueFlowSafeFunctions(tokenlist, symboldatabase, errorLogger, settings)),
});
runner.run_once({
VFA(valueFlowDynamicBufferSize(tokenlist, symboldatabase, errorLogger, settings)),
VFA(valueFlowDebug(tokenlist, errorLogger, settings)), // TODO: add option to print it after each step/iteration
});
}
std::string ValueFlow::eitherTheConditionIsRedundant(const Token *condition)
{
if (!condition)
return "Either the condition is redundant";
if (condition->str() == "case") {
std::string expr;
for (const Token *tok = condition; tok && tok->str() != ":"; tok = tok->next()) {
expr += tok->str();
if (Token::Match(tok, "%name%|%num% %name%|%num%"))
expr += ' ';
}
return "Either the switch case '" + expr + "' is redundant";
}
return "Either the condition '" + condition->expressionString() + "' is redundant";
}
const ValueFlow::Value* ValueFlow::findValue(const std::list<ValueFlow::Value>& values,
const Settings& settings,
const std::function<bool(const ValueFlow::Value&)> &pred)
{
const ValueFlow::Value* ret = nullptr;
for (const ValueFlow::Value& v : values) {
if (pred(v)) {
if (!ret || ret->isInconclusive() || (ret->condition && !v.isInconclusive()))
ret = &v;
if (!ret->isInconclusive() && !ret->condition)
break;
}
}
if (ret) {
if (ret->isInconclusive() && !settings.certainty.isEnabled(Certainty::inconclusive))
return nullptr;
if (ret->condition && !settings.severity.isEnabled(Severity::warning))
return nullptr;
}
return ret;
}
// TODO: returns a single value at most - no need for std::vector
static std::vector<ValueFlow::Value> isOutOfBoundsImpl(const ValueFlow::Value& size,
const Token* indexTok,
bool condition)
{
if (!indexTok)
return {};
const ValueFlow::Value* indexValue = indexTok->getMaxValue(condition, size.path);
if (!indexValue)
return {};
if (indexValue->intvalue >= size.intvalue)
return {*indexValue};
if (!condition)
return {};
// TODO: Use a better way to decide if the variable in unconstrained
if (!indexTok->variable() || !indexTok->variable()->isArgument())
return {};
if (std::any_of(indexTok->values().cbegin(), indexTok->values().cend(), [&](const ValueFlow::Value& v) {
return v.isSymbolicValue() && v.isPossible() && v.bound == ValueFlow::Value::Bound::Upper;
}))
return {};
if (indexValue->bound != ValueFlow::Value::Bound::Lower)
return {};
if (size.bound == ValueFlow::Value::Bound::Lower)
return {};
// Checking for underflow doesn't mean it could be out of bounds
if (indexValue->intvalue == 0)
return {};
ValueFlow::Value value = inferCondition(">=", indexTok, indexValue->intvalue);
if (!value.isKnown())
return {};
if (value.intvalue == 0)
return {};
value.intvalue = size.intvalue;
value.bound = ValueFlow::Value::Bound::Lower;
return {std::move(value)};
}
// TODO: return single value at most - no need for std::vector
std::vector<ValueFlow::Value> ValueFlow::isOutOfBounds(const Value& size, const Token* indexTok, bool possible)
{
ValueFlow::Value inBoundsValue = inferCondition("<", indexTok, size.intvalue);
if (inBoundsValue.isKnown() && inBoundsValue.intvalue != 0)
return {};
std::vector<ValueFlow::Value> result = isOutOfBoundsImpl(size, indexTok, false);
if (!result.empty())
return result;
if (!possible)
return result;
return isOutOfBoundsImpl(size, indexTok, true);
}
| null |
945 | cpp | cppcheck | errortypes.cpp | lib/errortypes.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "errortypes.h"
#include "utils.h"
static std::string typeToString(InternalError::Type type)
{
switch (type) {
case InternalError::Type::AST:
return "internalAstError";
case InternalError::Type::SYNTAX:
return "syntaxError";
case InternalError::Type::UNKNOWN_MACRO:
return "unknownMacro";
case InternalError::Type::INTERNAL:
return "internalError";
case InternalError::Type::LIMIT:
return "cppcheckLimit";
case InternalError::Type::INSTANTIATION:
return "instantiationError";
}
cppcheck::unreachable();
}
InternalError::InternalError(const Token *tok, std::string errorMsg, Type type) :
InternalError(tok, std::move(errorMsg), "", type)
{}
InternalError::InternalError(const Token *tok, std::string errorMsg, std::string details, Type type) :
token(tok), errorMessage(std::move(errorMsg)), details(std::move(details)), type(type), id(typeToString(type))
{}
std::string severityToString(Severity severity)
{
switch (severity) {
case Severity::none:
return "";
case Severity::error:
return "error";
case Severity::warning:
return "warning";
case Severity::style:
return "style";
case Severity::performance:
return "performance";
case Severity::portability:
return "portability";
case Severity::information:
return "information";
case Severity::debug:
return "debug";
case Severity::internal:
return "internal";
}
throw InternalError(nullptr, "Unknown severity");
}
// TODO: bail out on invalid severity
Severity severityFromString(const std::string& severity)
{
if (severity.empty())
return Severity::none;
if (severity == "none")
return Severity::none;
if (severity == "error")
return Severity::error;
if (severity == "warning")
return Severity::warning;
if (severity == "style")
return Severity::style;
if (severity == "performance")
return Severity::performance;
if (severity == "portability")
return Severity::portability;
if (severity == "information")
return Severity::information;
if (severity == "debug")
return Severity::debug;
if (severity == "internal")
return Severity::internal;
return Severity::none;
}
| null |
946 | cpp | cppcheck | pathmatch.cpp | lib/pathmatch.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "pathmatch.h"
#include "path.h"
#include "utils.h"
#include <cstddef>
#include <utility>
PathMatch::PathMatch(std::vector<std::string> paths, bool caseSensitive)
: mPaths(std::move(paths)), mCaseSensitive(caseSensitive)
{
for (std::string& p : mPaths)
{
p = Path::fromNativeSeparators(p);
if (!mCaseSensitive)
strTolower(p);
}
// TODO: also make lowercase?
mWorkingDirectory.push_back(Path::fromNativeSeparators(Path::getCurrentPath()));
}
bool PathMatch::match(const std::string &path) const
{
if (path.empty())
return false;
std::string findpath = Path::fromNativeSeparators(path);
if (!mCaseSensitive)
strTolower(findpath);
const bool is_absolute = Path::isAbsolute(path);
// TODO: align the match logic with ImportProject::ignorePaths()
for (std::vector<std::string>::const_iterator i = mPaths.cbegin(); i != mPaths.cend(); ++i) {
const std::string pathToMatch((!is_absolute && Path::isAbsolute(*i)) ? Path::getRelativePath(*i, mWorkingDirectory) : *i);
// Filtering directory name
if (endsWith(pathToMatch,'/')) {
if (!endsWith(findpath,'/'))
findpath = removeFilename(findpath);
if (pathToMatch.length() > findpath.length())
continue;
// Match relative paths starting with mask
// -isrc matches src/foo.cpp
if (findpath.compare(0, pathToMatch.size(), pathToMatch) == 0)
return true;
// Match only full directory name in middle or end of the path
// -isrc matches myproject/src/ but does not match
// myproject/srcfiles/ or myproject/mysrc/
if (findpath.find("/" + pathToMatch) != std::string::npos)
return true;
}
// Filtering filename
else {
if (pathToMatch.length() > findpath.length())
continue;
// Check if path ends with mask
// -ifoo.cpp matches (./)foo.c, src/foo.cpp and proj/src/foo.cpp
// -isrc/file.cpp matches src/foo.cpp and proj/src/foo.cpp
if (findpath.compare(findpath.size() - pathToMatch.size(), findpath.size(), pathToMatch) == 0)
return true;
}
}
return false;
}
std::string PathMatch::removeFilename(const std::string &path)
{
const std::size_t ind = path.find_last_of('/');
return path.substr(0, ind + 1);
}
| null |
947 | cpp | cppcheck | checkstl.h | lib/checkstl.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef checkstlH
#define checkstlH
//---------------------------------------------------------------------------
#include "check.h"
#include "config.h"
#include "errortypes.h"
#include "tokenize.h"
#include "vfvalue.h"
#include <cstdint>
#include <string>
class Scope;
class Settings;
class Token;
class Variable;
class ErrorLogger;
/// @addtogroup Checks
/// @{
/** @brief %Check STL usage (invalidation of iterators, mismatching containers, etc) */
class CPPCHECKLIB CheckStl : public Check {
public:
/** This constructor is used when registering the CheckClass */
CheckStl() : Check(myName()) {}
private:
/** This constructor is used when running checks. */
CheckStl(const Tokenizer* tokenizer, const Settings* settings, ErrorLogger* errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {}
/** run checks, the token list is not simplified */
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
if (!tokenizer.isCPP()) {
return;
}
CheckStl checkStl(&tokenizer, &tokenizer.getSettings(), errorLogger);
checkStl.erase();
checkStl.if_find();
checkStl.checkFindInsert();
checkStl.iterators();
checkStl.missingComparison();
checkStl.outOfBounds();
checkStl.outOfBoundsIndexExpression();
checkStl.redundantCondition();
checkStl.string_c_str();
checkStl.uselessCalls();
checkStl.useStlAlgorithm();
checkStl.stlOutOfBounds();
checkStl.negativeIndex();
checkStl.invalidContainer();
checkStl.mismatchingContainers();
checkStl.mismatchingContainerIterator();
checkStl.knownEmptyContainer();
checkStl.eraseIteratorOutOfBounds();
checkStl.stlBoundaries();
checkStl.checkDereferenceInvalidIterator();
checkStl.checkDereferenceInvalidIterator2();
checkStl.checkMutexes();
// Style check
checkStl.size();
}
/** Accessing container out of bounds using ValueFlow */
void outOfBounds();
/** Accessing container out of bounds, following index expression */
void outOfBoundsIndexExpression();
/**
* Finds errors like this:
* for (unsigned ii = 0; ii <= foo.size(); ++ii)
*/
void stlOutOfBounds();
/**
* negative index for array like containers
*/
void negativeIndex();
/**
* Finds errors like this:
* for (it = foo.begin(); it != bar.end(); ++it)
*/
void iterators();
void invalidContainer();
bool checkIteratorPair(const Token* tok1, const Token* tok2);
/**
* Mismatching containers:
* std::find(foo.begin(), bar.end(), x)
*/
void mismatchingContainers();
void mismatchingContainerIterator();
/**
* Dangerous usage of erase. The iterator is invalidated by erase so
* it is bad to dereference it after the erase.
*/
void erase();
void eraseCheckLoopVar(const Scope& scope, const Variable* var);
/**
* bad condition.. "it < alist.end()"
*/
void stlBoundaries();
/** if (a.find(x)) - possibly incorrect condition */
void if_find();
void checkFindInsert();
/**
* Suggest using empty() instead of checking size() against zero for containers.
* Item 4 from Scott Meyers book "Effective STL".
*/
void size();
/**
* Check for redundant condition 'if (ints.find(1) != ints.end()) ints.remove(123);'
* */
void redundantCondition();
/**
* @brief Missing inner comparison, when incrementing iterator inside loop
* Dangers:
* - may increment iterator beyond end
* - may unintentionally skip elements in list/set etc
*/
void missingComparison();
/** Check for common mistakes when using the function string::c_str() */
void string_c_str();
/** @brief %Check calls that using them is useless */
void uselessCalls();
/** @brief %Check for dereferencing an iterator that is invalid */
void checkDereferenceInvalidIterator();
void checkDereferenceInvalidIterator2();
/**
* Dereferencing an erased iterator
* @param erased token where the erase occurs
* @param deref token where the dereference occurs
* @param itername iterator name
* @param inconclusive inconclusive flag
*/
void dereferenceErasedError(const Token* erased, const Token* deref, const std::string& itername, bool inconclusive);
/** @brief Look for loops that can replaced with std algorithms */
void useStlAlgorithm();
void knownEmptyContainer();
void eraseIteratorOutOfBounds();
void checkMutexes();
bool isContainerSize(const Token *containerToken, const Token *expr) const;
bool isContainerSizeGE(const Token * containerToken, const Token *expr) const;
void missingComparisonError(const Token* incrementToken1, const Token* incrementToken2);
void string_c_strThrowError(const Token* tok);
void string_c_strError(const Token* tok);
void string_c_strReturn(const Token* tok);
void string_c_strParam(const Token* tok, nonneg int number, const std::string& argtype = "std::string");
void string_c_strConstructor(const Token* tok, const std::string& argtype = "std::string");
void string_c_strAssignment(const Token* tok, const std::string& argtype = "std::string");
void string_c_strConcat(const Token* tok);
void string_c_strStream(const Token* tok);
void outOfBoundsError(const Token *tok, const std::string &containerName, const ValueFlow::Value *containerSize, const std::string &index, const ValueFlow::Value *indexValue);
void outOfBoundsIndexExpressionError(const Token *tok, const Token *index);
void stlOutOfBoundsError(const Token* tok, const std::string& num, const std::string& var, bool at);
void negativeIndexError(const Token* tok, const ValueFlow::Value& index);
void invalidIteratorError(const Token* tok, const std::string& iteratorName);
void iteratorsError(const Token* tok, const std::string& containerName1, const std::string& containerName2);
void iteratorsError(const Token* tok, const Token* containerTok, const std::string& containerName1, const std::string& containerName2);
void iteratorsError(const Token* tok, const Token* containerTok, const std::string& containerName);
void mismatchingContainerIteratorError(const Token* containerTok, const Token* iterTok, const Token* containerTok2);
void mismatchingContainersError(const Token* tok1, const Token* tok2);
void mismatchingContainerExpressionError(const Token *tok1, const Token *tok2);
void sameIteratorExpressionError(const Token *tok);
void stlBoundariesError(const Token* tok);
void if_findError(const Token* tok, bool str);
void checkFindInsertError(const Token *tok);
void sizeError(const Token* tok);
void redundantIfRemoveError(const Token* tok);
void invalidContainerLoopError(const Token* tok, const Token* loopTok, ErrorPath errorPath);
void invalidContainerError(const Token *tok, const Token * contTok, const ValueFlow::Value *val, ErrorPath errorPath);
void invalidContainerReferenceError(const Token* tok, const Token* contTok, ErrorPath errorPath);
void uselessCallsReturnValueError(const Token* tok, const std::string& varname, const std::string& function);
void uselessCallsSwapError(const Token* tok, const std::string& varname);
enum class SubstrErrorType : std::uint8_t { EMPTY, COPY, PREFIX, PREFIX_CONCAT };
void uselessCallsSubstrError(const Token* tok, SubstrErrorType type);
void uselessCallsEmptyError(const Token* tok);
void uselessCallsRemoveError(const Token* tok, const std::string& function);
void uselessCallsConstructorError(const Token* tok);
void dereferenceInvalidIteratorError(const Token* deref, const std::string& iterName);
void dereferenceInvalidIteratorError(const Token* tok, const ValueFlow::Value *value, bool inconclusive);
void useStlAlgorithmError(const Token *tok, const std::string &algoName);
void knownEmptyContainerError(const Token *tok, const std::string& algo);
void eraseIteratorOutOfBoundsError(const Token* ftok, const Token* itertok, const ValueFlow::Value* val = nullptr);
void globalLockGuardError(const Token *tok);
void localMutexError(const Token *tok);
void getErrorMessages(ErrorLogger* errorLogger, const Settings* settings) const override {
CheckStl c(nullptr, settings, errorLogger);
c.outOfBoundsError(nullptr, "container", nullptr, "x", nullptr);
c.invalidIteratorError(nullptr, "iterator");
c.iteratorsError(nullptr, "container1", "container2");
c.iteratorsError(nullptr, nullptr, "container0", "container1");
c.iteratorsError(nullptr, nullptr, "container");
c.invalidContainerLoopError(nullptr, nullptr, ErrorPath{});
c.invalidContainerError(nullptr, nullptr, nullptr, ErrorPath{});
c.mismatchingContainerIteratorError(nullptr, nullptr, nullptr);
c.mismatchingContainersError(nullptr, nullptr);
c.mismatchingContainerExpressionError(nullptr, nullptr);
c.sameIteratorExpressionError(nullptr);
c.dereferenceErasedError(nullptr, nullptr, "iter", false);
c.stlOutOfBoundsError(nullptr, "i", "foo", false);
c.negativeIndexError(nullptr, ValueFlow::Value(-1));
c.stlBoundariesError(nullptr);
c.if_findError(nullptr, false);
c.if_findError(nullptr, true);
c.checkFindInsertError(nullptr);
c.string_c_strError(nullptr);
c.string_c_strReturn(nullptr);
c.string_c_strParam(nullptr, 0);
c.string_c_strThrowError(nullptr);
c.sizeError(nullptr);
c.missingComparisonError(nullptr, nullptr);
c.redundantIfRemoveError(nullptr);
c.uselessCallsReturnValueError(nullptr, "str", "find");
c.uselessCallsSwapError(nullptr, "str");
c.uselessCallsSubstrError(nullptr, SubstrErrorType::COPY);
c.uselessCallsEmptyError(nullptr);
c.uselessCallsRemoveError(nullptr, "remove");
c.dereferenceInvalidIteratorError(nullptr, "i");
c.eraseIteratorOutOfBoundsError(nullptr, nullptr);
c.useStlAlgorithmError(nullptr, emptyString);
c.knownEmptyContainerError(nullptr, emptyString);
c.globalLockGuardError(nullptr);
c.localMutexError(nullptr);
}
static std::string myName() {
return "STL usage";
}
std::string classInfo() const override {
return "Check for invalid usage of STL:\n"
"- out of bounds errors\n"
"- misuse of iterators when iterating through a container\n"
"- mismatching containers in calls\n"
"- same iterators in calls\n"
"- dereferencing an erased iterator\n"
"- for vectors: using iterator/pointer after push_back has been used\n"
"- optimisation: use empty() instead of size() to guarantee fast code\n"
"- suspicious condition when using find\n"
"- unnecessary searching in associative containers\n"
"- redundant condition\n"
"- common mistakes when using string::c_str()\n"
"- useless calls of string and STL functions\n"
"- dereferencing an invalid iterator\n"
"- erasing an iterator that is out of bounds\n"
"- reading from empty STL container\n"
"- iterating over an empty STL container\n"
"- consider using an STL algorithm instead of raw loop\n"
"- incorrect locking with mutex\n";
}
};
/// @}
//---------------------------------------------------------------------------
#endif // checkstlH
| null |
948 | cpp | cppcheck | vf_common.cpp | lib/vf_common.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "vf_common.h"
#include "astutils.h"
#include "mathlib.h"
#include "path.h"
#include "platform.h"
#include "settings.h"
#include "standards.h"
#include "symboldatabase.h"
#include "token.h"
#include "valueflow.h"
#include "vf_settokenvalue.h"
#include <climits>
#include <cstddef>
#include <exception>
#include <limits>
#include <utility>
#include <vector>
namespace ValueFlow
{
bool getMinMaxValues(const ValueType *vt, const Platform &platform, MathLib::bigint &minValue, MathLib::bigint &maxValue)
{
if (!vt || !vt->isIntegral() || vt->pointer)
return false;
int bits;
switch (vt->type) {
case ValueType::Type::BOOL:
bits = 1;
break;
case ValueType::Type::CHAR:
bits = platform.char_bit;
break;
case ValueType::Type::SHORT:
bits = platform.short_bit;
break;
case ValueType::Type::INT:
bits = platform.int_bit;
break;
case ValueType::Type::LONG:
bits = platform.long_bit;
break;
case ValueType::Type::LONGLONG:
bits = platform.long_long_bit;
break;
default:
return false;
}
if (bits == 1) {
minValue = 0;
maxValue = 1;
} else if (bits < 62) {
if (vt->sign == ValueType::Sign::UNSIGNED) {
minValue = 0;
maxValue = (1LL << bits) - 1;
} else {
minValue = -(1LL << (bits - 1));
maxValue = (1LL << (bits - 1)) - 1;
}
} else if (bits == 64) {
if (vt->sign == ValueType::Sign::UNSIGNED) {
minValue = 0;
maxValue = LLONG_MAX; // todo max unsigned value
} else {
minValue = LLONG_MIN;
maxValue = LLONG_MAX;
}
} else {
return false;
}
return true;
}
MathLib::bigint truncateIntValue(MathLib::bigint value, size_t value_size, const ValueType::Sign dst_sign)
{
if (value_size == 0)
return value;
const MathLib::biguint unsignedMaxValue = std::numeric_limits<MathLib::biguint>::max() >> ((sizeof(unsignedMaxValue) - value_size) * 8);
const MathLib::biguint signBit = 1ULL << (value_size * 8 - 1);
value &= unsignedMaxValue;
if (dst_sign == ValueType::Sign::SIGNED && (value & signBit))
value |= ~unsignedMaxValue;
return value;
}
static nonneg int getSizeOfType(const Token *typeTok, const Settings &settings)
{
const ValueType &valueType = ValueType::parseDecl(typeTok, settings);
return getSizeOf(valueType, settings);
}
// Handle various constants..
Token * valueFlowSetConstantValue(Token *tok, const Settings &settings)
{
if ((tok->isNumber() && MathLib::isInt(tok->str())) || (tok->tokType() == Token::eChar)) {
try {
MathLib::bigint signedValue = MathLib::toBigNumber(tok->str());
const ValueType* vt = tok->valueType();
if (vt && vt->sign == ValueType::UNSIGNED && signedValue < 0 && getSizeOf(*vt, settings) < sizeof(MathLib::bigint)) {
MathLib::bigint minValue{}, maxValue{};
if (getMinMaxValues(tok->valueType(), settings.platform, minValue, maxValue))
signedValue += maxValue + 1;
}
Value value(signedValue);
if (!tok->isTemplateArg())
value.setKnown();
setTokenValue(tok, std::move(value), settings);
} catch (const std::exception & /*e*/) {
// Bad character literal
}
} else if (tok->isNumber() && MathLib::isFloat(tok->str())) {
Value value;
value.valueType = Value::ValueType::FLOAT;
value.floatValue = MathLib::toDoubleNumber(tok->str());
if (!tok->isTemplateArg())
value.setKnown();
setTokenValue(tok, std::move(value), settings);
} else if (tok->enumerator() && tok->enumerator()->value_known) {
Value value(tok->enumerator()->value);
if (!tok->isTemplateArg())
value.setKnown();
setTokenValue(tok, std::move(value), settings);
} else if (tok->str() == "NULL" || (tok->isCpp() && tok->str() == "nullptr")) {
Value value(0);
if (!tok->isTemplateArg())
value.setKnown();
setTokenValue(tok, std::move(value), settings);
} else if (Token::simpleMatch(tok, "sizeof (")) {
if (tok->next()->astOperand2() && !tok->next()->astOperand2()->isLiteral() && tok->next()->astOperand2()->valueType() &&
(tok->next()->astOperand2()->valueType()->pointer == 0 || // <- TODO this is a bailout, abort when there are array->pointer conversions
(tok->next()->astOperand2()->variable() && !tok->next()->astOperand2()->variable()->isArray())) &&
!tok->next()->astOperand2()->valueType()->isEnum()) { // <- TODO this is a bailout, handle enum with non-int types
const size_t sz = getSizeOf(*tok->next()->astOperand2()->valueType(), settings);
if (sz) {
Value value(sz);
value.setKnown();
setTokenValue(tok->next(), std::move(value), settings);
return tok->linkAt(1);
}
}
const Token *tok2 = tok->tokAt(2);
// skip over tokens to find variable or type
while (tok2 && !tok2->isStandardType() && Token::Match(tok2, "%name% ::|.|[")) {
if (tok2->strAt(1) == "[")
tok2 = tok2->linkAt(1)->next();
else
tok2 = tok2->tokAt(2);
}
if (Token::simpleMatch(tok, "sizeof ( *")) {
const ValueType *vt = tok->tokAt(2)->valueType();
const size_t sz = vt ? getSizeOf(*vt, settings) : 0;
if (sz > 0) {
Value value(sz);
if (!tok2->isTemplateArg() && settings.platform.type != Platform::Type::Unspecified)
value.setKnown();
setTokenValue(tok->next(), std::move(value), settings);
}
} else if (tok2->enumerator() && tok2->enumerator()->scope) {
long long size = settings.platform.sizeof_int;
const Token * type = tok2->enumerator()->scope->enumType;
if (type) {
size = getSizeOfType(type, settings);
if (size == 0)
tok->linkAt(1);
}
Value value(size);
if (!tok2->isTemplateArg() && settings.platform.type != Platform::Type::Unspecified)
value.setKnown();
setTokenValue(tok, value, settings);
setTokenValue(tok->next(), std::move(value), settings);
} else if (tok2->type() && tok2->type()->isEnumType()) {
long long size = settings.platform.sizeof_int;
if (tok2->type()->classScope) {
const Token * type = tok2->type()->classScope->enumType;
if (type) {
size = getSizeOfType(type, settings);
}
}
Value value(size);
if (!tok2->isTemplateArg() && settings.platform.type != Platform::Type::Unspecified)
value.setKnown();
setTokenValue(tok, value, settings);
setTokenValue(tok->next(), std::move(value), settings);
} else if (Token::Match(tok, "sizeof ( %var% ) /") && tok->next()->astParent() == tok->tokAt(4) &&
tok->tokAt(4)->astOperand2() && Token::simpleMatch(tok->tokAt(4)->astOperand2()->previous(), "sizeof (")) {
// Get number of elements in array
const Token *sz1 = tok->tokAt(2);
const Token *sz2 = tok->tokAt(4)->astOperand2(); // left parenthesis of sizeof on rhs
const nonneg int varid1 = sz1->varId();
if (varid1 &&
sz1->variable() &&
sz1->variable()->isArray() &&
!sz1->variable()->dimensions().empty() &&
sz1->variable()->dimensionKnown(0) &&
Token::Match(sz2->astOperand2(), "*|[") && Token::Match(sz2->astOperand2()->astOperand1(), "%varid%", varid1)) {
Value value(sz1->variable()->dimension(0));
if (!tok2->isTemplateArg() && settings.platform.type != Platform::Type::Unspecified)
value.setKnown();
setTokenValue(tok->tokAt(4), std::move(value), settings);
}
} else if (Token::Match(tok2, "%var% )")) {
const Variable *var = tok2->variable();
// only look for single token types (no pointers or references yet)
if (var && var->typeStartToken() == var->typeEndToken()) {
// find the size of the type
size_t size = 0;
if (var->isEnumType()) {
size = settings.platform.sizeof_int;
if (var->type()->classScope && var->type()->classScope->enumType)
size = getSizeOfType(var->type()->classScope->enumType, settings);
} else if (var->valueType()) {
size = getSizeOf(*var->valueType(), settings);
} else if (!var->type()) {
size = getSizeOfType(var->typeStartToken(), settings);
}
// find the number of elements
size_t count = 1;
for (size_t i = 0; i < var->dimensions().size(); ++i) {
if (var->dimensionKnown(i))
count *= var->dimension(i);
else
count = 0;
}
if (size && count > 0) {
Value value(count * size);
if (settings.platform.type != Platform::Type::Unspecified)
value.setKnown();
setTokenValue(tok, value, settings);
setTokenValue(tok->next(), std::move(value), settings);
}
}
} else if (tok2->tokType() == Token::eString) {
const size_t sz = Token::getStrSize(tok2, settings);
if (sz > 0) {
Value value(sz);
value.setKnown();
setTokenValue(tok->next(), std::move(value), settings);
}
} else if (tok2->tokType() == Token::eChar) {
nonneg int sz = 0;
if (tok2->isCpp() && settings.standards.cpp >= Standards::CPP20 && tok2->isUtf8())
sz = 1;
else if (tok2->isUtf16())
sz = 2;
else if (tok2->isUtf32())
sz = 4;
else if (tok2->isLong())
sz = settings.platform.sizeof_wchar_t;
else if ((!tok2->isCpp() && tok2->isCChar()) || (tok2->isCMultiChar()))
sz = settings.platform.sizeof_int;
else
sz = 1;
if (sz > 0) {
Value value(sz);
value.setKnown();
setTokenValue(tok->next(), std::move(value), settings);
}
} else if (!tok2->type()) {
const ValueType& vt = ValueType::parseDecl(tok2, settings);
size_t sz = getSizeOf(vt, settings);
const Token* brac = tok2->astParent();
while (Token::simpleMatch(brac, "[")) {
const Token* num = brac->astOperand2();
if (num && ((num->isNumber() && MathLib::isInt(num->str())) || num->tokType() == Token::eChar)) {
try {
const MathLib::biguint dim = MathLib::toBigUNumber(num->str());
sz *= dim;
brac = brac->astParent();
continue;
}
catch (const std::exception& /*e*/) {
// Bad integer literal
}
}
sz = 0;
break;
}
if (sz > 0) {
Value value(sz);
if (!tok2->isTemplateArg() && settings.platform.type != Platform::Type::Unspecified)
value.setKnown();
setTokenValue(tok->next(), std::move(value), settings);
}
}
// skip over enum
tok = tok->linkAt(1);
} else if (Token::Match(tok, "%name% [{(] [)}]") && (tok->isStandardType() ||
(tok->variable() && tok->variable()->nameToken() == tok &&
(tok->variable()->isPointer() || (tok->variable()->valueType() && tok->variable()->valueType()->isIntegral()))))) {
Value value(0);
if (!tok->isTemplateArg())
value.setKnown();
setTokenValue(tok->next(), std::move(value), settings);
} else if (Token::simpleMatch(tok, "= { } ;")) {
const Token* lhs = tok->astOperand1();
if (lhs && lhs->valueType() && (lhs->valueType()->isIntegral() || lhs->valueType()->pointer > 0)) {
Value value(0);
value.setKnown();
setTokenValue(tok->next(), std::move(value), settings);
}
}
return tok->next();
}
Value castValue(Value value, const ValueType::Sign sign, nonneg int bit)
{
if (value.isFloatValue()) {
value.valueType = Value::ValueType::INT;
if (value.floatValue >= std::numeric_limits<int>::min() && value.floatValue <= std::numeric_limits<int>::max()) {
value.intvalue = value.floatValue;
} else { // don't perform UB
value.intvalue = 0;
}
}
if (bit < MathLib::bigint_bits) {
constexpr MathLib::biguint one = 1;
value.intvalue &= (one << bit) - 1;
if (sign == ValueType::Sign::SIGNED && value.intvalue & (one << (bit - 1))) {
value.intvalue |= ~((one << bit) - 1ULL);
}
}
return value;
}
std::string debugString(const Value& v)
{
std::string kind;
switch (v.valueKind) {
case Value::ValueKind::Impossible:
case Value::ValueKind::Known:
kind = "always";
break;
case Value::ValueKind::Inconclusive:
kind = "inconclusive";
break;
case Value::ValueKind::Possible:
kind = "possible";
break;
}
return kind + " " + v.toString();
}
void setSourceLocation(Value& v,
SourceLocation ctx,
const Token* tok,
SourceLocation local)
{
std::string file = ctx.file_name();
if (file.empty())
return;
std::string s = Path::stripDirectoryPart(file) + ":" + std::to_string(ctx.line()) + ": " + ctx.function_name() +
" => " + local.function_name() + ": " + debugString(v);
v.debugPath.emplace_back(tok, std::move(s));
}
MathLib::bigint valueFlowGetStrLength(const Token* tok)
{
if (tok->tokType() == Token::eString)
return Token::getStrLength(tok);
if (astIsGenericChar(tok) || tok->tokType() == Token::eChar)
return 1;
if (const Value* v = tok->getKnownValue(Value::ValueType::CONTAINER_SIZE))
return v->intvalue;
if (const Value* v = tok->getKnownValue(Value::ValueType::TOK)) {
if (v->tokvalue != tok)
return valueFlowGetStrLength(v->tokvalue);
}
return 0;
}
}
| null |
949 | cpp | cppcheck | testuninitvar.cpp | test/testuninitvar.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "check.h"
#include "checkuninitvar.h"
#include "ctu.h"
#include "fixture.h"
#include "helpers.h"
#include "settings.h"
#include <list>
#include <string>
class TestUninitVar : public TestFixture {
public:
TestUninitVar() : TestFixture("TestUninitVar") {}
private:
const Settings settings = settingsBuilder().library("std.cfg").build();
void run() override {
TEST_CASE(uninitvar1);
TEST_CASE(uninitvar_warn_once); // only write 1 warning at a time
TEST_CASE(uninitvar_decl); // handling various types in C and C++ files
TEST_CASE(uninitvar_bitop); // using uninitialized operand in bit operation
TEST_CASE(uninitvar_alloc); // data is allocated but not initialized
TEST_CASE(uninitvar_arrays); // arrays
TEST_CASE(uninitvar_class); // class/struct
TEST_CASE(uninitvar_enum); // enum variables
TEST_CASE(uninitvar_if); // handling if
TEST_CASE(uninitvar_loops); // handling for/while
TEST_CASE(uninitvar_switch); // handling switch
TEST_CASE(uninitvar_references); // references
TEST_CASE(uninitvar_return); // return
TEST_CASE(uninitvar_assign); // = {..}
TEST_CASE(uninitvar_strncpy); // strncpy doesn't always null-terminate
TEST_CASE(func_uninit_var); // analyse function calls for: 'int a(int x) { return x+x; }'
TEST_CASE(func_uninit_pointer); // analyse function calls for: 'void a(int *p) { *p = 0; }'
TEST_CASE(uninitvar_typeof); // typeof
TEST_CASE(uninitvar_ignore); // ignore cast, *&x, ..
TEST_CASE(uninitvar2);
TEST_CASE(uninitvar3); // #3844
TEST_CASE(uninitvar4); // #3869 (reference)
TEST_CASE(uninitvar5); // #3861
TEST_CASE(uninitvar6); // #13227
TEST_CASE(uninitvar2_func); // function calls
TEST_CASE(uninitvar2_value); // value flow
TEST_CASE(valueFlowUninit2_value);
TEST_CASE(valueFlowUninit_uninitvar2);
TEST_CASE(valueFlowUninit_functioncall);
TEST_CASE(uninitStructMember); // struct members
TEST_CASE(uninitvar2_while);
TEST_CASE(uninitvar2_4494); // #4494
TEST_CASE(uninitvar2_malloc); // malloc returns uninitialized data
TEST_CASE(uninitvar8); // ticket #6230
TEST_CASE(uninitvar9); // ticket #6424
TEST_CASE(uninitvar10); // ticket #9467
TEST_CASE(uninitvar11); // ticket #9123
TEST_CASE(uninitvar12); // #10218 - stream read
TEST_CASE(uninitvar13); // #9772
TEST_CASE(uninitvar14);
TEST_CASE(uninitvar_unconditionalTry);
TEST_CASE(uninitvar_funcptr); // #6404
TEST_CASE(uninitvar_operator); // #6680
TEST_CASE(uninitvar_ternaryexpression); // #4683
TEST_CASE(uninitvar_pointertoarray);
TEST_CASE(uninitvar_cpp11ArrayInit); // #7010
TEST_CASE(uninitvar_rangeBasedFor); // #7078
TEST_CASE(uninitvar_static); // #8734
TEST_CASE(uninitvar_configuration);
TEST_CASE(checkExpr);
TEST_CASE(trac_4871);
TEST_CASE(syntax_error); // Ticket #5073
TEST_CASE(trac_5970);
TEST_CASE(valueFlowUninitTest);
TEST_CASE(valueFlowUninitBreak);
TEST_CASE(valueFlowUninitStructMembers);
TEST_CASE(uninitvar_ipa);
TEST_CASE(uninitvar_memberfunction);
TEST_CASE(uninitvar_nonmember); // crash in ycmd test
TEST_CASE(uninitvarDesignatedInitializers);
TEST_CASE(isVariableUsageDeref); // *p
TEST_CASE(isVariableUsageDerefValueflow); // *p
TEST_CASE(uninitvar_memberaccess); // (&(a))->b <=> a.b
// whole program analysis
TEST_CASE(ctuTest);
}
#define checkUninitVar(...) checkUninitVar_(__FILE__, __LINE__, __VA_ARGS__)
void checkUninitVar_(const char* file, int line, const char code[], bool cpp = true, bool debugwarnings = false, const Settings *s = nullptr) {
const Settings settings1 = settingsBuilder(s ? *s : settings).debugwarnings(debugwarnings).build();
// Tokenize..
SimpleTokenizer tokenizer(settings1, *this);
ASSERT_LOC(tokenizer.tokenize(code, cpp), file, line);
// Check for redundant code..
CheckUninitVar checkuninitvar(&tokenizer, &settings1, this);
checkuninitvar.check();
}
void uninitvar1() {
// extracttests.start: int b; int c;
// Ticket #2207 - False negative
checkUninitVar("void foo() {\n"
" int a;\n"
" b = c - a;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: a\n", errout_str());
checkUninitVar("void foo() {\n"
" int a;\n"
" b = a - c;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: a\n", errout_str());
// Ticket #6455 - some compilers allow const variables to be uninitialized
// extracttests.disable
checkUninitVar("void foo() {\n"
" const int a;\n"
" b = c - a;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: a\n", errout_str());
// extracttests.enable
checkUninitVar("void foo() {\n"
" int *p;\n"
" realloc(p,10);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: p\n", errout_str());
checkUninitVar("void foo() {\n" // #5240
" char *p = malloc(100);\n"
" char *tmp = realloc(p,1000);\n"
" if (!tmp) free(p);\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void foo() {\n"
" int *p = NULL;\n"
" realloc(p,10);\n"
"}");
ASSERT_EQUALS("", errout_str());
// dereferencing uninitialized pointer..
// extracttests.start: struct Foo { void abcd(); };
checkUninitVar("static void foo()\n"
"{\n"
" Foo *p;\n"
" p->abcd();\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: p\n", errout_str());
// extracttests.start: template<class T> struct Foo { void abcd(); };
checkUninitVar("static void foo()\n"
"{\n"
" Foo<int> *p;\n"
" p->abcd();\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: p\n", errout_str());
// extracttests.start: struct Foo { void* a; };
checkUninitVar("void f(Foo *p)\n"
"{\n"
" int a;\n"
" p->a = malloc(4 * a);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: a\n", errout_str());
checkUninitVar("static void foo()\n"
"{\n"
" int *p;\n"
" delete p;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: p\n", errout_str());
checkUninitVar("static void foo()\n"
"{\n"
" int *p;\n"
" delete [] p;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: p\n", errout_str());
checkUninitVar("static void foo()\n"
"{\n"
" int *p;\n"
" *p = 135;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: p\n", errout_str());
checkUninitVar("static void foo()\n"
"{\n"
" int *p;\n"
" p[0] = 135;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: p\n", errout_str());
checkUninitVar("static void foo()\n"
"{\n"
" int *x;\n"
" int y = *x;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: x\n", errout_str());
checkUninitVar("static void foo()\n"
"{\n"
" int *x;\n"
" int &y(*x);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: x\n", errout_str());
checkUninitVar("void foo()\n"
"{\n"
" int x;\n"
" int *y = &x;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void foo()\n"
"{\n"
" int *x;\n"
" int *&y = x;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void foo()\n"
"{\n"
" int x = xyz::x;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f()\n"
"{\n"
" int a;\n"
" a = 5 + a;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: a\n", errout_str());
checkUninitVar("void f()\n"
"{\n"
" int a;\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: a\n", errout_str());
checkUninitVar("void f()\n"
"{\n"
" extern int a;\n"
" a++;\n"
"}");
ASSERT_EQUALS("", errout_str());
// extracttests.start: void bar(int);
checkUninitVar("void f()\n"
"{\n"
" int a;\n"
" bar(4 * a);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: a\n", errout_str());
checkUninitVar("static void foo()\n"
"{\n"
" int i;\n"
" if (i);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: i\n", errout_str());
checkUninitVar("static void foo()\n"
"{\n"
" int i;\n"
" for (int x = 0; i < 10; x++);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: i\n", errout_str());
checkUninitVar("static void foo()\n"
"{\n"
" int i;\n"
" for (int x = 0; x < 10; i++);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: i\n", errout_str());
checkUninitVar("static void foo(int x)\n"
"{\n"
" int i;\n"
" if (x)\n"
" i = 0;\n"
" i++;\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Uninitialized variable: i\n", errout_str());
checkUninitVar("static void foo()\n"
"{\n"
" int ar[10];\n"
" int i;\n"
" ar[i] = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: i\n", errout_str());
checkUninitVar("static void foo()\n"
"{\n"
" int x, y;\n"
" x = (y = 10);\n"
" int z = y * 2;\n"
"}", true, false);
ASSERT_EQUALS("", errout_str());
checkUninitVar("static void foo() {\n"
" int x, y;\n"
" x = ((y) = 10);\n"
"}");
ASSERT_EQUALS("", errout_str());
// Ticket #3597
checkUninitVar("void f() {\n"
" int a;\n"
" int b = 1;\n"
" (b += a) = 1;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: a\n", errout_str());
checkUninitVar("int f() {\n"
" int a,b,c;\n"
" a = b = c;\n"
"}", true, /*debugwarnings=*/ false);
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: c\n", errout_str());
checkUninitVar("static void foo()\n"
"{\n"
" Foo p;\n"
" p.abcd();\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("static void foo()\n"
"{\n"
" Foo p;\n"
" int x = p.abcd();\n"
"}");
ASSERT_EQUALS("", errout_str());
// Unknown types
// extracttests.disable
{
checkUninitVar("void a()\n"
"{\n"
" A ret;\n"
" return ret;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void a()\n"
"{\n"
" A ret;\n"
" return ret;\n"
"}\n",
false);
ASSERT_EQUALS("[test.c:4]: (error) Uninitialized variable: ret\n", errout_str());
}
// extracttests.enable
// #3916 - avoid false positive
checkUninitVar("void f(float x) {\n"
" union lf { long l; float f; } u_lf;\n"
" float hx = (u_lf.f = (x), u_lf.l);\n"
"}",
false, false);
ASSERT_EQUALS("", errout_str());
checkUninitVar("void a()\n"
"{\n"
" int x[10];\n"
" int *y = x;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void a()\n"
"{\n"
" int x;\n"
" int *y = &x;\n"
" *y = 0;\n"
" x++;\n"
"}", true, false);
ASSERT_EQUALS("", errout_str());
checkUninitVar("void a()\n"
"{\n"
" char x[10], y[10];\n"
" char *z = x;\n"
" memset(z, 0, sizeof(x));\n"
" memcpy(y, x, sizeof(x));\n"
"}", true, false);
ASSERT_EQUALS("", errout_str());
// Handling >> and <<
{
checkUninitVar("int a() {\n"
" int ret;\n"
" std::cin >> ret;\n"
" ret++;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f(int b) {\n"
" int a;\n"
" std::cin >> b >> a;\n"
" return a;"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n"
" int ret[2];\n"
" std::cin >> ret[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f(int i) {\n"
" int a;\n"
" i >> a;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: a\n", errout_str());
checkUninitVar("int a() {\n"
" int ret;\n"
" int a = value >> ret;\n"
"}\n",
false);
ASSERT_EQUALS("[test.c:3]: (error) Uninitialized variable: ret\n", errout_str());
checkUninitVar("void foo() {\n" // #3707
" Node node;\n"
" int x;\n"
" node[\"abcd\"] >> x;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("int a(FArchive &arc) {\n" // #3060 (initialization through operator<<)
" int *p;\n"
" arc << p;\n" // <- TODO initialization?
" return *p;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: p\n", errout_str());
checkUninitVar("void a() {\n"
" int ret;\n"
" a = value << ret;\n"
"}\n",
false);
ASSERT_EQUALS("[test.c:3]: (error) Uninitialized variable: ret\n", errout_str());
// #4320 says this is a FP. << is overloaded.
checkUninitVar("int f() {\n"
" int a;\n"
" a << 1;\n" // <- TODO initialization?
" return a;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: a\n", errout_str());
// #4673
checkUninitVar("void f() {\n"
" int a;\n"
" std::cout << a;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: a\n", errout_str());
checkUninitVar("void f(std::ostringstream& os) {\n"
" int a;\n"
" os << a;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: a\n", errout_str());
checkUninitVar("void f() {\n"
" int a;\n"
" std::cout << 1 << a;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: a\n", errout_str());
checkUninitVar("void f(std::ostringstream& os) {\n"
" int a;\n"
" os << 1 << a;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: a\n", errout_str());
{
// #9422
checkUninitVar("void f() {\n"
" char *p = new char[10];\n"
" std::cout << (void *)p << 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n"
" char p[10];\n"
" std::cout << (void *)p << 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n"
" char *p = new char[10];\n"
" std::cout << p << 1;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Memory is allocated but not initialized: p\n", errout_str());
checkUninitVar("void f() {\n" // #9696
" int *p = new int[10];\n"
" std::cout << p << 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n"
" int i[10];\n"
" std::cout << i;\n"
" char c[10];\n"
" std::cout << c;\n"
" wchar_t w[10];\n"
" std::cout << w;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: c\n"
"[test.cpp:7]: (error) Uninitialized variable: w\n",
errout_str());
checkUninitVar("void f() {\n"
" char p[10];\n"
" std::cout << p << 1;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: p\n", errout_str());
checkUninitVar("void f() {\n"
" char p[10];\n"
" std::cout << *p << 1;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: p\n", errout_str());
}
}
// #8494 : Overloaded & operator
checkUninitVar("void f() {\n"
" int x;\n"
" a & x;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f(int a) {\n"
" int x;\n"
" a & x;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: x\n", errout_str());
checkUninitVar("void f() {\n"
" int a,b,c;\n"
" ar & a & b & c;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void a() {\n" // asm
" int x;\n"
" asm();\n"
" x++;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void a()\n"
"{\n"
" int x[10];\n"
" struct xyz xyz1 = { .x = x };\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void a()\n"
"{\n"
" struct S *s;\n"
" s->x = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: s\n", errout_str());
checkUninitVar("void foo()\n"
"{\n"
" char *buf = malloc(100);\n"
" struct ABC *abc = buf;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("class Fred {\n"
"public:\n"
" FILE *f;\n"
" ~Fred();\n"
"}\n"
"Fred::~Fred()\n"
"{\n"
" fclose(f);\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f()\n"
"{\n"
" int c;\n"
" ab(sizeof(xyz), &c);\n"
" if (c);\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f()\n"
"{\n"
" int c;\n"
" a = (f2(&c));\n"
" c++;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f(int a)\n"
"{\n"
" if (a) {\n"
" char *p;\n"
" *p = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: p\n", errout_str());
// +=
checkUninitVar("void f()\n"
"{\n"
" int c;\n"
" c += 2;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: c\n", errout_str());
checkUninitVar("void f()\n"
"{\n"
" int a[10];\n"
" a[0] = 10 - a[1];\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: a[1]\n", errout_str());
// goto/setjmp/longjmp..
checkUninitVar("void foo(int x)\n"
"{\n"
" long b;\n"
" if (g()) {\n"
" b =2;\n"
" goto found;\n"
" }\n"
"\n"
" return;\n"
"\n"
"found:\n"
" int a = b;\n"
"}", true, false);
ASSERT_EQUALS("", errout_str());
checkUninitVar("int foo()\n"
"{\n"
" jmp_buf env;\n"
" int a;\n"
" int val = setjmp(env);\n"
" if(val)\n"
" return a;\n"
" a = 1;\n"
" longjmp(env, 1);\n"
"}");
ASSERT_EQUALS("", errout_str());
// macro_for..
checkUninitVar("int foo()\n"
"{\n"
" int retval;\n"
" if (condition) {\n"
" for12(1,2) { }\n"
" retval = 1;\n"
" }\n"
" else\n"
" retval = 2;\n"
" return retval;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("int foo()\n"
"{\n"
" int i;\n"
" goto exit;\n"
" i++;\n"
"exit:\n"
"}", true, false);
ASSERT_EQUALS("", errout_str());
checkUninitVar("int foo() {\n"
" int x,y=0;\n"
"again:\n"
" if (y) return x;\n"
" x = a;\n"
" y = 1;\n"
" goto again;\n"
"}", false, false);
ASSERT_EQUALS("", errout_str());
// Ticket #3873 (false positive)
checkUninitVar("MachineLoopRange *MachineLoopRanges::getLoopRange(const MachineLoop *Loop) {\n"
" MachineLoopRange *&Range = Cache[Loop];\n"
" if (!Range)\n"
" Range = new MachineLoopRange(Loop, Allocator, *Indexes);\n"
" return Range;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #4040 - False positive
checkUninitVar("int f(int x) {\n"
" int iter;\n"
" {\n"
" union\n"
" {\n"
" int asInt;\n"
" double asDouble;\n"
" };\n"
"\n"
" iter = x;\n"
" }\n"
" return 1 + iter;\n"
"}", true, false);
ASSERT_EQUALS("", errout_str());
// C++11 style initialization
checkUninitVar("int f() {\n"
" int i = 0;\n"
" int j{ i };\n"
" return j;\n"
"}");
ASSERT_EQUALS("", errout_str());
// Ticket #5646
checkUninitVar("float foo() {\n"
" float source[2] = {3.1, 3.1};\n"
" float (*sink)[2] = &source;\n"
" return (*sink)[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
// Ticket #9296
checkUninitVar("void f(void)\n"
"{\n"
" int x;\n"
" int z = (x) & ~__round_mask(1, 1);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: x\n", errout_str());
checkUninitVar("void f(void)\n"
"{\n"
" int x;\n"
" int z = (x) | ~__round_mask(1, 1);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: x\n", errout_str());
checkUninitVar("int __round_mask(int, int);\n"
"void f(void)\n"
"{\n"
" int x;\n"
" int* z = &x;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void uninitvar_warn_once() {
// extracttests.start: int a; int b;
checkUninitVar("void f() {\n"
" int x;\n"
" a = x;\n"
" b = x;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: x\n", errout_str());
}
// Handling of unknown types. Assume they are POD in C.
void uninitvar_decl() {
const char code[] = "void f() {\n"
" dfs a;\n"
" return a;\n"
"}";
// Assume dfs is a non POD type if file is C++
checkUninitVar(code, true);
ASSERT_EQUALS("", errout_str());
// Assume dfs is a POD type if file is C
checkUninitVar(code, false);
ASSERT_EQUALS("[test.c:3]: (error) Uninitialized variable: a\n", errout_str());
const char code2[] = "struct AB { int a,b; };\n"
"void f() {\n"
" struct AB ab;\n"
" return ab;\n"
"}";
checkUninitVar(code2, true);
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized struct member: ab.a\n"
"[test.cpp:4]: (error) Uninitialized struct member: ab.b\n", errout_str());
checkUninitVar(code2, false);
ASSERT_EQUALS("[test.c:4]: (error) Uninitialized variable: ab\n", errout_str());
// Ticket #3890 - False positive for std::map
checkUninitVar("void f() {\n"
" std::map<int,bool> x;\n"
" return x;\n"
"}");
ASSERT_EQUALS("", errout_str());
// Ticket #3906 - False positive for std::vector pointer
checkUninitVar("void f() {\n"
" std::vector<int> *x = NULL;\n"
" return x;\n"
"}", true, false);
ASSERT_EQUALS("", errout_str());
{
// Ticket #6701 - Variable name is a POD type according to cfg
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def format=\"1\">"
" <podtype name=\"_tm\"/>"
"</def>";
const Settings s = settingsBuilder(settings).libraryxml(xmldata, sizeof(xmldata)).build();
checkUninitVar("void f() {\n"
" Fred _tm;\n"
" _tm.dostuff();\n"
"}", true, false, &s);
ASSERT_EQUALS("", errout_str());
}
// Ticket #7822 - Array type
checkUninitVar("A *f() {\n"
" A a,b;\n"
" b[0] = 0;"
" return a;\n"
"}", false, false);
ASSERT_EQUALS("", errout_str());
}
void uninitvar3() { // #3844
// avoid false positive
checkUninitVar("namespace std _GLIBCXX_VISIBILITY(default)\n"
"{\n"
"_GLIBCXX_BEGIN_NAMESPACE_CONTAINER\n"
" typedef unsigned long _Bit_type;\n"
" struct _Bit_reference\n"
" {\n"
" _Bit_type * _M_p;\n"
" _Bit_type _M_mask;\n"
" _Bit_reference(_Bit_type * __x, _Bit_type __y)\n"
" : _M_p(__x), _M_mask(__y) { }\n"
" };\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void uninitvar_bitop() {
// extracttests.start: int a; int c;
checkUninitVar("void foo() {\n"
" int b;\n"
" c = a | b;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: b\n", errout_str());
checkUninitVar("void foo() {\n"
" int b;\n"
" c = b | a;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: b\n", errout_str());
}
// if..
void uninitvar_if() {
// extracttests.start: struct Foo { void abcd(); };
checkUninitVar("static void foo(int x)\n"
"{\n"
" Foo *p;\n"
" if (x)\n"
" p = new Foo;\n"
" p->abcd();\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Uninitialized variable: p\n", errout_str());
checkUninitVar("static void foo(int x)\n"
"{\n"
" int a;\n"
" if (x==1);\n"
" if (x==2);\n"
" x = a;\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Uninitialized variable: a\n", errout_str());
checkUninitVar("int foo() {\n"
" int i;\n"
" if (1)\n"
" i = 11;\n"
" return i;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("int bar(int x) {\n"
" int n;\n"
" if ( x == 23)\n"
" n = 1;\n"
" else if ( x == 11 )\n"
" n = 2;\n"
" return n;\n"
"}");
TODO_ASSERT_EQUALS("error", "", errout_str());
checkUninitVar("int foo()\n"
"{\n"
" int i;\n"
" if (x)\n"
" i = 22;\n"
" else\n"
" i = 33;\n"
" return i;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("int foo(int x)\n" // #5503
"{\n"
" int i;\n"
" if (x < 2)\n"
" i = 22;\n"
" else if (x >= 2)\n" // condition is always true
" i = 33;\n"
" return i;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("int foo()\n"
"{\n"
" int i;\n"
" if (x)\n"
" i = 22;\n"
" else\n"
" {\n"
" char *y = {0};\n"
" i = 33;\n"
" }\n"
" return i;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("int foo()\n"
"{\n"
" int i;\n"
" if (x)\n"
" {\n"
" struct abc abc1 = (struct abc) { .a=0, .b=0, .c=0 };\n"
" i = 22;\n"
" }\n"
" else\n"
" {\n"
" i = 33;\n"
" }\n"
" return i;\n"
"}", true, false);
ASSERT_EQUALS("", errout_str());
checkUninitVar("static void foo(int x)\n"
"{\n"
" Foo *p;\n"
" if (x)\n"
" p = new Foo;\n"
" if (x)\n"
" p->abcd();\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void foo(int a)\n"
"{\n"
" int n;\n"
" int condition;\n"
" if(a == 1) {\n"
" n=0;\n"
" condition=0;\n"
" }\n"
" else {\n"
" n=1;\n"
" }\n"
"\n"
" if( n == 0) {\n"
" a=condition;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f()\n"
"{\n"
" C *c;\n"
" if (fun(&c));\n"
" c->Release();\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n"
" C c;\n"
" if (fun(&c.d));\n"
" return c;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n"
" char a[10];\n"
" if (a[0] = x){}\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("int foo(int x)\n"
"{\n"
" int i;\n"
" if (one())\n"
" i = 1;\n"
" else\n"
" return 3;\n"
" return i;\n"
"}");
ASSERT_EQUALS("", errout_str());
// Ticket #2207 - False positive
checkUninitVar("void foo(int x) {\n"
" int a;\n"
" if (x)\n"
" a = 1;\n"
" if (!x)\n"
" return;\n"
" b = (c - a);\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("int foo()\n"
"{\n"
" int ret;\n"
" if (one())\n"
" ret = 1;\n"
" else\n"
" throw 3;\n"
" return ret;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("int f(int a)\n"
"{\n"
" int ret;\n"
" if (a == 1)\n"
" ret = 1;\n"
" else\n"
" XYZ ret = 2;\n" // XYZ may be an unexpanded macro so bailout the checking of "ret".
" return ret;\n"
"}");
ASSERT_EQUALS("[test.cpp:8]: (error) Uninitialized variable: ret\n", errout_str());
checkUninitVar("int f(int a, int b)\n"
"{\n"
" int x;\n"
" if (a)\n"
" x = a;\n"
" else {\n"
" do { } while (f2());\n"
" x = b;\n"
" }\n"
" return x;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void foo(long verbose,bool bFlag)\n"
"{\n"
" double t;\n"
" if (bFlag)\n"
" {\n"
" if (verbose)\n"
" t = 1;\n"
" if (verbose)\n"
" std::cout << (12-t);\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("int test(int cond1, int cond2) {\n"
" int foo;\n"
" if (cond1 || cond2) {\n"
" if (cond2)\n"
" foo = 0;\n"
" }\n"
" if (cond2) {\n"
" int t = foo*foo;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void foo(int *pix) {\n"
" int dest_x;\n"
" {\n"
" if (pix)\n"
" dest_x = 123;\n"
" }\n"
" if (pix)\n"
" a = dest_x;\n" // <- not uninitialized
"}");
ASSERT_EQUALS("", errout_str());
// ? :
checkUninitVar("static void foo(int v) {\n"
" int x;\n"
" x = v <= 0 ? -1 : x;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: x\n", errout_str());
checkUninitVar("void foo()\n"
"{\n"
" const char *msgid1, *msgid2;\n"
" int ret = bar(&msgid1);\n"
" if (ret > 0) {\n"
" ret = bar(&msgid2);\n"
" }\n"
" ret = ret <= 0 ? -1 :\n"
" strcmp(msgid1, msgid2) == 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void foo(int a, int b)\n"
"{\n"
" int x; x = (a<b) ? 1 : 0;\n"
" int y = y;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: y\n", errout_str());
checkUninitVar("void foo() {\n" // pidgin-2.11.0/finch/libgnt/gnttree.c
" int x = (x = bar()) ? x : 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
// ; { .. }
checkUninitVar("int foo()\n"
"{\n"
" int retval;\n"
" if (condition) {\n"
" { }\n"
" retval = 1; }\n"
" else\n"
" retval = 2;\n"
" return retval;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void foo()\n"
"{\n"
" {\n"
" for (int i = 0; i < 10; ++i)\n"
" { }\n"
" }\n"
"\n"
" { }\n"
"}");
ASSERT_EQUALS("", errout_str());
// ({ .. })
checkUninitVar("void f() {\n"
" int x;\n"
" if (abc) { x = 123; }\n"
" else { a = ({b=c;}); x = 456; }\n"
" ++x;\n"
"}");
ASSERT_EQUALS("", errout_str());
// Ticket #3098 - False negative uninitialized variable
checkUninitVar("void f()\n"
"{\n"
" char *c1,*c2;\n"
" if(strcoll(c1,c2))\n"
" {\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: c1\n"
"[test.cpp:4]: (error) Uninitialized variable: c2\n", errout_str());
checkUninitVar("void f(char *c1, char *c2)\n"
"{\n"
" if(strcoll(c1,c2))\n"
" {\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f()\n"
"{\n"
" char *c1;\n"
" c1=strcpy(c1,\"test\");\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: c1\n", errout_str());
checkUninitVar("void f(char *c1)\n"
"{\n"
" c1=strcpy(c1,\"test\");\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n"
" X var;\n"
" memset(var, 0, sizeof(var));\n"
"}", false);
ASSERT_EQUALS("", errout_str());
checkUninitVar("int f() {\n" // #8692
" bool b = e();\n"
" int v;\n"
" if (b)\n"
" doStuff(&v);\n"
" int v2 = (b) ? v / 5 : 0;\n"
" int v3;\n"
" if (b)\n"
" v3 = 50;\n"
" int v4 = (b) ? v3 + 5 : 0;\n"
" int v5;\n"
" int v6 = v5;\n"
" doStuff(&v5);\n"
" int v7 = v5;\n"
" return v2 + v4 + v6 + v7;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:12]: (error) Uninitialized variable: v5\n", errout_str());
checkUninitVar("bool set(int *p);\n"
"\n"
"void foo(bool a) {\n"
" bool flag{false};\n"
" int x;\n"
" if (!a) {\n"
" flag = set(&x);\n"
" }\n"
" if (!flag || x == 0) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f(int n, int a) {\n" // #12011
" double x[10];\n"
" if (n == 1) {\n"
" if (a)\n"
" x[0] = 4;\n"
" }\n"
" else\n"
" for (int i = 0; i < n; i++) {\n"
" if (a)\n"
" x[i] = 8;\n"
" }\n"
" if (n == 1)\n"
" if (a)\n"
" (void)x[0];\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
// handling for/while loops..
void uninitvar_loops() {
// for..
// extracttests.start: void b(int);
checkUninitVar("void f()\n"
"{\n"
" for (int i = 0; i < 4; ++i) {\n"
" int a;\n"
" b(4*a);\n"
" }"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: a\n", errout_str());
checkUninitVar("void f() {\n"
" int k;\n"
" for (int i = 0; i < 4; ++i) {\n"
" k = k + 2;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: k\n", errout_str());
checkUninitVar("void f() {\n"
" gchar sel[10];\n"
" for (int i = 0; i < 4; ++i) {\n"
" int sz = sizeof(sel);\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("enum ABCD { A, B, C, D };\n"
"\n"
"static void f(char *str ) {\n"
" enum ABCD i;\n"
" for (i = 0; i < D; i++) {\n"
" str[i] = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void x() {\n"
" do {\n"
" Token * tok;\n"
" for (tok = a; tok; tok = tok->next())\n"
" {\n"
" }\n"
" } while (tok2);\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void foo(void) {\n"
" int a = 0;\n"
" int x;\n"
"\n"
" for (;;) {\n"
" if (!a || 12 < x) {\n" // <- x is not uninitialized
" a = 1;\n"
" x = 2;\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void foo(void) {\n"
" int a = 0;\n"
" int x;\n"
"\n"
" for (;;) {\n"
" if (!a || 12 < x) {\n" // <- x is uninitialized
" a = 1;\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Uninitialized variable: x\n", errout_str());
checkUninitVar("void foo(int n) {\n"
" int one[10];\n"
" for (int rank = 0; rank < n; ++rank) {\n"
" for (int i=0;i<rank;i++)\n"
" f = one[i];\n"
" one[rank] = -1;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// Ticket #2226: C++0x loop
checkUninitVar("void f() {\n"
" container c;\n"
" for (iterator it : c) {\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// Ticket #2345: False positive in sub-condition in if inside a loop
checkUninitVar("void f(int x) {\n"
" const PoolItem* pItem;\n"
" while (x > 0) {\n"
" if (GetItem(&pItem) && (*pItem != rPool))\n"
" { }\n"
" x--;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// extracttests.start: struct PoolItem { bool operator!=(const PoolItem&) const; };
checkUninitVar("void f(int x, const PoolItem& rPool) {\n"
" const PoolItem* pItem;\n"
" while (x > 0) {\n"
" if (*pItem != rPool)\n"
" { }\n"
" x--;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: pItem\n", errout_str());
// #2231 - conditional initialization in loop..
checkUninitVar("int foo(char *a) {\n"
" int x;\n"
"\n"
" for (int i = 0; i < 10; ++i) {\n"
" if (a[i] == 'x') {\n"
" x = i;\n"
" break;\n"
" }\n"
" }\n"
"\n"
" return x;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:11]: (error) Uninitialized variable: x\n", "", errout_str());
// Ticket #2796
checkUninitVar("void foo() {\n"
" while (true) {\n"
" int x;\n"
" if (y) x = 0;\n"
" else break;\n"
" return x;\n" // <- x is initialized
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// Assignment in for. Ticket #3287
checkUninitVar("int foo(char* in, bool b) {\n"
" char* c;\n"
" if (b) for (c = in; *c == 0; ++c) {}\n"
" else c = in + strlen(in) - 1;\n"
" *c = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #10273 - assignment in conditional code
// extracttests.start: extern const int PORT_LEARN_DISABLE;
checkUninitVar("void foo() {\n"
" int learn;\n"
" for (int index = 0; index < 10; index++) {\n"
" if (!(learn & PORT_LEARN_DISABLE))\n"
" learn = 123;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: learn\n", errout_str());
// extracttests.start: struct Entry { Entry *next; }; Entry *buckets[10];
checkUninitVar("void foo() {\n"
" Entry *entry, *nextEntry;\n"
" for(int i = 0; i < 10; i++) {\n"
" for(entry = buckets[i]; entry != NULL; entry = nextEntry) {\n" // <- nextEntry is not uninitialized
" nextEntry = entry->next;\n"
" }\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void foo() {\n"
" Entry *entry, *nextEntry;\n"
" for(int i = 0; i < 10; i++) {\n"
" for(entry = buckets[i]; entry != NULL; entry = nextEntry) {\n"
" }\n"
" }\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: nextEntry\n", errout_str());
checkUninitVar("void f(int x) {\n"
" list *f = NULL;\n"
" list *l;\n"
"\n"
" while (--x) {\n"
" if (!f)\n"
" f = c;\n"
" else\n"
" l->next = c;\n" // <- not uninitialized
" l = c;\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #6952 - do-while-loop
checkUninitVar("void f(void)\n"
"{\n"
" int* p;\n"
" do\n"
" {\n"
" if (true) {;}\n"
" else\n"
" {\n"
" return;\n"
" }\n"
" *p = 7;\n" // <<
" p = new int(9);\n"
" } while (*p != 8);\n"
"}");
ASSERT_EQUALS("[test.cpp:11]: (error) Uninitialized variable: p\n", errout_str());
// #6952 - while-loop
checkUninitVar("void f(void)\n"
"{\n"
" int* p;\n"
" while (*p != 8) {\n" // <<
" *p = 7;\n"
" p = new int(9);\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: p\n", errout_str());
// switch in loop
checkUninitVar("int foo(int *p) {\n"
" int x;\n"
" while (true) {\n"
" switch (*p) {\n"
" case 1:\n"
" return x;\n"
" case 2:\n"
" x = 123;\n"
" break;\n"
" };\n"
" ++p\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
// switch..
void uninitvar_switch() {
checkUninitVar("void f(int x)\n"
"{\n"
" short c;\n"
" switch(x) {\n"
" case 1:\n"
" c++;\n"
" break;\n"
" };\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:6]: (error) Uninitialized variable: c\n", "", errout_str());
checkUninitVar("char * f()\n"
"{\n"
" static char ret[200];\n"
" memset(ret, 0, 200);\n"
" switch (x)\n"
" {\n"
" case 1: return ret;\n"
" case 2: return ret;\n"
" }\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("int foo(const int iVar, unsigned int slot, unsigned int pin)\n"
"{\n"
" int i;\n"
" if (iVar == 0)\n"
" {\n"
" switch (slot)\n"
" {\n"
" case 4: return 5;\n"
" default: return -1;\n"
" }\n"
" }\n"
" else\n"
" {\n"
" switch (pin)\n"
" {\n"
" case 0: i = 2; break;\n"
" default: i = -1; break;\n"
" }\n"
" }\n"
" return i;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #1855 - switch(foo(&x))
checkUninitVar("int a()\n"
"{\n"
" int x;\n"
" switch (foo(&x))\n"
" {\n"
" case 1:\n"
" return x;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// #3231 - ({ switch .. })
checkUninitVar("void f() {\n"
" int a;\n"
" ({\n"
" switch(sizeof(int)) {\n"
" case 4:\n"
" default:\n"
" (a)=0;\n"
" break;\n"
" };\n"
" })\n"
"}", true, false);
ASSERT_EQUALS("", errout_str());
}
// arrays..
void uninitvar_arrays() {
checkUninitVar("void f()\n"
"{\n"
" char a[10];\n"
" a[a[0]] = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: a[0]\n", errout_str());
checkUninitVar("int f()\n"
"{\n"
" char a[10];\n"
" *a = '\\0';\n"
" int i = strlen(a);\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f()\n"
"{\n"
" char a, b[10];\n"
" a = b[0] = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f()\n"
"{\n"
" char a[10], b[10];\n"
" a[0] = b[0] = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f()\n"
"{\n"
" char a[10], *p;\n"
" *(p = a) = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n"
" char a[10], *p;\n"
" p = &(a[10]);\n"
"}");
ASSERT_EQUALS("", errout_str());
// array usage in ?: (tests that the isVariableUsed() works)
checkUninitVar("void f() {\n"
" char a[10], *p;\n"
" p = c?a:0;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f(int x) {\n"
" char a[10], c;\n"
" c = *(x?a:0);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: a\n", errout_str());
checkUninitVar("void f() {\n"
" char a[10], c;\n"
" strcpy(dest, x?a:\"\");\n"
"}");
TODO_ASSERT_EQUALS("error", "", errout_str());
checkUninitVar("void f(int x) {\n"
" int a[2];\n"
" y *= (x ? 1 : 2);\n"
"}");
ASSERT_EQUALS("", errout_str());
// passing array to library functions
checkUninitVar("void f()\n"
"{\n"
" char c[50] = \"\";\n"
" strcat(c, \"test\");\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f(char *s2) {\n"
" char s[20];\n"
" strcpy(s2, s);\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: s\n", errout_str());
checkUninitVar("void f() {\n"
" char s[20];\n"
" strcat(s, \"abc\");\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: s\n", errout_str());
checkUninitVar("void f() {\n"
" char s[20];\n"
" strchr(s, ' ');\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: s\n", errout_str());
checkUninitVar("void foo()\n"
"{\n"
" int y[2];\n"
" int s;\n"
" GetField( y + 0, y + 1 );\n"
" s = y[0] * y[1];\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void foo()\n"
"{\n"
" int a[2];\n"
" init(a - 1);\n"
" int b = a[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void foo()\n"
"{\n"
" Fred a[2];\n"
" Fred b = a[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void foo() {\n"
" char buf[1024];\n"
" char *b = (char *) (((uintptr_t) buf + 63) & ~(uintptr_t) 63);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void foo() {\n"
" char buf[1024];\n"
" char x = *(char *) (((uintptr_t) buf + 63) & ~(uintptr_t) 63);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: buf\n", errout_str());
// Passing array to function
checkUninitVar("void f(int i);\n"
"void foo()\n"
"{\n"
" int a[10];\n"
" f(a[0]);\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: a\n", errout_str());
// Ticket #2320
checkUninitVar("void foo() {\n"
" char a[2];\n"
" unsigned long b = (unsigned long)(a+2) & ~7;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n" // Ticket #3050
" char a[2];\n"
" printf(\"%s\", a);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: a\n", "", errout_str());
checkUninitVar("void f() {\n" // Ticket #5108 (fp)
" const char *a;\n"
" printf(\"%s\", a=\"abc\");\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n" // Ticket #3497
" char header[1];\n"
" *((unsigned char*)(header)) = 0xff;\n"
" return header[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n" // Ticket #3497
" char header[1];\n"
" *((unsigned char*)((unsigned char *)(header))) = 0xff;\n"
" return header[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n"
" ABC abc;\n"
" int a[1];\n"
"\n"
" abc.a = a;\n"
" init(&abc);\n"
" return a[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
// ticket #3344
checkUninitVar("void f(){\n"
" char *strMsg = \"This is a message\";\n"
" char *buffer=(char*)malloc(128*sizeof(char));\n"
" strcpy(strMsg,buffer);\n"
" free(buffer);\n"
"}", true, false);
ASSERT_EQUALS("[test.cpp:4]: (error) Memory is allocated but not initialized: buffer\n", errout_str());
checkUninitVar("void f(){\n"
" char *strMsg = \"This is a message\";\n"
" char *buffer=static_cast<char*>(malloc(128*sizeof(char)));\n"
" strcpy(strMsg,buffer);\n"
" free(buffer);\n"
"}", true, false);
ASSERT_EQUALS("[test.cpp:4]: (error) Memory is allocated but not initialized: buffer\n", errout_str());
// #3845
checkUninitVar("int foo() {\n"
" int a[1] = {5};\n"
" return a[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("int foo() {\n"
" int a[2][2] = {{3,4}, {5,6}};\n"
" return a[0][1];\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("int foo() {\n"
" int a[1];\n"
" return a[0];\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: a\n", errout_str());
checkUninitVar("int foo() {\n"
" int a[2][2];\n"
" return a[0][1];\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: a\n", errout_str());
checkUninitVar("int foo() {\n"
" int a[10];\n"
" dostuff(a[0]);\n"
"}");
ASSERT_EQUALS("", errout_str());
// # 4740
checkUninitVar("void f() {\n"
" int *a[2][19];\n"
" int **b = a[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
// #6869 - FP when passing uninit array to function
checkUninitVar("void bar(PSTR x);\n"
"void foo() {\n"
" char x[10];\n"
" bar(x);\n"
"}");
ASSERT_EQUALS("", errout_str());
// struct
checkUninitVar("struct Fred { int x; int y; };\n"
""
"void f() {\n"
" struct Fred fred[10];\n"
" fred[1].x = 0;\n"
"}", false);
ASSERT_EQUALS("", errout_str());
checkUninitVar("char f() {\n"
" std::array<char, 1> a;\n"
" return a[0];\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: a\n", errout_str());
checkUninitVar("std::string f() {\n"
" std::array<std::string, 1> a;\n"
" return a[0];\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkUninitVar("int f() {\n" // #12355
" const int x[10](1, 2);\n"
" if (x[0] == 1) {}\n"
" return x[0];\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void uninitvar_pointertoarray() {
checkUninitVar("void draw_quad(float z) {\n"
" int i;\n"
" float (*vertices)[2][4];\n"
" vertices[0][0][0] = z;\n"
" vertices[0][0][1] = z;\n"
" vertices[1][0][0] = z;\n"
" vertices[1][0][1] = z;\n"
" vertices[2][0][0] = z;\n"
" vertices[2][0][1] = z;\n"
" vertices[3][0][0] = z;\n"
" vertices[3][0][1] = z;\n"
" for (i = 0; i < 4; i++) {\n"
" vertices[i][0][2] = z;\n"
" vertices[i][0][3] = 1.0;\n"
" vertices[i][1][0] = 2.0;\n"
" vertices[i][1][1] = 3.0;\n"
" vertices[i][1][2] = 4.0;\n"
" vertices[i][1][3] = 5.0;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: vertices\n",
errout_str());
checkUninitVar("void f() {\n"
" std::array<int, 3> *PArr[2] = { p0, p1 };\n"
" (*PArr[0])[2] = 0;\n"
" (*PArr[1])[2] = 0;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void uninitvar_cpp11ArrayInit() { // #7010
checkUninitVar("double foo(bool flag) {\n"
" double adIHPoint_local[4][4]{};\n"
" function(*adIHPoint_local);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
// alloc..
void uninitvar_alloc() {
checkUninitVar("void f() {\n"
" char *s = (char *)malloc(100);\n"
" strcat(s, \"abc\");\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (error) Memory is allocated but not initialized: s\n", errout_str());
checkUninitVar("void f()\n"
"{\n"
" char *s1 = new char[10];\n"
" char *s2 = new char[strlen(s1)];\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (error) Memory is allocated but not initialized: s1\n", errout_str());
checkUninitVar("void f()\n"
"{\n"
" char *p = (char*)malloc(64);\n"
" int x = p[0];\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Memory is allocated but not initialized: p\n", errout_str());
checkUninitVar("void f() {\n"
" char *p = (char*)malloc(64);\n"
" if (p[0]) { }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Memory is allocated but not initialized: p[0]\n", errout_str());
checkUninitVar("char f() {\n"
" char *p = (char*)malloc(64);\n"
" return p[0];\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Memory is allocated but not initialized: p\n", errout_str());
checkUninitVar("void f()\n"
"{\n"
" Fred *fred = new Fred;\n"
" fred->foo();\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("struct Fred { int i; Fred(int, float); };\n"
"void f() {\n"
" Fred *fred = new Fred(1, 2);\n"
" fred->foo();\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f()\n"
"{\n"
" Fred *fred = malloc(sizeof(Fred));\n"
" x(&fred->f);\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f()\n"
"{\n"
" Fred *fred = malloc(sizeof(Fred));\n"
" x(fred->f);\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void foo(char *s)\n"
"{\n"
" char *a = malloc(100);\n"
" *a = *s;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void foo()\n"
"{\n"
" char *a;\n"
" if (a);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: a\n", errout_str());
checkUninitVar("void foo()\n"
"{\n"
" char *a = malloc(100);\n"
" if (a);\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void foo()\n"
"{\n"
" ABC *abc = malloc(100);\n"
" abc->a = 123;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void foo()\n"
"{\n"
" ABC *abc = malloc(100);\n"
" abc->a.word = 123;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void foo()\n"
"{\n"
" ABC *abc = malloc(100);\n"
" abc->a = 123;\n"
" abc->a += 123;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void foo()\n"
"{\n"
" ABC *abc = malloc(100);\n"
" free(abc);\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f()\n"
"{\n"
" char *s = (char*)malloc(100);\n"
" if (!s)\n"
" return;\n"
" char c = *s;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:6]: (error) Memory is allocated but not initialized: s\n", "", errout_str());
// #3708 - false positive when using ptr typedef
checkUninitVar("void f() {\n"
" uintptr_t x = malloc(100);\n"
" uintptr_t y = x + 10;\n" // <- not bad usage
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n"
" z_stream strm;\n"
" char* buf = malloc(10);\n"
" strm.next_out = buf;\n"
" deflate(&strm, Z_FINISH);\n"
" memcpy(body, buf, 10);\n"
"}");
ASSERT_EQUALS("", errout_str());
// #6451 - allocation in subscope
checkUninitVar("struct StgStrm {\n"
" StgIo& rIo;\n"
" StgStrm(StgIo&);\n"
" virtual sal_Int32 Write();\n"
"};\n"
"void Tmp2Strm() {\n"
" StgStrm* pNewStrm;\n"
" if (someflag)\n"
" pNewStrm = new StgStrm(rIo);\n"
" else\n"
" pNewStrm = new StgStrm(rIo);\n"
" pNewStrm->Write();\n"
"}");
ASSERT_EQUALS("", errout_str());
// #6450 - calling a member function is allowed if memory was allocated by new
checkUninitVar("struct EMFPFont {\n"
" bool family;\n"
" void Initialize();\n"
"};\n"
"void processObjectRecord() {\n"
" EMFPFont *font = new EMFPFont();\n"
" font->Initialize();\n"
"}");
ASSERT_EQUALS("", errout_str());
// #7623 - new can also initialize the memory, don't warn in this case
checkUninitVar("void foo(){\n"
" int* p1 = new int(314);\n"
" int* p2 = new int();\n"
" int* arr = new int[5]();\n"
" std::cout << *p1 << *p2 << arr[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
// new in C code does not allocate..
checkUninitVar("int main() {\n"
" char * pBuf = new(10);\n"
" a = *pBuf;\n"
"}", false);
ASSERT_EQUALS("", errout_str());
checkUninitVar("class A {};\n" // #10698
"void f() {\n"
" A* a = new A{};\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #1175
checkUninitVar("void f() {\n"
" int* p = new int;\n"
" *((int*)*p) = 42;\n"
" delete p;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Memory is allocated but not initialized: p\n", errout_str());
checkUninitVar("int f() {\n" // #10596
" int* a = new int;\n"
" int i{};\n"
" i += *a;\n"
" delete a;\n"
" return i;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (error) Memory is allocated but not initialized: a\n", errout_str());
checkUninitVar("void* f(size_t n, int i) {\n" // #11766
" char* p = (char*)malloc(n);\n"
" *(int*)p = i;\n"
" return p;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void* f(size_t n, int i) {\n"
" char* p = (char*)malloc(n);\n"
" *(int*)(void*)p = i;\n"
" return p;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f(int n) {\n"
" int* p = (int*)malloc(n * sizeof(int));\n"
" for (int i = 0; i < n; ++i)\n"
" *(p + i) = 0;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
// class / struct..
void uninitvar_class() {
checkUninitVar("class Fred\n"
"{\n"
" int i;\n"
" int a() { return i; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f()\n"
"{\n"
" struct Relative {\n"
" Surface *surface;\n"
" void MoveTo(int x, int y) {\n"
" surface->MoveTo();\n"
" }\n"
" };\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f()\n"
"{\n"
" static const struct ab {\n"
" int a,b;\n"
" int get_a() { return a; }"
" } = { 0, 0 };\n"
"}", true, false);
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f()\n"
"{\n"
" int i;\n"
" {\n"
" union ab {\n"
" int a,b;\n"
" }\n"
" i = 0;\n"
" }\n"
" return i;\n"
"}", true, false);
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f(int x) {\n"
" struct AB ab;\n"
" x = ab.x = 12;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
// enum..
void uninitvar_enum() {
checkUninitVar("void f()\n"
"{\n"
" enum AB { a, b };\n"
" AB ab;\n"
" if (ab);\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: ab\n", errout_str());
}
// references..
void uninitvar_references() {
checkUninitVar("void f()\n"
"{\n"
" int a;\n"
" int &b = a;\n"
" b = 0;\n"
" int x = a;\n"
"}", true, false);
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f(struct blame_entry *ent)\n"
"{\n"
" struct origin *suspect = ent->suspect;\n"
" char hex[41];\n"
" strcpy(hex, sha1_to_hex(suspect->commit->object.sha1));\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void foo()\n"
"{\n"
" const std::string s(x());\n"
" strchr(s.c_str(), ',');\n"
"}");
ASSERT_EQUALS("", errout_str());
// #6717
checkUninitVar("void f() {\n"
" struct thing { int value; };\n"
" thing it;\n"
" int& referenced_int = it.value;\n"
" referenced_int = 123;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void uninitvar_return() {
checkUninitVar("static int foo() {\n"
" int ret;\n"
" return ret;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: ret\n", errout_str());
checkUninitVar("static int foo() {\n"
" int ret;\n"
" return ret+5;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: ret\n", errout_str());
checkUninitVar("static int foo() {\n"
" int ret;\n"
" return ret = 5;\n"
"}");
ASSERT_EQUALS("", errout_str());
{
checkUninitVar("static int foo() {\n"
" int ret;\n"
" cin >> ret;\n"
" return ret;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("static int foo() {\n"
" int ret;\n"
" return cin >> ret;\n"
"}\n", false);
ASSERT_EQUALS("[test.c:3]: (error) Uninitialized variable: ret\n", errout_str());
}
// Ticket #6341- False negative
{
checkUninitVar("wchar_t f() { int i; return btowc(i); }");
ASSERT_EQUALS("[test.cpp:1]: (error) Uninitialized variable: i\n", errout_str());
checkUninitVar("wchar_t f(int i) { return btowc(i); }");
ASSERT_EQUALS("", errout_str());
// Avoid a potential false positive (#6341)
checkUninitVar(
"void setvalue(int &x) {\n"
" x = 0;\n"
" return 123;\n"
"}\n"
"int f() {\n"
" int x;\n"
" return setvalue(x);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
// Ticket #5412 - False negative
{
checkUninitVar("void f(bool b) {\n"
" double f;\n"
" if (b) { }\n"
" else {\n"
" f = 0.0;\n"
" }\n"
" printf (\"%f\",f);\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (error) Uninitialized variable: f\n", errout_str());
// Check for potential FP
checkUninitVar("void f(bool b) {\n"
" double f;\n"
" if (b) { f = 1.0 }\n"
" else {\n"
" f = 0.0;\n"
" }\n"
" printf (\"%f\",f);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
// Ticket #2146 - False negative
checkUninitVar("int f(int x) {\n"
" int y;\n"
" return x ? 1 : y;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: y\n", errout_str());
// Ticket #3106 - False positive
{
checkUninitVar("int f() {\n"
" int i;\n"
" return x(&i) ? i : 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("int f() {\n"
" int i;\n"
" return x() ? i : 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: i\n", errout_str());
}
}
void uninitvar_assign() { // = { .. }
// #1533
checkUninitVar("char a()\n"
"{\n"
" char key;\n"
" struct A msg = { .buf = {&key} };\n"
" init(&msg);\n"
" key++;\n"
"}");
ASSERT_EQUALS("", errout_str());
// Ticket #5660 - False positive
checkUninitVar("int f() {\n"
" int result;\n"
" int *res[] = {&result};\n"
" foo(res);\n"
" return result;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #6873
checkUninitVar("int f() {\n"
" char a[10];\n"
" char *b[] = {a};\n"
" foo(b);\n"
" return atoi(a);\n"
"}");
ASSERT_EQUALS("", errout_str());
// = { .. }
checkUninitVar("int f() {\n"
" int a;\n"
" int *p[] = { &a };\n"
" *p[0] = 0;\n"
" return a;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
// strncpy doesn't always null-terminate..
void uninitvar_strncpy() {
// TODO: Add this checking
// Can it be added without hardcoding?
checkUninitVar("void f()\n"
"{\n"
" char a[100];\n"
" strncpy(a, s, 20);\n"
" strncat(a, s, 20);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:5]: (error) Dangerous usage of 'a' (strncpy doesn't always null-terminate it).\n", "", errout_str());
checkUninitVar("void f()\n"
"{\n"
" char a[100];\n"
" strncpy(a, \"hello\", 3);\n"
" strncat(a, \"world\", 20);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:5]: (error) Dangerous usage of 'a' (strncpy doesn't always null-terminate it).\n", "", errout_str());
checkUninitVar("void f()\n"
"{\n"
" char a[100];\n"
" strncpy(a, \"hello\", sizeof(a));\n"
" strncat(a, \"world\", 20);\n"
"}", true, false);
ASSERT_EQUALS("", errout_str());
// #3245 - false positive
{
checkUninitVar("void f() {\n"
" char a[100];\n"
" strncpy(a,p,10);\n"
" memcmp(a,q,10);\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n"
" char a[100];\n"
" strncpy(a,p,10);\n"
" if (memcmp(a,q,10)==0);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
// Using strncpy isn't necessarily dangerous usage
checkUninitVar("void f(const char dev[], char *str) {\n"
" char buf[10];\n"
" strncpy(buf, dev, 10);\n"
" strncpy(str, buf, 10);\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n"
" char dst[4];\n"
" const char* source = \"You\";\n"
" strncpy(dst, source, sizeof(dst));\n"
" char value = dst[2];\n"
"}", true, false);
ASSERT_EQUALS("", errout_str());
}
// valid and invalid use of 'int a(int x) { return x + x; }'
void func_uninit_var() {
const std::string funca("int a(int x) { return x + x; }");
checkUninitVar((funca +
"void b() {\n"
" int x;\n"
" a(x);\n"
"}").c_str());
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: x\n", errout_str());
checkUninitVar((funca +
"void b() {\n"
" int *p;\n"
" a(*p);\n"
"}").c_str());
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: p\n", errout_str());
}
// valid and invalid use of 'void a(int *p) { *p = 0; }'
void func_uninit_pointer() {
const std::string funca("void a(int *p) { *p = 0; }");
// ok - initialized pointer
checkUninitVar((funca +
"void b() {\n"
" int buf[10];\n"
" a(buf);\n"
"}").c_str());
ASSERT_EQUALS("", errout_str());
// not ok - uninitialized pointer
checkUninitVar((funca +
"void b() {\n"
" int *p;\n"
" a(p);\n"
"}").c_str());
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: p\n", errout_str());
}
void uninitvar_typeof() {
checkUninitVar("void f() {\n"
" struct Fred *fred;\n"
" typeof(fred->x);\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n"
" struct SData * s;\n"
" ab(typeof(s->status));\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n"
" struct SData * s;\n"
" TYPEOF(s->status);\n"
"}");
TODO_ASSERT_EQUALS("", "[test.cpp:3]: (error) Uninitialized variable: s\n", errout_str());
checkUninitVar("void f() {\n"
" int *n = ({ typeof(*n) z; (typeof(*n)*)z; })\n"
"}", true, false);
ASSERT_EQUALS("", errout_str());
}
void uninitvar_ignore() {
checkUninitVar("void foo() {\n"
" int i;\n"
" dostuff((int&)i, 0);\n" // <- cast is not use
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("int foo() {\n"
" int i;\n"
" return (int&)i + 2;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: i\n", errout_str());
checkUninitVar("void foo() {\n"
" int i;\n"
" dostuff(*&i, 0);\n" // <- *& is not use
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("int foo() {\n"
" int i;\n"
" return *&i;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: i\n", errout_str());
}
void uninitvar2() {
// using uninit var
checkUninitVar("void f() {\n"
" int x;\n"
" x++;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: x\n", errout_str());
// extracttests.start: char str[10];
checkUninitVar("void f() {\n"
" int x;\n"
" str[x] = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: x\n", errout_str());
checkUninitVar("void f() {\n" // #7736
" int buf[12];\n"
" printf (\"%d\", buf[0] );\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: buf\n", errout_str());
checkUninitVar("void f() {\n"
" int x;\n"
" int y = x & 3;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: x\n", errout_str());
checkUninitVar("void f() {\n"
" int x;\n"
" int y = 3 & x;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: x\n", errout_str());
checkUninitVar("void f() {\n"
" int x;\n"
" x = 3 + x;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: x\n", errout_str());
checkUninitVar("void f() {\n"
" int x;\n"
" x = x;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: x\n", errout_str());
// extracttests.start: struct ABC {int a;};
checkUninitVar("void f() {\n"
" struct ABC *abc;\n"
" abc->a = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: abc\n", errout_str());
checkUninitVar("int f() {\n"
" static int x;\n"
" return ++x;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("int f() {\n"
" extern int x;\n"
" return ++x;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n" // #3926 - weird cast.
" int x;\n"
" *(((char *)&x) + 0) = 0;\n"
"}", false, false);
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n" // #4737 - weird cast.
" int x;\n"
" do_something(&((char*)&x)[0], 1);\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n"
" int x;\n"
" char *p = (char*)&x + 1;\n"
"}", true, false);
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n"
" int i;\n"
" i=f(), i!=2;\n"
"}");
ASSERT_EQUALS("", errout_str());
// using uninit var in condition
checkUninitVar("void f(void) {\n"
" int x;\n"
" if (x) { }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: x\n", errout_str());
checkUninitVar("void f() {\n"
" int x;\n"
" if (1 == (3 & x)) { }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: x\n", errout_str());
// ?:
checkUninitVar("int f(int *ptr) {\n"
" int a;\n"
" int *p = ptr ? ptr : &a;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("int f(int a) {\n"
" int x;\n"
" if (a==3) { x=2; }\n"
" y = (a==3) ? x : a;\n"
"}");
ASSERT_EQUALS("", errout_str());
// = ({ .. })
checkUninitVar("void f() {\n"
" int x = ({ 1 + 2; });\n"
" int y = 1 + (x ? y : y);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: y\n", errout_str());
// >> => initialization / usage
{
const char code[] = "void f() {\n"
" int x;\n"
" if (i >> x) { }\n"
"}";
checkUninitVar(code, true);
ASSERT_EQUALS("", errout_str());
checkUninitVar(code, false);
ASSERT_EQUALS("[test.c:3]: (error) Uninitialized variable: x\n", errout_str());
}
checkUninitVar("void f() {\n"
" int i, i2;\n"
" strm >> i >> i2;\n"
"}");
ASSERT_EQUALS("", errout_str());
// unconditional initialization
checkUninitVar("int f() {\n"
" int ret;\n"
" if (a) { ret = 1; }\n"
" else { {} ret = 2; }\n"
" return ret;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("int f() {\n"
" int ret;\n"
" if (a) { ret = 1; }\n"
" else { s=foo(1,{2,3},4); ret = 2; }\n"
" return ret;\n"
"}");
ASSERT_EQUALS("", errout_str());
// conditional initialization
checkUninitVar("void f() {\n"
" int x;\n"
" if (y == 1) { x = 1; }\n"
" else { if (y == 2) { x = 1; } }\n"
" return x;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: x\n", errout_str());
checkUninitVar("void f() {\n"
" int x;\n"
" if (y == 1) { x = 1; }\n"
" else { if (y == 2) { x = 1; } }\n"
" if (y == 3) { }\n" // <- ignore condition
" return x;\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Uninitialized variable: x\n", errout_str());
// initialization in condition
checkUninitVar("void f() {\n"
" int a;\n"
" if (init(&a)) { }\n"
" a++;\n"
"}");
ASSERT_EQUALS("", errout_str());
// return, break, continue, goto
checkUninitVar("void f() {\n"
" int x;\n"
" if (y == 1) { return; }\n"
" else { x = 1; }\n"
" return x;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n"
" int x;\n"
" if (y == 1) { return; }\n"
" return x;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: x\n", errout_str());
checkUninitVar("int f(int x) {\n"
" int ret;\n"
" if (!x) {\n"
" ret = -123;\n"
" goto out1;\n"
" }\n"
" return 0;\n"
"out1:\n"
"out2:\n"
" return ret;\n"
"}", false);
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n"
" int i;\n"
" if (x) {\n"
" i = 1;\n"
" } else {\n"
" goto out;\n"
" }\n"
" i++;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("int f() {\n"
" int i,x;\n"
" for (i=0;i<9;++i)\n"
" if (foo) break;\n"
" return x;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: x\n", errout_str());
checkUninitVar("int f() {\n"
" int x;\n"
" while (foo)\n"
" if (bar) break;\n"
" return x;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: x\n", errout_str());
// try/catch : don't warn about exception variable
checkUninitVar("void f() {\n"
" try {\n"
" } catch (CException* e) {\n"
" trace();\n"
" e->Delete();\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n" // #5347
" try {\n"
" } catch (const char* e) {\n"
" A a = e;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// exit
checkUninitVar("void f() {\n"
" int x;\n"
" if (y == 1) { exit(0); }\n"
" else { x = 1; }\n"
" return x;\n"
"}");
ASSERT_EQUALS("", errout_str());
// strange code.. don't crash (#3415)
checkUninitVar("void foo() {\n"
" int i;\n"
" ({ if (0); });\n"
" for_each(i) { }\n"
"}", false, false);
// if, if
checkUninitVar("void f(int a) {\n"
" int i;\n"
" if (a) i = 0;\n"
" if (a) i++;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n"
" int a,b=0;\n"
" if (x) {\n"
" if (y) {\n"
" a = 0;\n"
" b = 1;\n"
" }\n"
" }\n"
" if (b) a++;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n"
" int a=0, b;\n"
" if (x) { }\n"
" else { if (y==2) { a=1; b=2; } }\n"
" if (a) { ++b; }\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("static void f(int x, int y) {\n"
" int a;\n"
" if (x == 0) { a = y; }\n"
" if (x == 0 && (a == 1)) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("static void f() {\n"
" int a=0, b;\n"
" if (something) { a = dostuff(&b); }\n"
" if (!a || b) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("static void f(int x, int y) {\n"
" int a;\n"
" if (x == 0 && (a == 1)) { }\n"
"}", true, false);
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: a\n", errout_str());
checkUninitVar("void f() {\n"
" int a;\n"
" if (x) { a = 0; }\n"
" if (x) { if (y) { a++; } }\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n"
" int a;\n"
" if (x) { a = 0; }\n"
" if (x) { if (y) { } else { a++; } }\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("struct AB { int a; int b; };\n"
"void f(void) {\n"
" struct AB ab;\n"
" if (x) ab = getAB();\n"
" else ab.a = 0;\n"
" if (ab.a == 1) b = ab.b;\n"
"}", false);
ASSERT_EQUALS("", errout_str());
checkUninitVar("int f(void) {\n"
" int a;\n"
" int i;\n"
" if (x) { noreturn(); }\n"
" else { i = 0; }\n"
" if (i==1) { a = 0; }\n"
" else { a = 1; }\n"
" return a;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("int f(int a) {\n" // #4560
" int x = 0, y;\n"
" if (a) x = 1;\n"
" else return 0;\n"
" if (x) y = 123;\n" // <- y is always initialized
" else {}\n"
" return y;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("int f(int a) {\n" // #6583
" int x;\n"
" if (a < 2) exit(1);\n"
" else if (a == 2) x = 0;\n"
" else exit(2);\n"
" return x;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("int f(int a) {\n" // #4560
" int x = 1, y;\n"
" if (a) x = 0;\n"
" else return 0;\n"
" if (x) {}\n"
" else y = 123;\n" // <- y is always initialized
" return y;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f(int x) {\n" // #3948
" int value;\n"
" if (x !=-1)\n"
" value = getvalue();\n"
" if (x == -1 || value > 300) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("enum t_err { ERR_NONE, ERR_BAD_ARGS };\n" // #9649
"struct box_t { int value; };\n"
"int init_box(box_t *p, int v);\n"
"\n"
"void foo(int ret) {\n"
" box_t box2;\n"
" if (ret == ERR_NONE)\n"
" ret = init_box(&box2, 20);\n"
" if (ret == ERR_NONE)\n"
" z = x + box2.value;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f(int x) {\n"
" int value;\n"
" if (x == 32)\n"
" value = getvalue();\n"
" if (x == 1)\n"
" v = value;\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Uninitialized variable: value\n", errout_str());
checkUninitVar("void f(int x) {\n"
" int value;\n"
" if (x == 32)\n"
" value = getvalue();\n"
" if (x == 32) {}\n"
" else v = value;\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Uninitialized variable: value\n", errout_str());
checkUninitVar("static int x;" // #4773
"int f() {\n"
" int y;\n"
" if (x) g();\n"
" if (x) y = 123;\n"
" else y = 456;\n"
" return y;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("static int x;" // #4773
"int f() {\n"
" int y;\n"
" if (!x) g();\n"
" if (x) y = 123;\n"
" else y = 456;\n"
" return y;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f(int a) {\n"
" int x;\n"
" if (a) x=123;\n"
" if (!a) {\n"
" if (!a) {}\n"
" else if (x) {}\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// asm
checkUninitVar("void f() {\n"
" int x;\n"
" asm();\n"
" x++;\n"
"}");
ASSERT_EQUALS("", errout_str());
// sizeof / typeof / offsetof / etc
checkUninitVar("void f() {\n"
" int i;\n"
" sizeof(i+1);\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n"
" int i;\n"
" if (100 == sizeof(i+1));\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n"
" struct ABC *abc;\n"
" int i = ARRAY_SIZE(abc.a);"
"}");
TODO_ASSERT_EQUALS("", "[test.cpp:3]: (error) Uninitialized variable: abc\n", errout_str());
checkUninitVar("void f() {\n"
" int *abc;\n"
" typeof(*abc);\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n"
" struct ABC *abc;\n"
" return do_something(typeof(*abc));\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n"
" A *a;\n"
" a = malloc(sizeof(*a));\n"
"}");
ASSERT_EQUALS("", errout_str());
// &
checkUninitVar("void f() {\n" // #4426 - address of uninitialized variable
" int a,b;\n"
" if (&a == &b);\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n" // #4439 - cast address of uninitialized variable
" int a;\n"
" x((LPARAM)(RECT*)&a);\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("int main() {\n"
" int done;\n"
" dostuff(1, (AuPointer) &done);\n" // <- It is not conclusive if the "&" is a binary or unary operator. Bailout.
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n" // #4778 - cast address of uninitialized variable
" long a;\n"
" &a;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n" // #4717 - ({})
" int a = ({ long b = (long)(123); 2 + b; });\n"
"}", false);
ASSERT_EQUALS("", errout_str());
}
// #3869 - reference variable
void uninitvar4() {
checkUninitVar("void f() {\n"
" int buf[10];\n"
" int &x = buf[0];\n"
" buf[0] = 0;\n"
" x++;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
// #3861
void uninitvar5() {
// ensure there is no false positive
checkUninitVar("void f() {\n"
" x<char> c;\n"
" c << 2345;\n"
"}");
ASSERT_EQUALS("", errout_str());
// ensure there is no false negative
checkUninitVar("void f() {\n"
" char c;\n"
" char a = c << 2;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: c\n", errout_str());
}
// #13227
void uninitvar6() {
checkUninitVar("int foo(int x) {\n"
" int i;\n"
" if (x == 1) {\n"
" i = 3;\n"
" } else {\n"
" do {\n"
" return 2;\n"
" } while (0);\n"
" }\n"
" return i;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void uninitvar8() {
const char code[] = "struct Fred {\n"
" void Sync(dsmp_t& type, int& len, int limit = 123);\n"
" void Sync(int& syncpos, dsmp_t& type, int& len, int limit = 123);\n"
" void FindSyncPoint();\n"
"};\n"
"void Fred::FindSyncPoint() {\n"
" dsmp_t type;\n"
" int syncpos, len;\n"
" Sync(syncpos, type, len);\n"
"}";
checkUninitVar(code, true);
ASSERT_EQUALS("", errout_str());
}
void uninitvar9() { // 6424
const char code[] = "namespace Ns { class C; }\n"
"void f1() { char *p; *p = 0; }\n"
"class Ns::C* p;\n"
"void f2() { char *p; *p = 0; }";
checkUninitVar(code, true);
ASSERT_EQUALS("[test.cpp:2]: (error) Uninitialized variable: p\n"
"[test.cpp:4]: (error) Uninitialized variable: p\n", errout_str());
}
void uninitvar10() { // 9467
const char code[] = "class Foo {\n"
" template <unsigned int i>\n"
" bool bar() {\n"
" return true;\n"
" }\n"
"};\n"
"template <>\n"
"bool Foo::bar<9>() {\n"
" return true;\n"
"}\n"
"int global() {\n"
" int bar = 1;\n"
" return bar;\n"
"}";
checkUninitVar(code, true);
ASSERT_EQUALS("", errout_str());
}
void uninitvar11() { // 9123
const char code[] = "bool get(int &var);\n"
"void foo () {\n"
" int x;\n"
" x = get(x) && x;\n"
"}";
checkUninitVar(code, true);
ASSERT_EQUALS("", errout_str());
}
void uninitvar12() { // 10218
const char code[] = "void fp() {\n"
" std::stringstream ss;\n"
" for (int i; ss >> i;) {}\n"
"}";
checkUninitVar(code);
ASSERT_EQUALS("", errout_str());
}
void uninitvar13() { // #9772 - FP
const char code[] = "int func(void)\n"
"{ int rez;\n"
" struct sccb* ccb;\n"
" \n"
" do\n"
" { if ((ccb = calloc(1, sizeof(*ccb))) == NULL)\n"
" { rez = 1;\n"
" break;\n"
" }\n"
" rez = 0;\n"
" } while (0);\n"
" \n"
" if (rez != 0)\n"
" free(ccb);\n"
" \n"
" return rez;\n"
"}";
checkUninitVar(code);
ASSERT_EQUALS("", errout_str());
}
void uninitvar14() { // #11832
const char code[] = "void f() {\n"
" int b;\n"
" *(&b) = 0;\n"
"}";
checkUninitVar(code);
ASSERT_EQUALS("", errout_str());
}
void uninitvar_unconditionalTry() {
// Unconditional scopes and try{} scopes
checkUninitVar("int f() {\n"
" int i;\n"
" {\n"
" return i;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: i\n", errout_str());
checkUninitVar("int f() {\n"
" int i;\n"
" try {\n"
" return i;\n"
" } catch(...) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: i\n", errout_str());
checkUninitVar("void f(bool x) {\n"
" bool b;\n"
" {\n"
" auto g = []{};\n"
" b = x;\n"
" }\n"
" if (b) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f(bool x) {\n"
" bool b;\n"
" {\n"
" int i[2]{ 1, 2 };\n"
" b = x;\n"
" }\n"
" if (b) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f(bool x) {\n"
" bool b;\n"
" {\n"
" auto g = []{};\n"
" }\n"
" if (b) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:6]: (error) Uninitialized variable: b\n", errout_str());
}
void uninitvar_funcptr() {
// extracttests.disable
checkUninitVar("void getLibraryContainer() {\n"
" Reference< XStorageBasedLibraryContainer >(*Factory)(const Reference< XComponentContext >&, const Reference< XStorageBasedDocument >&)\n"
" = &DocumentDialogLibraryContainer::create;\n"
" rxContainer.set((*Factory)(m_aContext, xDocument));\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void foo() {\n"
" void* x;\n"
" int (*f)(int, int) = x;\n"
" dostuff((*f)(a,b));\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: x\n", errout_str());
checkUninitVar("void getLibraryContainer() {\n"
" Reference< XStorageBasedLibraryContainer >(*Factory)(const Reference< XComponentContext >&, const Reference< XStorageBasedDocument >&);\n"
" rxContainer.set((*Factory)(m_aContext, xDocument));\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: Factory\n", errout_str());
// extracttests.enable
}
void uninitvar_operator() { // Ticket #6463, #6680
checkUninitVar("struct Source { Source& operator>>(int& i) { i = 0; return *this; } };\n"
"struct Sink { int v; };\n"
"Source foo;\n"
"void uninit() {\n"
" Sink s;\n"
" int n = 1 >> s.v;\n" // Not initialized
"};\n"
"void notUninit() {\n"
" Sink s1;\n"
" foo >> s1.v;\n" // Initialized by operator>>
" Sink s2;\n"
" int n;\n"
" foo >> s2.v >> n;\n" // Initialized by operator>>
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Uninitialized struct member: s.v\n", errout_str());
checkUninitVar("struct Fred { int a; };\n"
"void foo() {\n"
" Fred fred;\n"
" std::cin >> fred.a;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
// Handling of function calls
void uninitvar2_func() {
// #4716
checkUninitVar("void bar(const int a, const int * const b);\n"
"int foo(void) {\n"
" int a;\n"
" int *b = 0;\n"
" bar(a,b);\n" // <<
" return 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: a\n", errout_str());
// non-pointer variable
checkUninitVar("void a(char);\n" // value => error
"void b() {\n"
" char c;\n"
" a(c);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: c\n", errout_str());
checkUninitVar("void a(char c);\n" // value => error
"void b() {\n"
" char c;\n"
" a(c);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: c\n", errout_str());
checkUninitVar("void a(const char c);\n" // const value => error
"void b() {\n"
" char c;\n"
" a(c);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: c\n", errout_str());
checkUninitVar("void a(char *c);\n" // address => no error
"void b() {\n"
" char c;\n"
" a(&c);\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void a(pstr s);\n" // address => no error
"void b() {\n"
" char c;\n"
" a(&c);\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void a(const char *c);\n" // const address => data is not changed
"void b() {\n"
" char c;\n"
" a(&c);\n" // <- no warning
" c++;\n" // <- uninitialized variable
"}");
TODO_ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: c\n", "", errout_str());
// pointer variable
checkUninitVar("void a(char c);\n" // value => error
"void b() {\n"
" char *c;\n"
" a(*c);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: c\n", errout_str());
checkUninitVar("void a(char *c);\n" // address => error
"void b() {\n"
" char *c;\n"
" a(c);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: c\n", errout_str());
checkUninitVar("typedef struct { int a; int b; } AB;\n"
"void a(AB *ab);\n"
"void b() {\n"
" AB *ab;\n"
" a(ab);\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: ab\n", errout_str());
checkUninitVar("void a(const char *c);\n" // const address => error
"void b() {\n"
" char *c;\n"
" a(c);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: c\n", errout_str());
checkUninitVar("void a(const char c[]);\n" // const address => error
"void b() {\n"
" char *c;\n"
" a(c);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: c\n", errout_str());
checkUninitVar("void a(char **c);\n" // address of pointer => no error
"void b() {\n"
" char *c;\n"
" a(&c);\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void a(char *c);\n" // address of pointer (suspicious cast to pointer) => no error
"void b() {\n"
" char *c;\n"
" a(&c);\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void a(const char **c);\n" // const address of pointer => no error
"void b() {\n"
" const char *c;\n"
" a(&c);\n"
"}");
ASSERT_EQUALS("", errout_str());
// array
checkUninitVar("int calc(const int *p, int n);\n"
"void f() {\n"
" int x[10];\n"
" calc(x,10);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: x\n",
"", errout_str());
checkUninitVar("void f() {\n"
" int x[10];\n"
" int &x0(*x);\n"
"}");
ASSERT_EQUALS("", errout_str());
// ....
checkUninitVar("struct ABC { int a; };\n" // struct initialization
"void clear(struct ABC &abc);\n"
"int f() {\n"
" struct ABC abc;\n"
" clear(abc);\n"
" return abc.a;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void write_packet() {\n"
" time_t now0;\n"
" time(&now0);\n"
"}", false);
ASSERT_EQUALS("", errout_str());
checkUninitVar("void write_packet() {\n"
" time_t* now0;\n"
" time(now0);\n"
"}", false);
ASSERT_EQUALS("[test.c:3]: (error) Uninitialized variable: now0\n", errout_str());
checkUninitVar("void write_packet() {\n"
" char now0;\n"
" strcmp(&now0, sth);\n"
"}", false);
ASSERT_EQUALS("[test.c:3]: (error) Uninitialized variable: now0\n", errout_str());
// #2775 - uninitialized struct pointer in subfunction
// extracttests.start: struct Fred {int x;};
checkUninitVar("void a(struct Fred *fred) {\n"
" fred->x = 0;\n"
"}\n"
"\n"
"void b() {\n"
" struct Fred *p;\n"
" a(p);\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (error) Uninitialized variable: p\n", errout_str());
// #2946 - FP array is initialized in subfunction
checkUninitVar("void a(char *buf) {\n"
" buf[0] = 0;\n"
"}\n"
"void b() {\n"
" char buf[10];\n"
" a(buf);\n"
" buf[1] = buf[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
// unknown macro
checkUninitVar("void f() {\n"
" struct listnode *item;\n"
" list_for_each(item, &key_list) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void uninitvar2_value() {
checkUninitVar("void f() {\n"
" int i;\n"
" if (x) {\n"
" int y = -ENOMEM;\n" // assume constant ENOMEM is nonzero since it's negated
" if (y != 0) return;\n"
" i++;\n"
" }\n"
"}", true, false);
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n"
" int i, y;\n"
" if (x) {\n"
" y = -ENOMEM;\n" // assume constant ENOMEM is nonzero since it's negated
" if (y != 0) return;\n"
" i++;\n"
" }\n"
"}", true, false);
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n"
" int i, y;\n"
" if (x) y = -ENOMEM;\n" // assume constant ENOMEM is nonzero since it's negated
" else y = get_value(i);\n"
" if (y != 0) return;\n" // <- condition is always true if i is uninitialized
" i++;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f(int x) {\n"
" int i;\n"
" if (x) i = 0;\n"
" if (!x || i>0) {}\n" // <- no error
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f(int x) {\n"
" int i;\n"
" if (!x) { }\n"
" else i = 0;\n"
" if (x || i>0) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: i\n", errout_str());
checkUninitVar("void f(int x) {\n"
" int i;\n"
" if (x) { }\n"
" else i = 0;\n"
" if (x || i>0) {}\n" // <- no error
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("int f(int x) {\n"
" int y;\n"
" if (x) y = do_something();\n"
" if (!x) return 0;\n"
" return y;\n"
"}");
ASSERT_EQUALS("", errout_str());
// extracttests.start: int y;
checkUninitVar("int f(int x) {\n" // FP with ?:
" int a;\n"
" if (x)\n"
" a = y;\n"
" return x ? 2*a : 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("int f(int x) {\n"
" int a;\n"
" if (x)\n"
" a = y;\n"
" return y ? 2*a : 3*a;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: a\n", errout_str());
ASSERT_THROW_INTERNAL(checkUninitVar("void f() {\n" // Don't crash
" int a;\n"
" dostuff(\"ab\" cd \"ef\", x?a:z);\n" // <- No AST is created for ?
"}"), UNKNOWN_MACRO);
// Unknown => bail out..
checkUninitVar("void f(int x) {\n"
" int i;\n"
" if (a(x)) i = 0;\n"
" if (b(x)) return;\n"
" i++;\n" // <- no error if b(x) is always true when a(x) is false
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f(int x) {\n"
" int i;\n"
" if (x) i = 0;\n"
" while (condition) {\n"
" if (x) i++;\n" // <- no error
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f(int x) {\n"
" int i;\n"
" if (x) i = 0;\n"
" while (condition) {\n"
" i++;\n"
" }\n"
"}");
TODO_ASSERT_EQUALS("error", "", errout_str());
}
#define valueFlowUninit(...) valueFlowUninit_(__FILE__, __LINE__, __VA_ARGS__)
void valueFlowUninit2_value()
{
valueFlowUninit("void f() {\n"
" int i;\n"
" if (x) {\n"
" int y = -ENOMEM;\n" // assume constant ENOMEM is nonzero since it's negated
" if (y != 0) return;\n"
" i++;\n"
" }\n"
"}",
true);
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f() {\n"
" int i, y;\n"
" if (x) {\n"
" y = -ENOMEM;\n" // assume constant ENOMEM is nonzero since it's negated
" if (y != 0) return;\n"
" i++;\n"
" }\n"
"}",
true);
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f() {\n"
" int i, y;\n"
" if (x) y = -ENOMEM;\n" // assume constant ENOMEM is nonzero since it's negated
" else y = get_value(i);\n"
" if (y != 0) return;\n" // <- condition is always true if i is uninitialized
" i++;\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f(int x) {\n"
" int i;\n"
" if (!x) i = 0;\n"
" if (!x || i>0) {}\n" // <- error
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (warning) Uninitialized variable: i\n", errout_str());
valueFlowUninit("void f(int x) {\n"
" int i;\n"
" if (x) i = 0;\n"
" if (!x || i>0) {}\n" // <- no error
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f(int x) {\n"
" int i;\n"
" if (!x) { }\n"
" else i = 0;\n"
" if (x || i>0) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:5]: (warning) Uninitialized variable: i\n", errout_str());
valueFlowUninit("void f(int x) {\n"
" int i;\n"
" if (x) { }\n"
" else i = 0;\n"
" if (x || i>0) {}\n" // <- no error
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("int f(int x) {\n"
" int y;\n"
" if (x) y = do_something();\n"
" if (!x) return 0;\n"
" return y;\n"
"}");
ASSERT_EQUALS("", errout_str());
// extracttests.start: int y;
valueFlowUninit("int f(int x) {\n" // FP with ?:
" int a;\n"
" if (x)\n"
" a = y;\n"
" return x ? 2*a : 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("int f(int x, int y) {\n"
" int a;\n"
" if (x)\n"
" a = y;\n"
" return y ? 2*a : 3*a;\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:5]: (warning) Uninitialized variable: a\n", errout_str());
ASSERT_THROW_INTERNAL(valueFlowUninit("void f() {\n" // Don't crash
" int a;\n"
" dostuff(\"ab\" cd \"ef\", x?a:z);\n" // <- No AST is created for ?
"}"), UNKNOWN_MACRO);
// Unknown => bail out..
valueFlowUninit("void f(int x) {\n"
" int i;\n"
" if (a(x)) i = 0;\n"
" if (b(x)) return;\n"
" i++;\n" // <- no error if b(x) is always true when a(x) is false
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f(int x) {\n"
" int i;\n"
" if (x) i = 0;\n"
" while (condition) {\n"
" if (x) i++;\n" // <- no error
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f(int x) {\n"
" int i;\n"
" if (x) i = 0;\n"
" while (condition) {\n"
" i++;\n"
" }\n"
"}");
TODO_ASSERT_EQUALS("error", "", errout_str());
valueFlowUninit("void f ( void ){\n" // #9313 - FN
" int *p;\n"
" int a[ 2 ] = { [ 0 ] = *p++, [ 1 ] = 1 };\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: p\n", errout_str());
valueFlowUninit("void f(int height) {\n"
" int a[11];\n"
" int *p = a;\n"
" int step = 2;\n"
" for (int i = 0; i < (height * step); i += step)\n"
" *p++ = 0;\n"
" for (int i = 0; i < height; i++)\n"
" if (a[i]) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f(void) {\n"
" char *c;\n"
" char x;\n"
" while (true) {\n"
" c = &x;\n"
" break;\n"
" }\n"
" ++c;\n"
"}", false);
ASSERT_EQUALS("", errout_str());
// #12030
valueFlowUninit("int set(int *x);\n"
"void foo(bool a) {\n"
" bool flag{0};\n"
" int x;\n"
" if (!a) {\n"
" flag = set(&x);\n"
" }\n"
" if (!flag || x==3) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("int set(int *x);\n"
"void foo(bool a) {\n"
" bool flag{0};\n"
" int x;\n"
" if (!a) {\n"
" flag = set(&x);\n"
" }\n"
" if (!flag && x==3) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:8]: (warning) Uninitialized variable: x\n", errout_str());
valueFlowUninit("int do_something();\n" // #11983
"int set_st(int *x);\n"
"int bar();\n"
"void foo() {\n"
" int x, y;\n"
" int status = 1;\n"
" if (bar() == 1) {\n"
" status = 0;\n"
" }\n"
" if (status == 1) {\n"
" status = set_st(&x);\n"
" }\n"
" for (int i = 0; status == 1 && i < x; i++) {\n"
" if (do_something() == 0) {\n"
" status = 0;\n"
" }\n"
" }\n"
" if(status == 1 && x > 0){}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("int h(bool, bool*);\n" // #11760
"int f(bool t) {\n"
" int i = 0;\n"
" bool b;\n"
" if (t)\n"
" g();\n"
" if (i == 0)\n"
" i = h(t, &b);\n"
" if (i == 0 && b)\n"
" i = h(t, &b);\n"
" if (i == 0 && b)\n"
" i = h(t, &b);\n"
" return i;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void valueFlowUninit_uninitvar2()
{
// using uninit var
valueFlowUninit("void f() {\n"
" int x;\n"
" x++;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: x\n", errout_str());
// extracttests.start: char str[10];
valueFlowUninit("void f() {\n"
" int x;\n"
" str[x] = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: x\n", errout_str());
valueFlowUninit("void f() {\n" // #7736
" int buf[12];\n"
" printf (\"%d\", buf[0] );\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: buf\n", errout_str());
valueFlowUninit("void f() {\n"
" int x;\n"
" int y = x & 3;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: x\n", errout_str());
valueFlowUninit("void f() {\n"
" int x;\n"
" int y = 3 & x;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: x\n", errout_str());
valueFlowUninit("void f() {\n"
" int x;\n"
" x = 3 + x;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: x\n", errout_str());
valueFlowUninit("void f() {\n"
" int x;\n"
" x = x;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: x\n", errout_str());
// extracttests.start: struct ABC {int a;};
valueFlowUninit("void f() {\n"
" struct ABC *abc;\n"
" abc->a = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: abc\n", errout_str());
valueFlowUninit("int f() {\n"
" static int x;\n"
" return ++x;\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("int f() {\n"
" extern int x;\n"
" return ++x;\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f() {\n" // #3926 - weird cast.
" int x;\n"
" *(((char *)&x) + 0) = 0;\n"
"}",
false);
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f() {\n" // #4737 - weird cast.
" int x;\n"
" do_something(&((char*)&x)[0], 1);\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f() {\n"
" int x;\n"
" char *p = (char*)&x + 1;\n"
"}",
true);
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f() {\n"
" int i;\n"
" i=f(), i!=2;\n"
"}");
ASSERT_EQUALS("", errout_str());
// using uninit var in condition
valueFlowUninit("void f(void) {\n"
" int x;\n"
" if (x) { }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: x\n", errout_str());
valueFlowUninit("void f() {\n"
" int x;\n"
" if (1 == (3 & x)) { }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: x\n", errout_str());
// ?:
valueFlowUninit("int f(int *ptr) {\n"
" int a;\n"
" int *p = ptr ? ptr : &a;\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("int f(int a) {\n"
" int x;\n"
" if (a==3) { x=2; }\n"
" y = (a==3) ? x : a;\n"
"}");
ASSERT_EQUALS("", errout_str());
// = ({ .. })
valueFlowUninit("void f() {\n"
" int x = ({ 1 + 2; });\n"
" int y = 1 + (x ? y : y);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: y\n", "", errout_str());
// >> => initialization / usage
{
const char code[] = "void f() {\n"
" int x;\n"
" if (i >> x) { }\n"
"}";
valueFlowUninit(code, true);
ASSERT_EQUALS("", errout_str());
valueFlowUninit(code, false);
ASSERT_EQUALS("[test.c:3]: (error) Uninitialized variable: x\n", errout_str());
}
valueFlowUninit("void f() {\n"
" int i, i2;\n"
" strm >> i >> i2;\n"
"}");
ASSERT_EQUALS("", errout_str());
// unconditional initialization
valueFlowUninit("int f() {\n"
" int ret;\n"
" if (a) { ret = 1; }\n"
" else { {} ret = 2; }\n"
" return ret;\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("int f() {\n"
" int ret;\n"
" if (a) { ret = 1; }\n"
" else { s=foo(1,{2,3},4); ret = 2; }\n"
" return ret;\n"
"}");
ASSERT_EQUALS("", errout_str());
// conditional initialization
valueFlowUninit("void f() {\n"
" int x;\n"
" if (y == 1) { x = 1; }\n"
" else { if (y == 2) { x = 1; } }\n"
" return x;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: x\n", "", errout_str());
valueFlowUninit("void f() {\n"
" int x;\n"
" if (y == 1) { x = 1; }\n"
" else { if (y == 2) { x = 1; } }\n"
" if (y == 3) { }\n" // <- ignore condition
" return x;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:6]: (error) Uninitialized variable: x\n", "", errout_str());
// initialization in condition
valueFlowUninit("void f() {\n"
" int a;\n"
" if (init(&a)) { }\n"
" a++;\n"
"}");
ASSERT_EQUALS("", errout_str());
// return, break, continue, goto
valueFlowUninit("void f() {\n"
" int x;\n"
" if (y == 1) { return; }\n"
" else { x = 1; }\n"
" return x;\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f() {\n"
" int x;\n"
" if (y == 1) { return; }\n"
" return x;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: x\n", errout_str());
valueFlowUninit("int f(int x) {\n"
" int ret;\n"
" if (!x) {\n"
" ret = -123;\n"
" goto out1;\n"
" }\n"
" return 0;\n"
"out1:\n"
"out2:\n"
" return ret;\n"
"}",
false);
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f() {\n"
" int i;\n"
" if (x) {\n"
" i = 1;\n"
" } else {\n"
" goto out;\n"
" }\n"
" i++;\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("int f() {\n"
" int i,x;\n"
" for (i=0;i<9;++i)\n"
" if (foo) break;\n"
" return x;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: x\n", errout_str());
valueFlowUninit("int f() {\n"
" int x;\n"
" while (foo)\n"
" if (bar) break;\n"
" return x;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: x\n", errout_str());
// try/catch : don't warn about exception variable
valueFlowUninit("void f() {\n"
" try {\n"
" } catch (CException* e) {\n"
" trace();\n"
" e->Delete();\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f() {\n" // #5347
" try {\n"
" } catch (const char* e) {\n"
" A a = e;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// exit
valueFlowUninit("void f() {\n"
" int x;\n"
" if (y == 1) { exit(0); }\n"
" else { x = 1; }\n"
" return x;\n"
"}");
ASSERT_EQUALS("", errout_str());
// strange code.. don't crash (#3415)
valueFlowUninit("void foo() {\n"
" int i;\n"
" ({ if (0); });\n"
" for_each(i) { }\n"
"}",
false);
// if, if
valueFlowUninit("void f(int a) {\n"
" int i;\n"
" if (a) i = 0;\n"
" if (a) i++;\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f() {\n"
" int a,b=0;\n"
" if (x) {\n"
" if (y) {\n"
" a = 0;\n"
" b = 1;\n"
" }\n"
" }\n"
" if (b) a++;\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f() {\n"
" int a=0, b;\n"
" if (x) { }\n"
" else { if (y==2) { a=1; b=2; } }\n"
" if (a) { ++b; }\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("static void f(int x, int y) {\n"
" int a;\n"
" if (x == 0) { a = y; }\n"
" if (x == 0 && (a == 1)) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("static void f() {\n"
" int a=0, b;\n"
" if (something) { a = dostuff(&b); }\n"
" if (!a || b) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("static void f(int x, int y) {\n"
" int a;\n"
" if (x == 0 && (a == 1)) { }\n"
"}",
true);
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: a\n", errout_str());
valueFlowUninit("void f() {\n"
" int a;\n"
" if (x) { a = 0; }\n"
" if (x) { if (y) { a++; } }\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f() {\n"
" int a;\n"
" if (x) { a = 0; }\n"
" if (x) { if (y) { } else { a++; } }\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct AB { int a; int b; };\n"
"void f(void) {\n"
" struct AB ab;\n"
" if (x) ab = getAB();\n"
" else ab.a = 0;\n"
" if (ab.a == 1) b = ab.b;\n"
"}",
false);
ASSERT_EQUALS("", errout_str());
valueFlowUninit("int f(void) {\n"
" int a;\n"
" int i;\n"
" if (x) { noreturn(); }\n"
" else { i = 0; }\n"
" if (i==1) { a = 0; }\n"
" else { a = 1; }\n"
" return a;\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("int f(int a) {\n" // #4560
" int x = 0, y;\n"
" if (a) x = 1;\n"
" else return 0;\n"
" if (x) y = 123;\n" // <- y is always initialized
" else {}\n"
" return y;\n"
"}");
TODO_ASSERT_EQUALS("", "[test.cpp:5] -> [test.cpp:7]: (warning) Uninitialized variable: y\n", errout_str());
valueFlowUninit("int f(int a) {\n" // #6583
" int x;\n"
" if (a < 2) exit(1);\n"
" else if (a == 2) x = 0;\n"
" else exit(2);\n"
" return x;\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("int f(int a) {\n" // #4560
" int x = 1, y;\n"
" if (a) x = 0;\n"
" else return 0;\n"
" if (x) {}\n"
" else y = 123;\n" // <- y is always initialized
" return y;\n"
"}");
TODO_ASSERT_EQUALS("", "[test.cpp:5] -> [test.cpp:7]: (warning) Uninitialized variable: y\n", errout_str());
valueFlowUninit("void f(int x) {\n" // #3948
" int value;\n"
" if (x !=-1)\n"
" value = getvalue();\n"
" if (x == -1 || value > 300) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("enum t_err { ERR_NONE, ERR_BAD_ARGS };\n" // #9649
"struct box_t { int value; };\n"
"int init_box(box_t *p, int v);\n"
"\n"
"void foo(int ret) {\n"
" box_t box2;\n"
" if (ret == ERR_NONE)\n"
" ret = init_box(&box2, 20);\n"
" if (ret == ERR_NONE)\n"
" z = x + box2.value;\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f(int x) {\n"
" int value;\n"
" if (x == 32)\n"
" value = getvalue();\n"
" if (x == 1)\n"
" v = value;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:6]: (error) Uninitialized variable: value\n", "", errout_str());
valueFlowUninit("void f(int x) {\n"
" int value;\n"
" if (x == 32)\n"
" value = getvalue();\n"
" if (x == 32) {}\n"
" else v = value;\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:6]: (warning) Uninitialized variable: value\n", errout_str());
valueFlowUninit("static int x;" // #4773
"int f() {\n"
" int y;\n"
" if (x) g();\n"
" if (x) y = 123;\n"
" else y = 456;\n"
" return y;\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("static int x;" // #4773
"int f() {\n"
" int y;\n"
" if (!x) g();\n"
" if (x) y = 123;\n"
" else y = 456;\n"
" return y;\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f(int a) {\n"
" int x;\n"
" if (a) x=123;\n"
" if (!a) {\n"
" if (!a) {}\n"
" else if (x) {}\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// asm
valueFlowUninit("void f() {\n"
" int x;\n"
" asm();\n"
" x++;\n"
"}");
ASSERT_EQUALS("", errout_str());
// sizeof / typeof / offsetof / etc
valueFlowUninit("void f() {\n"
" int i;\n"
" sizeof(i+1);\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f() {\n"
" int i;\n"
" if (100 == sizeof(i+1));\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f() {\n"
" struct ABC *abc;\n"
" int i = ARRAY_SIZE(abc.a);"
"}");
// FP ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f() {\n"
" int *abc;\n"
" typeof(*abc);\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f() {\n"
" struct ABC *abc;\n"
" return do_something(typeof(*abc));\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f() {\n"
" A *a;\n"
" a = malloc(sizeof(*a));\n"
"}");
ASSERT_EQUALS("", errout_str());
// &
valueFlowUninit("void f() {\n" // #4426 - address of uninitialized variable
" int a,b;\n"
" if (&a == &b);\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f() {\n" // #4439 - cast address of uninitialized variable
" int a;\n"
" x((LPARAM)(RECT*)&a);\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit(
"int main() {\n"
" int done;\n"
" dostuff(1, (AuPointer) &done);\n" // <- It is not conclusive if the "&" is a binary or unary operator. Bailout.
"}");
TODO_ASSERT_EQUALS("", "[test.cpp:3]: (error) Uninitialized variable: done\n", errout_str());
valueFlowUninit("void f() {\n" // #4778 - cast address of uninitialized variable
" long a;\n"
" &a;\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f() {\n" // #4717 - ({})
" int a = ({ long b = (long)(123); 2 + b; });\n"
"}",
false);
ASSERT_EQUALS("", errout_str());
}
void valueFlowUninit_functioncall() {
// #12462 - pointer data is not read
valueFlowUninit("struct myst { int a; };\n"
"void bar(const void* p) {}\n"
"void foo() {\n"
" struct myst item;\n"
" bar(&item);\n"
"}", false);
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct myst { int a; };\n"
"void bar(const void* p) { a = (p != 0); }\n"
"void foo() {\n"
" struct myst item;\n"
" bar(&item);\n"
" a = item.a;\n" // <- item.a is not initialized
"}", false);
ASSERT_EQUALS("[test.c:6]: (error) Uninitialized variable: item.a\n", errout_str());
valueFlowUninit("struct myst { int a; };\n"
"void bar(struct myst* p) { p->a = 0; }\n"
"void foo() {\n"
" struct myst item;\n"
" bar(&item);\n"
" a = item.a;\n"
"}", false);
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f(int& r) {}\n" // #12536
"void g() {\n"
" int i;\n"
" f(i);\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("int f(int& i, int j, int k) {\n" // #12514
" if (k)\n"
" i = 2;\n"
" return i + j;\n"
"}\n"
"int main() {\n"
" int i;\n"
" return f(i, 1, 0);\n"
"}");
ASSERT_EQUALS("[test.cpp:8] -> [test.cpp:4]: (warning) Uninitialized variable: i\n", errout_str());
valueFlowUninit("int f(int& i, int k) {\n"
" if (k)\n"
" i = 2;\n"
" return i;\n"
"}\n"
"int main() {\n"
" int i;\n"
" return f(i, 0);\n"
"}");
ASSERT_EQUALS("[test.cpp:8] -> [test.cpp:4]: (warning) Uninitialized variable: i\n", errout_str());
}
void uninitStructMember() { // struct members
checkUninitVar("struct AB { int a; int b; };\n"
"void f(void) {\n"
" struct AB ab;\n"
" int a = ab.a;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized struct member: ab.a\n", errout_str());
checkUninitVar("struct AB { int a; int b; };\n"
"void f(void) {\n"
" AB ab;\n"
" int a = ab.a;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized struct member: ab.a\n", errout_str());
checkUninitVar("struct AB { int a; int b; };\n"
"void f(void) {\n"
" struct AB ab;\n"
" ab.a = ab.a + 1;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized struct member: ab.a\n", errout_str());
checkUninitVar("struct AB { int a; int b; };\n"
"void do_something(const struct AB ab);\n"
"void f(void) {\n"
" struct AB ab;\n"
" ab.a = 0;\n"
" do_something(ab);\n"
"}\n", false);
ASSERT_EQUALS("[test.c:6]: (error) Uninitialized struct member: ab.b\n", errout_str());
checkUninitVar("struct AB { int a; int b; };\n" // #4760
"void do_something(int a);\n"
"void f(void) {\n"
" struct AB ab;\n"
" do_something(ab.a);\n"
"}\n", false);
ASSERT_EQUALS("[test.c:5]: (error) Uninitialized struct member: ab.a\n", errout_str());
checkUninitVar("struct AB { int a; int b; };\n"
"void do_something(const struct AB &ab) { a = ab.a; }\n"
"void f(void) {\n"
" struct AB ab;\n"
" ab.a = 0;\n"
" do_something(ab);\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("struct AB { int a; int b; };\n"
"void f(void) {\n"
" struct AB ab;\n"
" int a = ab.a;\n"
"}\n", false);
ASSERT_EQUALS("[test.c:4]: (error) Uninitialized struct member: ab.a\n", errout_str());
checkUninitVar("struct AB { int a; int b; };\n"
"void f(void) {\n"
" AB ab1;\n"
" AB ab2 = { ab1.a, 0 };\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized struct member: ab1.a\n", errout_str());
checkUninitVar("struct AB { int a; int b; };\n"
"void f(void) {\n"
" struct AB ab;\n"
" buf[ab.a] = 0;\n"
"}\n", false);
ASSERT_EQUALS("[test.c:4]: (error) Uninitialized struct member: ab.a\n", errout_str());
checkUninitVar("struct AB { int a; int b; };\n"
"void f(void) {\n"
" struct AB ab;\n"
" ab.a = 1;\n"
" x = ab;\n"
"}\n", false);
ASSERT_EQUALS("[test.c:5]: (error) Uninitialized struct member: ab.b\n", errout_str());
checkUninitVar("struct AB { int a; int b; };\n"
"void f(void) {\n"
" struct AB ab;\n"
" ab.a = 1;\n"
" x = *(&ab);\n"
"}\n", false);
ASSERT_EQUALS("[test.c:5]: (error) Uninitialized struct member: ab.b\n", errout_str());
checkUninitVar("void f(void) {\n"
" struct AB ab;\n"
" int x;\n"
" ab.a = (addr)&x;\n"
" dostuff(&ab,0);\n"
"}\n", false);
ASSERT_EQUALS("", errout_str());
checkUninitVar("struct Element {\n"
" static void f() { }\n"
"};\n"
"void test() {\n"
" Element *element; element->f();\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: element\n", errout_str());
checkUninitVar("struct Element {\n"
" static void f() { }\n"
"};\n"
"void test() {\n"
" Element *element; (*element).f();\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: element\n", errout_str());
checkUninitVar("struct Element {\n"
" static int v;\n"
"};\n"
"void test() {\n"
" Element *element; element->v;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: element\n", errout_str());
checkUninitVar("struct Element {\n"
" static int v;\n"
"};\n"
"void test() {\n"
" Element *element; (*element).v;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: element\n", errout_str());
checkUninitVar("struct Element {\n"
" void f() { }\n"
"};\n"
"void test() {\n"
" Element *element; element->f();\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: element\n", errout_str());
checkUninitVar("struct Element {\n"
" void f() { }\n"
"};\n"
"void test() {\n"
" Element *element; (*element).f();\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: element\n", errout_str());
checkUninitVar("struct Element {\n"
" int v;\n"
"};\n"
"void test() {\n"
" Element *element; element->v;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: element\n", errout_str());
checkUninitVar("struct Element {\n"
" int v;\n"
"};\n"
"void test() {\n"
" Element *element; (*element).v;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: element\n", errout_str());
checkUninitVar("struct AB { int a; int b; };\n" // pass struct member by address
"void f(void) {\n"
" struct AB ab;\n"
" assign(&ab.a, 0);\n"
"}\n", false);
ASSERT_EQUALS("", errout_str());
checkUninitVar("struct Cstring { char *text; int size, alloc; };\n"
"int maybe();\n"
"void f() {\n"
" Cstring res;\n"
" if ( ! maybe() ) return;\n" // <- fp goes away if this is removed
" ( ((res).text = (void*)0), ((res).size = (res).alloc = 0) );\n" // <- fp goes away if parentheses are removed
"}");
ASSERT_EQUALS("", errout_str());
{
constexpr char argDirectionsTestXmlData[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <function name=\"uninitvar_funcArgInTest\">\n"
" <arg nr=\"1\" direction=\"in\"/>\n"
" </function>\n"
" <function name=\"uninitvar_funcArgOutTest\">\n"
" <arg nr=\"1\" direction=\"out\"/>\n"
" </function>\n"
"</def>";
const Settings s = settingsBuilder(settings).libraryxml(argDirectionsTestXmlData, sizeof(argDirectionsTestXmlData)).build();
checkUninitVar("struct AB { int a; };\n"
"void f(void) {\n"
" struct AB ab;\n"
" uninitvar_funcArgInTest(&ab);\n"
" x = ab;\n"
"}\n", false, false, &s);
ASSERT_EQUALS("[test.c:5]: (error) Uninitialized struct member: ab.a\n", errout_str());
checkUninitVar("struct AB { int a; };\n"
"void f(void) {\n"
" struct AB ab;\n"
" uninitvar_funcArgOutTest(&ab);\n"
" x = ab;\n"
"}\n", false, false, &s);
ASSERT_EQUALS("", errout_str());
}
checkUninitVar("struct AB { int a; int b; };\n"
"void do_something(const struct AB ab);\n"
"void f(void) {\n"
" struct AB ab;\n"
" ab.a = 0;\n"
" ab.b = 0;\n"
" do_something(ab);\n"
"}\n", false);
ASSERT_EQUALS("", errout_str());
{
checkUninitVar("struct AB { char a[10]; };\n"
"void f(void) {\n"
" struct AB ab;\n"
" strcpy(ab.a, STR);\n"
"}\n", false);
ASSERT_EQUALS("", errout_str());
checkUninitVar("struct AB { unsigned char a[10]; };\n" // #8999 - cast
"void f(void) {\n"
" struct AB ab;\n"
" strcpy((char *)ab.a, STR);\n"
"}\n", false);
ASSERT_EQUALS("", errout_str());
checkUninitVar("struct AB { char a[10]; };\n"
"void f(void) {\n"
" struct AB ab;\n"
" strcpy(x, ab.a);\n"
"}\n", false);
TODO_ASSERT_EQUALS("[test.c:4]: (error) Uninitialized variable: ab.a\n", "", errout_str());
checkUninitVar("struct AB { int a; };\n"
"void f(void) {\n"
" struct AB ab;\n"
" dosomething(ab.a);\n"
"}\n", false);
ASSERT_EQUALS("", errout_str());
}
checkUninitVar("struct AB { int a; int b; };\n"
"void do_something(const struct AB ab);\n"
"void f(void) {\n"
" struct AB ab;\n"
" ab = getAB();\n"
" do_something(ab);\n"
"}\n", false);
ASSERT_EQUALS("", errout_str());
{
// #6769 - calling method that might assign struct members
checkUninitVar("struct AB { int a; int b; void set(); };\n"
"void f(void) {\n"
" struct AB ab;\n"
" ab.set();\n"
" x = ab;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("struct AB { int a; int get() const; };\n"
"void f(void) {\n"
" struct AB ab;\n"
" ab.get();\n"
" x = ab;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized struct member: ab.a\n", errout_str());
checkUninitVar("struct AB { int a; void dostuff() {} };\n"
"void f(void) {\n"
" struct AB ab;\n"
" ab.dostuff();\n"
" x = ab;\n"
"}");
TODO_ASSERT_EQUALS("error", "", errout_str());
}
checkUninitVar("struct AB { int a; struct { int b; int c; } s; };\n"
"void do_something(const struct AB ab);\n"
"void f(void) {\n"
" struct AB ab;\n"
" ab.a = 1;\n"
" ab.s.b = 2;\n"
" ab.s.c = 3;\n"
" do_something(ab);\n"
"}\n", false);
ASSERT_EQUALS("", errout_str());
checkUninitVar("struct conf {\n"
" char x;\n"
"};\n"
"\n"
"void do_something(struct conf ant_conf);\n"
"\n"
"void f(void) {\n"
" struct conf c;\n"
" initdata(&c);\n"
" do_something(c);\n"
"}\n", false);
ASSERT_EQUALS("", errout_str());
checkUninitVar("struct PIXEL {\n"
" union {\n"
" struct { unsigned char red,green,blue,alpha; };\n"
" unsigned int color;\n"
" };\n"
"};\n"
"\n"
"unsigned char f() {\n"
" struct PIXEL p1;\n"
" p1.color = 255;\n"
" return p1.red;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("struct AB { int a; int b; };\n"
"int f() {\n"
" struct AB *ab;\n"
" for (i = 1; i < 10; i++) {\n"
" if (condition && (ab = getab()) != NULL) {\n"
" a = ab->a;\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("struct AB { int a; int b; };\n"
"int f(int x) {\n"
" struct AB *ab;\n"
" if (x == 0) {\n"
" ab = getab();\n"
" }\n"
" if (x == 0 && (ab != NULL || ab->a == 0)) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("struct A { int *x; };\n" // declarationId is 0 for "delete"
"void foo(void *info, void*p);\n"
"void bar(void) {\n"
" struct A *delete = 0;\n"
" foo( info, NULL );\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("struct ABC { int a; int b; int c; };\n"
"void foo(int x, const struct ABC *abc);\n"
"void bar(void) {\n"
" struct ABC abc;\n"
" foo(123, &abc);\n"
" return abc.b;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized struct member: abc.a\n"
"[test.cpp:5]: (error) Uninitialized struct member: abc.b\n"
"[test.cpp:5]: (error) Uninitialized struct member: abc.c\n",
"[test.cpp:6]: (error) Uninitialized struct member: abc.b\n",
errout_str());
checkUninitVar("struct ABC { int a; int b; int c; };\n"
"void foo() {\n"
" struct ABC abc;\n"
" dostuff((uint32_t *)&abc.a);\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f(void) {\n"
" struct tm t;\n"
" t.tm_year = 123;\n"
"}");
ASSERT_EQUALS("", errout_str());
// return
checkUninitVar("struct AB { int a; int b; };\n"
"void f(void) {\n"
" struct AB ab;\n"
" ab.a = 0;\n"
" return ab.b;\n"
"}\n", false);
ASSERT_EQUALS("[test.c:5]: (error) Uninitialized struct member: ab.b\n", errout_str());
checkUninitVar("struct AB { int a; int b; };\n"
"void f(void) {\n"
" struct AB ab;\n"
" ab.a = 0;\n"
" return ab.a;\n"
"}\n", false);
ASSERT_EQUALS("", errout_str());
checkUninitVar("struct S { int a; int b; };\n" // #8299
"void f(void) {\n"
" struct S s;\n"
" s.a = 0;\n"
" return s;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized struct member: s.b\n", errout_str());
checkUninitVar("struct S { int a; int b; };\n" // #9810
"void f(void) {\n"
" struct S s;\n"
" return s.a ? 1 : 2;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized struct member: s.a\n", errout_str());
// checkIfForWhileHead
checkUninitVar("struct FRED {\n"
" int a;\n"
" int b;\n"
"};\n"
"\n"
"void f(void) {\n"
" struct FRED fred;\n"
" fred.a = do_something();\n"
" if (fred.a == 0) { }\n"
"}\n", false);
ASSERT_EQUALS("", errout_str());
checkUninitVar("struct FRED {\n"
" int a;\n"
" int b;\n"
"};\n"
"\n"
"void f(void) {\n"
" struct FRED fred;\n"
" fred.a = do_something();\n"
" if (fred.b == 0) { }\n"
"}\n", false, false);
ASSERT_EQUALS("[test.c:9]: (error) Uninitialized struct member: fred.b\n", errout_str());
checkUninitVar("struct Fred { int a; };\n"
"void f() {\n"
" struct Fred fred;\n"
" if (fred.a==1) {}\n"
"}", false);
ASSERT_EQUALS("[test.c:4]: (error) Uninitialized struct member: fred.a\n", errout_str());
checkUninitVar("struct S { int n; int m; };\n"
"void f(void) {\n"
" struct S s;\n"
" for (s.n = 0; s.n <= 10; s.n++) { }\n"
"}", false);
ASSERT_EQUALS("", errout_str());
checkUninitVar("void test2() {\n"
" struct { char type; } s_d;\n"
" if (foo(&s_d.type)){}\n"
"}");
ASSERT_EQUALS("", errout_str());
// for
checkUninitVar("struct AB { int a; };\n"
"void f() {\n"
" struct AB ab;\n"
" while (x) { clear(ab); z = ab.a; }\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("struct AB { int a; };\n"
"void f() {\n"
" struct AB ab;\n"
" while (x) { ab.a = ab.a + 1; }\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized struct member: ab.a\n", errout_str());
checkUninitVar("struct AB { int a; };\n"
"void f() {\n"
" struct AB ab;\n"
" while (x) { init(&ab); z = ab.a; }\n"
"}");
ASSERT_EQUALS("", errout_str());
// address of member
checkUninitVar("struct AB { int a[10]; int b; };\n"
"void f() {\n"
" struct AB ab;\n"
" int *p = ab.a;\n"
"}");
ASSERT_EQUALS("", errout_str());
// Reference
checkUninitVar("struct A { int x; };\n"
"void foo() {\n"
" struct A a;\n"
" int& x = a.x;\n"
" x = 0;\n"
" return a.x;\n"
"}");
ASSERT_EQUALS("", errout_str());
// non static data-member initialization
checkUninitVar("struct AB { int a=1; int b; };\n"
"void f(void) {\n"
" struct AB ab;\n"
" int a = ab.a;\n"
" int b = ab.b;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized struct member: ab.b\n", errout_str());
// STL class member
checkUninitVar("struct A {\n"
" std::map<int, int> m;\n"
" int i;\n"
"};\n"
"void foo() {\n"
" A a;\n"
" x = a.m;\n"
"}");
ASSERT_EQUALS("", errout_str());
// Unknown type (C++)
checkUninitVar("struct A {\n"
" C m;\n"
" int i;\n"
"};\n"
"void foo() {\n"
" A a;\n"
" x = a.m;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
// Unknown type (C)
checkUninitVar("struct A {\n"
" C m;\n"
" int i;\n"
"};\n"
"void foo() {\n"
" A a;\n"
" x = a.m;\n"
"}", false);
ASSERT_EQUALS("[test.c:7]: (error) Uninitialized struct member: a.m\n", errout_str());
// Type with constructor
checkUninitVar("class C { C(); }\n"
"struct A {\n"
" C m;\n"
" int i;\n"
"};\n"
"void foo() {\n"
" A a;\n"
" x = a.m;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #11002
checkUninitVar("struct S { char *p; int len; };\n"
"void f() {\n"
" S s;\n"
" s.p = nullptr;\n"
" char* q = (s).p;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// if with flag
checkUninitVar("struct AB { int a; int b; };\n"
"int f(int x) {\n"
" struct AB ab;\n"
" int flag = 0;\n"
" if (x == 0) {\n"
" flag = dostuff(&ab);\n"
" }\n"
" if (flag) {\n"
" a = ab.a;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("struct S { int x; };\n"
"S h() {\n"
" S s;\n"
" S& r = s;\n"
" r.x = 0;\n"
" return s;\n"
"}\n"
"S i() {\n"
" S s;\n"
" S& r{ s };\n"
" r.x = 0;\n"
" return s;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("struct S { int i; };\n" // #12142
"int f() {\n"
" S s;\n"
" int S::* p = &S::i;\n"
" s.*p = 123;\n"
" return s.i;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void uninitvar2_while() {
// extracttests.start: int a;
// for, while
checkUninitVar("void f() {\n"
" int x;\n"
" while (a) {\n"
" x = x + 1;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: x\n", errout_str());
checkUninitVar("void f() {\n"
" int x;\n"
" do {\n"
" x = x + 1;\n"
" } while (a);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: x\n", errout_str());
checkUninitVar("void f() {\n"
" for (int x = x; x < 10; x++) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Uninitialized variable: x\n", errout_str());
// extracttests.start: struct Element{Element*Next();};
checkUninitVar("void f() {\n"
" for (Element *ptr3 = ptr3->Next(); ptr3; ptr3 = ptr3->Next()) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Uninitialized variable: ptr3\n", errout_str());
// extracttests.start: int a;
checkUninitVar("void f() {\n"
" int x;\n"
" while (a) {\n"
" init(&x);\n"
" x++;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n"
" int x;\n"
" while (a) {\n"
" if (b) x++;\n"
" else x = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n"
" int x;\n"
" for (int i = 0; i < 10; i += x) {\n"
" x = y;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n"
" int x;\n"
" for (int i = 0; i < 10; i += x) { }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: x\n", errout_str());
checkUninitVar("int f() {\n"
" int i;\n"
" for (i=0;i<9;++i)\n"
" if (foo()) return i;\n"
" return 9;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n"
" int i;\n"
" do {} while (!getvalue(&i));\n"
" i++;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("int f(void) {\n"
" int x;\n"
" while (a()) {\n" // <- condition must always be true or there will be problem
" if (b()) {\n"
" x = 1;\n"
" break;"
" }\n"
" }\n"
" return x;\n"
"}");
TODO_ASSERT_EQUALS("error", "", errout_str());
checkUninitVar("int f(void) {\n"
" int x;\n"
" while (a()) {\n"
" if (b() && (x=1)) {\n"
" return x;\n"
" }\n"
" }\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
// extracttests.start: void do_something(int);
checkUninitVar("void f(void) {\n"
" int x;\n"
" for (;;) {\n"
" int a = x+1;\n"
" do_something(a);\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: x\n", errout_str());
checkUninitVar("struct AB {int a; int b;};\n"
"void f(void) {\n"
" struct AB ab;\n"
" while (true) {\n"
" int a = 1+ab.a;\n"
" do_something(a);\n"
" }\n"
"}\n", false);
ASSERT_EQUALS("[test.c:5]: (error) Uninitialized struct member: ab.a\n", errout_str());
checkUninitVar("void f(int i) {\n" // #4569 fp
" float *buffer;\n"
" if(i>10) buffer = f;\n"
" if(i>10) {\n"
" for (int i=0;i<10;i++)\n"
" buffer[i] = 0;\n" // <- fp
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f(){\n" // #4519 - fp: inline assembler in loop
" int x;\n"
" for (int i = 0; i < 10; i++) {\n"
" asm(\"foo\");\n"
" if (x & 0xf1) { }\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("static void f(void) {\n"
" struct ABC *abc;\n"
" for (i = 0; i < 10; i++)\n"
" x += sizeof(*abc);\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f(void) {\n" // #4879
" int i;\n"
" while (x) {\n"
" for (i = 0; i < 5; i++)\n"
" a[i] = b[i];\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f(void) {\n" // #5658
" struct Foo *foo;\n"
" while (true) {\n"
" foo = malloc(sizeof(*foo));\n"
" foo->x = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f(void) {\n"
" int i;\n"
" while (x) {\n"
" for (i=0,y=i;;){}\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n"
" char *p = (char *)malloc(256);\n"
" while(*p && *p == '_')\n"
" p++;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Memory is allocated but not initialized: *p\n", errout_str());
// #6646 - init in for loop
checkUninitVar("void f() {\n" // No FP
" for (int i;;i++)\n"
" dostuff(&i);\n"
"}");
ASSERT_EQUALS("", errout_str());
// extracttests.start: int a;
checkUninitVar("void f() {\n" // No FN
" for (int i;;i++)\n"
" a=i;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Uninitialized variable: i\n", errout_str());
checkUninitVar("namespace N {\n" // #7377
" template<typename T>\n"
" class C {};\n"
" using V = class C<void>;\n"
"}\n"
"int f() {\n"
" int r = 0;\n"
" for (int x; x < 4; x++)\n"
" r += x;\n"
" return r;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:8]: (error) Uninitialized variable: x\n", errout_str());
}
void uninitvar2_4494() {
checkUninitVar("namespace N1 {\n"
" class Fred {\n"
" public:\n"
" static void f1(char *p) { *p = 0; }\n"
" };\n"
" void fa(void) { char *p; Fred::f1(p); }\n"
" void fb(void) { char *p; Fred::f2(p); }\n"
" void fc(void) { char *p; ::N1::Fred::f1(p); }\n"
" void fd(void) { char *p; ::N1::Fred::f2(p); }\n"
"}\n"
"namespace N2 {\n"
" static void f1(char *p) { *p = 0; }\n"
" void fa(void) { char *p; f1(p); }\n"
" void fb(void) { char *p; f2(p); }\n"
" void fc(void) { char *p; N1::Fred::f1(p); }\n"
" void fd(void) { char *p; N1::Fred::f2(p); }\n"
" void fe(void) { char *p; ::N1::Fred::f1(p); }\n"
" void ff(void) { char *p; ::N1::Fred::f2(p); }\n"
" void fg(void) { char *p; Foo::f1(p); }\n"
" void fh(void) { char *p; Foo::f2(p); }\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Uninitialized variable: p\n"
"[test.cpp:8]: (error) Uninitialized variable: p\n"
"[test.cpp:13]: (error) Uninitialized variable: p\n"
"[test.cpp:15]: (error) Uninitialized variable: p\n"
"[test.cpp:17]: (error) Uninitialized variable: p\n", errout_str());
checkUninitVar("class Fred {\n"
"public:\n"
" void f1(char *p) { *p = 0; }\n"
"};\n"
"Fred fred;\n"
"void f(void) {\n"
" char *p;\n"
" fred.f1(p);\n"
"}");
ASSERT_EQUALS("[test.cpp:8]: (error) Uninitialized variable: p\n", errout_str());
checkUninitVar("class Fred {\n"
"public:\n"
" class Wilma {\n"
" public:\n"
" class Barney {\n"
" public:\n"
" class Betty {\n"
" public:\n"
" void f1(char *p) { *p = 0; }\n"
" };\n"
" Betty betty;\n"
" };\n"
" Barney barney;\n"
" };\n"
" Wilma wilma;\n"
"};\n"
"Fred fred;\n"
"void f(void) {\n"
" char *p;\n"
" fred.wilma.barney.betty.f1(p);\n"
"}");
ASSERT_EQUALS("[test.cpp:20]: (error) Uninitialized variable: p\n", errout_str());
}
void uninitvar2_malloc() {
checkUninitVar("int f() {\n"
" int *p = (int*)malloc(40);\n"
" return *p;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Memory is allocated but not initialized: p\n", errout_str());
checkUninitVar("void f() {\n"
" int *p = (int*)malloc(40);\n"
" int var = *p;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Memory is allocated but not initialized: p\n", errout_str());
checkUninitVar("struct AB { int a; int b; };\n"
"int f() {\n"
" struct AB *ab = (AB*)malloc(sizeof(struct AB));\n"
" return ab->a;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Memory is allocated but not initialized: ab\n"
"[test.cpp:4]: (error) Uninitialized struct member: ab.a\n",
errout_str());
checkUninitVar("struct t_udf_file { int dir_left; };\n"
"\n"
"void f() {\n"
" struct t_udf_file *newf;\n"
" newf = malloc(sizeof(*newf));\n"
" if (!newf) {};\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n"
" char *s = malloc(100);\n"
" if (s != NULL) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n"
" char *p = malloc(100);\n"
" p || assert_failed();\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n"
" char *p = malloc(100);\n"
" x = p;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("int* f() {\n"
" int *p = (int*)malloc(40);\n"
" return p;\n"
"}");
ASSERT_EQUALS("", errout_str());
// function parameter (treat it as initialized until malloc is used)
checkUninitVar("int f(int *p) {\n"
" if (*p == 1) {}\n" // no error
" p = (int*)malloc(256);\n"
" return *p;\n" // error
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Memory is allocated but not initialized: p\n", errout_str());
checkUninitVar("struct AB { int a; int b; };\n"
"int f(struct AB *ab) {\n"
" if (ab->a == 1) {}\n" // no error
" ab = (AB*)malloc(sizeof(struct AB));\n"
" return ab->a;\n" // error
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized struct member: ab.a\n", errout_str());
checkUninitVar("struct AB { int a; int b; };\n"
"void do_something(struct AB *ab);\n" // unknown function
"void f() {\n"
" struct AB *ab = (AB*)malloc(sizeof(struct AB));\n"
" do_something(ab);\n"
"}");
ASSERT_EQUALS("", errout_str());
// analysis failed. varid 0.
checkUninitVar("void *vlc_custom_create (vlc_object_t *parent, size_t length, const char *typename) {\n"
" assert (length >= sizeof (vlc_object_t));\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void uninitvar_ternaryexpression() { // #4683
checkUninitVar("struct B { int asd; };\n"
"int f() {\n"
" int a=0;\n"
" struct B *b;\n"
" if (x) {\n"
" a = 1;\n"
" b = p;\n"
" }\n"
" return a ? b->asd : 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void uninitvar_rangeBasedFor() {
checkUninitVar("void function(Entry& entry) {\n" // #7078
" for (auto* expr : entry.exprs) {\n"
" expr->operate();\n"
" expr->operate();\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n"
" int *item;\n"
" for (item: itemList) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n"
" int buf[10];\n"
" for (int &i: buf) { i = 0; }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void uninitvar_static() { // #8734
checkUninitVar("struct X { "
" typedef struct { int p; } P_t; "
" static int arr[]; "
"}; "
"int X::arr[] = {42}; "
"void f() { "
" std::vector<X::P_t> result; "
" X::P_t P; "
" P.p = 0; "
" result.push_back(P); "
"}");
ASSERT_EQUALS("", errout_str());
}
void uninitvar_configuration() {
const Settings s = settingsBuilder(settings).checkLibrary().build();
checkUninitVar("int f() {\n"
" int i, j;\n"
" do {\n"
" i = 0;\n"
" return i;\n"
" } while (0);\n"
"}\n", true, false, &s);
ASSERT_EQUALS("", errout_str());
}
void checkExpr() {
checkUninitVar("struct AB { int a; int b; };\n"
"void f() {\n"
" struct AB *ab = (struct AB*)calloc(1, sizeof(*ab));\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void trac_4871() { // #4871
checkUninitVar("void pickup(int a) {\n"
"bool using_planner_action;\n"
"if (a) {\n"
" using_planner_action = false;\n"
"}\n"
"else {\n"
" try\n"
" {}\n"
" catch (std::exception &ex) {\n"
" return;\n"
" }\n"
" using_planner_action = true;\n"
"}\n"
"if (using_planner_action) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void syntax_error() { // Ticket #5073
const char code[] = "struct flex_array {};\n"
"struct cgroup_taskset {};\n"
"void cgroup_attach_task() {\n"
" struct flex_array *group;\n"
" struct cgroup_taskset tset = { };\n"
" do { } while_each_thread(leader, tsk);\n"
"}";
ASSERT_THROW_INTERNAL(checkUninitVar(code), SYNTAX);
}
void trac_5970() { // Ticket #5970
checkUninitVar("void DES_ede3_ofb64_encrypt() {\n"
" DES_cblock d;\n"
" char *dp;\n"
" dp=(char *)d;\n"
" init(dp);\n"
"}", false);
// Unknown type
TODO_ASSERT_EQUALS("", "[test.c:4]: (error) Uninitialized variable: d\n", errout_str());
}
void valueFlowUninit_(const char* file, int line, const char code[], bool cpp = true)
{
// Tokenize..
const Settings s = settingsBuilder(settings).debugwarnings(false).build();
SimpleTokenizer tokenizer(s, *this);
ASSERT_LOC(tokenizer.tokenize(code, cpp), file, line);
// Check for redundant code..
CheckUninitVar checkuninitvar(&tokenizer, &s, this);
(checkuninitvar.valueFlowUninit)();
}
#define ctu(code) ctu_(__FILE__, __LINE__, code)
void valueFlowUninitTest() {
// #9735 - FN
valueFlowUninit("typedef struct\n"
"{\n"
" int x;\n"
" unsigned int flag : 1;\n" // bit filed gets never initialized
"} status;\n"
"bool foo(const status * const s)\n"
"{\n"
" return s->flag;\n" // << uninitvar
"}\n"
"void bar(const status * const s)\n"
"{\n"
" if( foo(s) == 1) {;}\n"
"}\n"
"void f(void)\n"
"{\n"
" status s;\n"
" s.x = 42;\n"
" bar(&s);\n"
"}");
ASSERT_EQUALS("[test.cpp:18] -> [test.cpp:12] -> [test.cpp:8]: (warning) Uninitialized variable: s->flag\n", errout_str());
// Ticket #2207 - False negative
valueFlowUninit("void foo() {\n"
" int a;\n"
" b = c - a;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: a\n", errout_str());
valueFlowUninit("void foo() {\n"
" int a;\n"
" b = a - c;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: a\n", errout_str());
// Ticket #6455 - some compilers allow const variables to be uninitialized
// extracttests.disable
valueFlowUninit("void foo() {\n"
" const int a;\n"
" b = c - a;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: a\n", errout_str());
// extracttests.enable
valueFlowUninit("void foo() {\n"
" int *p;\n"
" realloc(p,10);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: p\n", errout_str());
valueFlowUninit("void foo() {\n" // #5240
" char *p = malloc(100);\n"
" char *tmp = realloc(p,1000);\n"
" if (!tmp) free(p);\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void foo() {\n"
" int *p = NULL;\n"
" realloc(p,10);\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f() {\n"
" int x;\n"
" switch (x) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: x\n", errout_str());
valueFlowUninit("int f() {\n"
" int x;\n"
" init(x);\n"
" return x;\n" // TODO: inconclusive ?
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f() {\n" // #8172
" char **x;\n"
" if (2 < sizeof(*x)) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void foo() {\n" // #5259 - False negative
" int a;\n"
" int x[] = {a,2};\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: a\n", errout_str());
valueFlowUninit("void foo()\n"
"{\n"
" int x;\n"
" int *y = &x;\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void foo()\n"
"{\n"
" int *x;\n"
" int *&y = x;\n"
" y = nullptr;\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void foo()\n"
"{\n"
" int x = xyz::x;\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f()\n"
"{\n"
" extern int a;\n"
" a++;\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("static void foo()\n"
"{\n"
" int x, y;\n"
" x = (y = 10);\n"
" int z = y * 2;\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("static void foo() {\n"
" int x, y;\n"
" x = ((y) = 10);\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("static void foo()\n"
"{\n"
" Foo p;\n"
" p.abcd();\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("static void foo()\n"
"{\n"
" Foo p;\n"
" int x = p.abcd();\n"
"}");
ASSERT_EQUALS("", errout_str());
// struct
valueFlowUninit("struct AB { int a; int b; };\n"
"void f(void) {\n"
" AB ab;\n"
" AB *p = &ab;\n"
" p->a = 1;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct S {\n"
" S& rIo;\n"
" S(S&);\n"
" void Write();\n"
"};\n"
"void foo(bool b, struct S &io) {\n"
" S* p;\n"
" if (b)\n"
" p = new S(io);\n"
" p->Write();\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:8] -> [test.cpp:10]: (warning) Uninitialized variable: p\n",
"[test.cpp:8] -> [test.cpp:10]: (warning) Uninitialized variable: p.rIo\n",
errout_str());
// Unknown types
{
valueFlowUninit("void a()\n"
"{\n"
" A ret;\n"
" return ret;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #3916 - avoid false positive
valueFlowUninit("void f(float x) {\n"
" union lf { long l; float f; } u_lf;\n"
" float hx = (u_lf.f = (x), u_lf.l);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
valueFlowUninit("void a()\n"
"{\n"
" int x[10];\n"
" int *y = x;\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void a()\n"
"{\n"
" int x;\n"
" int *y = &x;\n"
" *y = 0;\n"
" x++;\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void a()\n"
"{\n"
" char x[10], y[10];\n"
" char *z = x;\n"
" memset(z, 0, sizeof(x));\n"
" memcpy(y, x, sizeof(x));\n"
"}");
ASSERT_EQUALS("", errout_str());
// Handling >> and <<
{
valueFlowUninit("int a() {\n"
" int ret;\n"
" std::cin >> ret;\n"
" ret++;\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f(int b) {\n"
" int a;\n"
" std::cin >> b >> a;\n"
" return a;"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void foo() {\n" // #3707
" Node node;\n"
" int x;\n"
" node[\"abcd\"] >> x;\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("int a(FArchive &arc) {\n" // #3060 (initialization through operator<<)
" int *p;\n"
" arc << p;\n" // <- TODO initialization?
" return *p;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: p\n", errout_str());
// #4320
valueFlowUninit("void f() {\n"
" int a;\n"
" a << 1;\n"
" return a;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: a\n", errout_str());
// #9750
valueFlowUninit("struct S {\n"
" int one;\n"
" int two;\n"
"};\n"
"\n"
"void test(std::istringstream& in) {\n"
" S p;\n"
" in >> p.one >> p.two;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
valueFlowUninit("struct S { int x; };\n" // #9417
"void f() {\n"
" S s;\n"
" return s(1);\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void a() {\n" // asm
" int x;\n"
" asm();\n"
" x++;\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void a()\n"
"{\n"
" int x[10];\n"
" struct xyz xyz1 = { .x = x };\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void foo()\n"
"{\n"
" char *buf = malloc(100);\n"
" struct ABC *abc = buf;\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("class Fred {\n"
"public:\n"
" FILE *f;\n"
" ~Fred();\n"
"}\n"
"Fred::~Fred()\n"
"{\n"
" fclose(f);\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f()\n"
"{\n"
" int c;\n"
" ab(sizeof(xyz), &c);\n"
" if (c);\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f()\n"
"{\n"
" int c;\n"
" a = (f2(&c));\n"
" c++;\n"
"}");
ASSERT_EQUALS("", errout_str());
// goto/setjmp/longjmp..
valueFlowUninit("void foo(int x)\n"
"{\n"
" long b;\n"
" if (g()) {\n"
" b =2;\n"
" goto found;\n"
" }\n"
"\n"
" return;\n"
"\n"
"found:\n"
" int a = b;\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("int foo()\n"
"{\n"
" jmp_buf env;\n"
" int a;\n"
" int val = setjmp(env);\n"
" if(val)\n"
" return a;\n"
" a = 1;\n"
" longjmp(env, 1);\n"
"}");
ASSERT_EQUALS("", errout_str());
// range for..
valueFlowUninit("void f() {\n"
" X *item;\n"
" for (item: itemList) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("X f() {\n"
" if (!itemList.empty()) {\n"
" X* item;\n"
" for(item: itemList) {}\n"
" return *item;\n"
" }\n"
" return X{};\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// macro_for..
valueFlowUninit("int foo()\n"
"{\n"
" int retval;\n"
" if (condition) {\n"
" for12(1,2) { }\n"
" retval = 1;\n"
" }\n"
" else\n"
" retval = 2;\n"
" return retval;\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void foo(struct qb_list_head *list) {\n"
" struct qb_list_head *iter;\n"
" qb_list_for_each(iter, list) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void json_parse_nat_type_flags(json_t *root) {\n"
" int index;\n"
" json_array_foreach(root, index, value) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("int foo()\n"
"{\n"
" int i;\n"
" goto exit;\n"
" i++;\n"
"exit:\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("int foo() {\n"
" int x,y=0;\n"
"again:\n"
" if (y) return x;\n"
" x = a;\n"
" y = 1;\n"
" goto again;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #4040 - False positive
valueFlowUninit("int f(int x) {\n"
" int iter;\n"
" {\n"
" union\n"
" {\n"
" int asInt;\n"
" double asDouble;\n"
" };\n"
"\n"
" iter = x;\n"
" }\n"
" return 1 + iter;\n"
"}");
ASSERT_EQUALS("", errout_str());
// C++11 style initialization
valueFlowUninit("int f() {\n"
" int i = 0;\n"
" int j{ i };\n"
" return j;\n"
"}");
ASSERT_EQUALS("", errout_str());
// Ticket #5646
valueFlowUninit("float foo() {\n"
" float source[2] = {3.1, 3.1};\n"
" float (*sink)[2] = &source;\n"
" return (*sink)[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
// Ticket #8755
valueFlowUninit("void f(int b) {\n"
" int a;\n"
" if (b == 10)\n"
" a = 1;\n"
" if (b == 13)\n"
" a = 1;\n"
" if (b == 'x') {}\n"
" if (a) {}\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:8]: (error) Uninitialized variable: a\n", "", errout_str());
valueFlowUninit("void h() {\n"
" int i;\n"
" int* v = &i;\n"
" sscanf(\"0\", \"%d\", v);\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void test(int p) {\n"
" int f;\n"
" if (p > 0)\n"
" f = 0;\n"
" if (p > 1)\n"
" f += 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("unsigned char get();\n"
"char f() {\n"
" unsigned char c;\n"
" do {\n"
" c = get();\n"
" } while (isalpha(c) == 0);\n"
" return static_cast<char>(c);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f(int x)\n"
"{\n"
" int i;\n"
" char value;\n"
" for(i = 0; i < 1; i++) {\n"
" if(x > 1)\n"
" value = 0;\n"
" }\n"
" printf(\"\", value);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:6] -> [test.cpp:9]: (warning) Uninitialized variable: value\n", errout_str());
valueFlowUninit("void f(int x)\n"
"{\n"
" int i;\n"
" char value;\n"
" for(i = 0; i < 1; i++) {\n"
" if(x > 1)\n"
" value = 0;\n"
" else\n"
" value = 1;\n"
" }\n"
" printf(\"\", value);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// function pointers
valueFlowUninit("int f (const struct FileFuncDefs *ffd) {\n" // #10279
" int c;\n"
" (*ffd->zread)(&c, 1);\n"
" return c;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("int foo(unsigned int code) {\n" // #10279
" int res;\n\n"
" (* (utility_table[code])) (&res);\n"
" return (res);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct Archive {\n"
" bool isNull;\n"
" friend void operator&(const Archive &, bool &isNull);\n"
"};\n"
"void load(Archive& ar) {\n"
" bool isNull;\n"
" ar & isNull;\n"
" if (!isNull) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #10119
valueFlowUninit("struct Foo {\n"
" int i{};\n"
" static const float cf;\n"
"};\n"
"const float Foo::cf = 0.1f;\n"
"int bar() {\n"
" Foo f;\n"
" return f.i;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #10326
valueFlowUninit("void foo() {\n"
" int cnt;\n"
" do {\n"
" cnt = 32 ;\n"
" }\n"
" while ( 0 ) ;\n"
" if (cnt != 0) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #10327 - avoid extra warnings for uninitialized variable
valueFlowUninit("void dowork( int me ) {\n"
" if ( me == 0 ) {}\n" // <- not uninitialized
"}\n"
"\n"
"int main() {\n"
" int me;\n"
" dowork(me);\n" // <- me is uninitialized
"}");
ASSERT_EQUALS("[test.cpp:7]: (error) Uninitialized variable: me\n", errout_str());
valueFlowUninit("int foo() {\n"
" int x;\n"
" int a = x;\n" // <- x is uninitialized
" return a;\n" // <- a has been initialized
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: x\n", errout_str());
// #10468
valueFlowUninit("uint32_t foo(uint32_t in) {\n"
" uint32_t out, mask = 0x7F;\n"
" while (mask ^ 0x7FFFFFFF)\n"
" out = in & ~mask;\n"
" return out;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #6597
valueFlowUninit("int f(int b) {\n"
" int a;\n"
" if (!b)\n"
" a = 1;\n"
" if (b)\n"
" return a;\n"
" else\n"
" return -1;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:6]: (warning) Uninitialized variable: a\n", errout_str());
// #9772
valueFlowUninit("int func(void) {\n"
" int rez;\n"
" struct sccb* ccb;\n"
" do {\n"
" if ((ccb = calloc(1, sizeof(*ccb))) == NULL) {\n"
" rez = 1;\n"
" break;\n"
" }\n"
" rez = 0;\n"
" } while (0);\n"
" if (rez != 0)\n"
" free(ccb);\n"
" return rez;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #10553
valueFlowUninit("struct CharDataOnly {\n"
" char data[100];\n"
"};\n"
"CharDataOnly f() {\n"
" CharDataOnly testData;\n"
" strcpy(testData.data, \"string smaller than size\");\n"
" return testData;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #10089
valueFlowUninit("typedef union {\n"
" struct { int x; };\n"
" int v[1];\n"
"} U;\n"
"void init(int* d) {\n"
" *d = 42;\n"
"}\n"
"void f() {\n"
" U u;\n"
" init(u.v);\n"
" printf(\"%d\\n\", u.x);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #10280
valueFlowUninit("union U {\n"
" char c[2];\n"
" uint16_t u16;\n"
"};\n"
"uint16_t f(std::istream& is) {\n"
" U u;\n"
" is.read(u.c, 2);\n"
" return u.u16;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f() {\n"
" char src, dest;\n"
" std::memcpy(&dest, &src, 1);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: &src\n", errout_str());
// #10988
valueFlowUninit("void f(const void* ptr, bool* result) {\n"
" int dummy;\n"
" *result = (&dummy < ptr);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct A {\n"
" int x;\n"
"};\n"
"void f() {\n"
" A a;\n"
" A* p = &a;\n"
" p->x = 1;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct A {\n"
" int x;\n"
"};\n"
"void g(const int&);\n"
"void f() {\n"
" A a;\n"
" g(a.x);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:7]: (error) Uninitialized variable: a.x\n", errout_str());
valueFlowUninit("struct A {\n"
" int x;\n"
"};\n"
"void g(const int&);\n"
"void f() {\n"
" A a;\n"
" A* p = &a;\n"
" g(p->x);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:7] -> [test.cpp:8]: (error) Uninitialized variable: p->x\n", errout_str());
valueFlowUninit("void f() {\n"
" int a;\n"
" a++;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: a\n", errout_str());
// #11006
valueFlowUninit("int g(int);\n"
"void f() {\n"
" int received[NSIG];\n"
" for (int sig = 0; sig < NSIG; sig++)\n"
" received[sig] = g(sig);\n"
" for (int sig = 0; sig < NSIG; sig++)\n"
" if (received[sig]) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void increment(int& i) { ++i; }\n" // #6475
"int f() {\n"
" int n;\n"
" increment(n);\n"
" return n;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:1]: (warning) Uninitialized variable: i\n", errout_str());
// #11412
valueFlowUninit("void f(int n) {\n"
" short* p;\n"
" if (n) {\n"
" p = g(n);\n"
" }\n"
" for (int i = 0; i < n; i++)\n"
" (void)p[i];\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #11492
valueFlowUninit("void f() {\n"
" int i;\n"
" try {\n"
" i = 0;\n"
" }\n"
" catch (...) {\n"
" if (i) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #11624
valueFlowUninit("const int N = 2;\n"
"void g(int a[N]) {\n"
" for (int i = 0; i < N; ++i)\n"
" a[i] = 1;\n"
"}\n"
"void f() {\n"
" int a[N];\n"
" g(a);\n"
" if (a[0]) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #11673
valueFlowUninit("void f() {\n"
" bool b;\n"
" auto g = [&b]() {\n"
" b = true;\n"
" };\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #6619
valueFlowUninit("void f() {\n"
" int nok, i;\n"
" for (i = 1; i < 5; i++) {\n"
" if (i == 8)\n"
" nok = 8;\n"
" }\n"
" printf(\"nok = %d\\n\", nok);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:7]: (error) Uninitialized variable: nok\n", errout_str());
// #7475
valueFlowUninit("struct S {\n"
" int a, b, c;\n"
"} typedef s_t;\n"
"void f() {\n"
" s_t s;\n"
" printf(\"%d\", s.a);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:6]: (error) Uninitialized variable: s.a\n", errout_str());
valueFlowUninit("void f(char* src) {\n" // #11608
" char envar[64], *cp, c;\n"
" for (src += 2, cp = envar; (c = *src) != '\\0'; src++)\n"
" *cp++ = c;\n"
" if (cp != envar)\n"
" if ((cp = getenv(envar)) != NULL) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #11459
valueFlowUninit("struct S {\n"
" enum E { N = 3 };\n"
" static const int A[N];\n"
" static void f();\n"
"};\n"
"const int S::A[N] = { 0, 1, 2 };\n"
"void S::f() {\n"
" int tmp[N];\n"
" for (int i = 0; i < N; i++)\n"
" tmp[i] = 0;\n"
" if (tmp[0]) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #11055
valueFlowUninit("void g(int*);\n"
"void f(bool b) {\n"
" int i;\n"
" int* p = b ? &i : nullptr;\n"
" g(p);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct T {};\n" // #11075
"struct S {\n"
" int n;\n"
" struct T t[10];\n"
"};\n"
"void f(struct S* s, char** tokens) {\n"
" struct T t[10];\n"
" int n = 0;\n"
" for (int i = 0; i < s->n; i++)\n"
" if (tokens[i])\n"
" t[n++] = s->t[i];\n"
" for (int i = 0; i < n; i++)\n"
" t[i];\n"
"}\n", false);
ASSERT_EQUALS("", errout_str());
valueFlowUninit("bool g();\n"
"void f() {\n"
" int a[10];\n"
" int idx = 0;\n"
" if (g())\n"
" a[idx++] = 1;\n"
" for (int i = 0; i < idx; i++)\n"
" (void)a[i];\n"
"}\n");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f() {\n"
" int x;\n"
" int *p = 0 ? 0 : &x;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void g() {\n"
" int y;\n"
" int *q = 1 ? &y : 0;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f(std::stringstream& ss) {\n" // #11805
" int x;\n"
" int* p = &x;\n"
" ss >> *p;\n"
"}\n"
"void g() {\n"
" int x;\n"
" int* p = &x;\n"
" int& r = *p;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f(std::stringstream& ss) {\n" // #11805
" int x;\n"
" int* p = &x;\n"
" ss >> *p;\n"
"}\n"
"void g() {\n"
" int x;\n"
" int* p = &x;\n"
" int& r = *p;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct S1 { char a[10]; };\n" // #11804
"struct S2 { struct S1 s1; };\n"
"void init(char* c);\n"
"void f() {\n"
" struct S2 s2;\n"
" init(s2.s1.a);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct S { int i; };\n" // #11731
"void f(const S*& p);\n"
"int g() {\n"
" const S* s;\n"
" f(s);\n"
" return s->i;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("int f(int i) {\n"
" int x;\n"
" int* p = &x;\n"
" return i >> *p;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: *p\n", errout_str());
valueFlowUninit("void f(int& x) {\n"
" int i;\n"
" x = i;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: i\n", errout_str());
valueFlowUninit("void f() {\n" // #11890
" int x;\n"
" int* a[] = { &x };\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #11992
valueFlowUninit("void foo(const int &x) {\n"
" if(x==42) {;}\n"
"}\n"
"void test(void) {\n"
" int t;\n"
" int &p = t;\n"
" int &s = p;\n"
" int &q = s;\n"
" foo(q);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:9]: (error) Uninitialized variable: q\n", errout_str());
valueFlowUninit("int g();\n" // #12082
"void f() {\n"
" int a[1], b[1];\n"
" while (a[0] = g()) {}\n"
" if ((b[0] = g()) == 0) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f(const char *x, char *y);\n" // #4527
"void g(char* b) {\n"
" char a[1000];\n"
" f(a, b);\n"
" printf(\"%s\", a);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: a\n", errout_str());
valueFlowUninit("void usage(const char *);\n" // #10330
"int main(int argc, char* argv[]) {\n"
" int user = 0;\n"
" struct passwd* pwd;\n"
" while (1) {\n"
" int c = getc();\n"
" if (c == -1)\n"
" break;\n"
" switch (c) {\n"
" case 'u': user = 123; break;\n"
" }\n"
" }\n"
" if (argc == 1)\n"
" usage(argv[0]);\n"
" if (user)\n"
" pwd = getpwnam(user);\n"
" if (pwd == NULL) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:15] -> [test.cpp:17]: (warning) Uninitialized variable: pwd\n", errout_str());
valueFlowUninit("size_t Read(unsigned char* buffer, size_t len);\n" // #11540
"void f() {\n"
" const int N = 100;\n"
" uint8_t data[N];\n"
" size_t data_size = 0;\n"
" for (int i = 0; i < 10; i++) {\n"
" if (!data_size)\n"
" data_size = Read(data, N);\n"
" if (!data_size)\n"
" return;\n"
" if (data[0] == 0x47) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #12033
valueFlowUninit("void g(const char*p);\n"
"void f() {\n"
" char buf[10];\n"
" g(buf);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: buf\n", errout_str());
valueFlowUninit("void f() {\n" // #12288
" char buf[100];\n"
" char* p = new (buf) char[100];\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #12355
valueFlowUninit("int f() {\n"
" const int x[10](1, 2);\n"
" if (x[0] == 1) {}\n"
" return x[0];\n"
"}\n");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f(bool* p) {\n" // #12287
" if (p)\n"
" *p = true; \n"
"}\n"
"void g() {\n"
" bool b;\n"
" f(&b);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct S { int x; };\n" // #12394
"int f() {\n"
" struct S s[1];\n"
" s->x = 0;\n"
" return s[0].x;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct S { int* p; };\n" // #12473
"void f() {\n"
" struct S s;\n"
" s.p[0] = 0;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: s.p\n", errout_str());
// #12460
valueFlowUninit("typedef struct {\n"
" int a;\n"
"} st;\n"
"void foo(int* p, bool success) {\n"
" st myst;\n"
" if (success == 1) {\n"
" myst.a = 5;\n"
" }\n"
" if ((success == 1) && (myst.a != 0)) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #12606
valueFlowUninit("void f(int& r) { if (r) {} }\n"
"void g() {\n"
" int i;\n"
" f(i);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:1]: (warning) Uninitialized variable: r\n", errout_str());
// #12197
valueFlowUninit("void f() {\n"
" char a[N];\n"
" for (int i = 0; i < N; i++)\n"
" a[i] = 1;\n"
" const int* p = a;\n"
" for (int i = 0; i < N; i++) {\n"
" if (p[i]) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #12247
valueFlowUninit("void f() {\n"
" char a[10], *p = &a[0];\n"
" p = getenv(\"abc\");\n"
" printf(\"%\", p);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f(char *q) {\n"
" char a[1];\n"
" char *p = a;\n"
" p = q;\n"
" printf(\"%s\", p);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("std::string f() {\n" // #12922
" std::string a[2];\n"
" std::array<std::string, 2> b;\n"
" return a[1] + b.at(1);\n" // don't warn
"}\n"
"struct S { int i; };\n"
"struct T { int i = 0; };\n"
"int g() {\n"
" std::array<int, 2> a;\n"
" std::array<S, 2> b;\n"
" std::array<T, 2> c;\n" // don't warn
" return a.at(1) + b.at(1).i + c.at(1).i;\n"
"}\n"
"int h() {\n"
" std::array<int, 2> a;\n"
" return a[1];\n"
"}\n");
ASSERT_EQUALS("[test.cpp:12]: (error) Uninitialized variable: a\n"
"[test.cpp:12]: (error) Uninitialized variable: b\n"
"[test.cpp:16]: (error) Uninitialized variable: a\n",
errout_str());
valueFlowUninit("void f() {\n" // # 12932
" std::array<int, 0> a;\n"
" if (a.begin() == a.end()) {}\n"
" std::array<int, 1> b;\n"
" auto it = b.begin();\n"
" *it = 0;\n"
" std::array<int, 1> c;\n"
" return c.front();\n"
"}\n");
ASSERT_EQUALS("[test.cpp:8]: (error) Uninitialized variable: c\n", errout_str());
}
void valueFlowUninitBreak() { // Do not show duplicate warnings about the same uninitialized value
valueFlowUninit("struct wcsstruct {\n"
" int *wcsprm;\n"
"};\n"
"\n"
"void copy_wcs(wcsstruct *wcsin) {\n"
" wcsstruct *x;\n"
" memcpy(wcsin, x, sizeof(wcsstruct));\n" // <- warning
" x->wcsprm = NULL;\n" // <- no warning
"}");
ASSERT_EQUALS("[test.cpp:7]: (error) Uninitialized variable: x\n", errout_str());
valueFlowUninit("struct wcsstruct {\n"
" int *wcsprm;\n"
"};\n"
"\n"
"void copy_wcs(wcsstruct *wcsin) {\n"
" wcsstruct *x;\n"
" sizeof(x);\n"
" x->wcsprm = NULL;\n" // <- Warn
"}");
ASSERT_EQUALS("[test.cpp:8]: (error) Uninitialized variable: x\n", errout_str());
valueFlowUninit("struct wcsstruct {\n"
" int *wcsprm;\n"
"};\n"
"\n"
"void init_wcs(wcsstruct *x) { if (x->wcsprm != NULL); }\n" // <- no warning
"\n"
"void copy_wcs() {\n"
" wcsstruct *x;\n"
" x->wcsprm = NULL;\n" // <- warn here
" init_wcs(x);\n" // <- no warning
"}");
ASSERT_EQUALS("[test.cpp:9]: (error) Uninitialized variable: x\n", errout_str());
}
void uninitvar_ipa() {
// #8825
valueFlowUninit("typedef struct {\n"
" int flags;\n"
"} someType_t;\n"
"void bar(const someType_t * const p) {\n"
" if( (p->flags & 0xF000) == 0xF000){}\n"
"}\n"
"void f(void) {\n"
" someType_t gVar;\n"
" bar(&gVar);\n"
"}");
ASSERT_EQUALS("[test.cpp:9]: (error) Uninitialized variable: &gVar\n", errout_str());
valueFlowUninit("typedef struct\n"
"{\n"
" int flags[3];\n"
"} someType_t;\n"
"void f(void) {\n"
" someType_t gVar;\n"
" if(gVar.flags[1] == 42){}\n"
"}");
// TODO : find bugs for member arrays
TODO_ASSERT_EQUALS("[test.cpp:7]: (error) Uninitialized variable: gVar.flags\n", "", errout_str());
valueFlowUninit("void foo() {\n" // #10293
" union {\n"
" struct hdr cm;\n"
" char control[123];\n"
" } u;\n"
" char *x = u.control;\n" // <- no error
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct pc_data {\n"
" struct {\n"
" char * strefa;\n"
" } wampiryzm;\n"
"};\n"
"void f() {\n"
" struct pc_data *pcdata;\n"
" if ( *pcdata->wampiryzm.strefa == '\\0' ) { }\n"
"}");
ASSERT_EQUALS("[test.cpp:8]: (error) Uninitialized variable: pcdata\n", errout_str());
// # 9293
valueFlowUninit("struct S {\n"
" int x;\n"
" int y;\n"
"};\n"
"\n"
"void f() {\n"
" struct S s1;\n"
" int * x = &s1.x;\n"
" struct S s2 = {*x, 0};\n"
"}");
ASSERT_EQUALS("[test.cpp:9]: (error) Uninitialized variable: *x\n", errout_str());
valueFlowUninit("struct S {\n"
" int x;\n"
" int y;\n"
"};\n"
"\n"
"void f() {\n"
" struct S s1;\n"
" struct S s2;\n"
" int * x = &s1.x;\n"
" s2.x = *x;\n"
"}");
ASSERT_EQUALS("[test.cpp:10]: (error) Uninitialized variable: *x\n", errout_str());
valueFlowUninit("void f(bool * x) {\n"
" *x = false;\n"
"}\n"
"void g() {\n"
" bool b;\n"
" f(&b);\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f(bool * x) {\n"
" if (x != nullptr)\n"
" x = 1;\n"
"}\n"
"void g() {\n"
" bool x;\n"
" f(&x);\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f() {\n"
" bool b;\n"
" bool * x = &b;\n"
" if (x != nullptr)\n"
" x = 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct A { bool b; };"
"void f(A * x) {\n"
" x->b = false;\n"
"}\n"
"void g() {\n"
" A b;\n"
" f(&b);\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("std::string f() {\n"
" std::ostringstream ostr;\n"
" ostr << \"\";\n"
" return ostr.str();\n"
"}");
ASSERT_EQUALS("", errout_str());
// #9281
valueFlowUninit("struct s {\n"
" char a[20];\n"
"};\n"
"void c(struct s *sarg) {\n"
" sarg->a[0] = '\\0';\n"
"}\n"
"void b(struct s *sarg) {\n"
" c(sarg);\n"
"}\n"
"void a() {\n"
" struct s s1;\n"
" b(&s1);\n"
"}");
ASSERT_EQUALS("", errout_str());
// # 9290
valueFlowUninit("struct A {\n"
" double x;\n"
"};\n"
"double b() {\n"
" A * c;\n"
" c->x = 42;\n"
" return c->x;\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Uninitialized variable: c\n",
errout_str());
valueFlowUninit("struct A {\n"
" double x;\n"
"};\n"
"double b() {\n"
" A c;\n"
" c.x = 42;\n"
" return c.x;\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct A {\n"
" double x;\n"
"};\n"
"double d(A * e) {\n"
" e->x = 42;\n"
" return e->x;\n"
"}\n"
"double b() {\n"
" A c;\n"
" return d(&c);\n"
"}");
ASSERT_EQUALS("", errout_str());
// # 9302
valueFlowUninit("struct VZ {\n"
" double typ;\n"
"};\n"
"void read() {\n"
" struct VZ vz;\n"
" struct VZ* pvz = &vz;\n"
" vz.typ = 42;\n"
" if (pvz->typ == 0)\n"
" return;\n"
"}");
ASSERT_EQUALS("", errout_str());
// # 9305
valueFlowUninit("struct kf {\n"
" double x;\n"
"};\n"
"void set(kf* k) {\n"
" k->x = 0;\n"
"}\n"
"void cal() {\n"
" KF b;\n"
" KF* pb = &b;\n"
" set( pb);\n"
" if (pb->x)\n"
" return;\n"
"}");
ASSERT_EQUALS("", errout_str());
// # 9348
valueFlowUninit("void f(int *a) {\n"
" int b = 0;\n"
" memcpy(a, &b, sizeof(b));\n"
"}\n"
"void g() {\n"
" int i;\n"
" f(&i);\n"
"}");
ASSERT_EQUALS("", errout_str());
// # 9631
valueFlowUninit("static void g(bool * result, int num, int num2, size_t * buflen) {\n"
" if (*result && *buflen >= 5) {}\n"
"}\n"
"void f() {\n"
" size_t bytesCopied;\n"
" bool copied_all = true;\n"
" g(&copied_all, 5, 6, &bytesCopied);\n"
"}");
ASSERT_EQUALS("[test.cpp:7] -> [test.cpp:2]: (warning) Uninitialized variable: *buflen\n", errout_str());
// # 9953
valueFlowUninit("uint32_t f(uint8_t *mem) {\n"
" uint32_t u32;\n"
" uint8_t *buf = (uint8_t *)(&u32);\n"
" buf[0] = mem[0];\n"
" return(*(uint32_t *)buf);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void valueFlowUninitStructMembers()
{
valueFlowUninit("struct AB { int a; int b; };\n"
"void f(void) {\n"
" struct AB ab;\n"
" ab.a = 1;\n"
" if (ab.b == 2) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: ab.b\n", errout_str());
valueFlowUninit("struct AB { int a; int b; };\n"
"void do_something(const struct AB &ab) { a = ab.a; }\n"
"void f(void) {\n"
" struct AB ab;\n"
" ab.a = 0;\n"
" do_something(ab);\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct AB { int a; int b; };\n"
"void do_something(const struct AB &ab) { a = ab.b; }\n"
"void f(void) {\n"
" struct AB ab;\n"
" ab.a = 0;\n"
" do_something(ab);\n"
"}");
ASSERT_EQUALS("[test.cpp:6] -> [test.cpp:2]: (warning) Uninitialized variable: ab.b\n", errout_str());
valueFlowUninit("struct AB { int a; int b; };\n"
"void f(void) {\n"
" struct AB ab;\n"
" int a = ab.a;\n"
"}\n",
false);
ASSERT_EQUALS("[test.c:4]: (error) Uninitialized variable: ab.a\n", errout_str());
valueFlowUninit("struct AB { int a; int b; };\n"
"void f(void) {\n"
" AB ab1;\n"
" AB ab2 = { ab1.a, 0 };\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: ab1.a\n", errout_str());
valueFlowUninit("struct AB { int a; int b; };\n"
"void f(void) {\n"
" struct AB ab;\n"
" buf[ab.a] = 0;\n"
"}\n",
false);
ASSERT_EQUALS("[test.c:4]: (error) Uninitialized variable: ab.a\n", errout_str());
valueFlowUninit("struct AB { int a; int b; };\n"
"void f(void) {\n"
" struct AB ab;\n"
" ab.a = 1;\n"
" x = ab;\n"
"}\n",
false);
ASSERT_EQUALS("[test.c:5]: (error) Uninitialized variable: ab.b\n", errout_str());
valueFlowUninit("struct AB { int a; int b; };\n"
"void f(void) {\n"
" struct AB ab;\n"
" ab.a = 1;\n"
" x = *(&ab);\n"
"}\n",
false);
ASSERT_EQUALS("[test.c:5]: (error) Uninitialized variable: *(&ab).b\n", errout_str());
valueFlowUninit("void f(void) {\n"
" struct AB ab;\n"
" int x;\n"
" ab.a = (void*)&x;\n"
" dostuff(&ab,0);\n"
"}\n",
false);
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct Element {\n"
" static void f() { }\n"
"};\n"
"void test() {\n"
" Element *element; element->f();\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: element\n", errout_str());
valueFlowUninit("struct Element {\n"
" static void f() { }\n"
"};\n"
"void test() {\n"
" Element *element; (*element).f();\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: element\n", errout_str());
valueFlowUninit("struct Element {\n"
" static int v;\n"
"};\n"
"void test() {\n"
" Element *element; element->v;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: element\n", errout_str());
valueFlowUninit("struct Element {\n"
" static int v;\n"
"};\n"
"void test() {\n"
" Element *element; (*element).v;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: element\n", errout_str());
valueFlowUninit("struct Element {\n"
" void f() { }\n"
"};\n"
"void test() {\n"
" Element *element; element->f();\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: element\n", errout_str());
valueFlowUninit("struct Element {\n"
" void f() { }\n"
"};\n"
"void test() {\n"
" Element *element; (*element).f();\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: element\n", errout_str());
valueFlowUninit("struct Element {\n"
" int v;\n"
"};\n"
"void test() {\n"
" Element *element; element->v;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: element\n", errout_str());
valueFlowUninit("struct Element {\n"
" int v;\n"
"};\n"
"void test() {\n"
" Element *element; (*element).v;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: element\n", errout_str());
valueFlowUninit("struct AB { int a; int b; };\n" // pass struct member by address
"void f(void) {\n"
" struct AB ab;\n"
" assign(&ab.a, 0);\n"
"}\n",
false);
ASSERT_EQUALS("", errout_str());
valueFlowUninit(
"struct Cstring { char *text; int size, alloc; };\n"
"int maybe();\n"
"void f() {\n"
" Cstring res;\n"
" if ( ! maybe() ) return;\n" // <- fp goes away if this is removed
" ( ((res).text = (void*)0), ((res).size = (res).alloc = 0) );\n" // <- fp goes away if parentheses are removed
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct AB { int a; int b; };\n"
"void do_something(const struct AB ab);\n"
"void f(void) {\n"
" struct AB ab;\n"
" ab.a = 0;\n"
" ab.b = 0;\n"
" do_something(ab);\n"
"}\n",
false);
ASSERT_EQUALS("", errout_str());
{
valueFlowUninit("struct AB { char a[10]; };\n"
"void f(void) {\n"
" struct AB ab;\n"
" strcpy(ab.a, STR);\n"
"}\n",
false);
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct AB { unsigned char a[10]; };\n" // #8999 - cast
"void f(void) {\n"
" struct AB ab;\n"
" strcpy((char *)ab.a, STR);\n"
"}\n",
false);
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct AB { char a[10]; };\n"
"void f(void) {\n"
" struct AB ab;\n"
" strcpy(x, ab.a);\n"
"}\n",
false);
TODO_ASSERT_EQUALS("[test.c:4]: (error) Uninitialized variable: ab.a\n", "", errout_str());
valueFlowUninit("struct AB { int a; };\n"
"void f(void) {\n"
" struct AB ab;\n"
" dosomething(ab.a);\n"
"}\n",
false);
ASSERT_EQUALS("", errout_str());
}
valueFlowUninit("struct AB { int a; int b; };\n"
"void do_something(const struct AB ab);\n"
"void f(void) {\n"
" struct AB ab;\n"
" ab = getAB();\n"
" do_something(ab);\n"
"}\n",
false);
ASSERT_EQUALS("", errout_str());
{
// #6769 - calling method that might assign struct members
valueFlowUninit("struct AB { int a; int b; void set(); };\n"
"void f(void) {\n"
" struct AB ab;\n"
" ab.set();\n"
" x = ab;\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct AB { int a; int get() const; };\n"
"void f(void) {\n"
" struct AB ab;\n"
" ab.get();\n"
" x = ab;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: ab\n", errout_str());
valueFlowUninit("struct AB { int a; void dostuff() {} };\n"
"void f(void) {\n"
" struct AB ab;\n"
" ab.dostuff();\n"
" x = ab;\n"
"}");
TODO_ASSERT_EQUALS("error", "", errout_str());
}
valueFlowUninit("struct AB { int a; struct { int b; int c; } s; };\n"
"void do_something(const struct AB ab);\n"
"void f(void) {\n"
" struct AB ab;\n"
" ab.a = 1;\n"
" ab.s.b = 2;\n"
" ab.s.c = 3;\n"
" do_something(ab);\n"
"}\n",
false);
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct conf {\n"
" char x;\n"
"};\n"
"\n"
"void do_something(struct conf ant_conf);\n"
"\n"
"void f(void) {\n"
" struct conf c;\n"
" initdata(&c);\n"
" do_something(c);\n"
"}\n",
false);
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct PIXEL {\n"
" union {\n"
" struct { unsigned char red,green,blue,alpha; };\n"
" unsigned int color;\n"
" };\n"
"};\n"
"\n"
"unsigned char f() {\n"
" struct PIXEL p1;\n"
" p1.color = 255;\n"
" return p1.red;\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct AB { int a; int b; };\n"
"int f() {\n"
" struct AB *ab;\n"
" for (i = 1; i < 10; i++) {\n"
" if (condition && (ab = getab()) != NULL) {\n"
" a = ab->a;\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct AB { int a; int b; };\n"
"int f(int x) {\n"
" struct AB *ab;\n"
" if (x == 0) {\n"
" ab = getab();\n"
" }\n"
" if (x == 0 && (ab != NULL || ab->a == 0)) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct A { int *x; };\n" // declarationId is 0 for "delete"
"void foo(void *info, void*p);\n"
"void bar(void) {\n"
" struct A *delete = 0;\n"
" foo( info, NULL );\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct ABC { int a; int b; int c; };\n"
"void foo(int x, const struct ABC *abc);\n"
"void bar(void) {\n"
" struct ABC abc;\n"
" foo(123, &abc);\n"
" return abc.b;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: &abc\n", errout_str());
valueFlowUninit("struct ABC { int a; int b; int c; };\n"
"void foo() {\n"
" struct ABC abc;\n"
" dostuff((uint32_t *)&abc.a);\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f(void) {\n"
" struct tm t;\n"
" t.tm_year = 123;\n"
"}");
ASSERT_EQUALS("", errout_str());
// return
valueFlowUninit("struct AB { int a; int b; };\n"
"void f(void) {\n"
" struct AB ab;\n"
" ab.a = 0;\n"
" return ab.b;\n"
"}\n",
false);
ASSERT_EQUALS("[test.c:5]: (error) Uninitialized variable: ab.b\n", errout_str());
valueFlowUninit("struct AB { int a; int b; };\n"
"void f(void) {\n"
" struct AB ab;\n"
" ab.a = 0;\n"
" return ab.a;\n"
"}\n",
false);
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct S { int a; int b; };\n" // #8299
"void f(void) {\n"
" struct S s;\n"
" s.a = 0;\n"
" return s;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: s.b\n", errout_str());
valueFlowUninit("struct S { int a; int b; };\n" // #9810
"void f(void) {\n"
" struct S s;\n"
" return s.a ? 1 : 2;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: s.a\n", errout_str());
// checkIfForWhileHead
valueFlowUninit("struct FRED {\n"
" int a;\n"
" int b;\n"
"};\n"
"\n"
"void f(void) {\n"
" struct FRED fred;\n"
" fred.a = do_something();\n"
" if (fred.a == 0) { }\n"
"}\n",
false);
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct FRED {\n"
" int a;\n"
" int b;\n"
"};\n"
"\n"
"void f(void) {\n"
" struct FRED fred;\n"
" fred.a = do_something();\n"
" if (fred.b == 0) { }\n"
"}\n",
false);
ASSERT_EQUALS("[test.c:9]: (error) Uninitialized variable: fred.b\n", errout_str());
valueFlowUninit("struct Fred { int a; };\n"
"void f() {\n"
" struct Fred fred;\n"
" if (fred.a==1) {}\n"
"}",
false);
ASSERT_EQUALS("[test.c:4]: (error) Uninitialized variable: fred.a\n", errout_str());
valueFlowUninit("struct S { int n; int m; };\n"
"void f(void) {\n"
" struct S s;\n"
" for (s.n = 0; s.n <= 10; s.n++) { }\n"
"}",
false);
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void test2() {\n"
" struct { char type; } s_d;\n"
" if (foo(&s_d.type)){}\n"
"}");
ASSERT_EQUALS("", errout_str());
// for
valueFlowUninit("struct AB { int a; };\n"
"void f() {\n"
" struct AB ab;\n"
" while (x) { clear(ab); z = ab.a; }\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct AB { int a; };\n"
"void f() {\n"
" struct AB ab;\n"
" while (x) { ab.a = ab.a + 1; }\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: ab.a\n", errout_str());
valueFlowUninit("struct AB { int a; };\n"
"void f() {\n"
" struct AB ab;\n"
" while (x) { init(&ab); z = ab.a; }\n"
"}");
ASSERT_EQUALS("", errout_str());
// address of member
valueFlowUninit("struct AB { int a[10]; int b; };\n"
"void f() {\n"
" struct AB ab;\n"
" int *p = ab.a;\n"
"}");
ASSERT_EQUALS("", errout_str());
// Reference
valueFlowUninit("struct A { int x; };\n"
"void foo() {\n"
" struct A a;\n"
" int& x = a.x;\n"
" x = 0;\n"
" return a.x;\n"
"}");
ASSERT_EQUALS("", errout_str());
// non static data-member initialization
valueFlowUninit("struct AB { int a=1; int b; };\n"
"void f(void) {\n"
" struct AB ab;\n"
" int a = ab.a;\n"
" int b = ab.b;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: ab.b\n", errout_str());
// STL class member
valueFlowUninit("struct A {\n"
" std::map<int, int> m;\n"
" int i;\n"
"};\n"
"void foo() {\n"
" A a;\n"
" x = a.m;\n"
"}");
ASSERT_EQUALS("", errout_str());
// Unknown type (C++)
valueFlowUninit("struct A {\n"
" C m;\n"
" int i;\n"
"};\n"
"void foo() {\n"
" A a;\n"
" x = a.m;\n"
"}",
true);
ASSERT_EQUALS("", errout_str());
// Unknown type (C)
valueFlowUninit("struct A {\n"
" C m;\n"
" int i;\n"
"};\n"
"void foo() {\n"
" A a;\n"
" x = a.m;\n"
"}",
false);
ASSERT_EQUALS("[test.c:7]: (error) Uninitialized variable: a.m\n", errout_str());
// Type with constructor
valueFlowUninit("class C { C(); }\n"
"struct A {\n"
" C m;\n"
" int i;\n"
"};\n"
"void foo() {\n"
" A a;\n"
" x = a.m;\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct S {\n"
" int t[1];\n"
"};\n"
"int f(const S* ps) {\n"
" return ps->t[0];\n"
"}\n"
"void g() {\n"
" S s;\n"
" s.t[0] = 1;\n"
" f(&s);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct S {\n"
" int t[1];\n"
" int u;\n"
"};\n"
"\n"
"int f(const S* ps) {\n"
" return ps->t[0];\n"
"}\n"
"\n"
"int main(void)\n"
"{\n"
" S s;\n"
" s.t[0] = 1;\n"
" f(&s);\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct X {\n"
" int a, b;\n"
"};\n"
"struct S {\n"
" X t;\n"
"};\n"
"int f(const S* ps) {\n"
" return ps->t.a;\n"
"}\n"
"void g() {\n"
" S s;\n"
" s.t.a = 1;\n"
" f(&s);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("typedef struct { int a; int b; int c; } ABC;\n" // #5777
"void setabc(int x, const ABC* const abc) {\n"
" sum = abc->a + abc->b + abc->c;\n"
"}\n"
"void f(void) {\n"
" ABC abc;\n"
" abc.a = 1;\n"
" setabc(123, &abc);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:8] -> [test.cpp:3]: (warning) Uninitialized variable: abc->b\n", errout_str());
valueFlowUninit("struct S { int* p; };\n" // #10463
"void f(S* in) {\n"
" S* s;\n"
" memcpy(in, s, sizeof(S));\n"
" s->p = NULL;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: s\n", errout_str());
valueFlowUninit("struct S {\n" // #11321
" int a = 0;\n"
" int b;\n"
"};\n"
"void f() {\n"
" S s1;\n"
" s1.b = 1;\n"
" S s2 = s1;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #11460
valueFlowUninit("struct B { int i; };\n"
" struct H {\n"
" void e() const;\n"
" static const B b;\n"
"};\n"
"void f() {\n"
" H h;\n"
" h.e();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #11597
valueFlowUninit("void f(size_t f) {\n"
" struct {\n"
" int i;\n"
" enum { offset = 1062 };\n"
" } s;\n"
" if (f < s.offset + sizeof(s)) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #11776 - function call initialises struct array member
valueFlowUninit("typedef struct {\n"
" int arr[1];\n"
" int count;\n"
"} arr_struct;\n"
"\n"
"void init(int *a, int b);\n"
"\n"
"void foo(arr_struct const *var);\n" // <- inconclusive if var->count is used
"\n"
"void uninitvar_FP7() {\n"
" arr_struct my_st;\n"
" init(my_st.arr, 12);\n" // <- assume that my_st.arr is written
" foo(&my_st);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("typedef struct {\n"
" int arr[1];\n"
" int count;\n"
"} arr_struct;\n"
"\n"
"void init(int *a, int b);\n"
"\n"
"void foo(arr_struct const *var) {\n"
" x = var->arr[0];\n"
"}\n"
"\n"
"void uninitvar_FP7() {\n"
" arr_struct my_st;\n"
" init(my_st.arr, 12);\n" // <- assume that my_st.arr is written
" foo(&my_st);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct S {\n" // #12188
" int i;\n"
" struct T { int j; } t;\n"
"};\n"
"void f() {\n"
" S s;\n"
" ++s.i;\n"
"}\n"
"void g() {\n"
" S s;\n"
" s.i--;\n"
"}\n"
"void h() {\n"
" S s;\n"
" s.i &= 3;\n"
"}\n"
"void k() {\n"
" S s;\n"
" if (++s.i < 3) {}\n"
"}\n"
"void m() {\n"
" S s;\n"
" ++s.t.j;\n"
"}\n"
"void n() {\n"
" S s;\n"
" if (s.t.j-- < 3) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:7]: (error) Uninitialized variable: s.i\n"
"[test.cpp:11]: (error) Uninitialized variable: s.i\n"
"[test.cpp:15]: (error) Uninitialized variable: s.i\n"
"[test.cpp:19]: (error) Uninitialized variable: s.i\n"
"[test.cpp:23]: (error) Uninitialized variable: s.t.j\n"
"[test.cpp:27]: (error) Uninitialized variable: s.t.j\n",
errout_str());
valueFlowUninit("struct S { int x; };\n" // #6933
"void f() {\n"
" int i;\n"
" S s(i);\n"
"}\n"
"void g() {\n"
" int i;\n"
" S t{ i };\n"
"}\n"
"void h() {\n"
" int i;\n"
" std::vector<int> v(i);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: i\n"
"[test.cpp:8]: (error) Uninitialized variable: i\n"
"[test.cpp:12]: (error) Uninitialized variable: i\n",
errout_str());
valueFlowUninit("struct S {\n"
" S(char**);\n"
" int i;\n"
"};\n"
"void f() {\n"
" char* p;\n"
" S s(&p);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct S {\n" // #12354
" int i{};\n"
" void f();\n"
"};\n"
"void f(bool b) {\n"
" S* p;\n"
" if (b)\n"
" p = new S();\n"
" p->f();\n"
"}\n");
ASSERT_EQUALS("[test.cpp:7] -> [test.cpp:9]: (warning) Uninitialized variable: p\n", errout_str());
// #12461
valueFlowUninit("struct stry_type {\n"
" void *out;\n"
"};\n"
"void bar(str_type *items);\n"
"void foo() {\n"
" str_type st_arr[1];\n"
" char arr[5];\n"
" st_arr[0].out = &arr;\n"
" bar(st_arr);\n"
" int len = strlen(arr);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct stry_type {\n"
" void *out;\n"
"};\n"
"void foo() {\n"
" str_type st_arr[1];\n"
" char arr[5];\n"
" st_arr[0].out = &arr;\n"
" int len = strlen(arr);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:8]: (error) Uninitialized variable: arr\n", errout_str());
valueFlowUninit("struct S {\n"
" void *out;\n"
"};\n"
"void bar(S* s);\n"
"void foo() {\n"
" S s[1][1];\n"
" char arr[5];\n"
" s[0][0].out = &arr;\n"
" bar(s[0]);\n"
" int len = strlen(arr);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct S1 { int x; };\n" // #12401
"struct S2 { struct S1 s1; };\n"
"struct S2 f() {\n"
" struct S2 s2;\n"
" struct S1* s1 = &s2.s1;\n"
" s1->x = 0;\n"
" return s2;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct S {\n" // #12685
" explicit S(double v);\n"
" double m;\n"
"};\n"
"void f() {\n"
" double d;\n"
" S s(d);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:7]: (error) Uninitialized variable: d\n", errout_str());
valueFlowUninit("struct S {\n"
" explicit S(double v) : m(v) {}\n"
" double m;\n"
"};\n"
"void f() {\n"
" double d;\n"
" S s{ d };\n"
"}\n");
ASSERT_EQUALS("[test.cpp:7]: (error) Uninitialized variable: d\n", errout_str());
}
void uninitvar_memberfunction() {
// # 8715
valueFlowUninit("struct C {\n"
" int x();\n"
"};\n"
"void f() {\n"
" C *c;\n"
" if (c->x() == 4) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Uninitialized variable: c\n", errout_str());
valueFlowUninit("struct A { \n"
" int i; \n"
" void f();\n"
"};\n"
"void g() {\n"
" A a;\n"
" a.f();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void uninitvar_nonmember() {
valueFlowUninit("struct Foo {\n"
" int bar;\n"
"};\n"
"\n"
"int main() {\n"
" Foo* foo;\n"
" foo->bar = 3;\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (error) Uninitialized variable: foo\n", errout_str());
}
void uninitvarDesignatedInitializers() {
checkUninitVar("struct a { int b; };\n"
"int main() {\n"
" char *b;\n"
" extern int f(struct a *);\n"
" return f(&(struct a){.b = 0});\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("struct a { int b, c; };\n"
"int main() {\n"
" char *c;\n"
" extern int f(struct a *);\n"
" return f(&(struct a){.b = 0, .c = 0});\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void isVariableUsageDeref() {
// *p
checkUninitVar("void f() {\n"
" char a[10];\n"
" char c = *a;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: a\n", errout_str());
// extracttests.start: extern const int SIZE;
checkUninitVar("void f() {\n"
" char a[SIZE+10];\n"
" char c = *a;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: a\n", errout_str());
checkUninitVar("void f() {\n"
" char a[10];\n"
" *a += 10;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: a\n", errout_str());
checkUninitVar("void f() {\n"
" int a[10][10];\n"
" dostuff(*a);\n"
"}");
ASSERT_EQUALS("", errout_str());
checkUninitVar("void f() {\n"
" void (*fp[1]) (void) = {function1};\n"
" (*fp[0])();\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void isVariableUsageDerefValueflow()
{
// *p
valueFlowUninit("void f() {\n"
" char a[10];\n"
" char c = *a;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: *a\n", errout_str());
// extracttests.start: extern const int SIZE;
valueFlowUninit("void f() {\n"
" char a[SIZE+10];\n"
" char c = *a;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: *a\n", errout_str());
valueFlowUninit("void f() {\n"
" char a[10];\n"
" *a += 10;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: *a\n", errout_str());
valueFlowUninit("void f() {\n"
" int a[10][10];\n"
" dostuff(*a);\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f() {\n"
" void (*fp[1]) (void) = {function1};\n"
" (*fp[0])();\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("template <typename T, int value> T Get() {return value;}\n"
"char f() {\n"
" char buf[10];\n"
" for(int i = 0; i < Get<int,10>() ; ++i) \n"
" buf[i] = 0;\n"
" return buf[0];\n"
"}\n");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("static void Foo(double* p) {\n"
" p[0] = 0;\n"
" p[1] = 0;\n"
" p[2] = 0;\n"
" p[3] = 0;\n"
"}\n"
"double f() {\n"
" double L[2][2];\n"
" Foo(*L);\n"
" return L[0][0];\n"
"}\n");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("void f() {\n" // #11305
" type_t a;\n"
" a[0] = 0;\n"
"}\n", false);
ASSERT_EQUALS("", errout_str());
}
void uninitvar_memberaccess() {
valueFlowUninit("struct foo{char *bar;};\n"
"void f(unsigned long long *p) {\n"
" foo a;\n"
" ((&a)->bar) = reinterpret_cast<char*>(*p);\n"
" if ((&a)->bar) ;\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct foo{char *bar;};\n"
"void f(unsigned long long *p) {\n"
" foo a;\n"
" ((&(a))->bar) = reinterpret_cast<char*>(*p);\n"
" if ((&a)->bar) ;\n"
"}");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct A {\n" // #10200
" struct B {\n"
" int i;\n"
" };\n"
" int j;\n"
"};\n"
"void f(std::vector<A::B>& x) {\n"
" A::B b;\n"
" b.i = 123;\n"
" x.push_back(b);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct A {\n"
" struct B {\n"
" int i;\n"
" };\n"
" int j;\n"
"};\n"
"void f(std::vector<A::B>& x) {\n"
" A::B b;\n"
" x.push_back(b);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:9]: (error) Uninitialized variable: b\n", errout_str());
valueFlowUninit("struct A {\n"
" struct B {\n"
" int i;\n"
" };\n"
" int j;\n"
"};\n"
"void f(std::vector<A>&x) {\n"
" A a;\n"
" a.j = 123;\n"
" x.push_back(a);\n"
"}\n");
valueFlowUninit("struct A {\n"
" struct B {\n"
" int i;\n"
" };\n"
" int j;\n"
"};\n"
"void f(std::vector<A>& x) {\n"
" A a;\n"
" x.push_back(a);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:9]: (error) Uninitialized variable: a\n", errout_str());
valueFlowUninit("struct S { struct T { int* p; } t[2]; };\n" // #11018
"void f() {\n"
" S s;\n"
" *&s.t[0].p = 0;\n"
"}\n"
"void g() {\n"
" S s;\n"
" ((*&(*&s.t[0].p))) = 0;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
valueFlowUninit("struct S { int i; };\n" // #6323
"void f() {\n"
" struct S s;\n"
" int x = -3;\n"
" int y = x < (1, s.i);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: s.i\n", errout_str());
valueFlowUninit("struct S { int x; };\n" // #11353
"struct S f() {\n"
" struct S s;\n"
" int* p = &s.x;\n"
" *p = 0;\n"
" return s;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void ctu_(const char* file, int line, const char code[]) {
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
CTU::FileInfo *ctu = CTU::getFileInfo(tokenizer);
// Check code..
std::list<Check::FileInfo*> fileInfo;
Check& c = getCheck<CheckUninitVar>();
fileInfo.push_back(c.getFileInfo(tokenizer, settings));
c.analyseWholeProgram(ctu, fileInfo, settings, *this); // TODO: check result
while (!fileInfo.empty()) {
delete fileInfo.back();
fileInfo.pop_back();
}
delete ctu;
}
void ctuTest() {
ctu("void f(int *p) {\n"
" a = *p;\n"
"}\n"
"int main() {\n"
" int x;\n"
" f(&x);\n"
"}");
ASSERT_EQUALS("[test.cpp:6] -> [test.cpp:2]: (error) Using argument p that points at uninitialized variable x\n", errout_str());
ctu("void use(int *p) { a = *p + 3; }\n"
"void call(int x, int *p) { x++; use(p); }\n"
"int main() {\n"
" int x;\n"
" call(4,&x);\n"
"}");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:2] -> [test.cpp:1]: (error) Using argument p that points at uninitialized variable x\n", errout_str());
ctu("void dostuff(int *x, int *y) {\n"
" if (!var)\n"
" return -1;\n" // <- early return
" *x = *y;\n"
"}\n"
"\n"
"void f() {\n"
" int x;\n"
" dostuff(a, &x);\n"
"}");
ASSERT_EQUALS("", errout_str());
ctu("void dostuff(int *x, int *y) {\n"
" if (cond)\n"
" *y = -1;\n" // <- conditionally written
" *x = *y;\n"
"}\n"
"\n"
"void f() {\n"
" int x;\n"
" dostuff(a, &x);\n"
"}");
ASSERT_EQUALS("", errout_str());
ctu("void f(int *p) {\n"
" a = sizeof(*p);\n"
"}\n"
"int main() {\n"
" int x;\n"
" f(&x);\n"
"}");
ASSERT_EQUALS("", errout_str());
ctu("void f(int *v) {\n"
" std::cin >> *v;\n"
"}\n"
"int main() {\n"
" int x;\n"
" f(&x);\n"
"}");
ASSERT_EQUALS("", errout_str());
ctu("void increment(int& i) { ++i; }\n" // #6475
"int f() {\n"
" int n;\n"
" increment(n);\n"
" return n;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:1]: (error) Using argument i that points at uninitialized variable n\n", errout_str());
ctu("void increment(int* i) { ++(*i); }\n"
"int f() {\n"
" int n;\n"
" increment(&n);\n"
" return n;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:1]: (error) Using argument i that points at uninitialized variable n\n", errout_str());
ctu("typedef struct { int type; int id; } Stem;\n"
"void lookupStem(recodeCtx h, Stem *stem) {\n"
" i = stem->type & STEM_VERT;\n"
"}\n"
"void foo() {\n"
" Stem stem;\n"
" stem.type = 0;\n"
" lookupStem(h, &stem);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
ctu("void increment(int& i) { ++i; }\n" // #6475
"int f() {\n"
" int n;\n"
" increment(n);\n"
" return n;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:1]: (error) Using argument i that points at uninitialized variable n\n", errout_str());
}
};
REGISTER_TEST(TestUninitVar)
| null |
950 | cpp | cppcheck | options.h | test/options.h | null | // Cppcheck - A tool for static C/C++ code analysis
// Copyright (C) 2007-2024 Cppcheck team.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#ifndef OPTIONS_H
#define OPTIONS_H
#include <set>
#include <string>
/**
* @brief Class to parse command-line parameters for ./testrunner .
* Has getters for available switches and parameters.
* See test/testoptions.cpp for sample usage.
*/
class options {
public:
/** Call from main() to populate object */
options(int argc, const char* const argv[]);
/** Don't print the name of each method being tested. */
bool quiet() const;
/** Print help. */
bool help() const;
/** Print summary. */
bool summary() const;
/** Perform dry run. */
bool dry_run() const;
/** Which test should be run. Empty string means 'all tests' */
const std::set<std::string>& which_test() const;
const std::string& exe() const;
options() = delete;
options(const options&) = delete;
options& operator =(const options&) = delete;
private:
std::set<std::string> mWhichTests;
const bool mQuiet;
const bool mHelp;
const bool mSummary;
const bool mDryRun;
std::string mExe;
};
#endif
| null |
951 | cpp | cppcheck | teststl.cpp | test/teststl.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "checkstl.h"
#include "errortypes.h"
#include "fixture.h"
#include "helpers.h"
#include "settings.h"
#include "standards.h"
#include "utils.h"
#include <cstddef>
#include <string>
class TestStl : public TestFixture {
public:
TestStl() : TestFixture("TestStl") {}
private:
/*const*/ Settings settings = settingsBuilder().severity(Severity::warning).severity(Severity::style).severity(Severity::performance).library("std.cfg").build();
void run() override {
TEST_CASE(outOfBounds);
TEST_CASE(outOfBoundsSymbolic);
TEST_CASE(outOfBoundsIndexExpression);
TEST_CASE(outOfBoundsIterator);
TEST_CASE(iterator1);
TEST_CASE(iterator2);
TEST_CASE(iterator3);
TEST_CASE(iterator4);
TEST_CASE(iterator5);
TEST_CASE(iterator6);
TEST_CASE(iterator7);
TEST_CASE(iterator8);
TEST_CASE(iterator9);
TEST_CASE(iterator10);
TEST_CASE(iterator11);
TEST_CASE(iterator12);
TEST_CASE(iterator13);
TEST_CASE(iterator14); // #8191
TEST_CASE(iterator15); // #8341
TEST_CASE(iterator16);
TEST_CASE(iterator17);
TEST_CASE(iterator18);
TEST_CASE(iterator19);
TEST_CASE(iterator20);
TEST_CASE(iterator21);
TEST_CASE(iterator22);
TEST_CASE(iterator23);
TEST_CASE(iterator24);
TEST_CASE(iterator25); // #9742
TEST_CASE(iterator26); // #9176
TEST_CASE(iterator27); // #10378
TEST_CASE(iterator28); // #10450
TEST_CASE(iterator29);
TEST_CASE(iterator30);
TEST_CASE(iterator31);
TEST_CASE(iteratorExpression);
TEST_CASE(iteratorSameExpression);
TEST_CASE(mismatchingContainerIterator);
TEST_CASE(eraseIteratorOutOfBounds);
TEST_CASE(dereference);
TEST_CASE(dereference_break); // #3644 - handle "break"
TEST_CASE(dereference_member);
TEST_CASE(STLSize);
TEST_CASE(STLSizeNoErr);
TEST_CASE(negativeIndex);
TEST_CASE(negativeIndexMultiline);
TEST_CASE(erase1);
TEST_CASE(erase2);
TEST_CASE(erase3);
TEST_CASE(erase4);
TEST_CASE(erase5);
TEST_CASE(erase6);
TEST_CASE(eraseBreak);
TEST_CASE(eraseContinue);
TEST_CASE(eraseReturn1);
TEST_CASE(eraseReturn2);
TEST_CASE(eraseReturn3);
TEST_CASE(eraseGoto);
TEST_CASE(eraseAssign1);
TEST_CASE(eraseAssign2);
TEST_CASE(eraseAssign3);
TEST_CASE(eraseAssign4);
TEST_CASE(eraseAssignByFunctionCall);
TEST_CASE(eraseErase);
TEST_CASE(eraseByValue);
TEST_CASE(eraseIf);
TEST_CASE(eraseOnVector);
TEST_CASE(pushback1);
TEST_CASE(pushback2);
TEST_CASE(pushback3);
TEST_CASE(pushback4);
TEST_CASE(pushback5);
TEST_CASE(pushback6);
TEST_CASE(pushback7);
TEST_CASE(pushback8);
TEST_CASE(pushback9);
TEST_CASE(pushback10);
TEST_CASE(pushback11);
TEST_CASE(pushback12);
TEST_CASE(pushback13);
TEST_CASE(insert1);
TEST_CASE(insert2);
TEST_CASE(popback1);
TEST_CASE(stlBoundaries1);
TEST_CASE(stlBoundaries2);
TEST_CASE(stlBoundaries3);
TEST_CASE(stlBoundaries4); // #4364
TEST_CASE(stlBoundaries5); // #4352
TEST_CASE(stlBoundaries6); // #7106
// if (str.find("ab"))
TEST_CASE(if_find);
TEST_CASE(if_str_find);
TEST_CASE(size1);
TEST_CASE(size2);
TEST_CASE(size3);
TEST_CASE(size4); // #2652 - don't warn about vector/deque
// Redundant conditions..
// if (ints.find(123) != ints.end()) ints.remove(123);
TEST_CASE(redundantCondition1);
// missing inner comparison when incrementing iterator inside loop
TEST_CASE(missingInnerComparison1);
TEST_CASE(missingInnerComparison2); // no FP when there is comparison
TEST_CASE(missingInnerComparison3); // no FP when there is iterator shadowing
TEST_CASE(missingInnerComparison4); // no FP when "break;" is used
TEST_CASE(missingInnerComparison5); // Ticket #2154 - FP
TEST_CASE(missingInnerComparison6); // #2643 - 'it=foo.insert(++it,0);'
// catch common problems when using the string::c_str() function
TEST_CASE(cstr);
TEST_CASE(uselessCalls);
TEST_CASE(stabilityOfChecks); // #4684 cppcheck crash in template function call
TEST_CASE(dereferenceInvalidIterator);
TEST_CASE(dereferenceInvalidIterator2); // #6572
TEST_CASE(dereference_auto);
TEST_CASE(loopAlgoElementAssign);
TEST_CASE(loopAlgoAccumulateAssign);
TEST_CASE(loopAlgoContainerInsert);
TEST_CASE(loopAlgoIncrement);
TEST_CASE(loopAlgoConditional);
TEST_CASE(loopAlgoMinMax);
TEST_CASE(loopAlgoMultipleReturn);
TEST_CASE(invalidContainer);
TEST_CASE(invalidContainerLoop);
TEST_CASE(findInsert);
TEST_CASE(checkKnownEmptyContainer);
TEST_CASE(checkMutexes);
}
#define check(...) check_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
void check_(const char* file, int line, const char (&code)[size], const bool inconclusive = false, const Standards::cppstd_t cppstandard = Standards::CPPLatest) {
const Settings settings1 = settingsBuilder(settings).certainty(Certainty::inconclusive, inconclusive).cpp(cppstandard).build();
// Tokenize..
SimpleTokenizer tokenizer(settings1, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
runChecks<CheckStl>(tokenizer, this);
}
// TODO: get rid of this
void check_(const char* file, int line, const std::string& code) {
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
runChecks<CheckStl>(tokenizer, this);
}
#define checkNormal(code) checkNormal_(code, __FILE__, __LINE__)
template<size_t size>
void checkNormal_(const char (&code)[size], const char* file, int line) {
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
// Check..
runChecks<CheckStl>(tokenizer, this);
}
void outOfBounds() {
setMultiline();
checkNormal("bool f(const int a, const int b)\n" // #8648
"{\n"
" std::cout << a << b;\n"
" return true;\n"
"}\n"
"void f(const std::vector<int> &v)\n"
"{\n"
" if(v.size() >=2 &&\n"
" bar(v[2], v[3]) )\n" // v[3] is accessed
" {;}\n"
"}\n");
ASSERT_EQUALS("test.cpp:9:warning:Either the condition 'v.size()>=2' is redundant or size of 'v' can be 2. Expression 'v[2]' causes access out of bounds.\n"
"test.cpp:8:note:condition 'v.size()>=2'\n"
"test.cpp:9:note:Access out of bounds\n"
"test.cpp:9:warning:Either the condition 'v.size()>=2' is redundant or size of 'v' can be 2. Expression 'v[3]' causes access out of bounds.\n"
"test.cpp:8:note:condition 'v.size()>=2'\n"
"test.cpp:9:note:Access out of bounds\n", errout_str());
checkNormal("void f() {\n"
" std::string s;\n"
" s[10] = 1;\n"
"}");
ASSERT_EQUALS("test.cpp:3:error:Out of bounds access in expression 's[10]' because 's' is empty.\n", errout_str());
checkNormal("void f() {\n"
" std::string s = \"abcd\";\n"
" s[10] = 1;\n"
"}");
ASSERT_EQUALS("test.cpp:3:error:Out of bounds access in 's[10]', if 's' size is 4 and '10' is 10\n", errout_str());
checkNormal("void f(std::vector<int> v) {\n"
" v.front();\n"
" if (v.empty()) {}\n"
"}");
ASSERT_EQUALS("test.cpp:2:warning:Either the condition 'v.empty()' is redundant or expression 'v.front()' causes access out of bounds.\n"
"test.cpp:3:note:condition 'v.empty()'\n"
"test.cpp:2:note:Access out of bounds\n", errout_str());
checkNormal("void f(std::vector<int> v) {\n"
" if (v.size() == 3) {}\n"
" v[16] = 0;\n"
"}");
ASSERT_EQUALS("test.cpp:3:warning:Either the condition 'v.size()==3' is redundant or size of 'v' can be 3. Expression 'v[16]' causes access out of bounds.\n"
"test.cpp:2:note:condition 'v.size()==3'\n"
"test.cpp:3:note:Access out of bounds\n", errout_str());
checkNormal("void f(std::vector<int> v) {\n"
" int i = 16;\n"
" if (v.size() == 3) {\n"
" v[i] = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("test.cpp:4:warning:Either the condition 'v.size()==3' is redundant or size of 'v' can be 3. Expression 'v[i]' causes access out of bounds.\n"
"test.cpp:3:note:condition 'v.size()==3'\n"
"test.cpp:4:note:Access out of bounds\n", errout_str());
checkNormal("void f(std::vector<int> v, int i) {\n"
" if (v.size() == 3 || i == 16) {}\n"
" v[i] = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkNormal("void f(std::map<int,int> x) {\n"
" if (x.empty()) { x[1] = 2; }\n"
"}");
ASSERT_EQUALS("", errout_str());
checkNormal("void f(std::string s) {\n"
" if (s.size() == 1) {\n"
" s[2] = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("test.cpp:3:warning:Either the condition 's.size()==1' is redundant or size of 's' can be 1. Expression 's[2]' causes access out of bounds.\n"
"test.cpp:2:note:condition 's.size()==1'\n"
"test.cpp:3:note:Access out of bounds\n", errout_str());
// Do not crash
checkNormal("void a() {\n"
" std::string b[];\n"
" for (auto c : b)\n"
" c.data();\n"
"}");
ASSERT_EQUALS("", errout_str());
checkNormal("std::string f(std::string x) {\n"
" if (x.empty()) return {};\n"
" x[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
checkNormal("std::string f(std::string x) {\n"
" if (x.empty()) return std::string{};\n"
" x[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
checkNormal("void f() {\n"
" std::string s;\n"
" x = s.begin() + 1;\n"
"}");
ASSERT_EQUALS(
"test.cpp:3:error:Out of bounds access in expression 's.begin()+1' because 's' is empty.\n"
"test.cpp:3:error:Out of bounds access in expression 's.begin()+1' because 's' is empty.\n", // duplicate
errout_str());
checkNormal("void f(int x) {\n"
" std::string s;\n"
" auto it = s.begin() + x;\n"
"}");
ASSERT_EQUALS("test.cpp:3:error:Out of bounds access in expression 's.begin()+x' because 's' is empty and 'x' may be non-zero.\n", errout_str());
checkNormal("char fstr1(){const std::string s = \"<a><b>\"; return s[42]; }\n"
"wchar_t fwstr1(){const std::wstring s = L\"<a><b>\"; return s[42]; }");
ASSERT_EQUALS("test.cpp:1:error:Out of bounds access in 's[42]', if 's' size is 6 and '42' is 42\n"
"test.cpp:2:error:Out of bounds access in 's[42]', if 's' size is 6 and '42' is 42\n", errout_str());
checkNormal("char fstr1(){const std::string s = \"<a><b>\"; return s[1]; }\n"
"wchar_t fwstr1(){const std::wstring s = L\"<a><b>\"; return s[1]; }");
ASSERT_EQUALS("", errout_str());
checkNormal("int f() {\n"
" std::vector<int> v;\n"
" std::vector<int> * pv = &v;\n"
" return (*pv)[42];\n"
"}");
ASSERT_EQUALS("test.cpp:4:error:Out of bounds access in expression '(*pv)[42]' because '*pv' is empty.\n", errout_str());
checkNormal("void f() {\n"
" std::string s;\n"
" ++abc[s];\n"
"}");
ASSERT_EQUALS("", errout_str());
// # 9274
checkNormal("char f(bool b) {\n"
" const std::string s = \"<a><b>\";\n"
" int x = 6;\n"
" if(b) ++x;\n"
" return s[x];\n"
"}");
ASSERT_EQUALS("test.cpp:5:error:Out of bounds access in 's[x]', if 's' size is 6 and 'x' is 6\n", errout_str());
checkNormal("void f() {\n"
" static const int N = 4;\n"
" std::array<int, N> x;\n"
" x[0] = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkNormal("void f(bool b) {\n"
" std::vector<int> x;\n"
" if (b)\n"
" x.push_back(1);\n"
" if (x.size() < 2)\n"
" return;\n"
" x[0] = 2;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkNormal("void f(bool b) {\n"
" std::vector<int> v;\n"
" if(v.at(b?42:0)) {}\n"
"}\n");
ASSERT_EQUALS(
"test.cpp:3:error:Out of bounds access in expression 'v.at(b?42:0)' because 'v' is empty.\n",
errout_str());
checkNormal("void f(std::vector<int> v, bool b){\n"
" if (v.size() == 1)\n"
" if(v.at(b?42:0)) {}\n"
"}\n");
ASSERT_EQUALS(
"test.cpp:3:warning:Either the condition 'v.size()==1' is redundant or size of 'v' can be 1. Expression 'v.at(b?42:0)' causes access out of bounds.\n"
"test.cpp:2:note:condition 'v.size()==1'\n"
"test.cpp:3:note:Access out of bounds\n",
errout_str());
check("struct T {\n"
" std::vector<int>* v;\n"
"};\n"
"struct S {\n"
" T t;\n"
"};\n"
"long g(S& s);\n"
"int f() {\n"
" std::vector<int> ArrS;\n"
" S s = { { &ArrS } };\n"
" g(s);\n"
" return ArrS[0];\n"
"}\n", true);
ASSERT_EQUALS("", errout_str());
check("struct T {\n"
" std::vector<int>* v;\n"
"};\n"
"struct S {\n"
" std::vector<T> t;\n"
"};\n"
"long g(S& s);\n"
"int f() {\n"
" std::vector<int> ArrS;\n"
" S s = { { { &ArrS } } };\n"
" g(s);\n"
" return ArrS[0];\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("struct T {\n"
" std::vector<int>* v;\n"
"};\n"
"struct S {\n"
" std::vector<std::vector<T>> t;\n"
"};\n"
"long g(S& s);\n"
"int f() {\n"
" std::vector<int> ArrS;\n"
" S s = { { { { &ArrS } } } };\n"
" g(s);\n"
" return ArrS[0];\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("struct T {\n"
" std::vector<int>* v;\n"
"};\n"
"struct S {\n"
" T t;\n"
"};\n"
"long g(S& s);\n"
"int f() {\n"
" std::vector<int> ArrS;\n"
" S s { { &ArrS } };\n"
" g(s);\n"
" return ArrS[0];\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("struct T {\n"
" std::vector<int>* v;\n"
"};\n"
"struct S {\n"
" std::vector<T> t;\n"
"};\n"
"long g(S& s);\n"
"int f() {\n"
" std::vector<int> ArrS;\n"
" S s { { { &ArrS } } };\n"
" g(s);\n"
" return ArrS[0];\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("struct T {\n"
" std::vector<int>* v;\n"
"};\n"
"struct S {\n"
" std::vector<std::vector<T>> t;\n"
"};\n"
"long g(S& s);\n"
"int f() {\n"
" std::vector<int> ArrS;\n"
" S s { { { { &ArrS } } } };\n"
" g(s);\n"
" return ArrS[0];\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
checkNormal("extern void Bar(const double, const double);\n"
"void f(std::vector<double> &r, const double ) {\n"
" std::vector<double> result;\n"
" double d = 0.0;\n"
" const double inc = 0.1;\n"
" for(unsigned int i = 0; i < 10; ++i) {\n"
" result.push_back(d);\n"
" d = (i + 1) * inc;\n"
" }\n"
" Bar(1.0, d);\n"
" Bar(10U, result.size());\n"
" Bar(0.0, result[0]);\n"
" Bar(0.34, result[1]);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkNormal("void f(size_t entries) {\n"
" std::vector<uint8_t> v;\n"
" if (v.size() < entries + 2)\n"
" v.resize(entries + 2);\n"
" v[0] = 1;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkNormal("void f(size_t entries) {\n"
" std::vector<uint8_t> v;\n"
" if (v.size() < entries)\n"
" v.resize(entries);\n"
" v[0] = 1;\n"
"}\n");
ASSERT_EQUALS("test.cpp:5:error:Out of bounds access in expression 'v[0]' because 'v' is empty.\n", errout_str());
checkNormal("void f(size_t entries) {\n"
" if (entries < 2) return;\n"
" std::vector<uint8_t> v;\n"
" if (v.size() < entries)\n"
" v.resize(entries);\n"
" v[0] = 1;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkNormal("void f(size_t entries) {\n"
" if (entries == 0) return;\n"
" std::vector<uint8_t> v;\n"
" if (v.size() < entries)\n"
" v.resize(entries);\n"
" v[0] = 1;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkNormal("void foo(std::vector<int>* PArr, int n) {\n"
" std::vector<int> Arr;\n"
" if (!PArr)\n"
" PArr = &Arr;\n"
" PArr->resize(n);\n"
" for (int i = 0; i < n; ++i)\n"
" (*PArr)[i] = 1;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkNormal("int f() {\n"
" std::vector<int> v;\n"
" std::vector<int> * pv = &v;\n"
" return (*pv).at(42);\n"
"}\n");
ASSERT_EQUALS("test.cpp:4:error:Out of bounds access in expression '(*pv).at(42)' because '*pv' is empty.\n",
errout_str());
checkNormal("std::string f(const char* DirName) {\n"
" if (DirName == nullptr)\n"
" return {};\n"
" std::string Name{ DirName };\n"
" if (!Name.empty() && Name.back() != '\\\\')\n"
" Name += '\\\\';\n"
" return Name;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkNormal("bool f(bool b) {\n"
" std::vector<int> v;\n"
" if (b)\n"
" v.push_back(0);\n"
" for(auto i:v)\n"
" if (v[i] > 0)\n"
" return true;\n"
" return false;\n"
"}\n");
ASSERT_EQUALS("test.cpp:5:style:Consider using std::any_of algorithm instead of a raw loop.\n", errout_str());
checkNormal("std::vector<int> range(int n);\n"
"bool f(bool b) {\n"
" std::vector<int> v;\n"
" if (b)\n"
" v.push_back(1);\n"
" assert(range(v.size()).size() == v.size());\n"
" for(auto i:range(v.size()))\n"
" if (v[i] > 0)\n"
" return true;\n"
" return false;\n"
"}\n");
ASSERT_EQUALS("test.cpp:7:style:Consider using std::any_of algorithm instead of a raw loop.\n", errout_str());
checkNormal("bool g();\n"
"int f(int x) {\n"
" std::vector<int> v;\n"
" if (g())\n"
" v.emplace_back(x);\n"
" const auto n = (int)v.size();\n"
" for (int i = 0; i < n; ++i)\n"
" if (v[i] > 0)\n"
" return i;\n"
" return 0;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkNormal("bool g();\n"
"int f(int x) {\n"
" std::vector<int> v;\n"
" if (g())\n"
" v.emplace_back(x);\n"
" const auto n = static_cast<int>(v.size());\n"
" for (int i = 0; i < n; ++i)\n"
" if (v[i] > 0)\n"
" return i;\n"
" return 0;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkNormal("bool g();\n"
"void f(int x) {\n"
" std::vector<int> v;\n"
" if (g())\n"
" v.emplace_back(x);\n"
" const int n = v.size();\n"
" h(n);\n"
" for (int i = 0; i < n; ++i)\n"
" h(v[i]);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkNormal("void foo(const std::vector<int> &v) {\n"
" if(v.size() >=1 && v[0] == 4 && v[1] == 2){}\n"
"}\n");
ASSERT_EQUALS("test.cpp:2:warning:Either the condition 'v.size()>=1' is redundant or size of 'v' can be 1. Expression 'v[1]' causes access out of bounds.\n"
"test.cpp:2:note:condition 'v.size()>=1'\n"
"test.cpp:2:note:Access out of bounds\n", errout_str());
checkNormal("int f(int x, int y) {\n"
" std::vector<int> a = {0,1,2};\n"
" if(x<2)\n"
" y = a[x] + 1;\n"
" else\n"
" y = a[x];\n"
" return y;\n"
"}\n");
ASSERT_EQUALS(
"test.cpp:6:warning:Either the condition 'x<2' is redundant or 'x' can have the value greater or equal to 3. Expression 'a[x]' causes access out of bounds.\n"
"test.cpp:3:note:condition 'x<2'\n"
"test.cpp:6:note:Access out of bounds\n",
errout_str());
checkNormal("int f(std::vector<int> v) {\n"
" if (v.size() > 3)\n"
" return v[v.size() - 3];\n"
" return 0;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkNormal("void f(std::vector<int> v) {\n"
" v[v.size() - 1];\n"
" if (v.size() == 1) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkNormal("void f(int n) {\n"
" std::vector<int> v = {1, 2, 3, 4};\n"
" const int i = qMin(n, v.size());\n"
" if (i > 1)\n"
" v[i] = 1;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkNormal("void f(std::vector<int>& v, int i) {\n"
" if (i > -1) {\n"
" v.erase(v.begin() + i);\n"
" if (v.empty()) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkNormal("void g(const char *, ...) { exit(1); }\n" // #10025
"void f(const char c[]) {\n"
" std::vector<int> v = get();\n"
" if (v.empty())\n"
" g(\"\", c[0]);\n"
" return h(&v[0], v.size()); \n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkNormal("void f(int i, std::vector<int> v) {\n" // #9157
" if (i <= (int)v.size()) {\n"
" if (v[i]) {}\n"
" }\n"
" if (i <= static_cast<int>(v.size())) {\n"
" if (v[i]) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("test.cpp:3:warning:Either the condition 'i<=(int)v.size()' is redundant or 'i' can have the value v.size(). Expression 'v[i]' causes access out of bounds.\n"
"test.cpp:2:note:condition 'i<=(int)v.size()'\n"
"test.cpp:3:note:Access out of bounds\n"
"test.cpp:6:warning:Either the condition 'i<=static_cast<int>(v.size())' is redundant or 'i' can have the value v.size(). Expression 'v[i]' causes access out of bounds.\n"
"test.cpp:5:note:condition 'i<=static_cast<int>(v.size())'\n"
"test.cpp:6:note:Access out of bounds\n",
errout_str());
check("template<class Iterator>\n"
"void b(Iterator d) {\n"
" std::string c = \"a\";\n"
" d + c.length();\n"
"}\n"
"void f() {\n"
" std::string buf;\n"
" b(buf.begin());\n"
"}\n",
true);
ASSERT_EQUALS("test.cpp:4:error:Out of bounds access in expression 'd+c.length()' because 'buf' is empty.\n",
errout_str());
check("template<class Iterator>\n"
"void b(Iterator d) {\n"
" std::string c = \"a\";\n"
" sort(d, d + c.length());\n"
"}\n"
"void f() {\n"
" std::string buf;\n"
" b(buf.begin());\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("int f(const std::vector<int> &v) {\n"
" return !v.empty() ? 42 : v.back();\n"
"}\n",
true);
ASSERT_EQUALS(
"test.cpp:2:warning:Either the condition 'v.empty()' is redundant or expression 'v.back()' causes access out of bounds.\n"
"test.cpp:2:note:condition 'v.empty()'\n"
"test.cpp:2:note:Access out of bounds\n",
errout_str());
check("std::vector<int> g() {\n" // #10779
" std::vector<int> v(10);\n"
" for(int i = 0; i <= 10; ++i)\n"
" v[i] = 42;\n"
" return v;\n"
"}\n");
ASSERT_EQUALS("test.cpp:4:error:Out of bounds access in 'v[i]', if 'v' size is 10 and 'i' is 10\n",
errout_str());
check("void f() {\n"
" int s = 2;\n"
" std::vector <int> v(s);\n"
" v[100] = 1;\n"
"}\n");
ASSERT_EQUALS("test.cpp:4:error:Out of bounds access in 'v[100]', if 'v' size is 2 and '100' is 100\n",
errout_str());
check("void f() {\n"
" std::vector <int> v({ 1, 2, 3 });\n"
" v[100] = 1;\n"
"}\n");
ASSERT_EQUALS("test.cpp:3:error:Out of bounds access in 'v[100]', if 'v' size is 3 and '100' is 100\n",
errout_str());
check("void f() {\n"
" char c[] = { 1, 2, 3 };\n"
" std::vector<char> v(c, sizeof(c) + c);\n"
" v[100] = 1;\n"
"}\n");
ASSERT_EQUALS("test.cpp:4:error:Out of bounds access in 'v[100]', if 'v' size is 3 and '100' is 100\n",
errout_str());
check("void f() {\n"
" char c[] = { 1, 2, 3 };\n"
" std::vector<char> v{ c, c + sizeof(c) };\n"
" v[100] = 1;\n"
"}\n");
ASSERT_EQUALS("test.cpp:4:error:Out of bounds access in 'v[100]', if 'v' size is 3 and '100' is 100\n",
errout_str());
check("void f() {\n"
" int i[] = { 1, 2, 3 };\n"
" std::vector<int> v(i, i + sizeof(i) / 4);\n"
" v[100] = 1;\n"
"}\n");
ASSERT_EQUALS("test.cpp:4:error:Out of bounds access in 'v[100]', if 'v' size is 3 and '100' is 100\n",
errout_str());
check("void f() {\n" // #6615
" int i[] = { 1, 2, 3 };\n"
" std::vector<int> v(i, i + sizeof(i) / sizeof(int));\n"
" v[100] = 1;\n"
"}\n");
TODO_ASSERT_EQUALS("test.cpp:4:error:Out of bounds access in 'v[100]', if 'v' size is 3 and '100' is 100\n",
"",
errout_str());
check("void f() {\n"
" std::array<int, 10> a = {};\n"
" a[10];\n"
" constexpr std::array<int, 10> b = {};\n"
" b[10];\n"
" const std::array<int, 10> c = {};\n"
" c[10];\n"
" static constexpr std::array<int, 10> d = {};\n"
" d[10];\n"
"}\n");
ASSERT_EQUALS("test.cpp:3:error:Out of bounds access in 'a[10]', if 'a' size is 10 and '10' is 10\n"
"test.cpp:5:error:Out of bounds access in 'b[10]', if 'b' size is 10 and '10' is 10\n"
"test.cpp:7:error:Out of bounds access in 'c[10]', if 'c' size is 10 and '10' is 10\n"
"test.cpp:9:error:Out of bounds access in 'd[10]', if 'd' size is 10 and '10' is 10\n",
errout_str());
check("struct test_fixed {\n"
" std::array<int, 10> array = {};\n"
" void index(int i) { array[i]; }\n"
"};\n"
"void f() {\n"
" test_fixed x = test_fixed();\n"
" x.index(10);\n"
"}\n");
ASSERT_EQUALS("test.cpp:3:error:Out of bounds access in 'array[i]', if 'array' size is 10 and 'i' is 10\n",
errout_str());
check("struct test_constexpr {\n"
" static constexpr std::array<int, 10> array = {};\n"
" void index(int i) { array[i]; }\n"
"};\n"
"void f() {\n"
" test_constexpr x = test_constexpr();\n"
" x.index(10);\n"
"}\n");
ASSERT_EQUALS("test.cpp:3:error:Out of bounds access in 'array[i]', if 'array' size is 10 and 'i' is 10\n",
errout_str());
checkNormal("struct A {\n"
" const std::vector<int>& v;\n"
" A(const std::vector<int>& x) : v(x)\n"
" {}\n"
" int f() const {\n"
" return v[0];\n"
" }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkNormal("struct A {\n"
" static const std::vector<int> v;\n"
" int f() const {\n"
" return v[0];\n"
" }\n"
"};\n"
"const std::vector<int> A::v = {1, 2};\n");
ASSERT_EQUALS("", errout_str());
checkNormal("struct a {\n"
" std::vector<int> g() const;\n"
"};\n"
"int f(const a& b) {\n"
" auto c = b.g();\n"
" assert(not c.empty());\n"
" int d = c.front();\n"
" return d;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkNormal("std::string f() {\n"
" std::map<int, std::string> m = { { 1, \"1\" } };\n"
" return m.at(1);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkNormal("struct A {\n"
" virtual void init_v(std::vector<int> *v) = 0;\n"
"};\n"
"A* create_a();\n"
"struct B {\n"
" B() : a(create_a()) {}\n"
" void init_v(std::vector<int> *v) {\n"
" a->init_v(v);\n"
" }\n"
" A* a;\n"
"};\n"
"void f() {\n"
" B b;\n"
" std::vector<int> v;\n"
" b.init_v(&v);\n"
" v[0];\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkNormal("void f(std::vector<int>* v) {\n"
" if (v->empty())\n"
" v->push_back(1);\n"
" auto x = v->back();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkNormal("template <typename T, uint8_t count>\n"
"struct Foo {\n"
" std::array<T, count> items = {0};\n"
" T maxCount = count;\n"
" explicit Foo(const T& maxValue = (std::numeric_limits<T>::max)()) : maxCount(maxValue) {}\n"
" bool Set(const uint8_t idx) {\n"
" if (CheckBounds(idx) && items[idx] < maxCount) {\n"
" items[idx] += 1;\n"
" return true;\n"
" }\n"
" return false;\n"
" }\n"
" static bool CheckBounds(const uint8_t idx) { return idx < count; }\n"
"};\n"
"void f() {\n"
" Foo<uint8_t, 42U> x;\n"
" if (x.Set(42U)) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkNormal("struct S { void g(std::span<int>& r) const; };\n" // #11828
"int f(const S& s) {\n"
" std::span<int> t;\n"
" s.g(t);\n"
" return t[0];\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkNormal("char h() {\n"
" std::string s;\n"
" std::string_view sv(s);\n"
" return s[2];\n"
"}\n");
ASSERT_EQUALS("test.cpp:4:error:Out of bounds access in expression 's[2]' because 's' is empty.\n", errout_str());
checkNormal("void f() {\n" // #12738
" std::vector<double> v{ 0, 0.1 };\n"
" (void)v[0];\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void outOfBoundsSymbolic()
{
check("void foo(std::string textline, int col) {\n"
" if(col > textline.size())\n"
" return false;\n"
" int x = textline[col];\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:2] -> [test.cpp:4]: (warning) Either the condition 'col>textline.size()' is redundant or 'col' can have the value textline.size(). Expression 'textline[col]' causes access out of bounds.\n",
errout_str());
}
void outOfBoundsIndexExpression() {
setMultiline();
checkNormal("void f(std::string s) {\n"
" s[s.size()] = 1;\n"
"}");
ASSERT_EQUALS("test.cpp:2:error:Out of bounds access of s, index 's.size()' is out of bounds.\n", errout_str());
checkNormal("void f(std::string s) {\n"
" s[s.size()+1] = 1;\n"
"}");
ASSERT_EQUALS("test.cpp:2:error:Out of bounds access of s, index 's.size()+1' is out of bounds.\n", errout_str());
checkNormal("void f(std::string s) {\n"
" s[1+s.size()] = 1;\n"
"}");
ASSERT_EQUALS("test.cpp:2:error:Out of bounds access of s, index '1+s.size()' is out of bounds.\n", errout_str());
checkNormal("void f(std::string s) {\n"
" s[x*s.size()] = 1;\n"
"}");
ASSERT_EQUALS("test.cpp:2:error:Out of bounds access of s, index 'x*s.size()' is out of bounds.\n", errout_str());
checkNormal("bool f(std::string_view& sv) {\n" // #10031
" return sv[sv.size()] == '\\0';\n"
"}\n");
ASSERT_EQUALS("test.cpp:2:error:Out of bounds access of sv, index 'sv.size()' is out of bounds.\n", errout_str());
}
void outOfBoundsIterator() {
check("int f() {\n"
" std::vector<int> v;\n"
" auto it = v.begin();\n"
" return *it;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (error) Out of bounds access in expression 'it' because 'v' is empty.\n",
errout_str());
check("int f() {\n"
" std::vector<int> v;\n"
" v.push_back(0);\n"
" auto it = v.begin() + 1;\n"
" return *it;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5]: (error) Out of bounds access in 'it', if 'v' size is 1 and 'it' is at position 1 from the beginning\n",
errout_str());
check("int f() {\n"
" std::vector<int> v;\n"
" v.push_back(0);\n"
" auto it = v.end() - 1;\n"
" return *it;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("int f() {\n"
" std::vector<int> v;\n"
" v.push_back(0);\n"
" auto it = v.end() - 2;\n"
" return *it;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5]: (error) Out of bounds access in 'it', if 'v' size is 1 and 'it' is at position 2 from the end\n",
errout_str());
check("void g(int);\n"
"void f(std::vector<int> x) {\n"
" std::map<int, int> m;\n"
" if (!m.empty()) {\n"
" g(m.begin()->second);\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" std::vector<int> vec;\n"
" std::vector<int>::iterator it = vec.begin();\n"
" *it = 1;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (error) Out of bounds access in expression 'it' because 'vec' is empty.\n",
errout_str());
check("void f() {\n"
" std::vector<int> vec;\n"
" auto it = vec.begin();\n"
" *it = 1;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (error) Out of bounds access in expression 'it' because 'vec' is empty.\n",
errout_str());
}
void iterator1() {
check("void f()\n"
"{\n"
" std::list<int> l1;\n"
" std::list<int> l2;\n"
" for (std::list<int>::iterator it = l1.begin(); it != l2.end(); ++it)\n"
" { }\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Iterators of different containers 'l1' and 'l2' are used together.\n",
errout_str());
check("void f()\n"
"{\n"
" std::list<int> l1;\n"
" std::list<int> l2;\n"
" for (std::list<int>::iterator it = l1.begin(); l2.end() != it; ++it)\n"
" { }\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Iterators of different containers 'l2' and 'l1' are used together.\n",
errout_str());
check("struct C { std::list<int> l1; void func(); };\n"
"void C::func() {\n"
" std::list<int>::iterator it;\n"
" for (it = l1.begin(); it != l1.end(); ++it) { }\n"
" C c;\n"
" for (it = c.l1.begin(); it != c.l1.end(); ++it) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
// Same check with reverse iterator
check("void f()\n"
"{\n"
" std::list<int> l1;\n"
" std::list<int> l2;\n"
" for (std::list<int>::const_reverse_iterator it = l1.rbegin(); it != l2.rend(); ++it)\n"
" { }\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Iterators of different containers 'l1' and 'l2' are used together.\n",
errout_str());
}
void iterator2() {
check("void foo()\n"
"{\n"
" std::list<int> l1;\n"
" std::list<int> l2;\n"
" std::list<int>::iterator it = l1.begin();\n"
" while (it != l2.end())\n"
" {\n"
" ++it;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Iterators of different containers 'l1' and 'l2' are used together.\n",
errout_str());
check("void foo()\n"
"{\n"
" std::list<int> l1;\n"
" std::list<int> l2;\n"
" std::list<int>::iterator it = l1.begin();\n"
" while (l2.end() != it)\n"
" {\n"
" ++it;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Iterators of different containers 'l2' and 'l1' are used together.\n",
errout_str());
}
void iterator3() {
check("void foo()\n"
"{\n"
" std::list<int> l1;\n"
" std::list<int> l2;\n"
" std::list<int>::iterator it = l1.begin();\n"
" l2.insert(it, 0);\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Same iterator is used with different containers 'l1' and 'l2'.\n"
"[test.cpp:6]: (error) Iterator 'it' referring to container 'l1' is used with container 'l2'.\n",
errout_str());
check("void foo() {\n" // #5803
" std::list<int> l1;\n"
" std::list<int> l2;\n"
" std::list<int>::iterator it = l1.begin();\n"
" l2.insert(it, l1.end());\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo() {\n" // #7658
" std::list<int> l1;\n"
" std::list<int> l2;\n"
" std::list<int>::iterator it = l1.begin();\n"
" std::list<int>::iterator end = l1.end();\n"
" l2.insert(it, end);\n"
"}");
ASSERT_EQUALS("", errout_str());
// only warn for insert when there are preciself 2 arguments.
check("void foo() {\n"
" std::list<int> l1;\n"
" std::list<int> l2;\n"
" std::list<int>::iterator it = l1.begin();\n"
" l2.insert(it);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" std::list<int> l1;\n"
" std::list<int> l2;\n"
" std::list<int>::iterator it = l1.begin();\n"
" l2.insert(it,0,1);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void iterator4() {
check("void foo(std::vector<std::string> &test)\n"
"{\n"
" std::set<int> result;\n"
" for (std::vector<std::string>::const_iterator cit = test.begin();\n"
" cit != test.end();\n"
" ++cit)\n"
" {\n"
" result.insert(cit->size());\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void iterator5() {
check("void foo(std::vector<int> ints1, std::vector<int> ints2)\n"
"{\n"
" std::vector<int>::iterator it = std::find(ints1.begin(), ints2.end(), 22);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Iterators of different containers 'ints1' and 'ints2' are used together.\n",
errout_str());
}
void iterator6() {
// Ticket #1357
check("void foo(const std::set<int> &ints1)\n"
"{\n"
" std::set<int> ints2;\n"
" std::set<int>::iterator it1 = ints1.begin();\n"
" std::set<int>::iterator it2 = ints1.end();\n"
" ints2.insert(it1, it2);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(const std::set<int> &ints1)\n"
"{\n"
" std::set<int> ints2;\n"
" std::set<int>::iterator it1 = ints1.begin();\n"
" std::set<int>::iterator it2 = ints2.end();\n"
" ints2.insert(it1, it2);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:6]: (error) Iterators of different containers are used together.\n", "", errout_str());
}
void iterator7() {
check("void foo(std::vector<int> ints1, std::vector<int> ints2)\n"
"{\n"
" std::vector<int>::iterator it = std::inplace_merge(ints1.begin(), std::advance(ints1.rbegin(), 5), ints2.end());\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Iterators of different containers 'ints1' and 'ints2' are used together.\n",
errout_str());
check("void foo(std::vector<int> ints1, std::vector<int> ints2)\n"
"{\n"
" std::vector<int>::iterator it = std::inplace_merge(ints1.begin(), std::advance(ints2.rbegin(), 5), ints1.end());\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void iterator8() {
check("void foo(std::vector<int> ints1, std::vector<int> ints2)\n"
"{\n"
" std::vector<int>::iterator it = std::find_first_of(ints1.begin(), ints2.end(), ints1.begin(), ints1.end());\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Iterators of different containers 'ints1' and 'ints2' are used together.\n",
errout_str());
check("void foo(std::vector<int> ints1, std::vector<int> ints2)\n"
"{\n"
" std::vector<int>::iterator it = std::find_first_of(ints1.begin(), ints1.end(), ints2.begin(), ints1.end());\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Iterators of different containers 'ints2' and 'ints1' are used together.\n",
errout_str());
check("void foo(std::vector<int> ints1, std::vector<int> ints2)\n"
"{\n"
" std::vector<int>::iterator it = std::find_first_of(foo.bar.begin(), foo.bar.end()-6, ints2.begin(), ints1.end());\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Iterators of different containers 'ints2' and 'ints1' are used together.\n",
errout_str());
check("void foo(std::vector<int> ints1, std::vector<int> ints2)\n"
"{\n"
" std::vector<int>::iterator it = std::find_first_of(ints1.begin(), ints1.end(), ints2.begin(), ints2.end());\n"
"}");
ASSERT_EQUALS("", errout_str());
// #6839
check("void f(const std::wstring& a, const std::wstring& b) {\n"
" const std::string tp1 = std::string(a.begin(), b.end());\n"
" const std::wstring tp2 = std::string(b.begin(), a.end());\n"
" const std::u16string tp3(a.begin(), b.end());\n"
" const std::u32string tp4(b.begin(), a.end());\n"
" const std::string fp1 = std::string(a.begin(), a.end());\n"
" const std::string tp2(a.begin(), a.end());\n"
"}");
ASSERT_EQUALS( // TODO "[test.cpp:2]: (error) Iterators of different containers are used together.\n"
// TODO "[test.cpp:3]: (error) Iterators of different containers are used together.\n"
"[test.cpp:4]: (error) Iterators of different containers 'tp3' and 'a' are used together.\n"
"[test.cpp:5]: (error) Iterators of different containers 'tp4' and 'b' are used together.\n",
errout_str());
}
void iterator9() {
// Ticket #1600
check("void foo(std::vector<int> &r)\n"
"{\n"
" std::vector<int>::iterator aI = r.begin();\n"
" while(aI != r.end())\n"
" {\n"
" if (*aI == 0)\n"
" {\n"
" r.insert(aI, 42);\n"
" return;\n"
" }\n"
" ++aI;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// Ticket #2481
check("void foo(std::vector<int> &r)\n"
"{\n"
" std::vector<int>::iterator aI = r.begin();\n"
" while(aI != r.end())\n"
" {\n"
" if (*aI == 0)\n"
" {\n"
" r.insert(aI, 42);\n"
" break;\n"
" }\n"
" ++aI;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// Execution path checking..
check("void foo(std::vector<int> &r, int c)\n"
"{\n"
" std::vector<int>::iterator aI = r.begin();\n"
" while(aI != r.end())\n"
" {\n"
" if (*aI == 0)\n"
" {\n"
" r.insert(aI, 42);\n"
" if (c)\n"
" {\n"
" return;\n"
" }\n"
" }\n"
" ++aI;\n"
" }\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:14] (error) After insert(), the iterator 'aI' may be invalid.", "", errout_str());
}
void iterator10() {
// Ticket #1679
check("void foo()\n"
"{\n"
" std::set<int> s1;\n"
" std::set<int> s2;\n"
" for (std::set<int>::iterator it = s1.begin(); it != s1.end(); ++it)\n"
" {\n"
" if (true) { }\n"
" if (it != s2.end()) continue;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Iterators of different containers 's1' and 's2' are used together.\n",
errout_str());
}
void iterator11() {
// Ticket #3433
check("int main() {\n"
" map<int, int> myMap;\n"
" vector<string> myVector;\n"
" for(vector<int>::iterator x = myVector.begin(); x != myVector.end(); x++)\n"
" myMap.erase(*x);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void iterator12() {
// Ticket #3201
check("void f() {\n"
" std::map<int, int> map1;\n"
" std::map<int, int> map2;\n"
" std::map<int, int>::const_iterator it = map1.find(123);\n"
" if (it == map2.end()) { }"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Iterators of different containers 'map1' and 'map2' are used together.\n",
errout_str());
check("void f() {\n"
" std::map<int, int> map1;\n"
" std::map<int, int> map2;\n"
" std::map<int, int>::const_iterator it = map1.find(123);\n"
" if (map2.end() == it) { }"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Iterators of different containers 'map2' and 'map1' are used together.\n",
errout_str());
check("void f(std::string &s) {\n"
" int pos = s.find(x);\n"
" s.erase(pos);\n"
" s.erase(pos);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void iterator13() {
check("void f() {\n"
" std::vector<int> a;\n"
" std::vector<int> t;\n"
" std::vector<int>::const_iterator it;\n"
" it = a.begin();\n"
" while (it!=a.end())\n"
" ++it;\n"
" it = t.begin();\n"
" while (it!=a.end())\n"
" ++it;\n"
"}");
ASSERT_EQUALS("[test.cpp:8]: (error) Iterators of different containers 't' and 'a' are used together.\n",
errout_str());
// #4062
check("void f() {\n"
" std::vector<int> a;\n"
" std::vector<int> t;\n"
" std::vector<int>::const_iterator it;\n"
" it = a.begin();\n"
" while (it!=a.end())\n"
" v++it;\n"
" it = t.begin();\n"
" while (it!=t.end())\n"
" ++it;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" std::vector<int> a;\n"
" std::vector<int> t;\n"
" std::vector<int>::const_iterator it;\n"
" if(z)\n"
" it = a.begin();\n"
" else\n"
" it = t.begin();\n"
" while (z && it!=a.end())\n"
" v++it;\n"
" while (!z && it!=t.end())\n"
" v++it;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void iterator14() {
check("void f() {\n"
" std::map<int,Foo> x;\n"
" std::map<int,Foo>::const_iterator it;\n"
" for (it = x.find(0)->second.begin(); it != x.find(0)->second.end(); ++it) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void iterator15() {
check("void f(C1* x, std::list<int> a) {\n"
" std::list<int>::iterator pos = a.begin();\n"
" for(pos = x[0]->plist.begin(); pos != x[0]->plist.end(); ++pos) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void iterator16() {
check("void foo()\n"
"{\n"
" std::list<int> l1;\n"
" std::list<int> l2;\n"
" std::list<int>::iterator it1 = l1.begin();\n"
" std::list<int>::iterator it2 = l2.end();\n"
" while (it1 != it2)\n"
" {\n"
" ++it1;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Iterators of different containers 'l1' and 'l2' are used together.\n",
errout_str());
check("void foo()\n"
"{\n"
" std::list<int> l1;\n"
" std::list<int> l2;\n"
" std::list<int>::iterator it1 = l1.end();\n"
" std::list<int>::iterator it2 = l2.begin();\n"
" while (it2 != it1)\n"
" {\n"
" ++it2;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Iterators of different containers 'l2' and 'l1' are used together.\n",
errout_str());
check("void foo()\n"
"{\n"
" std::list<int> l1;\n"
" std::list<int> l2;\n"
" std::list<int>::iterator it2 = l2.end();\n"
" std::list<int>::iterator it1 = l1.begin();\n"
" while (it1 != it2)\n"
" {\n"
" ++it1;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Iterators of different containers 'l1' and 'l2' are used together.\n",
errout_str());
check("void foo()\n"
"{\n"
" std::set<int> l1;\n"
" std::set<int> l2(10, 4);\n"
" std::set<int>::iterator it1 = l1.begin();\n"
" std::set<int>::iterator it2 = l2.find(4);\n"
" while (it1 != it2)\n"
" {\n"
" ++it1;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Iterators of different containers 'l1' and 'l2' are used together.\n",
errout_str());
}
void iterator17() {
check("void foo()\n"
"{\n"
" std::list<int> l1;\n"
" std::list<int> l2;\n"
" std::list<int>::iterator it1 = l1.begin();\n"
" std::list<int>::iterator it2 = l1.end();\n"
" { it2 = l2.end(); }\n"
" while (it1 != it2)\n"
" {\n"
" ++it1;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Iterators of different containers 'l1' and 'l2' are used together.\n",
errout_str());
check("void foo()\n"
"{\n"
" std::list<int> l1;\n"
" std::list<int> l2;\n"
" std::list<int>::iterator it1 = l1.begin();\n"
" std::list<int>::iterator it2 = l1.end();\n"
" while (it1 != it2)\n"
" {\n"
" ++it1;\n"
" }\n"
" it2 = l2.end();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo()\n"
"{\n"
" std::list<int> l1;\n"
" std::list<int> l2;\n"
" std::list<int>::iterator it1 = l1.begin();\n"
" std::list<int>::iterator it2 = l1.end();\n"
" it1 = l2.end();\n"
" it1 = l1.end();\n"
" if (it1 != it2)\n"
" {\n"
" ++it1;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo()\n"
"{\n"
" std::list<int> l1;\n"
" std::list<int> l2;\n"
" std::list<int>::iterator it1 = l1.begin();\n"
" std::list<int>::iterator it2 = l1.end();\n"
" { it2 = l2.end(); }\n"
" it2 = l1.end();\n"
" { it2 = l2.end(); }\n"
" while (it1 != it2)\n"
" {\n"
" ++it1;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Iterators of different containers 'l1' and 'l2' are used together.\n",
errout_str());
}
void iterator18() {
check("void foo(std::list<int> l1, std::list<int> l2)\n"
"{\n"
" std::list<int>::iterator it1 = l1.begin();\n"
" std::list<int>::iterator it2 = l1.end();\n"
" while (++it1 != --it2)\n"
" {\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(std::list<int> l1, std::list<int> l2)\n"
"{\n"
" std::list<int>::iterator it1 = l1.begin();\n"
" std::list<int>::iterator it2 = l1.end();\n"
" while (it1++ != --it2)\n"
" {\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(std::list<int> l1, std::list<int> l2)\n"
"{\n"
" std::list<int>::iterator it1 = l1.begin();\n"
" std::list<int>::iterator it2 = l1.end();\n"
" if (--it2 > it1++)\n"
" {\n"
" }\n"
"}");
TODO_ASSERT_EQUALS("", "[test.cpp:5]: (error) Dangerous comparison using operator< on iterator.\n", errout_str());
}
void iterator19() {
check("void foo()\n"
"{\n"
" std::list<int> l1;\n"
" std::list<int>::iterator it1 = l1.begin();\n"
" {\n"
" std::list<int> l1;\n"
" if (it1 != l1.end())\n"
" {\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS(
"[test.cpp:7] -> [test.cpp:4]: (error) Same iterator is used with containers 'l1' that are temporaries or defined in different scopes.\n",
errout_str());
check("void foo()\n"
"{\n"
" std::list<int> l1;\n"
" std::list<int>::iterator it1 = l1.begin();\n"
" {\n"
" std::list<int> l1;\n"
" if (l1.end() > it1)\n"
" {\n"
" }\n"
" }\n"
"}");
TODO_ASSERT_EQUALS(
"[test.cpp:7] -> [test.cpp:4]: (error) Same iterator is used with containers 'l1' that are defined in different scopes.\n",
"[test.cpp:7] -> [test.cpp:7]: (error) Same iterator is used with containers 'l1' that are temporaries or defined in different scopes.\n[test.cpp:7]: (error) Dangerous comparison using operator< on iterator.\n",
errout_str());
check("void foo()\n"
"{\n"
" std::list<int> l1;\n"
" std::list<int>::iterator it1 = l1.begin();\n"
" {\n"
" std::list<int> l1;\n"
" std::list<int>::iterator it2 = l1.begin();\n"
" if (it1 != it2)\n"
" {\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS(
"[test.cpp:8] -> [test.cpp:4]: (error) Same iterator is used with containers 'l1' that are temporaries or defined in different scopes.\n",
errout_str());
check("void foo()\n"
"{\n"
" std::list<int> l1;\n"
" std::list<int>::iterator it1 = l1.begin();\n"
" {\n"
" std::list<int> l1;\n"
" std::list<int>::iterator it2 = l1.begin();\n"
" if (it2 != it1)\n"
" {\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS(
"[test.cpp:8] -> [test.cpp:7]: (error) Same iterator is used with containers 'l1' that are temporaries or defined in different scopes.\n",
errout_str());
check("std::set<int> g() {\n"
" static const std::set<int> s = {1};\n"
" return s;\n"
"}\n"
"void f() {\n"
" if (g().find(2) == g().end()) {}\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:6] -> [test.cpp:6]: (error) Same iterator is used with containers 'g()' that are temporaries or defined in different scopes.\n",
errout_str());
check("std::set<long> f() {\n" // #5804
" std::set<long> s;\n"
" return s;\n"
"}\n"
"void g() {\n"
" for (std::set<long>::iterator it = f().begin(); it != f().end(); ++it) {}\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:6] -> [test.cpp:6]: (error) Same iterator is used with containers 'f()' that are temporaries or defined in different scopes.\n",
errout_str());
}
void iterator20() {
check("void foo()\n"
"{\n"
" std::list<int> l1;\n"
" std::list<int> l2;\n"
" std::list<int>::iterator it1 = l1.begin();\n"
" std::list<int>::iterator it2 = l2.begin();\n"
" it1 = it2;\n"
" while (it1 != l1.end())\n"
" {\n"
" ++it1;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Iterators of different containers 'l2' and 'l1' are used together.\n",
errout_str());
check("std::list<int> l3;\n"
"std::list<int>::iterator bar()\n"
"{\n"
" return l3.end();\n"
"}\n"
"void foo()\n"
"{\n"
" std::list<int> l1;\n"
" std::list<int> l2;\n"
" std::list<int>::iterator it1 = l1.begin();\n"
" std::list<int>::iterator it2 = l2.begin();\n"
" it1 = bar();\n"
" while (it1 != it2)\n"
" {\n"
" ++it1;\n"
" }\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:13] -> [test.cpp:10] -> [test.cpp:11]: (error) Comparison of iterators from containers 'l1' and 'l2'.\n", "", errout_str());
}
void iterator21() {
check("void foo()\n"
"{\n"
" std::list<int> l1;\n"
" std::list<int> l2;\n"
" std::list<int>::iterator it1 = l1.end();\n"
" std::list<int>::iterator it2 = l2.begin();\n"
" if (it1 != it2)\n"
" {\n"
" }\n"
" if (it2 != it1)\n"
" {\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Iterators of different containers 'l1' and 'l2' are used together.\n"
"[test.cpp:6]: (error) Iterators of different containers 'l2' and 'l1' are used together.\n",
errout_str());
check("void foo()\n"
"{\n"
" std::list<int> l1;\n"
" std::list<int> l2;\n"
" std::list<int>::iterator it1 = l1.end();\n"
" std::list<int>::iterator it2 = l2.begin();\n"
" if (it1 != it2 && it1 != it2)\n"
" {\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Iterators of different containers 'l1' and 'l2' are used together.\n"
"[test.cpp:5]: (error) Iterators of different containers 'l1' and 'l2' are used together.\n", // duplicate
errout_str());
}
void iterator22() { // #7107
check("void foo() {\n"
" std::list<int> &l = x.l;\n"
" std::list<int>::iterator it = l.find(123);\n"
" x.l.erase(it);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void iterator23() { // #9550
check("struct A {\n"
" struct B {\n"
" bool operator==(const A::B& b) const;\n"
" int x;\n"
" int y;\n"
" int z;\n"
" };\n"
"};\n"
"bool A::B::operator==(const A::B& b) const {\n"
" return std::tie(x, y, z) == std::tie(b.x, b.y, b.z);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void iterator24() {
// #9556
check("void f(int a, int b) {\n"
" if (&a == &b) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int a, int b) {\n"
" if (std::for_each(&a, &b + 1, [](auto) {})) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Iterators of different containers 'a' and 'b' are used together.\n",
errout_str());
check("void f(int a, int b) {\n"
" if (std::for_each(&a, &b, [](auto) {})) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Iterators of different containers 'a' and 'b' are used together.\n",
errout_str());
check("void f(int a) {\n"
" if (std::for_each(&a, &a, [](auto) {})) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Same iterators expression are used for algorithm.\n", errout_str());
check("void f(int a) {\n"
" if (std::for_each(&a, &a + 1, [](auto) {})) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void iterator25() {
// #9742
check("struct S {\n"
" std::vector<int>& v;\n"
"};\n"
"struct T {\n"
" bool operator()(const S& lhs, const S& rhs) const {\n"
" return &lhs.v != &rhs.v;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void iterator26() { // #9176
check(
"#include <map>\n"
"int main()\n"
"{"
" std::map<char const*, int> m{ {\"a\", 1} };\n"
" if (auto iter = m.find(\"x\"); iter != m.end()) {\n"
" return iter->second;\n"
" }\n"
" return 0;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void iterator27() {
// #10378
check("struct A {\n"
" int a;\n"
" int b;\n"
"};\n"
"int f(std::map<int, A> m) {\n"
" auto it = m.find( 1 );\n"
" const int a( it == m.cend() ? 0 : it->second.a );\n"
" const int b( it == m.cend() ? 0 : it->second.b );\n"
" return a + b;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void iterator28()
{
// #10450
check("struct S {\n"
" struct Private {\n"
" std::list<int> l;\n"
" };\n"
" std::unique_ptr<Private> p;\n"
" int foo();\n"
"};\n"
"int S::foo() {\n"
" for(auto iter = p->l.begin(); iter != p->l.end(); ++iter) {\n"
" if(*iter == 1) {\n"
" p->l.erase(iter);\n"
" return 1;\n"
" }\n"
" }\n"
" return 0;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:10]: (style) Consider using std::find_if algorithm instead of a raw loop.\n", errout_str());
}
void iterator29()
{
// #11511
check("std::vector<int>& g();\n"
"void f() {\n"
" auto v = g();\n"
" auto it = g().begin();\n"
" while (it != g().end())\n"
" it = v.erase(it);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:6]: (error) Iterator 'it' referring to container 'g()' is used with container 'v'.\n", errout_str());
check("std::vector<int>& g(int);\n"
"void f(int i, int j) {\n"
" auto& r = g(i);\n"
" auto it = g(j).begin();\n"
" while (it != g(j).end())\n"
" it = r.erase(it);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:6]: (error) Iterator 'it' referring to container 'g(j)' is used with container 'r'.\n", errout_str());
check("std::vector<int>& g();\n"
"void f() {\n"
" auto& r = g();\n"
" auto it = g().begin();\n"
" while (it != g().end())\n"
" it = r.erase(it);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void iterator30()
{
check("struct S {\n" // #12641
" bool b;\n"
" std::list<int> A, B;\n"
" void f();\n"
"};\n"
"void S::f() {\n"
" std::list<int>::iterator i = (b ? B : A).begin();\n"
" while (i != (b ? B : A).end()) {\n"
" ++i;\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void iterator31()
{
check("struct S {\n" // #13327
" std::string a;\n"
"};\n"
"struct T {\n"
" S s;\n"
"};\n"
"bool f(const S& s) {\n"
" std::string b;\n"
" return s.a.c_str() == b.c_str();\n"
"}\n"
"bool g(const T& t) {\n"
" std::string b;\n"
" return t.s.a.c_str() == b.c_str();\n"
"}\n");
ASSERT_EQUALS("[test.cpp:9]: (error) Iterators of different containers 's.a' and 'b' are used together.\n"
"[test.cpp:13]: (error) Iterators of different containers 't.s.a' and 'b' are used together.\n",
errout_str());
}
void iteratorExpression() {
check("std::vector<int>& f();\n"
"std::vector<int>& g();\n"
"void foo() {\n"
" (void)std::find(f().begin(), g().end(), 0);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Iterators of different containers 'f()' and 'g()' are used together.\n",
errout_str());
check("std::vector<int>& f();\n"
"std::vector<int>& g();\n"
"void foo() {\n"
" if(f().begin() == g().end()) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Iterators of different containers 'f()' and 'g()' are used together.\n",
errout_str());
check("std::vector<int>& f();\n"
"std::vector<int>& g();\n"
"void foo() {\n"
" auto size = f().end() - g().begin();\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Iterators of different containers 'f()' and 'g()' are used together.\n",
errout_str());
check("struct A {\n"
" std::vector<int>& f();\n"
" std::vector<int>& g();\n"
"};\n"
"void foo() {\n"
" (void)std::find(A().f().begin(), A().g().end(), 0);\n"
"}");
ASSERT_EQUALS(
"[test.cpp:6]: (error) Iterators of different containers 'A().f()' and 'A().g()' are used together.\n",
errout_str());
check("struct A {\n"
" std::vector<int>& f();\n"
" std::vector<int>& g();\n"
"};\n"
"void foo() {\n"
" (void)std::find(A{} .f().begin(), A{} .g().end(), 0);\n"
"}");
ASSERT_EQUALS(
"[test.cpp:6]: (error) Iterators of different containers 'A{}.f()' and 'A{}.g()' are used together.\n",
errout_str());
check("std::vector<int>& f();\n"
"std::vector<int>& g();\n"
"void foo() {\n"
" (void)std::find(begin(f()), end(g()), 0);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (warning) Iterators to containers from different expressions 'f()' and 'g()' are used together.\n", errout_str());
check("struct A {\n"
" std::vector<int>& f();\n"
" std::vector<int>& g();\n"
"};\n"
"void foo() {\n"
" (void)std::find(A().f().begin(), A().f().end(), 0);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("std::vector<int>& f();\n"
"std::vector<int>& g();\n"
"void foo() {\n"
" if(bar(f().begin()) == g().end()) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("std::vector<int>& f();\n"
"void foo() {\n"
" auto it = f().end() - 1;\n"
" f().begin() - it;\n"
" f().begin()+1 - it;\n"
" f().begin() - (it + 1);\n"
" f().begin() - f().end();\n"
" f().begin()+1 - f().end();\n"
" f().begin() - (f().end() + 1);\n"
" (void)std::find(f().begin(), it, 0);\n"
" (void)std::find(f().begin(), it + 1, 0);\n"
" (void)std::find(f().begin() + 1, it + 1, 0);\n"
" (void)std::find(f().begin() + 1, it, 0);\n"
" (void)std::find(f().begin(), f().end(), 0);\n"
" (void)std::find(f().begin() + 1, f().end(), 0);\n"
" (void)std::find(f().begin(), f().end() - 1, 0);\n"
" (void)std::find(f().begin() + 1, f().end() - 1, 0);\n"
" (void)std::find(begin(f()), end(f()));\n"
" (void)std::find(begin(f()) + 1, end(f()), 0);\n"
" (void)std::find(begin(f()), end(f()) - 1, 0);\n"
" (void)std::find(begin(f()) + 1, end(f()) - 1, 0);\n"
"}");
ASSERT_EQUALS("[test.cpp:9]: (error) Dereference of an invalid iterator: f().end()+1\n", errout_str());
check("std::vector<int>& f();\n"
"void foo() {\n"
" if(f().begin() == f().end()) {}\n"
" if(f().begin() == f().end()+1) {}\n"
" if(f().begin()+1 == f().end()) {}\n"
" if(f().begin()+1 == f().end()+1) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Dereference of an invalid iterator: f().end()+1\n"
"[test.cpp:6]: (error) Dereference of an invalid iterator: f().end()+1\n",
errout_str());
check("std::vector<int>& f();\n"
"void foo() {\n"
" if(std::begin(f()) == std::end(f())) {}\n"
" if(std::begin(f()) == std::end(f())+1) {}\n"
" if(std::begin(f())+1 == std::end(f())) {}\n"
" if(std::begin(f())+1 == std::end(f())+1) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Dereference of an invalid iterator: std::end(f())+1\n"
"[test.cpp:6]: (error) Dereference of an invalid iterator: std::end(f())+1\n",
errout_str());
check("template<int N>\n"
"std::vector<int>& f();\n"
"void foo() {\n"
" if(f<1>().begin() == f<1>().end()) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" if (a.begin().x == b.begin().x) {}\n"
" if (begin(a).x == begin(b).x) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(std::list<int*> a, std::list<int*> b) {\n"
" if (*a.begin() == *b.begin()) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" if(f().begin(1) == f().end()) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(const uint8_t* data, const uint32_t dataLength) {\n"
" const uint32_t minimumLength = sizeof(uint16_t) + sizeof(uint16_t);\n"
" if (dataLength >= minimumLength) {\n"
" char* payload = new char[dataLength - minimumLength];\n"
" std::copy(&data[minimumLength], &data[dataLength], payload);\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("bool f(const std::vector<int>& a, const std::vector<int>& b) {\n" // #11469
" return (a.begin() - a.end()) == (b.begin() - b.end());\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct S {\n" // #11469
" const std::vector<int>* vec() const { return &v; }\n"
" const std::vector<int> v;\n"
"};\n"
"void f(const S& a, const S& b) {\n"
" if (a.vec()->begin() - a.vec()->end() != b.vec()->begin() - b.vec()->end()) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void iteratorSameExpression() {
check("void f(std::vector<int> v) {\n"
" std::for_each(v.begin(), v.begin(), [](int){});\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Same iterators expression are used for algorithm.\n", errout_str());
check("std::vector<int>& g();\n"
"void f() {\n"
" std::for_each(g().begin(), g().begin(), [](int){});\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Same iterators expression are used for algorithm.\n", errout_str());
check("void f(std::vector<int> v) {\n"
" std::for_each(v.end(), v.end(), [](int){});\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Same iterators expression are used for algorithm.\n", errout_str());
check("std::vector<int>& g();\n"
"void f() {\n"
" std::for_each(g().end(), g().end(), [](int){});\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Same iterators expression are used for algorithm.\n", errout_str());
check("std::vector<int>::iterator g();\n"
"void f(std::vector<int> v) {\n"
" std::for_each(g(), g(), [](int){});\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Same iterators expression are used for algorithm.\n", errout_str());
check("void f(std::vector<int>::iterator it) {\n"
" std::for_each(it, it, [](int){});\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Same iterators expression are used for algorithm.\n", errout_str());
}
void mismatchingContainerIterator() {
check("std::vector<int> to_vector(int value) {\n"
" std::vector<int> a, b;\n"
" a.insert(b.end(), value);\n"
" return a;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Iterator 'b.end()' referring to container 'b' is used with container 'a'.\n", errout_str());
check("std::vector<int> f(std::vector<int> a, std::vector<int> b) {\n"
" a.erase(b.begin());\n"
" return a;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Iterator 'b.begin()' referring to container 'b' is used with container 'a'.\n", errout_str());
// #9973
check("void f() {\n"
" std::list<int> l1;\n"
" std::list<int> l2;\n"
" std::list<int>& l = l2;\n"
" for (auto it = l.begin(); it != l.end(); ++it) {\n"
" if (*it == 1) {\n"
" l.erase(it);\n"
" break;\n"
" }\n"
" }\n"
"}\n");
ASSERT_EQUALS("[test.cpp:6]: (style) Consider using std::find_if algorithm instead of a raw loop.\n", errout_str());
// #10012
check("struct a {\n"
" int b;\n"
" int end() { return b; }\n"
"};\n"
"void f(a c, a d) {\n"
" if (c.end() == d.end()) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #10467
check("void f(std::array<std::vector<int>, N>& A) {\n"
" for (auto& a : A) {\n"
" auto it = std::find_if(a.begin(), a.end(), \n"
" [](auto i) { return i == 0; });\n"
" if (it != a.end()) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #10604
check("struct S {\n"
" std::vector<int> v;\n"
"};\n"
"void f(S& s, int m) {\n"
" s.v.erase(s.v.begin() + m);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #11093
check("struct S {\n"
" std::vector<int> v1, v2;\n"
" void f(bool b) {\n"
" std::vector<int>& v = b ? v1 : v2;\n"
" v.erase(v.begin());\n"
" }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
// #12377
check("void f(bool b) {\n"
" std::vector<int> *pv;\n"
" if (b) {\n"
" std::vector<int>& r = get1();\n"
" pv = &r;\n"
" }\n"
" else {\n"
" std::vector<int>& r = get2();\n"
" pv = &r;\n"
" }\n"
" std::vector<int>::iterator it = pv->begin();\n"
" it = pv->erase(it, it + 2);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct S {\n"
" std::vector<int> v;\n"
" void f() {\n"
" std::vector<int>* p = &v;\n"
" p->insert(std::find(p->begin(), p->end(), 0), 1);\n"
" }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
check("struct S {\n"
" std::vector<int> v;\n"
" void f(int i) {\n"
" std::vector<int>* p = &v;\n"
" if (p->size() > i)\n"
" p->erase(p->begin() + i, p->end());\n"
" }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
// #11067
check("struct S {\n"
" std::vector<int> v;\n"
" std::list<std::vector<int>::const_iterator> li;\n"
" void f();\n"
"};\n"
"void S::f() {\n"
" v.erase(*li.begin());\n"
" li.pop_front();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(std::set<std::string>& a, std::stack<std::set<std::string>::iterator>& b) {\n"
" while (!b.empty()) {\n"
" a.erase(b.top());\n"
" b.pop();\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(std::vector<int>& a, std::vector<std::vector<int>::iterator>& b) {\n"
" auto it = b.begin();\n"
" a.erase(*it);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("namespace N {\n" // #12443
" std::vector<int> v;\n"
"}\n"
"using namespace N;\n"
"void f() {\n"
" auto it = std::find(v.begin(), v.end(), 0);\n"
" if (it != N::v.end()) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(void* p) {\n" // #12445
" std::vector<int>&v = *(std::vector<int>*)(p);\n"
" v.erase(v.begin(), v.end());\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #13408
check("void f(const std::vector<int>& v) {\n"
" for (const auto& i : v) {\n"
" if (std::distance(&*v.cbegin(), &i)) {}\n"
" } \n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void eraseIteratorOutOfBounds() {
check("void f() {\n"
" std::vector<int> v;\n"
" v.erase(v.begin());\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Calling function 'erase()' on the iterator 'v.begin()' which is out of bounds.\n", errout_str());
check("void f() {\n"
" std::vector<int> v;\n"
" v.erase(v.end());\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Calling function 'erase()' on the iterator 'v.end()' which is out of bounds.\n", errout_str());
check("void f() {\n"
" std::vector<int> v;\n"
" auto it = v.begin();\n"
" v.erase(it);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (error) Calling function 'erase()' on the iterator 'it' which is out of bounds.\n", errout_str());
check("void f() {\n"
" std::vector<int> v{ 1, 2, 3 };\n"
" auto it = v.end();\n"
" v.erase(it);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (error) Calling function 'erase()' on the iterator 'it' which is out of bounds.\n", errout_str());
check("void f() {\n"
" std::vector<int> v{ 1, 2, 3 };\n"
" auto it = v.begin();\n"
" v.erase(it);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" std::vector<int> v{ 1, 2, 3 };\n"
" v.erase(v.end() - 1);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" std::vector<int> v{ 1, 2, 3 };\n"
" v.erase(v.begin() - 1);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Calling function 'erase()' on the iterator 'v.begin()-1' which is out of bounds.\n"
"[test.cpp:3]: (error) Dereference of an invalid iterator: v.begin()-1\n",
errout_str());
check("void f(std::vector<int>& v, std::vector<int>::iterator it) {\n"
" if (it == v.end()) {}\n"
" v.erase(it);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (warning) Either the condition 'it==v.end()' is redundant or function 'erase()' is called on the iterator 'it' which is out of bounds.\n",
errout_str());
check("void f() {\n"
" std::vector<int> v;\n"
" ((v).erase)(v.begin());\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Calling function 'erase()' on the iterator 'v.begin()' which is out of bounds.\n",
errout_str());
}
// Dereferencing invalid pointer
void dereference() {
check("void f()\n"
"{\n"
" std::vector<int> ints{1,2,3,4,5};\n"
" std::vector<int>::iterator iter;\n"
" iter = ints.begin() + 2;\n"
" ints.erase(iter);\n"
" std::cout << (*iter) << std::endl;\n"
"}", true);
TODO_ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:6] -> [test.cpp:3] -> [test.cpp:7]: (error) Using iterator to local container 'ints' that may be invalid.\n", "[test.cpp:5] -> [test.cpp:6] -> [test.cpp:3] -> [test.cpp:7]: (error, inconclusive) Using iterator to local container 'ints' that may be invalid.\n", errout_str());
// #6554 "False positive eraseDereference - erase in while() loop"
check("typedef std::map<Packet> packetMap;\n"
"packetMap waitingPackets;\n"
"void ProcessRawPacket() {\n"
" packetMap::iterator wpi;\n"
" while ((wpi = waitingPackets.find(lastInOrder + 1)) != waitingPackets.end()) {\n"
" waitingPackets.erase(wpi);\n"
" for (unsigned pos = 0; pos < buf.size(); ) { }\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// #8509 Uniform initialization ignored for iterator
check("void f() {\n"
" std::vector<int> ints;\n"
" std::vector<int>::const_iterator iter {ints.cbegin()};\n"
" std::cout << (*iter) << std::endl;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void dereference_break() { // #3644
check("void f(std::vector<int> &ints) {\n"
" std::vector<int>::iterator iter;\n"
" for (iter=ints.begin();iter!=ints.end();++iter) {\n"
" if (*iter == 2) {\n"
" ints.erase(iter);\n"
" break;\n"
" }\n"
" if (*iter == 3) {\n"
" ints.erase(iter);\n"
" break;\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void dereference_member() {
check("void f()\n"
"{\n"
" std::map<int, int> ints;\n"
" std::map<int, int>::iterator iter;\n"
" iter = ints.begin();\n"
" ints.erase(iter);\n"
" std::cout << iter->first << std::endl;\n"
"}");
ASSERT_EQUALS("[test.cpp:7] -> [test.cpp:6]: (error) Iterator 'iter' used after element has been erased.\n"
"[test.cpp:6]: (error) Calling function 'erase()' on the iterator 'iter' which is out of bounds.\n",
errout_str());
// Reverse iterator
check("void f()\n"
"{\n"
" std::map<int, int> ints;\n"
" std::map<int, int>::reverse_iterator iter;\n"
" iter = ints.rbegin();\n"
" ints.erase(iter);\n"
" std::cout << iter->first << std::endl;\n"
"}");
ASSERT_EQUALS("[test.cpp:7] -> [test.cpp:6]: (error) Iterator 'iter' used after element has been erased.\n"
"[test.cpp:6]: (error) Calling function 'erase()' on the iterator 'iter' which is out of bounds.\n",
errout_str());
}
void dereference_auto() {
check("void f()\n"
"{\n"
" std::vector<int> ints{1,2,3,4,5};\n"
" auto iter = ints.begin() + 2;\n"
" ints.erase(iter);\n"
" std::cout << (*iter) << std::endl;\n"
"}", true);
TODO_ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:5] -> [test.cpp:3] -> [test.cpp:6]: (error) Using iterator to local container 'ints' that may be invalid.\n", "[test.cpp:4] -> [test.cpp:5] -> [test.cpp:3] -> [test.cpp:6]: (error, inconclusive) Using iterator to local container 'ints' that may be invalid.\n", errout_str());
check("void f() {\n"
" auto x = *myList.begin();\n"
" myList.erase(x);\n"
" auto b = x.first;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("const CXXRecordDecl *CXXRecordDecl::getTemplateInstantiationPattern() const {\n"
" if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(this)) {\n"
" auto From = TD->getInstantiatedFrom();\n"
" }\n"
" return nullptr;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void STLSize() {
check("void foo()\n"
"{\n"
" std::vector<int> foo;\n"
" for (unsigned int ii = 0; ii <= foo.size(); ++ii)\n"
" {\n"
" foo[ii] = 0;\n"
" }\n"
"}");
ASSERT_EQUALS(
"[test.cpp:6]: (error) Out of bounds access in expression 'foo[ii]' because 'foo' is empty.\n",
errout_str());
check("void foo(std::vector<int> foo) {\n"
" for (unsigned int ii = 0; ii <= foo.size(); ++ii) {\n"
" foo.at(ii) = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) When ii==foo.size(), foo.at(ii) is out of bounds.\n", errout_str());
check("void foo(std::string& foo) {\n"
" for (unsigned int ii = 0; ii <= foo.length(); ++ii) {\n"
" foo[ii] = 'x';\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) When ii==foo.size(), foo[ii] is out of bounds.\n", errout_str());
check("void foo(std::string& foo, unsigned int ii) {\n"
" if (ii <= foo.length()) {\n"
" foo[ii] = 'x';\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) When ii==foo.size(), foo[ii] is out of bounds.\n", errout_str());
check("void foo(std::string& foo, unsigned int ii) {\n"
" do {\n"
" foo[ii] = 'x';\n"
" ++i;\n"
" } while(ii <= foo.length());\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) When ii==foo.size(), foo[ii] is out of bounds.\n", errout_str());
check("void foo(std::string& foo, unsigned int ii) {\n"
" if (anything()) {\n"
" } else if (ii <= foo.length()) {\n"
" foo[ii] = 'x';\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) When ii==foo.size(), foo[ii] is out of bounds.\n", errout_str());
check("void foo()\n"
"{\n"
" std::vector<int> foo;\n"
" foo.push_back(1);\n"
" for (unsigned int ii = 0; ii <= foo.size(); ++ii)\n"
" {\n"
" }\n"
" int ii = 0;\n"
" foo[ii] = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" for (B b : D()) {}\n" // Don't crash on range-based for-loop
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(std::vector<int> foo) {\n"
" for (unsigned int ii = 0; ii <= foo.size() + 1; ++ii) {\n"
" foo.at(ii) = 0;\n"
" }\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:3]: (error) When ii==foo.size(), foo.at(ii) is out of bounds.\n", "", errout_str());
}
void STLSizeNoErr() {
{
check("void foo()\n"
"{\n"
" std::vector<int> foo;\n"
" for (unsigned int ii = 0; ii < foo.size(); ++ii)\n"
" {\n"
" foo[ii] = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
{
check("void foo()\n"
"{\n"
" std::vector<int> foo;\n"
" for (unsigned int ii = 0; ii <= foo.size(); ++ii)\n"
" {\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
{
check("void foo()\n"
"{\n"
" std::vector<int> foo;\n"
" for (unsigned int ii = 0; ii <= foo.size(); ++ii)\n"
" {\n"
" if (ii == foo.size())\n"
" {\n"
" }\n"
" else\n"
" {\n"
" foo[ii] = 0;\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS(
"[test.cpp:11]: (error) Out of bounds access in expression 'foo[ii]' because 'foo' is empty.\n",
errout_str());
}
{
check("void f(const std::map<int,int> &data) {\n"
" int i = x;"
" for (int i = 5; i <= data.size(); i++)\n"
" data[i] = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
{
check("void foo(std::vector<int> foo) {\n"
" for (unsigned int ii = 0; ii <= foo.size() - 1; ++ii) {\n"
" foo.at(ii) = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
}
void negativeIndex() {
check("void f(const std::vector<int> &v) {\n"
" v[-11] = 123;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Array index -11 is out of bounds.\n", errout_str());
check("int f(int x, const std::vector<int>& a) {\n"
" if (!(x < 5))\n"
" return a[x - 5];\n"
" else\n"
" return a[4 - x];\n"
"}");
ASSERT_EQUALS("", errout_str());
check("std::array<int,6> values;\n"
"int get_value();\n"
"int compute() {\n"
" int i = get_value();\n"
" if( i < 0 || i > 5)\n"
" return -1;\n"
" int sum = 0;\n"
" for( int j = i+1; j < 7; ++j)\n"
" sum += values[j-1];\n"
" return sum;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct B { virtual int g() { return 0; } };\n" // #11831
"struct C {\n"
" int h() const { return b->g(); }\n"
" B* b;\n"
"};\n"
"struct O {\n"
" int f() const;\n"
" std::vector<int> v;\n"
" C c;\n"
"};\n"
"int O::f() const { return v[c.h() - 1]; }\n");
ASSERT_EQUALS("", errout_str());
check("void f(const std::vector<int>& v) {\n" // #13196
" if (v.empty())\n"
" return;\n"
" int idx = -1;\n"
" for (int i = 0; i < v.size(); ++i) {\n"
" idx = i;\n"
" }\n"
" (void)v[idx];\n"
"}\n");
ASSERT_EQUALS("", errout_str());
const auto oldSettings = settings;
settings.daca = true;
check("void f() {\n"
" const char a[][5] = { \"1\", \"true\", \"on\", \"yes\" };\n"
"}\n");
ASSERT_EQUALS("", errout_str());
settings = oldSettings;
}
void negativeIndexMultiline() {
setMultiline();
const auto oldSettings = settings;
settings.verbose = true;
check("bool valid(int);\n" // #11697
"void f(int i, const std::vector<int>& v) {\n"
" if (!valid(i))\n"
" return;\n"
" if (v[i]) {}\n"
"}\n"
"void g(const std::vector<int>& w) {\n"
" f(-1, w);\n"
"}\n");
ASSERT_EQUALS("test.cpp:5:warning:Array index -1 is out of bounds.\n"
"test.cpp:8:note:Calling function 'f', 1st argument '-1' value is -1\n"
"test.cpp:3:note:Assuming condition is false\n"
"test.cpp:5:note:Negative array index\n",
errout_str());
settings = oldSettings;
}
void erase1() {
check("void f()\n"
"{\n"
" std::list<int>::iterator it;\n"
" for (it = foo.begin(); it != foo.end(); ++it) {\n"
" foo.erase(it);\n"
" }\n"
" for (it = foo.begin(); it != foo.end(); ++it) {\n"
" foo.erase(it);\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:5]: (error) Iterator 'it' used after element has been erased.\n"
"[test.cpp:7] -> [test.cpp:8]: (error) Iterator 'it' used after element has been erased.\n", errout_str());
check("void f(std::list<int> &ints)\n"
"{\n"
" std::list<int>::iterator i = ints.begin();\n"
" i = ints.erase(i);\n"
" *i = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f()\n"
"{\n"
" std::list<int>::iterator i;\n"
" while (i != x.y.end())\n"
" i = x.y.erase(i);\n"
"}");
ASSERT_EQUALS("", errout_str());
// #2101
check("void f(vector< std::list<int> > &ints, unsigned int i)\n"
"{\n"
" std::list<int>::iterator it;\n"
" for(it = ints[i].begin(); it != ints[i].end(); it++) {\n"
" if (*it % 2)\n"
" it = ints[i].erase(it);\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void erase2() {
check("static void f()\n"
"{\n"
" for (iterator it = foo.begin(); it != foo.end(); it = next)\n"
" {\n"
" next = it;\n"
" next++;\n"
" foo.erase(it);\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void erase3() {
check("static void f(std::list<abc> &foo)\n"
"{\n"
" std::list<abc>::iterator it = foo.begin();\n"
" foo.erase(it->a);\n"
" if (it->b);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void erase4() {
check("void f()\n"
"{\n"
" std::list<int>::iterator it, it2;\n"
" for (it = foo.begin(); it != i2; ++it)\n"
" {\n"
" foo.erase(it);\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:6]: (error) Iterator 'it' used after element has been erased.\n", errout_str());
check("void f()\n"
"{\n"
" std::list<int>::iterator it = foo.begin();\n"
" for (; it != i2; ++it)\n"
" {\n"
" foo.erase(it);\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:6]: (error) Iterator 'it' used after element has been erased.\n", errout_str());
check("void f()\n"
"{\n"
" std::list<int>::iterator it = foo.begin();\n"
" while (it != i2)\n"
" {\n"
" foo.erase(it);\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:6]: (error) Iterator 'it' used after element has been erased.\n", errout_str());
check("void f()\n"
"{\n"
" std::list<int>::iterator it = foo.begin();\n"
" while (it != i2)\n"
" {\n"
" foo.erase(++it);\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:6]: (error) Iterator 'it' used after element has been erased.\n", errout_str());
}
void erase5() {
check("void f()\n"
"{\n"
" std::list<int> foo;\n"
" std::list<int>::iterator it;\n"
" for (it = foo.begin(); it != foo.end(); ++it)\n"
" {\n"
" if (*it == 123)\n"
" foo.erase(it);\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:8]: (error) Iterator 'it' used after element has been erased.\n", errout_str());
}
void erase6() {
check("void f() {\n"
" std::vector<int> vec(3);\n"
" std::vector<int>::iterator it;\n"
" std::vector<int>::iterator itEnd = vec.end();\n"
" for (it = vec.begin(); it != itEnd; it = vec.begin(), itEnd = vec.end())\n"
" {\n"
" vec.erase(it);\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void eraseBreak() {
check("void f()\n"
"{\n"
" for (std::vector<int>::iterator it = foo.begin(); it != foo.end(); ++it)\n"
" {\n"
" foo.erase(it);\n"
" if (x)"
" break;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:5]: (error) Iterator 'it' used after element has been erased.\n", errout_str());
check("void f()\n"
"{\n"
" for (std::vector<int>::iterator it = foo.begin(); it != foo.end(); ++it)\n"
" {\n"
" if (x) {\n"
" foo.erase(it);\n"
" break;\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x)\n"
"{\n"
" for (std::vector<int>::iterator it = foo.begin(); it != foo.end(); ++it)\n"
" {\n"
" foo.erase(it);\n"
" if (x)"
" return;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:5]: (error) Iterator 'it' used after element has been erased.\n", errout_str());
}
void eraseContinue() {
check("void f(std::vector<int> &ints)\n"
"{\n"
" std::vector<int>::iterator it;\n"
" std::vector<int>::iterator jt = ints.begin();\n"
" for (it = ints.begin(); it != ints.end(); it = jt) {\n"
" ++jt;\n"
" if (*it == 1) {\n"
" jt = ints.erase(it);\n"
" continue;\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(std::map<uint32, uint32> my_map) {\n" // #7365
" std::map<uint32, uint32>::iterator itr = my_map.begin();\n"
" switch (itr->first) {\n"
" case 0:\n"
" my_map.erase(itr);\n"
" continue;\n"
" case 1:\n"
" itr->second = 1;\n"
" break;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void eraseReturn1() {
check("void f()\n"
"{\n"
" std::vector<int> foo;\n"
" std::vector<int>::iterator it;\n"
" for (it = foo.begin(); it != foo.end(); ++it)\n"
" {\n"
" foo.erase(it);\n"
" return;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void eraseReturn2() {
check("void f()\n"
"{\n"
" std::vector<int> foo;\n"
" std::vector<int>::iterator it;\n"
" for (it = foo.begin(); it != foo.end(); ++it)\n"
" {\n"
" if (*it == 1) {\n"
" foo.erase(it);\n"
" return;\n"
" }\n"
" else {\n"
" foo.erase(it);\n"
" return;\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void eraseReturn3() {
check("void f()\n"
"{\n"
" std::vector<int> foo;\n"
" std::vector<int>::iterator it;\n"
" for (it = foo.begin(); it != foo.end(); ++it)\n"
" {\n"
" if (somecondition) {\n"
" if (*it == 1)\n"
" foo.erase(it);\n"
" else\n"
" *it = 0;\n"
" return;\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f()\n"
"{\n"
" std::vector<int> foo;\n"
" std::vector<int>::iterator it;\n"
" for (it = foo.begin(); it != foo.end(); ++it)\n"
" {\n"
" if (a) {\n"
" if (b)\n"
" foo.erase(it);\n" // <- TODO: erase shound't cause inconclusive valueflow
" else\n"
" *it = 0;\n"
" }\n"
" }\n"
"}");
TODO_ASSERT_EQUALS(
"[test.cpp:5] -> [test.cpp:7] -> [test.cpp:8] -> [test.cpp:8] -> [test.cpp:7] -> [test.cpp:5] -> [test.cpp:9] -> [test.cpp:3] -> [test.cpp:5]: (error) Using iterator to local container 'foo' that may be invalid.\n",
"[test.cpp:5] -> [test.cpp:7] -> [test.cpp:8] -> [test.cpp:8] -> [test.cpp:7] -> [test.cpp:5] -> [test.cpp:9] -> [test.cpp:3] -> [test.cpp:5]: (error, inconclusive) Using iterator to local container 'foo' that may be invalid.\n",
errout_str());
}
void eraseGoto() {
check("void f()\n"
"{\n"
" for (std::vector<int>::iterator it = foo.begin(); it != foo.end(); ++it)\n"
" {\n"
" foo.erase(it);\n"
" goto abc;\n"
" }\n"
"bar:\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void eraseAssign1() {
check("void f()\n"
"{\n"
" for (std::vector<int>::iterator it = foo.begin(); it != foo.end(); ++it)\n"
" {\n"
" foo.erase(it);\n"
" it = foo.begin();\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void eraseAssign2() {
check("void f(std::list<int> &ints)\n"
"{\n"
" for (std::list<int>::iterator it = ints.begin(); it != ints.end();) {\n"
" if (*it == 123) {\n"
" std::list<int>::iterator copy = it;\n"
" ++copy;\n"
" ints.erase(it);\n"
" it = copy;\n"
" } else {\n"
" it->second = 123;\n"
" ++it;\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void eraseAssign3() {
check("void f(std::list<list<int> >& l) {\n"
" std::list<std::list<int> >::const_iterator i = l.begin();\n"
" std::list<int>::const_iterator j = (*i).begin();\n"
" cout << *j << endl;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void eraseAssign4() {
check("void f(std::list<int> data) {\n"
" std::list<int>::const_iterator it = data.begin();\n"
" it = data.erase(it);\n"
" it = data.erase(it);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(Data data) {\n"
" std::list<int>::const_iterator it = data.ints.begin();\n"
" it = data.ints.erase(it);\n"
" it = data.ints.erase(it);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void eraseAssignByFunctionCall() {
check("void f(std::list<list<int> >& l) {\n"
" std::list<foo>::const_iterator i;\n"
" bar(i);\n"
" cout << *i;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void eraseErase() {
check("void f(std::vector<ints> &ints)\n"
"{\n"
" std::vector<int>::iterator iter;\n"
" iter = ints.begin() + 2;\n"
" ints.erase(iter);\n"
" ints.erase(iter);\n"
"}", true);
TODO_ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:4] -> [test.cpp:5] -> [test.cpp:1] -> [test.cpp:6]: (error) Using iterator to local container 'ints' that may be invalid.\n", "[test.cpp:1] -> [test.cpp:4] -> [test.cpp:5] -> [test.cpp:1] -> [test.cpp:6]: (error, inconclusive) Using iterator to local container 'ints' that may be invalid.\n", errout_str());
}
void eraseByValue() {
check("void f()\n"
"{\n"
" std::set<int> foo;\n"
" for (std::set<int>::iterator it = foo.begin(); it != foo.end(); ++it)\n"
" {\n"
" foo.erase(*it);\n"
" }\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:6]: (error) Iterator 'it' becomes invalid when deleted by value from 'foo'\n", "", errout_str());
check("int f(std::set<int> foo) {\n"
" std::set<int>::iterator it = foo.begin();\n"
" foo.erase(*it);\n"
" return *it;\n"
"}");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:3]: (error) Iterator 'it' used after element has been erased.\n", errout_str());
check("void f(std::set<int> foo)\n"
"{\n"
" std::set<int>::iterator it = foo.begin();\n"
" foo.erase(*it);\n"
"}");
ASSERT_EQUALS("", errout_str());
// #5669
check("void f() {\n"
" HashSet_Ref::iterator aIt = m_ImplementationMap.find( xEle );\n"
" m_SetLoadedFactories.erase(*aIt);\n"
" m_SetLoadedFactories.erase(aIt);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(const std::list<int>& m_ImplementationMap) {\n"
" std::list<int>::iterator aIt = m_ImplementationMap.begin();\n"
" m_ImplementationMap.erase(*aIt);\n"
" m_ImplementationMap.erase(aIt);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Invalid iterator: aIt\n", errout_str());
check("void f(const std::list<int>& m_ImplementationMap) {\n"
" std::list<int>::iterator aIt = m_ImplementationMap.begin();\n"
" std::list<int>::iterator bIt = m_ImplementationMap.begin();\n"
" m_ImplementationMap.erase(*bIt);\n"
" m_ImplementationMap.erase(aIt);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void eraseIf() {
// #4816
check("void func(std::list<std::string> strlist) {\n"
" for (std::list<std::string>::iterator str = strlist.begin(); str != strlist.end(); str++) {\n"
" if (func2(*str)) {\n"
" strlist.erase(str);\n"
" if (strlist.empty())\n"
" return;\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:4]: (error) Iterator 'str' used after element has been erased.\n", errout_str());
}
void eraseOnVector() {
check("void f(std::vector<int>& v) {\n"
" std::vector<int>::iterator aIt = v.begin();\n"
" v.erase(something(unknown));\n" // All iterators become invalidated when erasing from std::vector
" v.erase(aIt);\n"
"}");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:2] -> [test.cpp:3] -> [test.cpp:1] -> [test.cpp:4]: (error) Using iterator to local container 'v' that may be invalid.\n", errout_str());
check("void f(std::vector<int>& v) {\n"
" std::vector<int>::iterator aIt = v.begin();\n"
" std::vector<int>::iterator bIt = v.begin();\n"
" v.erase(bIt);\n" // All iterators become invalidated when erasing from std::vector
" aIt = v.erase(aIt);\n"
"}");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:2] -> [test.cpp:4] -> [test.cpp:1] -> [test.cpp:5]: (error) Using iterator to local container 'v' that may be invalid.\n", errout_str());
}
void pushback1() {
check("void f(const std::vector<int> &foo)\n"
"{\n"
" std::vector<int>::const_iterator it = foo.begin();\n"
" foo.push_back(123);\n"
" *it;\n"
"}");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:3] -> [test.cpp:4] -> [test.cpp:1] -> [test.cpp:5]: (error) Using iterator to local container 'foo' that may be invalid.\n", errout_str());
}
void pushback2() {
check("void f()\n"
"{\n"
" std::vector<int>::const_iterator it = foo.begin();\n"
" foo.push_back(123);\n"
" {\n"
" int *it = &foo[0];\n"
" *it = 456;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void pushback3() {
check("void f()\n"
"{\n"
" std::vector<int> foo;\n"
" foo.push_back(10);\n"
" std::vector<int>::iterator it;\n"
" for (it = foo.begin(); it != foo.end(); ++it)\n"
" {\n"
" foo.push_back(123);\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:6] -> [test.cpp:6] -> [test.cpp:8] -> [test.cpp:3] -> [test.cpp:6]: (error) Using iterator to local container 'foo' that may be invalid.\n", errout_str());
}
void pushback4() {
check("void f()\n"
"{\n"
" std::vector<int> ints;\n"
" ints.push_back(1);\n"
" int *first = &ints[0];\n"
" ints.push_back(2);\n"
" *first;\n"
"}");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:6] -> [test.cpp:3] -> [test.cpp:7]: (error) Using pointer to local variable 'ints' that may be invalid.\n", errout_str());
}
void pushback5() {
check("void f()\n"
"{\n"
" std::vector<int>::const_iterator i;\n"
"\n"
" for (i=v.begin(); i!=v.end(); ++i)\n"
" {\n"
" }\n"
"\n"
" for (i=rhs.v.begin(); i!=rhs.v.end(); ++i)\n"
" {\n"
" v.push_back(*i);\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void pushback6() {
// ticket #735
check("void f()\n"
"{\n"
" std::vector<int> v;\n"
" v.push_back(1);\n"
" v.push_back(2);\n"
" for (std::vector<int>::iterator it = v.begin(); it != v.end(); ++it)\n"
" {\n"
" if (*it == 1)\n"
" v.push_back(10);\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:6] -> [test.cpp:8] -> [test.cpp:8] -> [test.cpp:6] -> [test.cpp:9] -> [test.cpp:3] -> [test.cpp:6]: (error) Using iterator to local container 'v' that may be invalid.\n", errout_str());
check("void f()\n"
"{\n"
" std::vector<int> v;\n"
" vector.push_back(1);\n"
" vector.push_back(2);\n"
" for (std::vector<int>::iterator it = v.begin(); it != v.end(); ++it)\n"
" {\n"
" if (*it == 1)\n"
" v.push_back(10);\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:6] -> [test.cpp:8] -> [test.cpp:8] -> [test.cpp:6] -> [test.cpp:9] -> [test.cpp:3] -> [test.cpp:6]: (error) Using iterator to local container 'v' that may be invalid.\n", errout_str());
}
void pushback7() {
check("void f()\n"
"{\n"
" std::vector<int> foo;\n"
" foo.push_back(10);\n"
" std::vector<int>::iterator it;\n"
" for (it = foo.begin(); it != foo.end(); it++)\n"
" {\n"
" foo.push_back(123);\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:6] -> [test.cpp:6] -> [test.cpp:8] -> [test.cpp:3] -> [test.cpp:6]: (error) Using iterator to local container 'foo' that may be invalid.\n", errout_str());
}
void pushback8() {
check("void f()\n"
"{\n"
" std::vector<int> ints;\n"
" std::vector<int>::const_iterator end = ints.end();\n"
" ints.push_back(10);\n"
" std::vector<int>::iterator it;\n"
" unsigned int sum = 0;\n"
" for (it = ints.begin(); it != end; ++it)\n"
" {\n"
" sum += *it;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:10]: (style) Consider using std::accumulate algorithm instead of a raw loop.\n"
"[test.cpp:4] -> [test.cpp:5] -> [test.cpp:3] -> [test.cpp:8]: (error) Using iterator to local container 'ints' that may be invalid.\n",
errout_str());
}
void pushback9() {
check("struct A {\n"
" std::vector<int> ints;\n"
"};\n"
"\n"
"void f()\n"
"{\n"
" std::vector<int> ints;\n"
" A a;\n"
" std::vector<int>::const_iterator i = ints.begin();\n"
" std::vector<int>::const_iterator e = ints.end();\n"
" while (i != e)\n"
" {\n"
" a.ints.push_back(*i);\n"
" ++i;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void pushback10() {
check("void f(std::vector<int> &foo)\n"
"{\n"
" std::vector<int>::const_iterator it = foo.begin();\n"
" foo.reserve(100);\n"
" *it = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:3] -> [test.cpp:4] -> [test.cpp:1] -> [test.cpp:5]: (error) Using iterator to local container 'foo' that may be invalid.\n", errout_str());
// in loop
check("void f()\n"
"{\n"
" std::vector<int> foo;\n"
" foo.push_back(10);\n"
" std::vector<int>::iterator it;\n"
" for (it = foo.begin(); it != foo.end(); ++it)\n"
" {\n"
" foo.reserve(123);\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:6] -> [test.cpp:6] -> [test.cpp:8] -> [test.cpp:3] -> [test.cpp:6]: (error) Using iterator to local container 'foo' that may be invalid.\n", errout_str());
}
void pushback11() {
// #2798
check("void f() {\n"
" std::vector<int> ints;\n"
" std::vector<int>::iterator it = ints.begin();\n"
" if (it == ints.begin()) {\n"
" ints.push_back(0);\n"
" } else {\n"
" ints.insert(it,0);\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void pushback12() {
// #4197
check("void foo(double s)\n"
"{\n"
" std::vector<double> vec;\n"
" for( std::vector<double>::iterator it = vec.begin(); it != vec.end(); ++it )\n"
" {\n"
" vec.insert( it, s );\n"
" for(unsigned int i = 0; i < 42; i++)\n"
" {}\n"
" *it;\n"
" }\n"
"}");
ASSERT_EQUALS(
"[test.cpp:4] -> [test.cpp:6] -> [test.cpp:3] -> [test.cpp:9]: (error, inconclusive) Using iterator to local container 'vec' that may be invalid.\n",
errout_str());
}
void pushback13() {
check("bool Preprocessor::ConcatenateIncludeName(SmallString<128> &FilenameBuffer, SourceLocation &End) {\n"
" unsigned PreAppendSize = FilenameBuffer.size();\n"
" FilenameBuffer.resize(PreAppendSize + CurTok.getLength());\n"
" const char *BufPtr = &FilenameBuffer[PreAppendSize];\n"
" return true;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void insert1() {
check("void f(std::vector<int> &ints)\n"
"{\n"
" std::vector<int>::iterator iter = ints.begin() + 5;\n"
" ints.insert(ints.begin(), 1);\n"
" ++iter;\n"
"}");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:3] -> [test.cpp:4] -> [test.cpp:1] -> [test.cpp:5]: (error) Using iterator to local container 'ints' that may be invalid.\n", errout_str());
check("void f()\n"
"{\n"
" std::vector<int> ints;\n"
" std::vector<int>::iterator iter = ints.begin();\n"
" ints.insert(iter, 1);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f()\n"
"{\n"
" std::vector<int> ints;\n"
" std::vector<int>::iterator iter = ints.begin();\n"
" ints.insert(iter, 1);\n"
" ints.insert(iter, 2);\n"
"}", true);
TODO_ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:5] -> [test.cpp:3] -> [test.cpp:6]: (error) Using iterator to local container 'ints' that may be invalid.\n", "[test.cpp:4] -> [test.cpp:5] -> [test.cpp:3] -> [test.cpp:6]: (error, inconclusive) Using iterator to local container 'ints' that may be invalid.\n", errout_str());
check("void* f(const std::vector<Bar>& bars) {\n"
" std::vector<Bar>::iterator i = bars.begin();\n"
" bars.insert(Bar());\n"
" void* v = &i->foo;\n"
" return v;\n"
"}");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:2] -> [test.cpp:3] -> [test.cpp:1] -> [test.cpp:4]: (error) Using iterator to local container 'bars' that may be invalid.\n", errout_str());
check("Foo f(const std::vector<Bar>& bars) {\n"
" std::vector<Bar>::iterator i = bars.begin();\n"
" bars.insert(Bar());\n"
" return i->foo;\n"
"}");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:2] -> [test.cpp:3] -> [test.cpp:1] -> [test.cpp:4]: (error) Using iterator to local container 'bars' that may be invalid.\n", errout_str());
check("void f(const std::vector<Bar>& bars) {\n"
" for(std::vector<Bar>::iterator i = bars.begin(); i != bars.end(); ++i) {\n"
" i = bars.insert(i, bar);\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// TODO: This shouldn't be inconclusive
check("void f(const std::vector<Bar>& bars) {\n"
" for(std::vector<Bar>::iterator i = bars.begin(); i != bars.end(); ++i) {\n"
" bars.insert(i, bar);\n"
" i = bars.insert(i, bar);\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:2] -> [test.cpp:3] -> [test.cpp:1] -> [test.cpp:4]: (error, inconclusive) Using iterator to local container 'bars' that may be invalid.\n", errout_str());
// TODO: This shouldn't be inconclusive
check("void* f(const std::vector<Bar>& bars) {\n"
" std::vector<Bar>::iterator i = bars.begin();\n"
" bars.insert(i, Bar());\n"
" i = bars.insert(i, Bar());\n"
" void* v = &i->foo;\n"
" return v;\n"
"}");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:2] -> [test.cpp:3] -> [test.cpp:1] -> [test.cpp:4]: (error, inconclusive) Using iterator to local container 'bars' that may be invalid.\n", errout_str());
}
void insert2() {
// Ticket: #2169
check("void f(std::vector<int> &vec) {\n"
" for(std::vector<int>::iterator iter = vec.begin(); iter != vec.end(); ++iter)\n"
" {\n"
" vec.insert(iter, 0);\n"
" break;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(std::vector<int> &vec) {\n"
" for(std::vector<int>::iterator iter = vec.begin(); iter != vec.end(); ++iter)\n"
" {\n"
" if (*it == 0) {\n"
" vec.insert(iter, 0);\n"
" return;\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void popback1() { // #11553
check("void f() {\n"
" std::vector<int> v;\n"
" v.pop_back();\n"
" std::list<int> l;\n"
" l.pop_front();\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Out of bounds access in expression 'v.pop_back()' because 'v' is empty.\n"
"[test.cpp:5]: (error) Out of bounds access in expression 'l.pop_front()' because 'l' is empty.\n",
errout_str());
check("void f(std::vector<int>& v) {\n"
" if (v.empty()) {}\n"
" v.pop_back();\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (warning) Either the condition 'v.empty()' is redundant or expression 'v.pop_back()' causes access out of bounds.\n",
errout_str());
check("void f(std::vector<int>& v) {\n"
" v.pop_back();\n"
" if (v.empty()) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void stlBoundaries1() {
const std::string stlCont[] = {
"list", "set", "multiset", "map", "multimap"
};
for (size_t i = 0; i < getArrayLength(stlCont); ++i) {
check("void f()\n"
"{\n"
" std::" + stlCont[i] + "<int>::iterator it;\n"
" for (it = ab.begin(); it < ab.end(); ++it)\n"
" ;\n"
"}");
ASSERT_EQUALS_MSG("[test.cpp:4]: (error) Dangerous comparison using operator< on iterator.\n", errout_str(), stlCont[i]);
}
check("void f() {\n"
" std::forward_list<int>::iterator it;\n"
" for (it = ab.begin(); ab.end() > it; ++it) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Dangerous comparison using operator< on iterator.\n", errout_str());
// #5926 no FP Dangerous comparison using operator< on iterator on std::deque
check("void f() {\n"
" std::deque<int>::iterator it;\n"
" for (it = ab.begin(); ab.end() > it; ++it) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void stlBoundaries2() {
check("void f()\n"
"{\n"
" std::vector<std::string> files;\n"
" std::vector<std::string>::const_iterator it;\n"
" for (it = files.begin(); it < files.end(); it++) { }\n"
" for (it = files.begin(); it < files.end(); it++) { };\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void stlBoundaries3() {
check("void f()\n"
"{\n"
" set<int> files;\n"
" set<int>::const_iterator current;\n"
" for (current = files.begin(); current != files.end(); ++current)\n"
" {\n"
" assert(*current < 100)\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool f() {\n"
" static set<Foo>::const_iterator current;\n"
" return 25 > current->bar;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Invalid iterator 'current' used.\n", errout_str());
}
void stlBoundaries4() {
check("void f() {\n"
" std::forward_list<std::vector<std::vector<int>>>::iterator it;\n"
" for (it = ab.begin(); ab.end() > it; ++it) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Dangerous comparison using operator< on iterator.\n", errout_str());
// don't crash
check("void f() {\n"
" if (list < 0) ;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" if (list < 0) {\n"
" std::forward_list<std::vector<std::vector<int>>>::iterator it;\n"
" for (it = ab.begin(); ab.end() > it; ++it) {}\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Dangerous comparison using operator< on iterator.\n", errout_str());
}
void stlBoundaries5() {
check("class iterator { int foo(); };\n"
"int foo() {\n"
" iterator i;\n"
" return i.foo();;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("class iterator {\n"
" Class operator*();\n"
" iterator& operator++();\n"
" int foo();\n"
"};\n"
"int foo() {\n"
" iterator i;\n"
" return i.foo();;\n"
"}", true);
ASSERT_EQUALS("[test.cpp:8]: (error, inconclusive) Invalid iterator 'i' used.\n", errout_str());
}
void stlBoundaries6() { // #7106
check("void foo(std::vector<int>& vec) {\n"
" for (Function::iterator BB : vec) {\n"
" for (int Inst : *BB)\n"
" {\n"
" }\n"
" }\n"
"}", true);
ASSERT_EQUALS("", errout_str());
}
void if_find() {
// ---------------------------
// set::find
// ---------------------------
// error (simple)
check("void f(std::set<int> s)\n"
"{\n"
" if (s.find(12)) { }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Suspicious condition. The result of find() is an iterator, but it is not properly checked.\n", errout_str());
// error (pointer)
check("void f(std::set<int> *s)\n"
"{\n"
" if ((*s).find(12)) { }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Suspicious condition. The result of find() is an iterator, but it is not properly checked.\n", errout_str());
// error (pointer)
check("void f(std::set<int> *s)\n"
"{\n"
" if (s->find(12)) { }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Suspicious condition. The result of find() is an iterator, but it is not properly checked.\n", errout_str());
// error (array-like pointer)
check("void f(std::set<int> *s)\n"
"{\n"
" if (s[0].find(12)) { }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Suspicious condition. The result of find() is an iterator, but it is not properly checked.\n", errout_str());
// error (array)
check("void f(std::set<int> s [10])\n"
"{\n"
" if (s[0].find(12)) { }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Suspicious condition. The result of find() is an iterator, but it is not properly checked.\n", errout_str());
// error (undefined length array)
check("void f(std::set<int> s [])\n"
"{\n"
" if (s[0].find(12)) { }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Suspicious condition. The result of find() is an iterator, but it is not properly checked.\n", errout_str());
// error (vector)
check("void f(std::vector<std::set<int> > s)\n"
"{\n"
" if (s[0].find(12)) { }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Suspicious condition. The result of find() is an iterator, but it is not properly checked.\n", errout_str());
// error (assignment)
check("void f(std::set<int> s)\n"
"{\n"
" if (a || (x = s.find(12))) { }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Suspicious condition. The result of find() is an iterator, but it is not properly checked.\n", errout_str());
// ok (simple)
check("void f(std::set<int> s)\n"
"{\n"
" if (s.find(123) != s.end()) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
// ok (pointer)
check("void f(std::set<int> *s)\n"
"{\n"
" if ((*s).find(12) != s.end()) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
// ok (array-like pointer)
check("void f(std::set<int> *s)\n"
"{\n"
" if (s[0].find(12) != s->end()) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
// ok (array)
check("void f(std::set<int> s [10])\n"
"{\n"
" if (s[0].find(123) != s->end()) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
// ok (undefined length array)
check("void f(std::set<int> s [])\n"
"{\n"
" if (s[0].find(123) != s->end()) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
// ok (assignment)
check("void f(std::set<int> s)\n"
"{\n"
" if (a || (x = s.find(12)) != s.end()) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
// ok (dereference, #6402)
check("void f(std::set<Foo> s) {\n"
" if (s.find(12).member) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(std::set<int> s) {\n"
" if (auto result = s.find(123); result != s.end()) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
// ---------------------------
// std::find
// ---------------------------
// error
check("void f()\n"
"{\n"
" if (std::find(a,b,c)) { }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Suspicious condition. The result of find() is an iterator, but it is not properly checked.\n", errout_str());
// ok
check("void f()\n"
"{\n"
" if (std::find(a,b,c) != c) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
// ok (less than comparison, #6217)
check("void f(std::vector<int> s)\n"
"{\n"
" if (std::find(a, b, c) < d) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
// #3714 - segmentation fault for syntax error
ASSERT_THROW_INTERNAL(check("void f() {\n"
" if (()) { }\n"
"}"),
AST);
// #3865
check("void f() {\n"
" if ((std::find(a,b,c)) != b) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void if_str_find() {
// error (simple)
check("void f(const std::string &s)\n"
"{\n"
" if (s.find(\"abc\")) { }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (performance) Inefficient usage of string::find() in condition; string::starts_with() could be faster.\n", errout_str());
// error (pointer)
check("void f(const std::string *s)\n"
"{\n"
" if ((*s).find(\"abc\")) { }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (performance) Inefficient usage of string::find() in condition; string::starts_with() could be faster.\n", errout_str());
// error (pointer)
check("void f(const std::string *s)\n"
"{\n"
" if (s->find(\"abc\")) { }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (performance) Inefficient usage of string::find() in condition; string::starts_with() could be faster.\n", errout_str());
// error (vector)
check("void f(const std::vector<std::string> &s)\n"
"{\n"
" if (s[0].find(\"abc\")) { }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (performance) Inefficient usage of string::find() in condition; string::starts_with() could be faster.\n", errout_str());
// #3162
check("void f(const std::string& s1, const std::string& s2)\n"
"{\n"
" if ((!s1.empty()) && (0 == s1.find(s2))) { }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (performance) Inefficient usage of string::find() in condition; string::starts_with() could be faster.\n", errout_str());
// #4102
check("void f(const std::string &define) {\n"
" if (define.find(\"=\") + 1U == define.size());\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(std::string a, std::string b) {\n" // #4480
" if (a.find(\"<\") < b.find(\">\")) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(const std::string &s) {\n"
" if (foo(s.find(\"abc\"))) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
// #7349 - std::string::find_first_of
check("void f(const std::string &s) {\n"
" if (s.find_first_of(\"abc\")==0) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
// # 10153
check("int main() {\n"
" for (;;) {\n"
" std::string line = getLine();\n"
" if (line.find(\" GL_EXTENSIONS =\") < 12)\n"
" return 1;\n"
" }\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void size1() {
{
const char code[] = "struct Fred {\n"
" void foo();\n"
" std::list<int> x;\n"
"};\n"
"void Fred::foo()\n"
"{\n"
" if (x.size() == 0) {}\n"
"}";
check(code, false, Standards::CPP03);
ASSERT_EQUALS("[test.cpp:7]: (performance) Possible inefficient checking for 'x' emptiness.\n", errout_str());
check(code);
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "std::list<int> x;\n"
"void f()\n"
"{\n"
" if (x.size() == 0) {}\n"
"}";
check(code, false, Standards::CPP03);
ASSERT_EQUALS("[test.cpp:4]: (performance) Possible inefficient checking for 'x' emptiness.\n", errout_str());
check(code);
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "void f()\n"
"{\n"
" std::list<int> x;\n"
" if (x.size() == 0) {}\n"
"}";
check(code, false, Standards::CPP03);
ASSERT_EQUALS("[test.cpp:4]: (performance) Possible inefficient checking for 'x' emptiness.\n", errout_str());
check(code);
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "void f()\n"
"{\n"
" std::list<int> x;\n"
" if (0 == x.size()) {}\n"
"}";
check(code, false, Standards::CPP03);
ASSERT_EQUALS("[test.cpp:4]: (performance) Possible inefficient checking for 'x' emptiness.\n", errout_str());
check(code);
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "void f()\n"
"{\n"
" std::list<int> x;\n"
" if (x.size() != 0) {}\n"
"}";
check(code, false, Standards::CPP03);
ASSERT_EQUALS("[test.cpp:4]: (performance) Possible inefficient checking for 'x' emptiness.\n", errout_str());
check(code);
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "void f()\n"
"{\n"
" std::list<int> x;\n"
" if (0 != x.size()) {}\n"
"}";
check(code, false, Standards::CPP03);
ASSERT_EQUALS("[test.cpp:4]: (performance) Possible inefficient checking for 'x' emptiness.\n", errout_str());
check(code);
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "void f()\n"
"{\n"
" std::list<int> x;\n"
" if (x.size() > 0) {}\n"
"}";
check(code, false, Standards::CPP03);
ASSERT_EQUALS("[test.cpp:4]: (performance) Possible inefficient checking for 'x' emptiness.\n", errout_str());
check(code);
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "void f()\n"
"{\n"
" std::list<int> x;\n"
" if (0 < x.size()) {}\n"
"}";
check(code, false, Standards::CPP03);
ASSERT_EQUALS("[test.cpp:4]: (performance) Possible inefficient checking for 'x' emptiness.\n", errout_str());
check(code);
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "void f()\n"
"{\n"
" std::list<int> x;\n"
" if (x.size() >= 1) {}\n"
"}";
check(code, false, Standards::CPP03);
ASSERT_EQUALS("[test.cpp:4]: (performance) Possible inefficient checking for 'x' emptiness.\n", errout_str());
check(code);
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "void f()\n"
"{\n"
" std::list<int> x;\n"
" if (x.size() < 1) {}\n"
"}";
check(code, false, Standards::CPP03);
ASSERT_EQUALS("[test.cpp:4]: (performance) Possible inefficient checking for 'x' emptiness.\n", errout_str());
check(code);
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "void f()\n"
"{\n"
" std::list<int> x;\n"
" if (1 <= x.size()) {}\n"
"}";
check(code, false, Standards::CPP03);
ASSERT_EQUALS("[test.cpp:4]: (performance) Possible inefficient checking for 'x' emptiness.\n", errout_str());
check(code);
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "void f()\n"
"{\n"
" std::list<int> x;\n"
" if (1 > x.size()) {}\n"
"}";
check(code, false, Standards::CPP03);
ASSERT_EQUALS("[test.cpp:4]: (performance) Possible inefficient checking for 'x' emptiness.\n", errout_str());
check(code);
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "void f()\n"
"{\n"
" std::list<int> x;\n"
" if (x.size()) {}\n"
"}";
check(code, false, Standards::CPP03);
ASSERT_EQUALS("[test.cpp:4]: (performance) Possible inefficient checking for 'x' emptiness.\n", errout_str());
check(code);
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "void f()\n"
"{\n"
" std::list<int> x;\n"
" if (!x.size()) {}\n"
"}";
check(code, false, Standards::CPP03);
ASSERT_EQUALS("[test.cpp:4]: (performance) Possible inefficient checking for 'x' emptiness.\n", errout_str());
check(code);
ASSERT_EQUALS("", errout_str());
}
check("void f()\n"
"{\n"
" std::list<int> x;\n"
" fun(x.size());\n"
"}");
ASSERT_EQUALS("", errout_str());
{
const char code[] ="void f()\n"
"{\n"
" std::list<int> x;\n"
" fun(!x.size());\n"
"}";
check(code, false, Standards::CPP03);
ASSERT_EQUALS("[test.cpp:4]: (performance) Possible inefficient checking for 'x' emptiness.\n", errout_str());
check(code);
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "void f()\n"
"{\n"
" std::list<int> x;\n"
" fun(a && x.size());\n"
"}";
check(code, false, Standards::CPP03);
ASSERT_EQUALS("[test.cpp:4]: (performance) Possible inefficient checking for 'x' emptiness.\n", errout_str());
check(code);
ASSERT_EQUALS("", errout_str());
}
check("void f() {\n" // #4039
" std::list<int> x;\n"
" fun(width % x.size() != 0);\n"
"}");
ASSERT_EQUALS("", errout_str());
// #4584
check("void f() {\n"
" std::list<int> x;\n"
" if (foo + 1 > x.size()) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" std::list<int> x;\n"
" if (x.size() < 1 + foo) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void size2() {
const char code[] = "struct Fred {\n"
" std::list<int> x;\n"
"};\n"
"struct Wilma {\n"
" Fred f;\n"
" void foo();\n"
"};\n"
"void Wilma::foo()\n"
"{\n"
" if (f.x.size() == 0) {}\n"
"}";
check(code, false, Standards::CPP03);
ASSERT_EQUALS(
"[test.cpp:10]: (performance) Possible inefficient checking for 'x' emptiness.\n"
"[test.cpp:10]: (performance) Possible inefficient checking for 'x' emptiness.\n", // duplicate
errout_str());
check(code);
ASSERT_EQUALS("", errout_str());
}
void size3() {
{
const char code[] = "namespace N {\n"
" class Zzz {\n"
" public:\n"
" std::list<int> x;\n"
" };\n"
"}\n"
"using namespace N;\n"
"Zzz * zzz;\n"
"int main() {\n"
" if (zzz->x.size() > 0) { }\n"
"}";
check(code, false, Standards::CPP03);
ASSERT_EQUALS(
"[test.cpp:10]: (performance) Possible inefficient checking for 'x' emptiness.\n"
"[test.cpp:10]: (performance) Possible inefficient checking for 'x' emptiness.\n", // duplicate
errout_str());
}
{
const char code[] = "namespace N {\n"
" class Zzz {\n"
" public:\n"
" std::list<int> x;\n"
" };\n"
"}\n"
"using namespace N;\n"
"int main() {\n"
" Zzz * zzz;\n"
" if (zzz->x.size() > 0) { }\n"
"}";
check(code, false, Standards::CPP03);
ASSERT_EQUALS(
"[test.cpp:10]: (performance) Possible inefficient checking for 'x' emptiness.\n"
"[test.cpp:10]: (performance) Possible inefficient checking for 'x' emptiness.\n", // duplicate
errout_str());
check(code);
ASSERT_EQUALS("", errout_str());
}
}
void size4() { // #2652 - don't warn about vector/deque
check("void f(std::vector<int> &v) {\n"
" if (v.size() > 0U) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(std::deque<int> &v) {\n"
" if (v.size() > 0U) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(std::array<int,3> &a) {\n"
" if (a.size() > 0U) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void redundantCondition1() {
check("void f(string haystack)\n"
"{\n"
" if (haystack.find(needle) != haystack.end())\n"
" haystack.remove(needle);"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Redundant checking of STL container element existence before removing it.\n", errout_str());
}
void missingInnerComparison1() {
check("void f(std::set<int> &ints) {\n"
" for (std::set<int>::iterator it = ints.begin(); it != ints.end(); ++it) {\n"
" if (a) {\n"
" it++;\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:2]: (warning) Missing bounds check for extra iterator increment in loop.\n", errout_str());
check("void f(std::map<int,int> &ints) {\n"
" for (std::map<int,int>::iterator it = ints.begin(); it != ints.end(); ++it) {\n"
" ++it->second;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(const std::vector<std::string> &v) {\n"
" for(std::vector<std::string>::const_iterator it = v.begin(); it != v.end(); ++it) {\n"
" if(it+2 != v.end())\n"
" {\n"
" ++it;\n"
" ++it;\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void missingInnerComparison2() {
check("void f(std::set<int> &ints) {\n"
" for (std::set<int>::iterator it = ints.begin(); it != ints.end(); ++it) {\n"
" if (a) {\n"
" it++;\n"
" if (it == ints.end())\n"
" return;\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void missingInnerComparison3() {
check("void f(std::set<int> &ints) {\n"
" for (std::set<int>::iterator it = ints.begin(); it != ints.end(); ++it) {\n"
" for (std::set<int>::iterator it = ints2.begin(); it != ints2.end(); ++it)\n"
" { }\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void missingInnerComparison4() {
check("function f1(std::list<int> &l1) {\n"
" for(std::list<int>::iterator i = l1.begin(); i != l1.end(); i++) {\n"
" if (*i == 44) {\n"
" l1.insert(++i, 55);\n"
" break;\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Consider using std::find_if algorithm instead of a raw loop.\n", errout_str());
check("function f1(std::list<int> &l1) {\n"
" for(std::list<int>::iterator i = l1.begin(); i != l1.end(); i++) {\n"
" if (*i == 44) {\n"
" l1.insert(++i, 55);\n"
" return;\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Consider using std::find_if algorithm instead of a raw loop.\n", errout_str());
}
void missingInnerComparison5() {
check("void f() {\n"
" for(it = map1.begin(); it != map1.end(); it++) {\n"
" str[i++] = (*it).first;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void missingInnerComparison6() {
check("void f(std::string &s) {\n"
" for(string::iterator it = s.begin(); it != s.end(); it++) {\n"
" it = s.insert(++it, 0);\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void cstr() {
check("void f() {\n"
" std::string errmsg;\n"
" throw errmsg.c_str();\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Dangerous usage of c_str(). The value returned by c_str() is invalid after throwing exception.\n", errout_str());
check("const char *get_msg() {\n"
" std::string errmsg;\n"
" return errmsg.c_str();\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Dangerous usage of c_str(). The value returned by c_str() is invalid after this call.\n", errout_str());
check("const char *get_msg() {\n"
" std::ostringstream errmsg;\n"
" return errmsg.str().c_str();\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Dangerous usage of c_str(). The value returned by c_str() is invalid after this call.\n", errout_str());
check("const char *get_msg() {\n"
" std::string errmsg;\n"
" return std::string(\"ERROR: \" + errmsg).c_str();\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Dangerous usage of c_str(). The value returned by c_str() is invalid after this call.\n", errout_str());
check("const char *get_msg() {\n"
" std::string errmsg;\n"
" return (\"ERROR: \" + errmsg).c_str();\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Dangerous usage of c_str(). The value returned by c_str() is invalid after this call.\n", errout_str());
check("const char *get_msg() {\n"
" std::string errmsg;\n"
" return (\"ERROR: \" + std::string(\"crash me\")).c_str();\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Dangerous usage of c_str(). The value returned by c_str() is invalid after this call.\n", errout_str());
check("void f() {\n"
" std::ostringstream errmsg;\n"
" const char *c = errmsg.str().c_str();\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Dangerous usage of c_str(). The value returned by c_str() is invalid after this call.\n", errout_str());
check("std::string f();\n"
"\n"
"void foo() {\n"
" const char *c = f().c_str();\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Dangerous usage of c_str(). The value returned by c_str() is invalid after this call.\n", errout_str());
check("class Foo {\n"
" const char *f();\n"
"};\n"
"const char *Foo::f() {\n"
" std::string s;\n"
" return s.c_str();\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Dangerous usage of c_str(). The value returned by c_str() is invalid after this call.\n", errout_str());
check("class Foo {\n"
" std::string GetVal() const;\n"
"};\n"
"const char *f() {\n"
" Foo f;\n"
" return f.GetVal().c_str();\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Dangerous usage of c_str(). The value returned by c_str() is invalid after this call.\n", errout_str());
check("const char* foo() {\n"
" static std::string text;\n"
" text = \"hello world\\n\";\n"
" return text.c_str();\n"
"}");
ASSERT_EQUALS("", errout_str()); // #3427
// Implicit conversion back to std::string
check("std::string get_msg() {\n"
" std::string errmsg;\n"
" return errmsg.c_str();\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (performance) Returning the result of c_str() in a function that returns std::string is slow and redundant.\n", errout_str());
check("const std::string& get_msg() {\n"
" std::string errmsg;\n"
" return errmsg.c_str();\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (performance) Returning the result of c_str() in a function that returns std::string is slow and redundant.\n", errout_str());
check("class Foo {\n"
" std::string GetVal() const;\n"
"};\n"
"std::string f() {\n"
" Foo f;\n"
" return f.GetVal().c_str();\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (performance) Returning the result of c_str() in a function that returns std::string is slow and redundant.\n", errout_str());
check("std::string get_msg() {\n"
" std::string errmsg;\n"
" return errmsg;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("std::string get_msg() {\n" // #3678
" MyStringClass errmsg;\n"
" return errmsg.c_str();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void Foo1(const std::string& str) {}\n"
"void Foo2(const char* c, const std::string str) {}\n"
"void Foo3(std::string& rstr) {}\n"
"void Foo4(std::string str, const std::string& str) {}\n"
"void Bar() {\n"
" std::string str = \"bar\";\n"
" std::stringstream ss(\"foo\");\n"
" Foo1(str);\n"
" Foo1(str.c_str());\n"
" Foo2(str.c_str(), str);\n"
" Foo2(str.c_str(), str.c_str());\n"
" Foo3(str.c_str());\n"
" Foo4(str, str);\n"
" Foo4(str.c_str(), str);\n"
" Foo4(str, str.c_str());\n"
" Foo4(ss.str(), ss.str().c_str());\n"
" Foo4(str.c_str(), str.c_str());\n"
"}");
ASSERT_EQUALS("[test.cpp:9]: (performance) Passing the result of c_str() to a function that takes std::string as argument no. 1 is slow and redundant.\n"
"[test.cpp:11]: (performance) Passing the result of c_str() to a function that takes std::string as argument no. 2 is slow and redundant.\n"
"[test.cpp:14]: (performance) Passing the result of c_str() to a function that takes std::string as argument no. 1 is slow and redundant.\n"
"[test.cpp:15]: (performance) Passing the result of c_str() to a function that takes std::string as argument no. 2 is slow and redundant.\n"
"[test.cpp:16]: (performance) Passing the result of c_str() to a function that takes std::string as argument no. 2 is slow and redundant.\n"
"[test.cpp:17]: (performance) Passing the result of c_str() to a function that takes std::string as argument no. 1 is slow and redundant.\n"
"[test.cpp:17]: (performance) Passing the result of c_str() to a function that takes std::string as argument no. 2 is slow and redundant.\n", errout_str());
check("void Foo1(const std::string& str) {}\n"
"void Foo2(char* c, const std::string str) {}\n"
"void Bar() {\n"
" std::string str = \"bar\";\n"
" Foo1(str, foo);\n" // Don't crash
" Foo2(str.c_str());\n" // Don't crash
"}");
ASSERT_EQUALS("", errout_str());
check("struct Foo {\n"
" void func(std::string str) const {}\n"
" static void sfunc(std::string str) {}\n"
"};\n"
"void func(std::string str) {}\n"
"void Bar() {\n"
" std::string str = \"bar\";\n"
" Foo foo;\n"
" func(str.c_str());\n"
" Foo::sfunc(str.c_str());\n"
" foo.func(str.c_str());\n"
"}");
ASSERT_EQUALS("[test.cpp:9]: (performance) Passing the result of c_str() to a function that takes std::string as argument no. 1 is slow and redundant.\n"
"[test.cpp:10]: (performance) Passing the result of c_str() to a function that takes std::string as argument no. 1 is slow and redundant.\n"
"[test.cpp:11]: (performance) Passing the result of c_str() to a function that takes std::string as argument no. 1 is slow and redundant.\n",
errout_str());
check("void f(const std::string& s);\n" // #8336
"struct T {\n"
" std::string g();\n"
" std::string a[1];\n"
" struct U { std::string s; } u;"
"};\n"
"namespace N { namespace O { std::string s; } }\n"
"void g(const std::vector<std::string>& v, T& t) {\n"
" for (std::vector<std::string>::const_iterator it = v.begin(); it != v.end(); ++it)\n"
" f(it->c_str());\n"
" f(v.begin()->c_str());\n"
" f(t.g().c_str());\n"
" f(t.a[0].c_str());\n"
" f(t.u.s.c_str());\n"
" f(N::O::s.c_str());\n"
"}\n");
ASSERT_EQUALS("[test.cpp:9]: (performance) Passing the result of c_str() to a function that takes std::string as argument no. 1 is slow and redundant.\n"
"[test.cpp:10]: (performance) Passing the result of c_str() to a function that takes std::string as argument no. 1 is slow and redundant.\n"
"[test.cpp:11]: (performance) Passing the result of c_str() to a function that takes std::string as argument no. 1 is slow and redundant.\n"
"[test.cpp:12]: (performance) Passing the result of c_str() to a function that takes std::string as argument no. 1 is slow and redundant.\n"
"[test.cpp:13]: (performance) Passing the result of c_str() to a function that takes std::string as argument no. 1 is slow and redundant.\n"
"[test.cpp:14]: (performance) Passing the result of c_str() to a function that takes std::string as argument no. 1 is slow and redundant.\n",
errout_str());
check("void svgFile(const std::string &content, const std::string &fileName, const double end = 1000., const double start = 0.);\n"
"void Bar(std::string filename) {\n"
" std::string str = \"bar\";\n"
" std::ofstream svgFile(filename.c_str(), std::ios::trunc);\n"
" svgFile << \"test\";\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void Foo(const char* p) {}\n"
"void Foo(const std::string& str) {Foo(str.c_str());}\n" // Overloaded
"void Bar() {\n"
" std::string str = \"bar\";\n"
" Foo(str);\n"
" Foo(str.c_str());\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int atoi(const std::string& str) {\n" // #3729: Don't suggest recursive call
" return atoi(str.c_str());\n"
"}");
ASSERT_EQUALS("", errout_str());
check("std::string hello()\n"
"{\n"
" return \"hello\";\n"
"}\n"
"\n"
"const char *f()\n"
"{\n"
" return hello().c_str();\n"
"}");
ASSERT_EQUALS("[test.cpp:8]: (error) Dangerous usage of c_str(). The value returned by c_str() is invalid after this call.\n", errout_str());
check("class Fred {\n"
" std::string hello();\n"
" const char *f();\n"
"};\n"
"std::string Fred::hello()\n"
"{\n"
" return \"hello\";\n"
"}\n"
"const char *Fred::f()\n"
"{\n"
" return hello().c_str();\n"
"}");
ASSERT_EQUALS("[test.cpp:11]: (error) Dangerous usage of c_str(). The value returned by c_str() is invalid after this call.\n", errout_str());
// #4183 - using MyStringClass.c_str()
check("void a(const std::string &str);\n"
"\n"
"void b() {\n"
" MyStringClass s;\n"
" a(s.c_str());\n"
"}");
ASSERT_EQUALS("", errout_str());
check("std::string Format(const char * name) {\n" // #4938
" return String::Format(\"%s:\", name).c_str();\n"
"}");
ASSERT_EQUALS("", errout_str());
// #7480
check("struct InternalMapInfo {\n"
" std::string author;\n"
"};\n"
"const char* GetMapAuthor(int index) {\n"
" const InternalMapInfo* mapInfo = &internal_getMapInfo;\n"
" return mapInfo->author.c_str();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct InternalMapInfo {\n"
" std::string author;\n"
"};\n"
"std::string GetMapAuthor(int index) {\n"
" const InternalMapInfo* mapInfo = &internal_getMapInfo;\n"
" return mapInfo->author.c_str();\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (performance) Returning the result of c_str() in a function that returns std::string is slow and redundant.\n", errout_str());
check("struct InternalMapInfo {\n"
" std::string author;\n"
"};\n"
"const char* GetMapAuthor(int index) {\n"
" const InternalMapInfo mapInfo = internal_getMapInfo;\n"
" return mapInfo.author.c_str();\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Dangerous usage of c_str(). The value returned by c_str() is invalid after this call.\n", errout_str());
check("struct S {\n" // #7656
" std::string data;\n"
"};\n"
"const S& getS();\n"
"const char* test() {\n"
" const struct S &s = getS();\n"
" return s.data.c_str();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct S {\n" // #7930
" std::string data;\n"
"};\n"
"const char* test() {\n"
" S s;\n"
" std::string &ref = s.data;\n"
" return ref.c_str();\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (error) Dangerous usage of c_str(). The value returned by c_str() is invalid after this call.\n", errout_str());
check("void f(const wchar_t* w, int i = 0, ...);\n" // #10357
"void f(const std::string& s, int i = 0);\n"
"void g(const std::wstring& p) {\n"
" f(p.c_str());\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct S {\n" //#9161
" const char* f() const noexcept {\n"
" return (\"\" + m).c_str();\n"
" }\n"
" std::string m;\n"
"};\n", /*inconclusive*/ true);
ASSERT_EQUALS("[test.cpp:3]: (error) Dangerous usage of c_str(). The value returned by c_str() is invalid after this call.\n", errout_str());
check("struct S {\n" // #10493
" void f(const char** pp);\n"
" std::string s;\n"
"};\n"
"void S::f(const char** pp) {\n"
" try {\n"
" *pp = member.c_str();\n"
" }\n"
" catch (...) {\n"
" s = \"xyz\";\n"
" *pp = member.c_str();\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("std::string f(const std::string& a) {\n"
" std::string b(a.c_str());\n"
" return b;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (performance) Constructing a std::string from the result of c_str() is slow and redundant.\n", errout_str());
check("std::string f(const std::string& a) {\n"
" std::string b{ a.c_str() };\n"
" return b;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (performance) Constructing a std::string from the result of c_str() is slow and redundant.\n", errout_str());
check("std::string f(const std::string& a) {\n"
" std::string b = a.c_str();\n"
" return b;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (performance) Assigning the result of c_str() to a std::string is slow and redundant.\n", errout_str());
check("std::string g(const std::string& a, const std::string& b) {\n"
" return a + b.c_str();\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (performance) Concatenating the result of c_str() and a std::string is slow and redundant.\n", errout_str());
check("std::string g(const std::string& a, const std::string& b) {\n"
" return a.c_str() + b;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (performance) Concatenating the result of c_str() and a std::string is slow and redundant.\n", errout_str());
check("std::vector<double> v;\n" // don't crash
"int i;\n"
"void f() {\n"
" const double* const QM_R__ buf(v.data() + i);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct T {\n" // #7515
" std::string g();\n"
" std::string a[1];\n"
" std::vector<std::string> v;\n"
"};\n"
"void f(std::stringstream& strm, const std::string& s, T& t) {\n"
" strm << s.c_str();\n"
" strm << \"abc\" << s.c_str();\n"
" strm << \"abc\" << s.c_str() << \"def\";\n"
" strm << \"abc\" << t.g().c_str() << \"def\";\n"
" strm << t.a[0].c_str();\n"
" strm << t.v.begin()->c_str();\n"
" auto it = t.v.begin()\n"
" strm << it->c_str();\n"
"}\n");
ASSERT_EQUALS("[test.cpp:7]: (performance) Passing the result of c_str() to a stream is slow and redundant.\n"
"[test.cpp:8]: (performance) Passing the result of c_str() to a stream is slow and redundant.\n"
"[test.cpp:9]: (performance) Passing the result of c_str() to a stream is slow and redundant.\n"
"[test.cpp:10]: (performance) Passing the result of c_str() to a stream is slow and redundant.\n"
"[test.cpp:11]: (performance) Passing the result of c_str() to a stream is slow and redundant.\n"
"[test.cpp:12]: (performance) Passing the result of c_str() to a stream is slow and redundant.\n"
"[test.cpp:14]: (performance) Passing the result of c_str() to a stream is slow and redundant.\n",
errout_str());
check("struct S { std::string str; };\n"
"struct T { S s; };\n"
"struct U { T t[1]; };\n"
"void f(const T& t, const U& u, std::string& str) {\n"
" if (str.empty())\n"
" str = t.s.str.c_str();\n"
" else\n"
" str = u.t[0].s.str.c_str();\n"
"}\n");
ASSERT_EQUALS("[test.cpp:6]: (performance) Assigning the result of c_str() to a std::string is slow and redundant.\n"
"[test.cpp:8]: (performance) Assigning the result of c_str() to a std::string is slow and redundant.\n",
errout_str());
check("void f(std::string_view);\n" // #11547
"void g(const std::string & s) {\n"
" f(s.c_str());\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (performance) Passing the result of c_str() to a function that takes std::string_view as argument no. 1 is slow and redundant.\n",
errout_str());
check("std::string_view f(const std::string& s) {\n"
" std::string_view sv = s.c_str();\n"
" return sv;\n"
"}\n"
"std::string_view g(const std::string& s) {\n"
" std::string_view sv{ s.c_str() };\n"
" return sv;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (performance) Assigning the result of c_str() to a std::string_view is slow and redundant.\n"
"[test.cpp:6]: (performance) Constructing a std::string_view from the result of c_str() is slow and redundant.\n",
errout_str());
check("void f(const std::string& s) {\n" // #11819
" std::string_view sv(s.data(), 13);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct S { std::string x; };\n" // #11802
"std::vector<std::shared_ptr<S>> global;\n"
"const char* f() {\n"
" auto s = std::make_shared<S>();\n"
" global.push_back(s);\n"
" return s->x.c_str();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void uselessCalls() {
check("void f()\n"
"{\n"
" string s1, s2;\n"
" s1.swap(s2);\n"
" s2.swap(s2);\n"
"};");
ASSERT_EQUALS("", errout_str());
check("void f()\n"
"{\n"
" std::string s1, s2;\n"
" s1.swap(s2);\n"
" s2.swap(s2);\n"
"};");
ASSERT_EQUALS("[test.cpp:5]: (performance) It is inefficient to swap a object with itself by calling 's2.swap(s2)'\n", errout_str());
check("void f()\n"
"{\n"
" std::string s1, s2;\n"
" s1.compare(s2);\n"
" s2.compare(s2);\n"
" s1.compare(s2.c_str());\n"
" s1.compare(0, s1.size(), s1);\n"
"};");
ASSERT_EQUALS("[test.cpp:5]: (warning) It is inefficient to call 's2.compare(s2)' as it always returns 0.\n", errout_str());
// #7370 False positive uselessCallsCompare on unknown type
check("class ReplayIteratorImpl{\n"
" int Compare(ReplayIteratorImpl* other) {\n"
" int cmp;\n"
" int ret = cursor_->compare(cursor_, other->cursor_, &cmp);\n"
" return (cmp);\n"
" }\n"
" WT_CURSOR *cursor_;\n"
"};");
ASSERT_EQUALS("", errout_str());
check("void f()\n"
"{\n"
" int x=1;\n"
" std::string s1, s2;\n"
" s1 = s1.substr();\n"
" s2 = s1.substr(x);\n"
" s1 = s2.substr(0, x);\n"
" s1 = s2.substr(0,std::string::npos);\n"
" s1 = s2.substr(x+5-n, 0);\n"
"};");
ASSERT_EQUALS("[test.cpp:5]: (performance) Ineffective call of function \'substr\' because it returns a copy of "
"the object. Use operator= instead.\n"
"[test.cpp:8]: (performance) Ineffective call of function \'substr\' because it returns a copy of "
"the object. Use operator= instead.\n"
"[test.cpp:9]: (performance) Ineffective call of function \'substr\' because it returns an empty string.\n", errout_str());
check("void f()\n"
"{\n"
" int x=1;\n"
" string s1, s2;\n"
" s1 = s1.substr();\n"
" s2 = s1.substr(x);\n"
" s1 = s2.substr(0, x);\n"
" s1 = s2.substr(0,std::string::npos);\n"
" s1 = s2.substr(x+5-n, 0);\n"
"};");
ASSERT_EQUALS("", errout_str());
check("int main()\n"
"{\n"
" std::string str = \"a1b1\";\n"
" return str.find(str[1], 2);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool foo(std::vector<int>& v) {\n"
" v.empty();\n"
" return v.empty();\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Ineffective call of function 'empty()'. Did you intend to call 'clear()' instead?\n", errout_str());
check("void f() {\n" // #4938
" OdString str;\n"
" str.empty();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n" // #4032
" const std::string greeting(\"Hello World !!!\");\n"
" const std::string::size_type npos = greeting.rfind(\" \");\n"
" if (npos != std::string::npos)\n"
" std::cout << greeting.substr(0, npos) << std::endl;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(std::vector<int> a) {\n"
" std::remove(a.begin(), a.end(), val);\n"
" std::remove_if(a.begin(), a.end(), val);\n"
" std::unique(a.begin(), a.end(), val);\n"
" x = std::remove(a.begin(), a.end(), val);\n"
" a.erase(std::remove(a.begin(), a.end(), val));\n"
" std::remove(\"foo.txt\");\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Return value of std::remove() ignored. Elements remain in container.\n"
"[test.cpp:3]: (warning) Return value of std::remove_if() ignored. Elements remain in container.\n"
"[test.cpp:4]: (warning) Return value of std::unique() ignored. Elements remain in container.\n", errout_str());
// #4431 - fp
check("bool f() {\n"
" return x ? true : (y.empty());\n"
"}");
ASSERT_EQUALS("", errout_str());
// #8360
check("void f(std::string s) {\n"
" for (;s.empty();) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
// #11166
check("std::string f(std::string s) {\n"
" s = s.substr(0, s.size() - 1);\n"
" return s;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (performance) Ineffective call of function 'substr' because a prefix of the string is assigned to itself. Use resize() or pop_back() instead.\n",
errout_str());
check("std::string f(std::string s, std::size_t start, std::size_t end, const std::string& i) {\n"
" s = s.substr(0, start) + i + s.substr(end + 1);\n"
" return s;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (performance) Ineffective call of function 'substr' because a prefix of the string is assigned to itself. Use replace() instead.\n",
errout_str());
check("std::string f(std::string s, std::size_t end) {\n"
" s = { s.begin(), s.begin() + end };\n"
" return s;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (performance) Inefficient constructor call: container 's' is assigned a partial copy of itself. Use erase() or resize() instead.\n",
errout_str());
check("std::list<int> f(std::list<int> l, std::size_t end) {\n"
" l = { l.begin(), l.begin() + end };\n"
" return l;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (performance) Inefficient constructor call: container 'l' is assigned a partial copy of itself. Use erase() or resize() instead.\n",
errout_str());
check("std::string f(std::string s, std::size_t end) {\n"
" s = std::string{ s.begin(), s.begin() + end };\n"
" return s;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (performance) Inefficient constructor call: container 's' is assigned a partial copy of itself. Use erase() or resize() instead.\n",
errout_str());
check("std::string f(std::string s, std::size_t end) {\n"
" s = std::string(s.begin(), s.begin() + end);\n"
" return s;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (performance) Inefficient constructor call: container 's' is assigned a partial copy of itself. Use erase() or resize() instead.\n",
errout_str());
check("std::vector<int> f(std::vector<int> v, std::size_t end) {\n"
" v = std::vector<int>(v.begin(), v.begin() + end);\n"
" return v;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (performance) Inefficient constructor call: container 'v' is assigned a partial copy of itself. Use erase() or resize() instead.\n",
errout_str());
}
void stabilityOfChecks() {
// Stability test: 4684 cppcheck crash in template function call.
check("template<class T>\n"
"class EffectivityRangeData {};\n"
"template<class T>\n"
"class EffectivityRange {\n"
" void unite() {\n"
" x < vector < EffectivityRangeData<int >> >();\n"
" EffectivityRange<int> er;\n"
" }\n"
" void shift() { EffectivityRangeData<int>::iterator it; }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void dereferenceInvalidIterator() {
// Test simplest "if" with && case
check("void foo(std::string::iterator& i) {\n"
" if (std::isalpha(*i) && i != str.end()) {\n"
" std::cout << *i;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Possible dereference of an invalid iterator: i\n", errout_str());
check("void foo(std::string::iterator& i) {\n"
" if(foo) { bar(); }\n"
" else if (std::isalpha(*i) && i != str.end()) {\n"
" std::cout << *i;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Possible dereference of an invalid iterator: i\n", errout_str());
// Test suggested correction doesn't report an error
check("void foo(std::string::iterator& i) {\n"
" if (i != str.end() && std::isalpha(*i)) {\n"
" std::cout << *i;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// Test "while" with "&&" case
check("void foo(std::string::iterator& i) {\n"
" while (std::isalpha(*i) && i != str.end()) {\n"
" std::cout << *i;\n"
" i ++;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Possible dereference of an invalid iterator: i\n", errout_str());
check("void foo(std::string::iterator& i) {\n"
" do {\n"
" std::cout << *i;\n"
" i ++;\n"
" } while (std::isalpha(*i) && i != str.end());\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (warning) Possible dereference of an invalid iterator: i\n", errout_str());
// Test "while" with "||" case
check("void foo(std::string::iterator& i) {\n"
" while (!(!std::isalpha(*i) || i == str.end())) {\n"
" std::cout << *i;\n"
" i ++;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Possible dereference of an invalid iterator: i\n", errout_str());
// Test fix for "while" with "||" case
check("void foo(std::string::iterator& i) {\n"
" while (!(i == str.end() || !std::isalpha(*i))) {\n"
" std::cout << *i;\n"
" i ++;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// Test "for" with "&&" case
check("void foo(std::string::iterator& i) {\n"
" for (; std::isalpha(*i) && i != str.end() ;) {\n"
" std::cout << *i;\n"
" i ++;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Possible dereference of an invalid iterator: i\n", errout_str());
// Test "for" with "||" case
check("void foo(std::string::iterator& i) {\n"
" for (; std::isalpha(*i) || i == str.end() ;) {\n"
" std::cout << *i;\n"
" i ++;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Possible dereference of an invalid iterator: i\n", errout_str());
// Test that a dereference outside the condition part of a "for"
// loop does not result in a false positive
check("void foo(std::string::iterator& i) {\n"
" for (char c = *i; isRunning && i != str.end() ;) {\n"
" std::cout << c;\n"
" i ++;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// Test that other "&&" terms in the condition don't invalidate the check
check("void foo(char* c, std::string::iterator& i) {\n"
" if (*c && std::isalpha(*i) && i != str.end()) {\n"
" std::cout << *i;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Possible dereference of an invalid iterator: i\n", errout_str());
// Test that dereference of different variable doesn't trigger a false positive
check("void foo(const char* c, std::string::iterator& i) {\n"
" if (std::isalpha(*c) && i != str.end()) {\n"
" std::cout << *c;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// Test case involving "rend()" instead of "end()"
check("void foo(std::string::iterator& i) {\n"
" while (std::isalpha(*i) && i != str.rend()) {\n"
" std::cout << *i;\n"
" i ++;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Possible dereference of an invalid iterator: i\n", errout_str());
// Test that mixed "&&" and "||" don't result in a false positive
check("void foo(std::string::iterator& i) {\n"
" if ((i == str.end() || *i) || (isFoo() && i != str.end())) {\n"
" std::cout << \"foo\";\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" std::vector <int> v;\n"
" std::vector <int>::iterator i = v.end();\n"
" *i=0;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (error) Dereference of an invalid iterator: i\n", errout_str());
check("void f() {\n"
" std::vector <int> v;\n"
" std::vector <int>::iterator i = std::end(v);\n"
" *i=0;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (error) Dereference of an invalid iterator: i\n", errout_str());
check("void f(std::vector <int> v) {\n"
" std::vector <int>::iterator i = v.end();\n"
" *i=0;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Dereference of an invalid iterator: i\n", errout_str());
check("void f(std::vector <int> v) {\n"
" std::vector <int>::iterator i = v.end();\n"
" *(i+1)=0;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Dereference of an invalid iterator: i+1\n", errout_str());
check("void f(std::vector <int> v) {\n"
" std::vector <int>::iterator i = v.end();\n"
" *(i-1)=0;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(std::vector <int> v) {\n"
" std::vector <int>::iterator i = v.begin();\n"
" *(i-1)=0;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Dereference of an invalid iterator: i-1\n", errout_str());
check("void f(std::vector <int> v) {\n"
" std::vector <int>::iterator i = std::begin(v);\n"
" *(i-1)=0;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Dereference of an invalid iterator: i-1\n", errout_str());
check("void f(std::vector <int> v, bool b) {\n"
" std::vector <int>::iterator i = v.begin();\n"
" if (b)\n"
" i = v.end();\n"
" *i=0;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5]: (warning) Possible dereference of an invalid iterator: i\n", errout_str());
check("void f(std::vector <int> v, bool b) {\n"
" std::vector <int>::iterator i = v.begin();\n"
" if (b)\n"
" i = v.end();\n"
" *(i+1)=0;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5]: (warning) Possible dereference of an invalid iterator: i+1\n", errout_str());
check("void f(std::vector <int> v, bool b) {\n"
" std::vector <int>::iterator i = v.begin();\n"
" if (b)\n"
" i = v.end();\n"
" *(i-1)=0;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5]: (warning) Possible dereference of an invalid iterator: i-1\n", errout_str());
check("int f(std::vector<int> v, int pos) {\n"
" if (pos >= 0)\n"
" return *(v.begin() + pos);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("int f(std::vector<int> v, int i) {\n"
" auto it = std::find(v.begin(), v.end(), i);\n"
" if (it != v.end()) {}\n"
" return *it;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (warning) Either the condition 'it!=v.end()' is redundant or there is possible dereference of an invalid iterator: it.\n", errout_str());
check("void f(std::vector<int> & v) {\n"
" std::vector<int>::iterator i= v.begin();\n"
" if(i == v.end() && *(i+1) == *i) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:3]: (warning) Either the condition 'i==v.end()' is redundant or there is possible dereference of an invalid iterator: i+1.\n"
"[test.cpp:3] -> [test.cpp:3]: (warning) Either the condition 'i==v.end()' is redundant or there is possible dereference of an invalid iterator: i.\n", errout_str());
check("void f(std::vector<int> & v) {\n"
" std::vector<int>::iterator i= v.begin();\n"
" if(i == v.end() && *i == *(i+1)) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:3]: (warning) Either the condition 'i==v.end()' is redundant or there is possible dereference of an invalid iterator: i.\n"
"[test.cpp:3] -> [test.cpp:3]: (warning) Either the condition 'i==v.end()' is redundant or there is possible dereference of an invalid iterator: i+1.\n", errout_str());
check("void f(std::vector<int> & v) {\n"
" std::vector<int>::iterator i= v.begin();\n"
" if(i != v.end() && *i == *(i+1)) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:3]: (warning) Either the condition 'i!=v.end()' is redundant or there is possible dereference of an invalid iterator: i+1.\n", errout_str());
check("void f(std::vector<int> & v) {\n"
" std::vector<int>::iterator i= v.begin();\n"
" if(i != v.end()) {\n"
" if (*(i+1) == *i) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (warning) Either the condition 'i!=v.end()' is redundant or there is possible dereference of an invalid iterator: i+1.\n", errout_str());
check("void f(std::vector<int> & v) {\n"
" std::vector<int>::iterator i= v.begin();\n"
" if(i == v.end()) { return; }\n"
" if (*(i+1) == *i) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (warning) Either the condition 'i==v.end()' is redundant or there is possible dereference of an invalid iterator: i+1.\n", errout_str());
check("void f(std::vector<int> & v) {\n"
" std::vector<int>::iterator i= v.begin();\n"
" if(i != v.end() && (i+1) != v.end() && *(i+1) == *i) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(std::string s) {\n"
" for (std::string::const_iterator i = s.begin(); i != s.end(); ++i) {\n"
" if (i != s.end() && (i + 1) != s.end() && *(i + 1) == *i) {\n"
" if (!isalpha(*(i + 2))) {\n"
" std::string modifier;\n"
" modifier += *i;\n"
" modifier += *(i + 1);\n"
" }\n"
" }\n"
" }\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (warning) Either the condition '(i+1)!=s.end()' is redundant or there is possible dereference of an invalid iterator: i+2.\n", errout_str());
check("void f(int v, std::map<int, int> &items) {\n"
" for (auto it = items.begin(); it != items.end();)\n"
" (it->first == v) ? it = items.erase(it) : ++it;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(std::string s) {\n"
" for (std::string::const_iterator i = s.begin(); i != s.end(); ++i) {\n"
" if (i != s.end() && (i + 1) != s.end() && *(i + 1) == *i) {\n"
" if ((i + 2) != s.end() && !isalpha(*(i + 2))) {\n"
" std::string modifier;\n"
" modifier += *i;\n"
" modifier += *(i + 1);\n"
" }\n"
" }\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("int f(std::vector<int>::iterator it, const std::vector<int>& vector) {\n"
" if (!(it != vector.end() && it != vector.begin()))\n"
" throw std::out_of_range();\n"
" if (it != vector.end() && *it == 0)\n"
" return -1;\n"
" return *it;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("int f(std::vector<int> &vect) {\n"
" const int &v = *vect.emplace(vect.end());\n"
" return v;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("extern bool bar(int);\n"
"void f(std::vector<int> & v) {\n"
" std::vector<int>::iterator i= v.begin();\n"
" if(i == v.end() && bar(*(i+1)) ) {}\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:4] -> [test.cpp:4]: (warning) Either the condition 'i==v.end()' is redundant or there is possible dereference of an invalid iterator: i+1.\n",
errout_str());
// #10657
check("std::list<int> mValues;\n"
"typedef std::list<int>::iterator ValueIterator;\n"
"void foo(ValueIterator beginValue, ValueIterator endValue) {\n"
" ValueIterator prevValue = beginValue;\n"
" ValueIterator curValue = beginValue;\n"
" for (++curValue; prevValue != endValue && curValue != mValues.end(); ++curValue) {\n"
" a = bar(*curValue);\n"
" prevValue = curValue;\n"
" }\n"
" if (endValue == mValues.end()) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #10642
check("int f(std::vector<int> v) {\n"
" return *(v.begin() + v.size() - 1);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #10716
check("struct a;\n"
"class b {\n"
" void c(std::map<std::string, a *> &);\n"
" std::string d;\n"
" std::map<std::string, std::set<std::string>> e;\n"
"};\n"
"void b::c(std::map<std::string, a *> &) {\n"
" e.clear();\n"
" auto f = *e[d].begin();\n"
"}\n");
ASSERT_EQUALS("[test.cpp:9]: (error) Out of bounds access in expression 'e[d].begin()' because 'e[d]' is empty.\n",
errout_str());
// #10151
check("std::set<int>::iterator f(std::set<int>& s) {\n"
"for (auto it = s.begin(); it != s.end(); ++it)\n"
" if (*it == 42)\n"
" return s.erase(it);\n"
" return s.end();\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) Consider using std::find_if algorithm instead of a raw loop.\n", errout_str());
// #11381
check("int f(std::map<int, int>& map) {\n"
" auto it = map.find(1);\n"
" if (it == map.end()) {\n"
" bool bInserted;\n"
" std::tie(it, bInserted) = map.emplace(1, 42);\n"
" }\n"
" return debug_valueflow(it)->second;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #11557
check("bool f(const std::vector<int*>& v, std::vector<int*>::iterator it, bool b) {\n"
" if (it == v.end())\n"
" return false;\n"
" if (b && ((it + 1) == v.end() || (*(it + 1)) != nullptr))\n"
" return false;\n"
" return true;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #6925
check("void f(const std::string& s, std::string::iterator i) {\n"
" if (i != s.end() && *(i + 1) == *i) {\n"
" if (i + 1 != s.end()) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:2]: (warning) Either the condition 'i+1!=s.end()' is redundant or there is possible dereference of an invalid iterator: i+1.\n",
errout_str());
check("void f(bool b, std::vector<std::string> v) {\n" // #12680
" if (!v.empty()) {\n"
" auto it = v.begin();\n"
" if (b) {\n"
" v.clear();\n"
" it = v.begin();\n"
" }\n"
" for (++it; it != v.end(); ++it) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str()); // don't crash
check("void f(int);\n" // #13064
"void g() {\n"
" std::vector<int> v{ 0 };\n"
" auto it = std::find(v.begin(), v.end(), 0);\n"
" if (it == v.end()) {\n"
" f({});\n"
" it = v.begin();\n"
" }\n"
" *it;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("int g() {\n" // #13332
" const std::vector<int> v = { 1, 2, 3, 4 };\n"
" const std::vector<int>::const_iterator a[2] = { v.begin(), v.end() };\n"
" return *a[0];\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void dereferenceInvalidIterator2() {
// Self-implemented iterator class
check("class iterator {\n"
"public:\n"
" CCommitPointer m_ptr;\n"
" iterator() {}\n"
" CCommitPointer& operator*() {\n"
" return m_ptr;\n"
" }\n"
" CCommitPointer* operator->() {\n"
" return &m_ptr;\n"
" }\n"
" iterator& operator++() {\n"
" ++m_ptr.m_place;\n"
" return *this;\n"
" }\n"
" };\n"
" iterator begin() {\n"
" iterator it;\n"
" it->m_place = 0;\n"
" return it;\n"
"}\n", true);
ASSERT_EQUALS("[test.cpp:18]: (error, inconclusive) Invalid iterator 'it' used.\n", errout_str());
}
void loopAlgoElementAssign() {
check("void foo() {\n"
" for(int& x:v)\n"
" x = 1;\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:3]: (style) Consider using std::fill algorithm instead of a raw loop.\n", errout_str());
check("void foo() {\n"
" for(int& x:v)\n"
" x = x + 1;\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:3]: (style) Consider using std::transform algorithm instead of a raw loop.\n", errout_str());
check("void foo(int a, int b) {\n"
" for(int& x:v)\n"
" x = a + b;\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:3]: (style) Consider using std::fill or std::generate algorithm instead of a raw loop.\n", errout_str());
check("void foo() {\n"
" for(int& x:v)\n"
" x += 1;\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:3]: (style) Consider using std::transform algorithm instead of a raw loop.\n", errout_str());
check("void foo() {\n"
" for(int& x:v)\n"
" x = f();\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:3]: (style) Consider using std::generate algorithm instead of a raw loop.\n", errout_str());
check("void foo() {\n"
" for(int& x:v) {\n"
" f();\n"
" x = 1;\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" for(int& x:v) {\n"
" x = 1;\n"
" f();\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
// There should probably be a message for unconditional break
check("void foo() {\n"
" for(int& x:v) {\n"
" x = 1;\n"
" break;\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" for(int& x:v)\n"
" x = ++x;\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
}
void loopAlgoAccumulateAssign() {
check("void foo() {\n"
" int n = 0;\n"
" for(int x:v)\n"
" n += x;\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:4]: (style) Consider using std::accumulate algorithm instead of a raw loop.\n", errout_str());
check("void foo() {\n"
" int n = 0;\n"
" for(int x:v)\n"
" n = n + x;\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:4]: (style) Consider using std::accumulate algorithm instead of a raw loop.\n", errout_str());
check("void foo() {\n"
" int n = 0;\n"
" for(int x:v)\n"
" n += 1;\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:4]: (style) Consider using std::distance algorithm instead of a raw loop.\n", errout_str());
check("void foo() {\n"
" int n = 0;\n"
" for(int x:v)\n"
" n = n + 1;\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:4]: (style) Consider using std::distance algorithm instead of a raw loop.\n", errout_str());
check("bool f(int);\n"
"void foo() {\n"
" bool b = false;\n"
" for(int x:v)\n"
" b &= f(x);\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("bool f(int);\n"
"void foo() {\n"
" bool b = false;\n"
" for(int x:v)\n"
" b |= f(x);\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("bool f(int);\n"
"void foo() {\n"
" bool b = false;\n"
" for(int x:v)\n"
" b = b && f(x);\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("bool f(int);\n"
"void foo() {\n"
" bool b = false;\n"
" for(int x:v)\n"
" b = b || f(x);\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" int n = 0;\n"
" for(int& x:v)\n"
" n = ++x;\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("std::size_t f(const std::map<std::string, std::size_t>& m) {\n" // #10412
" std::size_t t = 0;\n"
" for (std::map<std::string, std::size_t>::const_iterator i = m.begin(); i != m.end(); ++i) {\n"
" t += i->second;\n"
" }\n"
" for (std::map<std::string, std::size_t>::const_iterator i = m.begin(); i != m.end(); i++) {\n"
" t += i->second;\n"
" }\n"
" return t; \n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (style) Consider using std::accumulate algorithm instead of a raw loop.\n"
"[test.cpp:7]: (style) Consider using std::accumulate algorithm instead of a raw loop.\n",
errout_str());
check("int g(const std::vector<int>& v) {\n"
" int t = 0;\n"
" for (auto i = v.begin(); i != v.end(); ++i) {\n"
" t += *i;\n"
" }\n"
" return t;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (style) Consider using std::accumulate algorithm instead of a raw loop.\n", errout_str());
check("auto g(const std::vector<int>& v) {\n"
" std::vector<std::vector<int>::iterator> r;\n"
" for (auto i = v.begin(); i != v.end(); ++i) {\n"
" r.push_back(i);\n"
" }\n"
" return r;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("std::string f(std::vector<std::string> v) {\n"
" std::string ret;\n"
" for (const std::string& s : v)\n"
" ret += s + '\\n';\n"
" return ret;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("std::string f(const std::string& s) {\n"
" std::string ret;\n"
" for (char c : s)\n"
" if (c != ' ')\n"
" ret += i;\n"
" return ret;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("int f(const std::vector<int>& v) {\n"
" int sum = 0;\n"
" for (auto it = v.begin(); it != v.end(); it += 2)\n"
" sum += *it;\n"
" return sum;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void loopAlgoContainerInsert() {
check("void foo() {\n"
" std::vector<int> c;\n"
" for(int x:v)\n"
" c.push_back(x);\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:4]: (style) Consider using std::copy algorithm instead of a raw loop.\n", errout_str());
check("void foo() {\n"
" std::vector<int> c;\n"
" for(int x:v)\n"
" c.push_back(f(x));\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:4]: (style) Consider using std::transform algorithm instead of a raw loop.\n", errout_str());
check("void foo() {\n"
" std::vector<int> c;\n"
" for(int x:v)\n"
" c.push_back(x + 1);\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:4]: (style) Consider using std::transform algorithm instead of a raw loop.\n", errout_str());
check("void foo() {\n"
" std::vector<int> c;\n"
" for(int x:v)\n"
" c.push_front(x);\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:4]: (style) Consider using std::copy algorithm instead of a raw loop.\n", errout_str());
check("void foo() {\n"
" std::vector<int> c;\n"
" for(int x:v)\n"
" c.push_front(f(x));\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:4]: (style) Consider using std::transform algorithm instead of a raw loop.\n", errout_str());
check("void foo() {\n"
" std::vector<int> c;\n"
" for(int x:v)\n"
" c.push_front(x + 1);\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:4]: (style) Consider using std::transform algorithm instead of a raw loop.\n", errout_str());
check("void foo() {\n"
" std::vector<int> c;\n"
" for(int x:v)\n"
" c.push_back(v);\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" std::vector<int> c;\n"
" for(int x:v)\n"
" c.push_back(0);\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
}
void loopAlgoIncrement() {
check("void foo() {\n"
" int n = 0;\n"
" for(int x:v)\n"
" n++;\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:4]: (style) Consider using std::distance algorithm instead of a raw loop.\n", errout_str());
check("void foo() {\n"
" int n = 0;\n"
" for(int x:v)\n"
" ++n;\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:4]: (style) Consider using std::distance algorithm instead of a raw loop.\n", errout_str());
check("void foo() {\n"
" for(int& x:v)\n"
" x++;\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:3]: (style) Consider using std::transform algorithm instead of a raw loop.\n", errout_str());
check("void foo() {\n"
" for(int& x:v)\n"
" ++x;\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:3]: (style) Consider using std::transform algorithm instead of a raw loop.\n", errout_str());
}
void loopAlgoConditional() {
check("bool pred(int x);\n"
"void foo() {\n"
" for(int& x:v) {\n"
" if (pred(x)) {\n"
" x = 1;\n"
" }\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:5]: (style) Consider using std::replace_if algorithm instead of a raw loop.\n", errout_str());
check("bool pred(int x);\n"
"void foo() {\n"
" int n = 0;\n"
" for(int x:v) {\n"
" if (pred(x)) {\n"
" n += x;\n"
" }\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:6]: (style) Consider using std::accumulate algorithm instead of a raw loop.\n", errout_str());
check("bool pred(int x);\n"
"void foo() {\n"
" int n = 0;\n"
" for(int x:v) {\n"
" if (pred(x)) {\n"
" n += 1;\n"
" }\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:6]: (style) Consider using std::count_if algorithm instead of a raw loop.\n", errout_str());
check("bool pred(int x);\n"
"void foo() {\n"
" int n = 0;\n"
" for(int x:v) {\n"
" if (pred(x)) {\n"
" n++;\n"
" }\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:6]: (style) Consider using std::count_if algorithm instead of a raw loop.\n", errout_str());
check("bool pred(int x);\n"
"void foo() {\n"
" for(int& x:v) {\n"
" if (pred(x)) {\n"
" x = x + 1;\n"
" }\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:5]: (style) Consider using std::transform algorithm instead of a raw loop.\n", errout_str());
check("bool pred(int x);\n"
"void foo() {\n"
" std::vector<int> c;\n"
" for(int x:v) {\n"
" if (pred(x)) {\n"
" c.push_back(x);\n"
" }\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:6]: (style) Consider using std::copy_if algorithm instead of a raw loop.\n", errout_str());
check("bool pred(int x);\n"
"bool foo() {\n"
" for(int x:v) {\n"
" if (pred(x)) {\n"
" return false;\n"
" }\n"
" }\n"
" return true;\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:3]: (style) Consider using std::all_of or std::none_of algorithm instead of a raw loop.\n",
errout_str());
check("bool pred(int x);\n"
"bool foo() {\n"
" for(int x:v) {\n"
" if (pred(x)) {\n"
" break;\n"
" }\n"
" }\n"
" return true;\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:4]: (style) Consider using std::any_of algorithm instead of a raw loop.\n", errout_str());
check("bool pred(int x);\n"
"void f();\n"
"void foo() {\n"
" for(int x:v) {\n"
" if (pred(x)) {\n"
" f();\n"
" break;\n"
" }\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:5]: (style) Consider using std::any_of algorithm instead of a raw loop.\n", errout_str());
check("bool pred(int x);\n"
"void f(int x);\n"
"void foo() {\n"
" for(int x:v) {\n"
" if (pred(x)) {\n"
" f(x);\n"
" break;\n"
" }\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:5]: (style) Consider using std::find_if algorithm instead of a raw loop.\n", errout_str());
check("bool pred(int x);\n"
"bool foo() {\n"
" bool b = false;\n"
" for(int x:v) {\n"
" if (pred(x)) {\n"
" b = true;\n"
" }\n"
" }\n"
" if(b) {}\n"
" return true;\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("bool pred(int x);\n"
"bool foo() {\n"
" bool b = false;\n"
" for(int x:v) {\n"
" if (pred(x)) {\n"
" b |= true;\n"
" }\n"
" }\n"
" return true;\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("bool pred(int x);\n"
"bool foo() {\n"
" bool b = false;\n"
" for(int x:v) {\n"
" if (pred(x)) {\n"
" b &= true;\n"
" }\n"
" }\n"
" return true;\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("bool pred(int x);\n"
"bool foo() {\n"
" for(int x:v) {\n"
" if (pred(x)) {\n"
" return false;\n"
" }\n"
" return true;\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
// There is no transform_if
check("bool pred(int x);\n"
"void foo() {\n"
" std::vector<int> c;\n"
" for(int x:v) {\n"
" if (pred(x)) {\n"
" c.push_back(x + 1);\n"
" }\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("bool pred(int x);\n"
"void foo() {\n"
" for(int& x:v) {\n"
" x++;\n"
" if (pred(x)) {\n"
" x = 1;\n"
" }\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("bool pred(int x);\n"
"void f();\n"
"void foo() {\n"
" for(int x:v) {\n"
" if (pred(x)) {\n"
" if(x) { return; }\n"
" break;\n"
" }\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("bool g(int);\n"
"int f(const std::vector<int>& v) {\n"
" int ret = 0;\n"
" for (const auto i : v)\n"
" if (!g(i))\n"
" ret = 1;\n"
" return ret;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("int f(const std::vector<int>& v) {\n"
" int ret = 0;\n"
" for (const auto i : v)\n"
" if (i < 5)\n"
" ret = 1;\n"
" return ret;\n"
"}\n");
TODO_ASSERT_EQUALS("[test.cpp:5]: (style) Consider using std::any_of, std::all_of, std::none_of algorithm instead of a raw loop.\n",
"",
errout_str());
check("int f(const std::vector<int>& v) {\n"
" int ret = 0;\n"
" for (const auto i : v)\n"
" if (i < 5) {\n"
" ret = 1;\n"
" break;\n"
" }\n"
" return ret;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (style) Consider using std::any_of algorithm instead of a raw loop.\n", errout_str());
check("struct T {\n"
" std::vector<int> v0, v1;\n"
" void g();\n"
"};\n"
"void T::g() {\n"
" for (std::vector<int>::const_iterator it0 = v0.cbegin(); it0 != v0.cend(); ++it0) {\n"
" std::vector<int>::iterator it1;\n"
" for (it1 = v1.begin(); it1 != v1.end(); ++it1)\n"
" if (*it0 == *it1)\n"
" break;\n"
" if (it1 != v1.end())\n"
" v1.erase(it1);\n"
" }\n"
"}\n");
ASSERT_EQUALS("[test.cpp:9]: (style) Consider using std::find_if algorithm instead of a raw loop.\n", errout_str());
check("bool f(const std::set<std::string>& set, const std::string& f) {\n" // #11595
" for (const std::string& s : set) {\n"
" if (f.length() >= s.length() && f.compare(0, s.length(), s) == 0) {\n"
" return true;\n"
" }\n"
" }\n"
" return false;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Consider using std::any_of algorithm instead of a raw loop.\n",
errout_str());
check("void f() {\n" // #12064
" for (const auto& animal : { \"cat\", \"bat\", \"tiger\", \"rat\" })\n"
" if (std::strlen(animal) > 4)\n"
" throw 1;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void loopAlgoMinMax() {
check("void foo() {\n"
" int n = 0;\n"
" for(int x:v)\n"
" n = x > n ? x : n;\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:4]: (style) Consider using std::max_element algorithm instead of a raw loop.\n", errout_str());
check("void foo() {\n"
" int n = 0;\n"
" for(int x:v)\n"
" n = x < n ? x : n;\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:4]: (style) Consider using std::min_element algorithm instead of a raw loop.\n", errout_str());
check("void foo() {\n"
" int n = 0;\n"
" for(int x:v)\n"
" n = x > n ? n : x;\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:4]: (style) Consider using std::min_element algorithm instead of a raw loop.\n", errout_str());
check("void foo() {\n"
" int n = 0;\n"
" for(int x:v)\n"
" n = x < n ? n : x;\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:4]: (style) Consider using std::max_element algorithm instead of a raw loop.\n", errout_str());
check("void foo(int m) {\n"
" int n = 0;\n"
" for(int x:v)\n"
" n = x > m ? x : n;\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:4]: (style) Consider using std::accumulate algorithm instead of a raw loop.\n", errout_str());
check("void f(const std::vector<int>& v) {\n"
" int maxY = 0;\n"
" for (int y : v) {\n"
" if (y > maxY)\n"
" maxY = y;\n"
" }\n"
"}\n",
true);
TODO_ASSERT_EQUALS("[test.cpp:5]: (style) Consider using std::max_element algorithm instead of a raw loop.\n",
"",
errout_str());
}
void loopAlgoMultipleReturn()
{
check("bool f(const std::vector<int>& v) {\n"
" for (auto i : v) {\n"
" if (i < 0)\n"
" continue;\n"
" if (i)\n"
" return true;\n"
" }\n"
" return false;\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:2]: (style) Consider using std::any_of algorithm instead of a raw loop.\n",
errout_str());
check("bool g(const std::vector<int>& v) {\n"
" for (auto i : v) {\n"
" if (i % 5 == 0)\n"
" return true;\n"
" if (i % 7 == 0)\n"
" return true;\n"
" }\n"
" return false;\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:2]: (style) Consider using std::any_of algorithm instead of a raw loop.\n",
errout_str());
check("bool g(const std::vector<int>& v) {\n"
" for (auto i : v) {\n"
" if (i % 5 == 0)\n"
" return false;\n"
" if (i % 7 == 0)\n"
" return true;\n"
" }\n"
" return false;\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("bool g(std::vector<int>& v) {\n"
" for (auto& i : v) {\n"
" if (i % 5 == 0)\n"
" return false;\n"
" if (i % 7 == 0)\n"
" i++;\n"
" }\n"
" return false;\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("bool g(const std::vector<int>& v, int& j) {\n"
" for (auto i : v) {\n"
" if (i % 5 == 0)\n"
" return false;\n"
" if (i % 7 == 0)\n"
" j++;\n"
" }\n"
" return false;\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("bool g(const std::vector<int>& v, int& j) {\n"
" for (auto i : v) {\n"
" int& k = j;\n"
" if (i % 5 == 0)\n"
" return false;\n"
" if (i % 7 == 0)\n"
" k++;\n"
" }\n"
" return false;\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("bool g(const std::vector<int>& v, int& j) {\n"
" for (auto i : v) {\n"
" int* k = &j;\n"
" if (i % 5 == 0)\n"
" return false;\n"
" if (i % 7 == 0)\n"
" (*k)++;\n"
" }\n"
" return false;\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("bool g(const std::vector<int>& v, int j) {\n"
" for (auto i : v) {\n"
" int k = j;\n"
" if (i % 5 == 0)\n"
" return false;\n"
" if (i % 7 == 0)\n"
" k++;\n"
" }\n"
" return false;\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:2]: (style) Consider using std::all_of or std::none_of algorithm instead of a raw loop.\n",
errout_str());
check("class C {\n"
"private:\n"
" QString s;\n"
"public:\n"
" C(QString);\n"
"private:\n"
" void f() {\n"
" QVERIFY(QDir(s).exists());\n"
" }\n"
" void f(const QStringList& d) {\n"
" for (QString f : d)\n"
" QDir(s);\n"
" }\n"
"};\n",
true);
ASSERT_EQUALS("", errout_str());
}
void invalidContainer() {
check("void f(std::vector<int> &v) {\n"
" auto v0 = v.begin();\n"
" v.push_back(123);\n"
" std::cout << *v0 << std::endl;\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:2] -> [test.cpp:3] -> [test.cpp:1] -> [test.cpp:4]: (error) Using iterator to local container 'v' that may be invalid.\n", errout_str());
check("std::string e();\n"
"void a() {\n"
" std::vector<std::string> b;\n"
" for (std::vector<std::string>::const_iterator c; c != b.end(); ++c) {\n"
" std::string f = e();\n"
" std::string::const_iterator d = f.begin();\n"
" if (d != f.end()) {}\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("void f(std::vector<int> &v) {\n"
" int *v0 = &v[0];\n"
" v.push_back(123);\n"
" std::cout << (*v0)[0] << std::endl;\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:2] -> [test.cpp:3] -> [test.cpp:1] -> [test.cpp:4]: (error) Using pointer to local variable 'v' that may be invalid.\n", errout_str());
check("void f() {\n"
" std::vector<int> v = {1};\n"
" int &v0 = v.front();\n"
" v.push_back(123);\n"
" std::cout << v0 << std::endl;\n"
"}\n",
true);
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:3] -> [test.cpp:4] -> [test.cpp:5]: (error) Reference to v that may be invalid.\n",
errout_str());
check("void f() {\n"
" std::vector<int> v = {1};\n"
" int &v0 = v[0];\n"
" v.push_back(123);\n"
" std::cout << v0 << std::endl;\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4] -> [test.cpp:5]: (error) Reference to v that may be invalid.\n",
errout_str());
check("void f(std::vector<int> &v) {\n"
" int &v0 = v.front();\n"
" v.push_back(123);\n"
" std::cout << v0 << std::endl;\n"
"}\n",
true);
ASSERT_EQUALS(
"[test.cpp:2] -> [test.cpp:2] -> [test.cpp:1] -> [test.cpp:3] -> [test.cpp:4]: (error) Reference to v that may be invalid.\n",
errout_str());
check("void f(std::vector<int> &v) {\n"
" int &v0 = v[0];\n"
" v.push_back(123);\n"
" std::cout << v0 << std::endl;\n"
"}\n",
true);
ASSERT_EQUALS(
"[test.cpp:2] -> [test.cpp:1] -> [test.cpp:3] -> [test.cpp:4]: (error) Reference to v that may be invalid.\n",
errout_str());
check("void f(std::vector<int> &v) {\n"
" std::vector<int> *v0 = &v;\n"
" v.push_back(123);\n"
" std::cout << (*v0)[0] << std::endl;\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("const std::vector<int> * g(int);\n"
"void f() {\n"
" const std::vector<int> *v = g(1);\n"
" if (v && v->size() == 1U) {\n"
" const int &m = v->front();\n"
" }\n"
"\n"
" v = g(2);\n"
" if (v && v->size() == 1U) {\n"
" const int &m = v->front();\n"
" if (m == 0) {}\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("std::vector<std::string> g();\n"
"void f() {\n"
" std::vector<std::string> x = g();\n"
" const std::string& y = x[1];\n"
" std::string z;\n"
" z += \"\";\n"
" z += y;\n"
"}\n",true);
ASSERT_EQUALS("", errout_str());
check("void f(std::vector<char> v)\n"
"{\n"
" auto *cur = v.data();\n"
" auto *end = cur + v.size();\n"
" while (cur < end) {\n"
" v.erase(v.begin(), FindNext(v));\n"
" cur = v.data();\n"
" end = cur + v.size();\n"
" }\n"
"}\n",true);
ASSERT_EQUALS("", errout_str());
// #9598
check("void f(std::vector<std::string> v) {\n"
" for (auto it = v.begin(); it != v.end(); it = v.erase(it))\n"
" *it;\n"
"}\n",true);
ASSERT_EQUALS("", errout_str());
// #9714
check("void f() {\n"
" auto v = std::vector<std::string>();\n"
" std::string x;\n"
" v.push_back(x.insert(0, \"x\"));\n"
" v.push_back(\"y\");\n"
"}\n",true);
ASSERT_EQUALS("", errout_str());
// #9783
check("std::string GetTaskIDPerUUID(int);\n"
"void InitializeJumpList(CString s);\n"
"void foo() {\n"
" CString sAppID = GetTaskIDPerUUID(123).c_str();\n"
" InitializeJumpList(sAppID);\n"
"}\n",true);
ASSERT_EQUALS("", errout_str());
// #9796
check("struct A {};\n"
"void f() {\n"
" std::vector<A *> v;\n"
" A *a = new A();\n"
" v.push_back(a);\n"
" A *b = v.back();\n"
" v.pop_back();\n"
" delete b;\n"
"}\n",true);
ASSERT_EQUALS("", errout_str());
check("struct A {};\n"
"void f() {\n"
" std::vector<A *, std::allocator<A*>> v;\n"
" A *a = new A();\n"
" v.push_back(a);\n"
" A *b = v.back();\n"
" v.pop_back();\n"
" delete b;\n"
"}\n",true);
ASSERT_EQUALS("", errout_str());
check("struct A {};\n"
"void f() {\n"
" std::vector<std::shared_ptr<A>> v;\n"
" std::shared_ptr<A> a = std::make_shared<A>();\n"
" v.push_back(a);\n"
" std::shared_ptr<A> b = v.back();\n"
" v.pop_back();\n"
" delete b;\n"
"}\n",true);
ASSERT_EQUALS("", errout_str());
// #9780
check("int f() {\n"
" std::vector<int> vect;\n"
" MyStruct info{};\n"
" info.vect = &vect;\n"
" vect.push_back(1);\n"
" return info.ret;\n"
"}\n",true);
ASSERT_EQUALS("", errout_str());
// #9133
check("struct Fred {\n"
" std::vector<int> v;\n"
" void foo();\n"
" void bar();\n"
"};\n"
"void Fred::foo() {\n"
" std::vector<int>::iterator it = v.begin();\n"
" bar();\n"
" it++;\n"
"}\n"
"void Fred::bar() {\n"
" v.push_back(0);\n"
"}\n",
true);
ASSERT_EQUALS(
"[test.cpp:7] -> [test.cpp:8] -> [test.cpp:12] -> [test.cpp:9]: (error) Using iterator to member container 'v' that may be invalid.\n",
errout_str());
check("void foo(std::vector<int>& v) {\n"
" std::vector<int>::iterator it = v.begin();\n"
" bar(v);\n"
" it++;\n"
"}\n"
"void bar(std::vector<int>& v) {\n"
" v.push_back(0);\n"
"}\n",
true);
ASSERT_EQUALS(
"[test.cpp:1] -> [test.cpp:2] -> [test.cpp:3] -> [test.cpp:7] -> [test.cpp:1] -> [test.cpp:4]: (error) Using iterator to local container 'v' that may be invalid.\n",
errout_str());
// #10264
check("void f(std::vector<std::string>& x) {\n"
" struct I {\n"
" std::vector<std::string> *px{};\n"
" };\n"
" I i = { &x };\n"
" x.clear();\n"
" Parse(i);\n"
"}\n",true);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" std::string x;\n"
" struct V {\n"
" std::string* pStr{};\n"
" };\n"
" struct I {\n"
" std::vector<V> v;\n"
" };\n"
" I b[] = {{{{ &x }}}};\n"
" x = \"Arial\";\n"
" I cb[1];\n"
" for (long i = 0; i < 1; ++i)\n"
" cb[i] = b[i];\n"
"}\n",true);
ASSERT_EQUALS("", errout_str());
// #9836
check("void f() {\n"
" auto v = std::vector<std::vector<std::string> >{ std::vector<std::string>{ \"hello\" } };\n"
" auto p = &(v.at(0).at(0));\n"
" v.clear();\n"
" std::cout << *p << std::endl;\n"
"}\n",
true);
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:3] -> [test.cpp:3] -> [test.cpp:4] -> [test.cpp:2] -> [test.cpp:5]: (error) Using pointer to local variable 'v' that may be invalid.\n",
errout_str());
check("struct A {\n"
" const std::vector<int>* i;\n"
" A(const std::vector<int>& v)\n"
" : i(&v)\n"
" {}\n"
"};\n"
"int f() {\n"
" std::vector<int> v;\n"
" A a{v};\n"
" v.push_back(1);\n"
" return a.i->front();\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("struct A {\n"
" const std::vector<int>* i;\n"
" A(const std::vector<int>& v)\n"
" : i(&v)\n"
" {}\n"
"};\n"
"void g(const std::vector<int>& v);\n"
"void f() {\n"
" std::vector<int> v;\n"
" A a{v};\n"
" v.push_back(1);\n"
" g(a);\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
// #10984
check("void f() {\n"
" std::vector<int> v;\n"
" auto g = [&v]{};\n"
" v.push_back(1);\n"
" g();\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("void f(std::vector<int> v) {\n"
" auto it = v.begin();\n"
" auto g = [&]{ std::cout << *it << std::endl;};\n"
" v.push_back(1);\n"
" g();\n"
"}\n",
true);
ASSERT_EQUALS(
"[test.cpp:2] -> [test.cpp:3] -> [test.cpp:4] -> [test.cpp:1] -> [test.cpp:5]: (error) Using iterator to local container 'v' that may be invalid.\n",
errout_str());
check("void f(std::vector<int> v) {\n"
" auto it = v.begin();\n"
" auto g = [=]{ std::cout << *it << std::endl;};\n"
" v.push_back(1);\n"
" g();\n"
"}\n",
true);
ASSERT_EQUALS(
"[test.cpp:2] -> [test.cpp:4] -> [test.cpp:1] -> [test.cpp:5]: (error) Using iterator to local container 'v' that may be invalid.\n",
errout_str());
check("struct A {\n"
" int* p;\n"
" void g();\n"
"};\n"
"void f(std::vector<int> v) {\n"
" auto it = v.begin();\n"
" A a{v.data()};\n"
" v.push_back(1);\n"
" a.g();\n"
"}\n",
true);
ASSERT_EQUALS(
"[test.cpp:7] -> [test.cpp:8] -> [test.cpp:5] -> [test.cpp:9]: (error) Using object that points to local variable 'v' that may be invalid.\n",
errout_str());
check("struct A {\n"
" int*& p;\n"
" void g();\n"
"};\n"
"void f(std::vector<int> v) {\n"
" auto* p = v.data();\n"
" A a{p};\n"
" v.push_back(1);\n"
" a.g();\n"
"}\n",
true);
ASSERT_EQUALS(
"[test.cpp:6] -> [test.cpp:7] -> [test.cpp:8] -> [test.cpp:5] -> [test.cpp:9]: (error) Using object that points to local variable 'v' that may be invalid.\n",
errout_str());
// #11028
check("void f(std::vector<int> c) {\n"
" std::vector<int> d(c.begin(), c.end());\n"
" c.erase(c.begin());\n"
" d.push_back(0);\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
// #11147
check("void f(std::string& s) {\n"
" if (!s.empty()) {\n"
" std::string::iterator it = s.begin();\n"
" s = s.substr(it - s.begin());\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS(
"[test.cpp:4]: (performance) Ineffective call of function 'substr' because a prefix of the string is assigned to itself. Use resize() or pop_back() instead.\n",
errout_str());
// #11630
check("int main(int argc, const char* argv[]) {\n"
" std::vector<std::string> args(argv + 1, argv + argc);\n"
" args.push_back(\"-h\");\n"
" args.front();\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("void f(std::vector<int>& v) {\n" // #13108
" auto it = unknown(v);\n"
" auto w = std::vector<int>{ it, v.end() };\n"
" v.erase(it, v.end());\n"
" for (const auto& i : w) {}\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
// #13410
check("int f(std::vector<int>& v) {\n"
" const int* i = &*v.cbegin();\n"
" v.push_back(1);\n"
" return *i;\n"
"}\n",
true);
ASSERT_EQUALS(
"[test.cpp:1] -> [test.cpp:2] -> [test.cpp:1] -> [test.cpp:2] -> [test.cpp:2] -> [test.cpp:3] -> [test.cpp:1] -> [test.cpp:4]: (error) Using pointer to local variable 'v' that may be invalid.\n",
errout_str());
}
void invalidContainerLoop() {
// #9435
check("void f(std::vector<int> v) {\n"
" for (auto i : v) {\n"
" if (i < 5)\n"
" v.push_back(i * 2);\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:4]: (error) Calling 'push_back' while iterating the container is invalid.\n", errout_str());
// #9713
check("void f() {\n"
" std::vector<int> v{1, 2, 3};\n"
" for (int i : v) {\n"
" if (i == 2) {\n"
" v.clear();\n"
" return;\n"
" }\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:4]: (style) Consider using std::any_of algorithm instead of a raw loop.\n", errout_str());
check("struct A {\n"
" std::vector<int> v;\n"
" void add(int i) {\n"
" v.push_back(i);\n"
" } \n"
" void f() {\n"
" for(auto i:v)\n"
" add(i);\n"
" }\n"
"};\n",
true);
ASSERT_EQUALS(
"[test.cpp:4] -> [test.cpp:7] -> [test.cpp:8]: (error) Calling 'add' while iterating the container is invalid.\n",
errout_str());
}
void findInsert() {
check("void f1(std::set<unsigned>& s, unsigned x) {\n"
" if (s.find(x) == s.end()) {\n"
" s.insert(x);\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:3]: (performance) Searching before insertion is not necessary.\n", errout_str());
check("void f2(std::map<unsigned, unsigned>& m, unsigned x) {\n"
" if (m.find(x) == m.end()) {\n"
" m.emplace(x, 1);\n"
" } else {\n"
" m[x] = 1;\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:3]: (performance) Searching before insertion is not necessary.\n", errout_str());
check("void f3(std::map<unsigned, unsigned>& m, unsigned x) {\n"
" if (m.count(x) == 0) {\n"
" m.emplace(x, 1);\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:3]: (performance) Searching before insertion is not necessary.\n", errout_str());
check("void f4(std::set<unsigned>& s, unsigned x) {\n"
" if (s.find(x) == s.end()) {\n"
" s.insert(x);\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:3]: (performance) Searching before insertion is not necessary.\n", errout_str());
check("void f5(std::map<unsigned, unsigned>& m, unsigned x) {\n"
" if (m.count(x) == 0) {\n"
" m.emplace(x, 1);\n"
" } else {\n"
" m[x] = 1;\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:3]: (performance) Searching before insertion is not necessary.\n", errout_str());
check("void f6(std::map<unsigned, unsigned>& m, unsigned x) {\n"
" if (m.count(x) == 0) {\n"
" m.emplace(x, 1);\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:3]: (performance) Searching before insertion is not necessary.\n", errout_str());
check("void f1(std::unordered_set<unsigned>& s, unsigned x) {\n"
" if (s.find(x) == s.end()) {\n"
" s.insert(x);\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:3]: (performance) Searching before insertion is not necessary.\n", errout_str());
check("void f2(std::unordered_map<unsigned, unsigned>& m, unsigned x) {\n"
" if (m.find(x) == m.end()) {\n"
" m.emplace(x, 1);\n"
" } else {\n"
" m[x] = 1;\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:3]: (performance) Searching before insertion is not necessary.\n", errout_str());
check("void f3(std::unordered_map<unsigned, unsigned>& m, unsigned x) {\n"
" if (m.count(x) == 0) {\n"
" m.emplace(x, 1);\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:3]: (performance) Searching before insertion is not necessary.\n", errout_str());
check("void f4(std::unordered_set<unsigned>& s, unsigned x) {\n"
" if (s.find(x) == s.end()) {\n"
" s.insert(x);\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:3]: (performance) Searching before insertion is not necessary.\n", errout_str());
check("void f5(std::unordered_map<unsigned, unsigned>& m, unsigned x) {\n"
" if (m.count(x) == 0) {\n"
" m.emplace(x, 1);\n"
" } else {\n"
" m[x] = 1;\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:3]: (performance) Searching before insertion is not necessary.\n", errout_str());
check("void f6(std::unordered_map<unsigned, unsigned>& m, unsigned x) {\n"
" if (m.count(x) == 0) {\n"
" m.emplace(x, 1);\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:3]: (performance) Searching before insertion is not necessary.\n", errout_str());
check("void g1(std::map<unsigned, unsigned>& m, unsigned x) {\n"
" if (m.find(x) == m.end()) {\n"
" m.emplace(x, 1);\n"
" } else {\n"
" m[x] = 2;\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("void g1(std::map<unsigned, unsigned>& m, unsigned x) {\n"
" if (m.count(x) == 0) {\n"
" m.emplace(x, 1);\n"
" } else {\n"
" m[x] = 2;\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("void f1(QSet<unsigned>& s, unsigned x) {\n"
" if (s.find(x) == s.end()) {\n"
" s.insert(x);\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("void f1(std::multiset<unsigned>& s, unsigned x) {\n"
" if (s.find(x) == s.end()) {\n"
" s.insert(x);\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("void f2(std::multimap<unsigned, unsigned>& m, unsigned x) {\n"
" if (m.find(x) == m.end()) {\n"
" m.emplace(x, 1);\n"
" } else {\n"
" m[x] = 1;\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("void f3(std::multimap<unsigned, unsigned>& m, unsigned x) {\n"
" if (m.count(x) == 0) {\n"
" m.emplace(x, 1);\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("void f4(std::multiset<unsigned>& s, unsigned x) {\n"
" if (s.find(x) == s.end()) {\n"
" s.insert(x);\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("void f5(std::multimap<unsigned, unsigned>& m, unsigned x) {\n"
" if (m.count(x) == 0) {\n"
" m.emplace(x, 1);\n"
" } else {\n"
" m[x] = 1;\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("void f1(std::unordered_multiset<unsigned>& s, unsigned x) {\n"
" if (s.find(x) == s.end()) {\n"
" s.insert(x);\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("void f2(std::unordered_multimap<unsigned, unsigned>& m, unsigned x) {\n"
" if (m.find(x) == m.end()) {\n"
" m.emplace(x, 1);\n"
" } else {\n"
" m[x] = 1;\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("void f3(std::unordered_multimap<unsigned, unsigned>& m, unsigned x) {\n"
" if (m.count(x) == 0) {\n"
" m.emplace(x, 1);\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("void f4(std::unordered_multiset<unsigned>& s, unsigned x) {\n"
" if (s.find(x) == s.end()) {\n"
" s.insert(x);\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("void f5(std::unordered_multimap<unsigned, unsigned>& m, unsigned x) {\n"
" if (m.count(x) == 0) {\n"
" m.emplace(x, 1);\n"
" } else {\n"
" m[x] = 1;\n"
" }\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
// #9218 - not small type => do not warn if cpp standard is < c++17
{
const char code[] = "void f1(std::set<LargeType>& s, const LargeType& x) {\n"
" if (s.find(x) == s.end()) {\n"
" s.insert(x);\n"
" }\n"
"}\n";
check(code, true, Standards::CPP11);
ASSERT_EQUALS("", errout_str());
check(code, true, Standards::CPP14);
ASSERT_EQUALS("", errout_str());
check(code, true, Standards::CPP17);
ASSERT_EQUALS("[test.cpp:3]: (performance) Searching before insertion is not necessary.\n", errout_str());
}
{ // #10558
check("void foo() {\n"
" std::map<int, int> x;\n"
" int data = 0;\n"
" for(int i=0; i<10; ++i) {\n"
" data += 123;\n"
" if(x.find(5) == x.end())\n"
" x[5] = data;\n"
" }\n"
"}", false, Standards::CPP03);
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" std::map<int, int> x;\n"
" int data = 0;\n"
" for(int i=0; i<10; ++i) {\n"
" data += 123;\n"
" if(x.find(5) == x.end())\n"
" x[5] = data;\n"
" }\n"
"}", false, Standards::CPP11);
ASSERT_EQUALS("[test.cpp:7]: (performance) Searching before insertion is not necessary. Instead of 'x[5]=data' consider using 'x.emplace(5, data);'.\n", errout_str());
check("void foo() {\n"
" std::map<int, int> x;\n"
" int data = 0;\n"
" for(int i=0; i<10; ++i) {\n"
" data += 123;\n"
" if(x.find(5) == x.end())\n"
" x[5] = data;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (performance) Searching before insertion is not necessary. Instead of 'x[5]=data' consider using 'x.try_emplace(5, data);'.\n", errout_str());
}
}
void checkKnownEmptyContainer() {
check("void f() {\n"
" std::vector<int> v;\n"
" for(auto x:v) {}\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:3]: (style) Iterating over container 'v' that is always empty.\n", errout_str());
check("void f(std::vector<int> v) {\n"
" v.clear();\n"
" for(auto x:v) {}\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:3]: (style) Iterating over container 'v' that is always empty.\n", errout_str());
check("void f(std::vector<int> v) {\n"
" if (!v.empty()) { return; }\n"
" for(auto x:v) {}\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:3]: (style) Iterating over container 'v' that is always empty.\n", errout_str());
check("void f(std::vector<int> v) {\n"
" if (v.empty()) { return; }\n"
" for(auto x:v) {}\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" std::vector<int> v;\n"
" std::sort(v.begin(), v.end());\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:3]: (style) Using sort with iterator 'v.begin()' that is always empty.\n", errout_str());
check("void f() {\n" // #1201
" std::vector<int> v1{ 0, 1 };\n"
" std::vector<int> v2;\n"
" std::copy(v1.begin(), v1.end(), v2.begin());\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:4]: (style) Using copy with iterator 'v2.begin()' that is always empty.\n", errout_str());
check("void f() {\n"
" std::vector<int> v;\n"
" v.insert(v.end(), 1);\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("struct A {\n"
" explicit A(std::vector<int>*);\n"
"};\n"
"A f() {\n"
" std::vector<int> v;\n"
" A a(&v);\n"
" for(auto&& x:v) {}\n"
" return a;\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("static void f1(std::list<std::string>& parameters) {\n"
" parameters.push_back(a);\n"
"}\n"
"int f2(std::list<std::string>& parameters) {\n"
" f1(parameters);\n"
"}\n"
"void f3() {\n"
" std::list<std::string> parameters;\n"
" int res = ::f2(parameters);\n"
" for (auto param : parameters) {}\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("namespace ns {\n"
" using ArrayType = std::vector<int>;\n"
"}\n"
"using namespace ns;\n"
"static void f() {\n"
" const ArrayType arr;\n"
" for (const auto &a : arr) {}\n"
"}",
true);
ASSERT_EQUALS("[test.cpp:7]: (style) Iterating over container 'arr' that is always empty.\n", errout_str());
check("struct S {\n"
" std::vector<int> v;\n"
"};\n"
"void foo(S& s) {\n"
" s.v.clear();\n"
" bar(s);\n"
" std::sort(s.v.begin(), s.v.end());\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("void f(const std::vector<int>& v, int e) {\n"
" if (!v.empty()) {\n"
" if (e < 0 || true) {\n"
" if (e < 0)\n"
" return;\n"
" }\n"
" }\n"
" for (auto i : v) {}\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" std::vector<int> v;\n"
" auto& rv = v;\n"
" rv.push_back(42);\n"
" for (auto i : v) {}\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("extern void f(std::string&&);\n"
"static void func() {\n"
" std::string s;\n"
" const std::string& s_ref = s;\n"
" f(std::move(s));\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("struct S {\n" // #12757
" template<class T = int>\n"
" void clear() {}\n"
" template<class T = int>\n"
" std::vector<T> get() const { return {}; }\n"
" std::vector<int> m;\n"
"};\n"
"template<> void S::clear() { m.clear(); }\n"
"template<> std::vector<int> S::get() const {\n"
" for (const auto& i : m) {}\n"
" return {};\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("void f(bool b) {\n" // #13121
" static std::string s = {};\n"
" for (auto c : s) {}\n"
" if (b)\n"
" s += \'a\';\n"
"}\n", true);
ASSERT_EQUALS("", errout_str());
}
void checkMutexes() {
check("void f() {\n"
" static std::mutex m;\n"
" static std::lock_guard<std::mutex> g(m);\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:3]: (warning) Lock guard is defined globally. Lock guards are intended to be local. A global lock guard could lead to a deadlock since it won't unlock until the end of the program.\n", errout_str());
check("void f() {\n"
" static std::mutex m;\n"
" std::lock_guard<std::mutex> g(m);\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" static std::mutex m;\n"
" static std::unique_lock<std::mutex> g(m, std::defer_lock);\n"
" static std::lock(g);\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:3]: (warning) Lock guard is defined globally. Lock guards are intended to be local. A global lock guard could lead to a deadlock since it won't unlock until the end of the program.\n", errout_str());
check("void f() {\n"
" static std::mutex m;\n"
" std::unique_lock<std::mutex> g(m, std::defer_lock);\n"
" std::lock(g);\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" std::mutex m;\n"
" std::lock_guard<std::mutex> g(m);\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:3]: (warning) The lock is ineffective because the mutex is locked at the same scope as the mutex itself.\n", errout_str());
check("void f() {\n"
" std::mutex m;\n"
" std::unique_lock<std::mutex> g(m);\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:3]: (warning) The lock is ineffective because the mutex is locked at the same scope as the mutex itself.\n", errout_str());
check("void f() {\n"
" std::mutex m;\n"
" std::unique_lock<std::mutex> g(m, std::defer_lock);\n"
" std::lock(g);\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:3]: (warning) The lock is ineffective because the mutex is locked at the same scope as the mutex itself.\n", errout_str());
check("void g();\n"
"void f() {\n"
" static std::mutex m;\n"
" m.lock();\n"
" g();\n"
" m.unlock();\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("void g();\n"
"void f() {\n"
" std::mutex m;\n"
" m.lock();\n"
" g();\n"
" m.unlock();\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:4]: (warning) The lock is ineffective because the mutex is locked at the same scope as the mutex itself.\n", errout_str());
check("class A {\n"
" std::mutex m;\n"
" void f() {\n"
" std::lock_guard<std::mutex> g(m);\n"
" }\n"
"};\n",
true);
ASSERT_EQUALS("", errout_str());
check("class A {\n"
" std::mutex m;\n"
" void g();\n"
" void f() {\n"
" m.lock();\n"
" g();\n"
" m.unlock();\n"
" }\n"
"};\n",
true);
ASSERT_EQUALS("", errout_str());
check("class A {\n"
" std::mutex m;\n"
" void f() {\n"
" static std::lock_guard<std::mutex> g(m);\n"
" }\n"
"};\n",
true);
ASSERT_EQUALS("[test.cpp:4]: (warning) Lock guard is defined globally. Lock guards are intended to be local. A global lock guard could lead to a deadlock since it won't unlock until the end of the program.\n", errout_str());
check("std::mutex& h();\n"
"void f() {\n"
" auto& m = h();\n"
" std::lock_guard<std::mutex> g(m);\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("void g();\n"
"std::mutex& h();\n"
"void f() {\n"
" auto& m = h();\n"
" m.lock();\n"
" g();\n"
" m.unlock();\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("std::mutex& h();\n"
"void f() {\n"
" auto m = h();\n"
" std::lock_guard<std::mutex> g(m);\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:4]: (warning) The lock is ineffective because the mutex is locked at the same scope as the mutex itself.\n", errout_str());
check("void g();\n"
"std::mutex& h();\n"
"void f() {\n"
" auto m = h();\n"
" m.lock();\n"
" g();\n"
" m.unlock();\n"
"}\n",
true);
ASSERT_EQUALS("[test.cpp:5]: (warning) The lock is ineffective because the mutex is locked at the same scope as the mutex itself.\n", errout_str());
check("void foo();\n"
"void bar();\n"
"void f() {\n"
" std::mutex m;\n"
" std::thread t([&m](){\n"
" m.lock();\n"
" foo();\n"
" m.unlock();\n"
" });\n"
" m.lock();\n"
" bar();\n"
" m.unlock();\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("void foo();\n"
"void bar();\n"
"void f() {\n"
" std::mutex m;\n"
" std::thread t([&m](){\n"
" std::unique_lock<std::mutex> g{m};\n"
" foo();\n"
" });\n"
" std::unique_lock<std::mutex> g{m};\n"
" bar();\n"
"}\n",
true);
ASSERT_EQUALS("", errout_str());
check("void foo() { int f = 0; auto g(f); g = g; }");
ASSERT_EQUALS("", errout_str());
check("struct foobar {\n"
" int foo;\n"
" std::shared_mutex foo_mtx;\n"
" int bar;\n"
" std::shared_mutex bar_mtx;\n"
"};\n"
"void f() {\n"
" foobar xyz;\n"
" {\n"
" std::shared_lock shared_foo_lock(xyz.foo_mtx, std::defer_lock);\n"
" std::shared_lock shared_bar_lock(xyz.bar_mtx, std::defer_lock);\n"
" std::scoped_lock shared_multi_lock(shared_foo_lock, shared_bar_lock);\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
};
REGISTER_TEST(TestStl)
| null |
952 | cpp | cppcheck | testio.cpp | test/testio.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "checkio.h"
#include "config.h"
#include "errortypes.h"
#include "fixture.h"
#include "helpers.h"
#include "platform.h"
#include "settings.h"
#include <cstddef>
#include <string>
class TestIO : public TestFixture {
public:
TestIO() : TestFixture("TestIO") {}
private:
const Settings settings = settingsBuilder().library("std.cfg").library("windows.cfg").library("qt.cfg").build();
/*const*/ Settings settings1 = settingsBuilder().library("std.cfg").library("windows.cfg").library("qt.cfg").severity(Severity::warning).severity(Severity::style).build();
void run() override {
TEST_CASE(coutCerrMisusage);
TEST_CASE(wrongMode_simple);
TEST_CASE(wrongMode_complex);
TEST_CASE(useClosedFile);
TEST_CASE(fileIOwithoutPositioning);
TEST_CASE(seekOnAppendedFile);
TEST_CASE(fflushOnInputStream);
TEST_CASE(incompatibleFileOpen);
TEST_CASE(testScanf1); // Scanf without field limiters
TEST_CASE(testScanf2);
TEST_CASE(testScanf3); // #3494
TEST_CASE(testScanf4); // #ticket 2553
TEST_CASE(testScanf5); // #10632
TEST_CASE(testScanfArgument);
TEST_CASE(testPrintfArgument);
TEST_CASE(testPrintfArgumentVariables);
TEST_CASE(testPosixPrintfScanfParameterPosition); // #4900
TEST_CASE(testMicrosoftPrintfArgument); // ticket #4902
TEST_CASE(testMicrosoftScanfArgument);
TEST_CASE(testMicrosoftCStringFormatArguments); // ticket #4920
TEST_CASE(testMicrosoftSecurePrintfArgument);
TEST_CASE(testMicrosoftSecureScanfArgument);
TEST_CASE(testQStringFormatArguments);
TEST_CASE(testTernary); // ticket #6182
TEST_CASE(testUnsignedConst); // ticket #6132
TEST_CASE(testAstType); // #7014
TEST_CASE(testPrintf0WithSuffix); // ticket #7069
TEST_CASE(testReturnValueTypeStdLib);
TEST_CASE(testPrintfTypeAlias1);
TEST_CASE(testPrintfAuto); // #8992
TEST_CASE(testPrintfParenthesis); // #8489
TEST_CASE(testStdDistance); // #10304
TEST_CASE(testParameterPack); // #11289
}
struct CheckOptions
{
CheckOptions() = default;
bool inconclusive = false;
bool portability = false;
Platform::Type platform = Platform::Type::Unspecified;
bool onlyFormatStr = false;
bool cpp = true;
};
#define check(...) check_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
void check_(const char* file, int line, const char (&code)[size], const CheckOptions& options = make_default_obj()) {
// TODO: using dedicated Settings (i.e. copying it) object causes major slowdown
settings1.severity.setEnabled(Severity::portability, options.portability);
settings1.certainty.setEnabled(Certainty::inconclusive, options.inconclusive);
PLATFORM(settings1.platform, options.platform);
// Tokenize..
SimpleTokenizer tokenizer(settings1, *this);
ASSERT_LOC(tokenizer.tokenize(code, options.cpp), file, line);
// Check..
if (options.onlyFormatStr) {
CheckIO checkIO(&tokenizer, &settings1, this);
checkIO.checkWrongPrintfScanfArguments();
return;
}
runChecks<CheckIO>(tokenizer, this);
}
void coutCerrMisusage() {
check(
"void foo() {\n"
" std::cout << std::cout;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Invalid usage of output stream: '<< std::cout'.\n", errout_str());
check(
"void foo() {\n"
" std::cout << (std::cout);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Invalid usage of output stream: '<< std::cout'.\n", errout_str());
check(
"void foo() {\n"
" std::cout << \"xyz\" << std::cout;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Invalid usage of output stream: '<< std::cout'.\n", errout_str());
check(
"void foo(int i) {\n"
" std::cout << i << std::cerr;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Invalid usage of output stream: '<< std::cerr'.\n", errout_str());
check(
"void foo() {\n"
" std::cout << \"xyz\";\n"
" std::cout << \"xyz\";\n"
"}");
ASSERT_EQUALS("", errout_str());
check(
"void foo() {\n"
" std::cout << std::cout.good();\n"
"}");
ASSERT_EQUALS("", errout_str());
check(
"void foo() {\n"
" unknownObject << std::cout;\n"
"}");
ASSERT_EQUALS("", errout_str());
check(
"void foo() {\n"
" MACRO(std::cout <<, << std::cout)\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void wrongMode_simple() {
// Read mode
check("void foo(FILE*& f) {\n"
" f = fopen(name, \"r\");\n"
" fread(buffer, 5, 6, f);\n"
" rewind(f);\n"
" fwrite(buffer, 5, 6, f);\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Write operation on a file that was opened only for reading.\n", errout_str());
check("void foo(FILE*& f) {\n"
" f = _wfopen(name, L\"r\");\n"
" fread(buffer, 5, 6, f);\n"
" rewind(f);\n"
" fwrite(buffer, 5, 6, f);\n"
"}", dinit(CheckOptions, $.platform = Platform::Type::Win32W));
ASSERT_EQUALS("[test.cpp:5]: (error) Write operation on a file that was opened only for reading.\n", errout_str());
check("void foo(FILE*& f) {\n"
" f = _tfopen(name, _T(\"r\"));\n"
" fread(buffer, 5, 6, f);\n"
" rewind(f);\n"
" fwrite(buffer, 5, 6, f);\n"
"}", dinit(CheckOptions, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("[test.cpp:5]: (error) Write operation on a file that was opened only for reading.\n", errout_str());
check("void foo(FILE*& f) {\n"
" f = _tfopen(name, _T(\"r\"));\n"
" fread(buffer, 5, 6, f);\n"
" rewind(f);\n"
" fwrite(buffer, 5, 6, f);\n"
"}", dinit(CheckOptions, $.platform = Platform::Type::Win32W));
ASSERT_EQUALS("[test.cpp:5]: (error) Write operation on a file that was opened only for reading.\n", errout_str());
check("void foo(FILE*& f) {\n"
" _wfopen_s(&f, name, L\"r\");\n"
" fread(buffer, 5, 6, f);\n"
" rewind(f);\n"
" fwrite(buffer, 5, 6, f);\n"
"}", dinit(CheckOptions, $.platform = Platform::Type::Win32W));
ASSERT_EQUALS("[test.cpp:5]: (error) Write operation on a file that was opened only for reading.\n", errout_str());
check("void foo(FILE*& f) {\n"
" _tfopen_s(&f, name, _T(\"r\"));\n"
" fread(buffer, 5, 6, f);\n"
" rewind(f);\n"
" fwrite(buffer, 5, 6, f);\n"
"}", dinit(CheckOptions, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("[test.cpp:5]: (error) Write operation on a file that was opened only for reading.\n", errout_str());
check("void foo(FILE*& f) {\n"
" _tfopen_s(&f, name, _T(\"r\"));\n"
" fread(buffer, 5, 6, f);\n"
" rewind(f);\n"
" fwrite(buffer, 5, 6, f);\n"
"}", dinit(CheckOptions, $.platform = Platform::Type::Win32W));
ASSERT_EQUALS("[test.cpp:5]: (error) Write operation on a file that was opened only for reading.\n", errout_str());
check("void foo(FILE*& f) {\n"
" f = fopen(name, \"r+\");\n"
" fwrite(buffer, 5, 6, f);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(FILE*& f) {\n"
" f = _wfopen(name, L\"r+\");\n"
" fwrite(buffer, 5, 6, f);\n"
"}", dinit(CheckOptions, $.platform = Platform::Type::Win32W));
ASSERT_EQUALS("", errout_str());
check("void foo(FILE*& f) {\n"
" f = _tfopen(name, _T(\"r+\"));\n"
" fwrite(buffer, 5, 6, f);\n"
"}", dinit(CheckOptions, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("", errout_str());
check("void foo(FILE*& f) {\n"
" f = _tfopen(name, _T(\"r+\"));\n"
" fwrite(buffer, 5, 6, f);\n"
"}", dinit(CheckOptions, $.platform = Platform::Type::Win32W));
ASSERT_EQUALS("", errout_str());
check("void foo(FILE*& f) {\n"
" _wfopen_s(&f, name, L\"r+\");\n"
" fwrite(buffer, 5, 6, f);\n"
"}", dinit(CheckOptions, $.platform = Platform::Type::Win32W));
ASSERT_EQUALS("", errout_str());
check("void foo(FILE*& f) {\n"
" _tfopen_s(&f, name, _T(\"r+\"));\n"
" fwrite(buffer, 5, 6, f);\n"
"}", dinit(CheckOptions, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("", errout_str());
check("void foo(FILE*& f) {\n"
" _tfopen_s(&f, name, _T(\"r+\"));\n"
" fwrite(buffer, 5, 6, f);\n"
"}", dinit(CheckOptions, $.platform = Platform::Type::Win32W));
ASSERT_EQUALS("", errout_str());
check("void foo(FILE*& f) {\n"
" f = tmpfile();\n"
" fwrite(buffer, 5, 6, f);\n"
"}", dinit(CheckOptions, $.platform = Platform::Type::Win32W));
ASSERT_EQUALS("", errout_str());
// Write mode
check("void foo(FILE*& f) {\n"
" f = fopen(name, \"w\");\n"
" fwrite(buffer, 5, 6, f);\n"
" rewind(f);\n"
" fread(buffer, 5, 6, f);\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Read operation on a file that was opened only for writing.\n", errout_str());
check("void foo(FILE*& f) {\n"
" f = fopen(name, \"w+\");\n"
" fread(buffer, 5, 6, f);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(FILE*& f) {\n"
" f = tmpfile();\n"
" fread(buffer, 5, 6, f);\n"
"}");
ASSERT_EQUALS("", errout_str());
// Append mode
check("void foo(FILE*& f) {\n"
" f = fopen(name, \"a\");\n"
" fwrite(buffer, 5, 6, f);\n"
" rewind(f);\n"
" fread(buffer, 5, 6, f);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (warning) Repositioning operation performed on a file opened in append mode has no effect.\n"
"[test.cpp:5]: (error) Read operation on a file that was opened only for writing.\n", errout_str());
check("void foo(FILE*& f) {\n"
" f = fopen(name, \"a+\");\n"
" fread(buffer, 5, 6, f);\n"
"}");
ASSERT_EQUALS("", errout_str());
// Variable declared locally
check("void foo() {\n"
" FILE* f = fopen(name, \"r\");\n"
" fwrite(buffer, 5, 6, f);\n"
" fclose(f);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Write operation on a file that was opened only for reading.\n", errout_str());
// Call unknown function
check("void foo(FILE*& f) {\n"
" f = fopen(name, \"a\");\n"
" fwrite(buffer, 5, 6, f);\n"
" bar(f);\n"
" fread(buffer, 5, 6, f);\n"
"}");
ASSERT_EQUALS("", errout_str());
// freopen and tmpfile
check("void foo(FILE*& f) {\n"
" f = freopen(name, \"r\", f);\n"
" fwrite(buffer, 5, 6, f);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Write operation on a file that was opened only for reading.\n", errout_str());
check("void foo(FILE*& f) {\n"
" f = _wfreopen(name, L\"r\", f);\n"
" fwrite(buffer, 5, 6, f);\n"
"}", dinit(CheckOptions, $.platform = Platform::Type::Win32W));
ASSERT_EQUALS("[test.cpp:3]: (error) Write operation on a file that was opened only for reading.\n", errout_str());
check("void foo(FILE*& f) {\n"
" f = _tfreopen(name, _T(\"r\"), f);\n"
" fwrite(buffer, 5, 6, f);\n"
"}", dinit(CheckOptions, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("[test.cpp:3]: (error) Write operation on a file that was opened only for reading.\n", errout_str());
check("void foo(FILE*& f) {\n"
" f = _tfreopen(name, _T(\"r\"), f);\n"
" fwrite(buffer, 5, 6, f);\n"
"}", dinit(CheckOptions, $.platform = Platform::Type::Win32W));
ASSERT_EQUALS("[test.cpp:3]: (error) Write operation on a file that was opened only for reading.\n", errout_str());
check("void foo(FILE*& f) {\n"
" f = _wfreopen_s(&f, name, L\"r\", f);\n"
" fwrite(buffer, 5, 6, f);\n"
"}", dinit(CheckOptions, $.platform = Platform::Type::Win32W));
ASSERT_EQUALS("[test.cpp:3]: (error) Write operation on a file that was opened only for reading.\n", errout_str());
check("void foo(FILE*& f) {\n"
" f = _tfreopen_s(&f, name, _T(\"r\"), f);\n"
" fwrite(buffer, 5, 6, f);\n"
"}", dinit(CheckOptions, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("[test.cpp:3]: (error) Write operation on a file that was opened only for reading.\n", errout_str());
check("void foo(FILE*& f) {\n"
" f = _tfreopen_s(&f, name, _T(\"r\"), f);\n"
" fwrite(buffer, 5, 6, f);\n"
"}", dinit(CheckOptions, $.platform = Platform::Type::Win32W));
ASSERT_EQUALS("[test.cpp:3]: (error) Write operation on a file that was opened only for reading.\n", errout_str());
// Crash tests
check("void foo(FILE*& f) {\n"
" f = fopen(name, mode);\n" // No assertion failure (#3830)
" fwrite(buffer, 5, 6, f);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void fopen(std::string const &filepath, std::string const &mode);"); // #3832
}
void wrongMode_complex() {
check("void foo(FILE* f) {\n"
" if(a) f = fopen(name, \"w\");\n"
" else f = fopen(name, \"r\");\n"
" if(a) fwrite(buffer, 5, 6, f);\n"
" else fread(buffer, 5, 6, f);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" FILE* f;\n"
" if(a) f = fopen(name, \"w\");\n"
" else f = fopen(name, \"r\");\n"
" if(a) fwrite(buffer, 5, 6, f);\n"
" else fread(buffer, 5, 6, f);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" FILE* f = fopen(name, \"w\");\n"
" if(a) fwrite(buffer, 5, 6, f);\n"
" else fread(buffer, 5, 6, f);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Read operation on a file that was opened only for writing.\n", errout_str());
}
void useClosedFile() {
check("void foo(FILE*& f) {\n"
" fclose(f);\n"
" fwrite(buffer, 5, 6, f);\n"
" clearerr(f);\n"
" fread(buffer, 5, 6, f);\n"
" ungetc('a', f);\n"
" ungetwc(L'a', f);\n"
" rewind(f);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Used file that is not opened.\n"
"[test.cpp:4]: (error) Used file that is not opened.\n"
"[test.cpp:5]: (error) Used file that is not opened.\n"
"[test.cpp:6]: (error) Used file that is not opened.\n"
"[test.cpp:7]: (error) Used file that is not opened.\n"
"[test.cpp:8]: (error) Used file that is not opened.\n", errout_str());
check("void foo(FILE*& f) {\n"
" if(!ferror(f)) {\n"
" fclose(f);\n"
" return;"
" }\n"
" fwrite(buffer, 5, 6, f);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(FILE*& f) {\n"
" fclose(f);\n"
" f = fopen(name, \"r\");\n"
" fread(buffer, 5, 6, f);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(FILE*& f) {\n"
" f = fopen(name, \"r\");\n"
" f = g;\n"
" fwrite(buffer, 5, 6, f);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" FILE* f;\n"
" fwrite(buffer, 5, 6, f);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Used file that is not opened.\n", errout_str());
check("void foo() {\n"
" FILE* f(stdout);\n"
" fwrite(buffer, 5, 6, f);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo() {\n" // #3965
" FILE* f[3];\n"
" f[0] = fopen(name, mode);\n"
" fclose(f[0]);\n"
"}");
ASSERT_EQUALS("", errout_str());
// #4368: multiple functions
check("static FILE *fp = NULL;\n"
"\n"
"void close()\n"
"{\n"
" fclose(fp);\n"
"}\n"
"\n"
"void dump()\n"
"{\n"
" if (fp == NULL) return;\n"
" fprintf(fp, \"Here's the output.\\n\");\n"
"}\n"
"\n"
"int main()\n"
"{\n"
" fp = fopen(\"test.txt\", \"w\");\n"
" dump();\n"
" close();\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("static FILE *fp = NULL;\n"
"\n"
"void close()\n"
"{\n"
" fclose(fp);\n"
"}\n"
"\n"
"void dump()\n"
"{\n"
" fclose(fp);\n"
" fprintf(fp, \"Here's the output.\\n\");\n"
"}");
ASSERT_EQUALS("[test.cpp:11]: (error) Used file that is not opened.\n", errout_str());
// #4466
check("void chdcd_parse_nero(FILE *infile) {\n"
" switch (mode) {\n"
" case 0x0300:\n"
" fclose(infile);\n"
" return;\n"
" case 0x0500:\n"
" fclose(infile);\n"
" return;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void chdcd_parse_nero(FILE *infile) {\n"
" switch (mode) {\n"
" case 0x0300:\n"
" fclose(infile);\n"
" exit(0);\n"
" case 0x0500:\n"
" fclose(infile);\n"
" return;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// #4649
check("void foo() {\n"
" struct {FILE *f1; FILE *f2;} a;\n"
" a.f1 = fopen(name,mode);\n"
" a.f2 = fopen(name,mode);\n"
" fclose(a.f1);\n"
" fclose(a.f2);\n"
"}");
ASSERT_EQUALS("", errout_str());
// #1473
check("void foo() {\n"
" FILE *a = fopen(\"aa\", \"r\");\n"
" while (fclose(a)) {}\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:3]: (error) Used file that is not opened.\n", "", errout_str());
// #6823
check("void foo() {\n"
" FILE f[2];\n"
" f[0] = fopen(\"1\", \"w\");\n"
" f[1] = fopen(\"2\", \"w\");\n"
" fclose(f[0]);\n"
" fclose(f[1]);\n"
"}");
ASSERT_EQUALS("", errout_str());
// #12236
check("void f() {\n"
" FILE* f = fopen(\"abc\", \"r\");\n"
" decltype(fclose(f)) y;\n"
" y = fclose(f);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void fileIOwithoutPositioning() {
check("void foo(FILE* f) {\n"
" fwrite(buffer, 5, 6, f);\n"
" fread(buffer, 5, 6, f);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Read and write operations without a call to a positioning function (fseek, fsetpos or rewind) or fflush in between result in undefined behaviour.\n", errout_str());
check("void foo(FILE* f) {\n"
" fread(buffer, 5, 6, f);\n"
" fwrite(buffer, 5, 6, f);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Read and write operations without a call to a positioning function (fseek, fsetpos or rewind) or fflush in between result in undefined behaviour.\n", errout_str());
check("void foo(FILE* f, bool read) {\n"
" if(read)\n"
" fread(buffer, 5, 6, f);\n"
" else\n"
" fwrite(buffer, 5, 6, f);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(FILE* f) {\n"
" fread(buffer, 5, 6, f);\n"
" fflush(f);\n"
" fwrite(buffer, 5, 6, f);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(FILE* f) {\n"
" fread(buffer, 5, 6, f);\n"
" rewind(f);\n"
" fwrite(buffer, 5, 6, f);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(FILE* f) {\n"
" fread(buffer, 5, 6, f);\n"
" fsetpos(f, pos);\n"
" fwrite(buffer, 5, 6, f);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(FILE* f) {\n"
" fread(buffer, 5, 6, f);\n"
" fseek(f, 0, SEEK_SET);\n"
" fwrite(buffer, 5, 6, f);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(FILE* f) {\n"
" fread(buffer, 5, 6, f);\n"
" long pos = ftell(f);\n"
" fwrite(buffer, 5, 6, f);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Read and write operations without a call to a positioning function (fseek, fsetpos or rewind) or fflush in between result in undefined behaviour.\n", errout_str());
// #6452 - member functions
check("class FileStream {\n"
" void insert(const ByteVector &data, ulong start);\n"
" void seek(long offset, Position p);\n"
" FileStreamPrivate *d;\n"
"};\n"
"void FileStream::insert(const ByteVector &data, ulong start) {\n"
" int bytesRead = fread(aboutToOverwrite.data(), 1, bufferLength, d->file);\n"
" seek(writePosition);\n"
" fwrite(buffer.data(), sizeof(char), buffer.size(), d->file);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("class FileStream {\n"
" void insert(const ByteVector &data, ulong start);\n"
" FileStreamPrivate *d;\n"
"};\n"
"void FileStream::insert(const ByteVector &data, ulong start) {\n"
" int bytesRead = fread(aboutToOverwrite.data(), 1, bufferLength, d->file);\n"
" unknown(writePosition);\n"
" fwrite(buffer.data(), sizeof(char), buffer.size(), d->file);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("class FileStream {\n"
" void insert(const ByteVector &data, ulong start);\n"
" FileStreamPrivate *d;\n"
"};\n"
"void known(int);\n"
"void FileStream::insert(const ByteVector &data, ulong start) {\n"
" int bytesRead = fread(aboutToOverwrite.data(), 1, bufferLength, d->file);\n"
" known(writePosition);\n"
" fwrite(buffer.data(), sizeof(char), buffer.size(), d->file);\n"
"}");
ASSERT_EQUALS("[test.cpp:9]: (error) Read and write operations without a call to a positioning function (fseek, fsetpos or rewind) or fflush in between result in undefined behaviour.\n", errout_str());
check("class FileStream {\n"
" void insert(const ByteVector &data, ulong start);\n"
" FileStreamPrivate *d;\n"
"};\n"
"void known(int);\n"
"void FileStream::insert(const ByteVector &data, ulong start) {\n"
" int bytesRead = fread(X::data(), 1, bufferLength, d->file);\n"
" known(writePosition);\n"
" fwrite(X::data(), sizeof(char), buffer.size(), d->file);\n"
"}");
ASSERT_EQUALS("[test.cpp:9]: (error) Read and write operations without a call to a positioning function (fseek, fsetpos or rewind) or fflush in between result in undefined behaviour.\n", errout_str());
}
void seekOnAppendedFile() {
check("void foo() {\n"
" FILE* f = fopen(\"\", \"a+\");\n"
" fseek(f, 0, SEEK_SET);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" FILE* f = fopen(\"\", \"w\");\n"
" fseek(f, 0, SEEK_SET);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" FILE* f = fopen(\"\", \"a\");\n"
" fseek(f, 0, SEEK_SET);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Repositioning operation performed on a file opened in append mode has no effect.\n", errout_str());
check("void foo() {\n"
" FILE* f = fopen(\"\", \"a\");\n"
" fflush(f);\n"
"}");
ASSERT_EQUALS("", errout_str()); // #5578
check("void foo() {\n"
" FILE* f = fopen(\"\", \"a\");\n"
" fclose(f);\n"
" f = fopen(\"\", \"r\");\n"
" fseek(f, 0, SEEK_SET);\n"
"}");
ASSERT_EQUALS("", errout_str()); // #6566
}
void fflushOnInputStream() {
check("void foo()\n"
"{\n"
" fflush(stdin);\n"
"}", dinit(CheckOptions, $.portability = true));
ASSERT_EQUALS("[test.cpp:3]: (portability) fflush() called on input stream 'stdin' may result in undefined behaviour on non-linux systems.\n", errout_str());
check("void foo()\n"
"{\n"
" fflush(stdout);\n"
"}", dinit(CheckOptions, $.portability = true));
ASSERT_EQUALS("", errout_str());
check("void foo(FILE*& f) {\n"
" f = fopen(path, \"r\");\n"
" fflush(f);\n"
"}", dinit(CheckOptions, $.portability = true));
ASSERT_EQUALS("[test.cpp:3]: (portability) fflush() called on input stream 'f' may result in undefined behaviour on non-linux systems.\n", errout_str());
check("void foo(FILE*& f) {\n"
" f = fopen(path, \"w\");\n"
" fflush(f);\n"
"}", dinit(CheckOptions, $.portability = true));
ASSERT_EQUALS("", errout_str());
check("void foo(FILE*& f) {\n"
" fflush(f);\n"
"}", dinit(CheckOptions, $.portability = true));
ASSERT_EQUALS("", errout_str());
}
void incompatibleFileOpen() {
check("void foo() {\n"
" FILE *f1 = fopen(\"tmp\", \"wt\");\n"
" FILE *f2 = fopen(\"tmp\", \"rt\");\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) The file '\"tmp\"' is opened for read and write access at the same time on different streams\n", errout_str());
}
void testScanf1() {
check("void foo() {\n"
" int a, b;\n"
" FILE *file = fopen(\"test\", \"r\");\n"
" a = fscanf(file, \"aa %s\", bar);\n"
" b = scanf(\"aa %S\", bar);\n"
" b = scanf(\"aa %ls\", bar);\n"
" sscanf(foo, \"%[^~]\", bar);\n"
" scanf(\"%dx%s\", &b, bar);\n"
" fclose(file);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (warning) fscanf() without field width limits can crash with huge input data.\n"
"[test.cpp:5]: (warning) scanf() without field width limits can crash with huge input data.\n"
"[test.cpp:6]: (warning) scanf() without field width limits can crash with huge input data.\n"
"[test.cpp:7]: (warning) sscanf() without field width limits can crash with huge input data.\n"
"[test.cpp:8]: (warning) scanf() without field width limits can crash with huge input data.\n", errout_str());
}
void testScanf2() {
check("void foo() {\n"
" scanf(\"%5s\", bar);\n" // Width specifier given
" scanf(\"%5[^~]\", bar);\n" // Width specifier given
" scanf(\"aa%%s\", bar);\n" // No %s
" scanf(\"aa%d\", &a);\n" // No %s
" scanf(\"aa%ld\", &a);\n" // No %s
" scanf(\"%*[^~]\");\n" // Ignore input
"}");
ASSERT_EQUALS("[test.cpp:4]: (warning) scanf format string requires 0 parameters but 1 is given.\n", errout_str());
}
void testScanf3() { // ticket #3494
check("void f() {\n"
" char str[8];\n"
" scanf(\"%7c\", str);\n"
" scanf(\"%8c\", str);\n"
" scanf(\"%9c\", str);\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Width 9 given in format string (no. 1) is larger than destination buffer 'str[8]', use %8c to prevent overflowing it.\n", errout_str());
}
void testScanf4() { // ticket #2553
check("void f()\n"
"{\n"
" char str [8];\n"
" scanf (\"%70s\",str);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Width 70 given in format string (no. 1) is larger than destination buffer 'str[8]', use %7s to prevent overflowing it.\n", errout_str());
}
void testScanf5() { // #10632
check("char s1[42], s2[42];\n"
"void test() {\n"
" scanf(\"%42s%42[a-z]\", s1, s2);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Width 42 given in format string (no. 1) is larger than destination buffer 's1[42]', use %41s to prevent overflowing it.\n"
"[test.cpp:3]: (error) Width 42 given in format string (no. 2) is larger than destination buffer 's2[42]', use %41[a-z] to prevent overflowing it.\n", errout_str());
}
#define TEST_SCANF_CODE(format, type) \
"void f(){" type " x; scanf(\"" format "\", &x);}"
#define TEST_SCANF_ERR(format, formatStr, type) \
"[test.c:1]: (warning) " format " in format string (no. 1) requires '" formatStr " *' but the argument type is '" type " *'.\n"
#define TEST_SCANF_ERR_AKA_(file, format, formatStr, type, akaType) \
"[" file ":1]: (portability) " format " in format string (no. 1) requires '" formatStr " *' but the argument type is '" type " * {aka " akaType " *}'.\n"
#define TEST_SCANF_ERR_AKA(format, formatStr, type, akaType) \
TEST_SCANF_ERR_AKA_("test.c", format, formatStr, type, akaType)
#define TEST_SCANF_ERR_AKA_CPP(format, formatStr, type, akaType) \
TEST_SCANF_ERR_AKA_("test.cpp", format, formatStr, type, akaType)
#define TEST_PRINTF_CODE(format, type) \
"void f(" type " x){printf(\"" format "\", x);}"
#define TEST_PRINTF_ERR(format, requiredType, actualType) \
"[test.c:1]: (warning) " format " in format string (no. 1) requires '" requiredType "' but the argument type is '" actualType "'.\n"
#define TEST_PRINTF_ERR_AKA_(file, format, requiredType, actualType, akaType) \
"[" file ":1]: (portability) " format " in format string (no. 1) requires '" requiredType "' but the argument type is '" actualType " {aka " akaType "}'.\n"
#define TEST_PRINTF_ERR_AKA(format, requiredType, actualType, akaType) \
TEST_PRINTF_ERR_AKA_("test.c", format, requiredType, actualType, akaType)
#define TEST_PRINTF_ERR_AKA_CPP(format, requiredType, actualType, akaType) \
TEST_PRINTF_ERR_AKA_("test.cpp", format, requiredType, actualType, akaType)
template<size_t size>
void testFormatStrNoWarn(const char *filename, unsigned int linenr, const char (&code)[size],
bool cpp = false) {
check(code, dinit(CheckOptions, $.inconclusive = true, $.platform = Platform::Type::Unix32, $.onlyFormatStr = true, $.cpp = cpp));
assertEquals(filename, linenr, emptyString, errout_str());
check(code, dinit(CheckOptions, $.inconclusive = true, $.platform = Platform::Type::Unix64, $.onlyFormatStr = true, $.cpp = cpp));
assertEquals(filename, linenr, emptyString, errout_str());
check(code, dinit(CheckOptions, $.inconclusive = true, $.platform = Platform::Type::Win32A, $.onlyFormatStr = true, $.cpp = cpp));
assertEquals(filename, linenr, emptyString, errout_str());
check(code, dinit(CheckOptions, $.inconclusive = true, $.platform = Platform::Type::Win32W, $.onlyFormatStr = true, $.cpp = cpp));
assertEquals(filename, linenr, emptyString, errout_str());
check(code, dinit(CheckOptions, $.inconclusive = true, $.platform = Platform::Type::Win64, $.onlyFormatStr = true, $.cpp = cpp));
assertEquals(filename, linenr, emptyString, errout_str());
}
template<size_t size>
void testFormatStrWarn(const char *filename, unsigned int linenr,
const char (&code)[size], const char* testScanfErrString,
bool cpp = false) {
check(code, dinit(CheckOptions, $.inconclusive = true, $.platform = Platform::Type::Unix32, $.onlyFormatStr = true, $.cpp = cpp));
assertEquals(filename, linenr, testScanfErrString, errout_str());
check(code, dinit(CheckOptions, $.inconclusive = true, $.platform = Platform::Type::Unix64, $.onlyFormatStr = true, $.cpp = cpp));
assertEquals(filename, linenr, testScanfErrString, errout_str());
check(code, dinit(CheckOptions, $.inconclusive = true, $.platform = Platform::Type::Win32A, $.onlyFormatStr = true, $.cpp = cpp));
assertEquals(filename, linenr, testScanfErrString, errout_str());
check(code, dinit(CheckOptions, $.inconclusive = true, $.platform = Platform::Type::Win32W, $.onlyFormatStr = true, $.cpp = cpp));
assertEquals(filename, linenr, testScanfErrString, errout_str());
check(code, dinit(CheckOptions, $.inconclusive = true, $.platform = Platform::Type::Win64, $.onlyFormatStr = true, $.cpp = cpp));
assertEquals(filename, linenr, testScanfErrString, errout_str());
}
template<size_t size>
void testFormatStrWarnAka(const char *filename, unsigned int linenr,
const char (&code)[size], const char* testScanfErrAkaString, const char* testScanfErrAkaWin64String,
bool cpp = false) {
check(code, dinit(CheckOptions, $.inconclusive = true, $.portability = true, $.platform = Platform::Type::Unix32, $.onlyFormatStr = true, $.cpp = cpp));
assertEquals(filename, linenr, testScanfErrAkaString, errout_str());
check(code, dinit(CheckOptions, $.inconclusive = true, $.portability = true, $.platform = Platform::Type::Unix64, $.onlyFormatStr = true, $.cpp = cpp));
assertEquals(filename, linenr, testScanfErrAkaString, errout_str());
check(code, dinit(CheckOptions, $.inconclusive = true, $.portability = true, $.platform = Platform::Type::Win32A, $.onlyFormatStr = true, $.cpp = cpp));
assertEquals(filename, linenr, testScanfErrAkaString, errout_str());
check(code, dinit(CheckOptions, $.inconclusive = true, $.portability = true, $.platform = Platform::Type::Win32W, $.onlyFormatStr = true, $.cpp = cpp));
assertEquals(filename, linenr, testScanfErrAkaString, errout_str());
check(code, dinit(CheckOptions, $.inconclusive = true, $.portability = true, $.platform = Platform::Type::Win64, $.onlyFormatStr = true, $.cpp = cpp));
assertEquals(filename, linenr, testScanfErrAkaWin64String, errout_str());
}
template<size_t size>
void testFormatStrWarnAkaWin64(const char *filename, unsigned int linenr,
const char (&code)[size], const char* testScanfErrAkaWin64String,
bool cpp = false) {
check(code, dinit(CheckOptions, $.inconclusive = true, $.portability = true, $.platform = Platform::Type::Unix32, $.onlyFormatStr = true, $.cpp = cpp));
assertEquals(filename, linenr, emptyString, errout_str());
check(code, dinit(CheckOptions, $.inconclusive = true, $.portability = true, $.platform = Platform::Type::Unix64, $.onlyFormatStr = true, $.cpp = cpp));
assertEquals(filename, linenr, emptyString, errout_str());
check(code, dinit(CheckOptions, $.inconclusive = true, $.portability = true, $.platform = Platform::Type::Win32A, $.onlyFormatStr = true, $.cpp = cpp));
assertEquals(filename, linenr, emptyString, errout_str());
check(code, dinit(CheckOptions, $.inconclusive = true, $.portability = true, $.platform = Platform::Type::Win32W, $.onlyFormatStr = true, $.cpp = cpp));
assertEquals(filename, linenr, emptyString, errout_str());
check(code, dinit(CheckOptions, $.inconclusive = true, $.portability = true, $.platform = Platform::Type::Win64, $.onlyFormatStr = true, $.cpp = cpp));
assertEquals(filename, linenr, testScanfErrAkaWin64String, errout_str());
}
template<size_t size>
void testFormatStrWarnAkaWin32(const char *filename, unsigned int linenr,
const char (&code)[size], const char* testScanfErrAkaString,
bool cpp = false) {
check(code, dinit(CheckOptions, $.inconclusive = true, $.portability = true, $.platform = Platform::Type::Unix32, $.onlyFormatStr = true, $.cpp = cpp));
assertEquals(filename, linenr, testScanfErrAkaString, errout_str());
check(code, dinit(CheckOptions, $.inconclusive = true, $.portability = true, $.platform = Platform::Type::Unix64, $.onlyFormatStr = true, $.cpp = cpp));
assertEquals(filename, linenr, testScanfErrAkaString, errout_str());
check(code, dinit(CheckOptions, $.inconclusive = true, $.portability = true, $.platform = Platform::Type::Win32A, $.onlyFormatStr = true, $.cpp = cpp));
assertEquals(filename, linenr, testScanfErrAkaString, errout_str());
check(code, dinit(CheckOptions, $.inconclusive = true, $.portability = true, $.platform = Platform::Type::Win32W, $.onlyFormatStr = true, $.cpp = cpp));
assertEquals(filename, linenr, testScanfErrAkaString, errout_str());
check(code, dinit(CheckOptions, $.inconclusive = true, $.portability = true, $.platform = Platform::Type::Win64, $.onlyFormatStr = true, $.cpp = cpp));
assertEquals(filename, linenr, emptyString, errout_str());
}
#define TEST_SCANF_NOWARN(FORMAT, FORMATSTR, TYPE) \
testFormatStrNoWarn(__FILE__, __LINE__, TEST_SCANF_CODE(FORMAT, TYPE))
#define TEST_SCANF_NOWARN_CPP(FORMAT, FORMATSTR, TYPE) \
testFormatStrNoWarn(__FILE__, __LINE__, TEST_SCANF_CODE(FORMAT, TYPE), true)
#define TEST_SCANF_WARN(FORMAT, FORMATSTR, TYPE) \
testFormatStrWarn(__FILE__, __LINE__, TEST_SCANF_CODE(FORMAT, TYPE), TEST_SCANF_ERR(FORMAT, FORMATSTR, TYPE))
#define TEST_SCANF_WARN_AKA(FORMAT, FORMATSTR, TYPE, AKATYPE, AKATYPE_WIN64) \
testFormatStrWarnAka(__FILE__, __LINE__, TEST_SCANF_CODE(FORMAT, TYPE), TEST_SCANF_ERR_AKA(FORMAT, FORMATSTR, TYPE, AKATYPE), TEST_SCANF_ERR_AKA(FORMAT, FORMATSTR, TYPE, AKATYPE_WIN64))
#define TEST_SCANF_WARN_AKA_CPP(FORMAT, FORMATSTR, TYPE, AKATYPE, AKATYPE_WIN64) \
testFormatStrWarnAka(__FILE__, __LINE__, TEST_SCANF_CODE(FORMAT, TYPE), TEST_SCANF_ERR_AKA_CPP(FORMAT, FORMATSTR, TYPE, AKATYPE), TEST_SCANF_ERR_AKA_CPP(FORMAT, FORMATSTR, TYPE, AKATYPE_WIN64), true)
#define TEST_SCANF_WARN_AKA_WIN64(FORMAT, FORMATSTR, TYPE, AKATYPE_WIN64) \
testFormatStrWarnAkaWin64(__FILE__, __LINE__, TEST_SCANF_CODE(FORMAT, TYPE), TEST_SCANF_ERR_AKA(FORMAT, FORMATSTR, TYPE, AKATYPE_WIN64))
#define TEST_SCANF_WARN_AKA_CPP_WIN64(FORMAT, FORMATSTR, TYPE, AKATYPE_WIN64) \
testFormatStrWarnAkaWin64(__FILE__, __LINE__, TEST_SCANF_CODE(FORMAT, TYPE), TEST_SCANF_ERR_AKA_CPP(FORMAT, FORMATSTR, TYPE, AKATYPE_WIN64), true)
#define TEST_SCANF_WARN_AKA_WIN32(FORMAT, FORMATSTR, TYPE, AKATYPE_WIN32) \
testFormatStrWarnAkaWin32(__FILE__, __LINE__, TEST_SCANF_CODE(FORMAT, TYPE), TEST_SCANF_ERR_AKA(FORMAT, FORMATSTR, TYPE, AKATYPE_WIN32))
#define TEST_SCANF_WARN_AKA_CPP_WIN32(FORMAT, FORMATSTR, TYPE, AKATYPE_WIN32) \
testFormatStrWarnAkaWin32(__FILE__, __LINE__, TEST_SCANF_CODE(FORMAT, TYPE), TEST_SCANF_ERR_AKA_CPP(FORMAT, FORMATSTR, TYPE, AKATYPE_WIN32), true)
#define TEST_PRINTF_NOWARN(FORMAT, FORMATSTR, TYPE) \
testFormatStrNoWarn(__FILE__, __LINE__, TEST_PRINTF_CODE(FORMAT, TYPE))
#define TEST_PRINTF_NOWARN_CPP(FORMAT, FORMATSTR, TYPE) \
testFormatStrNoWarn(__FILE__, __LINE__, TEST_PRINTF_CODE(FORMAT, TYPE), true)
#define TEST_PRINTF_WARN(FORMAT, FORMATSTR, TYPE) \
testFormatStrWarn(__FILE__, __LINE__, TEST_PRINTF_CODE(FORMAT, TYPE), TEST_PRINTF_ERR(FORMAT, FORMATSTR, TYPE))
#define TEST_PRINTF_WARN_AKA(FORMAT, FORMATSTR, TYPE, AKATYPE, AKATYPE_WIN64) \
testFormatStrWarnAka(__FILE__, __LINE__, TEST_PRINTF_CODE(FORMAT, TYPE), TEST_PRINTF_ERR_AKA(FORMAT, FORMATSTR, TYPE, AKATYPE), TEST_PRINTF_ERR_AKA(FORMAT, FORMATSTR, TYPE, AKATYPE_WIN64))
#define TEST_PRINTF_WARN_AKA_CPP(FORMAT, FORMATSTR, TYPE, AKATYPE, AKATYPE_WIN64) \
testFormatStrWarnAka(__FILE__, __LINE__, TEST_PRINTF_CODE(FORMAT, TYPE), TEST_PRINTF_ERR_AKA_CPP(FORMAT, FORMATSTR, TYPE, AKATYPE), TEST_PRINTF_ERR_AKA_CPP(FORMAT, FORMATSTR, TYPE, AKATYPE_WIN64), true)
#define TEST_PRINTF_WARN_AKA_WIN64(FORMAT, FORMATSTR, TYPE, AKATYPE_WIN64) \
testFormatStrWarnAkaWin64(__FILE__, __LINE__, TEST_PRINTF_CODE(FORMAT, TYPE), TEST_PRINTF_ERR_AKA(FORMAT, FORMATSTR, TYPE, AKATYPE_WIN64))
#define TEST_PRINTF_WARN_AKA_CPP_WIN64(FORMAT, FORMATSTR, TYPE, AKATYPE_WIN64) \
testFormatStrWarnAkaWin64(__FILE__, __LINE__, TEST_PRINTF_CODE(FORMAT, TYPE), TEST_PRINTF_ERR_AKA_CPP(FORMAT, FORMATSTR, TYPE, AKATYPE_WIN64), true)
#define TEST_PRINTF_WARN_AKA_WIN32(FORMAT, FORMATSTR, TYPE, AKATYPE_WIN32) \
testFormatStrWarnAkaWin32(__FILE__, __LINE__, TEST_PRINTF_CODE(FORMAT, TYPE), TEST_PRINTF_ERR_AKA(FORMAT, FORMATSTR, TYPE, AKATYPE_WIN32))
#define TEST_PRINTF_WARN_AKA_CPP_WIN32(FORMAT, FORMATSTR, TYPE, AKATYPE_WIN32) \
testFormatStrWarnAkaWin32(__FILE__, __LINE__, TEST_PRINTF_CODE(FORMAT, TYPE), TEST_PRINTF_ERR_AKA_CPP(FORMAT, FORMATSTR, TYPE, AKATYPE_WIN32), true)
void testScanfArgument() {
check("void foo() {\n"
" scanf(\"%1d\", &foo);\n"
" sscanf(bar, \"%1d\", &foo);\n"
" scanf(\"%1u%1u\", &foo, bar());\n"
" scanf(\"%*1x %1x %29s\", &count, KeyName);\n" // #3373
" fscanf(f, \"%7ms\", &ref);\n" // #3461
" sscanf(ip_port, \"%*[^:]:%4d\", &port);\n" // #3468
"}");
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" scanf(\"\", &foo);\n"
" scanf(\"%1d\", &foo, &bar);\n"
" fscanf(bar, \"%1d\", &foo, &bar);\n"
" scanf(\"%*1x %1x %29s\", &count, KeyName, foo);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) scanf format string requires 0 parameters but 1 is given.\n"
"[test.cpp:3]: (warning) scanf format string requires 1 parameter but 2 are given.\n"
"[test.cpp:4]: (warning) fscanf format string requires 1 parameter but 2 are given.\n"
"[test.cpp:5]: (warning) scanf format string requires 2 parameters but 3 are given.\n", errout_str());
check("void foo() {\n"
" scanf(\"%1d\");\n"
" scanf(\"%1u%1u\", bar());\n"
" sscanf(bar, \"%1d%1d\", &foo);\n"
" scanf(\"%*1x %1x %29s\", &count);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) scanf format string requires 1 parameter but only 0 are given.\n"
"[test.cpp:3]: (error) scanf format string requires 2 parameters but only 1 is given.\n"
"[test.cpp:4]: (error) sscanf format string requires 2 parameters but only 1 is given.\n"
"[test.cpp:5]: (error) scanf format string requires 2 parameters but only 1 is given.\n", errout_str());
check("void foo() {\n"
" char input[10];\n"
" char output[5];\n"
" sscanf(input, \"%3s\", output);\n"
" sscanf(input, \"%4s\", output);\n"
" sscanf(input, \"%5s\", output);\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Width 5 given in format string (no. 1) is larger than destination buffer 'output[5]', use %4s to prevent overflowing it.\n", errout_str());
check("void foo() {\n"
" char input[10];\n"
" char output[5];\n"
" sscanf(input, \"%s\", output);\n"
" sscanf(input, \"%3s\", output);\n"
" sscanf(input, \"%4s\", output);\n"
" sscanf(input, \"%5s\", output);\n"
"}", dinit(CheckOptions, $.inconclusive = true));
ASSERT_EQUALS("[test.cpp:5]: (warning, inconclusive) Width 3 given in format string (no. 1) is smaller than destination buffer 'output[5]'.\n"
"[test.cpp:7]: (error) Width 5 given in format string (no. 1) is larger than destination buffer 'output[5]', use %4s to prevent overflowing it.\n"
"[test.cpp:4]: (warning) sscanf() without field width limits can crash with huge input data.\n", errout_str());
check("void foo() {\n"
" const size_t BUFLENGTH(2048);\n"
" typedef char bufT[BUFLENGTH];\n"
" bufT line= {0};\n"
" bufT projectId= {0};\n"
" const int scanrc=sscanf(line, \"Project(\\\"{%36s}\\\")\", projectId);\n"
" sscanf(input, \"%5s\", output);\n"
"}", dinit(CheckOptions, $.inconclusive = true));
ASSERT_EQUALS("[test.cpp:6]: (warning, inconclusive) Width 36 given in format string (no. 1) is smaller than destination buffer 'projectId[2048]'.\n", errout_str());
check("void foo(unsigned int i) {\n"
" scanf(\"%h\", &i);\n"
" scanf(\"%hh\", &i);\n"
" scanf(\"%l\", &i);\n"
" scanf(\"%ll\", &i);\n"
" scanf(\"%j\", &i);\n"
" scanf(\"%z\", &i);\n"
" scanf(\"%t\", &i);\n"
" scanf(\"%L\", &i);\n"
" scanf(\"%I\", &i);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) 'h' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:3]: (warning) 'hh' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:4]: (warning) 'l' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:5]: (warning) 'll' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:6]: (warning) 'j' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:7]: (warning) 'z' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:8]: (warning) 't' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:9]: (warning) 'L' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:10]: (warning) 'I' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n", errout_str());
// Unrecognized (and non-existent in standard library) specifiers.
// Perhaps should emit warnings
TEST_SCANF_NOWARN("%jb", "intmax_t", "intmax_t");
TEST_SCANF_NOWARN("%jw", "uintmax_t", "uintmax_t");
TEST_SCANF_NOWARN("%zr", "size_t", "size_t");
TEST_SCANF_NOWARN("%tm", "ptrdiff_t", "ptrdiff_t");
TEST_SCANF_NOWARN("%La", "long double", "long double");
TEST_SCANF_NOWARN_CPP("%zv", "std::size_t", "std::size_t");
TEST_SCANF_NOWARN_CPP("%tp", "std::ptrdiff_t", "std::ptrdiff_t");
TEST_SCANF_WARN("%u", "unsigned int", "bool");
TEST_SCANF_WARN("%u", "unsigned int", "char");
TEST_SCANF_WARN("%u", "unsigned int", "signed char");
TEST_SCANF_WARN("%u", "unsigned int", "unsigned char");
TEST_SCANF_WARN("%u", "unsigned int", "signed short");
TEST_SCANF_WARN("%u", "unsigned int", "unsigned short");
TEST_SCANF_WARN("%u", "unsigned int", "signed int");
TEST_SCANF_NOWARN("%u", "unsigned int", "unsigned int");
TEST_SCANF_WARN("%u", "unsigned int", "signed long");
TEST_SCANF_WARN("%u", "unsigned int", "unsigned long");
TEST_SCANF_WARN("%u", "unsigned int", "signed long long");
TEST_SCANF_WARN("%u", "unsigned int", "unsigned long long");
TEST_SCANF_WARN("%u", "unsigned int", "float");
TEST_SCANF_WARN("%u", "unsigned int", "double");
TEST_SCANF_WARN("%u", "unsigned int", "long double");
TEST_SCANF_WARN("%u", "unsigned int", "void *");
TEST_SCANF_WARN_AKA("%u", "unsigned int", "size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%u", "unsigned int", "ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%u", "unsigned int", "ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%u", "unsigned int", "unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%u", "unsigned int", "intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%u", "unsigned int", "uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%u", "unsigned int", "intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%u", "unsigned int", "uintptr_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%u", "unsigned int", "std::size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%u", "unsigned int", "std::ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%u", "unsigned int", "std::ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%u", "unsigned int", "std::intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%u", "unsigned int", "std::uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%u", "unsigned int", "std::intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%u", "unsigned int", "std::uintptr_t", "unsigned long", "unsigned long long");
check("void foo() {\n"
" scanf(\"%u\", \"s3\");\n"
" scanf(\"%u\", L\"s5W\");\n"
"}", dinit(CheckOptions, $.inconclusive = true));
ASSERT_EQUALS("[test.cpp:2]: (warning) %u in format string (no. 1) requires 'unsigned int *' but the argument type is 'const char *'.\n"
"[test.cpp:3]: (warning) %u in format string (no. 1) requires 'unsigned int *' but the argument type is 'const wchar_t *'.\n", errout_str());
check("void foo(long l) {\n"
" scanf(\"%u\", l);\n"
"}", dinit(CheckOptions, $.inconclusive = true));
ASSERT_EQUALS("[test.cpp:2]: (warning) %u in format string (no. 1) requires 'unsigned int *' but the argument type is 'signed long'.\n", errout_str());
TEST_SCANF_WARN("%lu","unsigned long","bool");
TEST_SCANF_WARN("%lu","unsigned long","char");
TEST_SCANF_WARN("%lu","unsigned long","signed char");
TEST_SCANF_WARN("%lu","unsigned long","unsigned char");
TEST_SCANF_WARN("%lu","unsigned long","signed short");
TEST_SCANF_WARN("%lu","unsigned long","unsigned short");
TEST_SCANF_WARN("%lu","unsigned long","signed int");
TEST_SCANF_WARN("%lu","unsigned long","unsigned int");
TEST_SCANF_WARN("%lu","unsigned long","signed long");
TEST_SCANF_NOWARN("%lu","unsigned long","unsigned long");
TEST_SCANF_WARN("%lu","unsigned long","signed long long");
TEST_SCANF_WARN("%lu","unsigned long","unsigned long long");
TEST_SCANF_WARN("%lu","unsigned long","float");
TEST_SCANF_WARN("%lu","unsigned long","double");
TEST_SCANF_WARN("%lu","unsigned long","long double");
TEST_SCANF_WARN("%lu","unsigned long","void *");
TEST_SCANF_WARN_AKA("%lu","unsigned long","size_t","unsigned long","unsigned long long");
TEST_SCANF_WARN_AKA("%lu","unsigned long","ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%lu","unsigned long","ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%lu","unsigned long","unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%lu","unsigned long","intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%lu","unsigned long","uintmax_t","unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%lu","unsigned long","intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_WIN64("%lu","unsigned long","uintptr_t", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%lu","unsigned long","std::size_t","unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%lu","unsigned long","std::ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%lu","unsigned long","std::ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%lu","unsigned long","std::intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%lu","unsigned long","std::uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%lu","unsigned long","std::intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP_WIN64("%lu","unsigned long","std::uintptr_t", "unsigned long long");
TEST_SCANF_WARN("%lx","unsigned long","bool");
TEST_SCANF_WARN("%lx","unsigned long","char");
TEST_SCANF_WARN("%lx","unsigned long","signed char");
TEST_SCANF_WARN("%lx","unsigned long","unsigned char");
TEST_SCANF_WARN("%lx","unsigned long","signed short");
TEST_SCANF_WARN("%lx","unsigned long","unsigned short");
TEST_SCANF_WARN("%lx","unsigned long","signed int");
TEST_SCANF_WARN("%lx","unsigned long","unsigned int");
TEST_SCANF_WARN("%lx","unsigned long","signed long");
TEST_SCANF_NOWARN("%lx","unsigned long","unsigned long");
TEST_SCANF_WARN("%lx","unsigned long","signed long long");
TEST_SCANF_WARN("%lx","unsigned long","unsigned long long");
TEST_SCANF_WARN("%lx","unsigned long","float");
TEST_SCANF_WARN("%lx","unsigned long","double");
TEST_SCANF_WARN("%lx","unsigned long","long double");
TEST_SCANF_WARN("%lx","unsigned long","void *");
TEST_SCANF_WARN_AKA("%lx","unsigned long","size_t","unsigned long","unsigned long long");
TEST_SCANF_WARN_AKA("%lx","unsigned long","ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%lx","unsigned long","ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%lx","unsigned long","unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%lx","unsigned long","intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%lx","unsigned long","uintmax_t","unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%lx","unsigned long","intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_WIN64("%lx","unsigned long","uintptr_t", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%lx","unsigned long","std::size_t","unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%lx","unsigned long","std::ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%lx","unsigned long","std::ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%lx","unsigned long","std::intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%lx","unsigned long","std::uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%lx","unsigned long","std::intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP_WIN64("%lx","unsigned long","std::uintptr_t", "unsigned long long");
TEST_SCANF_WARN("%ld","long","bool");
TEST_SCANF_WARN("%ld","long","char");
TEST_SCANF_NOWARN("%ld","long","signed long");
TEST_SCANF_WARN("%ld","long","unsigned long");
TEST_SCANF_WARN("%ld","long","void *");
TEST_SCANF_WARN_AKA("%ld","long","size_t","unsigned long","unsigned long long");
TEST_SCANF_WARN_AKA("%ld","long","intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%ld","long","std::ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%ld","long","std::intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP_WIN64("%ld","long","std::intptr_t", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%ld","long","std::uintptr_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN("%llu","unsigned long long","bool");
TEST_SCANF_WARN("%llu","unsigned long long","char");
TEST_SCANF_WARN("%llu","unsigned long long","signed char");
TEST_SCANF_WARN("%llu","unsigned long long","unsigned char");
TEST_SCANF_WARN("%llu","unsigned long long","signed short");
TEST_SCANF_WARN("%llu","unsigned long long","unsigned short");
TEST_SCANF_WARN("%llu","unsigned long long","signed int");
TEST_SCANF_WARN("%llu","unsigned long long","unsigned int");
TEST_SCANF_WARN("%llu","unsigned long long","signed long");
TEST_SCANF_WARN("%llu","unsigned long long","unsigned long");
TEST_SCANF_WARN("%llu","unsigned long long","signed long long");
TEST_SCANF_NOWARN("%llu","unsigned long long","unsigned long long");
TEST_SCANF_WARN("%llu","unsigned long long","float");
TEST_SCANF_WARN("%llu","unsigned long long","double");
TEST_SCANF_WARN("%llu","unsigned long long","long double");
TEST_SCANF_WARN("%llu","unsigned long long","void *");
TEST_SCANF_WARN_AKA("%llu","unsigned long long","size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%llu","unsigned long long","ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%llu","unsigned long long","ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%llu","unsigned long long","unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%llu","unsigned long long","intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%llu","unsigned long long","uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%llu","unsigned long long","intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_WIN32("%llu","unsigned long long","uintptr_t", "unsigned long");
TEST_SCANF_WARN_AKA_CPP("%llu","unsigned long long","std::size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%llu","unsigned long long","std::ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%llu","unsigned long long","std::ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%llu","unsigned long long","std::intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%llu","unsigned long long","std::uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%llu","unsigned long long","std::intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP_WIN32("%llu","unsigned long long","std::uintptr_t", "unsigned long");
TEST_SCANF_WARN("%llx","unsigned long long","bool");
TEST_SCANF_WARN("%llx","unsigned long long","char");
TEST_SCANF_WARN("%llx","unsigned long long","signed char");
TEST_SCANF_WARN("%llx","unsigned long long","unsigned char");
TEST_SCANF_WARN("%llx","unsigned long long","signed short");
TEST_SCANF_WARN("%llx","unsigned long long","unsigned short");
TEST_SCANF_WARN("%llx","unsigned long long","signed int");
TEST_SCANF_WARN("%llx","unsigned long long","unsigned int");
TEST_SCANF_WARN("%llx","unsigned long long","signed long");
TEST_SCANF_WARN("%llx","unsigned long long","unsigned long");
TEST_SCANF_WARN("%llx","unsigned long long","signed long long");
TEST_SCANF_NOWARN("%llx","unsigned long long","unsigned long long");
TEST_SCANF_WARN("%llx","unsigned long long","float");
TEST_SCANF_WARN("%llx","unsigned long long","double");
TEST_SCANF_WARN("%llx","unsigned long long","long double");
TEST_SCANF_WARN("%llx","unsigned long long","void *");
TEST_SCANF_WARN_AKA("%llx","unsigned long long","size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%llx","unsigned long long","ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%llx","unsigned long long","ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%llx","unsigned long long","unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%llx","unsigned long long","intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%llx","unsigned long long","uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%llx","unsigned long long","intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_WIN32("%llx","unsigned long long","uintptr_t", "unsigned long");
TEST_SCANF_WARN_AKA_CPP("%llx","unsigned long long","std::size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%llx","unsigned long long","std::ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%llx","unsigned long long","std::ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%llx","unsigned long long","std::intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%llx","unsigned long long","std::uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%llx","unsigned long long","std::intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP_WIN32("%llx","unsigned long long","std::uintptr_t", "unsigned long");
TEST_SCANF_WARN("%lld","long long","bool");
TEST_SCANF_WARN("%lld","long long","char");
TEST_SCANF_NOWARN("%lld","long long","long long");
TEST_SCANF_WARN("%lld","long long","unsigned long long");
TEST_SCANF_WARN("%lld","long long","void *");
TEST_SCANF_WARN_AKA("%lld","long long","size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%lld","long long","intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%lld","long long","std::ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%lld","long long","std::intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP_WIN32("%lld","long long","std::intptr_t", "signed long");
TEST_SCANF_WARN("%hu", "unsigned short", "bool");
TEST_SCANF_WARN("%hu", "unsigned short", "char");
TEST_SCANF_WARN("%hu", "unsigned short", "signed char");
TEST_SCANF_WARN("%hu", "unsigned short", "unsigned char");
TEST_SCANF_WARN("%hu", "unsigned short", "signed short");
TEST_SCANF_NOWARN("%hu", "unsigned short", "unsigned short");
TEST_SCANF_WARN("%hu", "unsigned short", "signed int");
TEST_SCANF_WARN("%hu", "unsigned short", "unsigned int");
TEST_SCANF_WARN("%hu", "unsigned short", "signed long");
TEST_SCANF_WARN("%hu", "unsigned short", "unsigned long");
TEST_SCANF_WARN("%hu", "unsigned short", "signed long long");
TEST_SCANF_WARN("%hu", "unsigned short", "unsigned long long");
TEST_SCANF_WARN("%hu", "unsigned short", "float");
TEST_SCANF_WARN("%hu", "unsigned short", "double");
TEST_SCANF_WARN("%hu", "unsigned short", "long double");
TEST_SCANF_WARN("%hu", "unsigned short", "void *");
TEST_SCANF_WARN_AKA("%hu", "unsigned short", "size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%hu", "unsigned short", "ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%hu", "unsigned short", "ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%hu", "unsigned short", "unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%hu", "unsigned short", "intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%hu", "unsigned short", "uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%hu", "unsigned short", "std::size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%hu", "unsigned short", "std::ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%hu", "unsigned short", "std::ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%hu", "unsigned short", "std::intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%hu", "unsigned short", "std::uintptr_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN("%hx", "unsigned short", "bool");
TEST_SCANF_WARN("%hx", "unsigned short", "char");
TEST_SCANF_WARN("%hx", "unsigned short", "signed char");
TEST_SCANF_WARN("%hx", "unsigned short", "unsigned char");
TEST_SCANF_WARN("%hx", "unsigned short", "signed short");
TEST_SCANF_NOWARN("%hx", "unsigned short", "unsigned short");
TEST_SCANF_WARN("%hx", "unsigned short", "signed int");
TEST_SCANF_WARN("%hx", "unsigned short", "unsigned int");
TEST_SCANF_WARN("%hx", "unsigned short", "signed long");
TEST_SCANF_WARN("%hx", "unsigned short", "unsigned long");
TEST_SCANF_WARN("%hx", "unsigned short", "signed long long");
TEST_SCANF_WARN("%hx", "unsigned short", "unsigned long long");
TEST_SCANF_WARN("%hx", "unsigned short", "float");
TEST_SCANF_WARN("%hx", "unsigned short", "double");
TEST_SCANF_WARN("%hx", "unsigned short", "long double");
TEST_SCANF_WARN("%hx", "unsigned short", "void *");
TEST_SCANF_WARN_AKA("%hx", "unsigned short", "size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%hx", "unsigned short", "ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%hx", "unsigned short", "ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%hx", "unsigned short", "unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%hx", "unsigned short", "intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%hx", "unsigned short", "uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%hx", "unsigned short", "std::size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%hx", "unsigned short", "std::ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%hx", "unsigned short", "std::ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%hx", "unsigned short", "std::intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%hx", "unsigned short", "std::uintptr_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN("%hd", "short", "bool");
TEST_SCANF_WARN("%hd", "short", "char");
TEST_SCANF_WARN("%hd", "short", "signed char");
TEST_SCANF_WARN("%hd", "short", "unsigned char");
TEST_SCANF_NOWARN("%hd", "short", "signed short");
TEST_SCANF_WARN("%hd", "short", "unsigned short");
TEST_SCANF_WARN("%hd", "short", "signed int");
TEST_SCANF_WARN("%hd", "short", "unsigned int");
TEST_SCANF_WARN("%hd", "short", "signed long");
TEST_SCANF_WARN("%hd", "short", "void *");
TEST_SCANF_WARN_AKA("%hd", "short", "size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%hd", "short", "ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN("%hhu", "unsigned char", "bool");
TEST_SCANF_WARN("%hhu", "unsigned char", "char");
TEST_SCANF_WARN("%hhu", "unsigned char", "signed char");
TEST_SCANF_NOWARN("%hhu", "unsigned char", "unsigned char");
TEST_SCANF_WARN("%hhu", "unsigned char", "signed short");
TEST_SCANF_WARN("%hhu", "unsigned char", "unsigned short");
TEST_SCANF_WARN("%hhu", "unsigned char", "signed int");
TEST_SCANF_WARN("%hhu", "unsigned char", "unsigned int");
TEST_SCANF_WARN("%hhu", "unsigned char", "signed long");
TEST_SCANF_WARN("%hhu", "unsigned char", "unsigned long");
TEST_SCANF_WARN("%hhu", "unsigned char", "signed long long");
TEST_SCANF_WARN("%hhu", "unsigned char", "unsigned long long");
TEST_SCANF_WARN("%hhu", "unsigned char", "float");
TEST_SCANF_WARN("%hhu", "unsigned char", "double");
TEST_SCANF_WARN("%hhu", "unsigned char", "long double");
TEST_SCANF_WARN("%hhu", "unsigned char", "void *");
TEST_SCANF_WARN_AKA("%hhu", "unsigned char", "size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%hhu", "unsigned char", "ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%hhu", "unsigned char", "ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%hhu", "unsigned char", "unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%hhu", "unsigned char", "intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%hhu", "unsigned char", "uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%hhu", "unsigned char", "std::size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%hhu", "unsigned char", "std::ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%hhu", "unsigned char", "std::ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%hhu", "unsigned char", "std::intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%hhu", "unsigned char", "std::uintptr_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN("%hhx", "unsigned char", "bool");
TEST_SCANF_WARN("%hhx", "unsigned char", "char");
TEST_SCANF_WARN("%hhx", "unsigned char", "signed char");
TEST_SCANF_NOWARN("%hhx", "unsigned char", "unsigned char");
TEST_SCANF_WARN("%hhx", "unsigned char", "signed short");
TEST_SCANF_WARN("%hhx", "unsigned char", "unsigned short");
TEST_SCANF_WARN("%hhx", "unsigned char", "signed int");
TEST_SCANF_WARN("%hhx", "unsigned char", "unsigned int");
TEST_SCANF_WARN("%hhx", "unsigned char", "signed long");
TEST_SCANF_WARN("%hhx", "unsigned char", "unsigned long");
TEST_SCANF_WARN("%hhx", "unsigned char", "signed long long");
TEST_SCANF_WARN("%hhx", "unsigned char", "unsigned long long");
TEST_SCANF_WARN("%hhx", "unsigned char", "float");
TEST_SCANF_WARN("%hhx", "unsigned char", "double");
TEST_SCANF_WARN("%hhx", "unsigned char", "long double");
TEST_SCANF_WARN("%hhx", "unsigned char", "void *");
TEST_SCANF_WARN_AKA("%hhx", "unsigned char", "size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%hhx", "unsigned char", "ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%hhx", "unsigned char", "ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%hhx", "unsigned char", "unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%hhx", "unsigned char", "intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%hhx", "unsigned char", "uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%hhx", "unsigned char", "std::size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%hhx", "unsigned char", "std::ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%hhx", "unsigned char", "std::ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%hhx", "unsigned char", "std::intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%hhx", "unsigned char", "std::uintptr_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN("%hhd", "char", "bool");
TEST_SCANF_NOWARN("%hhd", "char", "char");
TEST_SCANF_NOWARN("%hhd", "char", "signed char");
TEST_SCANF_WARN("%hhd", "char", "unsigned char");
TEST_SCANF_WARN("%hhd", "char", "signed short");
TEST_SCANF_WARN("%hhd", "char", "void *");
TEST_SCANF_WARN_AKA("%hhd", "char", "size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN("%Lu", "unsigned long long", "bool");
TEST_SCANF_WARN("%Lu", "unsigned long long", "char");
TEST_SCANF_WARN("%Lu", "unsigned long long", "signed char");
TEST_SCANF_WARN("%Lu", "unsigned long long", "unsigned char");
TEST_SCANF_WARN("%Lu", "unsigned long long", "signed short");
TEST_SCANF_WARN("%Lu", "unsigned long long", "unsigned short");
TEST_SCANF_WARN("%Lu", "unsigned long long", "signed int");
TEST_SCANF_WARN("%Lu", "unsigned long long", "unsigned int");
TEST_SCANF_WARN("%Lu", "unsigned long long", "signed long");
TEST_SCANF_WARN("%Lu", "unsigned long long", "unsigned long");
TEST_SCANF_WARN("%Lu", "unsigned long long", "signed long long");
TEST_SCANF_NOWARN("%Lu", "unsigned long long", "unsigned long long");
TEST_SCANF_WARN("%Lu", "unsigned long long", "float");
TEST_SCANF_WARN("%Lu", "unsigned long long", "double");
TEST_SCANF_WARN("%Lu", "unsigned long long", "long double");
TEST_SCANF_WARN("%Lu", "unsigned long long", "void *");
TEST_SCANF_WARN_AKA("%Lu", "unsigned long long", "size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%Lu", "unsigned long long", "ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%Lu", "unsigned long long", "ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_WIN32("%Lu", "unsigned long long", "unsigned ptrdiff_t", "unsigned long");
TEST_SCANF_WARN_AKA("%Lu", "unsigned long long", "intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%Lu", "unsigned long long", "uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%Lu", "unsigned long long", "intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_WIN32("%Lu", "unsigned long long", "uintptr_t", "unsigned long");
TEST_SCANF_WARN_AKA_CPP("%Lu", "unsigned long long", "std::size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%Lu", "unsigned long long", "std::ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%Lu", "unsigned long long", "std::ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%Lu", "unsigned long long", "std::intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%Lu", "unsigned long long", "std::uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%Lu", "unsigned long long", "std::intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP_WIN32("%Lu", "unsigned long long", "std::uintptr_t", "unsigned long");
TEST_SCANF_WARN("%Lx", "unsigned long long", "bool");
TEST_SCANF_WARN("%Lx", "unsigned long long", "char");
TEST_SCANF_WARN("%Lx", "unsigned long long", "signed char");
TEST_SCANF_WARN("%Lx", "unsigned long long", "unsigned char");
TEST_SCANF_WARN("%Lx", "unsigned long long", "signed short");
TEST_SCANF_WARN("%Lx", "unsigned long long", "unsigned short");
TEST_SCANF_WARN("%Lx", "unsigned long long", "signed int");
TEST_SCANF_WARN("%Lx", "unsigned long long", "unsigned int");
TEST_SCANF_WARN("%Lx", "unsigned long long", "signed long");
TEST_SCANF_WARN("%Lx", "unsigned long long", "unsigned long");
TEST_SCANF_WARN("%Lx", "unsigned long long", "signed long long");
TEST_SCANF_NOWARN("%Lx", "unsigned long long", "unsigned long long");
TEST_SCANF_WARN("%Lx", "unsigned long long", "float");
TEST_SCANF_WARN("%Lx", "unsigned long long", "double");
TEST_SCANF_WARN("%Lx", "unsigned long long", "long double");
TEST_SCANF_WARN("%Lx", "unsigned long long", "void *");
TEST_SCANF_WARN_AKA("%Lx", "unsigned long long", "size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%Lx", "unsigned long long", "ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%Lx", "unsigned long long", "ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_WIN32("%Lx", "unsigned long long", "unsigned ptrdiff_t", "unsigned long");
TEST_SCANF_WARN_AKA("%Lx", "unsigned long long", "intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%Lx", "unsigned long long", "uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%Lx", "unsigned long long", "intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_WIN32("%Lx", "unsigned long long", "uintptr_t", "unsigned long");
TEST_SCANF_WARN_AKA_CPP("%Lx", "unsigned long long", "std::size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%Lx", "unsigned long long", "std::ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%Lx", "unsigned long long", "std::ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%Lx", "unsigned long long", "std::intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%Lx", "unsigned long long", "std::uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%Lx", "unsigned long long", "std::intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP_WIN32("%Lx", "unsigned long long", "std::uintptr_t", "unsigned long");
TEST_SCANF_WARN("%Ld", "long long", "bool");
TEST_SCANF_WARN("%Ld", "long long", "char");
TEST_SCANF_WARN("%Ld", "long long", "signed char");
TEST_SCANF_WARN("%Ld", "long long", "unsigned char");
TEST_SCANF_WARN("%Ld", "long long", "signed short");
TEST_SCANF_WARN("%Ld", "long long", "unsigned short");
TEST_SCANF_WARN("%Ld", "long long", "signed int");
TEST_SCANF_WARN("%Ld", "long long", "unsigned int");
TEST_SCANF_WARN("%Ld", "long long", "signed long");
TEST_SCANF_WARN("%Ld", "long long", "unsigned long");
TEST_SCANF_NOWARN("%Ld", "long long", "signed long long");
TEST_SCANF_WARN("%Ld", "long long", "unsigned long long");
TEST_SCANF_WARN("%Ld", "long long", "float");
TEST_SCANF_WARN("%Ld", "long long", "double");
TEST_SCANF_WARN("%Ld", "long long", "long double");
TEST_SCANF_WARN("%Ld", "long long", "void *");
TEST_SCANF_WARN_AKA("%Ld", "long long", "size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_WIN32("%Ld", "long long", "ssize_t", "signed long");
TEST_SCANF_WARN_AKA_WIN32("%Ld", "long long", "ptrdiff_t", "signed long");
TEST_SCANF_WARN_AKA("%Ld", "long long", "unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_WIN32("%Ld", "long long", "intmax_t", "signed long");
TEST_SCANF_WARN_AKA("%Ld", "long long", "uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%Ld", "long long", "std::size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP_WIN32("%Ld", "long long", "std::ssize_t", "signed long");
TEST_SCANF_WARN_AKA_CPP_WIN32("%Ld", "long long", "std::ptrdiff_t", "signed long");
TEST_SCANF_WARN_AKA_CPP_WIN32("%Ld", "long long", "std::intptr_t", "signed long");
TEST_SCANF_WARN_AKA_CPP("%Ld", "long long", "std::uintptr_t", "unsigned long", "unsigned long long");
check("void foo() {\n"
" scanf(\"%Ld\", \"s3\");\n"
" scanf(\"%Ld\", L\"s5W\");\n"
"}", dinit(CheckOptions, $.inconclusive = true));
ASSERT_EQUALS("[test.cpp:2]: (warning) %Ld in format string (no. 1) requires 'long long *' but the argument type is 'const char *'.\n"
"[test.cpp:3]: (warning) %Ld in format string (no. 1) requires 'long long *' but the argument type is 'const wchar_t *'.\n", errout_str());
check("void foo(int i) {\n"
" scanf(\"%Ld\", i);\n"
"}", dinit(CheckOptions, $.inconclusive = true));
ASSERT_EQUALS("[test.cpp:2]: (warning) %Ld in format string (no. 1) requires 'long long *' but the argument type is 'signed int'.\n", errout_str());
TEST_SCANF_WARN("%ju", "uintmax_t", "bool");
TEST_SCANF_WARN("%ju", "uintmax_t", "char");
TEST_SCANF_WARN("%ju", "uintmax_t", "signed char");
TEST_SCANF_WARN("%ju", "uintmax_t", "unsigned char");
TEST_SCANF_WARN("%ju", "uintmax_t", "signed short");
TEST_SCANF_WARN("%ju", "uintmax_t", "unsigned short");
TEST_SCANF_WARN("%ju", "uintmax_t", "signed int");
TEST_SCANF_WARN("%ju", "uintmax_t", "unsigned int");
TEST_SCANF_WARN("%ju", "uintmax_t", "signed long");
TEST_SCANF_WARN("%ju", "uintmax_t", "unsigned long");
TEST_SCANF_WARN("%ju", "uintmax_t", "signed long long");
TEST_SCANF_WARN("%ju", "uintmax_t", "unsigned long long");
TEST_SCANF_WARN("%ju", "uintmax_t", "float");
TEST_SCANF_WARN("%ju", "uintmax_t", "double");
TEST_SCANF_WARN("%ju", "uintmax_t", "long double");
TEST_SCANF_WARN("%ju", "uintmax_t", "void *");
TEST_SCANF_WARN_AKA("%ju", "uintmax_t", "size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%ju", "uintmax_t", "ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%ju", "uintmax_t", "ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%ju", "uintmax_t", "unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%ju", "uintmax_t", "intmax_t", "signed long", "signed long long");
TEST_SCANF_NOWARN("%ju", "uintmax_t", "uintmax_t");
TEST_SCANF_WARN_AKA_CPP("%ju", "uintmax_t", "std::size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%ju", "uintmax_t", "std::ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%ju", "uintmax_t", "std::ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%ju", "uintmax_t", "std::intmax_t", "signed long", "signed long long");
TEST_SCANF_NOWARN_CPP("%ju", "uintmax_t", "std::uintmax_t");
TEST_SCANF_WARN_AKA_CPP("%ju", "uintmax_t", "std::intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%ju", "uintmax_t", "std::uintptr_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN("%jx", "uintmax_t", "bool");
TEST_SCANF_WARN("%jx", "uintmax_t", "char");
TEST_SCANF_WARN("%jx", "uintmax_t", "signed char");
TEST_SCANF_WARN("%jx", "uintmax_t", "unsigned char");
TEST_SCANF_WARN("%jx", "uintmax_t", "signed short");
TEST_SCANF_WARN("%jx", "uintmax_t", "unsigned short");
TEST_SCANF_WARN("%jx", "uintmax_t", "signed int");
TEST_SCANF_WARN("%jx", "uintmax_t", "unsigned int");
TEST_SCANF_WARN("%jx", "uintmax_t", "signed long");
TEST_SCANF_WARN("%jx", "uintmax_t", "unsigned long");
TEST_SCANF_WARN("%jx", "uintmax_t", "signed long long");
TEST_SCANF_WARN("%jx", "uintmax_t", "unsigned long long");
TEST_SCANF_WARN("%jx", "uintmax_t", "float");
TEST_SCANF_WARN("%jx", "uintmax_t", "double");
TEST_SCANF_WARN("%jx", "uintmax_t", "long double");
TEST_SCANF_WARN("%jx", "uintmax_t", "void *");
TEST_SCANF_WARN_AKA("%jx", "uintmax_t", "size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%jx", "uintmax_t", "ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%jx", "uintmax_t", "ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%jx", "uintmax_t", "unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%jx", "uintmax_t", "intmax_t", "signed long", "signed long long");
TEST_SCANF_NOWARN("%jx", "uintmax_t", "uintmax_t");
TEST_SCANF_WARN_AKA_CPP("%jx", "uintmax_t", "std::size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%jx", "uintmax_t", "std::ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%jx", "uintmax_t", "std::ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%jx", "uintmax_t", "std::intmax_t", "signed long", "signed long long");
TEST_SCANF_NOWARN_CPP("%jx", "uintmax_t", "std::uintmax_t");
TEST_SCANF_WARN_AKA_CPP("%jx", "uintmax_t", "std::intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%jx", "uintmax_t", "std::uintptr_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN("%jd", "intmax_t", "long double");
TEST_SCANF_WARN("%jd", "intmax_t", "void *");
TEST_SCANF_WARN_AKA("%jd", "intmax_t", "size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%jd", "intmax_t", "unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%jd", "intmax_t", "std::ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%jd", "intmax_t", "std::ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_NOWARN("%jd", "intmax_t", "intmax_t");
TEST_SCANF_WARN_AKA("%jd", "intmax_t", "uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_NOWARN_CPP("%jd", "intmax_t", "std::intmax_t");
TEST_SCANF_WARN("%zu", "size_t", "bool");
TEST_SCANF_WARN("%zu", "size_t", "char");
TEST_SCANF_WARN("%zu", "size_t", "signed char");
TEST_SCANF_WARN("%zu", "size_t", "unsigned char");
TEST_SCANF_WARN("%zu", "size_t", "signed short");
TEST_SCANF_WARN("%zu", "size_t", "unsigned short");
TEST_SCANF_WARN("%zu", "size_t", "signed int");
TEST_SCANF_WARN("%zu", "size_t", "unsigned int");
TEST_SCANF_WARN("%zu", "size_t", "signed long");
TEST_SCANF_WARN("%zu", "size_t", "unsigned long");
TEST_SCANF_WARN("%zu", "size_t", "signed long long");
TEST_SCANF_WARN("%zu", "size_t", "unsigned long long");
TEST_SCANF_WARN("%zu", "size_t", "float");
TEST_SCANF_WARN("%zu", "size_t", "double");
TEST_SCANF_WARN("%zu", "size_t", "long double");
TEST_SCANF_WARN("%zu", "size_t", "void *");
TEST_SCANF_NOWARN("%zu", "size_t", "size_t");
TEST_SCANF_WARN_AKA("%zu", "size_t", "ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%zu", "size_t", "ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%zu", "size_t", "unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%zu", "size_t", "intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%zu", "size_t", "uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_NOWARN_CPP("%zu", "size_t", "std::size_t");
TEST_SCANF_WARN_AKA_CPP("%zu", "size_t", "std::ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%zu", "size_t", "std::ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%zu", "size_t", "std::intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%zu", "size_t", "std::uintptr_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN("%zx", "size_t", "bool");
TEST_SCANF_WARN("%zx", "size_t", "char");
TEST_SCANF_WARN("%zx", "size_t", "signed char");
TEST_SCANF_WARN("%zx", "size_t", "unsigned char");
TEST_SCANF_WARN("%zx", "size_t", "signed short");
TEST_SCANF_WARN("%zx", "size_t", "unsigned short");
TEST_SCANF_WARN("%zx", "size_t", "signed int");
TEST_SCANF_WARN("%zx", "size_t", "unsigned int");
TEST_SCANF_WARN("%zx", "size_t", "signed long");
TEST_SCANF_WARN("%zx", "size_t", "unsigned long");
TEST_SCANF_WARN("%zx", "size_t", "signed long long");
TEST_SCANF_WARN("%zx", "size_t", "unsigned long long");
TEST_SCANF_WARN("%zx", "size_t", "float");
TEST_SCANF_WARN("%zx", "size_t", "double");
TEST_SCANF_WARN("%zx", "size_t", "long double");
TEST_SCANF_WARN("%zx", "size_t", "void *");
TEST_SCANF_NOWARN("%zx", "size_t", "size_t");
TEST_SCANF_WARN_AKA("%zx", "size_t", "ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%zx", "size_t", "ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%zx", "size_t", "unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%zx", "size_t", "intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%zx", "size_t", "uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_NOWARN_CPP("%zx", "size_t", "std::size_t");
TEST_SCANF_WARN_AKA_CPP("%zx", "size_t", "std::ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%zx", "size_t", "std::ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%zx", "size_t", "std::intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%zx", "size_t", "std::uintptr_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN("%zd", "ssize_t", "bool");
TEST_SCANF_WARN("%zd", "ssize_t", "signed short");
TEST_SCANF_WARN("%zd", "ssize_t", "void *");
TEST_SCANF_WARN_AKA("%zd", "ssize_t", "size_t", "unsigned long", "unsigned long long");
TEST_SCANF_NOWARN("%zd", "ssize_t", "ssize_t");
TEST_SCANF_WARN_AKA("%zd", "ssize_t", "ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%zi", "ssize_t", "size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN("%tu", "unsigned ptrdiff_t", "bool");
TEST_SCANF_WARN("%tu", "unsigned ptrdiff_t", "char");
TEST_SCANF_WARN("%tu", "unsigned ptrdiff_t", "signed char");
TEST_SCANF_WARN("%tu", "unsigned ptrdiff_t", "unsigned char");
TEST_SCANF_WARN("%tu", "unsigned ptrdiff_t", "signed short");
TEST_SCANF_WARN("%tu", "unsigned ptrdiff_t", "unsigned short");
TEST_SCANF_WARN("%tu", "unsigned ptrdiff_t", "signed int");
TEST_SCANF_WARN("%tu", "unsigned ptrdiff_t", "unsigned int");
TEST_SCANF_WARN("%tu", "unsigned ptrdiff_t", "signed long");
TEST_SCANF_WARN("%tu", "unsigned ptrdiff_t", "unsigned long");
TEST_SCANF_WARN("%tu", "unsigned ptrdiff_t", "signed long long");
TEST_SCANF_WARN("%tu", "unsigned ptrdiff_t", "unsigned long long");
TEST_SCANF_WARN("%tu", "unsigned ptrdiff_t", "float");
TEST_SCANF_WARN("%tu", "unsigned ptrdiff_t", "double");
TEST_SCANF_WARN("%tu", "unsigned ptrdiff_t", "long double");
TEST_SCANF_WARN("%tu", "unsigned ptrdiff_t", "void *");
TEST_SCANF_WARN_AKA("%tu", "unsigned ptrdiff_t", "size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%tu", "unsigned ptrdiff_t", "ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%tu", "unsigned ptrdiff_t", "ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_NOWARN("%tu", "unsigned ptrdiff_t", "unsigned ptrdiff_t");
TEST_SCANF_WARN_AKA("%tu", "unsigned ptrdiff_t", "intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%tu", "unsigned ptrdiff_t", "uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%tu", "unsigned ptrdiff_t", "std::size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%tu", "unsigned ptrdiff_t", "std::ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%tu", "unsigned ptrdiff_t", "std::ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%tu", "unsigned ptrdiff_t", "std::intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%tu", "unsigned ptrdiff_t", "std::uintptr_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN("%tx", "unsigned ptrdiff_t", "bool");
TEST_SCANF_WARN("%tx", "unsigned ptrdiff_t", "char");
TEST_SCANF_WARN("%tx", "unsigned ptrdiff_t", "signed char");
TEST_SCANF_WARN("%tx", "unsigned ptrdiff_t", "unsigned char");
TEST_SCANF_WARN("%tx", "unsigned ptrdiff_t", "signed short");
TEST_SCANF_WARN("%tx", "unsigned ptrdiff_t", "unsigned short");
TEST_SCANF_WARN("%tx", "unsigned ptrdiff_t", "signed int");
TEST_SCANF_WARN("%tx", "unsigned ptrdiff_t", "unsigned int");
TEST_SCANF_WARN("%tx", "unsigned ptrdiff_t", "signed long");
TEST_SCANF_WARN("%tx", "unsigned ptrdiff_t", "unsigned long");
TEST_SCANF_WARN("%tx", "unsigned ptrdiff_t", "signed long long");
TEST_SCANF_WARN("%tx", "unsigned ptrdiff_t", "unsigned long long");
TEST_SCANF_WARN("%tx", "unsigned ptrdiff_t", "float");
TEST_SCANF_WARN("%tx", "unsigned ptrdiff_t", "double");
TEST_SCANF_WARN("%tx", "unsigned ptrdiff_t", "long double");
TEST_SCANF_WARN("%tx", "unsigned ptrdiff_t", "void *");
TEST_SCANF_WARN_AKA("%tx", "unsigned ptrdiff_t", "size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%tx", "unsigned ptrdiff_t", "ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%tx", "unsigned ptrdiff_t", "ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_NOWARN("%tx", "unsigned ptrdiff_t", "unsigned ptrdiff_t");
TEST_SCANF_WARN_AKA("%tx", "unsigned ptrdiff_t", "intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%tx", "unsigned ptrdiff_t", "uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%tx", "unsigned ptrdiff_t", "std::size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%tx", "unsigned ptrdiff_t", "std::ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%tx", "unsigned ptrdiff_t", "std::ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%tx", "unsigned ptrdiff_t", "std::intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%tx", "unsigned ptrdiff_t", "std::uintptr_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN("%td", "ptrdiff_t", "long double");
TEST_SCANF_WARN("%td", "ptrdiff_t", "void *");
TEST_SCANF_NOWARN("%td", "ptrdiff_t", "ptrdiff_t");
TEST_SCANF_WARN_AKA("%td", "ptrdiff_t", "intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%td", "ptrdiff_t", "uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%td", "ptrdiff_t", "unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN("%Iu", "size_t", "bool");
TEST_SCANF_WARN("%Iu", "size_t", "char");
TEST_SCANF_WARN("%Iu", "size_t", "signed char");
TEST_SCANF_WARN("%Iu", "size_t", "unsigned char");
TEST_SCANF_WARN("%Iu", "size_t", "signed short");
TEST_SCANF_WARN("%Iu", "size_t", "unsigned short");
TEST_SCANF_WARN("%Iu", "size_t", "signed int");
TEST_SCANF_WARN("%Iu", "size_t", "unsigned int");
TEST_SCANF_WARN("%Iu", "size_t", "signed long");
TEST_SCANF_WARN("%Iu", "size_t", "unsigned long");
TEST_SCANF_WARN("%Iu", "size_t", "signed long long");
TEST_SCANF_WARN("%Iu", "size_t", "unsigned long long");
TEST_SCANF_WARN("%Iu", "size_t", "float");
TEST_SCANF_WARN("%Iu", "size_t", "double");
TEST_SCANF_WARN("%Iu", "size_t", "long double");
TEST_SCANF_WARN("%Iu", "size_t", "void *");
TEST_SCANF_NOWARN("%Iu", "size_t", "size_t");
TEST_SCANF_WARN_AKA("%Iu", "size_t", "ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%Iu", "size_t", "ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%Iu", "size_t", "unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%Iu", "size_t", "intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%Iu", "size_t", "uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%Iu", "size_t", "intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%Iu", "size_t", "uintptr_t", "unsigned long", "unsigned long long");
TEST_SCANF_NOWARN_CPP("%Iu", "size_t", "std::size_t");
TEST_SCANF_WARN_AKA_CPP("%Iu", "size_t", "std::ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%Iu", "size_t", "std::ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%Iu", "size_t", "std::intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%Iu", "size_t", "std::uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%Iu", "size_t", "std::intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%Iu", "size_t", "std::uintptr_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN("%Ix", "size_t", "bool");
TEST_SCANF_WARN("%Ix", "size_t", "char");
TEST_SCANF_WARN("%Ix", "size_t", "signed char");
TEST_SCANF_WARN("%Ix", "size_t", "unsigned char");
TEST_SCANF_WARN("%Ix", "size_t", "signed short");
TEST_SCANF_WARN("%Ix", "size_t", "unsigned short");
TEST_SCANF_WARN("%Ix", "size_t", "signed int");
TEST_SCANF_WARN("%Ix", "size_t", "unsigned int");
TEST_SCANF_WARN("%Ix", "size_t", "signed long");
TEST_SCANF_WARN("%Ix", "size_t", "unsigned long");
TEST_SCANF_WARN("%Ix", "size_t", "signed long long");
TEST_SCANF_WARN("%Ix", "size_t", "unsigned long long");
TEST_SCANF_WARN("%Ix", "size_t", "float");
TEST_SCANF_WARN("%Ix", "size_t", "double");
TEST_SCANF_WARN("%Ix", "size_t", "long double");
TEST_SCANF_WARN("%Ix", "size_t", "void *");
TEST_SCANF_NOWARN("%Ix", "size_t", "size_t");
TEST_SCANF_WARN_AKA("%Ix", "size_t", "ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%Ix", "size_t", "ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%Ix", "size_t", "unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%Ix", "size_t", "intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%Ix", "size_t", "uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%Ix", "size_t", "intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%Ix", "size_t", "uintptr_t", "unsigned long", "unsigned long long");
TEST_SCANF_NOWARN_CPP("%Ix", "size_t", "std::size_t");
TEST_SCANF_WARN_AKA_CPP("%Ix", "size_t", "std::ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%Ix", "size_t", "std::ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%Ix", "size_t", "std::intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%Ix", "size_t", "std::uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%Ix", "size_t", "std::intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%Ix", "size_t", "std::uintptr_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN("%Id", "ptrdiff_t", "bool");
TEST_SCANF_WARN("%Id", "ptrdiff_t", "char");
TEST_SCANF_WARN("%Id", "ptrdiff_t", "signed char");
TEST_SCANF_WARN("%Id", "ptrdiff_t", "unsigned char");
TEST_SCANF_WARN("%Id", "ptrdiff_t", "signed short");
TEST_SCANF_WARN("%Id", "ptrdiff_t", "unsigned short");
TEST_SCANF_WARN("%Id", "ptrdiff_t", "signed int");
TEST_SCANF_WARN("%Id", "ptrdiff_t", "unsigned int");
TEST_SCANF_WARN("%Id", "ptrdiff_t", "signed long");
TEST_SCANF_WARN("%Id", "ptrdiff_t", "unsigned long");
TEST_SCANF_WARN("%Id", "ptrdiff_t", "signed long long");
TEST_SCANF_WARN("%Id", "ptrdiff_t", "unsigned long long");
TEST_SCANF_WARN("%Id", "ptrdiff_t", "float");
TEST_SCANF_WARN("%Id", "ptrdiff_t", "double");
TEST_SCANF_WARN("%Id", "ptrdiff_t", "long double");
TEST_SCANF_WARN("%Id", "ptrdiff_t", "void *");
TEST_SCANF_WARN_AKA("%Id", "ptrdiff_t", "size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%Id", "ptrdiff_t", "ssize_t", "signed long", "signed long long");
TEST_SCANF_NOWARN("%Id", "ptrdiff_t", "ptrdiff_t");
TEST_SCANF_WARN_AKA("%Id", "ptrdiff_t", "unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%Id", "ptrdiff_t", "intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%Id", "ptrdiff_t", "uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%Id", "ptrdiff_t", "std::size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%Id", "ptrdiff_t", "std::ssize_t", "signed long", "signed long long");
TEST_SCANF_NOWARN_CPP("%Id", "ptrdiff_t", "std::ptrdiff_t");
TEST_SCANF_WARN_AKA_CPP("%Id", "ptrdiff_t", "std::intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%Id", "ptrdiff_t", "std::uintptr_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN("%I64u", "unsigned __int64", "bool");
TEST_SCANF_WARN("%I64u", "unsigned __int64", "char");
TEST_SCANF_WARN("%I64u", "unsigned __int64", "signed char");
TEST_SCANF_WARN("%I64u", "unsigned __int64", "unsigned char");
TEST_SCANF_WARN("%I64u", "unsigned __int64", "signed short");
TEST_SCANF_WARN("%I64u", "unsigned __int64", "unsigned short");
TEST_SCANF_WARN("%I64u", "unsigned __int64", "signed int");
TEST_SCANF_WARN("%I64u", "unsigned __int64", "unsigned int");
TEST_SCANF_WARN("%I64u", "unsigned __int64", "signed long");
TEST_SCANF_WARN("%I64u", "unsigned __int64", "unsigned long");
TEST_SCANF_WARN("%I64u", "unsigned __int64", "signed long long");
TEST_SCANF_NOWARN("%I64u", "unsigned __int64", "unsigned long long");
TEST_SCANF_WARN("%I64u", "unsigned __int64", "float");
TEST_SCANF_WARN("%I64u", "unsigned __int64", "double");
TEST_SCANF_WARN("%I64u", "unsigned __int64", "long double");
TEST_SCANF_WARN("%I64u", "unsigned __int64", "void *");
TEST_SCANF_WARN_AKA_WIN32("%I64u", "unsigned __int64", "size_t", "unsigned long");
TEST_SCANF_WARN_AKA("%I64u", "unsigned __int64", "ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%I64u", "unsigned __int64", "ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_WIN32("%I64u", "unsigned __int64", "unsigned ptrdiff_t", "unsigned long");
TEST_SCANF_WARN_AKA("%I64u", "unsigned __int64", "intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_WIN32("%I64u", "unsigned __int64", "uintmax_t", "unsigned long");
TEST_SCANF_WARN_AKA("%I64u", "unsigned __int64", "intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_WIN32("%I64u", "unsigned __int64", "uintptr_t", "unsigned long");
TEST_SCANF_WARN_AKA_CPP_WIN32("%I64u", "unsigned __int64", "std::size_t", "unsigned long");
TEST_SCANF_WARN_AKA_CPP("%I64u", "unsigned __int64", "std::ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%I64u", "unsigned __int64", "std::ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%I64u", "unsigned __int64", "std::intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP_WIN32("%I64u", "unsigned __int64", "std::uintmax_t", "unsigned long");
TEST_SCANF_WARN_AKA_CPP("%I64u", "unsigned __int64", "std::intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP_WIN32("%I64u", "unsigned __int64", "std::uintptr_t", "unsigned long");
TEST_SCANF_WARN("%I64x", "unsigned __int64", "bool");
TEST_SCANF_WARN("%I64x", "unsigned __int64", "char");
TEST_SCANF_WARN("%I64x", "unsigned __int64", "signed char");
TEST_SCANF_WARN("%I64x", "unsigned __int64", "unsigned char");
TEST_SCANF_WARN("%I64x", "unsigned __int64", "signed short");
TEST_SCANF_WARN("%I64x", "unsigned __int64", "unsigned short");
TEST_SCANF_WARN("%I64x", "unsigned __int64", "signed int");
TEST_SCANF_WARN("%I64x", "unsigned __int64", "unsigned int");
TEST_SCANF_WARN("%I64x", "unsigned __int64", "signed long");
TEST_SCANF_WARN("%I64x", "unsigned __int64", "unsigned long");
TEST_SCANF_WARN("%I64x", "unsigned __int64", "signed long long");
TEST_SCANF_NOWARN("%I64x", "unsigned __int64", "unsigned long long");
TEST_SCANF_WARN("%I64x", "unsigned __int64", "float");
TEST_SCANF_WARN("%I64x", "unsigned __int64", "double");
TEST_SCANF_WARN("%I64x", "unsigned __int64", "long double");
TEST_SCANF_WARN("%I64x", "unsigned __int64", "void *");
TEST_SCANF_WARN_AKA_WIN32("%I64x", "unsigned __int64", "size_t", "unsigned long");
TEST_SCANF_WARN_AKA("%I64x", "unsigned __int64", "ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%I64x", "unsigned __int64", "ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_NOWARN("%I64x", "unsigned __int64", "unsigned __int64");
// TODO TEST_SCANF_WARN("%I64x", "unsigned __int64", "__int64");
TEST_SCANF_WARN_AKA_WIN32("%I64x", "unsigned __int64", "unsigned ptrdiff_t", "unsigned long");
TEST_SCANF_WARN_AKA("%I64x", "unsigned __int64", "intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_WIN32("%I64x", "unsigned __int64", "uintmax_t", "unsigned long");
TEST_SCANF_WARN_AKA("%I64x", "unsigned __int64", "intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_WIN32("%I64x", "unsigned __int64", "uintptr_t", "unsigned long");
TEST_SCANF_WARN_AKA_CPP_WIN32("%I64x", "unsigned __int64", "std::size_t", "unsigned long");
TEST_SCANF_WARN_AKA_CPP("%I64x", "unsigned __int64", "std::ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%I64x", "unsigned __int64", "std::ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%I64x", "unsigned __int64", "std::intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP_WIN32("%I64x", "unsigned __int64", "std::uintmax_t", "unsigned long");
TEST_SCANF_WARN_AKA_CPP("%I64x", "unsigned __int64", "std::intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP_WIN32("%I64x", "unsigned __int64", "std::uintptr_t", "unsigned long");
TEST_SCANF_WARN("%I64d", "__int64", "bool");
TEST_SCANF_WARN("%I64d", "__int64", "signed char");
TEST_SCANF_WARN("%I64d", "__int64", "unsigned char");
TEST_SCANF_WARN("%I64d", "__int64", "void *");
// TODO TEST_SCANF_WARN("%I64d", "__int64", "size_t");
TEST_SCANF_WARN_AKA_WIN32("%I64d", "__int64", "intmax_t", "signed long");
TEST_SCANF_WARN_AKA_WIN32("%I64d", "__int64", "ssize_t", "signed long");
TEST_SCANF_WARN_AKA_WIN32("%I64d", "__int64", "ptrdiff_t", "signed long");
TEST_SCANF_NOWARN("%I64d", "__int64", "__int64");
TEST_SCANF_WARN("%I32u", "unsigned __int32", "bool");
TEST_SCANF_WARN("%I32u", "unsigned __int32", "char");
TEST_SCANF_WARN("%I32u", "unsigned __int32", "signed char");
TEST_SCANF_WARN("%I32u", "unsigned __int32", "unsigned char");
TEST_SCANF_WARN("%I32u", "unsigned __int32", "signed short");
TEST_SCANF_WARN("%I32u", "unsigned __int32", "unsigned short");
TEST_SCANF_WARN("%I32u", "unsigned __int32", "signed int");
TEST_SCANF_NOWARN("%I32u", "unsigned __int32", "unsigned int");
TEST_SCANF_WARN("%I32u", "unsigned __int32", "signed long");
TEST_SCANF_WARN("%I32u", "unsigned __int32", "unsigned long");
TEST_SCANF_WARN("%I32u", "unsigned __int32", "signed long long");
TEST_SCANF_WARN("%I32u", "unsigned __int32", "unsigned long long");
TEST_SCANF_WARN("%I32u", "unsigned __int32", "float");
TEST_SCANF_WARN("%I32u", "unsigned __int32", "double");
TEST_SCANF_WARN("%I32u", "unsigned __int32", "long double");
TEST_SCANF_WARN("%I32u", "unsigned __int32", "void *");
TEST_SCANF_WARN_AKA("%I32u", "unsigned __int32", "size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%I32u", "unsigned __int32", "ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%I32u", "unsigned __int32", "ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%I32u", "unsigned __int32", "unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%I32u", "unsigned __int32", "intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%I32u", "unsigned __int32", "uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%I32u", "unsigned __int32", "intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%I32u", "unsigned __int32", "uintptr_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%I32u", "unsigned __int32", "std::size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%I32u", "unsigned __int32", "std::ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%I32u", "unsigned __int32", "std::ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%I32u", "unsigned __int32", "std::intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%I32u", "unsigned __int32", "std::uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%I32u", "unsigned __int32", "std::intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%I32u", "unsigned __int32", "std::uintptr_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN("%I32x", "unsigned __int32", "bool");
TEST_SCANF_WARN("%I32x", "unsigned __int32", "char");
TEST_SCANF_WARN("%I32x", "unsigned __int32", "signed char");
TEST_SCANF_WARN("%I32x", "unsigned __int32", "unsigned char");
TEST_SCANF_WARN("%I32x", "unsigned __int32", "signed short");
TEST_SCANF_WARN("%I32x", "unsigned __int32", "unsigned short");
TEST_SCANF_WARN("%I32x", "unsigned __int32", "signed int");
TEST_SCANF_NOWARN("%I32x", "unsigned __int32", "unsigned int");
TEST_SCANF_WARN("%I32x", "unsigned __int32", "signed long");
TEST_SCANF_WARN("%I32x", "unsigned __int32", "unsigned long");
TEST_SCANF_WARN("%I32x", "unsigned __int32", "signed long long");
TEST_SCANF_WARN("%I32x", "unsigned __int32", "unsigned long long");
TEST_SCANF_WARN("%I32x", "unsigned __int32", "float");
TEST_SCANF_WARN("%I32x", "unsigned __int32", "double");
TEST_SCANF_WARN("%I32x", "unsigned __int32", "long double");
TEST_SCANF_WARN("%I32x", "unsigned __int32", "void *");
TEST_SCANF_WARN_AKA("%I32x", "unsigned __int32", "size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%I32x", "unsigned __int32", "ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%I32x", "unsigned __int32", "ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%I32x", "unsigned __int32", "unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%I32x", "unsigned __int32", "intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%I32x", "unsigned __int32", "uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%I32x", "unsigned __int32", "intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%I32x", "unsigned __int32", "uintptr_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%I32x", "unsigned __int32", "std::size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%I32x", "unsigned __int32", "std::ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%I32x", "unsigned __int32", "std::ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%I32x", "unsigned __int32", "std::intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%I32x", "unsigned __int32", "std::uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%I32x", "unsigned __int32", "std::intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%I32x", "unsigned __int32", "std::uintptr_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN("%I32d", "__int32", "bool");
TEST_SCANF_WARN("%I32d", "__int32", "void *");
TEST_SCANF_WARN_AKA("%I32d", "__int32", "size_t", "unsigned long", "unsigned long long");
//TODO TEST_SCANF_WARN_AKA_WIN32("%I32d", "__int32", "ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%I32d", "__int32", "ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_NOWARN("%I32d", "__int32", "__int32");
TEST_SCANF_WARN("%d", "int", "bool");
TEST_SCANF_WARN("%d", "int", "char");
TEST_SCANF_WARN("%d", "int", "signed char");
TEST_SCANF_WARN("%d", "int", "unsigned char");
TEST_SCANF_WARN("%d", "int", "signed short");
TEST_SCANF_WARN("%d", "int", "unsigned short");
TEST_SCANF_NOWARN("%d", "int", "signed int");
TEST_SCANF_WARN("%d", "int", "unsigned int");
TEST_SCANF_WARN("%d", "int", "signed long");
TEST_SCANF_WARN("%d", "int", "unsigned long");
TEST_SCANF_WARN("%d", "int", "signed long long");
TEST_SCANF_WARN("%d", "int", "unsigned long long");
TEST_SCANF_WARN("%d", "int", "float");
TEST_SCANF_WARN("%d", "int", "double");
TEST_SCANF_WARN("%d", "int", "long double");
TEST_SCANF_WARN("%d", "int", "void *");
TEST_SCANF_WARN_AKA("%d", "int", "size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%d", "int", "ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%d", "int", "ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%d", "int", "unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%d", "int", "intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%d", "int", "uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%d", "int", "std::size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%d", "int", "std::ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%d", "int", "std::ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%d", "int", "std::intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%d", "int", "std::uintptr_t", "unsigned long", "unsigned long long");
check("void foo() {\n"
" scanf(\"%d\", \"s3\");\n"
" scanf(\"%d\", L\"s5W\");\n"
"}", dinit(CheckOptions, $.inconclusive = true));
ASSERT_EQUALS("[test.cpp:2]: (warning) %d in format string (no. 1) requires 'int *' but the argument type is 'const char *'.\n"
"[test.cpp:3]: (warning) %d in format string (no. 1) requires 'int *' but the argument type is 'const wchar_t *'.\n", errout_str());
check("void foo(long l) {\n"
" scanf(\"%d\", l);\n"
"}", dinit(CheckOptions, $.inconclusive = true));
ASSERT_EQUALS("[test.cpp:2]: (warning) %d in format string (no. 1) requires 'int *' but the argument type is 'signed long'.\n", errout_str());
TEST_SCANF_WARN("%x", "unsigned int", "bool");
TEST_SCANF_WARN("%x", "unsigned int", "char");
TEST_SCANF_WARN("%x", "unsigned int", "signed char");
TEST_SCANF_WARN("%x", "unsigned int", "unsigned char");
TEST_SCANF_WARN("%x", "unsigned int", "signed short");
TEST_SCANF_WARN("%x", "unsigned int", "unsigned short");
TEST_SCANF_WARN("%x", "unsigned int", "signed int");
TEST_SCANF_NOWARN("%x", "unsigned int", "unsigned int");
TEST_SCANF_WARN("%x", "unsigned int", "signed long");
TEST_SCANF_WARN("%x", "unsigned int", "unsigned long");
TEST_SCANF_WARN("%x", "unsigned int", "signed long long");
TEST_SCANF_WARN("%x", "unsigned int", "unsigned long long");
TEST_SCANF_WARN("%x", "unsigned int", "float");
TEST_SCANF_WARN("%x", "unsigned int", "double");
TEST_SCANF_WARN("%x", "unsigned int", "long double");
TEST_SCANF_WARN("%x", "unsigned int", "void *");
TEST_SCANF_WARN_AKA("%x", "unsigned int", "size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%x", "unsigned int", "ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%x", "unsigned int", "ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%x", "unsigned int", "unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%x", "unsigned int", "intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%x", "unsigned int", "uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%x", "unsigned int", "intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%x", "unsigned int", "uintptr_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%x", "unsigned int", "std::size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%x", "unsigned int", "std::ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%x", "unsigned int", "std::ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%x", "unsigned int", "std::intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%x", "unsigned int", "std::uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%x", "unsigned int", "std::intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%x", "unsigned int", "std::uintptr_t", "unsigned long", "unsigned long long");
check("void foo() {\n"
" scanf(\"%x\", \"s3\");\n"
" scanf(\"%x\", L\"s5W\");\n"
"}", dinit(CheckOptions, $.inconclusive = true));
ASSERT_EQUALS("[test.cpp:2]: (warning) %x in format string (no. 1) requires 'unsigned int *' but the argument type is 'const char *'.\n"
"[test.cpp:3]: (warning) %x in format string (no. 1) requires 'unsigned int *' but the argument type is 'const wchar_t *'.\n", errout_str());
check("void foo(long l) {\n"
" scanf(\"%x\", l);\n"
"}", dinit(CheckOptions, $.inconclusive = true));
ASSERT_EQUALS("[test.cpp:2]: (warning) %x in format string (no. 1) requires 'unsigned int *' but the argument type is 'signed long'.\n", errout_str());
TEST_SCANF_WARN("%f", "float", "bool");
TEST_SCANF_WARN("%f", "float", "char");
TEST_SCANF_WARN("%f", "float", "signed char");
TEST_SCANF_WARN("%f", "float", "unsigned char");
TEST_SCANF_WARN("%f", "float", "signed short");
TEST_SCANF_WARN("%f", "float", "unsigned short");
TEST_SCANF_WARN("%f", "float", "signed int");
TEST_SCANF_WARN("%f", "float", "unsigned int");
TEST_SCANF_WARN("%f", "float", "signed long");
TEST_SCANF_WARN("%f", "float", "unsigned long");
TEST_SCANF_WARN("%f", "float", "signed long long");
TEST_SCANF_WARN("%f", "float", "unsigned long long");
TEST_SCANF_NOWARN("%f", "float", "float");
TEST_SCANF_WARN("%f", "float", "double");
TEST_SCANF_WARN("%f", "float", "long double");
TEST_SCANF_WARN("%f", "float", "void *");
TEST_SCANF_WARN_AKA("%f", "float", "size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%f", "float", "ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%f", "float", "ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%f", "float", "unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%f", "float", "intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%f", "float", "uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%f", "float", "std::size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%f", "float", "std::ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%f", "float", "std::ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%f", "float", "std::intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%f", "float", "std::uintptr_t", "unsigned long", "unsigned long long");
check("void foo() {\n"
" scanf(\"%f\", \"s3\");\n"
" scanf(\"%f\", L\"s5W\");\n"
"}", dinit(CheckOptions, $.inconclusive = true));
ASSERT_EQUALS("[test.cpp:2]: (warning) %f in format string (no. 1) requires 'float *' but the argument type is 'const char *'.\n"
"[test.cpp:3]: (warning) %f in format string (no. 1) requires 'float *' but the argument type is 'const wchar_t *'.\n", errout_str());
check("void foo(float f) {\n"
" scanf(\"%f\", f);\n"
"}", dinit(CheckOptions, $.inconclusive = true));
ASSERT_EQUALS("[test.cpp:2]: (warning) %f in format string (no. 1) requires 'float *' but the argument type is 'float'.\n", errout_str());
TEST_SCANF_WARN("%lf", "double", "bool");
TEST_SCANF_WARN("%lf", "double", "char");
TEST_SCANF_WARN("%lf", "double", "signed char");
TEST_SCANF_WARN("%lf", "double", "unsigned char");
TEST_SCANF_WARN("%lf", "double", "signed short");
TEST_SCANF_WARN("%lf", "double", "unsigned short");
TEST_SCANF_WARN("%lf", "double", "signed int");
TEST_SCANF_WARN("%lf", "double", "unsigned int");
TEST_SCANF_WARN("%lf", "double", "signed long");
TEST_SCANF_WARN("%lf", "double", "unsigned long");
TEST_SCANF_WARN("%lf", "double", "signed long long");
TEST_SCANF_WARN("%lf", "double", "unsigned long long");
TEST_SCANF_WARN("%lf", "double", "float");
TEST_SCANF_NOWARN("%lf", "double", "double");
TEST_SCANF_WARN("%lf", "double", "long double");
TEST_SCANF_WARN("%lf", "double", "void *");
TEST_SCANF_WARN_AKA("%lf", "double", "size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%lf", "double", "ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%lf", "double", "ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%lf", "double", "unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%lf", "double", "intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%lf", "double", "uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%lf", "double", "std::size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%lf", "double", "std::ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%lf", "double", "std::ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%lf", "double", "std::intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%lf", "double", "std::uintptr_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN("%Lf", "long double", "bool");
TEST_SCANF_WARN("%Lf", "long double", "char");
TEST_SCANF_WARN("%Lf", "long double", "signed char");
TEST_SCANF_WARN("%Lf", "long double", "unsigned char");
TEST_SCANF_WARN("%Lf", "long double", "signed short");
TEST_SCANF_WARN("%Lf", "long double", "unsigned short");
TEST_SCANF_WARN("%Lf", "long double", "signed int");
TEST_SCANF_WARN("%Lf", "long double", "unsigned int");
TEST_SCANF_WARN("%Lf", "long double", "signed long");
TEST_SCANF_WARN("%Lf", "long double", "unsigned long");
TEST_SCANF_WARN("%Lf", "long double", "signed long long");
TEST_SCANF_WARN("%Lf", "long double", "unsigned long long");
TEST_SCANF_WARN("%Lf", "long double", "float");
TEST_SCANF_WARN("%Lf", "long double", "double");
TEST_SCANF_NOWARN("%Lf", "long double", "long double");
TEST_SCANF_WARN("%Lf", "long double", "void *");
TEST_SCANF_WARN_AKA("%Lf", "long double", "size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%Lf", "long double", "ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%Lf", "long double", "ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%Lf", "long double", "unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%Lf", "long double", "intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%Lf", "long double", "uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%Lf", "long double", "std::size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%Lf", "long double", "std::ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%Lf", "long double", "std::ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%Lf", "long double", "std::intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%Lf", "long double", "std::uintptr_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN("%n", "int", "bool");
TEST_SCANF_WARN("%n", "int", "char");
TEST_SCANF_WARN("%n", "int", "signed char");
TEST_SCANF_WARN("%n", "int", "unsigned char");
TEST_SCANF_WARN("%n", "int", "signed short");
TEST_SCANF_WARN("%n", "int", "unsigned short");
TEST_SCANF_NOWARN("%n", "int", "signed int");
TEST_SCANF_WARN("%n", "int", "unsigned int");
TEST_SCANF_WARN("%n", "int", "signed long");
TEST_SCANF_WARN("%n", "int", "unsigned long");
TEST_SCANF_WARN("%n", "int", "signed long long");
TEST_SCANF_WARN("%n", "int", "unsigned long long");
TEST_SCANF_WARN("%n", "int", "float");
TEST_SCANF_WARN("%n", "int", "double");
TEST_SCANF_WARN("%n", "int", "long double");
TEST_SCANF_WARN("%n", "int", "void *");
TEST_SCANF_WARN_AKA("%n", "int", "size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%n", "int", "ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%n", "int", "ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%n", "int", "unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA("%n", "int", "intmax_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA("%n", "int", "uintmax_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%n", "int", "std::size_t", "unsigned long", "unsigned long long");
TEST_SCANF_WARN_AKA_CPP("%n", "int", "std::ssize_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%n", "int", "std::ptrdiff_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%n", "int", "std::intptr_t", "signed long", "signed long long");
TEST_SCANF_WARN_AKA_CPP("%n", "int", "std::uintptr_t", "unsigned long", "unsigned long long");
check("void foo() {\n"
" scanf(\"%n\", \"s3\");\n"
" scanf(\"%n\", L\"s5W\");\n"
"}", dinit(CheckOptions, $.inconclusive = true));
ASSERT_EQUALS("[test.cpp:2]: (warning) %n in format string (no. 1) requires 'int *' but the argument type is 'const char *'.\n"
"[test.cpp:3]: (warning) %n in format string (no. 1) requires 'int *' but the argument type is 'const wchar_t *'.\n", errout_str());
check("void foo(long l) {\n"
" scanf(\"%n\", l);\n"
"}", dinit(CheckOptions, $.inconclusive = true));
ASSERT_EQUALS("[test.cpp:2]: (warning) %n in format string (no. 1) requires 'int *' but the argument type is 'signed long'.\n", errout_str());
check("void g() {\n" // #5104
" myvector<int> v1(1);\n"
" scanf(\"%d\",&v1[0]);\n"
" myvector<unsigned int> v2(1);\n"
" scanf(\"%u\",&v2[0]);\n"
" myvector<unsigned int> v3(1);\n"
" scanf(\"%x\",&v3[0]);\n"
" myvector<double> v4(1);\n"
" scanf(\"%lf\",&v4[0]);\n"
" myvector<char *> v5(1);\n"
" scanf(\"%10s\",v5[0]);\n"
"}");
ASSERT_EQUALS("", errout_str());
{
const char code[] = "void g() {\n" // #5348
" size_t s1;\n"
" ptrdiff_t s2;\n"
" ssize_t s3;\n"
" scanf(\"%zd\", &s1);\n"
" scanf(\"%zd\", &s2);\n"
" scanf(\"%zd\", &s3);\n"
"}\n";
const char* result("[test.cpp:5]: (portability) %zd in format string (no. 1) requires 'ssize_t *' but the argument type is 'size_t * {aka unsigned long *}'.\n"
"[test.cpp:6]: (portability) %zd in format string (no. 1) requires 'ssize_t *' but the argument type is 'ptrdiff_t * {aka signed long *}'.\n");
const char* result_win64("[test.cpp:5]: (portability) %zd in format string (no. 1) requires 'ssize_t *' but the argument type is 'size_t * {aka unsigned long long *}'.\n"
"[test.cpp:6]: (portability) %zd in format string (no. 1) requires 'ssize_t *' but the argument type is 'ptrdiff_t * {aka signed long long *}'.\n");
check(code, dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Unix32));
ASSERT_EQUALS(result, errout_str());
check(code, dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Unix64));
ASSERT_EQUALS(result, errout_str());
check(code, dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS(result, errout_str());
check(code, dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Win32W));
ASSERT_EQUALS(result, errout_str());
check(code, dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Win64));
ASSERT_EQUALS(result_win64, errout_str());
}
{
check("void g() {\n"
" const char c[]=\"42\";\n"
" scanf(\"%s\", c);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) %s in format string (no. 1) requires a 'char *' but the argument type is 'const char *'.\n"
"[test.cpp:3]: (warning) scanf() without field width limits can crash with huge input data.\n", errout_str());
}
check("void f() {\n" // #7038
" scanf(\"%i\", \"abc\" + 1);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (warning) %i in format string (no. 1) requires 'int *' but the argument type is 'const char *'.\n", errout_str());
}
void testPrintfArgument() {
check("void foo() {\n"
" printf(\"%i\");\n"
" printf(\"%i%s\", 123);\n"
" printf(\"%i%s%d\", 0, bar());\n"
" printf(\"%i%%%s%d\", 0, bar());\n"
" printf(\"%idfd%%dfa%s%d\", 0, bar());\n"
" fprintf(stderr,\"%u%s\");\n"
" snprintf(str,10,\"%u%s\");\n"
" sprintf(string1, \"%-*.*s\", 32, string2);\n" // #3364
" snprintf(a, 9, \"%s%d\", \"11223344\");\n" // #3655
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) printf format string requires 1 parameter but only 0 are given.\n"
"[test.cpp:3]: (error) printf format string requires 2 parameters but only 1 is given.\n"
"[test.cpp:4]: (error) printf format string requires 3 parameters but only 2 are given.\n"
"[test.cpp:5]: (error) printf format string requires 3 parameters but only 2 are given.\n"
"[test.cpp:6]: (error) printf format string requires 3 parameters but only 2 are given.\n"
"[test.cpp:7]: (error) fprintf format string requires 2 parameters but only 0 are given.\n"
"[test.cpp:8]: (error) snprintf format string requires 2 parameters but only 0 are given.\n"
"[test.cpp:9]: (error) sprintf format string requires 3 parameters but only 2 are given.\n"
"[test.cpp:10]: (error) snprintf format string requires 2 parameters but only 1 is given.\n", errout_str());
check("void foo(char *str) {\n"
" printf(\"\", 0);\n"
" printf(\"%i\", 123, bar());\n"
" printf(\"%i%s\", 0, bar(), 43123);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) printf format string requires 0 parameters but 1 is given.\n"
"[test.cpp:3]: (warning) printf format string requires 1 parameter but 2 are given.\n"
"[test.cpp:4]: (warning) printf format string requires 2 parameters but 3 are given.\n", errout_str());
check("void foo() {\n" // swprintf exists as MSVC extension and as standard function: #4790
" swprintf(string1, L\"%i\", 32, string2);\n" // MSVC implementation
" swprintf(string1, L\"%s%s\", L\"a\", string2);\n" // MSVC implementation
" swprintf(string1, 6, L\"%i\", 32, string2);\n" // Standard implementation
" swprintf(string1, 6, L\"%i%s\", 32, string2);\n" // Standard implementation
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) swprintf format string requires 1 parameter but 2 are given.\n"
"[test.cpp:4]: (warning) swprintf format string requires 1 parameter but 2 are given.\n", errout_str());
check("void foo(char *str) {\n"
" printf(\"%i\", 0);\n"
" printf(\"%i%s\", 123, bar());\n"
" printf(\"%i%s%d\", 0, bar(), 43123);\n"
" printf(\"%i%%%s%d\", 0, bar(), 43123);\n"
" printf(\"%idfd%%dfa%s%d\", 0, bar(), 43123);\n"
" printf(\"%\"PRId64\"\", 123);\n"
" fprintf(stderr,\"%\"PRId64\"\", 123);\n"
" snprintf(str,10,\"%\"PRId64\"\", 123);\n"
" fprintf(stderr, \"error: %m\");\n" // #3339
" printf(\"string: %.*s\", len, string);\n" // #3311
" fprintf(stderr, \"%*cText.\", indent, ' ');\n" // #3313
" sprintf(string1, \"%*\", 32);\n" // #3364
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(char* s, const char* s2, std::string s3, int i) {\n"
" printf(\"%s%s\", s, s2);\n"
" printf(\"%s\", i);\n"
" printf(\"%i%s\", i, i);\n"
" printf(\"%s\", s3);\n"
" printf(\"%s\", \"s4\");\n"
" printf(\"%u\", s);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) %s in format string (no. 1) requires 'char *' but the argument type is 'signed int'.\n"
"[test.cpp:4]: (warning) %s in format string (no. 2) requires 'char *' but the argument type is 'signed int'.\n"
"[test.cpp:5]: (warning) %s in format string (no. 1) requires 'char *' but the argument type is 'std::string'.\n"
"[test.cpp:7]: (warning) %u in format string (no. 1) requires 'unsigned int' but the argument type is 'char *'.\n", errout_str());
check("void foo(char* s, const char* s2, std::string s3, int i) {\n"
" printf(\"%jd\", s);\n"
" printf(\"%ji\", s);\n"
" printf(\"%ju\", s2);\n"
" printf(\"%jo\", s3);\n"
" printf(\"%jx\", i);\n"
" printf(\"%jX\", i);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) %jd in format string (no. 1) requires 'intmax_t' but the argument type is 'char *'.\n"
"[test.cpp:3]: (warning) %ji in format string (no. 1) requires 'intmax_t' but the argument type is 'char *'.\n"
"[test.cpp:4]: (warning) %ju in format string (no. 1) requires 'uintmax_t' but the argument type is 'const char *'.\n"
"[test.cpp:5]: (warning) %jo in format string (no. 1) requires 'uintmax_t' but the argument type is 'std::string'.\n"
"[test.cpp:6]: (warning) %jx in format string (no. 1) requires 'uintmax_t' but the argument type is 'signed int'.\n"
"[test.cpp:7]: (warning) %jX in format string (no. 1) requires 'uintmax_t' but the argument type is 'signed int'.\n", errout_str());
check("void foo(uintmax_t uim, std::string s3, unsigned int ui, int i) {\n"
" printf(\"%ju\", uim);\n"
" printf(\"%ju\", ui);\n"
" printf(\"%jd\", ui);\n"
" printf(\"%jd\", s3);\n"
" printf(\"%jd\", i);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) %ju in format string (no. 1) requires 'uintmax_t' but the argument type is 'unsigned int'.\n"
"[test.cpp:4]: (warning) %jd in format string (no. 1) requires 'intmax_t' but the argument type is 'unsigned int'.\n"
"[test.cpp:5]: (warning) %jd in format string (no. 1) requires 'intmax_t' but the argument type is 'std::string'.\n"
"[test.cpp:6]: (warning) %jd in format string (no. 1) requires 'intmax_t' but the argument type is 'signed int'.\n", errout_str());
check("void foo(const int* cpi, const int ci, int i, int* pi, std::string s) {\n"
" printf(\"%n\", cpi);\n"
" printf(\"%n\", ci);\n"
" printf(\"%n\", i);\n"
" printf(\"%n\", pi);\n"
" printf(\"%n\", s);\n"
" printf(\"%n\", \"s4\");\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) %n in format string (no. 1) requires 'int *' but the argument type is 'signed int'.\n"
"[test.cpp:4]: (warning) %n in format string (no. 1) requires 'int *' but the argument type is 'signed int'.\n"
"[test.cpp:6]: (warning) %n in format string (no. 1) requires 'int *' but the argument type is 'std::string'.\n"
"[test.cpp:7]: (warning) %n in format string (no. 1) requires 'int *' but the argument type is 'const char *'.\n", errout_str());
check("void foo() {\n"
" printf(\"%n\", L\"s5W\");\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) %n in format string (no. 1) requires 'int *' but the argument type is 'const wchar_t *'.\n", errout_str());
check("class foo {};\n"
"void foo(const int* cpi, foo f, bar b, bar* bp, double d, int i, unsigned int u) {\n"
" printf(\"%X\", f);\n"
" printf(\"%c\", \"s4\");\n"
" printf(\"%o\", d);\n"
" printf(\"%x\", cpi);\n"
" printf(\"%o\", b);\n"
" printf(\"%X\", bp);\n"
" printf(\"%X\", u);\n"
" printf(\"%X\", i);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) %X in format string (no. 1) requires 'unsigned int' but the argument type is 'foo'.\n"
"[test.cpp:4]: (warning) %c in format string (no. 1) requires 'unsigned int' but the argument type is 'const char *'.\n"
"[test.cpp:5]: (warning) %o in format string (no. 1) requires 'unsigned int' but the argument type is 'double'.\n"
"[test.cpp:6]: (warning) %x in format string (no. 1) requires 'unsigned int' but the argument type is 'const signed int *'.\n"
"[test.cpp:8]: (warning) %X in format string (no. 1) requires 'unsigned int' but the argument type is 'bar *'.\n", errout_str());
check("class foo {};\n"
"void foo(const char* cpc, char* pc) {\n"
" printf(\"%x\", cpc);\n"
" printf(\"%x\", pc);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) %x in format string (no. 1) requires 'unsigned int' but the argument type is 'const char *'.\n"
"[test.cpp:4]: (warning) %x in format string (no. 1) requires 'unsigned int' but the argument type is 'char *'.\n", errout_str());
check("class foo {};\n"
"void foo() {\n"
" printf(\"%x\", L\"s5W\");\n"
" printf(\"%X\", L\"s5W\");\n"
" printf(\"%c\", L\"s5W\");\n"
" printf(\"%o\", L\"s5W\");\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) %x in format string (no. 1) requires 'unsigned int' but the argument type is 'const wchar_t *'.\n"
"[test.cpp:4]: (warning) %X in format string (no. 1) requires 'unsigned int' but the argument type is 'const wchar_t *'.\n"
"[test.cpp:5]: (warning) %c in format string (no. 1) requires 'unsigned int' but the argument type is 'const wchar_t *'.\n"
"[test.cpp:6]: (warning) %o in format string (no. 1) requires 'unsigned int' but the argument type is 'const wchar_t *'.\n", errout_str());
check("class foo {};\n"
"void foo(const int* cpi, foo f, bar b, bar* bp, double d, unsigned int u, unsigned char uc) {\n"
" printf(\"%i\", f);\n"
" printf(\"%d\", \"s4\");\n"
" printf(\"%d\", d);\n"
" printf(\"%d\", u);\n"
" printf(\"%d\", cpi);\n"
" printf(\"%i\", b);\n"
" printf(\"%i\", bp);\n"
" printf(\"%i\", uc);\n" // char is smaller than int, so there shouldn't be a problem
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) %i in format string (no. 1) requires 'int' but the argument type is 'foo'.\n"
"[test.cpp:4]: (warning) %d in format string (no. 1) requires 'int' but the argument type is 'const char *'.\n"
"[test.cpp:5]: (warning) %d in format string (no. 1) requires 'int' but the argument type is 'double'.\n"
"[test.cpp:6]: (warning) %d in format string (no. 1) requires 'int' but the argument type is 'unsigned int'.\n"
"[test.cpp:7]: (warning) %d in format string (no. 1) requires 'int' but the argument type is 'const signed int *'.\n"
"[test.cpp:9]: (warning) %i in format string (no. 1) requires 'int' but the argument type is 'bar *'.\n", errout_str());
check("class foo {};\n"
"void foo() {\n"
" printf(\"%i\", L\"s5W\");\n"
" printf(\"%d\", L\"s5W\");\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) %i in format string (no. 1) requires 'int' but the argument type is 'const wchar_t *'.\n"
"[test.cpp:4]: (warning) %d in format string (no. 1) requires 'int' but the argument type is 'const wchar_t *'.\n", errout_str());
check("class foo {};\n"
"void foo(const int* cpi, foo f, bar b, bar* bp, double d, int i, bool bo) {\n"
" printf(\"%u\", f);\n"
" printf(\"%u\", \"s4\");\n"
" printf(\"%u\", d);\n"
" printf(\"%u\", i);\n"
" printf(\"%u\", cpi);\n"
" printf(\"%u\", b);\n"
" printf(\"%u\", bp);\n"
" printf(\"%u\", bo);\n" // bool shouldn't have a negative sign
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) %u in format string (no. 1) requires 'unsigned int' but the argument type is 'foo'.\n"
"[test.cpp:4]: (warning) %u in format string (no. 1) requires 'unsigned int' but the argument type is 'const char *'.\n"
"[test.cpp:5]: (warning) %u in format string (no. 1) requires 'unsigned int' but the argument type is 'double'.\n"
"[test.cpp:6]: (warning) %u in format string (no. 1) requires 'unsigned int' but the argument type is 'signed int'.\n"
"[test.cpp:7]: (warning) %u in format string (no. 1) requires 'unsigned int' but the argument type is 'const signed int *'.\n"
"[test.cpp:9]: (warning) %u in format string (no. 1) requires 'unsigned int' but the argument type is 'bar *'.\n", errout_str());
check("class foo {};\n"
"void foo(const int* cpi, foo f, bar b, bar* bp, double d, int i, bool bo) {\n"
" printf(\"%u\", L\"s5W\");\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) %u in format string (no. 1) requires 'unsigned int' but the argument type is 'const wchar_t *'.\n", errout_str());
check("class foo {};\n"
"void foo(const int* cpi, foo f, bar b, bar* bp, char c) {\n"
" printf(\"%p\", f);\n"
" printf(\"%p\", c);\n"
" printf(\"%p\", bp);\n"
" printf(\"%p\", cpi);\n"
" printf(\"%p\", b);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) %p in format string (no. 1) requires an address but the argument type is 'foo'.\n"
"[test.cpp:4]: (warning) %p in format string (no. 1) requires an address but the argument type is 'char'.\n", errout_str());
check("class foo {};\n"
"void foo(char* pc, const char* cpc, wchar_t* pwc, const wchar_t* cpwc) {\n"
" printf(\"%p\", pc);\n"
" printf(\"%p\", cpc);\n"
" printf(\"%p\", pwc);\n"
" printf(\"%p\", cpwc);\n"
" printf(\"%p\", \"s4\");\n"
" printf(\"%p\", L\"s5W\");\n"
"}");
ASSERT_EQUALS("", errout_str());
check("class foo {};\n"
"void foo(const int* cpi, foo f, bar b, bar* bp, double d) {\n"
" printf(\"%e\", f);\n"
" printf(\"%E\", \"s4\");\n"
" printf(\"%f\", cpi);\n"
" printf(\"%G\", bp);\n"
" printf(\"%f\", d);\n"
" printf(\"%f\", b);\n"
" printf(\"%f\", (float)cpi);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) %e in format string (no. 1) requires 'double' but the argument type is 'foo'.\n"
"[test.cpp:4]: (warning) %E in format string (no. 1) requires 'double' but the argument type is 'const char *'.\n"
"[test.cpp:5]: (warning) %f in format string (no. 1) requires 'double' but the argument type is 'const signed int *'.\n"
"[test.cpp:6]: (warning) %G in format string (no. 1) requires 'double' but the argument type is 'bar *'.\n", errout_str());
check("class foo {};\n"
"void foo(const char* cpc, char* pc) {\n"
" printf(\"%e\", cpc);\n"
" printf(\"%E\", pc);\n"
" printf(\"%f\", cpc);\n"
" printf(\"%G\", pc);\n"
" printf(\"%f\", pc);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) %e in format string (no. 1) requires 'double' but the argument type is 'const char *'.\n"
"[test.cpp:4]: (warning) %E in format string (no. 1) requires 'double' but the argument type is 'char *'.\n"
"[test.cpp:5]: (warning) %f in format string (no. 1) requires 'double' but the argument type is 'const char *'.\n"
"[test.cpp:6]: (warning) %G in format string (no. 1) requires 'double' but the argument type is 'char *'.\n"
"[test.cpp:7]: (warning) %f in format string (no. 1) requires 'double' but the argument type is 'char *'.\n", errout_str());
check("class foo {};\n"
"void foo() {\n"
" printf(\"%e\", L\"s5W\");\n"
" printf(\"%E\", L\"s5W\");\n"
" printf(\"%f\", L\"s5W\");\n"
" printf(\"%G\", L\"s5W\");\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) %e in format string (no. 1) requires 'double' but the argument type is 'const wchar_t *'.\n"
"[test.cpp:4]: (warning) %E in format string (no. 1) requires 'double' but the argument type is 'const wchar_t *'.\n"
"[test.cpp:5]: (warning) %f in format string (no. 1) requires 'double' but the argument type is 'const wchar_t *'.\n"
"[test.cpp:6]: (warning) %G in format string (no. 1) requires 'double' but the argument type is 'const wchar_t *'.\n", errout_str());
check("class foo;\n"
"void foo(foo f) {\n"
" printf(\"%u\", f);\n"
" printf(\"%f\", f);\n"
" printf(\"%p\", f);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) %u in format string (no. 1) requires 'unsigned int' but the argument type is 'foo'.\n"
"[test.cpp:4]: (warning) %f in format string (no. 1) requires 'double' but the argument type is 'foo'.\n"
"[test.cpp:5]: (warning) %p in format string (no. 1) requires an address but the argument type is 'foo'.\n", errout_str());
// Ticket #4189 (Improve check (printf("%l") not detected)) tests (according to C99 7.19.6.1.7)
// False positive tests
check("void foo(signed char sc, unsigned char uc, short int si, unsigned short int usi) {\n"
" printf(\"%hhx %hhd\", sc, uc);\n"
" printf(\"%hd %hu\", si, usi);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) %hhx in format string (no. 1) requires 'unsigned char' but the argument type is 'signed char'.\n"
"[test.cpp:2]: (warning) %hhd in format string (no. 2) requires 'char' but the argument type is 'unsigned char'.\n", errout_str());
check("void foo(long long int lli, unsigned long long int ulli, long int li, unsigned long int uli) {\n"
" printf(\"%llo %llx\", lli, ulli);\n"
" printf(\"%ld %lu\", li, uli);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(intmax_t im, uintmax_t uim, size_t s, ptrdiff_t p, long double ld, std::size_t ss, std::ptrdiff_t sp) {\n"
" printf(\"%jd %jo\", im, uim);\n"
" printf(\"%zx\", s);\n"
" printf(\"%ti\", p);\n"
" printf(\"%Lf\", ld);\n"
" printf(\"%zx\", ss);\n"
" printf(\"%ti\", sp);\n"
"}");
ASSERT_EQUALS("", errout_str());
// Unrecognized (and non-existent in standard library) specifiers.
// Perhaps should emit warnings
check("void foo(intmax_t im, uintmax_t uim, size_t s, ptrdiff_t p, long double ld, std::size_t ss, std::ptrdiff_t sp) {\n"
" printf(\"%jb %jw\", im, uim);\n"
" printf(\"%zr\", s);\n"
" printf(\"%tm\", p);\n"
" printf(\"%La\", ld);\n"
" printf(\"%zv\", ss);\n"
" printf(\"%tp\", sp);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(long long l, ptrdiff_t p, std::ptrdiff_t sp) {\n"
" printf(\"%td\", p);\n"
" printf(\"%td\", sp);\n"
" printf(\"%td\", l);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (warning) %td in format string (no. 1) requires 'ptrdiff_t' but the argument type is 'signed long long'.\n", errout_str());
check("void foo(int i, long double ld) {\n"
" printf(\"%zx %zu\", i, ld);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) %zx in format string (no. 1) requires 'size_t' but the argument type is 'signed int'.\n"
"[test.cpp:2]: (warning) %zu in format string (no. 2) requires 'size_t' but the argument type is 'long double'.\n", errout_str());
check("void foo(unsigned int ui, long double ld) {\n"
" printf(\"%zu %zx\", ui, ld);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) %zu in format string (no. 1) requires 'size_t' but the argument type is 'unsigned int'.\n"
"[test.cpp:2]: (warning) %zx in format string (no. 2) requires 'size_t' but the argument type is 'long double'.\n", errout_str());
check("void foo(int i, long double ld) {\n"
" printf(\"%tx %tu\", i, ld);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) %tx in format string (no. 1) requires 'unsigned ptrdiff_t' but the argument type is 'signed int'.\n"
"[test.cpp:2]: (warning) %tu in format string (no. 2) requires 'unsigned ptrdiff_t' but the argument type is 'long double'.\n", errout_str());
// False negative test
check("void foo(unsigned int i) {\n"
" printf(\"%h\", i);\n"
" printf(\"%hh\", i);\n"
" printf(\"%l\", i);\n"
" printf(\"%ll\", i);\n"
" printf(\"%j\", i);\n"
" printf(\"%z\", i);\n"
" printf(\"%t\", i);\n"
" printf(\"%L\", i);\n"
" printf(\"%I\", i);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) 'h' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:3]: (warning) 'hh' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:4]: (warning) 'l' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:5]: (warning) 'll' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:6]: (warning) 'j' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:7]: (warning) 'z' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:8]: (warning) 't' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:9]: (warning) 'L' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:10]: (warning) 'I' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n", errout_str());
check("void foo(unsigned int i) {\n"
" printf(\"%hd\", i);\n"
" printf(\"%hhd\", i);\n"
" printf(\"%ld\", i);\n"
" printf(\"%lld\", i);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) %hd in format string (no. 1) requires 'short' but the argument type is 'unsigned int'.\n"
"[test.cpp:3]: (warning) %hhd in format string (no. 1) requires 'char' but the argument type is 'unsigned int'.\n"
"[test.cpp:4]: (warning) %ld in format string (no. 1) requires 'long' but the argument type is 'unsigned int'.\n"
"[test.cpp:5]: (warning) %lld in format string (no. 1) requires 'long long' but the argument type is 'unsigned int'.\n", errout_str());
check("void foo(size_t s, ptrdiff_t p) {\n"
" printf(\"%zd\", s);\n"
" printf(\"%tu\", p);\n"
"}", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Unix32));
ASSERT_EQUALS("[test.cpp:2]: (portability) %zd in format string (no. 1) requires 'ssize_t' but the argument type is 'size_t {aka unsigned long}'.\n"
"[test.cpp:3]: (portability) %tu in format string (no. 1) requires 'unsigned ptrdiff_t' but the argument type is 'ptrdiff_t {aka signed long}'.\n", errout_str());
check("void foo(std::size_t s, std::ptrdiff_t p) {\n"
" printf(\"%zd\", s);\n"
" printf(\"%tu\", p);\n"
"}", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Unix32));
ASSERT_EQUALS("[test.cpp:2]: (portability) %zd in format string (no. 1) requires 'ssize_t' but the argument type is 'std::size_t {aka unsigned long}'.\n"
"[test.cpp:3]: (portability) %tu in format string (no. 1) requires 'unsigned ptrdiff_t' but the argument type is 'std::ptrdiff_t {aka signed long}'.\n", errout_str());
check("void foo(size_t s, ptrdiff_t p) {\n"
" printf(\"%zd\", s);\n"
" printf(\"%tu\", p);\n"
"}", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Unix64));
ASSERT_EQUALS("[test.cpp:2]: (portability) %zd in format string (no. 1) requires 'ssize_t' but the argument type is 'size_t {aka unsigned long}'.\n"
"[test.cpp:3]: (portability) %tu in format string (no. 1) requires 'unsigned ptrdiff_t' but the argument type is 'ptrdiff_t {aka signed long}'.\n", errout_str());
check("void foo(std::size_t s, std::ptrdiff_t p) {\n"
" printf(\"%zd\", s);\n"
" printf(\"%tu\", p);\n"
"}", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Unix64));
ASSERT_EQUALS("[test.cpp:2]: (portability) %zd in format string (no. 1) requires 'ssize_t' but the argument type is 'std::size_t {aka unsigned long}'.\n"
"[test.cpp:3]: (portability) %tu in format string (no. 1) requires 'unsigned ptrdiff_t' but the argument type is 'std::ptrdiff_t {aka signed long}'.\n", errout_str());
check("void foo(size_t s, ptrdiff_t p) {\n"
" printf(\"%zd\", s);\n"
" printf(\"%tu\", p);\n"
"}", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("[test.cpp:2]: (portability) %zd in format string (no. 1) requires 'ssize_t' but the argument type is 'size_t {aka unsigned long}'.\n"
"[test.cpp:3]: (portability) %tu in format string (no. 1) requires 'unsigned ptrdiff_t' but the argument type is 'ptrdiff_t {aka signed long}'.\n", errout_str());
check("void foo(std::size_t s, std::ptrdiff_t p) {\n"
" printf(\"%zd\", s);\n"
" printf(\"%tu\", p);\n"
"}", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("[test.cpp:2]: (portability) %zd in format string (no. 1) requires 'ssize_t' but the argument type is 'std::size_t {aka unsigned long}'.\n"
"[test.cpp:3]: (portability) %tu in format string (no. 1) requires 'unsigned ptrdiff_t' but the argument type is 'std::ptrdiff_t {aka signed long}'.\n", errout_str());
check("void foo(size_t s, ptrdiff_t p) {\n"
" printf(\"%zd\", s);\n"
" printf(\"%tu\", p);\n"
"}", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Win64));
ASSERT_EQUALS("[test.cpp:2]: (portability) %zd in format string (no. 1) requires 'ssize_t' but the argument type is 'size_t {aka unsigned long long}'.\n"
"[test.cpp:3]: (portability) %tu in format string (no. 1) requires 'unsigned ptrdiff_t' but the argument type is 'ptrdiff_t {aka signed long long}'.\n", errout_str());
check("void foo(std::size_t s, std::ptrdiff_t p) {\n"
" printf(\"%zd\", s);\n"
" printf(\"%tu\", p);\n"
"}", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Win64));
ASSERT_EQUALS("[test.cpp:2]: (portability) %zd in format string (no. 1) requires 'ssize_t' but the argument type is 'std::size_t {aka unsigned long long}'.\n"
"[test.cpp:3]: (portability) %tu in format string (no. 1) requires 'unsigned ptrdiff_t' but the argument type is 'std::ptrdiff_t {aka signed long long}'.\n", errout_str());
check("void foo(size_t s, uintmax_t um) {\n"
" printf(\"%lu\", s);\n"
" printf(\"%lu\", um);\n"
" printf(\"%llu\", s);\n"
" printf(\"%llu\", um);\n"
"}", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Win64));
ASSERT_EQUALS("[test.cpp:2]: (portability) %lu in format string (no. 1) requires 'unsigned long' but the argument type is 'size_t {aka unsigned long long}'.\n"
"[test.cpp:3]: (portability) %lu in format string (no. 1) requires 'unsigned long' but the argument type is 'uintmax_t {aka unsigned long long}'.\n"
"[test.cpp:4]: (portability) %llu in format string (no. 1) requires 'unsigned long long' but the argument type is 'size_t {aka unsigned long long}'.\n"
"[test.cpp:5]: (portability) %llu in format string (no. 1) requires 'unsigned long long' but the argument type is 'uintmax_t {aka unsigned long long}'.\n", errout_str());
check("void foo(unsigned int i) {\n"
" printf(\"%ld\", i);\n"
" printf(\"%lld\", i);\n"
" printf(\"%lu\", i);\n"
" printf(\"%llu\", i);\n"
" printf(\"%lx\", i);\n"
" printf(\"%llx\", i);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) %ld in format string (no. 1) requires 'long' but the argument type is 'unsigned int'.\n"
"[test.cpp:3]: (warning) %lld in format string (no. 1) requires 'long long' but the argument type is 'unsigned int'.\n"
"[test.cpp:4]: (warning) %lu in format string (no. 1) requires 'unsigned long' but the argument type is 'unsigned int'.\n"
"[test.cpp:5]: (warning) %llu in format string (no. 1) requires 'unsigned long long' but the argument type is 'unsigned int'.\n"
"[test.cpp:6]: (warning) %lx in format string (no. 1) requires 'unsigned long' but the argument type is 'unsigned int'.\n"
"[test.cpp:7]: (warning) %llx in format string (no. 1) requires 'unsigned long long' but the argument type is 'unsigned int'.\n", errout_str());
check("void foo(int i, intmax_t im, ptrdiff_t p) {\n"
" printf(\"%lld\", i);\n"
" printf(\"%lld\", im);\n"
" printf(\"%lld\", p);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) %lld in format string (no. 1) requires 'long long' but the argument type is 'signed int'.\n", errout_str());
check("void foo(intmax_t im, ptrdiff_t p) {\n"
" printf(\"%lld\", im);\n"
" printf(\"%lld\", p);\n"
"}", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Win64));
ASSERT_EQUALS("[test.cpp:2]: (portability) %lld in format string (no. 1) requires 'long long' but the argument type is 'intmax_t {aka signed long long}'.\n"
"[test.cpp:3]: (portability) %lld in format string (no. 1) requires 'long long' but the argument type is 'ptrdiff_t {aka signed long long}'.\n", errout_str());
check("class Foo {\n"
" double d;\n"
" struct Bar {\n"
" int i;\n"
" } bar[2];\n"
" struct Baz {\n"
" int i;\n"
" } baz;\n"
"};\n"
"int a[10];\n"
"Foo f[10];\n"
"void foo(const Foo* foo) {\n"
" printf(\"%d %f %f %d %f %f\",\n"
" foo->d, foo->bar[0].i, a[0],\n"
" f[0].d, f[0].baz.i, f[0].bar[0].i);\n"
"}");
ASSERT_EQUALS("[test.cpp:13]: (warning) %d in format string (no. 1) requires 'int' but the argument type is 'double'.\n"
"[test.cpp:13]: (warning) %f in format string (no. 2) requires 'double' but the argument type is 'signed int'.\n"
"[test.cpp:13]: (warning) %f in format string (no. 3) requires 'double' but the argument type is 'int'.\n"
"[test.cpp:13]: (warning) %d in format string (no. 4) requires 'int' but the argument type is 'double'.\n"
"[test.cpp:13]: (warning) %f in format string (no. 5) requires 'double' but the argument type is 'int'.\n"
"[test.cpp:13]: (warning) %f in format string (no. 6) requires 'double' but the argument type is 'int'.\n", errout_str());
check("short f() { return 0; }\n"
"void foo() { printf(\"%d %u %lu %I64u %I64d %f %Lf %p\", f(), f(), f(), f(), f(), f(), f(), f()); }");
ASSERT_EQUALS("[test.cpp:2]: (warning) %u in format string (no. 2) requires 'unsigned int' but the argument type is 'signed short'.\n"
"[test.cpp:2]: (warning) %lu in format string (no. 3) requires 'unsigned long' but the argument type is 'signed short'.\n"
"[test.cpp:2]: (warning) %I64u in format string (no. 4) requires 'unsigned __int64' but the argument type is 'signed short'.\n"
"[test.cpp:2]: (warning) %I64d in format string (no. 5) requires '__int64' but the argument type is 'signed short'.\n"
"[test.cpp:2]: (warning) %f in format string (no. 6) requires 'double' but the argument type is 'signed short'.\n"
"[test.cpp:2]: (warning) %Lf in format string (no. 7) requires 'long double' but the argument type is 'signed short'.\n"
"[test.cpp:2]: (warning) %p in format string (no. 8) requires an address but the argument type is 'signed short'.\n", errout_str());
check("unsigned short f() { return 0; }\n"
"void foo() { printf(\"%u %d %ld %I64d %I64u %f %Lf %p\", f(), f(), f(), f(), f(), f(), f(), f()); }");
ASSERT_EQUALS("[test.cpp:2]: (warning) %ld in format string (no. 3) requires 'long' but the argument type is 'unsigned short'.\n"
"[test.cpp:2]: (warning) %I64d in format string (no. 4) requires '__int64' but the argument type is 'unsigned short'.\n"
"[test.cpp:2]: (warning) %I64u in format string (no. 5) requires 'unsigned __int64' but the argument type is 'unsigned short'.\n"
"[test.cpp:2]: (warning) %f in format string (no. 6) requires 'double' but the argument type is 'unsigned short'.\n"
"[test.cpp:2]: (warning) %Lf in format string (no. 7) requires 'long double' but the argument type is 'unsigned short'.\n"
"[test.cpp:2]: (warning) %p in format string (no. 8) requires an address but the argument type is 'unsigned short'.\n", errout_str());
check("int f() { return 0; }\n"
"void foo() { printf(\"%d %u %lu %I64u %I64d %f %Lf %p\", f(), f(), f(), f(), f(), f(), f(), f()); }");
ASSERT_EQUALS("[test.cpp:2]: (warning) %u in format string (no. 2) requires 'unsigned int' but the argument type is 'signed int'.\n"
"[test.cpp:2]: (warning) %lu in format string (no. 3) requires 'unsigned long' but the argument type is 'signed int'.\n"
"[test.cpp:2]: (warning) %I64u in format string (no. 4) requires 'unsigned __int64' but the argument type is 'signed int'.\n"
"[test.cpp:2]: (warning) %I64d in format string (no. 5) requires '__int64' but the argument type is 'signed int'.\n"
"[test.cpp:2]: (warning) %f in format string (no. 6) requires 'double' but the argument type is 'signed int'.\n"
"[test.cpp:2]: (warning) %Lf in format string (no. 7) requires 'long double' but the argument type is 'signed int'.\n"
"[test.cpp:2]: (warning) %p in format string (no. 8) requires an address but the argument type is 'signed int'.\n", errout_str());
check("unsigned int f() { return 0; }\n"
"void foo() { printf(\"%u %d %ld %I64d %I64u %f %Lf %p\", f(), f(), f(), f(), f(), f(), f(), f()); }");
ASSERT_EQUALS("[test.cpp:2]: (warning) %d in format string (no. 2) requires 'int' but the argument type is 'unsigned int'.\n"
"[test.cpp:2]: (warning) %ld in format string (no. 3) requires 'long' but the argument type is 'unsigned int'.\n"
"[test.cpp:2]: (warning) %I64d in format string (no. 4) requires '__int64' but the argument type is 'unsigned int'.\n"
"[test.cpp:2]: (warning) %I64u in format string (no. 5) requires 'unsigned __int64' but the argument type is 'unsigned int'.\n"
"[test.cpp:2]: (warning) %f in format string (no. 6) requires 'double' but the argument type is 'unsigned int'.\n"
"[test.cpp:2]: (warning) %Lf in format string (no. 7) requires 'long double' but the argument type is 'unsigned int'.\n"
"[test.cpp:2]: (warning) %p in format string (no. 8) requires an address but the argument type is 'unsigned int'.\n", errout_str());
check("long f() { return 0; }\n"
"void foo() { printf(\"%ld %u %lu %I64u %I64d %f %Lf %p\", f(), f(), f(), f(), f(), f(), f(), f()); }");
ASSERT_EQUALS("[test.cpp:2]: (warning) %u in format string (no. 2) requires 'unsigned int' but the argument type is 'signed long'.\n"
"[test.cpp:2]: (warning) %lu in format string (no. 3) requires 'unsigned long' but the argument type is 'signed long'.\n"
"[test.cpp:2]: (warning) %I64u in format string (no. 4) requires 'unsigned __int64' but the argument type is 'signed long'.\n"
"[test.cpp:2]: (warning) %I64d in format string (no. 5) requires '__int64' but the argument type is 'signed long'.\n"
"[test.cpp:2]: (warning) %f in format string (no. 6) requires 'double' but the argument type is 'signed long'.\n"
"[test.cpp:2]: (warning) %Lf in format string (no. 7) requires 'long double' but the argument type is 'signed long'.\n"
"[test.cpp:2]: (warning) %p in format string (no. 8) requires an address but the argument type is 'signed long'.\n", errout_str());
check("unsigned long f() { return 0; }\n"
"void foo() { printf(\"%lu %d %ld %I64d %I64u %f %Lf %p\", f(), f(), f(), f(), f(), f(), f(), f()); }");
ASSERT_EQUALS("[test.cpp:2]: (warning) %d in format string (no. 2) requires 'int' but the argument type is 'unsigned long'.\n"
"[test.cpp:2]: (warning) %ld in format string (no. 3) requires 'long' but the argument type is 'unsigned long'.\n"
"[test.cpp:2]: (warning) %I64d in format string (no. 4) requires '__int64' but the argument type is 'unsigned long'.\n"
"[test.cpp:2]: (warning) %I64u in format string (no. 5) requires 'unsigned __int64' but the argument type is 'unsigned long'.\n"
"[test.cpp:2]: (warning) %f in format string (no. 6) requires 'double' but the argument type is 'unsigned long'.\n"
"[test.cpp:2]: (warning) %Lf in format string (no. 7) requires 'long double' but the argument type is 'unsigned long'.\n"
"[test.cpp:2]: (warning) %p in format string (no. 8) requires an address but the argument type is 'unsigned long'.\n", errout_str());
check("long long f() { return 0; }\n"
"void foo() { printf(\"%lld %u %lu %I64u %I64d %f %Lf %p\", f(), f(), f(), f(), f(), f(), f(), f()); }");
ASSERT_EQUALS("[test.cpp:2]: (warning) %u in format string (no. 2) requires 'unsigned int' but the argument type is 'signed long long'.\n"
"[test.cpp:2]: (warning) %lu in format string (no. 3) requires 'unsigned long' but the argument type is 'signed long long'.\n"
"[test.cpp:2]: (warning) %I64u in format string (no. 4) requires 'unsigned __int64' but the argument type is 'signed long long'.\n"
"[test.cpp:2]: (warning) %f in format string (no. 6) requires 'double' but the argument type is 'signed long long'.\n"
"[test.cpp:2]: (warning) %Lf in format string (no. 7) requires 'long double' but the argument type is 'signed long long'.\n"
"[test.cpp:2]: (warning) %p in format string (no. 8) requires an address but the argument type is 'signed long long'.\n", errout_str());
check("unsigned long long f() { return 0; }\n"
"void foo() { printf(\"%llu %d %ld %I64d %I64u %f %Lf %p\", f(), f(), f(), f(), f(), f(), f(), f()); }");
ASSERT_EQUALS("[test.cpp:2]: (warning) %d in format string (no. 2) requires 'int' but the argument type is 'unsigned long long'.\n"
"[test.cpp:2]: (warning) %ld in format string (no. 3) requires 'long' but the argument type is 'unsigned long long'.\n"
"[test.cpp:2]: (warning) %I64d in format string (no. 4) requires '__int64' but the argument type is 'unsigned long long'.\n"
"[test.cpp:2]: (warning) %f in format string (no. 6) requires 'double' but the argument type is 'unsigned long long'.\n"
"[test.cpp:2]: (warning) %Lf in format string (no. 7) requires 'long double' but the argument type is 'unsigned long long'.\n"
"[test.cpp:2]: (warning) %p in format string (no. 8) requires an address but the argument type is 'unsigned long long'.\n", errout_str());
check("float f() { return 0; }\n"
"void foo() { printf(\"%f %d %ld %u %lu %I64d %I64u %Lf %p\", f(), f(), f(), f(), f(), f(), f(), f(), f()); }");
ASSERT_EQUALS("[test.cpp:2]: (warning) %d in format string (no. 2) requires 'int' but the argument type is 'float'.\n"
"[test.cpp:2]: (warning) %ld in format string (no. 3) requires 'long' but the argument type is 'float'.\n"
"[test.cpp:2]: (warning) %u in format string (no. 4) requires 'unsigned int' but the argument type is 'float'.\n"
"[test.cpp:2]: (warning) %lu in format string (no. 5) requires 'unsigned long' but the argument type is 'float'.\n"
"[test.cpp:2]: (warning) %I64d in format string (no. 6) requires '__int64' but the argument type is 'float'.\n"
"[test.cpp:2]: (warning) %I64u in format string (no. 7) requires 'unsigned __int64' but the argument type is 'float'.\n"
"[test.cpp:2]: (warning) %Lf in format string (no. 8) requires 'long double' but the argument type is 'float'.\n"
"[test.cpp:2]: (warning) %p in format string (no. 9) requires an address but the argument type is 'float'.\n", errout_str());
check("double f() { return 0; }\n"
"void foo() { printf(\"%f %d %ld %u %lu %I64d %I64u %Lf %p\", f(), f(), f(), f(), f(), f(), f(), f(), f()); }");
ASSERT_EQUALS("[test.cpp:2]: (warning) %d in format string (no. 2) requires 'int' but the argument type is 'double'.\n"
"[test.cpp:2]: (warning) %ld in format string (no. 3) requires 'long' but the argument type is 'double'.\n"
"[test.cpp:2]: (warning) %u in format string (no. 4) requires 'unsigned int' but the argument type is 'double'.\n"
"[test.cpp:2]: (warning) %lu in format string (no. 5) requires 'unsigned long' but the argument type is 'double'.\n"
"[test.cpp:2]: (warning) %I64d in format string (no. 6) requires '__int64' but the argument type is 'double'.\n"
"[test.cpp:2]: (warning) %I64u in format string (no. 7) requires 'unsigned __int64' but the argument type is 'double'.\n"
"[test.cpp:2]: (warning) %Lf in format string (no. 8) requires 'long double' but the argument type is 'double'.\n"
"[test.cpp:2]: (warning) %p in format string (no. 9) requires an address but the argument type is 'double'.\n", errout_str());
check("long double f() { return 0; }\n"
"void foo() { printf(\"%Lf %d %ld %u %lu %I64d %I64u %f %p\", f(), f(), f(), f(), f(), f(), f(), f(), f()); }");
ASSERT_EQUALS("[test.cpp:2]: (warning) %d in format string (no. 2) requires 'int' but the argument type is 'long double'.\n"
"[test.cpp:2]: (warning) %ld in format string (no. 3) requires 'long' but the argument type is 'long double'.\n"
"[test.cpp:2]: (warning) %u in format string (no. 4) requires 'unsigned int' but the argument type is 'long double'.\n"
"[test.cpp:2]: (warning) %lu in format string (no. 5) requires 'unsigned long' but the argument type is 'long double'.\n"
"[test.cpp:2]: (warning) %I64d in format string (no. 6) requires '__int64' but the argument type is 'long double'.\n"
"[test.cpp:2]: (warning) %I64u in format string (no. 7) requires 'unsigned __int64' but the argument type is 'long double'.\n"
"[test.cpp:2]: (warning) %f in format string (no. 8) requires 'double' but the argument type is 'long double'.\n"
"[test.cpp:2]: (warning) %p in format string (no. 9) requires an address but the argument type is 'long double'.\n", errout_str());
check("int f() { return 0; }\n"
"void foo() { printf(\"%I64d %I64u %I64x %d\", f(), f(), f(), f()); }");
ASSERT_EQUALS("[test.cpp:2]: (warning) %I64d in format string (no. 1) requires '__int64' but the argument type is 'signed int'.\n"
"[test.cpp:2]: (warning) %I64u in format string (no. 2) requires 'unsigned __int64' but the argument type is 'signed int'.\n"
"[test.cpp:2]: (warning) %I64x in format string (no. 3) requires 'unsigned __int64' but the argument type is 'signed int'.\n", errout_str());
check("long long f() { return 0; }\n"
"void foo() { printf(\"%I32d %I32u %I32x %lld\", f(), f(), f(), f()); }");
ASSERT_EQUALS("[test.cpp:2]: (warning) %I32d in format string (no. 1) requires '__int32' but the argument type is 'signed long long'.\n"
"[test.cpp:2]: (warning) %I32u in format string (no. 2) requires 'unsigned __int32' but the argument type is 'signed long long'.\n"
"[test.cpp:2]: (warning) %I32x in format string (no. 3) requires 'unsigned __int32' but the argument type is 'signed long long'.\n", errout_str());
check("unsigned long long f() { return 0; }\n"
"void foo() { printf(\"%I32d %I32u %I32x %llx\", f(), f(), f(), f()); }");
ASSERT_EQUALS("[test.cpp:2]: (warning) %I32d in format string (no. 1) requires '__int32' but the argument type is 'unsigned long long'.\n"
"[test.cpp:2]: (warning) %I32u in format string (no. 2) requires 'unsigned __int32' but the argument type is 'unsigned long long'.\n"
"[test.cpp:2]: (warning) %I32x in format string (no. 3) requires 'unsigned __int32' but the argument type is 'unsigned long long'.\n", errout_str());
check("signed char f() { return 0; }\n"
"void foo() { printf(\"%Id %Iu %Ix %hhi\", f(), f(), f(), f()); }");
ASSERT_EQUALS("[test.cpp:2]: (warning) %Id in format string (no. 1) requires 'ptrdiff_t' but the argument type is 'signed char'.\n"
"[test.cpp:2]: (warning) %Iu in format string (no. 2) requires 'size_t' but the argument type is 'signed char'.\n"
"[test.cpp:2]: (warning) %Ix in format string (no. 3) requires 'size_t' but the argument type is 'signed char'.\n", errout_str());
check("unsigned char f() { return 0; }\n"
"void foo() { printf(\"%Id %Iu %Ix %hho\", f(), f(), f(), f()); }");
ASSERT_EQUALS("[test.cpp:2]: (warning) %Id in format string (no. 1) requires 'ptrdiff_t' but the argument type is 'unsigned char'.\n"
"[test.cpp:2]: (warning) %Iu in format string (no. 2) requires 'size_t' but the argument type is 'unsigned char'.\n"
"[test.cpp:2]: (warning) %Ix in format string (no. 3) requires 'size_t' but the argument type is 'unsigned char'.\n", errout_str());
check("namespace bar { int f() { return 0; } }\n"
"void foo() { printf(\"%d %u %lu %f %Lf %p\", bar::f(), bar::f(), bar::f(), bar::f(), bar::f(), bar::f()); }");
ASSERT_EQUALS("[test.cpp:2]: (warning) %u in format string (no. 2) requires 'unsigned int' but the argument type is 'signed int'.\n"
"[test.cpp:2]: (warning) %lu in format string (no. 3) requires 'unsigned long' but the argument type is 'signed int'.\n"
"[test.cpp:2]: (warning) %f in format string (no. 4) requires 'double' but the argument type is 'signed int'.\n"
"[test.cpp:2]: (warning) %Lf in format string (no. 5) requires 'long double' but the argument type is 'signed int'.\n"
"[test.cpp:2]: (warning) %p in format string (no. 6) requires an address but the argument type is 'signed int'.\n", errout_str());
check("struct Fred { int i; } f;\n"
"void foo() { printf(\"%d %u %lu %f %Lf %p\", f.i, f.i, f.i, f.i, f.i, f.i); }");
ASSERT_EQUALS("[test.cpp:2]: (warning) %u in format string (no. 2) requires 'unsigned int' but the argument type is 'signed int'.\n"
"[test.cpp:2]: (warning) %lu in format string (no. 3) requires 'unsigned long' but the argument type is 'signed int'.\n"
"[test.cpp:2]: (warning) %f in format string (no. 4) requires 'double' but the argument type is 'signed int'.\n"
"[test.cpp:2]: (warning) %Lf in format string (no. 5) requires 'long double' but the argument type is 'signed int'.\n"
"[test.cpp:2]: (warning) %p in format string (no. 6) requires an address but the argument type is 'signed int'.\n", errout_str());
check("struct Fred { unsigned int u; } f;\n"
"void foo() { printf(\"%u %d %ld %f %Lf %p\", f.u, f.u, f.u, f.u, f.u, f.u); }");
ASSERT_EQUALS("[test.cpp:2]: (warning) %d in format string (no. 2) requires 'int' but the argument type is 'unsigned int'.\n"
"[test.cpp:2]: (warning) %ld in format string (no. 3) requires 'long' but the argument type is 'unsigned int'.\n"
"[test.cpp:2]: (warning) %f in format string (no. 4) requires 'double' but the argument type is 'unsigned int'.\n"
"[test.cpp:2]: (warning) %Lf in format string (no. 5) requires 'long double' but the argument type is 'unsigned int'.\n"
"[test.cpp:2]: (warning) %p in format string (no. 6) requires an address but the argument type is 'unsigned int'.\n", errout_str());
check("struct Fred { unsigned int ui() { return 0; } } f;\n"
"void foo() { printf(\"%u %d %ld %f %Lf %p\", f.ui(), f.ui(), f.ui(), f.ui(), f.ui(), f.ui()); }");
ASSERT_EQUALS("[test.cpp:2]: (warning) %d in format string (no. 2) requires 'int' but the argument type is 'unsigned int'.\n"
"[test.cpp:2]: (warning) %ld in format string (no. 3) requires 'long' but the argument type is 'unsigned int'.\n"
"[test.cpp:2]: (warning) %f in format string (no. 4) requires 'double' but the argument type is 'unsigned int'.\n"
"[test.cpp:2]: (warning) %Lf in format string (no. 5) requires 'long double' but the argument type is 'unsigned int'.\n"
"[test.cpp:2]: (warning) %p in format string (no. 6) requires an address but the argument type is 'unsigned int'.\n", errout_str());
// #4975
check("void f(int len, int newline) {\n"
" printf(\"%s\", newline ? a : str + len);\n"
" printf(\"%s\", newline + newline);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) %s in format string (no. 1) requires 'char *' but the argument type is 'signed int'.\n", errout_str());
check("struct Fred { int i; } f;\n"
"struct Fred & bar() { };\n"
"void foo() { printf(\"%d %u %lu %f %Lf %p\", bar().i, bar().i, bar().i, bar().i, bar().i, bar().i); }");
ASSERT_EQUALS("[test.cpp:3]: (warning) %u in format string (no. 2) requires 'unsigned int' but the argument type is 'signed int'.\n"
"[test.cpp:3]: (warning) %lu in format string (no. 3) requires 'unsigned long' but the argument type is 'signed int'.\n"
"[test.cpp:3]: (warning) %f in format string (no. 4) requires 'double' but the argument type is 'signed int'.\n"
"[test.cpp:3]: (warning) %Lf in format string (no. 5) requires 'long double' but the argument type is 'signed int'.\n"
"[test.cpp:3]: (warning) %p in format string (no. 6) requires an address but the argument type is 'signed int'.\n", errout_str());
check("struct Fred { int i; } f;\n"
"const struct Fred & bar() { };\n"
"void foo() { printf(\"%d %u %lu %f %Lf %p\", bar().i, bar().i, bar().i, bar().i, bar().i, bar().i); }");
ASSERT_EQUALS("[test.cpp:3]: (warning) %u in format string (no. 2) requires 'unsigned int' but the argument type is 'signed int'.\n"
"[test.cpp:3]: (warning) %lu in format string (no. 3) requires 'unsigned long' but the argument type is 'signed int'.\n"
"[test.cpp:3]: (warning) %f in format string (no. 4) requires 'double' but the argument type is 'signed int'.\n"
"[test.cpp:3]: (warning) %Lf in format string (no. 5) requires 'long double' but the argument type is 'signed int'.\n"
"[test.cpp:3]: (warning) %p in format string (no. 6) requires an address but the argument type is 'signed int'.\n", errout_str());
check("struct Fred { int i; } f;\n"
"static const struct Fred & bar() { };\n"
"void foo() { printf(\"%d %u %lu %f %Lf %p\", bar().i, bar().i, bar().i, bar().i, bar().i, bar().i); }");
ASSERT_EQUALS("[test.cpp:3]: (warning) %u in format string (no. 2) requires 'unsigned int' but the argument type is 'signed int'.\n"
"[test.cpp:3]: (warning) %lu in format string (no. 3) requires 'unsigned long' but the argument type is 'signed int'.\n"
"[test.cpp:3]: (warning) %f in format string (no. 4) requires 'double' but the argument type is 'signed int'.\n"
"[test.cpp:3]: (warning) %Lf in format string (no. 5) requires 'long double' but the argument type is 'signed int'.\n"
"[test.cpp:3]: (warning) %p in format string (no. 6) requires an address but the argument type is 'signed int'.\n", errout_str());
check("struct Fred { int i; } f[2];\n"
"struct Fred * bar() { return f; };\n"
"void foo() { printf(\"%d %u %lu %f %Lf %p\", bar()[0].i, bar()[0].i, bar()[0].i, bar()[0].i, bar()[0].i, bar()[0].i); }");
ASSERT_EQUALS("[test.cpp:3]: (warning) %u in format string (no. 2) requires 'unsigned int' but the argument type is 'signed int'.\n"
"[test.cpp:3]: (warning) %lu in format string (no. 3) requires 'unsigned long' but the argument type is 'signed int'.\n"
"[test.cpp:3]: (warning) %f in format string (no. 4) requires 'double' but the argument type is 'signed int'.\n"
"[test.cpp:3]: (warning) %Lf in format string (no. 5) requires 'long double' but the argument type is 'signed int'.\n"
"[test.cpp:3]: (warning) %p in format string (no. 6) requires an address but the argument type is 'signed int'.\n", errout_str());
check("struct Fred { int i; } f[2];\n"
"const struct Fred * bar() { return f; };\n"
"void foo() { printf(\"%d %u %lu %f %Lf %p\", bar()[0].i, bar()[0].i, bar()[0].i, bar()[0].i, bar()[0].i, bar()[0].i); }");
ASSERT_EQUALS("[test.cpp:3]: (warning) %u in format string (no. 2) requires 'unsigned int' but the argument type is 'signed int'.\n"
"[test.cpp:3]: (warning) %lu in format string (no. 3) requires 'unsigned long' but the argument type is 'signed int'.\n"
"[test.cpp:3]: (warning) %f in format string (no. 4) requires 'double' but the argument type is 'signed int'.\n"
"[test.cpp:3]: (warning) %Lf in format string (no. 5) requires 'long double' but the argument type is 'signed int'.\n"
"[test.cpp:3]: (warning) %p in format string (no. 6) requires an address but the argument type is 'signed int'.\n", errout_str());
check("struct Fred { int i; } f[2];\n"
"static const struct Fred * bar() { return f; };\n"
"void foo() { printf(\"%d %u %lu %f %Lf %p\", bar()[0].i, bar()[0].i, bar()[0].i, bar()[0].i, bar()[0].i, bar()[0].i); }");
ASSERT_EQUALS("[test.cpp:3]: (warning) %u in format string (no. 2) requires 'unsigned int' but the argument type is 'signed int'.\n"
"[test.cpp:3]: (warning) %lu in format string (no. 3) requires 'unsigned long' but the argument type is 'signed int'.\n"
"[test.cpp:3]: (warning) %f in format string (no. 4) requires 'double' but the argument type is 'signed int'.\n"
"[test.cpp:3]: (warning) %Lf in format string (no. 5) requires 'long double' but the argument type is 'signed int'.\n"
"[test.cpp:3]: (warning) %p in format string (no. 6) requires an address but the argument type is 'signed int'.\n", errout_str());
check("struct Fred { int32_t i; } f;\n"
"struct Fred & bar() { };\n"
"void foo() { printf(\"%d %ld %u %lu %f %Lf\", bar().i, bar().i, bar().i, bar().i, bar().i, bar().i); }");
ASSERT_EQUALS("[test.cpp:3]: (warning) %ld in format string (no. 2) requires 'long' but the argument type is 'signed int'.\n"
"[test.cpp:3]: (warning) %u in format string (no. 3) requires 'unsigned int' but the argument type is 'signed int'.\n"
"[test.cpp:3]: (warning) %lu in format string (no. 4) requires 'unsigned long' but the argument type is 'signed int'.\n"
"[test.cpp:3]: (warning) %f in format string (no. 5) requires 'double' but the argument type is 'signed int'.\n"
"[test.cpp:3]: (warning) %Lf in format string (no. 6) requires 'long double' but the argument type is 'signed int'.\n",
errout_str());
// #4984
check("void f(double *x) {\n"
" printf(\"%f\", x[0]);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int array[10];\n"
"int * foo() { return array; }\n"
"void f() {\n"
" printf(\"%f\", foo()[0]);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (warning) %f in format string (no. 1) requires 'double' but the argument type is 'signed int'.\n", errout_str());
check("struct Base { int length() { } };\n"
"struct Derived : public Base { };\n"
"void foo(Derived * d) {\n"
" printf(\"%f\", d.length());\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (warning) %f in format string (no. 1) requires 'double' but the argument type is 'signed int'.\n", errout_str());
check("std::vector<int> v;\n"
"void foo() {\n"
" printf(\"%d %u %f\", v[0], v[0], v[0]);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) %u in format string (no. 2) requires 'unsigned int' but the argument type is 'signed int'.\n"
"[test.cpp:3]: (warning) %f in format string (no. 3) requires 'double' but the argument type is 'signed int'.\n", errout_str());
// #4999 (crash)
check("int bar(int a);\n"
"void foo() {\n"
" printf(\"%d\", bar(0));\n"
"}");
ASSERT_EQUALS("", errout_str());
check("std::vector<int> v;\n"
"std::string s;\n"
"void foo() {\n"
" printf(\"%zu %Iu %d %f\", v.size(), v.size(), v.size(), v.size());\n"
" printf(\"%zu %Iu %d %f\", s.size(), s.size(), s.size(), s.size());\n"
"}\n", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("[test.cpp:4]: (portability) %d in format string (no. 3) requires 'int' but the argument type is 'std::size_t {aka unsigned long}'.\n"
"[test.cpp:4]: (portability) %f in format string (no. 4) requires 'double' but the argument type is 'std::size_t {aka unsigned long}'.\n"
"[test.cpp:5]: (portability) %d in format string (no. 3) requires 'int' but the argument type is 'std::size_t {aka unsigned long}'.\n"
"[test.cpp:5]: (portability) %f in format string (no. 4) requires 'double' but the argument type is 'std::size_t {aka unsigned long}'.\n", errout_str());
check("std::vector<int> v;\n"
"std::string s;\n"
"void foo() {\n"
" printf(\"%zu %Iu %d %f\", v.size(), v.size(), v.size(), v.size());\n"
" printf(\"%zu %Iu %d %f\", s.size(), s.size(), s.size(), s.size());\n"
"}\n", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Win64));
ASSERT_EQUALS("[test.cpp:4]: (portability) %d in format string (no. 3) requires 'int' but the argument type is 'std::size_t {aka unsigned long long}'.\n"
"[test.cpp:4]: (portability) %f in format string (no. 4) requires 'double' but the argument type is 'std::size_t {aka unsigned long long}'.\n"
"[test.cpp:5]: (portability) %d in format string (no. 3) requires 'int' but the argument type is 'std::size_t {aka unsigned long long}'.\n"
"[test.cpp:5]: (portability) %f in format string (no. 4) requires 'double' but the argument type is 'std::size_t {aka unsigned long long}'.\n", errout_str());
check("std::vector<int> v;\n"
"std::string s;\n"
"void foo() {\n"
" printf(\"%zu %Iu %d %f\", v.size(), v.size(), v.size(), v.size());\n"
" printf(\"%zu %Iu %d %f\", s.size(), s.size(), s.size(), s.size());\n"
"}\n", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Unix32));
ASSERT_EQUALS("[test.cpp:4]: (portability) %d in format string (no. 3) requires 'int' but the argument type is 'std::size_t {aka unsigned long}'.\n"
"[test.cpp:4]: (portability) %f in format string (no. 4) requires 'double' but the argument type is 'std::size_t {aka unsigned long}'.\n"
"[test.cpp:5]: (portability) %d in format string (no. 3) requires 'int' but the argument type is 'std::size_t {aka unsigned long}'.\n"
"[test.cpp:5]: (portability) %f in format string (no. 4) requires 'double' but the argument type is 'std::size_t {aka unsigned long}'.\n", errout_str());
check("std::vector<int> v;\n"
"std::string s;\n"
"void foo() {\n"
" printf(\"%zu %Iu %d %f\", v.size(), v.size(), v.size(), v.size());\n"
" printf(\"%zu %Iu %d %f\", s.size(), s.size(), s.size(), s.size());\n"
"}\n", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Unix64));
ASSERT_EQUALS("[test.cpp:4]: (portability) %d in format string (no. 3) requires 'int' but the argument type is 'std::size_t {aka unsigned long}'.\n"
"[test.cpp:4]: (portability) %f in format string (no. 4) requires 'double' but the argument type is 'std::size_t {aka unsigned long}'.\n"
"[test.cpp:5]: (portability) %d in format string (no. 3) requires 'int' but the argument type is 'std::size_t {aka unsigned long}'.\n"
"[test.cpp:5]: (portability) %f in format string (no. 4) requires 'double' but the argument type is 'std::size_t {aka unsigned long}'.\n", errout_str());
check("class Fred : public std::vector<int> {} v;\n"
"std::string s;\n"
"void foo() {\n"
" printf(\"%zu %Iu %d %f\", v.size(), v.size(), v.size(), v.size());\n"
" printf(\"%zu %Iu %d %f\", s.size(), s.size(), s.size(), s.size());\n"
"}\n", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Unix64));
ASSERT_EQUALS("[test.cpp:4]: (portability) %d in format string (no. 3) requires 'int' but the argument type is 'size_t {aka unsigned long}'.\n"
"[test.cpp:4]: (portability) %f in format string (no. 4) requires 'double' but the argument type is 'size_t {aka unsigned long}'.\n"
"[test.cpp:5]: (portability) %d in format string (no. 3) requires 'int' but the argument type is 'std::size_t {aka unsigned long}'.\n"
"[test.cpp:5]: (portability) %f in format string (no. 4) requires 'double' but the argument type is 'std::size_t {aka unsigned long}'.\n", errout_str());
check("class Fred : public std::vector<int> {} v;\n"
"void foo() {\n"
" printf(\"%d %u %f\", v[0], v[0], v[0]);\n"
"}\n", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Unix64));
ASSERT_EQUALS("[test.cpp:3]: (warning) %u in format string (no. 2) requires 'unsigned int' but the argument type is 'int'.\n"
"[test.cpp:3]: (warning) %f in format string (no. 3) requires 'double' but the argument type is 'int'.\n", errout_str());
check("std::string s;\n"
"void foo() {\n"
" printf(\"%s %p %u %d %f\", s.c_str(), s.c_str(), s.c_str(), s.c_str(), s.c_str());\n"
"}\n", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Unix64));
ASSERT_EQUALS("[test.cpp:3]: (warning) %u in format string (no. 3) requires 'unsigned int' but the argument type is 'const char *'.\n"
"[test.cpp:3]: (warning) %d in format string (no. 4) requires 'int' but the argument type is 'const char *'.\n"
"[test.cpp:3]: (warning) %f in format string (no. 5) requires 'double' but the argument type is 'const char *'.\n", errout_str());
check("std::vector<int> array;\n"
"char * p = 0;\n"
"char q[] = \"abc\";\n"
"char r[10] = { 0 };\n"
"size_t s;\n"
"void foo() {\n"
" printf(\"%zu %zu\", array.size(), s);\n"
" printf(\"%u %u %u\", p, q, r);\n"
" printf(\"%u %u\", array.size(), s);\n"
" printf(\"%lu %lu\", array.size(), s);\n"
" printf(\"%llu %llu\", array.size(), s);\n"
"}\n", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Unix64));
ASSERT_EQUALS("[test.cpp:8]: (warning) %u in format string (no. 1) requires 'unsigned int' but the argument type is 'char *'.\n"
"[test.cpp:8]: (warning) %u in format string (no. 2) requires 'unsigned int' but the argument type is 'char *'.\n"
"[test.cpp:8]: (warning) %u in format string (no. 3) requires 'unsigned int' but the argument type is 'char *'.\n"
"[test.cpp:9]: (portability) %u in format string (no. 1) requires 'unsigned int' but the argument type is 'std::size_t {aka unsigned long}'.\n"
"[test.cpp:9]: (portability) %u in format string (no. 2) requires 'unsigned int' but the argument type is 'size_t {aka unsigned long}'.\n"
"[test.cpp:10]: (portability) %lu in format string (no. 1) requires 'unsigned long' but the argument type is 'std::size_t {aka unsigned long}'.\n"
"[test.cpp:10]: (portability) %lu in format string (no. 2) requires 'unsigned long' but the argument type is 'size_t {aka unsigned long}'.\n"
"[test.cpp:11]: (portability) %llu in format string (no. 1) requires 'unsigned long long' but the argument type is 'std::size_t {aka unsigned long}'.\n"
"[test.cpp:11]: (portability) %llu in format string (no. 2) requires 'unsigned long long' but the argument type is 'size_t {aka unsigned long}'.\n", errout_str());
check("bool b; bool bf();\n"
"char c; char cf();\n"
"signed char sc; signed char scf();\n"
"unsigned char uc; unsigned char ucf();\n"
"short s; short sf();\n"
"unsigned short us; unsigned short usf();\n"
"size_t st; size_t stf();\n"
"ptrdiff_t pt; ptrdiff_t ptf();\n"
"char * pc; char * pcf();\n"
"char cl[] = \"123\";\n"
"char ca[3];\n"
"void foo() {\n"
" printf(\"%td %zd %d %d %d %d %d %d %d %d %d %d %d\", pt, pt, b, c, sc, uc, s, us, st, pt, pc, cl, ca);\n"
"}\n", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Unix64));
ASSERT_EQUALS("[test.cpp:13]: (portability) %zd in format string (no. 2) requires 'ssize_t' but the argument type is 'ptrdiff_t {aka signed long}'.\n"
"[test.cpp:13]: (portability) %d in format string (no. 9) requires 'int' but the argument type is 'size_t {aka unsigned long}'.\n"
"[test.cpp:13]: (portability) %d in format string (no. 10) requires 'int' but the argument type is 'ptrdiff_t {aka signed long}'.\n"
"[test.cpp:13]: (warning) %d in format string (no. 11) requires 'int' but the argument type is 'char *'.\n"
"[test.cpp:13]: (warning) %d in format string (no. 12) requires 'int' but the argument type is 'char *'.\n"
"[test.cpp:13]: (warning) %d in format string (no. 13) requires 'int' but the argument type is 'char *'.\n", errout_str());
check("bool b; bool bf();\n"
"char c; char cf();\n"
"signed char sc; signed char scf();\n"
"unsigned char uc; unsigned char ucf();\n"
"short s; short sf();\n"
"unsigned short us; unsigned short usf();\n"
"size_t st; size_t stf();\n"
"ptrdiff_t pt; ptrdiff_t ptf();\n"
"char * pc; char * pcf();\n"
"char cl[] = \"123\";\n"
"char ca[3];\n"
"void foo() {\n"
" printf(\"%ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld\", b, c, sc, uc, s, us, st, pt, pc, cl, ca);\n"
"}\n", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Unix64));
ASSERT_EQUALS("[test.cpp:13]: (warning) %ld in format string (no. 1) requires 'long' but the argument type is 'bool'.\n"
"[test.cpp:13]: (warning) %ld in format string (no. 2) requires 'long' but the argument type is 'char'.\n"
"[test.cpp:13]: (warning) %ld in format string (no. 3) requires 'long' but the argument type is 'signed char'.\n"
"[test.cpp:13]: (warning) %ld in format string (no. 4) requires 'long' but the argument type is 'unsigned char'.\n"
"[test.cpp:13]: (warning) %ld in format string (no. 5) requires 'long' but the argument type is 'signed short'.\n"
"[test.cpp:13]: (warning) %ld in format string (no. 6) requires 'long' but the argument type is 'unsigned short'.\n"
"[test.cpp:13]: (portability) %ld in format string (no. 7) requires 'long' but the argument type is 'size_t {aka unsigned long}'.\n"
"[test.cpp:13]: (portability) %ld in format string (no. 8) requires 'long' but the argument type is 'ptrdiff_t {aka signed long}'.\n"
"[test.cpp:13]: (warning) %ld in format string (no. 9) requires 'long' but the argument type is 'char *'.\n"
"[test.cpp:13]: (warning) %ld in format string (no. 10) requires 'long' but the argument type is 'char *'.\n"
"[test.cpp:13]: (warning) %ld in format string (no. 11) requires 'long' but the argument type is 'char *'.\n", errout_str());
check("bool b; bool bf();\n"
"char c; char cf();\n"
"signed char sc; signed char scf();\n"
"unsigned char uc; unsigned char ucf();\n"
"short s; short sf();\n"
"unsigned short us; unsigned short usf();\n"
"size_t st; size_t stf();\n"
"ptrdiff_t pt; ptrdiff_t ptf();\n"
"char * pc; char * pcf();\n"
"char cl[] = \"123\";\n"
"char ca[3];\n"
"void foo() {\n"
" printf(\"%td %zd %d %d %d %d %d %d %d %d %d\", ptf(), ptf(), bf(), cf(), scf(), ucf(), sf(), usf(), stf(), ptf(), pcf());\n"
"}\n", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Unix64));
ASSERT_EQUALS("[test.cpp:13]: (portability) %zd in format string (no. 2) requires 'ssize_t' but the argument type is 'ptrdiff_t {aka signed long}'.\n"
"[test.cpp:13]: (portability) %d in format string (no. 9) requires 'int' but the argument type is 'size_t {aka unsigned long}'.\n"
"[test.cpp:13]: (portability) %d in format string (no. 10) requires 'int' but the argument type is 'ptrdiff_t {aka signed long}'.\n"
"[test.cpp:13]: (warning) %d in format string (no. 11) requires 'int' but the argument type is 'char *'.\n", errout_str());
check("bool b; bool bf();\n"
"char c; char cf();\n"
"signed char sc; signed char scf();\n"
"unsigned char uc; unsigned char ucf();\n"
"short s; short sf();\n"
"unsigned short us; unsigned short usf();\n"
"size_t st; size_t stf();\n"
"ptrdiff_t pt; ptrdiff_t ptf();\n"
"char * pc; char * pcf();\n"
"char cl[] = \"123\";\n"
"char ca[3];\n"
"void foo() {\n"
" printf(\"%ld %ld %ld %ld %ld %ld %ld %ld %ld\", bf(), cf(), scf(), ucf(), sf(), usf(), stf(), ptf(), pcf());\n"
"}\n", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Unix64));
ASSERT_EQUALS("[test.cpp:13]: (warning) %ld in format string (no. 1) requires 'long' but the argument type is 'bool'.\n"
"[test.cpp:13]: (warning) %ld in format string (no. 2) requires 'long' but the argument type is 'char'.\n"
"[test.cpp:13]: (warning) %ld in format string (no. 3) requires 'long' but the argument type is 'signed char'.\n"
"[test.cpp:13]: (warning) %ld in format string (no. 4) requires 'long' but the argument type is 'unsigned char'.\n"
"[test.cpp:13]: (warning) %ld in format string (no. 5) requires 'long' but the argument type is 'signed short'.\n"
"[test.cpp:13]: (warning) %ld in format string (no. 6) requires 'long' but the argument type is 'unsigned short'.\n"
"[test.cpp:13]: (portability) %ld in format string (no. 7) requires 'long' but the argument type is 'size_t {aka unsigned long}'.\n"
"[test.cpp:13]: (portability) %ld in format string (no. 8) requires 'long' but the argument type is 'ptrdiff_t {aka signed long}'.\n"
"[test.cpp:13]: (warning) %ld in format string (no. 9) requires 'long' but the argument type is 'char *'.\n", errout_str());
check("struct A {};\n"
"class B : public std::vector<const int *> {} b;\n"
"class C : public std::vector<const struct A *> {} c;\n"
"std::string s;\n"
"void foo() {\n"
" printf(\"%zu %u\", b.size(), b.size());\n"
" printf(\"%p %d\", b[0], b[0]);\n"
" printf(\"%p %d\", c[0], c[0]);\n"
" printf(\"%p %d\", s.c_str(), s.c_str());\n"
"}\n", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Unix64));
ASSERT_EQUALS("[test.cpp:6]: (portability) %u in format string (no. 2) requires 'unsigned int' but the argument type is 'size_t {aka unsigned long}'.\n"
"[test.cpp:7]: (warning) %d in format string (no. 2) requires 'int' but the argument type is 'const int *'.\n"
"[test.cpp:8]: (warning) %d in format string (no. 2) requires 'int' but the argument type is 'const struct A *'.\n"
"[test.cpp:9]: (warning) %d in format string (no. 2) requires 'int' but the argument type is 'const char *'.\n", errout_str());
check("class A : public std::vector<std::string> {} a;\n"
"class B : public std::string {} b;\n"
"std::string s;\n"
"void foo() {\n"
" printf(\"%p %d\", a[0].c_str(), a[0].c_str());\n"
" printf(\"%c %p\", b[0], b[0]);\n"
" printf(\"%c %p\", s[0], s[0]);\n"
"}\n", dinit(CheckOptions, $.platform = Platform::Type::Unix64));
ASSERT_EQUALS("[test.cpp:5]: (warning) %d in format string (no. 2) requires 'int' but the argument type is 'const char *'.\n"
"[test.cpp:6]: (warning) %p in format string (no. 2) requires an address but the argument type is 'char'.\n"
"[test.cpp:7]: (warning) %p in format string (no. 2) requires an address but the argument type is 'char'.\n", errout_str());
check("template <class T>\n"
"struct buffer {\n"
" size_t size();\n"
"};\n"
"buffer<int> b;\n"
"void foo() {\n"
" printf(\"%u\", b.size());\n"
"}\n", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Unix64));
ASSERT_EQUALS("[test.cpp:7]: (portability) %u in format string (no. 1) requires 'unsigned int' but the argument type is 'size_t {aka unsigned long}'.\n", errout_str());
check("DWORD a;\n"
"DWORD_PTR b;\n"
"void foo() {\n"
" printf(\"%u %u\", a, b);\n"
"}\n", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("[test.cpp:4]: (portability) %u in format string (no. 1) requires 'unsigned int' but the argument type is 'DWORD {aka unsigned long}'.\n"
"[test.cpp:4]: (portability) %u in format string (no. 2) requires 'unsigned int' but the argument type is 'DWORD_PTR {aka unsigned long}'.\n", errout_str());
check("unsigned long a[] = { 1, 2 };\n"
"void foo() {\n"
" printf(\"%d %d %x \", a[0], a[0], a[0]);\n"
"}\n", dinit(CheckOptions, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("[test.cpp:3]: (warning) %d in format string (no. 1) requires 'int' but the argument type is 'unsigned long'.\n"
"[test.cpp:3]: (warning) %d in format string (no. 2) requires 'int' but the argument type is 'unsigned long'.\n"
"[test.cpp:3]: (warning) %x in format string (no. 3) requires 'unsigned int' but the argument type is 'unsigned long'.\n", errout_str());
check("void foo (wchar_t c) {\n" // ticket #5051 false positive
" printf(\"%c\", c);\n"
"}\n", dinit(CheckOptions, $.platform = Platform::Type::Win64));
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" printf(\"%f %d\", static_cast<int>(1.0f), reinterpret_cast<const void *>(0));\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) %f in format string (no. 1) requires 'double' but the argument type is 'signed int'.\n"
"[test.cpp:2]: (warning) %d in format string (no. 2) requires 'int' but the argument type is 'const void *'.\n", errout_str());
check("void foo() {\n"
" UNKNOWN * u;\n"
" printf(\"%d %x %u %f\", u[i], u[i], u[i], u[i]);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" long * l;\n"
" printf(\"%d %x %u %f\", l[i], l[i], l[i], l[i]);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) %d in format string (no. 1) requires 'int' but the argument type is 'signed long'.\n"
"[test.cpp:3]: (warning) %x in format string (no. 2) requires 'unsigned int' but the argument type is 'signed long'.\n"
"[test.cpp:3]: (warning) %u in format string (no. 3) requires 'unsigned int' but the argument type is 'signed long'.\n"
"[test.cpp:3]: (warning) %f in format string (no. 4) requires 'double' but the argument type is 'signed long'.\n", errout_str());
check("void f() {\n" // #5104
" myvector<unsigned short> v1(1,0);\n"
" printf(\"%d\",v1[0]);\n"
" myvector<int> v2(1,0);\n"
" printf(\"%d\",v2[0]);\n"
" myvector<unsigned int> v3(1,0);\n"
" printf(\"%u\",v3[0]);\n"
" myvector<unsigned int> v4(1,0);\n"
" printf(\"%x\",v4[0]);\n"
" myvector<double> v5(1,0);\n"
" printf(\"%f\",v5[0]);\n"
" myvector<bool> v6(1,0);\n"
" printf(\"%u\",v6[0]);\n"
" myvector<char *> v7(1,0);\n"
" printf(\"%s\",v7[0]);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("std::vector<char> v;\n" // #5151
"void foo() {\n"
" printf(\"%c %u %f\", v.at(32), v.at(32), v.at(32));\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) %u in format string (no. 2) requires 'unsigned int' but the argument type is 'char'.\n"
"[test.cpp:3]: (warning) %f in format string (no. 3) requires 'double' but the argument type is 'char'.\n", errout_str());
// #5195 (segmentation fault)
check("void T::a(const std::vector<double>& vx) {\n"
" printf(\"%f\", vx.at(0));\n"
"}");
ASSERT_EQUALS("", errout_str());
// #5486
check("void foo() {\n"
" ssize_t test = 0;\n"
" printf(\"%zd\", test);\n"
"}");
ASSERT_EQUALS("", errout_str());
// #6009
check("extern std::string StringByReturnValue();\n"
"extern int IntByReturnValue();\n"
"void MyFunction() {\n"
" printf( \"%s - %s\", StringByReturnValue(), IntByReturnValue() );\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (warning) %s in format string (no. 1) requires 'char *' but the argument type is 'std::string'.\n"
"[test.cpp:4]: (warning) %s in format string (no. 2) requires 'char *' but the argument type is 'signed int'.\n", errout_str());
check("template <class T, size_t S>\n"
"struct Array {\n"
" T data[S];\n"
" T & operator [] (size_t i) { return data[i]; }\n"
"};\n"
"void foo() {\n"
" Array<int, 10> array1;\n"
" Array<float, 10> array2;\n"
" printf(\"%u %u\", array1[0], array2[0]);\n"
"}");
ASSERT_EQUALS("[test.cpp:9]: (warning) %u in format string (no. 1) requires 'unsigned int' but the argument type is 'int'.\n"
"[test.cpp:9]: (warning) %u in format string (no. 2) requires 'unsigned int' but the argument type is 'float'.\n", errout_str());
// Ticket #7445
check("struct S { unsigned short x; } s = {0};\n"
"void foo() {\n"
" printf(\"%d\", s.x);\n"
"}");
ASSERT_EQUALS("", errout_str());
// Ticket #7601
check("void foo(int i, unsigned int ui, long long ll, unsigned long long ull) {\n"
" printf(\"%Ld %Lu %Ld %Lu\", i, ui, ll, ull);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) %Ld in format string (no. 1) requires 'long long' but the argument type is 'signed int'.\n"
"[test.cpp:2]: (warning) %Lu in format string (no. 2) requires 'unsigned long long' but the argument type is 'unsigned int'.\n", errout_str());
check("void foo(char c, unsigned char uc, short s, unsigned short us, int i, unsigned int ui, long l, unsigned long ul) {\n"
" printf(\"%hhd %hhd %hhd %hhd %hhd %hhd %hhd %hhd\", c, uc, s, us, i, ui, l, ul);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) %hhd in format string (no. 2) requires 'char' but the argument type is 'unsigned char'.\n"
"[test.cpp:2]: (warning) %hhd in format string (no. 3) requires 'char' but the argument type is 'signed short'.\n"
"[test.cpp:2]: (warning) %hhd in format string (no. 4) requires 'char' but the argument type is 'unsigned short'.\n"
"[test.cpp:2]: (warning) %hhd in format string (no. 5) requires 'char' but the argument type is 'signed int'.\n"
"[test.cpp:2]: (warning) %hhd in format string (no. 6) requires 'char' but the argument type is 'unsigned int'.\n"
"[test.cpp:2]: (warning) %hhd in format string (no. 7) requires 'char' but the argument type is 'signed long'.\n"
"[test.cpp:2]: (warning) %hhd in format string (no. 8) requires 'char' but the argument type is 'unsigned long'.\n", errout_str());
check("void foo(char c, unsigned char uc, short s, unsigned short us, int i, unsigned int ui, long l, unsigned long ul) {\n"
" printf(\"%hhu %hhu %hhu %hhu %hhu %hhu %hhu %hhu\", c, uc, s, us, i, ui, l, ul);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) %hhu in format string (no. 1) requires 'unsigned char' but the argument type is 'char'.\n"
"[test.cpp:2]: (warning) %hhu in format string (no. 3) requires 'unsigned char' but the argument type is 'signed short'.\n"
"[test.cpp:2]: (warning) %hhu in format string (no. 4) requires 'unsigned char' but the argument type is 'unsigned short'.\n"
"[test.cpp:2]: (warning) %hhu in format string (no. 5) requires 'unsigned char' but the argument type is 'signed int'.\n"
"[test.cpp:2]: (warning) %hhu in format string (no. 6) requires 'unsigned char' but the argument type is 'unsigned int'.\n"
"[test.cpp:2]: (warning) %hhu in format string (no. 7) requires 'unsigned char' but the argument type is 'signed long'.\n"
"[test.cpp:2]: (warning) %hhu in format string (no. 8) requires 'unsigned char' but the argument type is 'unsigned long'.\n", errout_str());
check("void foo(char c, unsigned char uc, short s, unsigned short us, int i, unsigned int ui, long l, unsigned long ul) {\n"
" printf(\"%hhx %hhx %hhx %hhx %hhx %hhx %hhx %hhx\", c, uc, s, us, i, ui, l, ul);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) %hhx in format string (no. 1) requires 'unsigned char' but the argument type is 'char'.\n"
"[test.cpp:2]: (warning) %hhx in format string (no. 3) requires 'unsigned char' but the argument type is 'signed short'.\n"
"[test.cpp:2]: (warning) %hhx in format string (no. 4) requires 'unsigned char' but the argument type is 'unsigned short'.\n"
"[test.cpp:2]: (warning) %hhx in format string (no. 5) requires 'unsigned char' but the argument type is 'signed int'.\n"
"[test.cpp:2]: (warning) %hhx in format string (no. 6) requires 'unsigned char' but the argument type is 'unsigned int'.\n"
"[test.cpp:2]: (warning) %hhx in format string (no. 7) requires 'unsigned char' but the argument type is 'signed long'.\n"
"[test.cpp:2]: (warning) %hhx in format string (no. 8) requires 'unsigned char' but the argument type is 'unsigned long'.\n", errout_str());
check("void foo(char c, unsigned char uc, short s, unsigned short us, int i, unsigned int ui, long l, unsigned long ul) {\n"
" printf(\"%hd %hd %hd %hd %hd %hd %hd %hd\", c, uc, s, us, i, ui, l, ul);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) %hd in format string (no. 1) requires 'short' but the argument type is 'char'.\n"
"[test.cpp:2]: (warning) %hd in format string (no. 2) requires 'short' but the argument type is 'unsigned char'.\n"
"[test.cpp:2]: (warning) %hd in format string (no. 4) requires 'short' but the argument type is 'unsigned short'.\n"
"[test.cpp:2]: (warning) %hd in format string (no. 5) requires 'short' but the argument type is 'signed int'.\n"
"[test.cpp:2]: (warning) %hd in format string (no. 6) requires 'short' but the argument type is 'unsigned int'.\n"
"[test.cpp:2]: (warning) %hd in format string (no. 7) requires 'short' but the argument type is 'signed long'.\n"
"[test.cpp:2]: (warning) %hd in format string (no. 8) requires 'short' but the argument type is 'unsigned long'.\n", errout_str());
check("void foo(char c, unsigned char uc, short s, unsigned short us, int i, unsigned int ui, long l, unsigned long ul) {\n"
" printf(\"%hu %hu %hu %hu %hu %hu %hu %hu\", c, uc, s, us, i, ui, l, ul);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) %hu in format string (no. 1) requires 'unsigned short' but the argument type is 'char'.\n"
"[test.cpp:2]: (warning) %hu in format string (no. 2) requires 'unsigned short' but the argument type is 'unsigned char'.\n"
"[test.cpp:2]: (warning) %hu in format string (no. 3) requires 'unsigned short' but the argument type is 'signed short'.\n"
"[test.cpp:2]: (warning) %hu in format string (no. 5) requires 'unsigned short' but the argument type is 'signed int'.\n"
"[test.cpp:2]: (warning) %hu in format string (no. 6) requires 'unsigned short' but the argument type is 'unsigned int'.\n"
"[test.cpp:2]: (warning) %hu in format string (no. 7) requires 'unsigned short' but the argument type is 'signed long'.\n"
"[test.cpp:2]: (warning) %hu in format string (no. 8) requires 'unsigned short' but the argument type is 'unsigned long'.\n", errout_str());
check("void foo(char c, unsigned char uc, short s, unsigned short us, int i, unsigned int ui, long l, unsigned long ul) {\n"
" printf(\"%hx %hx %hx %hx %hx %hx %hx %hx\", c, uc, s, us, i, ui, l, ul);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) %hx in format string (no. 1) requires 'unsigned short' but the argument type is 'char'.\n"
"[test.cpp:2]: (warning) %hx in format string (no. 2) requires 'unsigned short' but the argument type is 'unsigned char'.\n"
"[test.cpp:2]: (warning) %hx in format string (no. 3) requires 'unsigned short' but the argument type is 'signed short'.\n"
"[test.cpp:2]: (warning) %hx in format string (no. 5) requires 'unsigned short' but the argument type is 'signed int'.\n"
"[test.cpp:2]: (warning) %hx in format string (no. 6) requires 'unsigned short' but the argument type is 'unsigned int'.\n"
"[test.cpp:2]: (warning) %hx in format string (no. 7) requires 'unsigned short' but the argument type is 'signed long'.\n"
"[test.cpp:2]: (warning) %hx in format string (no. 8) requires 'unsigned short' but the argument type is 'unsigned long'.\n", errout_str());
// #7837 - Use ValueType for function call
check("struct S {\n"
" double (* f)(double);\n"
"};\n"
"\n"
"void foo(struct S x) {\n"
" printf(\"%f\", x.f(4.0));\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" printf(\"%lu\", sizeof(char));\n"
"}\n", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Win64));
ASSERT_EQUALS("[test.cpp:2]: (portability) %lu in format string (no. 1) requires 'unsigned long' but the argument type is 'size_t {aka unsigned long long}'.\n",
errout_str());
}
void testPrintfArgumentVariables() {
TEST_PRINTF_NOWARN("%u", "unsigned int", "bool");
TEST_PRINTF_WARN("%u", "unsigned int", "char");
TEST_PRINTF_WARN("%u", "unsigned int", "signed char");
TEST_PRINTF_NOWARN("%u", "unsigned int", "unsigned char");
TEST_PRINTF_WARN("%u", "unsigned int", "signed short");
TEST_PRINTF_NOWARN("%u", "unsigned int", "unsigned short");
TEST_PRINTF_WARN("%u", "unsigned int", "signed int");
TEST_PRINTF_NOWARN("%u", "unsigned int", "unsigned int");
TEST_PRINTF_WARN("%u", "unsigned int", "signed long");
TEST_PRINTF_WARN("%u", "unsigned int", "unsigned long");
TEST_PRINTF_WARN("%u", "unsigned int", "signed long long");
TEST_PRINTF_WARN("%u", "unsigned int", "unsigned long long");
TEST_PRINTF_WARN("%u", "unsigned int", "float");
TEST_PRINTF_WARN("%u", "unsigned int", "double");
TEST_PRINTF_WARN("%u", "unsigned int", "long double");
TEST_PRINTF_WARN("%u", "unsigned int", "void *");
TEST_PRINTF_WARN_AKA("%u", "unsigned int", "size_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%u", "unsigned int", "ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%u", "unsigned int", "ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%u", "unsigned int", "unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%u", "unsigned int", "intmax_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%u", "unsigned int", "uintmax_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%u", "unsigned int", "intptr_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%u", "unsigned int", "uintptr_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP("%u", "unsigned int", "std::size_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP("%u", "unsigned int", "std::ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%u", "unsigned int", "std::ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%u", "unsigned int", "std::intmax_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%u", "unsigned int", "std::uintmax_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP("%u", "unsigned int", "std::intptr_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%u", "unsigned int", "std::uintptr_t", "unsigned long", "unsigned long long");
TEST_PRINTF_NOWARN("%x", "unsigned int", "bool");
//TODO TEST_PRINTF_WARN("%x", "unsigned int", "char");
//TODO TEST_PRINTF_WARN("%x", "unsigned int", "signed char");
TEST_PRINTF_NOWARN("%x", "unsigned int", "unsigned char");
//TODO TEST_PRINTF_WARN("%x", "unsigned int", "signed short");
TEST_PRINTF_NOWARN("%x", "unsigned int", "unsigned short");
//TODO TEST_PRINTF_WARN("%x", "unsigned int", "signed int");
TEST_PRINTF_NOWARN("%x", "unsigned int", "unsigned int");
TEST_PRINTF_WARN("%x", "unsigned int", "signed long");
TEST_PRINTF_WARN("%x", "unsigned int", "unsigned long");
TEST_PRINTF_WARN("%x", "unsigned int", "signed long long");
TEST_PRINTF_WARN("%x", "unsigned int", "unsigned long long");
TEST_PRINTF_WARN("%x", "unsigned int", "float");
TEST_PRINTF_WARN("%x", "unsigned int", "double");
TEST_PRINTF_WARN("%x", "unsigned int", "long double");
TEST_PRINTF_WARN("%x", "unsigned int", "void *");
TEST_PRINTF_WARN_AKA("%x", "unsigned int", "size_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%x", "unsigned int", "ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%x", "unsigned int", "ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%x", "unsigned int", "unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%x", "unsigned int", "intmax_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%x", "unsigned int", "uintmax_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%x", "unsigned int", "intptr_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%x", "unsigned int", "uintptr_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP("%x", "unsigned int", "std::size_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP("%x", "unsigned int", "std::ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%x", "unsigned int", "std::ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%x", "unsigned int", "std::intmax_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%x", "unsigned int", "std::uintmax_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP("%x", "unsigned int", "std::intptr_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%x", "unsigned int", "std::uintptr_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN("%lu","unsigned long","bool");
TEST_PRINTF_WARN("%lu","unsigned long","char");
TEST_PRINTF_WARN("%lu","unsigned long","signed char");
TEST_PRINTF_WARN("%lu","unsigned long","unsigned char");
TEST_PRINTF_WARN("%lu","unsigned long","signed short");
TEST_PRINTF_WARN("%lu","unsigned long","unsigned short");
TEST_PRINTF_WARN("%lu","unsigned long","signed int");
TEST_PRINTF_WARN("%lu","unsigned long","unsigned int");
TEST_PRINTF_WARN("%lu","unsigned long","signed long");
TEST_PRINTF_NOWARN("%lu","unsigned long","unsigned long");
TEST_PRINTF_WARN("%lu","unsigned long","signed long long");
TEST_PRINTF_WARN("%lu","unsigned long","unsigned long long");
TEST_PRINTF_WARN("%lu","unsigned long","float");
TEST_PRINTF_WARN("%lu","unsigned long","double");
TEST_PRINTF_WARN("%lu","unsigned long","long double");
TEST_PRINTF_WARN("%lu","unsigned long","void *");
TEST_PRINTF_WARN_AKA("%lu","unsigned long","size_t","unsigned long","unsigned long long");
TEST_PRINTF_WARN_AKA("%lu","unsigned long","ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%lu","unsigned long","ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_WIN64("%lu","unsigned long","unsigned ptrdiff_t", "unsigned long long");
TEST_PRINTF_WARN_AKA("%lu","unsigned long","intmax_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%lu","unsigned long","uintmax_t","unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%lu","unsigned long","intptr_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_WIN64("%lu","unsigned long","uintptr_t", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP("%lu","unsigned long","std::size_t","unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP("%lu","unsigned long","std::ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%lu","unsigned long","std::ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%lu","unsigned long","std::intmax_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP_WIN64("%lu","unsigned long","std::uintmax_t", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP("%lu","unsigned long","std::intptr_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP_WIN64("%lu","unsigned long","std::uintptr_t", "unsigned long long");
TEST_PRINTF_WARN("%lx","unsigned long","bool");
TEST_PRINTF_WARN("%lx","unsigned long","char");
TEST_PRINTF_WARN("%lx","unsigned long","signed char");
TEST_PRINTF_WARN("%lx","unsigned long","unsigned char");
TEST_PRINTF_WARN("%lx","unsigned long","signed short");
TEST_PRINTF_WARN("%lx","unsigned long","unsigned short");
TEST_PRINTF_WARN("%lx","unsigned long","signed int");
TEST_PRINTF_WARN("%lx","unsigned long","unsigned int");
//TODO TEST_PRINTF_WARN("%lx","unsigned long","signed long");
TEST_PRINTF_NOWARN("%lx","unsigned long","unsigned long");
TEST_PRINTF_WARN("%lx","unsigned long","signed long long");
TEST_PRINTF_WARN("%lx","unsigned long","unsigned long long");
TEST_PRINTF_WARN("%lx","unsigned long","float");
TEST_PRINTF_WARN("%lx","unsigned long","double");
TEST_PRINTF_WARN("%lx","unsigned long","long double");
TEST_PRINTF_WARN("%lx","unsigned long","void *");
TEST_PRINTF_WARN_AKA("%lx","unsigned long","size_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_WIN64("%lx","unsigned long","ssize_t", "signed long long");
TEST_PRINTF_WARN_AKA_WIN64("%lx","unsigned long","ptrdiff_t", "signed long long");
TEST_PRINTF_WARN_AKA_WIN64("%lx","unsigned long","unsigned ptrdiff_t", "unsigned long long");
TEST_PRINTF_WARN_AKA_WIN64("%lx","unsigned long","intmax_t", "signed long long");
TEST_PRINTF_WARN_AKA("%lx","unsigned long","uintmax_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_WIN64("%lx","unsigned long","intptr_t", "signed long long");
TEST_PRINTF_WARN_AKA_WIN64("%lx","unsigned long","uintptr_t", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP("%lx","unsigned long","std::size_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP_WIN64("%lx","unsigned long","std::ssize_t", "signed long long");
TEST_PRINTF_WARN_AKA_CPP_WIN64("%lx","unsigned long","std::ptrdiff_t", "signed long long");
TEST_PRINTF_WARN_AKA_CPP_WIN64("%lx","unsigned long","std::intmax_t", "signed long long");
TEST_PRINTF_WARN_AKA_CPP_WIN64("%lx","unsigned long","std::uintmax_t", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP_WIN64("%lx","unsigned long","std::intptr_t", "signed long long");
TEST_PRINTF_WARN_AKA_CPP_WIN64("%lx","unsigned long","std::uintptr_t", "unsigned long long");
TEST_PRINTF_WARN("%llu","unsigned long long","bool");
TEST_PRINTF_WARN("%llu","unsigned long long","char");
TEST_PRINTF_WARN("%llu","unsigned long long","signed char");
TEST_PRINTF_WARN("%llu","unsigned long long","unsigned char");
TEST_PRINTF_WARN("%llu","unsigned long long","signed short");
TEST_PRINTF_WARN("%llu","unsigned long long","unsigned short");
TEST_PRINTF_WARN("%llu","unsigned long long","signed int");
TEST_PRINTF_WARN("%llu","unsigned long long","unsigned int");
TEST_PRINTF_WARN("%llu","unsigned long long","signed long");
TEST_PRINTF_WARN("%llu","unsigned long long","unsigned long");
TEST_PRINTF_WARN("%llu","unsigned long long","signed long long");
TEST_PRINTF_NOWARN("%llu","unsigned long long","unsigned long long");
TEST_PRINTF_WARN("%llu","unsigned long long","float");
TEST_PRINTF_WARN("%llu","unsigned long long","double");
TEST_PRINTF_WARN("%llu","unsigned long long","long double");
TEST_PRINTF_WARN("%llu","unsigned long long","void *");
TEST_PRINTF_WARN_AKA("%llu","unsigned long long","size_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%llu","unsigned long long","ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%llu","unsigned long long","ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_WIN32("%llu","unsigned long long","unsigned ptrdiff_t", "unsigned long");
TEST_PRINTF_WARN_AKA("%llu","unsigned long long","intmax_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%llu","unsigned long long","uintmax_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%llu","unsigned long long","intptr_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_WIN32("%llu","unsigned long long","uintptr_t", "unsigned long");
TEST_PRINTF_WARN_AKA_CPP("%llu","unsigned long long","std::size_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP("%llu","unsigned long long","std::ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%llu","unsigned long long","std::ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%llu","unsigned long long","std::intmax_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP_WIN32("%llu","unsigned long long","std::uintmax_t", "unsigned long");
TEST_PRINTF_WARN_AKA_CPP("%llu","unsigned long long","std::intptr_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP_WIN32("%llu","unsigned long long","std::uintptr_t", "unsigned long");
TEST_PRINTF_WARN("%llx","unsigned long long","bool");
TEST_PRINTF_WARN("%llx","unsigned long long","char");
TEST_PRINTF_WARN("%llx","unsigned long long","signed char");
TEST_PRINTF_WARN("%llx","unsigned long long","unsigned char");
TEST_PRINTF_WARN("%llx","unsigned long long","signed short");
TEST_PRINTF_WARN("%llx","unsigned long long","unsigned short");
TEST_PRINTF_WARN("%llx","unsigned long long","signed int");
TEST_PRINTF_WARN("%llx","unsigned long long","unsigned int");
TEST_PRINTF_WARN("%llx","unsigned long long","signed long");
TEST_PRINTF_WARN("%llx","unsigned long long","unsigned long");
//TODO TEST_PRINTF_WARN("%llx","unsigned long long","signed long long");
TEST_PRINTF_NOWARN("%llx","unsigned long long","unsigned long long");
TEST_PRINTF_WARN("%llx","unsigned long long","float");
TEST_PRINTF_WARN("%llx","unsigned long long","double");
TEST_PRINTF_WARN("%llx","unsigned long long","long double");
TEST_PRINTF_WARN("%llx","unsigned long long","void *");
TEST_PRINTF_WARN_AKA("%llx","unsigned long long","size_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_WIN32("%llx","unsigned long long","ssize_t", "signed long");
TEST_PRINTF_WARN_AKA_WIN32("%llx","unsigned long long","ptrdiff_t", "signed long");
TEST_PRINTF_WARN_AKA_WIN32("%llx","unsigned long long","unsigned ptrdiff_t", "unsigned long");
TEST_PRINTF_WARN_AKA_WIN32("%llx","unsigned long long","intmax_t", "signed long");
TEST_PRINTF_WARN_AKA("%llx","unsigned long long","uintmax_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_WIN32("%llx","unsigned long long","intptr_t", "signed long");
TEST_PRINTF_WARN_AKA_WIN32("%llx","unsigned long long","uintptr_t", "unsigned long");
TEST_PRINTF_WARN_AKA_CPP("%llx","unsigned long long","std::size_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP_WIN32("%llx","unsigned long long","std::ssize_t", "signed long");
TEST_PRINTF_WARN_AKA_CPP_WIN32("%llx","unsigned long long","std::ptrdiff_t", "signed long");
TEST_PRINTF_WARN_AKA_CPP_WIN32("%llx","unsigned long long","std::intmax_t", "signed long");
TEST_PRINTF_WARN_AKA_CPP_WIN32("%llx","unsigned long long","std::uintmax_t", "unsigned long");
TEST_PRINTF_WARN_AKA_CPP_WIN32("%llx","unsigned long long","std::intptr_t", "signed long");
TEST_PRINTF_WARN_AKA_CPP_WIN32("%llx","unsigned long long","std::uintptr_t", "unsigned long");
TEST_PRINTF_WARN("%hu", "unsigned short", "bool");
TEST_PRINTF_WARN("%hu", "unsigned short", "char");
TEST_PRINTF_WARN("%hu", "unsigned short", "signed char");
TEST_PRINTF_WARN("%hu", "unsigned short", "unsigned char");
TEST_PRINTF_WARN("%hu", "unsigned short", "signed short");
TEST_PRINTF_NOWARN("%hu", "unsigned short", "unsigned short");
TEST_PRINTF_WARN("%hu", "unsigned short", "signed int");
TEST_PRINTF_WARN("%hu", "unsigned short", "unsigned int");
TEST_PRINTF_WARN("%hu", "unsigned short", "signed long");
TEST_PRINTF_WARN("%hu", "unsigned short", "unsigned long");
TEST_PRINTF_WARN("%hu", "unsigned short", "signed long long");
TEST_PRINTF_WARN("%hu", "unsigned short", "unsigned long long");
TEST_PRINTF_WARN("%hu", "unsigned short", "float");
TEST_PRINTF_WARN("%hu", "unsigned short", "double");
TEST_PRINTF_WARN("%hu", "unsigned short", "long double");
TEST_PRINTF_WARN("%hu", "unsigned short", "void *");
TEST_PRINTF_WARN_AKA("%hu", "unsigned short", "size_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%hu", "unsigned short", "ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%hu", "unsigned short", "ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%hu", "unsigned short", "unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%hu", "unsigned short", "intmax_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%hu", "unsigned short", "uintmax_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP("%hu", "unsigned short", "std::size_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP("%hu", "unsigned short", "std::ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%hu", "unsigned short", "std::ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%hu", "unsigned short", "std::intptr_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%hu", "unsigned short", "std::uintptr_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN("%hx", "unsigned short", "bool");
TEST_PRINTF_WARN("%hx", "unsigned short", "char");
TEST_PRINTF_WARN("%hx", "unsigned short", "signed char");
TEST_PRINTF_WARN("%hx", "unsigned short", "unsigned char");
TEST_PRINTF_WARN("%hx", "unsigned short", "signed short");
TEST_PRINTF_NOWARN("%hx", "unsigned short", "unsigned short");
TEST_PRINTF_WARN("%hx", "unsigned short", "signed int");
TEST_PRINTF_WARN("%hx", "unsigned short", "unsigned int");
TEST_PRINTF_WARN("%hx", "unsigned short", "signed long");
TEST_PRINTF_WARN("%hx", "unsigned short", "unsigned long");
TEST_PRINTF_WARN("%hx", "unsigned short", "signed long long");
TEST_PRINTF_WARN("%hx", "unsigned short", "unsigned long long");
TEST_PRINTF_WARN("%hx", "unsigned short", "float");
TEST_PRINTF_WARN("%hx", "unsigned short", "double");
TEST_PRINTF_WARN("%hx", "unsigned short", "long double");
TEST_PRINTF_WARN("%hx", "unsigned short", "void *");
TEST_PRINTF_WARN_AKA("%hx", "unsigned short", "size_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%hx", "unsigned short", "ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%hx", "unsigned short", "ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%hx", "unsigned short", "unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%hx", "unsigned short", "intmax_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%hx", "unsigned short", "uintmax_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP("%hx", "unsigned short", "std::size_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP("%hx", "unsigned short", "std::ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%hx", "unsigned short", "std::ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%hx", "unsigned short", "std::intptr_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%hx", "unsigned short", "std::uintptr_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN("%hhu", "unsigned char", "bool");
TEST_PRINTF_WARN("%hhu", "unsigned char", "char");
TEST_PRINTF_WARN("%hhu", "unsigned char", "signed char");
TEST_PRINTF_NOWARN("%hhu", "unsigned char", "unsigned char");
TEST_PRINTF_WARN("%hhu", "unsigned char", "signed short");
TEST_PRINTF_WARN("%hhu", "unsigned char", "unsigned short");
TEST_PRINTF_WARN("%hhu", "unsigned char", "signed int");
TEST_PRINTF_WARN("%hhu", "unsigned char", "unsigned int");
TEST_PRINTF_WARN("%hhu", "unsigned char", "signed long");
TEST_PRINTF_WARN("%hhu", "unsigned char", "unsigned long");
TEST_PRINTF_WARN("%hhu", "unsigned char", "signed long long");
TEST_PRINTF_WARN("%hhu", "unsigned char", "unsigned long long");
TEST_PRINTF_WARN("%hhu", "unsigned char", "float");
TEST_PRINTF_WARN("%hhu", "unsigned char", "double");
TEST_PRINTF_WARN("%hhu", "unsigned char", "long double");
TEST_PRINTF_WARN("%hhu", "unsigned char", "void *");
TEST_PRINTF_WARN_AKA("%hhu", "unsigned char", "size_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%hhu", "unsigned char", "ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%hhu", "unsigned char", "ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%hhu", "unsigned char", "unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%hhu", "unsigned char", "intmax_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%hhu", "unsigned char", "uintmax_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP("%hhu", "unsigned char", "std::size_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP("%hhu", "unsigned char", "std::ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%hhu", "unsigned char", "std::ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%hhu", "unsigned char", "std::intptr_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%hhu", "unsigned char", "std::uintptr_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN("%hhx", "unsigned char", "bool");
TEST_PRINTF_WARN("%hhx", "unsigned char", "char");
TEST_PRINTF_WARN("%hhx", "unsigned char", "signed char");
TEST_PRINTF_NOWARN("%hhx", "unsigned char", "unsigned char");
TEST_PRINTF_WARN("%hhx", "unsigned char", "signed short");
TEST_PRINTF_WARN("%hhx", "unsigned char", "unsigned short");
TEST_PRINTF_WARN("%hhx", "unsigned char", "signed int");
TEST_PRINTF_WARN("%hhx", "unsigned char", "unsigned int");
TEST_PRINTF_WARN("%hhx", "unsigned char", "signed long");
TEST_PRINTF_WARN("%hhx", "unsigned char", "unsigned long");
TEST_PRINTF_WARN("%hhx", "unsigned char", "signed long long");
TEST_PRINTF_WARN("%hhx", "unsigned char", "unsigned long long");
TEST_PRINTF_WARN("%hhx", "unsigned char", "float");
TEST_PRINTF_WARN("%hhx", "unsigned char", "double");
TEST_PRINTF_WARN("%hhx", "unsigned char", "long double");
TEST_PRINTF_WARN("%hhx", "unsigned char", "void *");
TEST_PRINTF_WARN_AKA("%hhx", "unsigned char", "size_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%hhx", "unsigned char", "ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%hhx", "unsigned char", "ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%hhx", "unsigned char", "unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%hhx", "unsigned char", "intmax_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%hhx", "unsigned char", "uintmax_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP("%hhx", "unsigned char", "std::size_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP("%hhx", "unsigned char", "std::ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%hhx", "unsigned char", "std::ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%hhx", "unsigned char", "std::intptr_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%hhx", "unsigned char", "std::uintptr_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN("%Lu", "unsigned long long", "bool");
TEST_PRINTF_WARN("%Lu", "unsigned long long", "char");
TEST_PRINTF_WARN("%Lu", "unsigned long long", "signed char");
TEST_PRINTF_WARN("%Lu", "unsigned long long", "unsigned char");
TEST_PRINTF_WARN("%Lu", "unsigned long long", "signed short");
TEST_PRINTF_WARN("%Lu", "unsigned long long", "unsigned short");
TEST_PRINTF_WARN("%Lu", "unsigned long long", "signed int");
TEST_PRINTF_WARN("%Lu", "unsigned long long", "unsigned int");
TEST_PRINTF_WARN("%Lu", "unsigned long long", "signed long");
TEST_PRINTF_WARN("%Lu", "unsigned long long", "unsigned long");
TEST_PRINTF_WARN("%Lu", "unsigned long long", "signed long long");
TEST_PRINTF_NOWARN("%Lu", "unsigned long long", "unsigned long long");
TEST_PRINTF_WARN("%Lu", "unsigned long long", "float");
TEST_PRINTF_WARN("%Lu", "unsigned long long", "double");
TEST_PRINTF_WARN("%Lu", "unsigned long long", "long double");
TEST_PRINTF_WARN("%Lu", "unsigned long long", "void *");
TEST_PRINTF_WARN_AKA_WIN32("%Lu", "unsigned long long", "size_t", "unsigned long");
TEST_PRINTF_WARN_AKA("%Lu", "unsigned long long", "ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%Lu", "unsigned long long", "ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_WIN32("%Lu", "unsigned long long", "unsigned ptrdiff_t", "unsigned long");
TEST_PRINTF_WARN_AKA("%Lu", "unsigned long long", "intmax_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_WIN32("%Lu", "unsigned long long", "uintmax_t", "unsigned long");
TEST_PRINTF_WARN_AKA("%Lu", "unsigned long long", "intptr_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_WIN32("%Lu", "unsigned long long", "uintptr_t", "unsigned long");
TEST_PRINTF_WARN_AKA_CPP_WIN32("%Lu", "unsigned long long", "std::size_t", "unsigned long");
TEST_PRINTF_WARN_AKA_CPP("%Lu", "unsigned long long", "std::ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%Lu", "unsigned long long", "std::ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%Lu", "unsigned long long", "std::intmax_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP_WIN32("%Lu", "unsigned long long", "std::uintmax_t", "unsigned long");
TEST_PRINTF_WARN_AKA_CPP("%Lu", "unsigned long long", "std::intptr_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP_WIN32("%Lu", "unsigned long long", "std::uintptr_t", "unsigned long");
//TODO TEST_PRINTF_WARN("%Lx", "unsigned long long", "bool");
//TODO TEST_PRINTF_WARN("%Lx", "unsigned long long", "char");
//TODO TEST_PRINTF_WARN("%Lx", "unsigned long long", "signed char");
//TODO TEST_PRINTF_WARN("%Lx", "unsigned long long", "unsigned char");
//TODO TEST_PRINTF_WARN("%Lx", "unsigned long long", "signed short");
//TODO TEST_PRINTF_WARN("%Lx", "unsigned long long", "unsigned short");
//TODO TEST_PRINTF_WARN("%Lx", "unsigned long long", "signed int");
//TODO TEST_PRINTF_WARN("%Lx", "unsigned long long", "unsigned int");
TEST_PRINTF_WARN("%Lx", "unsigned long long", "signed long");
TEST_PRINTF_WARN("%Lx", "unsigned long long", "unsigned long");
TEST_PRINTF_WARN("%Lx", "unsigned long long", "signed long long");
//TODO TEST_PRINTF_NOWARN("%Lx", "unsigned long long", "unsigned long long");
TEST_PRINTF_WARN("%Lx", "unsigned long long", "float");
TEST_PRINTF_WARN("%Lx", "unsigned long long", "double");
TEST_PRINTF_WARN("%Lx", "unsigned long long", "long double");
TEST_PRINTF_WARN("%Lx", "unsigned long long", "void *");
TEST_PRINTF_WARN_AKA("%Lx", "unsigned long long", "size_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%Lx", "unsigned long long", "ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%Lx", "unsigned long long", "ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%Lx", "unsigned long long", "unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%Lx", "unsigned long long", "intmax_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%Lx", "unsigned long long", "uintmax_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%Lx", "unsigned long long", "intptr_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%Lx", "unsigned long long", "uintptr_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP("%Lx", "unsigned long long", "std::size_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP("%Lx", "unsigned long long", "std::ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%Lx", "unsigned long long", "std::ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%Lx", "unsigned long long", "std::intmax_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%Lx", "unsigned long long", "std::uintmax_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP("%Lx", "unsigned long long", "std::intptr_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%Lx", "unsigned long long", "std::uintptr_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN("%ju", "uintmax_t", "bool");
TEST_PRINTF_WARN("%ju", "uintmax_t", "char");
TEST_PRINTF_WARN("%ju", "uintmax_t", "signed char");
TEST_PRINTF_WARN("%ju", "uintmax_t", "unsigned char");
TEST_PRINTF_WARN("%ju", "uintmax_t", "signed short");
TEST_PRINTF_WARN("%ju", "uintmax_t", "unsigned short");
TEST_PRINTF_WARN("%ju", "uintmax_t", "signed int");
TEST_PRINTF_WARN("%ju", "uintmax_t", "unsigned int");
TEST_PRINTF_WARN("%ju", "uintmax_t", "signed long");
TEST_PRINTF_WARN("%ju", "uintmax_t", "unsigned long");
TEST_PRINTF_WARN("%ju", "uintmax_t", "signed long long");
TEST_PRINTF_WARN("%ju", "uintmax_t", "unsigned long long");
TEST_PRINTF_WARN("%ju", "uintmax_t", "float");
TEST_PRINTF_WARN("%ju", "uintmax_t", "double");
TEST_PRINTF_WARN("%ju", "uintmax_t", "long double");
TEST_PRINTF_WARN("%ju", "uintmax_t", "void *");
TEST_PRINTF_WARN_AKA("%ju", "uintmax_t", "size_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%ju", "uintmax_t", "ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%ju", "uintmax_t", "ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%ju", "uintmax_t", "unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%ju", "uintmax_t", "intmax_t", "signed long", "signed long long");
TEST_PRINTF_NOWARN("%ju", "uintmax_t", "uintmax_t");
TEST_PRINTF_WARN_AKA_CPP("%ju", "uintmax_t", "std::size_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP("%ju", "uintmax_t", "std::ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%ju", "uintmax_t", "std::ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%ju", "uintmax_t", "std::intptr_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%ju", "uintmax_t", "std::uintptr_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN("%jx", "uintmax_t", "bool");
TEST_PRINTF_WARN("%jx", "uintmax_t", "char");
TEST_PRINTF_WARN("%jx", "uintmax_t", "signed char");
TEST_PRINTF_WARN("%jx", "uintmax_t", "unsigned char");
TEST_PRINTF_WARN("%jx", "uintmax_t", "signed short");
TEST_PRINTF_WARN("%jx", "uintmax_t", "unsigned short");
TEST_PRINTF_WARN("%jx", "uintmax_t", "signed int");
TEST_PRINTF_WARN("%jx", "uintmax_t", "unsigned int");
TEST_PRINTF_WARN("%jx", "uintmax_t", "signed long");
TEST_PRINTF_WARN("%jx", "uintmax_t", "unsigned long");
TEST_PRINTF_WARN("%jx", "uintmax_t", "signed long long");
TEST_PRINTF_WARN("%jx", "uintmax_t", "unsigned long long");
TEST_PRINTF_WARN("%jx", "uintmax_t", "float");
TEST_PRINTF_WARN("%jx", "uintmax_t", "double");
TEST_PRINTF_WARN("%jx", "uintmax_t", "long double");
TEST_PRINTF_WARN("%jx", "uintmax_t", "void *");
TEST_PRINTF_WARN_AKA("%jx", "uintmax_t", "size_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%jx", "uintmax_t", "ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%jx", "uintmax_t", "ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%jx", "uintmax_t", "unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%jx", "uintmax_t", "intmax_t", "signed long", "signed long long");
TEST_PRINTF_NOWARN("%jx", "uintmax_t", "uintmax_t");
TEST_PRINTF_WARN_AKA_CPP("%jx", "uintmax_t", "std::size_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP("%jx", "uintmax_t", "std::ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%jx", "uintmax_t", "std::ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%jx", "uintmax_t", "std::intptr_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%jx", "uintmax_t", "std::uintptr_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%zd", "ssize_t", "size_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%zi", "ssize_t", "size_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN("%zu", "size_t", "bool");
TEST_PRINTF_WARN("%zu", "size_t", "char");
TEST_PRINTF_WARN("%zu", "size_t", "signed char");
TEST_PRINTF_WARN("%zu", "size_t", "unsigned char");
TEST_PRINTF_WARN("%zu", "size_t", "signed short");
TEST_PRINTF_WARN("%zu", "size_t", "unsigned short");
TEST_PRINTF_WARN("%zu", "size_t", "signed int");
TEST_PRINTF_WARN("%zu", "size_t", "unsigned int");
TEST_PRINTF_WARN("%zu", "size_t", "signed long");
TEST_PRINTF_WARN("%zu", "size_t", "unsigned long");
TEST_PRINTF_WARN("%zu", "size_t", "signed long long");
TEST_PRINTF_WARN("%zu", "size_t", "unsigned long long");
TEST_PRINTF_WARN("%zu", "size_t", "float");
TEST_PRINTF_WARN("%zu", "size_t", "double");
TEST_PRINTF_WARN("%zu", "size_t", "long double");
TEST_PRINTF_WARN("%zu", "size_t", "void *");
TEST_PRINTF_NOWARN("%zu", "size_t", "size_t");
TEST_PRINTF_WARN_AKA("%zu", "size_t", "ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%zu", "size_t", "ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%zu", "size_t", "unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%zu", "size_t", "intmax_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%zu", "size_t", "uintmax_t", "unsigned long", "unsigned long long");
TEST_PRINTF_NOWARN_CPP("%zu", "size_t", "std::size_t");
TEST_PRINTF_WARN_AKA_CPP("%zu", "size_t", "std::ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%zu", "size_t", "std::ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%zu", "size_t", "std::intptr_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%zu", "size_t", "std::uintptr_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN("%zx", "size_t", "bool");
TEST_PRINTF_WARN("%zx", "size_t", "char");
TEST_PRINTF_WARN("%zx", "size_t", "signed char");
TEST_PRINTF_WARN("%zx", "size_t", "unsigned char");
TEST_PRINTF_WARN("%zx", "size_t", "signed short");
TEST_PRINTF_WARN("%zx", "size_t", "unsigned short");
TEST_PRINTF_WARN("%zx", "size_t", "signed int");
TEST_PRINTF_WARN("%zx", "size_t", "unsigned int");
TEST_PRINTF_WARN("%zx", "size_t", "signed long");
TEST_PRINTF_WARN("%zx", "size_t", "unsigned long");
TEST_PRINTF_WARN("%zx", "size_t", "signed long long");
TEST_PRINTF_WARN("%zx", "size_t", "unsigned long long");
TEST_PRINTF_WARN("%zx", "size_t", "float");
TEST_PRINTF_WARN("%zx", "size_t", "double");
TEST_PRINTF_WARN("%zx", "size_t", "long double");
TEST_PRINTF_WARN("%zx", "size_t", "void *");
TEST_PRINTF_NOWARN("%zx", "size_t", "size_t");
TEST_PRINTF_WARN_AKA("%zx", "size_t", "ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%zx", "size_t", "ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%zx", "size_t", "unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%zx", "size_t", "intmax_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%zx", "size_t", "uintmax_t", "unsigned long", "unsigned long long");
TEST_PRINTF_NOWARN_CPP("%zx", "size_t", "std::size_t");
TEST_PRINTF_WARN_AKA_CPP("%zx", "size_t", "std::ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%zx", "size_t", "std::ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%zx", "size_t", "std::intptr_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%zx", "size_t", "std::uintptr_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN("%tu", "unsigned ptrdiff_t", "bool");
TEST_PRINTF_WARN("%tu", "unsigned ptrdiff_t", "char");
TEST_PRINTF_WARN("%tu", "unsigned ptrdiff_t", "signed char");
TEST_PRINTF_WARN("%tu", "unsigned ptrdiff_t", "unsigned char");
TEST_PRINTF_WARN("%tu", "unsigned ptrdiff_t", "signed short");
TEST_PRINTF_WARN("%tu", "unsigned ptrdiff_t", "unsigned short");
TEST_PRINTF_WARN("%tu", "unsigned ptrdiff_t", "signed int");
TEST_PRINTF_WARN("%tu", "unsigned ptrdiff_t", "unsigned int");
TEST_PRINTF_WARN("%tu", "unsigned ptrdiff_t", "signed long");
TEST_PRINTF_WARN("%tu", "unsigned ptrdiff_t", "unsigned long");
TEST_PRINTF_WARN("%tu", "unsigned ptrdiff_t", "signed long long");
TEST_PRINTF_WARN("%tu", "unsigned ptrdiff_t", "unsigned long long");
TEST_PRINTF_WARN("%tu", "unsigned ptrdiff_t", "float");
TEST_PRINTF_WARN("%tu", "unsigned ptrdiff_t", "double");
TEST_PRINTF_WARN("%tu", "unsigned ptrdiff_t", "long double");
TEST_PRINTF_WARN("%tu", "unsigned ptrdiff_t", "void *");
TEST_PRINTF_WARN_AKA("%tu", "unsigned ptrdiff_t", "size_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%tu", "unsigned ptrdiff_t", "ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%tu", "unsigned ptrdiff_t", "ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_NOWARN("%tu", "unsigned ptrdiff_t", "unsigned ptrdiff_t");
TEST_PRINTF_WARN_AKA("%tu", "unsigned ptrdiff_t", "intmax_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%tu", "unsigned ptrdiff_t", "uintmax_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP("%tu", "unsigned ptrdiff_t", "std::size_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP("%tu", "unsigned ptrdiff_t", "std::ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%tu", "unsigned ptrdiff_t", "std::ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%tu", "unsigned ptrdiff_t", "std::intptr_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%tu", "unsigned ptrdiff_t", "std::uintptr_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN("%tx", "unsigned ptrdiff_t", "bool");
TEST_PRINTF_WARN("%tx", "unsigned ptrdiff_t", "char");
TEST_PRINTF_WARN("%tx", "unsigned ptrdiff_t", "signed char");
TEST_PRINTF_WARN("%tx", "unsigned ptrdiff_t", "unsigned char");
TEST_PRINTF_WARN("%tx", "unsigned ptrdiff_t", "signed short");
TEST_PRINTF_WARN("%tx", "unsigned ptrdiff_t", "unsigned short");
TEST_PRINTF_WARN("%tx", "unsigned ptrdiff_t", "signed int");
TEST_PRINTF_WARN("%tx", "unsigned ptrdiff_t", "unsigned int");
TEST_PRINTF_WARN("%tx", "unsigned ptrdiff_t", "signed long");
TEST_PRINTF_WARN("%tx", "unsigned ptrdiff_t", "unsigned long");
TEST_PRINTF_WARN("%tx", "unsigned ptrdiff_t", "signed long long");
TEST_PRINTF_WARN("%tx", "unsigned ptrdiff_t", "unsigned long long");
TEST_PRINTF_WARN("%tx", "unsigned ptrdiff_t", "float");
TEST_PRINTF_WARN("%tx", "unsigned ptrdiff_t", "double");
TEST_PRINTF_WARN("%tx", "unsigned ptrdiff_t", "long double");
TEST_PRINTF_WARN("%tx", "unsigned ptrdiff_t", "void *");
TEST_PRINTF_WARN_AKA("%tx", "unsigned ptrdiff_t", "size_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%tx", "unsigned ptrdiff_t", "ssize_t", "signed long", "signed long long");
//TODO TEST_PRINTF_WARN_AKA("%tx", "unsigned ptrdiff_t", "ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_NOWARN("%tx", "unsigned ptrdiff_t", "unsigned ptrdiff_t");
TEST_PRINTF_WARN_AKA("%tx", "unsigned ptrdiff_t", "intmax_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%tx", "unsigned ptrdiff_t", "uintmax_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP("%tx", "unsigned ptrdiff_t", "std::size_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP("%tx", "unsigned ptrdiff_t", "std::ssize_t", "signed long", "signed long long");
//TODO TEST_PRINTF_WARN_AKA_CPP("%tx", "unsigned ptrdiff_t", "std::ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%tx", "unsigned ptrdiff_t", "std::intptr_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%tx", "unsigned ptrdiff_t", "std::uintptr_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN("%Iu", "size_t", "bool");
TEST_PRINTF_WARN("%Iu", "size_t", "char");
TEST_PRINTF_WARN("%Iu", "size_t", "signed char");
TEST_PRINTF_WARN("%Iu", "size_t", "unsigned char");
TEST_PRINTF_WARN("%Iu", "size_t", "signed short");
TEST_PRINTF_WARN("%Iu", "size_t", "unsigned short");
TEST_PRINTF_WARN("%Iu", "size_t", "signed int");
TEST_PRINTF_WARN("%Iu", "size_t", "unsigned int");
TEST_PRINTF_WARN("%Iu", "size_t", "signed long");
TEST_PRINTF_WARN("%Iu", "size_t", "unsigned long");
TEST_PRINTF_WARN("%Iu", "size_t", "signed long long");
TEST_PRINTF_WARN("%Iu", "size_t", "unsigned long long");
TEST_PRINTF_WARN("%Iu", "size_t", "float");
TEST_PRINTF_WARN("%Iu", "size_t", "double");
TEST_PRINTF_WARN("%Iu", "size_t", "long double");
TEST_PRINTF_WARN("%Iu", "size_t", "void *");
TEST_PRINTF_NOWARN("%Iu", "size_t", "size_t");
TEST_PRINTF_WARN_AKA("%Iu", "size_t", "ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%Iu", "size_t", "ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%Iu", "size_t", "unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%Iu", "size_t", "intmax_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%Iu", "size_t", "uintmax_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%Iu", "size_t", "intptr_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%Iu", "size_t", "uintptr_t", "unsigned long", "unsigned long long");
TEST_PRINTF_NOWARN_CPP("%Iu", "size_t", "std::size_t");
TEST_PRINTF_WARN_AKA_CPP("%Iu", "size_t", "std::ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%Iu", "size_t", "std::ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%Iu", "size_t", "std::intmax_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%Iu", "size_t", "std::uintmax_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP("%Iu", "size_t", "std::intptr_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%Iu", "size_t", "std::uintptr_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN("%Ix", "size_t", "bool");
TEST_PRINTF_WARN("%Ix", "size_t", "char");
TEST_PRINTF_WARN("%Ix", "size_t", "signed char");
TEST_PRINTF_WARN("%Ix", "size_t", "unsigned char");
TEST_PRINTF_WARN("%Ix", "size_t", "signed short");
TEST_PRINTF_WARN("%Ix", "size_t", "unsigned short");
TEST_PRINTF_WARN("%Ix", "size_t", "signed int");
TEST_PRINTF_WARN("%Ix", "size_t", "unsigned int");
TEST_PRINTF_WARN("%Ix", "size_t", "signed long");
TEST_PRINTF_WARN("%Ix", "size_t", "unsigned long");
TEST_PRINTF_WARN("%Ix", "size_t", "signed long long");
TEST_PRINTF_WARN("%Ix", "size_t", "unsigned long long");
TEST_PRINTF_WARN("%Ix", "size_t", "float");
TEST_PRINTF_WARN("%Ix", "size_t", "double");
TEST_PRINTF_WARN("%Ix", "size_t", "long double");
TEST_PRINTF_WARN("%Ix", "size_t", "void *");
TEST_PRINTF_NOWARN("%Ix", "size_t", "size_t");
TEST_PRINTF_WARN_AKA("%Ix", "size_t", "ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%Ix", "size_t", "ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%Ix", "size_t", "unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%Ix", "size_t", "intmax_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%Ix", "size_t", "uintmax_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%Ix", "size_t", "intptr_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%Ix", "size_t", "uintptr_t", "unsigned long", "unsigned long long");
TEST_PRINTF_NOWARN_CPP("%Ix", "size_t", "std::size_t");
TEST_PRINTF_WARN_AKA_CPP("%Ix", "size_t", "std::ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%Ix", "size_t", "std::ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%Ix", "size_t", "std::intmax_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%Ix", "size_t", "std::uintmax_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP("%Ix", "size_t", "std::intptr_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%Ix", "size_t", "std::uintptr_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN("%I64u", "unsigned __int64", "bool");
TEST_PRINTF_WARN("%I64u", "unsigned __int64", "char");
TEST_PRINTF_WARN("%I64u", "unsigned __int64", "signed char");
TEST_PRINTF_WARN("%I64u", "unsigned __int64", "unsigned char");
TEST_PRINTF_WARN("%I64u", "unsigned __int64", "signed short");
TEST_PRINTF_WARN("%I64u", "unsigned __int64", "unsigned short");
TEST_PRINTF_WARN("%I64u", "unsigned __int64", "signed int");
TEST_PRINTF_WARN("%I64u", "unsigned __int64", "unsigned int");
TEST_PRINTF_WARN("%I64u", "unsigned __int64", "signed long");
TEST_PRINTF_WARN("%I64u", "unsigned __int64", "unsigned long");
TEST_PRINTF_WARN("%I64u", "unsigned __int64", "signed long long");
TEST_PRINTF_NOWARN("%I64u", "unsigned __int64", "unsigned long long");
TEST_PRINTF_WARN("%I64u", "unsigned __int64", "float");
TEST_PRINTF_WARN("%I64u", "unsigned __int64", "double");
TEST_PRINTF_WARN("%I64u", "unsigned __int64", "long double");
TEST_PRINTF_WARN("%I64u", "unsigned __int64", "void *");
TEST_PRINTF_WARN_AKA_WIN32("%I64u", "unsigned __int64", "size_t", "unsigned long");
TEST_PRINTF_WARN_AKA("%I64u", "unsigned __int64", "ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%I64u", "unsigned __int64", "ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_WIN32("%I64u", "unsigned __int64", "unsigned ptrdiff_t", "unsigned long");
TEST_PRINTF_WARN_AKA("%I64u", "unsigned __int64", "intmax_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_WIN32("%I64u", "unsigned __int64", "uintmax_t", "unsigned long");
TEST_PRINTF_WARN_AKA("%I64u", "unsigned __int64", "intptr_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_WIN32("%I64u", "unsigned __int64", "uintptr_t", "unsigned long");
TEST_PRINTF_WARN_AKA_CPP_WIN32("%I64u", "unsigned __int64", "std::size_t", "unsigned long");
TEST_PRINTF_WARN_AKA_CPP("%I64u", "unsigned __int64", "std::ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%I64u", "unsigned __int64", "std::ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%I64u", "unsigned __int64", "std::intmax_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP_WIN32("%I64u", "unsigned __int64", "std::uintmax_t", "unsigned long");
TEST_PRINTF_WARN_AKA_CPP("%I64u", "unsigned __int64", "std::intptr_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP_WIN32("%I64u", "unsigned __int64", "std::uintptr_t", "unsigned long");
TEST_PRINTF_WARN("%I64x", "unsigned __int64", "bool");
TEST_PRINTF_WARN("%I64x", "unsigned __int64", "char");
TEST_PRINTF_WARN("%I64x", "unsigned __int64", "signed char");
TEST_PRINTF_WARN("%I64x", "unsigned __int64", "unsigned char");
TEST_PRINTF_WARN("%I64x", "unsigned __int64", "signed short");
TEST_PRINTF_WARN("%I64x", "unsigned __int64", "unsigned short");
TEST_PRINTF_WARN("%I64x", "unsigned __int64", "signed int");
TEST_PRINTF_WARN("%I64x", "unsigned __int64", "unsigned int");
TEST_PRINTF_WARN("%I64x", "unsigned __int64", "signed long");
TEST_PRINTF_WARN("%I64x", "unsigned __int64", "unsigned long");
//TODO TEST_PRINTF_WARN("%I64x", "unsigned __int64", "signed long long");
TEST_PRINTF_NOWARN("%I64x", "unsigned __int64", "unsigned long long");
TEST_PRINTF_WARN("%I64x", "unsigned __int64", "float");
TEST_PRINTF_WARN("%I64x", "unsigned __int64", "double");
TEST_PRINTF_WARN("%I64x", "unsigned __int64", "long double");
TEST_PRINTF_WARN("%I64x", "unsigned __int64", "void *");
//TODO TEST_PRINTF_WARN("%I64x", "unsigned __int64", "size_t");
TEST_PRINTF_WARN_AKA_WIN32("%I64x", "unsigned __int64", "ssize_t", "signed long");
TEST_PRINTF_WARN_AKA_WIN32("%I64x", "unsigned __int64", "ptrdiff_t", "signed long");
//TODO TEST_PRINTF_NOWARN("%I64x", "unsigned __int64", "unsigned __int64");
// TODO TEST_PRINTF_WARN("%I64x", "unsigned __int64", "__int64");
TEST_PRINTF_WARN_AKA_WIN32("%I64x", "unsigned __int64", "unsigned ptrdiff_t", "unsigned long");
TEST_PRINTF_WARN_AKA_WIN32("%I64x", "unsigned __int64", "intmax_t", "signed long");
TEST_PRINTF_WARN_AKA_WIN32("%I64x", "unsigned __int64", "uintmax_t", "unsigned long");
TEST_PRINTF_WARN_AKA_WIN32("%I64x", "unsigned __int64", "intptr_t", "signed long");
TEST_PRINTF_WARN_AKA_WIN32("%I64x", "unsigned __int64", "uintptr_t", "unsigned long");
TEST_PRINTF_WARN_AKA_CPP_WIN32("%I64x", "unsigned __int64", "std::size_t", "unsigned long");
TEST_PRINTF_WARN_AKA_CPP_WIN32("%I64x", "unsigned __int64", "std::ssize_t", "signed long");
TEST_PRINTF_WARN_AKA_CPP_WIN32("%I64x", "unsigned __int64", "std::ptrdiff_t", "signed long");
TEST_PRINTF_WARN_AKA_CPP_WIN32("%I64x", "unsigned __int64", "std::intmax_t", "signed long");
TEST_PRINTF_WARN_AKA_CPP_WIN32("%I64x", "unsigned __int64", "std::uintmax_t", "unsigned long");
TEST_PRINTF_WARN_AKA_CPP_WIN32("%I64x", "unsigned __int64", "std::intptr_t", "signed long");
TEST_PRINTF_WARN_AKA_CPP_WIN32("%I64x", "unsigned __int64", "std::uintptr_t", "unsigned long");
TEST_PRINTF_WARN("%I64d", "__int64", "bool");
TEST_PRINTF_WARN("%I64d", "__int64", "signed char");
TEST_PRINTF_WARN("%I64d", "__int64", "unsigned char");
TEST_PRINTF_WARN("%I64d", "__int64", "void *");
// TODO TEST_PRINTF_WARN("%I64d", "__int64", "size_t");
TEST_PRINTF_WARN_AKA_WIN32("%I64d", "__int64", "intmax_t", "signed long");
TEST_PRINTF_WARN_AKA_WIN32("%I64d", "__int64", "ssize_t", "signed long");
TEST_PRINTF_WARN_AKA_WIN32("%I64d", "__int64", "ptrdiff_t", "signed long");
TEST_PRINTF_NOWARN("%I64d", "__int64", "__int64");
TEST_PRINTF_WARN("%I32u", "unsigned __int32", "bool");
TEST_PRINTF_WARN("%I32u", "unsigned __int32", "char");
TEST_PRINTF_WARN("%I32u", "unsigned __int32", "signed char");
TEST_PRINTF_WARN("%I32u", "unsigned __int32", "unsigned char");
TEST_PRINTF_WARN("%I32u", "unsigned __int32", "signed short");
TEST_PRINTF_WARN("%I32u", "unsigned __int32", "unsigned short");
TEST_PRINTF_WARN("%I32u", "unsigned __int32", "signed int");
TEST_PRINTF_NOWARN("%I32u", "unsigned __int32", "unsigned int");
TEST_PRINTF_WARN("%I32u", "unsigned __int32", "signed long");
TEST_PRINTF_WARN("%I32u", "unsigned __int32", "unsigned long");
TEST_PRINTF_WARN("%I32u", "unsigned __int32", "signed long long");
TEST_PRINTF_WARN("%I32u", "unsigned __int32", "unsigned long long");
TEST_PRINTF_WARN("%I32u", "unsigned __int32", "float");
TEST_PRINTF_WARN("%I32u", "unsigned __int32", "double");
TEST_PRINTF_WARN("%I32u", "unsigned __int32", "long double");
TEST_PRINTF_WARN("%I32u", "unsigned __int32", "void *");
TEST_PRINTF_WARN_AKA("%I32u", "unsigned __int32", "size_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%I32u", "unsigned __int32", "ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%I32u", "unsigned __int32", "ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%I32u", "unsigned __int32", "unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%I32u", "unsigned __int32", "intmax_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%I32u", "unsigned __int32", "uintmax_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%I32u", "unsigned __int32", "intptr_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%I32u", "unsigned __int32", "uintptr_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP("%I32u", "unsigned __int32", "std::size_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP("%I32u", "unsigned __int32", "std::ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%I32u", "unsigned __int32", "std::ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%I32u", "unsigned __int32", "std::intmax_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%I32u", "unsigned __int32", "std::uintmax_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP("%I32u", "unsigned __int32", "std::intptr_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%I32u", "unsigned __int32", "std::uintptr_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN("%I32x", "unsigned __int32", "bool");
TEST_PRINTF_WARN("%I32x", "unsigned __int32", "char");
TEST_PRINTF_WARN("%I32x", "unsigned __int32", "signed char");
TEST_PRINTF_WARN("%I32x", "unsigned __int32", "unsigned char");
TEST_PRINTF_WARN("%I32x", "unsigned __int32", "signed short");
TEST_PRINTF_WARN("%I32x", "unsigned __int32", "unsigned short");
//TODO TEST_PRINTF_WARN("%I32x", "unsigned __int32", "signed int");
TEST_PRINTF_NOWARN("%I32x", "unsigned __int32", "unsigned int");
TEST_PRINTF_WARN("%I32x", "unsigned __int32", "signed long");
TEST_PRINTF_WARN("%I32x", "unsigned __int32", "unsigned long");
TEST_PRINTF_WARN("%I32x", "unsigned __int32", "signed long long");
TEST_PRINTF_WARN("%I32x", "unsigned __int32", "unsigned long long");
TEST_PRINTF_WARN("%I32x", "unsigned __int32", "float");
TEST_PRINTF_WARN("%I32x", "unsigned __int32", "double");
TEST_PRINTF_WARN("%I32x", "unsigned __int32", "long double");
TEST_PRINTF_WARN("%I32x", "unsigned __int32", "void *");
TEST_PRINTF_WARN_AKA("%I32x", "unsigned __int32", "size_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%I32x", "unsigned __int32", "ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%I32x", "unsigned __int32", "ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%I32x", "unsigned __int32", "unsigned ptrdiff_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%I32x", "unsigned __int32", "intmax_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%I32x", "unsigned __int32", "uintmax_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA("%I32x", "unsigned __int32", "intptr_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA("%I32x", "unsigned __int32", "uintptr_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP("%I32x", "unsigned __int32", "std::size_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP("%I32x", "unsigned __int32", "std::ssize_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%I32x", "unsigned __int32", "std::ptrdiff_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%I32x", "unsigned __int32", "std::intmax_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%I32x", "unsigned __int32", "std::uintmax_t", "unsigned long", "unsigned long long");
TEST_PRINTF_WARN_AKA_CPP("%I32x", "unsigned __int32", "std::intptr_t", "signed long", "signed long long");
TEST_PRINTF_WARN_AKA_CPP("%I32x", "unsigned __int32", "std::uintptr_t", "unsigned long", "unsigned long long");
}
void testPosixPrintfScanfParameterPosition() { // #4900 - No support for parameters in format strings
check("void foo() {"
" int bar;"
" printf(\"%1$d\", 1);"
" printf(\"%1$d, %d, %1$d\", 1, 2);"
" scanf(\"%1$d\", &bar);"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" int bar;\n"
" printf(\"%1$d\");\n"
" printf(\"%1$d, %d, %4$d\", 1, 2, 3);\n"
" scanf(\"%2$d\", &bar);\n"
" printf(\"%0$f\", 0.0);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) printf format string requires 1 parameter but only 0 are given.\n"
"[test.cpp:4]: (warning) printf: referencing parameter 4 while 3 arguments given\n"
"[test.cpp:5]: (warning) scanf: referencing parameter 2 while 1 arguments given\n"
"[test.cpp:6]: (warning) printf: parameter positions start at 1, not 0\n"
"", errout_str());
}
void testMicrosoftPrintfArgument() {
check("void foo() {\n"
" size_t s;\n"
" ptrdiff_t p;\n"
" __int32 i32;\n"
" unsigned __int32 u32;\n"
" __int64 i64;\n"
" unsigned __int64 u64;\n"
" printf(\"%Id %Iu %Ix\", s, s, s);\n"
" printf(\"%Id %Iu %Ix\", p, p, p);\n"
" printf(\"%I32d %I32u %I32x\", i32, i32, i32);\n"
" printf(\"%I32d %I32u %I32x\", u32, u32, u32);\n"
" printf(\"%I64d %I64u %I64x\", i64, i64, i64);\n"
" printf(\"%I64d %I64u %I64x\", u64, u64, u64);\n"
"}", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("[test.cpp:8]: (portability) %Id in format string (no. 1) requires 'ptrdiff_t' but the argument type is 'size_t {aka unsigned long}'.\n"
"[test.cpp:9]: (portability) %Iu in format string (no. 2) requires 'size_t' but the argument type is 'ptrdiff_t {aka signed long}'.\n"
"[test.cpp:9]: (portability) %Ix in format string (no. 3) requires 'size_t' but the argument type is 'ptrdiff_t {aka signed long}'.\n"
"[test.cpp:10]: (portability) %I32u in format string (no. 2) requires 'unsigned __int32' but the argument type is '__int32 {aka signed int}'.\n"
"[test.cpp:11]: (portability) %I32d in format string (no. 1) requires '__int32' but the argument type is 'unsigned __int32 {aka unsigned int}'.\n"
"[test.cpp:12]: (portability) %I64u in format string (no. 2) requires 'unsigned __int64' but the argument type is '__int64 {aka signed long long}'.\n"
"[test.cpp:13]: (portability) %I64d in format string (no. 1) requires '__int64' but the argument type is 'unsigned __int64 {aka unsigned long long}'.\n", errout_str());
check("void foo() {\n"
" size_t s;\n"
" ptrdiff_t p;\n"
" __int32 i32;\n"
" unsigned __int32 u32;\n"
" __int64 i64;\n"
" unsigned __int64 u64;\n"
" printf(\"%Id %Iu %Ix\", s, s, s);\n"
" printf(\"%Id %Iu %Ix\", p, p, p);\n"
" printf(\"%I32d %I32u %I32x\", i32, i32, i32);\n"
" printf(\"%I32d %I32u %I32x\", u32, u32, u32);\n"
" printf(\"%I64d %I64u %I64x\", i64, i64, i64);\n"
" printf(\"%I64d %I64u %I64x\", u64, u64, u64);\n"
"}", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Win64));
ASSERT_EQUALS("[test.cpp:8]: (portability) %Id in format string (no. 1) requires 'ptrdiff_t' but the argument type is 'size_t {aka unsigned long long}'.\n"
"[test.cpp:9]: (portability) %Iu in format string (no. 2) requires 'size_t' but the argument type is 'ptrdiff_t {aka signed long long}'.\n"
"[test.cpp:9]: (portability) %Ix in format string (no. 3) requires 'size_t' but the argument type is 'ptrdiff_t {aka signed long long}'.\n"
"[test.cpp:10]: (portability) %I32u in format string (no. 2) requires 'unsigned __int32' but the argument type is '__int32 {aka signed int}'.\n"
"[test.cpp:11]: (portability) %I32d in format string (no. 1) requires '__int32' but the argument type is 'unsigned __int32 {aka unsigned int}'.\n"
"[test.cpp:12]: (portability) %I64u in format string (no. 2) requires 'unsigned __int64' but the argument type is '__int64 {aka signed long long}'.\n"
"[test.cpp:13]: (portability) %I64d in format string (no. 1) requires '__int64' but the argument type is 'unsigned __int64 {aka unsigned long long}'.\n", errout_str());
check("void foo() {\n"
" size_t s;\n"
" int i;\n"
" printf(\"%I\", s);\n"
" printf(\"%I6\", s);\n"
" printf(\"%I6x\", s);\n"
" printf(\"%I16\", s);\n"
" printf(\"%I16x\", s);\n"
" printf(\"%I32\", s);\n"
" printf(\"%I64\", s);\n"
" printf(\"%I%i\", s, i);\n"
" printf(\"%I6%i\", s, i);\n"
" printf(\"%I6x%i\", s, i);\n"
" printf(\"%I16%i\", s, i);\n"
" printf(\"%I16x%i\", s, i);\n"
" printf(\"%I32%i\", s, i);\n"
" printf(\"%I64%i\", s, i);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (warning) 'I' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:5]: (warning) 'I' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:6]: (warning) 'I' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:7]: (warning) 'I' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:8]: (warning) 'I' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:9]: (warning) 'I32' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:10]: (warning) 'I64' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:11]: (warning) 'I' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:12]: (warning) 'I' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:13]: (warning) 'I' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:14]: (warning) 'I' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:15]: (warning) 'I' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:16]: (warning) 'I32' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:17]: (warning) 'I64' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n", errout_str());
// ticket #5264
check("void foo(LPARAM lp, WPARAM wp, LRESULT lr) {\n"
" printf(\"%Ix %Ix %Ix\", lp, wp, lr);\n"
"}\n", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Win64));
ASSERT_EQUALS("", errout_str());
check("void foo(LPARAM lp, WPARAM wp, LRESULT lr) {\n"
" printf(\"%Ix %Ix %Ix\", lp, wp, lr);\n"
"}\n", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("", errout_str());
check("void foo(UINT32 a, ::UINT32 b, Fred::UINT32 c) {\n"
" printf(\"%d %d %d\", a, b, c);\n"
"};\n", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("[test.cpp:2]: (portability) %d in format string (no. 1) requires 'int' but the argument type is 'UINT32 {aka unsigned int}'.\n"
"[test.cpp:2]: (portability) %d in format string (no. 2) requires 'int' but the argument type is 'UINT32 {aka unsigned int}'.\n", errout_str());
check("void foo(LPCVOID a, ::LPCVOID b, Fred::LPCVOID c) {\n"
" printf(\"%d %d %d\", a, b, c);\n"
"};\n", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("[test.cpp:2]: (warning) %d in format string (no. 1) requires 'int' but the argument type is 'const void *'.\n"
"[test.cpp:2]: (warning) %d in format string (no. 2) requires 'int' but the argument type is 'const void *'.\n", errout_str());
check("void foo() {\n"
" SSIZE_T s = -2;\n" // In MSVC, SSIZE_T is available in capital letters using #include <BaseTsd.h>
" int i;\n"
" printf(\"%zd\", s);\n"
" printf(\"%zd%i\", s, i);\n"
" printf(\"%zu\", s);\n"
"}", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("[test.cpp:6]: (portability) %zu in format string (no. 1) requires 'size_t' but the argument type is 'SSIZE_T {aka signed long}'.\n", errout_str());
check("void foo() {\n"
" SSIZE_T s = -2;\n" // In MSVC, SSIZE_T is available in capital letters using #include <BaseTsd.h>
" int i;\n"
" printf(\"%zd\", s);\n"
" printf(\"%zd%i\", s, i);\n"
" printf(\"%zu\", s);\n"
"}", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Win64));
ASSERT_EQUALS("[test.cpp:6]: (portability) %zu in format string (no. 1) requires 'size_t' but the argument type is 'SSIZE_T {aka signed long long}'.\n", errout_str());
check("void foo() {\n"
" SSIZE_T s = -2;\n" // Under Unix, ssize_t has to be written in small letters. Not Cppcheck, but the compiler will report this.
" int i;\n"
" printf(\"%zd\", s);\n"
" printf(\"%zd%i\", s, i);\n"
" printf(\"%zu\", s);\n"
"}", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Unix64));
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" typedef SSIZE_T ssize_t;\n" // Test using typedef
" ssize_t s = -2;\n"
" int i;\n"
" printf(\"%zd\", s);\n"
" printf(\"%zd%i\", s, i);\n"
" printf(\"%zu\", s);\n"
"}", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Win64));
ASSERT_EQUALS("[test.cpp:7]: (portability) %zu in format string (no. 1) requires 'size_t' but the argument type is 'SSIZE_T {aka signed long long}'.\n", errout_str());
}
void testMicrosoftScanfArgument() {
check("void foo() {\n"
" size_t s;\n"
" ptrdiff_t p;\n"
" __int32 i32;\n"
" unsigned __int32 u32;\n"
" __int64 i64;\n"
" unsigned __int64 u64;\n"
" scanf(\"%Id %Iu %Ix\", &s, &s, &s);\n"
" scanf(\"%Id %Iu %Ix\", &p, &p, &p);\n"
" scanf(\"%I32d %I32u %I32x\", &i32, &i32, &i32);\n"
" scanf(\"%I32d %I32u %I32x\", &u32, &u32, &u32);\n"
" scanf(\"%I64d %I64u %I64x\", &i64, &i64, &i64);\n"
" scanf(\"%I64d %I64u %I64x\", &u64, &u64, &u64);\n"
"}", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("[test.cpp:8]: (portability) %Id in format string (no. 1) requires 'ptrdiff_t *' but the argument type is 'size_t * {aka unsigned long *}'.\n"
"[test.cpp:9]: (portability) %Iu in format string (no. 2) requires 'size_t *' but the argument type is 'ptrdiff_t * {aka signed long *}'.\n"
"[test.cpp:9]: (portability) %Ix in format string (no. 3) requires 'size_t *' but the argument type is 'ptrdiff_t * {aka signed long *}'.\n"
"[test.cpp:10]: (portability) %I32u in format string (no. 2) requires 'unsigned __int32 *' but the argument type is '__int32 * {aka signed int *}'.\n"
"[test.cpp:10]: (portability) %I32x in format string (no. 3) requires 'unsigned __int32 *' but the argument type is '__int32 * {aka signed int *}'.\n"
"[test.cpp:11]: (portability) %I32d in format string (no. 1) requires '__int32 *' but the argument type is 'unsigned __int32 * {aka unsigned int *}'.\n"
"[test.cpp:12]: (portability) %I64u in format string (no. 2) requires 'unsigned __int64 *' but the argument type is '__int64 * {aka signed long long *}'.\n"
"[test.cpp:12]: (portability) %I64x in format string (no. 3) requires 'unsigned __int64 *' but the argument type is '__int64 * {aka signed long long *}'.\n"
"[test.cpp:13]: (portability) %I64d in format string (no. 1) requires '__int64 *' but the argument type is 'unsigned __int64 * {aka unsigned long long *}'.\n", errout_str());
check("void foo() {\n"
" size_t s;\n"
" ptrdiff_t p;\n"
" __int32 i32;\n"
" unsigned __int32 u32;\n"
" __int64 i64;\n"
" unsigned __int64 u64;\n"
" scanf(\"%Id %Iu %Ix\", &s, &s, &s);\n"
" scanf(\"%Id %Iu %Ix\", &p, &p, &p);\n"
" scanf(\"%I32d %I32u %I32x\", &i32, &i32, &i32);\n"
" scanf(\"%I32d %I32u %I32x\", &u32, &u32, &u32);\n"
" scanf(\"%I64d %I64u %I64x\", &i64, &i64, &i64);\n"
" scanf(\"%I64d %I64u %I64x\", &u64, &u64, &u64);\n"
"}", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Win64));
ASSERT_EQUALS("[test.cpp:8]: (portability) %Id in format string (no. 1) requires 'ptrdiff_t *' but the argument type is 'size_t * {aka unsigned long long *}'.\n"
"[test.cpp:9]: (portability) %Iu in format string (no. 2) requires 'size_t *' but the argument type is 'ptrdiff_t * {aka signed long long *}'.\n"
"[test.cpp:9]: (portability) %Ix in format string (no. 3) requires 'size_t *' but the argument type is 'ptrdiff_t * {aka signed long long *}'.\n"
"[test.cpp:10]: (portability) %I32u in format string (no. 2) requires 'unsigned __int32 *' but the argument type is '__int32 * {aka signed int *}'.\n"
"[test.cpp:10]: (portability) %I32x in format string (no. 3) requires 'unsigned __int32 *' but the argument type is '__int32 * {aka signed int *}'.\n"
"[test.cpp:11]: (portability) %I32d in format string (no. 1) requires '__int32 *' but the argument type is 'unsigned __int32 * {aka unsigned int *}'.\n"
"[test.cpp:12]: (portability) %I64u in format string (no. 2) requires 'unsigned __int64 *' but the argument type is '__int64 * {aka signed long long *}'.\n"
"[test.cpp:12]: (portability) %I64x in format string (no. 3) requires 'unsigned __int64 *' but the argument type is '__int64 * {aka signed long long *}'.\n"
"[test.cpp:13]: (portability) %I64d in format string (no. 1) requires '__int64 *' but the argument type is 'unsigned __int64 * {aka unsigned long long *}'.\n", errout_str());
check("void foo() {\n"
" size_t s;\n"
" int i;\n"
" scanf(\"%I\", &s);\n"
" scanf(\"%I6\", &s);\n"
" scanf(\"%I6x\", &s);\n"
" scanf(\"%I16\", &s);\n"
" scanf(\"%I16x\", &s);\n"
" scanf(\"%I32\", &s);\n"
" scanf(\"%I64\", &s);\n"
" scanf(\"%I%i\", &s, &i);\n"
" scanf(\"%I6%i\", &s, &i);\n"
" scanf(\"%I6x%i\", &s, &i);\n"
" scanf(\"%I16%i\", &s, &i);\n"
" scanf(\"%I16x%i\", &s, &i);\n"
" scanf(\"%I32%i\", &s, &i);\n"
" scanf(\"%I64%i\", &s, &i);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (warning) 'I' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:5]: (warning) 'I' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:6]: (warning) 'I' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:7]: (warning) 'I' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:8]: (warning) 'I' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:9]: (warning) 'I32' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:10]: (warning) 'I64' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:11]: (warning) 'I' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:12]: (warning) 'I' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:13]: (warning) 'I' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:14]: (warning) 'I' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:15]: (warning) 'I' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:16]: (warning) 'I32' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n"
"[test.cpp:17]: (warning) 'I64' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n", errout_str());
check("void foo() {\n"
" SSIZE_T s;\n" // In MSVC, SSIZE_T is available in capital letters using #include <BaseTsd.h>
" int i;\n"
" scanf(\"%zd\", &s);\n"
" scanf(\"%zd%i\", &s, &i);\n"
" scanf(\"%zu\", &s);\n"
"}", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("[test.cpp:6]: (portability) %zu in format string (no. 1) requires 'size_t *' but the argument type is 'SSIZE_T * {aka signed long *}'.\n", errout_str());
check("void foo() {\n"
" SSIZE_T s;\n" // In MSVC, SSIZE_T is available in capital letters using #include <BaseTsd.h>
" int i;\n"
" scanf(\"%zd\", &s);\n"
" scanf(\"%zd%i\", &s, &i);\n"
" scanf(\"%zu\", &s);\n"
"}", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Win64));
ASSERT_EQUALS("[test.cpp:6]: (portability) %zu in format string (no. 1) requires 'size_t *' but the argument type is 'SSIZE_T * {aka signed long long *}'.\n", errout_str());
check("void foo() {\n"
" SSIZE_T s;\n" // Under Unix, ssize_t has to be written in small letters. Not Cppcheck, but the compiler will report this.
" int i;\n"
" scanf(\"%zd\", &s);\n"
" scanf(\"%zd%i\", &s, &i);\n"
" scanf(\"%zu\", &s);\n"
"}", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Unix64));
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" typedef SSIZE_T ssize_t;\n" // Test using typedef
" ssize_t s;\n"
" int i;\n"
" scanf(\"%zd\", &s);\n"
" scanf(\"%zd%i\", &s, &i);\n"
" scanf(\"%zu\", &s);\n"
"}", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Win64));
ASSERT_EQUALS("[test.cpp:7]: (portability) %zu in format string (no. 1) requires 'size_t *' but the argument type is 'SSIZE_T * {aka signed long long *}'.\n", errout_str());
}
void testMicrosoftCStringFormatArguments() { // ticket #4920
check("void foo() {\n"
" unsigned __int32 u32;\n"
" String string;\n"
" string.Format(\"%I32d\", u32);\n"
" string.AppendFormat(\"%I32d\", u32);\n"
"}", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" unsigned __int32 u32;\n"
" CString string;\n"
" string.Format(\"%I32d\", u32);\n"
" string.AppendFormat(\"%I32d\", u32);\n"
"}", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Unix32));
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" unsigned __int32 u32;\n"
" CString string;\n"
" string.Format(\"%I32d\", u32);\n"
" string.AppendFormat(\"%I32d\", u32);\n"
" CString::Format(\"%I32d\", u32);\n"
"}", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("[test.cpp:4]: (portability) %I32d in format string (no. 1) requires '__int32' but the argument type is 'unsigned __int32 {aka unsigned int}'.\n"
"[test.cpp:5]: (portability) %I32d in format string (no. 1) requires '__int32' but the argument type is 'unsigned __int32 {aka unsigned int}'.\n"
"[test.cpp:6]: (portability) %I32d in format string (no. 1) requires '__int32' but the argument type is 'unsigned __int32 {aka unsigned int}'.\n", errout_str());
}
void testMicrosoftSecurePrintfArgument() {
check("void foo() {\n"
" int i;\n"
" unsigned int u;\n"
" _tprintf_s(_T(\"%d %u\"), u, i, 0);\n"
"}\n", dinit(CheckOptions, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("[test.cpp:4]: (warning) %d in format string (no. 1) requires 'int' but the argument type is 'unsigned int'.\n"
"[test.cpp:4]: (warning) %u in format string (no. 2) requires 'unsigned int' but the argument type is 'signed int'.\n"
"[test.cpp:4]: (warning) _tprintf_s format string requires 2 parameters but 3 are given.\n", errout_str());
check("void foo() {\n"
" int i;\n"
" unsigned int u;\n"
" _tprintf_s(_T(\"%d %u\"), u, i, 0);\n"
"}\n", dinit(CheckOptions, $.platform = Platform::Type::Win32W));
ASSERT_EQUALS("[test.cpp:4]: (warning) %d in format string (no. 1) requires 'int' but the argument type is 'unsigned int'.\n"
"[test.cpp:4]: (warning) %u in format string (no. 2) requires 'unsigned int' but the argument type is 'signed int'.\n"
"[test.cpp:4]: (warning) _tprintf_s format string requires 2 parameters but 3 are given.\n", errout_str());
check("void foo() {\n"
" int i;\n"
" unsigned int u;\n"
" printf_s(\"%d %u\", u, i, 0);\n"
"}\n", dinit(CheckOptions, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("[test.cpp:4]: (warning) %d in format string (no. 1) requires 'int' but the argument type is 'unsigned int'.\n"
"[test.cpp:4]: (warning) %u in format string (no. 2) requires 'unsigned int' but the argument type is 'signed int'.\n"
"[test.cpp:4]: (warning) printf_s format string requires 2 parameters but 3 are given.\n", errout_str());
check("void foo() {\n"
" int i;\n"
" unsigned int u;\n"
" wprintf_s(L\"%d %u\", u, i, 0);\n"
"}\n", dinit(CheckOptions, $.platform = Platform::Type::Win32W));
ASSERT_EQUALS("[test.cpp:4]: (warning) %d in format string (no. 1) requires 'int' but the argument type is 'unsigned int'.\n"
"[test.cpp:4]: (warning) %u in format string (no. 2) requires 'unsigned int' but the argument type is 'signed int'.\n"
"[test.cpp:4]: (warning) wprintf_s format string requires 2 parameters but 3 are given.\n", errout_str());
check("void foo() {\n"
" TCHAR str[10];\n"
" int i;\n"
" unsigned int u;\n"
" _stprintf_s(str, sizeof(str) / sizeof(TCHAR), _T(\"%d %u\"), u, i, 0);\n"
"}\n", dinit(CheckOptions, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("[test.cpp:5]: (warning) %d in format string (no. 1) requires 'int' but the argument type is 'unsigned int'.\n"
"[test.cpp:5]: (warning) %u in format string (no. 2) requires 'unsigned int' but the argument type is 'signed int'.\n"
"[test.cpp:5]: (warning) _stprintf_s format string requires 2 parameters but 3 are given.\n", errout_str());
check("void foo() {\n"
" TCHAR str[10];\n"
" int i;\n"
" unsigned int u;\n"
" _stprintf_s(str, sizeof(str) / sizeof(TCHAR), _T(\"%d %u\"), u, i, 0);\n"
"}\n", dinit(CheckOptions, $.platform = Platform::Type::Win32W));
ASSERT_EQUALS("[test.cpp:5]: (warning) %d in format string (no. 1) requires 'int' but the argument type is 'unsigned int'.\n"
"[test.cpp:5]: (warning) %u in format string (no. 2) requires 'unsigned int' but the argument type is 'signed int'.\n"
"[test.cpp:5]: (warning) _stprintf_s format string requires 2 parameters but 3 are given.\n", errout_str());
check("void foo() {\n"
" char str[10];\n"
" int i;\n"
" unsigned int u;\n"
" sprintf_s(str, sizeof(str), \"%d %u\", u, i, 0);\n"
"}\n", dinit(CheckOptions, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("[test.cpp:5]: (warning) %d in format string (no. 1) requires 'int' but the argument type is 'unsigned int'.\n"
"[test.cpp:5]: (warning) %u in format string (no. 2) requires 'unsigned int' but the argument type is 'signed int'.\n"
"[test.cpp:5]: (warning) sprintf_s format string requires 2 parameters but 3 are given.\n", errout_str());
check("void foo() {\n"
" char str[10];\n"
" int i;\n"
" unsigned int u;\n"
" sprintf_s(str, \"%d %u\", u, i, 0);\n"
"}\n", dinit(CheckOptions, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("[test.cpp:5]: (warning) %d in format string (no. 1) requires 'int' but the argument type is 'unsigned int'.\n"
"[test.cpp:5]: (warning) %u in format string (no. 2) requires 'unsigned int' but the argument type is 'signed int'.\n"
"[test.cpp:5]: (warning) sprintf_s format string requires 2 parameters but 3 are given.\n", errout_str());
check("void foo() {\n"
" wchar_t str[10];\n"
" int i;\n"
" unsigned int u;\n"
" swprintf_s(str, sizeof(str) / sizeof(wchar_t), L\"%d %u\", u, i, 0);\n"
"}\n", dinit(CheckOptions, $.platform = Platform::Type::Win32W));
ASSERT_EQUALS("[test.cpp:5]: (warning) %d in format string (no. 1) requires 'int' but the argument type is 'unsigned int'.\n"
"[test.cpp:5]: (warning) %u in format string (no. 2) requires 'unsigned int' but the argument type is 'signed int'.\n"
"[test.cpp:5]: (warning) swprintf_s format string requires 2 parameters but 3 are given.\n", errout_str());
check("void foo() {\n"
" wchar_t str[10];\n"
" int i;\n"
" unsigned int u;\n"
" swprintf_s(str, L\"%d %u\", u, i, 0);\n"
"}\n", dinit(CheckOptions, $.platform = Platform::Type::Win32W));
ASSERT_EQUALS("[test.cpp:5]: (warning) %d in format string (no. 1) requires 'int' but the argument type is 'unsigned int'.\n"
"[test.cpp:5]: (warning) %u in format string (no. 2) requires 'unsigned int' but the argument type is 'signed int'.\n"
"[test.cpp:5]: (warning) swprintf_s format string requires 2 parameters but 3 are given.\n", errout_str());
check("void foo() {\n"
" TCHAR str[10];\n"
" int i;\n"
" unsigned int u;\n"
" _sntprintf_s(str, sizeof(str) / sizeof(TCHAR), _TRUNCATE, _T(\"%d %u\"), u, i, 0);\n"
"}\n", dinit(CheckOptions, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("[test.cpp:5]: (warning) %d in format string (no. 1) requires 'int' but the argument type is 'unsigned int'.\n"
"[test.cpp:5]: (warning) %u in format string (no. 2) requires 'unsigned int' but the argument type is 'signed int'.\n"
"[test.cpp:5]: (warning) _sntprintf_s format string requires 2 parameters but 3 are given.\n", errout_str());
check("void foo() {\n"
" TCHAR str[10];\n"
" int i;\n"
" unsigned int u;\n"
" _sntprintf_s(str, sizeof(str) / sizeof(TCHAR), _TRUNCATE, _T(\"%d %u\"), u, i, 0);\n"
"}\n", dinit(CheckOptions, $.platform = Platform::Type::Win32W));
ASSERT_EQUALS("[test.cpp:5]: (warning) %d in format string (no. 1) requires 'int' but the argument type is 'unsigned int'.\n"
"[test.cpp:5]: (warning) %u in format string (no. 2) requires 'unsigned int' but the argument type is 'signed int'.\n"
"[test.cpp:5]: (warning) _sntprintf_s format string requires 2 parameters but 3 are given.\n", errout_str());
check("void foo() {\n"
" char str[10];\n"
" int i;\n"
" unsigned int u;\n"
" _snprintf_s(str, sizeof(str), _TRUNCATE, \"%d %u\", u, i, 0);\n"
"}\n", dinit(CheckOptions, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("[test.cpp:5]: (warning) %d in format string (no. 1) requires 'int' but the argument type is 'unsigned int'.\n"
"[test.cpp:5]: (warning) %u in format string (no. 2) requires 'unsigned int' but the argument type is 'signed int'.\n"
"[test.cpp:5]: (warning) _snprintf_s format string requires 2 parameters but 3 are given.\n", errout_str());
check("void foo() {\n"
" wchar_t str[10];\n"
" int i;\n"
" unsigned int u;\n"
" _snwprintf_s(str, sizeof(str) / sizeof(wchar_t), _TRUNCATE, L\"%d %u\", u, i, 0);\n"
"}\n", dinit(CheckOptions, $.platform = Platform::Type::Win32W));
ASSERT_EQUALS("[test.cpp:5]: (warning) %d in format string (no. 1) requires 'int' but the argument type is 'unsigned int'.\n"
"[test.cpp:5]: (warning) %u in format string (no. 2) requires 'unsigned int' but the argument type is 'signed int'.\n"
"[test.cpp:5]: (warning) _snwprintf_s format string requires 2 parameters but 3 are given.\n", errout_str());
check("void foo(FILE * fp) {\n"
" int i;\n"
" unsigned int u;\n"
" _ftprintf_s(fp, _T(\"%d %u\"), u, i, 0);\n"
"}\n", dinit(CheckOptions, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("[test.cpp:4]: (warning) %d in format string (no. 1) requires 'int' but the argument type is 'unsigned int'.\n"
"[test.cpp:4]: (warning) %u in format string (no. 2) requires 'unsigned int' but the argument type is 'signed int'.\n"
"[test.cpp:4]: (warning) _ftprintf_s format string requires 2 parameters but 3 are given.\n", errout_str());
check("void foo(FILE * fp) {\n"
" int i;\n"
" unsigned int u;\n"
" _ftprintf_s(fp, _T(\"%d %u\"), u, i, 0);\n"
"}\n", dinit(CheckOptions, $.platform = Platform::Type::Win32W));
ASSERT_EQUALS("[test.cpp:4]: (warning) %d in format string (no. 1) requires 'int' but the argument type is 'unsigned int'.\n"
"[test.cpp:4]: (warning) %u in format string (no. 2) requires 'unsigned int' but the argument type is 'signed int'.\n"
"[test.cpp:4]: (warning) _ftprintf_s format string requires 2 parameters but 3 are given.\n", errout_str());
check("void foo(FILE * fp) {\n"
" int i;\n"
" unsigned int u;\n"
" fprintf_s(fp, \"%d %u\", u, i, 0);\n"
"}\n", dinit(CheckOptions, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("[test.cpp:4]: (warning) %d in format string (no. 1) requires 'int' but the argument type is 'unsigned int'.\n"
"[test.cpp:4]: (warning) %u in format string (no. 2) requires 'unsigned int' but the argument type is 'signed int'.\n"
"[test.cpp:4]: (warning) fprintf_s format string requires 2 parameters but 3 are given.\n", errout_str());
check("void foo(FILE * fp) {\n"
" int i;\n"
" unsigned int u;\n"
" fwprintf_s(fp, L\"%d %u\", u, i, 0);\n"
"}\n", dinit(CheckOptions, $.platform = Platform::Type::Win32W));
ASSERT_EQUALS("[test.cpp:4]: (warning) %d in format string (no. 1) requires 'int' but the argument type is 'unsigned int'.\n"
"[test.cpp:4]: (warning) %u in format string (no. 2) requires 'unsigned int' but the argument type is 'signed int'.\n"
"[test.cpp:4]: (warning) fwprintf_s format string requires 2 parameters but 3 are given.\n", errout_str());
check("void foo() {\n"
" char lineBuffer [600];\n"
" const char * const format = \"%15s%17s%17s%17s%17s\";\n"
" sprintf_s(lineBuffer, 600, format, \"type\", \"sum\", \"avg\", \"min\", \"max\");\n"
" sprintf_s(lineBuffer, format, \"type\", \"sum\", \"avg\", \"min\", \"max\");\n"
"}\n", dinit(CheckOptions, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" const char * const format1 = \"%15s%17s%17s%17s%17s\";\n"
" const char format2[] = \"%15s%17s%17s%17s%17s\";\n"
" const char * const format3 = format1;\n"
" int i = 0;\n"
" sprintf_s(lineBuffer, format1, \"type\", \"sum\", \"avg\", \"min\", i, 0);\n"
" sprintf_s(lineBuffer, format2, \"type\", \"sum\", \"avg\", \"min\", i, 0);\n"
" sprintf_s(lineBuffer, format3, \"type\", \"sum\", \"avg\", \"min\", i, 0);\n"
" sprintf(lineBuffer, format1, \"type\", \"sum\", \"avg\", \"min\", i, 0);\n"
" sprintf(lineBuffer, format2, \"type\", \"sum\", \"avg\", \"min\", i, 0);\n"
" sprintf(lineBuffer, format3, \"type\", \"sum\", \"avg\", \"min\", i, 0);\n"
" printf(format1, \"type\", \"sum\", \"avg\", \"min\", i, 0);\n"
" printf(format2, \"type\", \"sum\", \"avg\", \"min\", i, 0);\n"
" printf(format3, \"type\", \"sum\", \"avg\", \"min\", i, 0);\n"
" sprintf_s(lineBuffer, 100, format1, \"type\", \"sum\", \"avg\", \"min\", i, 0);\n"
" sprintf_s(lineBuffer, 100, format2, \"type\", \"sum\", \"avg\", \"min\", i, 0);\n"
" sprintf_s(lineBuffer, 100, format3, \"type\", \"sum\", \"avg\", \"min\", i, 0);\n"
"}\n", dinit(CheckOptions, $.inconclusive = true, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("[test.cpp:6]: (warning) %s in format string (no. 5) requires 'char *' but the argument type is 'signed int'.\n"
"[test.cpp:6]: (warning) sprintf_s format string requires 5 parameters but 6 are given.\n"
"[test.cpp:7]: (warning) %s in format string (no. 5) requires 'char *' but the argument type is 'signed int'.\n"
"[test.cpp:7]: (warning) sprintf_s format string requires 5 parameters but 6 are given.\n"
"[test.cpp:8]: (warning) %s in format string (no. 5) requires 'char *' but the argument type is 'signed int'.\n"
"[test.cpp:8]: (warning) sprintf_s format string requires 5 parameters but 6 are given.\n"
"[test.cpp:9]: (warning) %s in format string (no. 5) requires 'char *' but the argument type is 'signed int'.\n"
"[test.cpp:9]: (warning) sprintf format string requires 5 parameters but 6 are given.\n"
"[test.cpp:10]: (warning) %s in format string (no. 5) requires 'char *' but the argument type is 'signed int'.\n"
"[test.cpp:10]: (warning) sprintf format string requires 5 parameters but 6 are given.\n"
"[test.cpp:11]: (warning) %s in format string (no. 5) requires 'char *' but the argument type is 'signed int'.\n"
"[test.cpp:11]: (warning) sprintf format string requires 5 parameters but 6 are given.\n"
"[test.cpp:12]: (warning) %s in format string (no. 5) requires 'char *' but the argument type is 'signed int'.\n"
"[test.cpp:12]: (warning) printf format string requires 5 parameters but 6 are given.\n"
"[test.cpp:13]: (warning) %s in format string (no. 5) requires 'char *' but the argument type is 'signed int'.\n"
"[test.cpp:13]: (warning) printf format string requires 5 parameters but 6 are given.\n"
"[test.cpp:14]: (warning) %s in format string (no. 5) requires 'char *' but the argument type is 'signed int'.\n"
"[test.cpp:14]: (warning) printf format string requires 5 parameters but 6 are given.\n"
"[test.cpp:15]: (warning) %s in format string (no. 5) requires 'char *' but the argument type is 'signed int'.\n"
"[test.cpp:15]: (warning) sprintf_s format string requires 5 parameters but 6 are given.\n"
"[test.cpp:16]: (warning) %s in format string (no. 5) requires 'char *' but the argument type is 'signed int'.\n"
"[test.cpp:16]: (warning) sprintf_s format string requires 5 parameters but 6 are given.\n"
"[test.cpp:17]: (warning) %s in format string (no. 5) requires 'char *' but the argument type is 'signed int'.\n"
"[test.cpp:17]: (warning) sprintf_s format string requires 5 parameters but 6 are given.\n", errout_str());
}
void testMicrosoftSecureScanfArgument() {
check("void foo() {\n"
" int i;\n"
" unsigned int u;\n"
" TCHAR str[10];\n"
" _tscanf_s(_T(\"%s %d %u %[a-z]\"), str, 10, &u, &i, str, 10, 0)\n"
"}\n", dinit(CheckOptions, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("[test.cpp:5]: (warning) %d in format string (no. 2) requires 'int *' but the argument type is 'unsigned int *'.\n"
"[test.cpp:5]: (warning) %u in format string (no. 3) requires 'unsigned int *' but the argument type is 'signed int *'.\n"
"[test.cpp:5]: (warning) _tscanf_s format string requires 6 parameters but 7 are given.\n", errout_str());
check("void foo() {\n"
" int i;\n"
" unsigned int u;\n"
" TCHAR str[10];\n"
" _tscanf_s(_T(\"%s %d %u %[a-z]\"), str, 10, &u, &i, str, 10, 0)\n"
"}\n", dinit(CheckOptions, $.platform = Platform::Type::Win32W));
ASSERT_EQUALS("[test.cpp:5]: (warning) %d in format string (no. 2) requires 'int *' but the argument type is 'unsigned int *'.\n"
"[test.cpp:5]: (warning) %u in format string (no. 3) requires 'unsigned int *' but the argument type is 'signed int *'.\n"
"[test.cpp:5]: (warning) _tscanf_s format string requires 6 parameters but 7 are given.\n", errout_str());
check("void foo() {\n"
" int i;\n"
" unsigned int u;\n"
" char str[10];\n"
" scanf_s(\"%s %d %u %[a-z]\", str, 10, &u, &i, str, 10, 0)\n"
"}\n", dinit(CheckOptions, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("[test.cpp:5]: (warning) %d in format string (no. 2) requires 'int *' but the argument type is 'unsigned int *'.\n"
"[test.cpp:5]: (warning) %u in format string (no. 3) requires 'unsigned int *' but the argument type is 'signed int *'.\n"
"[test.cpp:5]: (warning) scanf_s format string requires 6 parameters but 7 are given.\n", errout_str());
check("void foo() {\n"
" int i;\n"
" unsigned int u;\n"
" wchar_t str[10];\n"
" wscanf_s(L\"%s %d %u %[a-z]\", str, 10, &u, &i, str, 10, 0)\n"
"}\n", dinit(CheckOptions, $.platform = Platform::Type::Win32W));
ASSERT_EQUALS("[test.cpp:5]: (warning) %d in format string (no. 2) requires 'int *' but the argument type is 'unsigned int *'.\n"
"[test.cpp:5]: (warning) %u in format string (no. 3) requires 'unsigned int *' but the argument type is 'signed int *'.\n"
"[test.cpp:5]: (warning) wscanf_s format string requires 6 parameters but 7 are given.\n", errout_str());
check("void f() {\n"
" char str[8];\n"
" scanf_s(\"%8c\", str, sizeof(str));\n"
" scanf_s(\"%9c\", str, sizeof(str));\n"
"}\n", dinit(CheckOptions, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("[test.cpp:4]: (error) Width 9 given in format string (no. 1) is larger than destination buffer 'str[8]', use %8c to prevent overflowing it.\n", errout_str());
check("void foo() {\n"
" TCHAR txt[100];\n"
" int i;\n"
" unsigned int u;\n"
" TCHAR str[10];\n"
" _stscanf_s(txt, _T(\"%s %d %u %[a-z]\"), str, 10, &u, &i, str, 10, 0)\n"
"}\n", dinit(CheckOptions, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("[test.cpp:6]: (warning) %d in format string (no. 2) requires 'int *' but the argument type is 'unsigned int *'.\n"
"[test.cpp:6]: (warning) %u in format string (no. 3) requires 'unsigned int *' but the argument type is 'signed int *'.\n"
"[test.cpp:6]: (warning) _stscanf_s format string requires 6 parameters but 7 are given.\n", errout_str());
check("void foo() {\n"
" TCHAR txt[100];\n"
" int i;\n"
" unsigned int u;\n"
" TCHAR str[10];\n"
" _stscanf_s(txt, _T(\"%s %d %u %[a-z]\"), str, 10, &u, &i, str, 10, 0)\n"
"}\n", dinit(CheckOptions, $.platform = Platform::Type::Win32W));
ASSERT_EQUALS("[test.cpp:6]: (warning) %d in format string (no. 2) requires 'int *' but the argument type is 'unsigned int *'.\n"
"[test.cpp:6]: (warning) %u in format string (no. 3) requires 'unsigned int *' but the argument type is 'signed int *'.\n"
"[test.cpp:6]: (warning) _stscanf_s format string requires 6 parameters but 7 are given.\n", errout_str());
check("void foo() {\n"
" char txt[100];\n"
" int i;\n"
" unsigned int u;\n"
" char str[10];\n"
" sscanf_s(txt, \"%s %d %u %[a-z]\", str, 10, &u, &i, str, 10, 0)\n"
"}\n", dinit(CheckOptions, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("[test.cpp:6]: (warning) %d in format string (no. 2) requires 'int *' but the argument type is 'unsigned int *'.\n"
"[test.cpp:6]: (warning) %u in format string (no. 3) requires 'unsigned int *' but the argument type is 'signed int *'.\n"
"[test.cpp:6]: (warning) sscanf_s format string requires 6 parameters but 7 are given.\n", errout_str());
check("void foo() {\n"
" wchar_t txt[100];\n"
" int i;\n"
" unsigned int u;\n"
" wchar_t str[10];\n"
" swscanf_s(txt, L\"%s %d %u %[a-z]\", str, 10, &u, &i, str, 10, 0)\n"
"}\n", dinit(CheckOptions, $.platform = Platform::Type::Win32W));
ASSERT_EQUALS("[test.cpp:6]: (warning) %d in format string (no. 2) requires 'int *' but the argument type is 'unsigned int *'.\n"
"[test.cpp:6]: (warning) %u in format string (no. 3) requires 'unsigned int *' but the argument type is 'signed int *'.\n"
"[test.cpp:6]: (warning) swscanf_s format string requires 6 parameters but 7 are given.\n", errout_str());
check("void foo(FILE * fp) {\n"
" int i;\n"
" unsigned int u;\n"
" TCHAR str[10];\n"
" _ftscanf_s(fp, _T(\"%s %d %u %[a-z]\"), str, 10, &u, &i, str, 10, 0)\n"
"}\n", dinit(CheckOptions, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("[test.cpp:5]: (warning) %d in format string (no. 2) requires 'int *' but the argument type is 'unsigned int *'.\n"
"[test.cpp:5]: (warning) %u in format string (no. 3) requires 'unsigned int *' but the argument type is 'signed int *'.\n"
"[test.cpp:5]: (warning) _ftscanf_s format string requires 6 parameters but 7 are given.\n", errout_str());
check("void foo(FILE * fp) {\n"
" int i;\n"
" unsigned int u;\n"
" TCHAR str[10];\n"
" _ftscanf_s(fp, _T(\"%s %d %u %[a-z]\"), str, 10, &u, &i, str, 10, 0)\n"
"}\n", dinit(CheckOptions, $.platform = Platform::Type::Win32W));
ASSERT_EQUALS("[test.cpp:5]: (warning) %d in format string (no. 2) requires 'int *' but the argument type is 'unsigned int *'.\n"
"[test.cpp:5]: (warning) %u in format string (no. 3) requires 'unsigned int *' but the argument type is 'signed int *'.\n"
"[test.cpp:5]: (warning) _ftscanf_s format string requires 6 parameters but 7 are given.\n", errout_str());
check("void foo(FILE * fp) {\n"
" int i;\n"
" unsigned int u;\n"
" char str[10];\n"
" fscanf_s(fp, \"%s %d %u %[a-z]\", str, 10, &u, &i, str, 10, 0)\n"
"}\n", dinit(CheckOptions, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("[test.cpp:5]: (warning) %d in format string (no. 2) requires 'int *' but the argument type is 'unsigned int *'.\n"
"[test.cpp:5]: (warning) %u in format string (no. 3) requires 'unsigned int *' but the argument type is 'signed int *'.\n"
"[test.cpp:5]: (warning) fscanf_s format string requires 6 parameters but 7 are given.\n", errout_str());
check("void foo(FILE * fp) {\n"
" int i;\n"
" unsigned int u;\n"
" wchar_t str[10];\n"
" fwscanf_s(fp, L\"%s %d %u %[a-z]\", str, 10, &u, &i, str, 10, 0)\n"
"}\n", dinit(CheckOptions, $.platform = Platform::Type::Win32W));
ASSERT_EQUALS("[test.cpp:5]: (warning) %d in format string (no. 2) requires 'int *' but the argument type is 'unsigned int *'.\n"
"[test.cpp:5]: (warning) %u in format string (no. 3) requires 'unsigned int *' but the argument type is 'signed int *'.\n"
"[test.cpp:5]: (warning) fwscanf_s format string requires 6 parameters but 7 are given.\n", errout_str());
check("void foo() {\n"
" WCHAR msStr1[5] = {0};\n"
" wscanf_s(L\"%4[^-]\", msStr1, _countof(msStr1));\n"
"}\n", dinit(CheckOptions, $.platform = Platform::Type::Win32W));
ASSERT_EQUALS("", errout_str());
}
void testQStringFormatArguments() {
check("void foo(float f) {\n"
" QString string;\n"
" string.sprintf(\"%d\", f);\n"
"}", dinit(CheckOptions, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("[test.cpp:3]: (warning) %d in format string (no. 1) requires 'int' but the argument type is 'float'.\n", errout_str());
check("void foo(float f) {\n"
" QString string;\n"
" string = QString::asprintf(\"%d\", f);\n"
"}", dinit(CheckOptions, $.platform = Platform::Type::Win32A));
ASSERT_EQUALS("[test.cpp:3]: (warning) %d in format string (no. 1) requires 'int' but the argument type is 'float'.\n", errout_str());
}
void testTernary() { // ticket #6182
check("void test(const std::string &val) {\n"
" printf(\"%s\", val.empty() ? \"I like to eat bananas\" : val.c_str());\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void testUnsignedConst() { // ticket #6321
check("void test() {\n"
" unsigned const x = 5;\n"
" printf(\"%u\", x);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void testAstType() { // ticket #7014
check("void test() {\n"
" printf(\"%c\", \"hello\"[0]);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void test() {\n"
" printf(\"%lld\", (long long)1);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void test() {\n"
" printf(\"%i\", (short *)x);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) %i in format string (no. 1) requires 'int' but the argument type is 'signed short *'.\n", errout_str());
check("int (*fp)();\n" // #7178 - function pointer call
"void test() {\n"
" printf(\"%i\", fp());\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void testPrintf0WithSuffix() { // ticket #7069
check("void foo() {\n"
" printf(\"%u %lu %llu\", 0U, 0UL, 0ULL);\n"
" printf(\"%u %lu %llu\", 0u, 0ul, 0ull);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void testReturnValueTypeStdLib() {
check("void f() {\n"
" const char *s = \"0\";\n"
" printf(\"%ld%lld\", atol(s), atoll(s));\n"
"}");
ASSERT_EQUALS("", errout_str());
// 8141
check("void f(int i) {\n"
" printf(\"%f\", imaxabs(i));\n"
"}\n", dinit(CheckOptions, $.portability = true, $.platform = Platform::Type::Unix64));
ASSERT_EQUALS("[test.cpp:2]: (portability) %f in format string (no. 1) requires 'double' but the argument type is 'intmax_t {aka signed long}'.\n", errout_str());
}
void testPrintfTypeAlias1() {
check("using INT = int;\n\n"
"using PINT = INT *;\n"
"using PCINT = const PINT;\n"
"INT i;\n"
"PINT pi;\n"
"PCINT pci;"
"void foo() {\n"
" printf(\"%d %p %p\", i, pi, pci);\n"
"};");
ASSERT_EQUALS("", errout_str());
check("using INT = int;\n\n"
"using PINT = INT *;\n"
"using PCINT = const PINT;\n"
"INT i;\n"
"PINT pi;\n"
"PCINT pci;"
"void foo() {\n"
" printf(\"%f %f %f\", i, pi, pci);\n"
"};");
ASSERT_EQUALS("[test.cpp:8]: (warning) %f in format string (no. 1) requires 'double' but the argument type is 'signed int'.\n"
"[test.cpp:8]: (warning) %f in format string (no. 2) requires 'double' but the argument type is 'signed int *'.\n"
"[test.cpp:8]: (warning) %f in format string (no. 3) requires 'double' but the argument type is 'const signed int *'.\n", errout_str());
}
void testPrintfAuto() { // #8992
check("void f() {\n"
" auto s = sizeof(int);\n"
" printf(\"%zu\", s);\n"
" printf(\"%f\", s);\n"
"}\n", dinit(CheckOptions, $.portability = true));
ASSERT_EQUALS("[test.cpp:4]: (portability) %f in format string (no. 1) requires 'double' but the argument type is 'size_t {aka unsigned long}'.\n", errout_str());
}
void testPrintfParenthesis() { // #8489
check("void f(int a) {\n"
" printf(\"%f\", (a >> 24) & 0xff);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) %f in format string (no. 1) requires 'double' but the argument type is 'signed int'.\n", errout_str());
check("void f(int a) {\n"
" printf(\"%f\", 0xff & (a >> 24));\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) %f in format string (no. 1) requires 'double' but the argument type is 'signed int'.\n", errout_str());
check("void f(int a) {\n"
" printf(\"%f\", ((a >> 24) + 1) & 0xff);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) %f in format string (no. 1) requires 'double' but the argument type is 'signed int'.\n", errout_str());
}
void testStdDistance() { // #10304
check("void foo(const std::vector<int>& IO, const int* pio) {\n"
"const auto Idx = std::distance(&IO.front(), pio);\n"
"printf(\"Idx = %td\", Idx);\n"
"}", dinit(CheckOptions, $.portability = true));
ASSERT_EQUALS("", errout_str());
}
void testParameterPack() { // #11289
check("template <typename... Args> auto f(const char* format, const Args&... args) {\n"
" return snprintf(nullptr, 0, format, args...);\n"
"}\n"
"void g() {\n"
" f(\"%d%d\", 1, 2);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
};
REGISTER_TEST(TestIO)
| null |
953 | cpp | cppcheck | fixture.h | test/fixture.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef fixtureH
#define fixtureH
#include "check.h"
#include "color.h"
#include "config.h"
#include "errorlogger.h"
#include "platform.h"
#include "settings.h"
#include "standards.h"
#include <cstddef>
#include <cstdint>
#include <list>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <utility>
class options;
class Tokenizer;
enum class Certainty : std::uint8_t;
enum class Severity : std::uint8_t;
class TestFixture : public ErrorLogger {
private:
static std::ostringstream errmsg;
static unsigned int countTests;
static std::size_t fails_counter;
static std::size_t todos_counter;
static std::size_t succeeded_todos_counter;
bool mVerbose{};
std::string mTemplateFormat;
std::string mTemplateLocation;
std::string mTestname;
protected:
std::string exename;
std::string testToRun;
bool quiet_tests{};
bool dry_run{};
virtual void run() = 0;
bool prepareTest(const char testname[]);
virtual void prepareTestInternal() {}
void teardownTest();
virtual void teardownTestInternal() {}
std::string getLocationStr(const char * filename, unsigned int linenr) const;
void assert_(const char * filename, unsigned int linenr, bool condition) const;
template<typename T>
void assertEquals(const char* const filename, const unsigned int linenr, const T& expected, const T& actual, const std::string& msg = emptyString) const {
if (expected != actual) {
std::ostringstream expectedStr;
expectedStr << expected;
std::ostringstream actualStr;
actualStr << actual;
assertFailure(filename, linenr, expectedStr.str(), actualStr.str(), msg);
}
}
template<typename T>
void assertEqualsEnum(const char* const filename, const unsigned int linenr, const T& expected, const T& actual, const std::string& msg = emptyString) const {
if (std::is_unsigned<T>())
assertEquals(filename, linenr, static_cast<std::uint64_t>(expected), static_cast<std::uint64_t>(actual), msg);
else
assertEquals(filename, linenr, static_cast<std::int64_t>(expected), static_cast<std::int64_t>(actual), msg);
}
template<typename T>
void todoAssertEqualsEnum(const char* const filename, const unsigned int linenr, const T& wanted, const T& current, const T& actual) const {
if (std::is_unsigned<T>())
todoAssertEquals(filename, linenr, static_cast<std::uint64_t>(wanted), static_cast<std::uint64_t>(current), static_cast<std::uint64_t>(actual));
else
todoAssertEquals(filename, linenr, static_cast<std::int64_t>(wanted), static_cast<std::int64_t>(current), static_cast<std::int64_t>(actual));
}
void assertEquals(const char * filename, unsigned int linenr, const std::string &expected, const std::string &actual, const std::string &msg = emptyString) const;
void assertEqualsWithoutLineNumbers(const char * filename, unsigned int linenr, const std::string &expected, const std::string &actual, const std::string &msg = emptyString) const;
void assertEquals(const char * filename, unsigned int linenr, const char expected[], const std::string& actual, const std::string &msg = emptyString) const;
void assertEquals(const char * filename, unsigned int linenr, const char expected[], const char actual[], const std::string &msg = emptyString) const;
void assertEquals(const char * filename, unsigned int linenr, const std::string& expected, const char actual[], const std::string &msg = emptyString) const;
void assertEquals(const char * filename, unsigned int linenr, long long expected, long long actual, const std::string &msg = emptyString) const;
void assertEqualsDouble(const char * filename, unsigned int linenr, double expected, double actual, double tolerance, const std::string &msg = emptyString) const;
void todoAssertEquals(const char * filename, unsigned int linenr, const std::string &wanted,
const std::string ¤t, const std::string &actual) const;
void todoAssertEquals(const char * filename, unsigned int linenr, const char wanted[],
const char current[], const std::string &actual) const;
void todoAssertEquals(const char * filename, unsigned int linenr, long long wanted,
long long current, long long actual) const;
void assertThrow(const char * filename, unsigned int linenr) const;
void assertThrowFail(const char * filename, unsigned int linenr) const;
void assertNoThrowFail(const char * filename, unsigned int linenr) const;
static std::string deleteLineNumber(const std::string &message);
void setVerbose(bool v) {
mVerbose = v;
}
void setTemplateFormat(const std::string &templateFormat);
void setMultiline() {
setTemplateFormat("multiline");
}
void processOptions(const options& args);
template<typename T>
static T& getCheck()
{
for (Check *check : Check::instances()) {
//cppcheck-suppress useStlAlgorithm
if (T* c = dynamic_cast<T*>(check))
return *c;
}
throw std::runtime_error("instance not found");
}
template<typename T>
static void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger)
{
Check& check = getCheck<T>();
check.runChecks(tokenizer, errorLogger);
}
class SettingsBuilder
{
public:
explicit SettingsBuilder(const TestFixture &fixture) : fixture(fixture) {}
SettingsBuilder(const TestFixture &fixture, Settings settings) : fixture(fixture), settings(std::move(settings)) {}
SettingsBuilder& severity(Severity sev, bool b = true) {
if (REDUNDANT_CHECK && settings.severity.isEnabled(sev) == b)
throw std::runtime_error("redundant setting: severity");
settings.severity.setEnabled(sev, b);
return *this;
}
SettingsBuilder& certainty(Certainty cert, bool b = true) {
if (REDUNDANT_CHECK && settings.certainty.isEnabled(cert) == b)
throw std::runtime_error("redundant setting: certainty");
settings.certainty.setEnabled(cert, b);
return *this;
}
SettingsBuilder& clang() {
if (REDUNDANT_CHECK && settings.clang)
throw std::runtime_error("redundant setting: clang");
settings.clang = true;
return *this;
}
SettingsBuilder& checkLibrary() {
if (REDUNDANT_CHECK && settings.checkLibrary)
throw std::runtime_error("redundant setting: checkLibrary");
settings.checkLibrary = true;
return *this;
}
SettingsBuilder& checkUnusedTemplates(bool b = true) {
if (REDUNDANT_CHECK && settings.checkUnusedTemplates == b)
throw std::runtime_error("redundant setting: checkUnusedTemplates");
settings.checkUnusedTemplates = b;
return *this;
}
SettingsBuilder& debugwarnings(bool b = true) {
if (REDUNDANT_CHECK && settings.debugwarnings == b)
throw std::runtime_error("redundant setting: debugwarnings");
settings.debugwarnings = b;
return *this;
}
SettingsBuilder& c(Standards::cstd_t std) {
// TODO: CLatest and C23 are the same - handle differently?
//if (REDUNDANT_CHECK && settings.standards.c == std)
// throw std::runtime_error("redundant setting: standards.c");
settings.standards.c = std;
return *this;
}
SettingsBuilder& cpp(Standards::cppstd_t std) {
// TODO: CPPLatest and CPP26 are the same - handle differently?
//if (REDUNDANT_CHECK && settings.standards.cpp == std)
// throw std::runtime_error("redundant setting: standards.cpp");
settings.standards.cpp = std;
return *this;
}
SettingsBuilder& checkLevel(Settings::CheckLevel level);
SettingsBuilder& library(const char lib[]);
SettingsBuilder& libraryxml(const char xmldata[], std::size_t len);
SettingsBuilder& platform(Platform::Type type);
SettingsBuilder& checkConfiguration() {
if (REDUNDANT_CHECK && settings.checkConfiguration)
throw std::runtime_error("redundant setting: checkConfiguration");
settings.checkConfiguration = true;
return *this;
}
SettingsBuilder& checkHeaders(bool b = true) {
if (REDUNDANT_CHECK && settings.checkHeaders == b)
throw std::runtime_error("redundant setting: checkHeaders");
settings.checkHeaders = b;
return *this;
}
Settings build() {
return std::move(settings);
}
private:
const TestFixture &fixture;
Settings settings;
const bool REDUNDANT_CHECK = false;
};
SettingsBuilder settingsBuilder() const {
return SettingsBuilder(*this);
}
SettingsBuilder settingsBuilder(Settings settings) const {
return SettingsBuilder(*this, std::move(settings));
}
std::string output_str() {
std::string s = mOutput.str();
mOutput.str("");
return s;
}
std::string errout_str() {
std::string s = mErrout.str();
mErrout.str("");
return s;
}
void ignore_errout() {
if (errout_str().empty())
throw std::runtime_error("no errout to ignore");
}
const Settings settingsDefault;
private:
//Helper function to be called when an assertEquals assertion fails.
//Writes the appropriate failure message to errmsg and increments fails_counter
void assertFailure(const char* filename, unsigned int linenr, const std::string& expected, const std::string& actual, const std::string& msg) const;
std::ostringstream mOutput;
std::ostringstream mErrout;
void reportOut(const std::string &outmsg, Color c = Color::Reset) override;
void reportErr(const ErrorMessage &msg) override;
void run(const std::string &str);
public:
static void printHelp();
const std::string classname;
explicit TestFixture(const char * _name);
static std::size_t runTests(const options& args);
};
class TestInstance {
public:
explicit TestInstance(const char * _name);
virtual ~TestInstance() = default;
virtual TestFixture* create() = 0;
const std::string classname;
protected:
std::unique_ptr<TestFixture> impl;
};
#define TEST_CASE( NAME ) do { if (prepareTest(#NAME)) { setVerbose(false); try { NAME(); teardownTest(); } catch (...) { assertNoThrowFail(__FILE__, __LINE__); } } } while (false)
// TODO: the asserts do not actually assert i.e. do stop executing the test
#define ASSERT( CONDITION ) assert_(__FILE__, __LINE__, (CONDITION))
#define ASSERT_LOC( CONDITION, FILE_, LINE_ ) assert_(FILE_, LINE_, (CONDITION))
// *INDENT-OFF*
#define ASSERT_EQUALS( EXPECTED, ACTUAL ) do { try { assertEquals(__FILE__, __LINE__, (EXPECTED), (ACTUAL)); } catch (...) { assertNoThrowFail(__FILE__, __LINE__); } } while (false)
// *INDENT-ON*
#define ASSERT_EQUALS_WITHOUT_LINENUMBERS( EXPECTED, ACTUAL ) assertEqualsWithoutLineNumbers(__FILE__, __LINE__, EXPECTED, ACTUAL)
#define ASSERT_EQUALS_DOUBLE( EXPECTED, ACTUAL, TOLERANCE ) assertEqualsDouble(__FILE__, __LINE__, EXPECTED, ACTUAL, TOLERANCE)
#define ASSERT_EQUALS_LOC_MSG( EXPECTED, ACTUAL, MSG, FILE_, LINE_ ) assertEquals(FILE_, LINE_, EXPECTED, ACTUAL, MSG)
#define ASSERT_EQUALS_MSG( EXPECTED, ACTUAL, MSG ) assertEquals(__FILE__, __LINE__, EXPECTED, ACTUAL, MSG)
#define ASSERT_EQUALS_ENUM( EXPECTED, ACTUAL ) assertEqualsEnum(__FILE__, __LINE__, (EXPECTED), (ACTUAL))
#define TODO_ASSERT_EQUALS_ENUM( WANTED, CURRENT, ACTUAL ) todoAssertEqualsEnum(__FILE__, __LINE__, WANTED, CURRENT, ACTUAL)
#define ASSERT_THROW_EQUALS( CMD, EXCEPTION, EXPECTED ) do { try { (void)(CMD); assertThrowFail(__FILE__, __LINE__); } catch (const EXCEPTION&e) { assertEquals(__FILE__, __LINE__, EXPECTED, e.errorMessage); } catch (...) { assertThrowFail(__FILE__, __LINE__); } } while (false)
#define ASSERT_THROW_EQUALS_2( CMD, EXCEPTION, EXPECTED ) do { try { (void)(CMD); assertThrowFail(__FILE__, __LINE__); } catch (const EXCEPTION&e) { assertEquals(__FILE__, __LINE__, EXPECTED, e.what()); } catch (...) { assertThrowFail(__FILE__, __LINE__); } } while (false)
#define ASSERT_THROW_INTERNAL( CMD, TYPE ) do { try { (void)(CMD); assertThrowFail(__FILE__, __LINE__); } catch (const InternalError& e) { assertEqualsEnum(__FILE__, __LINE__, InternalError::TYPE, e.type); } catch (...) { assertThrowFail(__FILE__, __LINE__); } } while (false)
#define ASSERT_THROW_INTERNAL_EQUALS( CMD, TYPE, EXPECTED ) do { try { (void)(CMD); assertThrowFail(__FILE__, __LINE__); } catch (const InternalError& e) { assertEqualsEnum(__FILE__, __LINE__, InternalError::TYPE, e.type); assertEquals(__FILE__, __LINE__, EXPECTED, e.errorMessage); } catch (...) { assertThrowFail(__FILE__, __LINE__); } } while (false)
#define ASSERT_NO_THROW( CMD ) do { try { (void)(CMD); } catch (...) { assertNoThrowFail(__FILE__, __LINE__); } } while (false)
#define TODO_ASSERT_THROW( CMD, EXCEPTION ) do { try { (void)(CMD); } catch (const EXCEPTION&) {} catch (...) { assertThrow(__FILE__, __LINE__); } } while (false)
#define TODO_ASSERT( CONDITION ) do { const bool condition=(CONDITION); todoAssertEquals(__FILE__, __LINE__, true, false, condition); } while (false)
#define TODO_ASSERT_EQUALS( WANTED, CURRENT, ACTUAL ) todoAssertEquals(__FILE__, __LINE__, WANTED, CURRENT, ACTUAL)
#define REGISTER_TEST( CLASSNAME ) namespace { class CLASSNAME ## Instance : public TestInstance { public: CLASSNAME ## Instance() : TestInstance(#CLASSNAME) {} TestFixture* create() override { impl.reset(new CLASSNAME); return impl.get(); } }; CLASSNAME ## Instance instance_ ## CLASSNAME; }
#define PLATFORM( P, T ) do { std::string errstr; assertEquals(__FILE__, __LINE__, true, P.set(Platform::toString(T), errstr, {exename}), errstr); } while (false)
#endif // fixtureH
| null |
954 | cpp | cppcheck | teststring.cpp | test/teststring.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "checkstring.h"
#include "errortypes.h"
#include "helpers.h"
#include "settings.h"
#include "fixture.h"
#include "tokenize.h"
#include <string>
#include <vector>
class TestString : public TestFixture {
public:
TestString() : TestFixture("TestString") {}
private:
const Settings settings = settingsBuilder().severity(Severity::warning).severity(Severity::style).build();
void run() override {
TEST_CASE(stringLiteralWrite);
TEST_CASE(alwaysTrueFalseStringCompare);
TEST_CASE(suspiciousStringCompare);
TEST_CASE(suspiciousStringCompare_char);
TEST_CASE(strPlusChar1); // "/usr" + '/'
TEST_CASE(strPlusChar2); // "/usr" + ch
TEST_CASE(strPlusChar3); // ok: path + "/sub" + '/'
TEST_CASE(strPlusChar4); // L"/usr" + L'/'
TEST_CASE(snprintf1); // Dangerous usage of snprintf
TEST_CASE(sprintf1); // Dangerous usage of sprintf
TEST_CASE(sprintf2);
TEST_CASE(sprintf3);
TEST_CASE(sprintf4); // struct member
TEST_CASE(sprintf5); // another struct member
TEST_CASE(sprintf6); // (char*)
TEST_CASE(sprintf7); // (char*)(void*)
TEST_CASE(wsprintf1); // Dangerous usage of wsprintf
TEST_CASE(incorrectStringCompare);
TEST_CASE(deadStrcmp);
}
#define check(...) check_(__FILE__, __LINE__, __VA_ARGS__)
void check_(const char* file, int line, const char code[], const char filename[] = "test.cpp") {
std::vector<std::string> files(1, filename);
Tokenizer tokenizer(settings, *this);
PreprocessorHelper::preprocess(code, files, tokenizer, *this);
// Tokenize..
ASSERT_LOC(tokenizer.simplifyTokens1(""), file, line);
// Check char variable usage..
runChecks<CheckString>(tokenizer, this);
}
void stringLiteralWrite() {
check("void f() {\n"
" char *abc = \"abc\";\n"
" abc[0] = 'a';\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:2]: (error) Modifying string literal \"abc\" directly or indirectly is undefined behaviour.\n", errout_str());
check("void f() {\n"
" char *abc = \"abc\";\n"
" *abc = 'a';\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:2]: (error) Modifying string literal \"abc\" directly or indirectly is undefined behaviour.\n", errout_str());
check("void f() {\n"
" char *abc = \"A very long string literal\";\n"
" abc[0] = 'a';\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:2]: (error) Modifying string literal \"A very long stri..\" directly or indirectly is undefined behaviour.\n", errout_str());
check("void f() {\n"
" QString abc = \"abc\";\n"
" abc[0] = 'a';\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo_FP1(char *p) {\n"
" p[1] = 'B';\n"
"}\n"
"void foo_FP2(void) {\n"
" char* s = \"Y\";\n"
" foo_FP1(s);\n"
"}");
ASSERT_EQUALS(
"[test.cpp:2] -> [test.cpp:5]: (error) Modifying string literal \"Y\" directly or indirectly is undefined behaviour.\n",
errout_str());
check("void foo_FP1(char *p) {\n"
" p[1] = 'B';\n"
"}\n"
"void foo_FP2(void) {\n"
" char s[10] = \"Y\";\n"
" foo_FP1(s);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" wchar_t *abc = L\"abc\";\n"
" abc[0] = u'a';\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:2]: (error) Modifying string literal L\"abc\" directly or indirectly is undefined behaviour.\n", errout_str());
check("void f() {\n"
" char16_t *abc = u\"abc\";\n"
" abc[0] = 'a';\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:2]: (error) Modifying string literal u\"abc\" directly or indirectly is undefined behaviour.\n", errout_str());
check("void foo() {\n" // #8332
" int i;\n"
" char *p = \"string literal\";\n"
" for( i = 0; i < strlen(p); i++) {\n"
" p[i] = \'X\';\n" // <<
" }\n"
" printf(\"%s\\n\", p);\n"
"}");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:3]: (error) Modifying string literal \"string literal\" directly or indirectly is undefined behaviour.\n", errout_str());
}
void alwaysTrueFalseStringCompare() {
check("void f() {\n"
" if (strcmp(\"A\",\"A\")){}\n"
" if (strncmp(\"A\",\"A\",1)){}\n"
" if (strcasecmp(\"A\",\"A\")){}\n"
" if (strncasecmp(\"A\",\"A\",1)){}\n"
" if (memcmp(\"A\",\"A\",1)){}\n"
" if (strverscmp(\"A\",\"A\")){}\n"
" if (bcmp(\"A\",\"A\",1)){}\n"
" if (wcsncasecmp(L\"A\",L\"A\",1)){}\n"
" if (wcsncmp(L\"A\",L\"A\",1)){}\n"
" if (wmemcmp(L\"A\",L\"A\",1)){}\n"
" if (wcscmp(L\"A\",L\"A\")){}\n"
" if (wcscasecmp(L\"A\",L\"A\")){}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Unnecessary comparison of static strings.\n"
"[test.cpp:3]: (warning) Unnecessary comparison of static strings.\n"
"[test.cpp:4]: (warning) Unnecessary comparison of static strings.\n"
"[test.cpp:5]: (warning) Unnecessary comparison of static strings.\n"
"[test.cpp:6]: (warning) Unnecessary comparison of static strings.\n"
"[test.cpp:7]: (warning) Unnecessary comparison of static strings.\n"
"[test.cpp:8]: (warning) Unnecessary comparison of static strings.\n"
"[test.cpp:9]: (warning) Unnecessary comparison of static strings.\n"
"[test.cpp:10]: (warning) Unnecessary comparison of static strings.\n"
"[test.cpp:11]: (warning) Unnecessary comparison of static strings.\n"
"[test.cpp:12]: (warning) Unnecessary comparison of static strings.\n"
"[test.cpp:13]: (warning) Unnecessary comparison of static strings.\n", errout_str());
// avoid false positives when the address is modified #6415
check("void f(void *p, int offset) {\n"
" if (!memcmp(p, p + offset, 42)){}\n"
" if (!memcmp(p + offset, p, 42)){}\n"
" if (!memcmp(offset + p, p, 42)){}\n"
" if (!memcmp(p, offset + p, 42)){}\n"
"}");
ASSERT_EQUALS("", errout_str());
// avoid false positives when the address is modified #6415
check("void f(char *c, int offset) {\n"
" if (!memcmp(c, c + offset, 42)){}\n"
" if (!memcmp(c + offset, c, 42)){}\n"
" if (!memcmp(offset + c, c, 42)){}\n"
" if (!memcmp(c, offset + c, 42)){}\n"
"}");
ASSERT_EQUALS("", errout_str());
// avoid false positives when the address is modified #6415
check("void f(std::string s, int offset) {\n"
" if (!memcmp(s.c_str(), s.c_str() + offset, 42)){}\n"
" if (!memcmp(s.c_str() + offset, s.c_str(), 42)){}\n"
" if (!memcmp(offset + s.c_str(), s.c_str(), 42)){}\n"
" if (!memcmp(s.c_str(), offset + s.c_str(), 42)){}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int main()\n"
"{\n"
" if (strcmp(\"00FF00\", \"00FF00\") == 0)"
" {"
" std::cout << \"Equal\";"
" }"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Unnecessary comparison of static strings.\n", errout_str());
check("void f() {\n"
" if (strcmp($\"00FF00\", \"00FF00\") == 0) {}"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" if ($strcmp(\"00FF00\", \"00FF00\") == 0) {}"
"}");
ASSERT_EQUALS("", errout_str());
check("int main()\n"
"{\n"
" if (stricmp(\"hotdog\",\"HOTdog\") == 0)"
" {"
" std::cout << \"Equal\";"
" }"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Unnecessary comparison of static strings.\n", errout_str());
check("int main()\n"
"{\n"
" if (QString::compare(\"Hamburger\", \"Hotdog\") == 0)"
" {"
" std::cout << \"Equal\";"
" }"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Unnecessary comparison of static strings.\n", errout_str());
check("int main()\n"
"{\n"
" if (QString::compare(argv[2], \"hotdog\") == 0)"
" {"
" std::cout << \"Equal\";"
" }"
"}");
ASSERT_EQUALS("", errout_str());
check("int main()\n"
"{\n"
" if (strncmp(\"hotdog\",\"hotdog\", 6) == 0)"
" {"
" std::cout << \"Equal\";"
" }"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Unnecessary comparison of static strings.\n", errout_str());
check("int foo(const char *buf)\n"
"{\n"
" if (strcmp(buf, buf) == 0)"
" {"
" std::cout << \"Equal\";"
" }"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Comparison of identical string variables.\n", errout_str());
check("int foo(const std::string& buf)\n"
"{\n"
" if (stricmp(buf.c_str(), buf.c_str()) == 0)"
" {"
" std::cout << \"Equal\";"
" }"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Comparison of identical string variables.\n", errout_str());
check("int main() {\n"
" if (\"str\" == \"str\") {\n"
" std::cout << \"Equal\";\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Unnecessary comparison of static strings.\n", errout_str());
check("int main() {\n"
" if (\"str\" != \"str\") {\n"
" std::cout << \"Equal\";\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Unnecessary comparison of static strings.\n", errout_str());
check("int main() {\n"
" if (a+\"str\" != \"str\"+b) {\n"
" std::cout << \"Equal\";\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void suspiciousStringCompare() {
check("bool foo(char* c) {\n"
" return c == \"x\";\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) String literal compared with variable 'c'. Did you intend to use strcmp() instead?\n", errout_str());
check("bool foo(char** c) {\n"
" return c[3] == \"x\";\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) String literal compared with variable 'c[3]'. Did you intend to use strcmp() instead?\n", errout_str());
check("bool foo(wchar_t* c) {\n"
" return c == L\"x\";\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) String literal compared with variable 'c'. Did you intend to use wcscmp() instead?\n", errout_str());
check("bool foo(const char* c) {\n"
" return \"x\" == c;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) String literal compared with variable 'c'. Did you intend to use strcmp() instead?\n", errout_str());
check("bool foo(char* c) {\n"
" return foo+\"x\" == c;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool foo(char* c) {\n"
" return \"x\" == c+foo;\n"
"}", "test.cpp");
ASSERT_EQUALS("", errout_str());
check("bool foo(char* c) {\n"
" return \"x\" == c+foo;\n"
"}", "test.c");
ASSERT_EQUALS("[test.c:2]: (warning) String literal compared with variable 'c+foo'. Did you intend to use strcmp() instead?\n", errout_str());
check("bool foo(Foo c) {\n"
" return \"x\" == c.foo;\n"
"}", "test.cpp");
ASSERT_EQUALS("", errout_str());
check("bool foo(Foo c) {\n"
" return \"x\" == c.foo;\n"
"}", "test.c");
ASSERT_EQUALS("[test.c:2]: (warning) String literal compared with variable 'c.foo'. Did you intend to use strcmp() instead?\n", errout_str());
check("bool foo(const std::string& c) {\n"
" return \"x\" == c;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool foo(const Foo* c) {\n"
" return \"x\" == c->bar();\n" // #4314
"}");
ASSERT_EQUALS("", errout_str());
// Ticket #4257
check("bool foo() {\n"
"MyString *str=Getter();\n"
"return *str==\"bug\"; }\n", "test.c");
ASSERT_EQUALS("[test.c:3]: (warning) String literal compared with variable '*str'. Did you intend to use strcmp() instead?\n", errout_str());
// Ticket #4257
check("bool foo() {\n"
"MyString *str=Getter();\n"
"return *str==\"bug\"; }");
ASSERT_EQUALS("", errout_str());
// Ticket #4257
check("bool foo() {\n"
"MyString **str=OtherGetter();\n"
"return *str==\"bug\"; }", "test.c");
ASSERT_EQUALS("[test.c:3]: (warning) String literal compared with variable '*str'. Did you intend to use strcmp() instead?\n", errout_str());
// Ticket #4257
check("bool foo() {\n"
"MyString str=OtherGetter2();\n"
"return &str==\"bug\"; }", "test.c");
ASSERT_EQUALS("[test.c:3]: (warning) String literal compared with variable '&str'. Did you intend to use strcmp() instead?\n", errout_str());
// Ticket #5734
check("int foo(char c) {\n"
"return c == '4';}", "test.cpp");
ASSERT_EQUALS("", errout_str());
check("int foo(char c) {\n"
"return c == '4';}", "test.c");
ASSERT_EQUALS("", errout_str());
check("int foo(char c) {\n"
"return c == \"42\"[0];}", "test.cpp");
ASSERT_EQUALS("", errout_str());
check("int foo(char c) {\n"
"return c == \"42\"[0];}", "test.c");
ASSERT_EQUALS("", errout_str());
// 5639 String literal compared with char buffer in a struct
check("struct Example {\n"
" char buffer[200];\n"
"};\n"
"void foo() {\n"
" struct Example example;\n"
" if (example.buffer == \"test\") ;\n"
"}\n", "test.cpp");
ASSERT_EQUALS("[test.cpp:6]: (warning) String literal compared with variable 'example.buffer'. Did you intend to use strcmp() instead?\n", errout_str());
check("struct Example {\n"
" char buffer[200];\n"
"};\n"
"void foo() {\n"
" struct Example example;\n"
" if (example.buffer == \"test\") ;\n"
"}\n", "test.c");
ASSERT_EQUALS("[test.c:6]: (warning) String literal compared with variable 'example.buffer'. Did you intend to use strcmp() instead?\n", errout_str());
// #9726
check("void f(std::vector<std::string> theArgs) {\n"
" std::string arg1(*theArgs.begin());\n"
" if(arg1 == \"aaa\") {}\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void suspiciousStringCompare_char() {
check("bool foo(char* c) {\n"
" return c == 'x';\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Char literal compared with pointer 'c'. Did you intend to dereference it?\n", errout_str());
check("bool foo(wchar_t* c) {\n"
" return c == L'x';\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Char literal compared with pointer 'c'. Did you intend to dereference it?\n", errout_str());
check("bool foo(char* c) {\n"
" return '\\0' != c;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Char literal compared with pointer 'c'. Did you intend to dereference it?\n", errout_str());
check("bool foo(char c) {\n"
" return c == '\\0';\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool foo(char* c) {\n"
" return c[0] == '\\0';\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool foo(char** c) {\n"
" return c[0] == '\\0';\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Char literal compared with pointer 'c[0]'. Did you intend to dereference it?\n", errout_str());
check("bool foo(char** c) {\n"
" return *c == '\\0';\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Char literal compared with pointer '*c'. Did you intend to dereference it?\n", errout_str());
check("bool foo(char c) {\n"
" return c == 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool foo(char* c) {\n"
" return *c == 0;\n"
"}", "test.c");
ASSERT_EQUALS("", errout_str());
check("bool foo(char* c) {\n"
" return *c == 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool foo(Foo* c) {\n"
" return 0 == c->x;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(char* c) {\n"
" if(c == '\\0') bar();\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Char literal compared with pointer 'c'. Did you intend to dereference it?\n", errout_str());
check("void f() {\n"
" struct { struct { char *str; } x; } a;\n"
" return a.x.str == '\\0';"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Char literal compared with pointer 'a.x.str'. Did you intend to dereference it?\n", errout_str());
check("void f() {\n"
" struct { struct { char *str; } x; } a;\n"
" return *a.x.str == '\\0';"
"}");
ASSERT_EQUALS("", errout_str());
}
void snprintf1() {
check("void foo()\n"
"{\n"
" char buf[100];\n"
" snprintf(buf,100,\"%s\",buf);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Undefined behavior: Variable 'buf' is used as parameter and destination in snprintf().\n", errout_str());
}
void sprintf1() {
check("void foo()\n"
"{\n"
" char buf[100];\n"
" sprintf(buf,\"%s\",buf);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Undefined behavior: Variable 'buf' is used as parameter and destination in sprintf().\n", errout_str());
}
void sprintf2() {
check("void foo()\n"
"{\n"
" char buf[100];\n"
" sprintf(buf,\"%i\",sizeof(buf));\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void sprintf3() {
check("void foo()\n"
"{\n"
" char buf[100];\n"
" sprintf(buf,\"%i\",sizeof(buf));\n"
" if (buf[0]);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void sprintf4() {
check("struct A\n"
"{\n"
" char filename[128];\n"
"};\n"
"\n"
"void foo()\n"
"{\n"
" const char* filename = \"hello\";\n"
" struct A a;\n"
" snprintf(a.filename, 128, \"%s\", filename);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void sprintf5() {
check("struct A\n"
"{\n"
" char filename[128];\n"
"};\n"
"\n"
"void foo(struct A *a)\n"
"{\n"
" snprintf(a->filename, 128, \"%s\", a->filename);\n"
"}");
ASSERT_EQUALS("[test.cpp:8]: (error) Undefined behavior: Variable 'a->filename' is used as parameter and destination in snprintf().\n", errout_str());
}
void sprintf6() {
check("void foo()\n"
"{\n"
" char buf[100];\n"
" sprintf((char*)buf,\"%s\",(char*)buf);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Undefined behavior: Variable 'buf' is used as parameter and destination in sprintf().\n", errout_str());
}
void sprintf7() {
check("void foo()\n"
"{\n"
" char buf[100];\n"
" sprintf((char*)(void*)buf,\"%s\",(void*)(char*)buf);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Undefined behavior: Variable 'buf' is used as parameter and destination in sprintf().\n", errout_str());
}
void wsprintf1() {
check("void foo()\n"
"{\n"
" wchar_t buf[100];\n"
" swprintf(buf,10, \"%s\",buf);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Undefined behavior: Variable 'buf' is used as parameter and destination in swprintf().\n", errout_str());
}
void strPlusChar1() {
// Strange looking pointer arithmetic..
check("void foo()\n"
"{\n"
" const char *p = \"/usr\" + '/';\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Unusual pointer arithmetic. A value of type 'char' is added to a string literal.\n", errout_str());
}
void strPlusChar2() {
// Strange looking pointer arithmetic..
check("void foo()\n"
"{\n"
" char ch = 1;\n"
" const char *p = ch + \"/usr\";\n"
"}");
ASSERT_EQUALS("", errout_str());
// Strange looking pointer arithmetic..
check("void foo()\n"
"{\n"
" int i = 1;\n"
" const char* psz = \"Bla\";\n"
" const std::string str = i + psz;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void strPlusChar3() {
// Strange looking pointer arithmetic..
check("void foo()\n"
"{\n"
" std::string temp = \"/tmp\";\n"
" std::string path = temp + '/' + \"sub\" + '/';\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void strPlusChar4() {
// Strange looking pointer arithmetic, wide char..
check("void foo()\n"
"{\n"
" const wchar_t *p = L\"/usr\" + L'/';\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Unusual pointer arithmetic. A value of type 'wchar_t' is added to a string literal.\n", errout_str());
check("void foo(wchar_t c)\n"
"{\n"
" const wchar_t *p = L\"/usr\" + c;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Unusual pointer arithmetic. A value of type 'wchar_t' is added to a string literal.\n", errout_str());
}
void incorrectStringCompare() {
check("int f() {\n"
" return test.substr( 0 , 4 ) == \"Hello\" ? 0 : 1 ;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) String literal \"Hello\" doesn't match length argument for substr().\n", errout_str());
check("int f() {\n"
" return test.substr( 0 , 4 ) == L\"Hello\" ? 0 : 1 ;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) String literal L\"Hello\" doesn't match length argument for substr().\n", errout_str());
check("int f() {\n"
" return test.substr( 0 , 5 ) == \"Hello\" ? 0 : 1 ;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f() {\n"
" return \"Hello\" == test.substr( 0 , 4 ) ? 0 : 1 ;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) String literal \"Hello\" doesn't match length argument for substr().\n", errout_str());
check("int f() {\n"
" return \"Hello\" == foo.bar<int>().z[1].substr(i+j*4, 4) ? 0 : 1 ;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) String literal \"Hello\" doesn't match length argument for substr().\n", errout_str());
check("int f() {\n"
" return \"Hello\" == test.substr( 0 , 5 ) ? 0 : 1 ;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f() {\n"
" if (\"Hello\") { }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Conversion of string literal \"Hello\" to bool always evaluates to true.\n", errout_str());
check("int f() {\n"
" if (\"Hello\" && test) { }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Conversion of string literal \"Hello\" to bool always evaluates to true.\n", errout_str());
check("int f() {\n"
" if (test && \"Hello\") { }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Conversion of string literal \"Hello\" to bool always evaluates to true.\n", errout_str());
check("int f() {\n"
" while (\"Hello\") { }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Conversion of string literal \"Hello\" to bool always evaluates to true.\n", errout_str());
check("int f() {\n"
" return \"Hello\" ? 1 : 2;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Conversion of string literal \"Hello\" to bool always evaluates to true.\n", errout_str());
check("int f() {\n"
" assert (test || \"Hello\");\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Conversion of string literal \"Hello\" to bool always evaluates to true.\n", errout_str());
check("int f() {\n"
" assert (test && \"Hello\");\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f() {\n"
" assert (\"Hello\" || test);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Conversion of string literal \"Hello\" to bool always evaluates to true.\n", errout_str());
check("int f() {\n"
" assert (\"Hello\" && test);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f() {\n"
" BOOST_ASSERT (\"Hello\" && test);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f() {\n"
" return f2(\"Hello\");\n"
"}");
ASSERT_EQUALS("", errout_str());
// #7750 warn about char literals in boolean expressions
check("void f() {\n"
" if('a'){}\n"
" if(L'b'){}\n"
" if(1 && 'c'){}\n"
" int x = 'd' ? 1 : 2;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Conversion of char literal 'a' to bool always evaluates to true.\n"
"[test.cpp:3]: (warning) Conversion of char literal L'b' to bool always evaluates to true.\n"
"[test.cpp:4]: (warning) Conversion of char literal 'c' to bool always evaluates to true.\n"
"[test.cpp:5]: (warning) Conversion of char literal 'd' to bool always evaluates to true.\n"
, errout_str());
check("void f() {\n"
" if('\\0'){}\n"
" if(L'\\0'){}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Conversion of char literal '\\0' to bool always evaluates to false.\n"
"[test.cpp:3]: (warning) Conversion of char literal L'\\0' to bool always evaluates to false.\n",
errout_str());
check("void f() {\n"
" if('\\0' || cond){}\n"
" if(L'\\0' || cond){}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Conversion of char literal '\\0' to bool always evaluates to false.\n"
"[test.cpp:3]: (warning) Conversion of char literal L'\\0' to bool always evaluates to false.\n", errout_str());
check("void f(bool b);\n" // #9450
"void f(std::string s);\n"
"void g() {\n"
" f(\"abc\");\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (warning) Conversion of string literal \"abc\" to bool always evaluates to true.\n", errout_str());
check("void g(bool);\n"
" void f(std::map<std::string, std::vector<int>>&m) {\n"
" if (m.count(\"abc\"))\n"
" g(m[\"abc\"][0] ? true : false);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void g(bool b);\n"
"void f() {\n"
" g('\\0');\n"
" g('a');\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (warning) Conversion of char literal '\\0' to bool always evaluates to false.\n"
"[test.cpp:4]: (warning) Conversion of char literal 'a' to bool always evaluates to true.\n",
errout_str());
check("#define ERROR(msg) if (msg) printf(\"%s\\n\", msg);\n"
"void f() {\n"
" ERROR(\"abc\")\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void g(int, bool);\n"
"void f() {\n"
" MyAssert(!\"abc\");\n"
" g(2, !\"def\");\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (warning) Conversion of string literal \"def\" to bool always evaluates to true.\n", errout_str());
check("bool f(const char *p) {\n"
" if (*p == '\\0')\n"
" return *p == '\\0';\n"
" return false;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(const int* p, const int* q) {\n"
" assert((p != NULL && q != NULL) || !\"abc\");\n"
" ASSERT((void*)(\"def\") == 0);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("class C {\n" // #6109
" void check(const char code[], bool validate = true, const char* filename = \"test.cpp\");\n"
" void f() {\n"
" check(\"class A<B&, C>;\", \"test.C\");\n"
" }\n"
"};\n");
ASSERT_EQUALS("[test.cpp:4]: (warning) Conversion of string literal \"test.C\" to bool always evaluates to true.\n", errout_str());
check("#define MACRO(C) if(!(C)) { error(__FILE__, __LINE__, __FUNCTION__, #C); return; }\n" // #13067
"void f() {\n"
" MACRO(false && \"abc\");\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("#define strequ(s1,s2) ((void *)s1 && (void *)s2 && strcmp(s1, s2) == 0)\n" // #13093
"void f(const char* p) {\n"
" if (strequ(p, \"ALL\")) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void deadStrcmp() {
check("void f(const char *str) {\n"
" if (strcmp(str, \"abc\") == 0 || strcmp(str, \"def\")) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) The expression 'strcmp(str,\"def\") != 0' is suspicious. It overlaps 'strcmp(str,\"abc\") == 0'.\n", errout_str());
check("void f(const wchar_t *str) {\n"
" if (wcscmp(str, L\"abc\") == 0 || wcscmp(str, L\"def\")) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) The expression 'wcscmp(str,L\"def\") != 0' is suspicious. It overlaps 'wcscmp(str,L\"abc\") == 0'.\n", errout_str());
check("struct X {\n"
" char *str;\n"
"};\n"
"\n"
"void f(const struct X *x) {\n"
" if (strcmp(x->str, \"abc\") == 0 || strcmp(x->str, \"def\")) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (warning) The expression 'strcmp(x->str,\"def\") != 0' is suspicious. It overlaps 'strcmp(x->str,\"abc\") == 0'.\n", errout_str());
}
};
REGISTER_TEST(TestString)
| null |
955 | cpp | cppcheck | testtoken.cpp | test/testtoken.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "fixture.h"
#include "helpers.h"
#include "standards.h"
#include "token.h"
#include "tokenlist.h"
#include "vfvalue.h"
#include <algorithm>
#include <string>
#include <vector>
class TestToken : public TestFixture {
public:
TestToken() : TestFixture("TestToken") {
list.setLang(Standards::Language::C);
}
private:
/*const*/ TokenList list{&settingsDefault};
std::vector<std::string> arithmeticalOps;
std::vector<std::string> logicalOps;
std::vector<std::string> bitOps;
std::vector<std::string> comparisonOps;
std::vector<std::string> extendedOps;
std::vector<std::string> assignmentOps;
void run() override {
arithmeticalOps = { "+", "-", "*", "/", "%", "<<", ">>" };
logicalOps = { "&&", "||", "!" };
comparisonOps = { "==", "!=", "<", "<=", ">", ">=" };
bitOps = { "&", "|", "^", "~" };
extendedOps = { ",", "[", "]", "(", ")", "?", ":" };
assignmentOps = { "=", "+=", "-=", "*=", "/=", "%=", "&=", "^=", "|=", "<<=", ">>=" };
TEST_CASE(nextprevious);
TEST_CASE(multiCompare);
TEST_CASE(multiCompare2); // #3294 - false negative multi compare between "=" and "=="
TEST_CASE(multiCompare3); // false positive for %or% on code using "|="
TEST_CASE(multiCompare4);
TEST_CASE(multiCompare5);
TEST_CASE(charTypes);
TEST_CASE(stringTypes);
TEST_CASE(getStrLength);
TEST_CASE(getStrSize);
TEST_CASE(strValue);
TEST_CASE(concatStr);
TEST_CASE(deleteLast);
TEST_CASE(deleteFirst);
TEST_CASE(nextArgument);
TEST_CASE(eraseTokens);
TEST_CASE(matchAny);
TEST_CASE(matchSingleChar);
TEST_CASE(matchNothingOrAnyNotElse);
TEST_CASE(matchType);
TEST_CASE(matchChar);
TEST_CASE(matchCompOp);
TEST_CASE(matchStr);
TEST_CASE(matchVarid);
TEST_CASE(matchNumeric);
TEST_CASE(matchBoolean);
TEST_CASE(matchOr);
TEST_CASE(matchOp);
TEST_CASE(matchConstOp);
TEST_CASE(isArithmeticalOp);
TEST_CASE(isOp);
TEST_CASE(isConstOp);
TEST_CASE(isExtendedOp);
TEST_CASE(isAssignmentOp);
TEST_CASE(isStandardType);
TEST_CASE(literals);
TEST_CASE(operators);
TEST_CASE(updateProperties);
TEST_CASE(isNameGuarantees1);
TEST_CASE(isNameGuarantees2);
TEST_CASE(isNameGuarantees3);
TEST_CASE(isNameGuarantees4);
TEST_CASE(isNameGuarantees5);
TEST_CASE(isNameGuarantees6);
TEST_CASE(canFindMatchingBracketsNeedsOpen);
TEST_CASE(canFindMatchingBracketsInnerPair);
TEST_CASE(canFindMatchingBracketsOuterPair);
TEST_CASE(canFindMatchingBracketsWithTooManyClosing);
TEST_CASE(canFindMatchingBracketsWithTooManyOpening);
TEST_CASE(findClosingBracket);
TEST_CASE(findClosingBracket2);
TEST_CASE(findClosingBracket3);
TEST_CASE(findClosingBracket4);
TEST_CASE(expressionString);
TEST_CASE(hasKnownIntValue);
}
void nextprevious() const {
TokensFrontBack tokensFrontBack(list);
auto *token = new Token(tokensFrontBack);
token->str("1");
(void)token->insertToken("2");
(void)token->next()->insertToken("3");
Token *last = token->tokAt(2);
ASSERT_EQUALS(token->str(), "1");
ASSERT_EQUALS(token->strAt(1), "2");
// cppcheck-suppress redundantNextPrevious - this is intentional
ASSERT_EQUALS(token->tokAt(2)->str(), "3");
ASSERT_EQUALS_MSG(true, last->next() == nullptr, "Null was expected");
ASSERT_EQUALS(last->str(), "3");
ASSERT_EQUALS(last->strAt(-1), "2");
// cppcheck-suppress redundantNextPrevious - this is intentional
ASSERT_EQUALS(last->tokAt(-2)->str(), "1");
ASSERT_EQUALS_MSG(true, token->previous() == nullptr, "Null was expected");
TokenList::deleteTokens(token);
}
#define MatchCheck(...) MatchCheck_(__FILE__, __LINE__, __VA_ARGS__)
bool MatchCheck_(const char* file, int line, const std::string& code, const std::string& pattern, unsigned int varid = 0) {
SimpleTokenizer tokenizer(settingsDefault, *this);
const std::string code2 = ";" + code + ";";
try {
ASSERT_LOC(tokenizer.tokenize(code2), file, line);
} catch (...) {}
return Token::Match(tokenizer.tokens()->next(), pattern.c_str(), varid);
}
void multiCompare() const {
// Test for found
{
TokensFrontBack tokensFrontBack(list);
Token one(tokensFrontBack);
one.str("one");
ASSERT_EQUALS(1, Token::multiCompare(&one, "one|two", 0));
}
{
TokensFrontBack tokensFrontBack(list);
Token two(tokensFrontBack);
two.str("two");
ASSERT_EQUALS(1, Token::multiCompare(&two, "one|two", 0));
ASSERT_EQUALS(1, Token::multiCompare(&two, "verybig|two|", 0));
}
// Test for empty string found
{
TokensFrontBack tokensFrontBack(list);
Token notfound(tokensFrontBack);
notfound.str("notfound");
ASSERT_EQUALS(0, Token::multiCompare(¬found, "one|two|", 0));
// Test for not found
ASSERT_EQUALS(-1, Token::multiCompare(¬found, "one|two", 0));
}
{
TokensFrontBack tokensFrontBack(list);
Token s(tokensFrontBack);
s.str("s");
ASSERT_EQUALS(-1, Token::multiCompare(&s, "verybig|two", 0));
}
{
TokensFrontBack tokensFrontBack(list);
Token ne(tokensFrontBack);
ne.str("ne");
ASSERT_EQUALS(-1, Token::multiCompare(&ne, "one|two", 0));
}
{
TokensFrontBack tokensFrontBack(list);
Token a(tokensFrontBack);
a.str("a");
ASSERT_EQUALS(-1, Token::multiCompare(&a, "abc|def", 0));
}
{
TokensFrontBack tokensFrontBack(list);
Token abcd(tokensFrontBack);
abcd.str("abcd");
ASSERT_EQUALS(-1, Token::multiCompare(&abcd, "abc|def", 0));
}
{
TokensFrontBack tokensFrontBack(list);
Token def(tokensFrontBack);
def.str("default");
ASSERT_EQUALS(-1, Token::multiCompare(&def, "abc|def", 0));
}
// %op%
{
TokensFrontBack tokensFrontBack(list);
Token plus(tokensFrontBack);
plus.str("+");
ASSERT_EQUALS(1, Token::multiCompare(&plus, "one|%op%", 0));
ASSERT_EQUALS(1, Token::multiCompare(&plus, "%op%|two", 0));
}
{
TokensFrontBack tokensFrontBack(list);
Token x(tokensFrontBack);
x.str("x");
ASSERT_EQUALS(-1, Token::multiCompare(&x, "one|%op%", 0));
ASSERT_EQUALS(-1, Token::multiCompare(&x, "%op%|two", 0));
}
}
void multiCompare2() const { // #3294
// Original pattern that failed: [[,(=<>+-*|&^] %num% [+-*/] %num% ]|,|)|;|=|%op%
const SimpleTokenList toks("a == 1");
ASSERT_EQUALS(true, Token::Match(toks.front(), "a =|%op%"));
}
void multiCompare3() const {
// Original pattern that failed: "return|(|&&|%oror% %name% &&|%oror%|==|!=|<=|>=|<|>|-|%or% %name% )|&&|%oror%|;"
// Code snippet that failed: "return lv@86 |= rv@87 ;"
// Note: Also test "reverse" alternative pattern, two different code paths to handle it
const SimpleTokenList toks("return a |= b ;");
ASSERT_EQUALS(false, Token::Match(toks.front(), "return %name% xyz|%or% %name% ;"));
ASSERT_EQUALS(false, Token::Match(toks.front(), "return %name% %or%|xyz %name% ;"));
const SimpleTokenList toks2("return a | b ;");
ASSERT_EQUALS(true, Token::Match(toks2.front(), "return %name% xyz|%or% %name% ;"));
ASSERT_EQUALS(true, Token::Match(toks2.front(), "return %name% %or%|xyz %name% ;"));
const SimpleTokenList toks3("return a || b ;");
ASSERT_EQUALS(false, Token::Match(toks3.front(), "return %name% xyz|%or% %name% ;"));
ASSERT_EQUALS(false, Token::Match(toks3.front(), "return %name% %or%|xyz %name% ;"));
ASSERT_EQUALS(true, Token::Match(toks3.front(), "return %name% xyz|%oror% %name% ;"));
ASSERT_EQUALS(true, Token::Match(toks3.front(), "return %name% %oror%|xyz %name% ;"));
const SimpleTokenList toks4("a % b ;");
ASSERT_EQUALS(true, Token::Match(toks4.front(), "%name% >>|<<|&|%or%|^|% %name% ;"));
ASSERT_EQUALS(true, Token::Match(toks4.front(), "%name% %|>>|<<|&|%or%|^ %name% ;"));
ASSERT_EQUALS(true, Token::Match(toks4.front(), "%name% >>|<<|&|%or%|%|^ %name% ;"));
//%name%|%num% support
const SimpleTokenList num("100");
ASSERT_EQUALS(true, Token::Match(num.front(), "%num%|%name%"));
ASSERT_EQUALS(true, Token::Match(num.front(), "%name%|%num%"));
ASSERT_EQUALS(true, Token::Match(num.front(), "%name%|%num%|%bool%"));
ASSERT_EQUALS(true, Token::Match(num.front(), "%name%|%bool%|%num%"));
ASSERT_EQUALS(true, Token::Match(num.front(), "%name%|%bool%|%str%|%num%"));
ASSERT_EQUALS(false, Token::Match(num.front(), "%bool%|%name%"));
ASSERT_EQUALS(false, Token::Match(num.front(), "%type%|%bool%|%char%"));
ASSERT_EQUALS(true, Token::Match(num.front(), "%type%|%bool%|100"));
const SimpleTokenList numparen("( 100 )");
ASSERT_EQUALS(true, Token::Match(numparen.front(), "(| %num%|%name% )|"));
ASSERT_EQUALS(true, Token::Match(numparen.front(), "(| %name%|%num% )|"));
ASSERT_EQUALS(true, Token::Match(numparen.front(), "(| %name%|%num%|%bool% )|"));
ASSERT_EQUALS(true, Token::Match(numparen.front(), "(| %name%|%bool%|%num% )|"));
ASSERT_EQUALS(true, Token::Match(numparen.front(), "(| %name%|%bool%|%str%|%num% )|"));
ASSERT_EQUALS(false, Token::Match(numparen.front(), "(| %bool%|%name% )|"));
ASSERT_EQUALS(true, Token::Match(numparen.front(), "(| 100 %num%|%name%| )|"));
ASSERT_EQUALS(true, Token::Match(numparen.front(), "(| 100 %name%|%num%| )|"));
ASSERT_EQUALS(true, Token::Match(numparen.front(), "(| 100 %name%|%num%|%bool%| )|"));
ASSERT_EQUALS(true, Token::Match(numparen.front(), "(| 100 %name%|%bool%|%num%| )|"));
ASSERT_EQUALS(true, Token::Match(numparen.front(), "(| 100 %name%|%bool%|%str%|%num%| )|"));
ASSERT_EQUALS(true, Token::Match(numparen.front(), "(| 100 %bool%|%name%| )|"));
}
void multiCompare4() {
const SimpleTokenizer var(*this, "std :: queue < int > foo ;");
ASSERT_EQUALS(Token::eBracket, var.tokens()->tokAt(3)->tokType());
ASSERT_EQUALS(Token::eBracket, var.tokens()->tokAt(5)->tokType());
ASSERT_EQUALS(false, Token::Match(var.tokens(), "std :: queue %op%"));
ASSERT_EQUALS(false, Token::Match(var.tokens(), "std :: queue x|%op%"));
ASSERT_EQUALS(false, Token::Match(var.tokens(), "std :: queue %op%|x"));
}
void multiCompare5() const {
TokensFrontBack tokensFrontBack(list);
Token tok(tokensFrontBack);
tok.str("||");
ASSERT_EQUALS(true, Token::multiCompare(&tok, "+|%or%|%oror%", 0) >= 0);
}
void charTypes() const {
TokensFrontBack tokensFrontBack(list);
Token tok(tokensFrontBack);
tok.str("'a'");
ASSERT_EQUALS(true, tok.isCChar());
ASSERT_EQUALS(false, tok.isUtf8());
ASSERT_EQUALS(false, tok.isUtf16());
ASSERT_EQUALS(false, tok.isUtf32());
ASSERT_EQUALS(false, tok.isLong());
ASSERT_EQUALS(false, tok.isCMultiChar());
tok.str("u8'a'");
ASSERT_EQUALS(false, tok.isCChar());
ASSERT_EQUALS(true, tok.isUtf8());
ASSERT_EQUALS(false, tok.isUtf16());
ASSERT_EQUALS(false, tok.isUtf32());
ASSERT_EQUALS(false, tok.isLong());
ASSERT_EQUALS(false, tok.isCMultiChar());
tok.str("u'a'");
ASSERT_EQUALS(false, tok.isCChar());
ASSERT_EQUALS(false, tok.isUtf8());
ASSERT_EQUALS(true, tok.isUtf16());
ASSERT_EQUALS(false, tok.isUtf32());
ASSERT_EQUALS(false, tok.isLong());
ASSERT_EQUALS(false, tok.isCMultiChar());
tok.str("U'a'");
ASSERT_EQUALS(false, tok.isCChar());
ASSERT_EQUALS(false, tok.isUtf8());
ASSERT_EQUALS(false, tok.isUtf16());
ASSERT_EQUALS(true, tok.isUtf32());
ASSERT_EQUALS(false, tok.isLong());
ASSERT_EQUALS(false, tok.isCMultiChar());
tok.str("L'a'");
ASSERT_EQUALS(false, tok.isCChar());
ASSERT_EQUALS(false, tok.isUtf8());
ASSERT_EQUALS(false, tok.isUtf16());
ASSERT_EQUALS(false, tok.isUtf32());
ASSERT_EQUALS(true, tok.isLong());
ASSERT_EQUALS(false, tok.isCMultiChar());
tok.str("'aaa'");
ASSERT_EQUALS(false, tok.isCChar());
ASSERT_EQUALS(false, tok.isUtf8());
ASSERT_EQUALS(false, tok.isUtf16());
ASSERT_EQUALS(false, tok.isUtf32());
ASSERT_EQUALS(false, tok.isLong());
ASSERT_EQUALS(true, tok.isCMultiChar());
tok.str("'\\''");
ASSERT_EQUALS(true, tok.isCChar());
ASSERT_EQUALS(false, tok.isUtf8());
ASSERT_EQUALS(false, tok.isUtf16());
ASSERT_EQUALS(false, tok.isUtf32());
ASSERT_EQUALS(false, tok.isLong());
ASSERT_EQUALS(false, tok.isCMultiChar());
tok.str("'\\r\\n'");
ASSERT_EQUALS(false, tok.isCChar());
ASSERT_EQUALS(false, tok.isUtf8());
ASSERT_EQUALS(false, tok.isUtf16());
ASSERT_EQUALS(false, tok.isUtf32());
ASSERT_EQUALS(false, tok.isLong());
ASSERT_EQUALS(true, tok.isCMultiChar());
tok.str("'\\x10'");
ASSERT_EQUALS(true, tok.isCChar());
ASSERT_EQUALS(false, tok.isUtf8());
ASSERT_EQUALS(false, tok.isUtf16());
ASSERT_EQUALS(false, tok.isUtf32());
ASSERT_EQUALS(false, tok.isLong());
ASSERT_EQUALS(false, tok.isCMultiChar());
}
void stringTypes() const {
TokensFrontBack tokensFrontBack(list);
Token tok(tokensFrontBack);
tok.str("\"a\"");
ASSERT_EQUALS(true, tok.isCChar());
ASSERT_EQUALS(false, tok.isUtf8());
ASSERT_EQUALS(false, tok.isUtf16());
ASSERT_EQUALS(false, tok.isUtf32());
ASSERT_EQUALS(false, tok.isLong());
ASSERT_EQUALS(false, tok.isCMultiChar());
tok.str("u8\"a\"");
ASSERT_EQUALS(false, tok.isCChar());
ASSERT_EQUALS(true, tok.isUtf8());
ASSERT_EQUALS(false, tok.isUtf16());
ASSERT_EQUALS(false, tok.isUtf32());
ASSERT_EQUALS(false, tok.isLong());
ASSERT_EQUALS(false, tok.isCMultiChar());
tok.str("u\"a\"");
ASSERT_EQUALS(false, tok.isCChar());
ASSERT_EQUALS(false, tok.isUtf8());
ASSERT_EQUALS(true, tok.isUtf16());
ASSERT_EQUALS(false, tok.isUtf32());
ASSERT_EQUALS(false, tok.isLong());
ASSERT_EQUALS(false, tok.isCMultiChar());
tok.str("U\"a\"");
ASSERT_EQUALS(false, tok.isCChar());
ASSERT_EQUALS(false, tok.isUtf8());
ASSERT_EQUALS(false, tok.isUtf16());
ASSERT_EQUALS(true, tok.isUtf32());
ASSERT_EQUALS(false, tok.isLong());
ASSERT_EQUALS(false, tok.isCMultiChar());
tok.str("L\"a\"");
ASSERT_EQUALS(false, tok.isCChar());
ASSERT_EQUALS(false, tok.isUtf8());
ASSERT_EQUALS(false, tok.isUtf16());
ASSERT_EQUALS(false, tok.isUtf32());
ASSERT_EQUALS(true, tok.isLong());
ASSERT_EQUALS(false, tok.isCMultiChar());
}
void getStrLength() const {
TokensFrontBack tokensFrontBack(list);
Token tok(tokensFrontBack);
tok.str("\"\"");
ASSERT_EQUALS(0, Token::getStrLength(&tok));
tok.str("\"test\"");
ASSERT_EQUALS(4, Token::getStrLength(&tok));
tok.str("\"test \\\\test\"");
ASSERT_EQUALS(10, Token::getStrLength(&tok));
tok.str("\"a\\0\"");
ASSERT_EQUALS(1, Token::getStrLength(&tok));
tok.str("L\"\"");
ASSERT_EQUALS(0, Token::getStrLength(&tok));
tok.str("u8\"test\"");
ASSERT_EQUALS(4, Token::getStrLength(&tok));
tok.str("U\"test \\\\test\"");
ASSERT_EQUALS(10, Token::getStrLength(&tok));
tok.str("u\"a\\0\"");
ASSERT_EQUALS(1, Token::getStrLength(&tok));
}
void getStrSize() const {
TokensFrontBack tokensFrontBack(list);
Token tok(tokensFrontBack);
tok.str("\"\"");
ASSERT_EQUALS(sizeof(""), Token::getStrSize(&tok, settingsDefault));
tok.str("\"abc\"");
ASSERT_EQUALS(sizeof("abc"), Token::getStrSize(&tok, settingsDefault));
tok.str("\"\\0abc\"");
ASSERT_EQUALS(sizeof("\0abc"), Token::getStrSize(&tok, settingsDefault));
tok.str("\"\\\\\"");
ASSERT_EQUALS(sizeof("\\"), Token::getStrSize(&tok, settingsDefault));
}
void strValue() const {
TokensFrontBack tokensFrontBack(list);
Token tok(tokensFrontBack);
tok.str("\"\"");
ASSERT_EQUALS("", tok.strValue());
tok.str("\"0\"");
ASSERT_EQUALS("0", tok.strValue());
tok.str("\"a\\n\"");
ASSERT_EQUALS("a\n", tok.strValue());
tok.str("\"a\\r\"");
ASSERT_EQUALS("a\r", tok.strValue());
tok.str("\"a\\t\"");
ASSERT_EQUALS("a\t", tok.strValue());
tok.str("\"\\\\\"");
ASSERT_EQUALS("\\", tok.strValue());
tok.str("\"a\\0\"");
ASSERT_EQUALS("a", tok.strValue());
tok.str("L\"a\\t\"");
ASSERT_EQUALS("a\t", tok.strValue());
tok.str("U\"a\\0\"");
ASSERT_EQUALS("a", tok.strValue());
}
void concatStr() const {
TokensFrontBack tokensFrontBack(list);
Token tok(tokensFrontBack);
tok.str("\"\"");
tok.concatStr("\"\"");
ASSERT_EQUALS("", tok.strValue());
ASSERT(tok.isCChar());
tok.str("\"ab\"");
tok.concatStr("\"cd\"");
ASSERT_EQUALS("abcd", tok.strValue());
ASSERT(tok.isCChar());
tok.str("L\"ab\"");
tok.concatStr("L\"cd\"");
ASSERT_EQUALS("abcd", tok.strValue());
ASSERT(tok.isLong());
tok.str("L\"ab\"");
tok.concatStr("\"cd\"");
ASSERT_EQUALS("abcd", tok.strValue());
ASSERT(tok.isLong());
tok.str("\"ab\"");
tok.concatStr("L\"cd\"");
ASSERT_EQUALS("abcd", tok.strValue());
ASSERT(tok.isLong());
tok.str("\"ab\"");
tok.concatStr("L\"\"");
ASSERT_EQUALS("ab", tok.strValue());
ASSERT(tok.isLong());
tok.str("\"ab\"");
tok.concatStr("u8\"cd\"");
ASSERT_EQUALS("abcd", tok.strValue());
ASSERT(tok.isUtf8());
}
void deleteLast() const {
TokensFrontBack listEnds(list);
Token ** const tokensBack = &(listEnds.back);
Token tok(listEnds);
(void)tok.insertToken("aba");
ASSERT_EQUALS(true, *tokensBack == tok.next());
tok.deleteNext();
ASSERT_EQUALS(true, *tokensBack == &tok);
}
void deleteFirst() const {
TokensFrontBack listEnds(list);
Token ** const tokensFront = &(listEnds.front);
Token tok(listEnds);
(void)tok.insertToken("aba");
ASSERT_EQUALS(true, *tokensFront == tok.previous());
tok.deletePrevious();
ASSERT_EQUALS(true, *tokensFront == &tok);
}
void nextArgument() {
const SimpleTokenizer example1(*this, "foo(1, 2, 3, 4);");
ASSERT_EQUALS(true, Token::simpleMatch(example1.tokens()->tokAt(2)->nextArgument(), "2 , 3"));
ASSERT_EQUALS(true, Token::simpleMatch(example1.tokens()->tokAt(4)->nextArgument(), "3 , 4"));
const SimpleTokenizer example2(*this, "foo();");
ASSERT_EQUALS(true, example2.tokens()->tokAt(2)->nextArgument() == nullptr);
const SimpleTokenizer example3(*this, "foo(bar(a, b), 2, 3);");
ASSERT_EQUALS(true, Token::simpleMatch(example3.tokens()->tokAt(2)->nextArgument(), "2 , 3"));
const SimpleTokenizer example4(*this, "foo(x.i[1], \"\", 3);");
ASSERT_EQUALS(true, Token::simpleMatch(example4.tokens()->tokAt(2)->nextArgument(), "\"\" , 3"));
}
void eraseTokens() const {
SimpleTokenList code("begin ; { this code will be removed } end", Standards::Language::C);
Token::eraseTokens(code.front()->next(), code.front()->tokAt(9));
ASSERT_EQUALS("begin ; end", code.front()->stringifyList(nullptr, false));
}
void matchAny() const {
const SimpleTokenList varBitOrVar("abc|def");
ASSERT_EQUALS(true, Token::Match(varBitOrVar.front(), "%name% %or% %name%"));
const SimpleTokenList varLogOrVar("abc||def");
ASSERT_EQUALS(true, Token::Match(varLogOrVar.front(), "%name% %oror% %name%"));
}
void matchSingleChar() const {
const SimpleTokenList singleChar("a");
ASSERT_EQUALS(true, Token::Match(singleChar.front(), "[a|bc]"));
ASSERT_EQUALS(false, Token::Match(singleChar.front(), "[d|ef]"));
TokensFrontBack tokensFrontBack(list);
Token multiChar(tokensFrontBack);
multiChar.str("[ab");
ASSERT_EQUALS(false, Token::Match(&multiChar, "[ab|def]"));
}
void matchNothingOrAnyNotElse() const {
const SimpleTokenList empty_String("");
ASSERT_EQUALS(true, Token::Match(empty_String.front(), "!!else"));
ASSERT_EQUALS(false, Token::Match(empty_String.front(), "!!else something"));
const SimpleTokenList ifSemicolon("if ;");
ASSERT_EQUALS(true, Token::Match(ifSemicolon.front(), "if ; !!else"));
const SimpleTokenList ifSemicolonSomething("if ; something");
ASSERT_EQUALS(true, Token::Match(ifSemicolonSomething.front(), "if ; !!else"));
const SimpleTokenList justElse("else");
ASSERT_EQUALS(false, Token::Match(justElse.front(), "!!else"));
const SimpleTokenList ifSemicolonElse("if ; else");
ASSERT_EQUALS(false, Token::Match(ifSemicolonElse.front(), "if ; !!else"));
}
void matchType() {
const SimpleTokenList type("abc");
ASSERT_EQUALS(true, Token::Match(type.front(), "%type%"));
const SimpleTokenizer isVar(*this, "int a = 3 ;");
ASSERT_EQUALS(true, Token::Match(isVar.tokens(), "%type%"));
ASSERT_EQUALS(true, Token::Match(isVar.tokens(), "%type% %name%"));
ASSERT_EQUALS(false, Token::Match(isVar.tokens(), "%type% %type%"));
// TODO: %type% should not match keywords other than fundamental types
const SimpleTokenList noType1_cpp("delete");
ASSERT_EQUALS(true, Token::Match(noType1_cpp.front(), "%type%"));
const SimpleTokenList noType1_c("delete", Standards::Language::C);
ASSERT_EQUALS(true, Token::Match(noType1_c.front(), "%type%"));
const SimpleTokenList noType2("void delete");
ASSERT_EQUALS(true, Token::Match(noType2.front(), "!!foo %type%"));
}
void matchChar() const {
const SimpleTokenList chr1("'a'");
ASSERT_EQUALS(true, Token::Match(chr1.front(), "%char%"));
const SimpleTokenList chr2("'1'");
ASSERT_EQUALS(true, Token::Match(chr2.front(), "%char%"));
const SimpleTokenList noChr("\"10\"");
ASSERT_EQUALS(false, Token::Match(noChr.front(), "%char%"));
}
void matchCompOp() const {
const SimpleTokenList comp1("<=");
ASSERT_EQUALS(true, Token::Match(comp1.front(), "%comp%"));
const SimpleTokenList comp2(">");
ASSERT_EQUALS(true, Token::Match(comp2.front(), "%comp%"));
const SimpleTokenList noComp("=");
ASSERT_EQUALS(false, Token::Match(noComp.front(), "%comp%"));
}
void matchStr() const {
const SimpleTokenList noStr1("abc");
ASSERT_EQUALS(false, Token::Match(noStr1.front(), "%str%"));
const SimpleTokenList noStr2("'a'");
ASSERT_EQUALS(false, Token::Match(noStr2.front(), "%str%"));
const SimpleTokenList str("\"abc\"");
ASSERT_EQUALS(true, Token::Match(str.front(), "%str%"));
// Empty string
const SimpleTokenList emptyStr("\"\"");
ASSERT_EQUALS(true, Token::Match(emptyStr.front(), "%str%"));
}
void matchVarid() {
const SimpleTokenizer var(*this, "int a ; int b ;");
// Varid == 0 should throw exception
ASSERT_THROW_INTERNAL_EQUALS((void)Token::Match(var.tokens(), "%type% %varid% ; %type% %name%", 0),INTERNAL,"Internal error. Token::Match called with varid 0. Please report this to Cppcheck developers");
ASSERT_EQUALS(true, Token::Match(var.tokens(), "%type% %varid% ; %type% %name%", 1));
ASSERT_EQUALS(true, Token::Match(var.tokens(), "%type% %name% ; %type% %varid%", 2));
// Try to match two different varids in one match call
ASSERT_EQUALS(false, Token::Match(var.tokens(), "%type% %varid% ; %type% %varid%", 2));
// %var% matches with every varid other than 0
ASSERT_EQUALS(true, Token::Match(var.tokens(), "%type% %var% ;"));
ASSERT_EQUALS(false, Token::Match(var.tokens(), "%var% %var% ;"));
}
void matchNumeric() const {
const SimpleTokenList nonNumeric("abc");
ASSERT_EQUALS(false, Token::Match(nonNumeric.front(), "%num%"));
const SimpleTokenList msLiteral("5ms"); // #11438
ASSERT_EQUALS(false, Token::Match(msLiteral.front(), "%num%"));
const SimpleTokenList sLiteral("3s");
ASSERT_EQUALS(false, Token::Match(sLiteral.front(), "%num%"));
const SimpleTokenList octal("0123");
ASSERT_EQUALS(true, Token::Match(octal.front(), "%num%"));
const SimpleTokenList decimal("4567");
ASSERT_EQUALS(true, Token::Match(decimal.front(), "%num%"));
const SimpleTokenList hexadecimal("0xDEADBEEF");
ASSERT_EQUALS(true, Token::Match(hexadecimal.front(), "%num%"));
const SimpleTokenList floatingPoint("0.0f");
ASSERT_EQUALS(true, Token::Match(floatingPoint.front(), "%num%"));
const SimpleTokenList signedLong("0L");
ASSERT_EQUALS(true, Token::Match(signedLong.front(), "%num%"));
const SimpleTokenList negativeSignedLong("-0L");
ASSERT_EQUALS(true, Token::Match(negativeSignedLong.front(), "- %num%"));
const SimpleTokenList positiveSignedLong("+0L");
ASSERT_EQUALS(true, Token::Match(positiveSignedLong.front(), "+ %num%"));
const SimpleTokenList unsignedInt("0U");
ASSERT_EQUALS(true, Token::Match(unsignedInt.front(), "%num%"));
const SimpleTokenList unsignedLong("0UL");
ASSERT_EQUALS(true, Token::Match(unsignedLong.front(), "%num%"));
const SimpleTokenList unsignedLongLong("0ULL");
ASSERT_EQUALS(true, Token::Match(unsignedLongLong.front(), "%num%"));
const SimpleTokenList positive("+666");
ASSERT_EQUALS(true, Token::Match(positive.front(), "+ %num%"));
const SimpleTokenList negative("-42");
ASSERT_EQUALS(true, Token::Match(negative.front(), "- %num%"));
const SimpleTokenList negativeNull("-.0");
ASSERT_EQUALS(true, Token::Match(negativeNull.front(), "- %num%"));
const SimpleTokenList positiveNull("+.0");
ASSERT_EQUALS(true, Token::Match(positiveNull.front(), "+ %num%"));
}
void matchBoolean() const {
const SimpleTokenList yes("YES");
ASSERT_EQUALS(false, Token::Match(yes.front(), "%bool%"));
const SimpleTokenList positive("true");
ASSERT_EQUALS(true, Token::Match(positive.front(), "%bool%"));
const SimpleTokenList negative("false");
ASSERT_EQUALS(true, Token::Match(negative.front(), "%bool%"));
}
void matchOr() const {
const SimpleTokenList bitwiseOr(";|;");
// cppcheck-suppress simplePatternError - this is intentional
ASSERT_EQUALS(true, Token::Match(bitwiseOr.front(), "; %or%"));
ASSERT_EQUALS(true, Token::Match(bitwiseOr.front(), "; %op%"));
// cppcheck-suppress simplePatternError - this is intentional
ASSERT_EQUALS(false, Token::Match(bitwiseOr.front(), "; %oror%"));
const SimpleTokenList bitwiseOrAssignment(";|=;");
// cppcheck-suppress simplePatternError - this is intentional
ASSERT_EQUALS(false, Token::Match(bitwiseOrAssignment.front(), "; %or%"));
ASSERT_EQUALS(true, Token::Match(bitwiseOrAssignment.front(), "; %op%"));
// cppcheck-suppress simplePatternError - this is intentional
ASSERT_EQUALS(false, Token::Match(bitwiseOrAssignment.front(), "; %oror%"));
const SimpleTokenList logicalOr(";||;");
// cppcheck-suppress simplePatternError - this is intentional
ASSERT_EQUALS(false, Token::Match(logicalOr.front(), "; %or%"));
ASSERT_EQUALS(true, Token::Match(logicalOr.front(), "; %op%"));
// cppcheck-suppress simplePatternError - this is intentional
ASSERT_EQUALS(true, Token::Match(logicalOr.front(), "; %oror%"));
ASSERT_EQUALS(true, Token::Match(logicalOr.front(), "; &&|%oror%"));
ASSERT_EQUALS(true, Token::Match(logicalOr.front(), "; %oror%|&&"));
const SimpleTokenList logicalAnd(";&&;");
ASSERT_EQUALS(true, Token::simpleMatch(logicalAnd.front(), "; &&"));
ASSERT_EQUALS(true, Token::Match(logicalAnd.front(), "; &&|%oror%"));
ASSERT_EQUALS(true, Token::Match(logicalAnd.front(), "; %oror%|&&"));
}
static void append_vector(std::vector<std::string> &dest, const std::vector<std::string> &src) {
dest.insert(dest.end(), src.cbegin(), src.cend());
}
void matchOp() {
std::vector<std::string> test_ops;
append_vector(test_ops, arithmeticalOps);
append_vector(test_ops, bitOps);
append_vector(test_ops, comparisonOps);
append_vector(test_ops, logicalOps);
append_vector(test_ops, assignmentOps);
ASSERT_EQUALS(true, std::all_of(test_ops.cbegin(), test_ops.cend(), [&](const std::string& s) {
return MatchCheck(s, "%op%");
}));
// Negative test against other operators
std::vector<std::string> other_ops;
append_vector(other_ops, extendedOps);
std::vector<std::string>::const_iterator other_op, other_ops_end = other_ops.cend();
for (other_op = other_ops.cbegin(); other_op != other_ops_end; ++other_op) {
ASSERT_EQUALS_MSG(false, MatchCheck(*other_op, "%op%"), "Failing other operator: " + *other_op);
}
}
void matchConstOp() {
std::vector<std::string> test_ops;
append_vector(test_ops, arithmeticalOps);
append_vector(test_ops, bitOps);
append_vector(test_ops, comparisonOps);
append_vector(test_ops, logicalOps);
ASSERT_EQUALS(true, std::all_of(test_ops.cbegin(), test_ops.cend(), [&](const std::string& s) {
return MatchCheck(s, "%cop%");
}));
// Negative test against other operators
std::vector<std::string> other_ops;
append_vector(other_ops, extendedOps);
append_vector(other_ops, assignmentOps);
std::vector<std::string>::const_iterator other_op, other_ops_end = other_ops.cend();
for (other_op = other_ops.cbegin(); other_op != other_ops_end; ++other_op) {
ASSERT_EQUALS_MSG(false, MatchCheck(*other_op, "%cop%"), "Failing other operator: " + *other_op);
}
}
void isArithmeticalOp() const {
std::vector<std::string>::const_iterator test_op, test_ops_end = arithmeticalOps.cend();
for (test_op = arithmeticalOps.cbegin(); test_op != test_ops_end; ++test_op) {
TokensFrontBack tokensFrontBack(list);
Token tok(tokensFrontBack);
tok.str(*test_op);
ASSERT_EQUALS(true, tok.isArithmeticalOp());
}
// Negative test against other operators
std::vector<std::string> other_ops;
append_vector(other_ops, bitOps);
append_vector(other_ops, comparisonOps);
append_vector(other_ops, logicalOps);
append_vector(other_ops, extendedOps);
append_vector(other_ops, assignmentOps);
std::vector<std::string>::const_iterator other_op, other_ops_end = other_ops.cend();
for (other_op = other_ops.cbegin(); other_op != other_ops_end; ++other_op) {
TokensFrontBack tokensFrontBack(list);
Token tok(tokensFrontBack);
tok.str(*other_op);
ASSERT_EQUALS_MSG(false, tok.isArithmeticalOp(), "Failing arithmetical operator: " + *other_op);
}
}
void isOp() const {
std::vector<std::string> test_ops;
append_vector(test_ops, arithmeticalOps);
append_vector(test_ops, bitOps);
append_vector(test_ops, comparisonOps);
append_vector(test_ops, logicalOps);
append_vector(test_ops, assignmentOps);
std::vector<std::string>::const_iterator test_op, test_ops_end = test_ops.cend();
for (test_op = test_ops.cbegin(); test_op != test_ops_end; ++test_op) {
TokensFrontBack tokensFrontBack(list);
Token tok(tokensFrontBack);
tok.str(*test_op);
ASSERT_EQUALS(true, tok.isOp());
}
// Negative test against other operators
std::vector<std::string> other_ops;
append_vector(other_ops, extendedOps);
std::vector<std::string>::const_iterator other_op, other_ops_end = other_ops.cend();
for (other_op = other_ops.cbegin(); other_op != other_ops_end; ++other_op) {
TokensFrontBack tokensFrontBack(list);
Token tok(tokensFrontBack);
tok.str(*other_op);
ASSERT_EQUALS_MSG(false, tok.isOp(), "Failing normal operator: " + *other_op);
}
}
void isConstOp() const {
std::vector<std::string> test_ops;
append_vector(test_ops, arithmeticalOps);
append_vector(test_ops, bitOps);
append_vector(test_ops, comparisonOps);
append_vector(test_ops, logicalOps);
std::vector<std::string>::const_iterator test_op, test_ops_end = test_ops.cend();
for (test_op = test_ops.cbegin(); test_op != test_ops_end; ++test_op) {
TokensFrontBack tokensFrontBack(list);
Token tok(tokensFrontBack);
tok.str(*test_op);
ASSERT_EQUALS(true, tok.isConstOp());
}
// Negative test against other operators
std::vector<std::string> other_ops;
append_vector(other_ops, extendedOps);
append_vector(other_ops, assignmentOps);
std::vector<std::string>::const_iterator other_op, other_ops_end = other_ops.cend();
for (other_op = other_ops.cbegin(); other_op != other_ops_end; ++other_op) {
TokensFrontBack tokensFrontBack(list);
Token tok(tokensFrontBack);
tok.str(*other_op);
ASSERT_EQUALS_MSG(false, tok.isConstOp(), "Failing normal operator: " + *other_op);
}
}
void isExtendedOp() const {
std::vector<std::string> test_ops;
append_vector(test_ops, arithmeticalOps);
append_vector(test_ops, bitOps);
append_vector(test_ops, comparisonOps);
append_vector(test_ops, logicalOps);
append_vector(test_ops, extendedOps);
std::vector<std::string>::const_iterator test_op, test_ops_end = test_ops.cend();
for (test_op = test_ops.cbegin(); test_op != test_ops_end; ++test_op) {
TokensFrontBack tokensFrontBack(list);
Token tok(tokensFrontBack);
tok.str(*test_op);
ASSERT_EQUALS(true, tok.isExtendedOp());
}
// Negative test against assignment operators
std::vector<std::string>::const_iterator other_op, other_ops_end = assignmentOps.cend();
for (other_op = assignmentOps.cbegin(); other_op != other_ops_end; ++other_op) {
TokensFrontBack tokensFrontBack(list);
Token tok(tokensFrontBack);
tok.str(*other_op);
ASSERT_EQUALS_MSG(false, tok.isExtendedOp(), "Failing assignment operator: " + *other_op);
}
}
void isAssignmentOp() const {
std::vector<std::string>::const_iterator test_op, test_ops_end = assignmentOps.cend();
for (test_op = assignmentOps.cbegin(); test_op != test_ops_end; ++test_op) {
TokensFrontBack tokensFrontBack(list);
Token tok(tokensFrontBack);
tok.str(*test_op);
ASSERT_EQUALS(true, tok.isAssignmentOp());
}
// Negative test against other operators
std::vector<std::string> other_ops;
append_vector(other_ops, arithmeticalOps);
append_vector(other_ops, bitOps);
append_vector(other_ops, comparisonOps);
append_vector(other_ops, logicalOps);
append_vector(other_ops, extendedOps);
std::vector<std::string>::const_iterator other_op, other_ops_end = other_ops.cend();
for (other_op = other_ops.cbegin(); other_op != other_ops_end; ++other_op) {
TokensFrontBack tokensFrontBack(list);
Token tok(tokensFrontBack);
tok.str(*other_op);
ASSERT_EQUALS_MSG(false, tok.isAssignmentOp(), "Failing assignment operator: " + *other_op);
}
}
void operators() const {
std::vector<std::string>::const_iterator test_op;
for (test_op = extendedOps.cbegin(); test_op != extendedOps.cend(); ++test_op) {
TokensFrontBack tokensFrontBack(list);
Token tok(tokensFrontBack);
tok.str(*test_op);
ASSERT_EQUALS(Token::eExtendedOp, tok.tokType());
}
for (test_op = logicalOps.cbegin(); test_op != logicalOps.cend(); ++test_op) {
TokensFrontBack tokensFrontBack(list);
Token tok(tokensFrontBack);
tok.str(*test_op);
ASSERT_EQUALS(Token::eLogicalOp, tok.tokType());
}
for (test_op = bitOps.cbegin(); test_op != bitOps.cend(); ++test_op) {
TokensFrontBack tokensFrontBack(list);
Token tok(tokensFrontBack);
tok.str(*test_op);
ASSERT_EQUALS(Token::eBitOp, tok.tokType());
}
for (test_op = comparisonOps.cbegin(); test_op != comparisonOps.cend(); ++test_op) {
TokensFrontBack tokensFrontBack(list);
Token tok(tokensFrontBack);
tok.str(*test_op);
ASSERT_EQUALS(Token::eComparisonOp, tok.tokType());
}
TokensFrontBack tokensFrontBack(list);
Token tok(tokensFrontBack);
tok.str("++");
ASSERT_EQUALS(Token::eIncDecOp, tok.tokType());
tok.str("--");
ASSERT_EQUALS(Token::eIncDecOp, tok.tokType());
}
void literals() const {
TokensFrontBack tokensFrontBack(list);
Token tok(tokensFrontBack);
tok.str("\"foo\"");
ASSERT(tok.tokType() == Token::eString);
tok.str("\"\"");
ASSERT(tok.tokType() == Token::eString);
tok.str("'f'");
ASSERT(tok.tokType() == Token::eChar);
tok.str("12345");
ASSERT(tok.tokType() == Token::eNumber);
tok.str("-55");
ASSERT(tok.tokType() == Token::eNumber);
tok.str("true");
ASSERT(tok.tokType() == Token::eBoolean);
tok.str("false");
ASSERT(tok.tokType() == Token::eBoolean);
}
void isStandardType() const {
std::vector<std::string> standard_types;
standard_types.emplace_back("bool");
standard_types.emplace_back("char");
standard_types.emplace_back("short");
standard_types.emplace_back("int");
standard_types.emplace_back("long");
standard_types.emplace_back("float");
standard_types.emplace_back("double");
standard_types.emplace_back("size_t");
std::vector<std::string>::const_iterator test_op, test_ops_end = standard_types.cend();
for (test_op = standard_types.cbegin(); test_op != test_ops_end; ++test_op) {
TokensFrontBack tokensFrontBack(list);
Token tok(tokensFrontBack);
tok.str(*test_op);
ASSERT_EQUALS_MSG(true, tok.isStandardType(), "Failing standard type: " + *test_op);
}
// Negative test
TokensFrontBack tokensFrontBack(list);
Token tok(tokensFrontBack);
tok.str("string");
ASSERT_EQUALS(false, tok.isStandardType());
// Change back to standard type
tok.str("int");
ASSERT_EQUALS(true, tok.isStandardType());
// token can't be both type and variable
tok.str("abc");
tok.isStandardType(true);
tok.varId(123);
ASSERT_EQUALS(false, tok.isStandardType());
}
void updateProperties() const {
TokensFrontBack tokensFrontBack(list);
Token tok(tokensFrontBack);
tok.str("foobar");
ASSERT_EQUALS(true, tok.isName());
ASSERT_EQUALS(false, tok.isNumber());
tok.str("123456");
ASSERT_EQUALS(false, tok.isName());
ASSERT_EQUALS(true, tok.isNumber());
}
void isNameGuarantees1() const {
TokensFrontBack tokensFrontBack(list);
Token tok(tokensFrontBack);
tok.str("Name");
ASSERT_EQUALS(true, tok.isName());
}
void isNameGuarantees2() const {
TokensFrontBack tokensFrontBack(list);
Token tok(tokensFrontBack);
tok.str("_name");
ASSERT_EQUALS(true, tok.isName());
}
void isNameGuarantees3() const {
TokensFrontBack tokensFrontBack(list);
Token tok(tokensFrontBack);
tok.str("_123");
ASSERT_EQUALS(true, tok.isName());
}
void isNameGuarantees4() const {
TokensFrontBack tokensFrontBack(list);
Token tok(tokensFrontBack);
tok.str("123456");
ASSERT_EQUALS(false, tok.isName());
ASSERT_EQUALS(true, tok.isNumber());
}
void isNameGuarantees5() const {
TokensFrontBack tokensFrontBack(list);
Token tok(tokensFrontBack);
tok.str("a123456");
ASSERT_EQUALS(true, tok.isName());
ASSERT_EQUALS(false, tok.isNumber());
}
void isNameGuarantees6() const {
TokensFrontBack tokensFrontBack(list);
Token tok(tokensFrontBack);
tok.str("$f");
ASSERT_EQUALS(true, tok.isName());
}
void canFindMatchingBracketsNeedsOpen() {
const SimpleTokenizer var(*this, "std::deque<std::set<int> > intsets;");
const Token* const t = var.tokens()->findClosingBracket();
ASSERT(t == nullptr);
}
void canFindMatchingBracketsInnerPair() {
const SimpleTokenizer var(*this, "std::deque<std::set<int> > intsets;");
const Token * const t = var.tokens()->tokAt(7)->findClosingBracket();
ASSERT_EQUALS(">", t->str());
ASSERT(var.tokens()->tokAt(9) == t);
}
void canFindMatchingBracketsOuterPair() {
const SimpleTokenizer var(*this, "std::deque<std::set<int> > intsets;");
const Token* const t = var.tokens()->tokAt(3)->findClosingBracket();
ASSERT_EQUALS(">", t->str());
ASSERT(var.tokens()->tokAt(10) == t);
}
void canFindMatchingBracketsWithTooManyClosing() {
const SimpleTokenizer var(*this, "X< 1>2 > x1;");
const Token* const t = var.tokens()->next()->findClosingBracket();
ASSERT_EQUALS(">", t->str());
ASSERT(var.tokens()->tokAt(3) == t);
}
void canFindMatchingBracketsWithTooManyOpening() {
const SimpleTokenizer var(*this, "X < (2 < 1) > x1;");
const Token* t = var.tokens()->next()->findClosingBracket();
ASSERT(t != nullptr && t->str() == ">");
t = var.tokens()->tokAt(4)->findClosingBracket();
ASSERT(t == nullptr);
}
void findClosingBracket() {
const SimpleTokenizer var(*this, "template<typename X, typename...Y> struct S : public Fred<Wilma<Y...>> {}");
const Token* const t = var.tokens()->next()->findClosingBracket();
ASSERT(Token::simpleMatch(t, "> struct"));
}
void findClosingBracket2() {
const SimpleTokenizer var(*this, "const auto g = []<typename T>() {};\n"); // #11275
const Token* const t = Token::findsimplematch(var.tokens(), "<");
ASSERT(t && Token::simpleMatch(t->findClosingBracket(), ">"));
}
void findClosingBracket3() {
const SimpleTokenizer var(*this, // #12789
"template <size_t I = 0, typename... ArgsT, std::enable_if_t<I < sizeof...(ArgsT)>* = nullptr>\n"
"void f();\n");
const Token* const t = Token::findsimplematch(var.tokens(), "<");
ASSERT(t && Token::simpleMatch(t->findClosingBracket(), ">"));
}
void findClosingBracket4() {
const SimpleTokenizer var(*this, // #12923
"template<template<class E> class T = std::vector, class U = std::vector<int>, class V = void>\n"
"class C;\n");
const Token *const t = Token::findsimplematch(var.tokens(), "<");
ASSERT(t);
const Token *const closing = t->findClosingBracket();
ASSERT(closing && closing == var.tokens()->tokAt(28));
}
void expressionString() {
const SimpleTokenizer var1(*this, "void f() { *((unsigned long long *)x) = 0; }");
const Token *const tok1 = Token::findsimplematch(var1.tokens(), "*");
ASSERT_EQUALS("*((unsigned long long*)x)", tok1->expressionString());
const SimpleTokenizer var2(*this, "typedef unsigned long long u64; void f() { *((u64 *)x) = 0; }");
const Token *const tok2 = Token::findsimplematch(var2.tokens(), "*");
ASSERT_EQUALS("*((unsigned long long*)x)", tok2->expressionString());
const SimpleTokenizer data3(*this, "void f() { return (t){1,2}; }");
ASSERT_EQUALS("return(t){1,2}", data3.tokens()->tokAt(5)->expressionString());
const SimpleTokenizer data4(*this, "void f() { return L\"a\"; }");
ASSERT_EQUALS("returnL\"a\"", data4.tokens()->tokAt(5)->expressionString());
const SimpleTokenizer data5(*this, "void f() { return U\"a\"; }");
ASSERT_EQUALS("returnU\"a\"", data5.tokens()->tokAt(5)->expressionString());
const SimpleTokenizer data6(*this, "x = \"\\0\\x1\\x2\\x3\\x4\\x5\\x6\\x7\";");
ASSERT_EQUALS("x=\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\"", data6.tokens()->next()->expressionString());
}
void hasKnownIntValue() const {
// pointer might be NULL
ValueFlow::Value v1(0);
// pointer points at buffer that is 2 bytes
ValueFlow::Value v2(2);
v2.valueType = ValueFlow::Value::ValueType::BUFFER_SIZE;
v2.setKnown();
TokensFrontBack tokensFrontBack(list);
Token token(tokensFrontBack);
ASSERT_EQUALS(true, token.addValue(v1));
ASSERT_EQUALS(true, token.addValue(v2));
ASSERT_EQUALS(false, token.hasKnownIntValue());
}
};
REGISTER_TEST(TestToken)
| null |
956 | cpp | cppcheck | testassert.cpp | test/testassert.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "checkassert.h"
#include "errortypes.h"
#include "fixture.h"
#include "helpers.h"
#include "settings.h"
#include <cstddef>
class TestAssert : public TestFixture {
public:
TestAssert() : TestFixture("TestAssert") {}
private:
const Settings settings = settingsBuilder().severity(Severity::warning).build();
#define check(...) check_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
void check_(const char* file, int line, const char (&code)[size]) {
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
// Check..
runChecks<CheckAssert>(tokenizer, this);
}
void run() override {
TEST_CASE(assignmentInAssert);
TEST_CASE(functionCallInAssert);
TEST_CASE(memberFunctionCallInAssert);
TEST_CASE(safeFunctionCallInAssert);
TEST_CASE(crash);
}
void safeFunctionCallInAssert() {
check(
"int a;\n"
"bool b = false;\n"
"int foo() {\n"
" if (b) { a = 1+2 };\n"
" return a;\n"
"}\n"
"assert(foo() == 3);");
ASSERT_EQUALS("", errout_str());
check(
"int foo(int a) {\n"
" int b=a+1;\n"
" return b;\n"
"}\n"
"assert(foo(1) == 2);");
ASSERT_EQUALS("", errout_str());
}
void functionCallInAssert() {
check(
"int a;\n"
"int foo() {\n"
" a = 1+2;\n"
" return a;\n"
"}\n"
"assert(foo() == 3);");
ASSERT_EQUALS("[test.cpp:6]: (warning) Assert statement calls a function which may have desired side effects: 'foo'.\n", errout_str());
// Ticket #4937 "false positive: Assert calls a function which may have desired side effects"
check("struct SquarePack {\n"
" static bool isRank1Or8( Square sq ) {\n"
" sq &= 0x38;\n"
" return sq == 0 || sq == 0x38;\n"
" }\n"
"};\n"
"void foo() {\n"
" assert( !SquarePack::isRank1Or8(push2) );\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct SquarePack {\n"
" static bool isRank1Or8( Square &sq ) {\n"
" sq &= 0x38;\n"
" return sq == 0 || sq == 0x38;\n"
" }\n"
"};\n"
"void foo() {\n"
" assert( !SquarePack::isRank1Or8(push2) );\n"
"}");
ASSERT_EQUALS("[test.cpp:8]: (warning) Assert statement calls a function which may have desired side effects: 'isRank1Or8'.\n", errout_str());
check("struct SquarePack {\n"
" static bool isRank1Or8( Square *sq ) {\n"
" *sq &= 0x38;\n"
" return *sq == 0 || *sq == 0x38;\n"
" }\n"
"};\n"
"void foo() {\n"
" assert( !SquarePack::isRank1Or8(push2) );\n"
"}");
ASSERT_EQUALS("[test.cpp:8]: (warning) Assert statement calls a function which may have desired side effects: 'isRank1Or8'.\n", errout_str());
check("struct SquarePack {\n"
" static bool isRank1Or8( Square *sq ) {\n"
" sq &= 0x38;\n"
" return sq == 0 || sq == 0x38;\n"
" }\n"
"};\n"
"void foo() {\n"
" assert( !SquarePack::isRank1Or8(push2) );\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct Geometry {\n"
" int nbv;\n"
" int empty() { return (nbv == 0); }\n"
" void ReadGeometry();\n"
"};\n"
"\n"
"void Geometry::ReadGeometry() {\n"
" assert(empty());\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct S {\n" // #4811
" void f() const;\n"
" bool g(std::ostream& os = std::cerr) const;\n"
"};\n"
"void S::f() const {\n"
" assert(g());\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void memberFunctionCallInAssert() {
check("struct SquarePack {\n"
" void Foo();\n"
"};\n"
"void foo(SquarePack s) {\n"
" assert( s.Foo() );\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (warning) Assert statement calls a function which may have desired side effects: 'Foo'.\n", errout_str());
check("struct SquarePack {\n"
" int Foo() const;\n"
"};\n"
"void foo(SquarePack* s) {\n"
" assert( s->Foo() );\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct SquarePack {\n"
" static int Foo();\n"
"};\n"
"void foo(SquarePack* s) {\n"
" assert( s->Foo() );\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct SquarePack {\n"
"};\n"
"void foo(SquarePack* s) {\n"
" assert( s->Foo() );\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void assignmentInAssert() {
check("void f() {\n"
" int a; a = 0;\n"
" assert(a = 2);\n"
" return a;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Assert statement modifies 'a'.\n", errout_str());
check("void f(int a) {\n"
" assert(a == 2);\n"
" return a;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int a, int b) {\n"
" assert(a == 2 && (b = 1));\n"
" return a;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Assert statement modifies 'b'.\n", errout_str());
check("void f() {\n"
" int a; a = 0;\n"
" assert(a += 2);\n"
" return a;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Assert statement modifies 'a'.\n", errout_str());
check("void f() {\n"
" int a; a = 0;\n"
" assert(a *= 2);\n"
" return a;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Assert statement modifies 'a'.\n", errout_str());
check("void f() {\n"
" int a; a = 0;\n"
" assert(a -= 2);\n"
" return a;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Assert statement modifies 'a'.\n", errout_str());
check("void f() {\n"
" int a = 0;\n"
" assert(a--);\n"
" return a;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Assert statement modifies 'a'.\n", errout_str());
check("void f() {\n"
" int a = 0;\n"
" assert(--a);\n"
" return a;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Assert statement modifies 'a'.\n", errout_str());
check("void f() {\n"
" assert(std::all_of(first, last, []() {\n"
" auto tmp = x.someValue();\n"
" auto const expected = someOtherValue;\n"
" return tmp == expected;\n"
" }));\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void crash() {
check("void foo() {\n"
" assert(sizeof(struct { int a[x++]; })==sizeof(int));\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo() {\n" // #9790
" assert(kad_bucket_hash(&(kad_guid) { .bytes = { 0 } }, & (kad_guid){.bytes = { 0 }}) == -1);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
};
REGISTER_TEST(TestAssert)
| null |
957 | cpp | cppcheck | options.cpp | test/options.cpp | null | // Cppcheck - A tool for static C/C++ code analysis
// Copyright (C) 2007-2024 Cppcheck team.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#include "options.h"
options::options(int argc, const char* const argv[])
: mWhichTests(argv + 1, argv + argc)
,mQuiet(mWhichTests.count("-q") != 0)
,mHelp(mWhichTests.count("-h") != 0 || mWhichTests.count("--help"))
,mSummary(mWhichTests.count("-n") == 0)
,mDryRun(mWhichTests.count("-d") != 0)
,mExe(argv[0])
{
for (std::set<std::string>::const_iterator it = mWhichTests.cbegin(); it != mWhichTests.cend();) {
if (!it->empty() && (((*it)[0] == '-') || (it->find("::") != std::string::npos && mWhichTests.count(it->substr(0, it->find("::"))))))
it = mWhichTests.erase(it);
else
++it;
}
if (mWhichTests.empty()) {
mWhichTests.insert("");
}
}
bool options::quiet() const
{
return mQuiet;
}
bool options::help() const
{
return mHelp;
}
bool options::summary() const
{
return mSummary;
}
bool options::dry_run() const
{
return mDryRun;
}
const std::set<std::string>& options::which_test() const
{
return mWhichTests;
}
const std::string& options::exe() const
{
return mExe;
}
| null |
958 | cpp | cppcheck | testvalueflow.cpp | test/testvalueflow.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "errortypes.h"
#include "fixture.h"
#include "helpers.h"
#include "mathlib.h"
#include "platform.h"
#include "settings.h"
#include "standards.h"
#include "token.h"
#include "tokenize.h"
#include "vfvalue.h"
#include <algorithm>
#include <climits>
#include <cmath>
#include <cstdint>
#include <cstring>
#include <functional>
#include <list>
#include <set>
#include <sstream>
#include <string>
#include <vector>
class TestValueFlow : public TestFixture {
public:
TestValueFlow() : TestFixture("TestValueFlow") {}
private:
/*const*/ Settings settings = settingsBuilder().library("std.cfg").build();
void run() override {
// strcpy, abort cfg
constexpr char cfg[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <function name=\"strcpy\"> <arg nr=\"1\"><not-null/></arg> </function>\n"
" <function name=\"abort\"> <noreturn>true</noreturn> </function>\n" // abort is a noreturn function
"</def>";
settings = settingsBuilder(settings).libraryxml(cfg, sizeof(cfg)).build();
TEST_CASE(valueFlowNumber);
TEST_CASE(valueFlowString);
TEST_CASE(valueFlowPointerAlias);
TEST_CASE(valueFlowLifetime);
TEST_CASE(valueFlowArrayElement);
TEST_CASE(valueFlowMove);
TEST_CASE(valueFlowBitAnd);
TEST_CASE(valueFlowRightShift);
TEST_CASE(valueFlowCalculations);
TEST_CASE(valueFlowSizeof);
TEST_CASE(valueFlowComma);
TEST_CASE(valueFlowErrorPath);
TEST_CASE(valueFlowBeforeCondition);
TEST_CASE(valueFlowBeforeConditionAndAndOrOrGuard);
TEST_CASE(valueFlowBeforeConditionAssignIncDec);
TEST_CASE(valueFlowBeforeConditionFunctionCall);
TEST_CASE(valueFlowBeforeConditionGlobalVariables);
TEST_CASE(valueFlowBeforeConditionGoto);
TEST_CASE(valueFlowBeforeConditionIfElse);
TEST_CASE(valueFlowBeforeConditionLoop);
TEST_CASE(valueFlowBeforeConditionMacro);
TEST_CASE(valueFlowBeforeConditionSizeof);
TEST_CASE(valueFlowBeforeConditionSwitch);
TEST_CASE(valueFlowBeforeConditionTernaryOp);
TEST_CASE(valueFlowBeforeConditionForward);
TEST_CASE(valueFlowBeforeConditionConstructor);
TEST_CASE(valueFlowAfterAssign);
TEST_CASE(valueFlowAfterSwap);
TEST_CASE(valueFlowAfterCondition);
TEST_CASE(valueFlowAfterConditionTernary);
TEST_CASE(valueFlowAfterConditionExpr);
TEST_CASE(valueFlowAfterConditionSeveralNot);
TEST_CASE(valueFlowForwardCompoundAssign);
TEST_CASE(valueFlowForwardCorrelatedVariables);
TEST_CASE(valueFlowForwardModifiedVariables);
TEST_CASE(valueFlowForwardFunction);
TEST_CASE(valueFlowForwardTernary);
TEST_CASE(valueFlowForwardLambda);
TEST_CASE(valueFlowForwardTryCatch);
TEST_CASE(valueFlowForwardInconclusiveImpossible);
TEST_CASE(valueFlowForwardConst);
TEST_CASE(valueFlowForwardAfterCondition);
TEST_CASE(valueFlowFwdAnalysis);
TEST_CASE(valueFlowSwitchVariable);
TEST_CASE(valueFlowForLoop);
TEST_CASE(valueFlowSubFunction);
TEST_CASE(valueFlowFunctionReturn);
TEST_CASE(valueFlowFunctionDefaultParameter);
TEST_CASE(knownValue);
TEST_CASE(valueFlowSizeofForwardDeclaredEnum);
TEST_CASE(valueFlowGlobalVar);
TEST_CASE(valueFlowGlobalConstVar);
TEST_CASE(valueFlowGlobalStaticVar);
TEST_CASE(valueFlowInlineAssembly);
TEST_CASE(valueFlowSameExpression);
TEST_CASE(valueFlowUninit);
TEST_CASE(valueFlowConditionExpressions);
TEST_CASE(valueFlowContainerSize);
TEST_CASE(valueFlowContainerElement);
TEST_CASE(valueFlowDynamicBufferSize);
TEST_CASE(valueFlowSafeFunctionParameterValues);
TEST_CASE(valueFlowUnknownFunctionReturn);
TEST_CASE(valueFlowUnknownFunctionReturnRand);
TEST_CASE(valueFlowUnknownFunctionReturnMalloc);
TEST_CASE(valueFlowPointerAliasDeref);
TEST_CASE(valueFlowCrashIncompleteCode);
TEST_CASE(valueFlowCrash);
TEST_CASE(valueFlowHang);
TEST_CASE(valueFlowCrashConstructorInitialization);
TEST_CASE(valueFlowUnknownMixedOperators);
TEST_CASE(valueFlowSolveExpr);
TEST_CASE(valueFlowIdempotent);
TEST_CASE(valueFlowUnsigned);
TEST_CASE(valueFlowMod);
TEST_CASE(valueFlowIncDec);
TEST_CASE(valueFlowNotNull);
TEST_CASE(valueFlowSymbolic);
TEST_CASE(valueFlowSymbolicIdentity);
TEST_CASE(valueFlowSymbolicStrlen);
TEST_CASE(valueFlowSmartPointer);
TEST_CASE(valueFlowImpossibleMinMax);
TEST_CASE(valueFlowImpossibleIncDec);
TEST_CASE(valueFlowImpossibleUnknownConstant);
TEST_CASE(valueFlowContainerEqual);
TEST_CASE(valueFlowBailoutIncompleteVar);
TEST_CASE(performanceIfCount);
}
static bool isNotTokValue(const ValueFlow::Value &val) {
return !val.isTokValue();
}
// cppcheck-suppress unusedPrivateFunction
static bool isNotLifetimeValue(const ValueFlow::Value& val) {
return !val.isLifetimeValue();
}
static bool isNotUninitValue(const ValueFlow::Value& val) {
return !val.isUninitValue();
}
static bool isNotPossible(const ValueFlow::Value& val) {
return !val.isPossible();
}
static bool isNotKnown(const ValueFlow::Value& val) {
return !val.isKnown();
}
static bool isNotInconclusive(const ValueFlow::Value& val) {
return !val.isInconclusive();
}
static bool isNotImpossible(const ValueFlow::Value& val) {
return !val.isImpossible();
}
#define testValueOfXKnown(...) testValueOfXKnown_(__FILE__, __LINE__, __VA_ARGS__)
bool testValueOfXKnown_(const char* file, int line, const char code[], unsigned int linenr, int value) {
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) {
if (tok->str() == "x" && tok->linenr() == linenr) {
if (std::any_of(tok->values().begin(), tok->values().end(), [&](const ValueFlow::Value& val) {
if (val.isSymbolicValue())
return false;
if (val.isKnown() && val.intvalue == value)
return true;
return false;
}))
return true;
}
}
return false;
}
bool testValueOfXKnown_(const char* file, int line, const char code[], unsigned int linenr, const std::string& expr, int value) {
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
for (const Token* tok = tokenizer.tokens(); tok; tok = tok->next()) {
if (tok->str() == "x" && tok->linenr() == linenr) {
if (std::any_of(tok->values().begin(), tok->values().end(), [&](const ValueFlow::Value& val) {
if (!val.isSymbolicValue())
return false;
if (val.isKnown() && val.intvalue == value && val.tokvalue->expressionString() == expr)
return true;
return false;
}))
return true;
}
}
return false;
}
#define testValueOfXImpossible(...) testValueOfXImpossible_(__FILE__, __LINE__, __VA_ARGS__)
bool testValueOfXImpossible_(const char* file, int line, const char code[], unsigned int linenr, int value) {
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) {
if (tok->str() == "x" && tok->linenr() == linenr) {
if (std::any_of(tok->values().begin(), tok->values().end(), [&](const ValueFlow::Value& val) {
if (val.isSymbolicValue())
return false;
if (val.isImpossible() && val.intvalue == value)
return true;
return false;
}))
return true;
}
}
return false;
}
bool testValueOfXImpossible_(const char* file, int line, const char code[], unsigned int linenr, const std::string& expr, int value)
{
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
for (const Token* tok = tokenizer.tokens(); tok; tok = tok->next()) {
if (tok->str() == "x" && tok->linenr() == linenr) {
if (std::any_of(tok->values().begin(), tok->values().end(), [&](const ValueFlow::Value& val) {
if (!val.isSymbolicValue())
return false;
if (val.isImpossible() && val.intvalue == value && val.tokvalue->expressionString() == expr)
return true;
return false;
}))
return true;
}
}
return false;
}
#define testValueOfXInconclusive(code, linenr, value) testValueOfXInconclusive_(code, linenr, value, __FILE__, __LINE__)
bool testValueOfXInconclusive_(const char code[], unsigned int linenr, int value, const char* file, int line) {
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) {
if (tok->str() == "x" && tok->linenr() == linenr) {
if (std::any_of(tok->values().begin(), tok->values().end(), [&](const ValueFlow::Value& val) {
if (val.isSymbolicValue())
return false;
if (val.isInconclusive() && val.intvalue == value)
return true;
return false;
}))
return true;
}
}
return false;
}
#define testValueOfX(...) testValueOfX_(__FILE__, __LINE__, __VA_ARGS__)
bool testValueOfX_(const char* file, int line, const char code[], unsigned int linenr, int value, const Settings *s = nullptr) {
const Settings *settings1 = s ? s : &settings;
// Tokenize..
SimpleTokenizer tokenizer(*settings1, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) {
if (tok->str() == "x" && tok->linenr() == linenr) {
if (std::any_of(tok->values().cbegin(), tok->values().cend(), [&](const ValueFlow::Value& v) {
return v.isIntValue() && !v.isImpossible() && v.intvalue == value;
}))
return true;
}
}
return false;
}
bool testValueOfX_(const char* file, int line, const char code[], unsigned int linenr, const std::string& expr, int value)
{
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
for (const Token* tok = tokenizer.tokens(); tok; tok = tok->next()) {
if (tok->str() == "x" && tok->linenr() == linenr) {
if (std::any_of(tok->values().cbegin(), tok->values().cend(), [&](const ValueFlow::Value& v) {
return v.isSymbolicValue() && !v.isImpossible() && v.intvalue == value && v.tokvalue->expressionString() == expr;
}))
return true;
}
}
return false;
}
bool testValueOfX_(const char* file, int line, const char code[], unsigned int linenr, double value, double diff) {
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) {
if (tok->str() == "x" && tok->linenr() == linenr) {
if (std::any_of(tok->values().cbegin(), tok->values().cend(), [&](const ValueFlow::Value& v) {
return v.isFloatValue() && !v.isImpossible() && v.floatValue >= value - diff && v.floatValue <= value + diff;
}))
return true;
}
}
return false;
}
#define getErrorPathForX(code, linenr) getErrorPathForX_(code, linenr, __FILE__, __LINE__)
std::string getErrorPathForX_(const char code[], unsigned int linenr, const char* file, int line) {
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) {
if (tok->str() != "x" || tok->linenr() != linenr)
continue;
std::ostringstream ostr;
for (const ValueFlow::Value &v : tok->values()) {
for (const ErrorPathItem &ep : v.errorPath) {
const Token *eptok = ep.first;
const std::string &msg = ep.second;
ostr << eptok->linenr() << ',' << msg << '\n';
}
}
return ostr.str();
}
return "";
}
bool testValueOfX_(const char* file, int line, const char code[], unsigned int linenr, const char value[], ValueFlow::Value::ValueType type) {
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
const std::size_t len = strlen(value);
for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) {
if (tok->str() == "x" && tok->linenr() == linenr) {
if (std::any_of(tok->values().cbegin(), tok->values().cend(), [&](const ValueFlow::Value& v) {
return v.valueType == type && Token::simpleMatch(v.tokvalue, value, len);
}))
return true;
}
}
return false;
}
#define testLifetimeOfX(...) testLifetimeOfX_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
bool testLifetimeOfX_(const char* file, int line, const char (&code)[size], unsigned int linenr, const char value[], ValueFlow::Value::LifetimeScope lifetimeScope = ValueFlow::Value::LifetimeScope::Local) {
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
const std::size_t len = strlen(value);
for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) {
if (tok->str() == "x" && tok->linenr() == linenr) {
if (std::any_of(tok->values().cbegin(), tok->values().cend(), [&](const ValueFlow::Value& v) {
return v.isLifetimeValue() && v.lifetimeScope == lifetimeScope && Token::simpleMatch(v.tokvalue, value, len);
}))
return true;
}
}
return false;
}
bool testValueOfX_(const char* file, int line, const char code[], unsigned int linenr, int value, ValueFlow::Value::ValueType type) {
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) {
if (tok->str() == "x" && tok->linenr() == linenr) {
if (std::any_of(tok->values().cbegin(), tok->values().cend(), [&](const ValueFlow::Value& v) {
return v.valueType == type && v.intvalue == value;
}))
return true;
}
}
return false;
}
bool testValueOfX_(const char* file, int line, const char code[], unsigned int linenr, ValueFlow::Value::MoveKind moveKind) {
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) {
if (tok->str() == "x" && tok->linenr() == linenr) {
if (std::any_of(tok->values().cbegin(), tok->values().cend(), [&](const ValueFlow::Value& v) {
return v.isMovedValue() && v.moveKind == moveKind;
}))
return true;
}
}
return false;
}
#define testConditionalValueOfX(code, linenr, value) testConditionalValueOfX_(code, linenr, value, __FILE__, __LINE__)
template<size_t size>
bool testConditionalValueOfX_(const char (&code)[size], unsigned int linenr, int value, const char* file, int line) {
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) {
if (tok->str() == "x" && tok->linenr() == linenr) {
if (std::any_of(tok->values().cbegin(), tok->values().cend(), [&](const ValueFlow::Value& v) {
return v.isIntValue() && v.intvalue == value && v.condition;
}))
return true;
}
}
return false;
}
#define bailout(...) bailout_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
void bailout_(const char* file, int line, const char (&code)[size]) {
const Settings s = settingsBuilder().debugwarnings().build();
std::vector<std::string> files(1, "test.cpp");
Tokenizer tokenizer(s, *this);
PreprocessorHelper::preprocess(code, files, tokenizer, *this);
// Tokenize..
ASSERT_LOC(tokenizer.simplifyTokens1(""), file, line);
}
#define tokenValues(...) tokenValues_(__FILE__, __LINE__, __VA_ARGS__)
std::list<ValueFlow::Value> tokenValues_(const char* file, int line, const char code[], const char tokstr[], const Settings *s = nullptr, bool cpp = true) {
SimpleTokenizer tokenizer(s ? *s : settings, *this);
ASSERT_LOC(tokenizer.tokenize(code, cpp), file, line);
const Token *tok = Token::findmatch(tokenizer.tokens(), tokstr);
return tok ? tok->values() : std::list<ValueFlow::Value>();
}
std::list<ValueFlow::Value> tokenValues_(const char* file, int line, const char code[], const char tokstr[], ValueFlow::Value::ValueType vt, const Settings *s = nullptr) {
std::list<ValueFlow::Value> values = tokenValues_(file, line, code, tokstr, s);
values.remove_if([&](const ValueFlow::Value& v) {
return v.valueType != vt;
});
return values;
}
#define lifetimeValues(...) lifetimeValues_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
std::vector<std::string> lifetimeValues_(const char* file, int line, const char (&code)[size], const char tokstr[], const Settings *s = nullptr) {
std::vector<std::string> result;
SimpleTokenizer tokenizer(s ? *s : settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
const Token *tok = Token::findmatch(tokenizer.tokens(), tokstr);
if (!tok)
return result;
for (const ValueFlow::Value& value:tok->values()) {
if (!value.isLifetimeValue())
continue;
if (!value.tokvalue)
continue;
result.push_back(value.tokvalue->expressionString());
}
return result;
}
#define valueOfTok(...) valueOfTok_(__FILE__, __LINE__, __VA_ARGS__)
ValueFlow::Value valueOfTok_(const char* file, int line, const char code[], const char tokstr[], const Settings *s = nullptr, bool cpp = true) {
std::list<ValueFlow::Value> values = removeImpossible(tokenValues_(file, line, code, tokstr, s, cpp));
return values.size() == 1U && !values.front().isTokValue() ? values.front() : ValueFlow::Value();
}
static std::list<ValueFlow::Value> removeSymbolicTok(std::list<ValueFlow::Value> values)
{
values.remove_if([](const ValueFlow::Value& v) {
return v.isSymbolicValue() || v.isTokValue();
});
return values;
}
static std::list<ValueFlow::Value> removeImpossible(std::list<ValueFlow::Value> values)
{
values.remove_if(std::mem_fn(&ValueFlow::Value::isImpossible));
return values;
}
void valueFlowNumber() {
ASSERT_EQUALS(123, valueOfTok("x=123;", "123").intvalue);
ASSERT_EQUALS_DOUBLE(192.0, valueOfTok("x=0x0.3p10;", "0x0.3p10").floatValue, 1e-5); // 3 * 16^-1 * 2^10 = 192
ASSERT(std::fabs(valueOfTok("x=0.5;", "0.5").floatValue - 0.5) < 0.1);
ASSERT_EQUALS(10, valueOfTok("enum {A=10,B=15}; x=A+0;", "+").intvalue);
ASSERT_EQUALS(0, valueOfTok("x=false;", "false").intvalue);
ASSERT_EQUALS(1, valueOfTok("x=true;", "true").intvalue);
ASSERT_EQUALS(0, valueOfTok("x(NULL);", "NULL").intvalue);
ASSERT_EQUALS((int)('a'), valueOfTok("x='a';", "'a'").intvalue);
ASSERT_EQUALS((int)('\n'), valueOfTok("x='\\n';", "'\\n'").intvalue);
TODO_ASSERT_EQUALS(0xFFFFFFFF00000000, 0, valueOfTok("x=0xFFFFFFFF00000000;", "0xFFFFFFFF00000000").intvalue); // #7701
ASSERT_EQUALS_DOUBLE(16, valueOfTok("x=(double)16;", "(").floatValue, 1e-5);
ASSERT_EQUALS_DOUBLE(0.0625, valueOfTok("x=1/(double)16;", "/").floatValue, 1e-5);
const Settings settingsC23 = settingsBuilder().c(Standards::C23).build();
ASSERT_EQUALS(1, valueOfTok("x=true;", "true", &settingsC23, false).intvalue);
ASSERT_EQUALS(0, valueOfTok("x=false;", "false", &settingsC23, false).intvalue);
const Settings settingsC17 = settingsBuilder().c(Standards::C17).build();
ASSERT(!valueOfTok("x=true;", "true", &settingsC17, false).isKnown());
ASSERT(!valueOfTok("x=false;", "false", &settingsC17, false).isKnown());
// scope
{
const char code[] = "namespace N { enum E {e0,e1}; }\n"
"void foo() { x = N::e1; }";
ASSERT_EQUALS(1, valueOfTok(code, "::").intvalue);
}
}
void valueFlowString() {
const char *code;
// valueFlowAfterAssign
code = "const char * f() {\n"
" static const char *x;\n"
" if (a) x = \"123\";\n"
" return x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 4, "\"123\"", ValueFlow::Value::ValueType::TOK));
// valueFlowSubFunction
code = "void dostuff(const char *x) {\n"
" f(x);\n"
"}\n"
"\n"
"void test() { dostuff(\"abc\"); }";
ASSERT_EQUALS(true, testValueOfX(code, 2, "\"abc\"", ValueFlow::Value::ValueType::TOK));
}
void valueFlowPointerAlias() {
const char *code;
std::list<ValueFlow::Value> values;
code = "const char * f() {\n"
" static const char *x;\n"
" static char ret[10];\n"
" if (a) x = &ret[0];\n"
" return x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 5, "& ret [ 0 ]", ValueFlow::Value::ValueType::TOK));
// dead pointer
code = "void f() {\n"
" int *x;\n"
" if (cond) { int i; x = &i; }\n"
" *x = 0;\n" // <- x can point at i
"}";
ASSERT_EQUALS(true, testValueOfX(code, 4, "& i", ValueFlow::Value::ValueType::TOK));
code = "void f() {\n"
" struct X *x;\n"
" x = &x[1];\n"
"}";
values = tokenValues(code, "&");
values.remove_if(&isNotTokValue);
ASSERT_EQUALS(true, values.empty());
values = tokenValues(code, "x [");
values.remove_if(&isNotTokValue);
ASSERT_EQUALS(true, values.empty());
}
void valueFlowLifetime() {
std::vector<std::string> lifetimes;
{
const char code[] = "void f() {\n"
" int a = 1;\n"
" auto x = [&]() { return a + 1; };\n"
" auto b = x;\n"
"}\n";
ASSERT_EQUALS(true, testLifetimeOfX(code, 4, "a + 1"));
}
{
const char code[] = "void f() {\n"
" int a = 1;\n"
" auto x = [=]() { return a + 1; };\n"
" auto b = x;\n"
"}\n";
ASSERT_EQUALS(false, testLifetimeOfX(code, 4, "a ;"));
}
{
const char code[] = "void f(int v) {\n"
" int a = v;\n"
" int * p = &a;\n"
" auto x = [=]() { return p + 1; };\n"
" auto b = x;\n"
"}\n";
ASSERT_EQUALS(true, testLifetimeOfX(code, 5, "a ;"));
}
{
const char code[] = "void f() {\n"
" std::vector<int> v;\n"
" auto x = v.begin();\n"
" auto it = x;\n"
"}\n";
ASSERT_EQUALS(true, testLifetimeOfX(code, 4, "v . begin"));
}
{
const char code[] = "void f() {\n"
" std::vector<int> v;\n"
" auto x = v.begin() + 1;\n"
" auto it = x;\n"
"}\n";
ASSERT_EQUALS(true, testLifetimeOfX(code, 4, "v . begin"));
}
{
const char code[] = "int* f() {\n"
" std::vector<int> v;\n"
" int * x = v.data();\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testLifetimeOfX(code, 4, "v . data"));
}
{
const char code[] = "int* f() {\n"
" std::vector<int> v;\n"
" int * x = v.data() + 1;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testLifetimeOfX(code, 4, "v . data"));
}
{
const char code[] = "int f(int* a) {\n"
" int **p = &a;\n"
" int * x = *p;\n"
" return x; \n"
"}\n";
ASSERT_EQUALS(false, testLifetimeOfX(code, 4, "a"));
}
{
const char code[] = "void f() {\n"
" int i = 0;\n"
" void* x = (void*)&i;\n"
"}\n";
lifetimes = lifetimeValues(code, "( void * )");
ASSERT_EQUALS(true, lifetimes.size() == 1);
ASSERT_EQUALS(true, lifetimes.front() == "i");
}
{
const char code[] = "struct T {\n" // #10810
" static int g() { return 0; }\n"
"};\n"
"T t;\n"
"struct S { int i; };\n"
"S f() {\n"
" S s = { decltype(t)::g() };\n"
" return s;\n"
"};\n";
lifetimes = lifetimeValues(code, "=");
ASSERT_EQUALS(true, lifetimes.empty());
}
{
const char code[] = "struct T {\n" // #10838
" void f();\n"
" double d[4][4];\n"
"};\n"
"void T::f() {\n"
" auto g = [this]() -> double(&)[4] {\n"
" double(&q)[4] = d[0];\n"
" return q;\n"
" };\n"
"}\n";
lifetimes = lifetimeValues(code, "return"); // don't crash
ASSERT_EQUALS(true, lifetimes.empty());
}
}
void valueFlowArrayElement() {
const char *code;
code = "void f() {\n"
" const int x[] = {43,23,12};\n"
" return x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, "{ 43 , 23 , 12 }", ValueFlow::Value::ValueType::TOK));
code = "void f() {\n"
" const char x[] = \"abcd\";\n"
" return x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, "\"abcd\"", ValueFlow::Value::ValueType::TOK));
code = "void f() {\n"
" char x[32] = \"abcd\";\n"
" return x;\n"
"}";
TODO_ASSERT_EQUALS(true, false, testValueOfX(code, 3U, "\"abcd\"", ValueFlow::Value::ValueType::TOK));
code = "void f() {\n"
" int a[10];\n"
" int *x = a;\n" // <- a value is a
" *x = 0;\n" // .. => x value is a
"}";
ASSERT_EQUALS(true, testValueOfX(code, 4, "a", ValueFlow::Value::ValueType::TOK));
code = "char f() {\n"
" const char *x = \"abcd\";\n"
" return x[0];\n"
"}";
ASSERT_EQUALS((int)('a'), valueOfTok(code, "[").intvalue);
code = "char f() {\n"
" const char *x = \"\";\n"
" return x[0];\n"
"}";
ASSERT_EQUALS(0, valueOfTok(code, "[").intvalue);
code = "int g() { return 3; }\n"
"void f() {\n"
" const int x[2] = { g(), g() };\n"
" return x[0];\n"
"}\n";
ASSERT_EQUALS(3, valueOfTok(code, "[ 0").intvalue);
code = "int g() { return 3; }\n"
"void f() {\n"
" const int x[2] = { g(), g() };\n"
" return x[1];\n"
"}\n";
ASSERT_EQUALS(3, valueOfTok(code, "[ 1").intvalue);
}
void valueFlowMove() {
const char *code;
code = "void f() {\n"
" X x;\n"
" g(std::move(x));\n"
" y=x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 4U, ValueFlow::Value::MoveKind::MovedVariable));
code = "void f() {\n"
" X x;\n"
" g(std::forward<X>(x));\n"
" y=x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 4U, ValueFlow::Value::MoveKind::ForwardedVariable));
code = "void f() {\n"
" X x;\n"
" g(std::move(x).getA());\n" // Only parts of x might be moved out
" y=x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 4U, ValueFlow::Value::MoveKind::MovedVariable));
code = "void f() {\n"
" X x;\n"
" g(std::forward<X>(x).getA());\n" // Only parts of x might be moved out
" y=x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 4U, ValueFlow::Value::MoveKind::ForwardedVariable));
code = "void f() {\n"
" X x;\n"
" g(std::move(x));\n"
" x.clear();\n"
" y=x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 5U, ValueFlow::Value::MoveKind::MovedVariable));
code = "void f() {\n"
" X x;\n"
" g(std::move(x));\n"
" y=x->y;\n"
" z=x->z;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 5U, ValueFlow::Value::MoveKind::MovedVariable));
code = "void f(int i) {\n"
" X x;\n"
" z = g(std::move(x));\n"
" y = x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 4U, ValueFlow::Value::MoveKind::MovedVariable));
code = "void f(int i) {\n"
" X x;\n"
" y = g(std::move(x),\n"
" x.size());\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 4U, ValueFlow::Value::MoveKind::MovedVariable));
code = "void f(int i) {\n"
" X x;\n"
" x = g(std::move(x));\n"
" y = x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 4U, ValueFlow::Value::MoveKind::MovedVariable));
code = "A f(int i) {\n"
" X x;\n"
" if (i)"
" return g(std::move(x));\n"
" return h(std::move(x));\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 5U, ValueFlow::Value::MoveKind::MovedVariable));
code = "struct X {\n"
"};\n"
"struct Data {\n"
" template<typename Fun>\n"
" void foo(Fun f) {}\n"
"};\n"
"Data g(X value) { return Data(); }\n"
"void f() {\n"
" X x;\n"
" g(std::move(x)).foo([=](int value) mutable {;});\n"
" X y=x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 11U, ValueFlow::Value::MoveKind::MovedVariable));
code = "void f(int x) {\n"
" g(std::move(x));\n"
" y=x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 3U, ValueFlow::Value::MoveKind::MovedVariable));
code = "void g(std::string);\n"
"void foo(std::string x) {\n"
" g(std::move(x));\n"
" int counter = 0;\n"
"\n"
" for (int i = 0; i < 5; i++) {\n"
" if (i % 2 == 0) {\n"
" x = std::to_string(i);\n"
" counter++;\n"
" }\n"
" }\n"
" for (int i = 0; i < counter; i++) {\n"
" if(x > 5) {}\n"
" }\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 13U, ValueFlow::Value::MoveKind::MovedVariable));
}
void valueFlowCalculations() {
const char *code;
// Different operators
ASSERT_EQUALS(5, valueOfTok("3 + (a ? b : 2);", "+").intvalue);
ASSERT_EQUALS(1, valueOfTok("3 - (a ? b : 2);", "-").intvalue);
ASSERT_EQUALS(6, valueOfTok("3 * (a ? b : 2);", "*").intvalue);
ASSERT_EQUALS(6, valueOfTok("13 / (a ? b : 2);", "/").intvalue);
ASSERT_EQUALS(1, valueOfTok("13 % (a ? b : 2);", "%").intvalue);
ASSERT_EQUALS(0, valueOfTok("3 == (a ? b : 2);", "==").intvalue);
ASSERT_EQUALS(1, valueOfTok("3 != (a ? b : 2);", "!=").intvalue);
ASSERT_EQUALS(1, valueOfTok("3 > (a ? b : 2);", ">").intvalue);
ASSERT_EQUALS(1, valueOfTok("3 >= (a ? b : 2);", ">=").intvalue);
ASSERT_EQUALS(0, valueOfTok("3 < (a ? b : 2);", "<").intvalue);
ASSERT_EQUALS(0, valueOfTok("3 <= (a ? b : 2);", "<=").intvalue);
ASSERT_EQUALS(1, valueOfTok("(UNKNOWN_TYPE)1;","(").intvalue);
ASSERT(tokenValues("(UNKNOWN_TYPE)1000;","(").empty()); // don't know if there is truncation, sign extension
ASSERT_EQUALS(255, valueOfTok("(unsigned char)~0;", "(").intvalue);
ASSERT_EQUALS(0, valueOfTok("(int)0;", "(").intvalue);
ASSERT_EQUALS(3, valueOfTok("(int)(1+2);", "(").intvalue);
ASSERT_EQUALS(0, valueOfTok("(UNKNOWN_TYPE*)0;","(").intvalue);
ASSERT_EQUALS(100, valueOfTok("(int)100.0;", "(").intvalue);
ASSERT_EQUALS(10, valueOfTok("x = static_cast<int>(10);", "( 10 )").intvalue);
ASSERT_EQUALS(0, valueOfTok("x = sizeof (struct {int a;}) * 0;", "*").intvalue);
// Don't calculate if there is UB
ASSERT(tokenValues(";-1<<10;","<<").empty());
ASSERT(tokenValues(";10<<-1;","<<").empty());
ASSERT(tokenValues(";10<<64;","<<").empty());
ASSERT(tokenValues(";-1>>10;",">>").empty());
ASSERT(tokenValues(";10>>-1;",">>").empty());
ASSERT(tokenValues(";10>>64;",">>").empty());
ASSERT(tokenValues(";((-1) * 9223372036854775807LL - 1) / (-1);", "/").empty()); // #12109
ASSERT_EQUALS(tokenValues(";((-1) * 9223372036854775807LL - 1) % (-1);", "%").size(), 1);
code = "float f(const uint16_t& value) {\n"
" const uint16_t uVal = value; \n"
" return static_cast<float>(uVal) / 2;\n"
"}\n";
ASSERT_EQUALS(true, tokenValues(code, "/").empty());
// calculation using 1,2 variables/values
code = "void f(int x) {\n"
" a = x+456;\n"
" if (x==123) {}"
"}";
ASSERT_EQUALS(579, valueOfTok(code, "+").intvalue);
code = "void f(int x, int y) {\n"
" a = x+y;\n"
" if (x==123 || y==456) {}"
"}";
ASSERT_EQUALS(0, valueOfTok(code, "+").intvalue);
code = "void f(int x) {\n"
" a = x+x;\n"
" if (x==123) {}"
"}";
ASSERT_EQUALS(246, valueOfTok(code, "+").intvalue);
code = "void f(int x, int y) {\n"
" a = x*x;\n"
" if (x==2) {}\n"
" if (x==4) {}\n"
"}";
std::list<ValueFlow::Value> values = tokenValues(code,"*");
ASSERT_EQUALS(2U, values.size());
ASSERT_EQUALS(4, values.front().intvalue);
ASSERT_EQUALS(16, values.back().intvalue);
code = "void f(int x) {\n"
" if (x == 3) {}\n"
" a = x * (1 - x - 1);\n"
"}";
ASSERT_EQUALS(-9, valueOfTok(code, "*").intvalue);
// addition of different variables with known values
code = "int f(int x) {\n"
" int a = 1;\n"
" while (x!=3) { x+=a; }\n"
" return x/a;\n"
"}\n";
ASSERT_EQUALS(3, valueOfTok(code, "/").intvalue);
// ? :
code = "x = y ? 2 : 3;\n";
values = tokenValues(code,"?");
ASSERT_EQUALS(2U, values.size());
ASSERT_EQUALS(2, values.front().intvalue);
ASSERT_EQUALS(3, values.back().intvalue);
code = "void f(int a) { x = a ? 2 : 3; }\n";
values = tokenValues(code,"?");
ASSERT_EQUALS(2U, values.size());
ASSERT_EQUALS(2, values.front().intvalue);
ASSERT_EQUALS(3, values.back().intvalue);
code = "x = (2<5) ? 2 : 3;\n";
values = tokenValues(code, "?");
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(2, values.front().intvalue);
code = "x = 123 ? : 456;\n";
values = tokenValues(code, "?");
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(123, values.empty() ? 0 : values.front().intvalue);
code = "int f() {\n"
" const int i = 1;\n"
" int x = i < 0 ? 0 : 1;\n"
" return x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 1));
// ~
code = "x = ~0U;";
values = tokenValues(code,"~");
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(~0U, values.back().intvalue);
// !
code = "void f(int x) {\n"
" a = !x;\n"
" if (x==0) {}\n"
"}";
values = removeImpossible(tokenValues(code, "!"));
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(1, values.back().intvalue);
// unary minus
code = "void f(int x) {\n"
" a = -x;\n"
" if (x==10) {}\n"
"}";
values = tokenValues(code,"-");
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(-10, values.back().intvalue);
// Logical and
code = "void f(bool b) {\n"
" bool x = false && b;\n"
" bool a = x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 0));
code = "void f(bool b) {\n"
" bool x = b && false;\n"
" bool a = x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 0));
code = "void f(bool b) {\n"
" bool x = true && b;\n"
" bool a = x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 3U, 1));
code = "void f(bool b) {\n"
" bool x = b && true;\n"
" bool a = x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 3U, 1));
// Logical or
code = "void f(bool b) {\n"
" bool x = true || b;\n"
" bool a = x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 1));
code = "void f(bool b) {\n"
" bool x = b || true;\n"
" bool a = x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 1));
code = "void f(bool b) {\n"
" bool x = false || b;\n"
" bool a = x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 3U, 0));
code = "void f(bool b) {\n"
" bool x = b || false;\n"
" bool a = x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 3U, 0));
code = "void f(int i) {\n"
" int * p = &i;\n"
" bool x = !p || i;\n"
" bool a = x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 4U, 1));
code = "bool f(const uint16_t * const p) {\n"
" const uint8_t x = (uint8_t)(*p & 0x01E0U) >> 5U;\n"
" return x != 0;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, -1));
code = "bool f() {\n"
" bool a = (4 == 3);\n"
" bool b = (3 == 3);\n"
" return a || b;\n"
"}\n";
values = tokenValues(code, "%oror%");
ASSERT_EQUALS(1, values.size());
if (!values.empty()) {
ASSERT_EQUALS(true, values.front().isIntValue());
ASSERT_EQUALS(true, values.front().isKnown());
ASSERT_EQUALS(1, values.front().intvalue);
}
// function call => calculation
code = "void f(int x, int y) {\n"
" a = x + y;\n"
"}\n"
"void callf() {\n"
" f(1,1);\n"
" f(10,10);\n"
"}";
values = tokenValues(code, "+");
ASSERT_EQUALS(true, values.empty());
if (!values.empty()) {
/* todo.. */
ASSERT_EQUALS(2U, values.size());
ASSERT_EQUALS(2, values.front().intvalue);
ASSERT_EQUALS(22, values.back().intvalue);
}
// #10251 starship operator
code = "struct X {};\n"
"auto operator<=>(const X & a, const X & b) -> decltype(1 <=> 2) {\n"
" return std::strong_ordering::less;\n"
"}\n";
ASSERT_NO_THROW(tokenValues(code, "<=>"));
// Comparison of string
values = removeImpossible(tokenValues("f(\"xyz\" == \"xyz\");", "==")); // implementation defined
ASSERT_EQUALS(0U, values.size()); // <- no value
values = removeImpossible(tokenValues("f(\"xyz\" == 0);", "=="));
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(0, values.front().intvalue);
values = removeImpossible(tokenValues("f(0 == \"xyz\");", "=="));
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(0, values.front().intvalue);
values = removeImpossible(tokenValues("f(\"xyz\" != 0);", "!="));
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(1, values.front().intvalue);
values = removeImpossible(tokenValues("f(0 != \"xyz\");", "!="));
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(1, values.front().intvalue);
}
void valueFlowSizeof() {
const char *code;
std::list<ValueFlow::Value> values;
// array size
code = "void f() {\n"
" char a[10];"
" x = sizeof(*a);\n"
"}";
values = tokenValues(code,"( *");
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(1, values.back().intvalue);
code = "void f() {\n"
" char a[10];"
" x = sizeof(a[0]);\n"
"}";
values = tokenValues(code,"( a");
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(1, values.back().intvalue);
code = "enum testEnum : uint32_t { a };\n"
"sizeof(testEnum);";
values = tokenValues(code,"( testEnum");
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(4, values.back().intvalue);
#define CHECK3(A, B, C) \
do { \
code = "void f() {\n" \
" x = sizeof(" A ");\n" \
"}"; \
values = tokenValues(code,"( " C " )"); \
ASSERT_EQUALS(1U, values.size()); \
ASSERT_EQUALS(B, values.back().intvalue); \
} while (false)
#define CHECK(A, B) CHECK3(A, B, A)
// standard types
CHECK("void *", settings.platform.sizeof_pointer);
CHECK("char", 1U);
CHECK("short", settings.platform.sizeof_short);
CHECK("int", settings.platform.sizeof_int);
CHECK("long", settings.platform.sizeof_long);
CHECK3("long long", settings.platform.sizeof_long_long, "long");
CHECK("wchar_t", settings.platform.sizeof_wchar_t);
CHECK("float", settings.platform.sizeof_float);
CHECK("double", settings.platform.sizeof_double);
CHECK3("long double", settings.platform.sizeof_long_double, "double");
// string/char literals
CHECK("\"asdf\"", 5);
CHECK("L\"asdf\"", 5LL * settings.platform.sizeof_wchar_t);
CHECK("u8\"asdf\"", 5); // char8_t
CHECK("u\"asdf\"", 5LL * 2); // char16_t
CHECK("U\"asdf\"", 5LL * 4); // char32_t
CHECK("'a'", 1U);
CHECK("'ab'", settings.platform.sizeof_int);
CHECK("L'a'", settings.platform.sizeof_wchar_t);
CHECK("u8'a'", 1U); // char8_t
CHECK("u'a'", 2U); // char16_t
CHECK("U'a'", 4U); // char32_t
#undef CHECK
#undef CHECK3
// array size
code = "void f() {\n"
" struct S *a[10];"
" x = sizeof(a) / sizeof(a[0]);\n"
"}";
values = tokenValues(code,"/");
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(10, values.back().intvalue);
code = "void f() {\n" // #11294
" struct S { int i; };\n"
" const S a[] = { 1, 2 };\n"
" x = sizeof(a) / ( sizeof(a[0]) );\n"
"}";
values = tokenValues(code, "/");
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(2, values.back().intvalue);
#define CHECK(A, B, C, D) \
do { \
code = "enum " A " E " B " { E0, E1 };\n" \
"void f() {\n" \
" x = sizeof(" C ");\n" \
"}"; \
values = tokenValues(code,"( " C " )"); \
ASSERT_EQUALS(1U, values.size()); \
ASSERT_EQUALS(D, values.back().intvalue); \
} while (false)
// enums
CHECK("", "", "E", settings.platform.sizeof_int);
// typed enums
CHECK("", ": char", "E", 1U);
CHECK("", ": signed char", "E", 1U);
CHECK("", ": unsigned char", "E", 1U);
CHECK("", ": short", "E", settings.platform.sizeof_short);
CHECK("", ": signed short", "E", settings.platform.sizeof_short);
CHECK("", ": unsigned short", "E", settings.platform.sizeof_short);
CHECK("", ": int", "E", settings.platform.sizeof_int);
CHECK("", ": signed int", "E", settings.platform.sizeof_int);
CHECK("", ": unsigned int", "E", settings.platform.sizeof_int);
CHECK("", ": long", "E", settings.platform.sizeof_long);
CHECK("", ": signed long", "E", settings.platform.sizeof_long);
CHECK("", ": unsigned long", "E", settings.platform.sizeof_long);
CHECK("", ": long long", "E", settings.platform.sizeof_long_long);
CHECK("", ": signed long long", "E", settings.platform.sizeof_long_long);
CHECK("", ": unsigned long long", "E", settings.platform.sizeof_long_long);
CHECK("", ": wchar_t", "E", settings.platform.sizeof_wchar_t);
CHECK("", ": size_t", "E", settings.platform.sizeof_size_t);
// enumerators
CHECK("", "", "E0", settings.platform.sizeof_int);
// typed enumerators
CHECK("", ": char", "E0", 1U);
CHECK("", ": signed char", "E0", 1U);
CHECK("", ": unsigned char", "E0", 1U);
CHECK("", ": short", "E0", settings.platform.sizeof_short);
CHECK("", ": signed short", "E0", settings.platform.sizeof_short);
CHECK("", ": unsigned short", "E0", settings.platform.sizeof_short);
CHECK("", ": int", "E0", settings.platform.sizeof_int);
CHECK("", ": signed int", "E0", settings.platform.sizeof_int);
CHECK("", ": unsigned int", "E0", settings.platform.sizeof_int);
CHECK("", ": long", "E0", settings.platform.sizeof_long);
CHECK("", ": signed long", "E0", settings.platform.sizeof_long);
CHECK("", ": unsigned long", "E0", settings.platform.sizeof_long);
CHECK("", ": long long", "E0", settings.platform.sizeof_long_long);
CHECK("", ": signed long long", "E0", settings.platform.sizeof_long_long);
CHECK("", ": unsigned long long", "E0", settings.platform.sizeof_long_long);
CHECK("", ": wchar_t", "E0", settings.platform.sizeof_wchar_t);
CHECK("", ": size_t", "E0", settings.platform.sizeof_size_t);
// class typed enumerators
CHECK("class", ": char", "E :: E0", 1U);
CHECK("class", ": signed char", "E :: E0", 1U);
CHECK("class", ": unsigned char", "E :: E0", 1U);
CHECK("class", ": short", "E :: E0", settings.platform.sizeof_short);
CHECK("class", ": signed short", "E :: E0", settings.platform.sizeof_short);
CHECK("class", ": unsigned short", "E :: E0", settings.platform.sizeof_short);
CHECK("class", ": int", "E :: E0", settings.platform.sizeof_int);
CHECK("class", ": signed int", "E :: E0", settings.platform.sizeof_int);
CHECK("class", ": unsigned int", "E :: E0", settings.platform.sizeof_int);
CHECK("class", ": long", "E :: E0", settings.platform.sizeof_long);
CHECK("class", ": signed long", "E :: E0", settings.platform.sizeof_long);
CHECK("class", ": unsigned long", "E :: E0", settings.platform.sizeof_long);
CHECK("class", ": long long", "E :: E0", settings.platform.sizeof_long_long);
CHECK("class", ": signed long long", "E :: E0", settings.platform.sizeof_long_long);
CHECK("class", ": unsigned long long", "E :: E0", settings.platform.sizeof_long_long);
CHECK("class", ": wchar_t", "E :: E0", settings.platform.sizeof_wchar_t);
CHECK("class", ": size_t", "E :: E0", settings.platform.sizeof_size_t);
#undef CHECK
#define CHECK(A, B) \
do { \
code = "enum E " A " { E0, E1 };\n" \
"void f() {\n" \
" E arrE[] = { E0, E1 };\n" \
" x = sizeof(arrE);\n" \
"}"; \
values = tokenValues(code,"( arrE )"); \
ASSERT_EQUALS(1U, values.size()); \
ASSERT_EQUALS(B * 2ULL, values.back().intvalue); \
} while (false)
// enum array
CHECK("", settings.platform.sizeof_int);
// typed enum array
CHECK(": char", 1U);
CHECK(": signed char", 1U);
CHECK(": unsigned char", 1U);
CHECK(": short", settings.platform.sizeof_short);
CHECK(": signed short", settings.platform.sizeof_short);
CHECK(": unsigned short", settings.platform.sizeof_short);
CHECK(": int", settings.platform.sizeof_int);
CHECK(": signed int", settings.platform.sizeof_int);
CHECK(": unsigned int", settings.platform.sizeof_int);
CHECK(": long", settings.platform.sizeof_long);
CHECK(": signed long", settings.platform.sizeof_long);
CHECK(": unsigned long", settings.platform.sizeof_long);
CHECK(": long long", settings.platform.sizeof_long_long);
CHECK(": signed long long", settings.platform.sizeof_long_long);
CHECK(": unsigned long long", settings.platform.sizeof_long_long);
CHECK(": wchar_t", settings.platform.sizeof_wchar_t);
CHECK(": size_t", settings.platform.sizeof_size_t);
#undef CHECK
#define CHECK(A, B) \
do { \
code = "enum class E " A " { E0, E1 };\n" \
"void f() {\n" \
" E arrE[] = { E::E0, E::E1 };\n" \
" x = sizeof(arrE);\n" \
"}"; \
values = tokenValues(code,"( arrE )"); \
ASSERT_EQUALS(1U, values.size()); \
ASSERT_EQUALS(B * 2ULL, values.back().intvalue); \
} while (false)
// enum array
CHECK("", settings.platform.sizeof_int);
// typed enum array
CHECK(": char", 1U);
CHECK(": signed char", 1U);
CHECK(": unsigned char", 1U);
CHECK(": short", settings.platform.sizeof_short);
CHECK(": signed short", settings.platform.sizeof_short);
CHECK(": unsigned short", settings.platform.sizeof_short);
CHECK(": int", settings.platform.sizeof_int);
CHECK(": signed int", settings.platform.sizeof_int);
CHECK(": unsigned int", settings.platform.sizeof_int);
CHECK(": long", settings.platform.sizeof_long);
CHECK(": signed long", settings.platform.sizeof_long);
CHECK(": unsigned long", settings.platform.sizeof_long);
CHECK(": long long", settings.platform.sizeof_long_long);
CHECK(": signed long long", settings.platform.sizeof_long_long);
CHECK(": unsigned long long", settings.platform.sizeof_long_long);
CHECK(": wchar_t", settings.platform.sizeof_wchar_t);
CHECK(": size_t", settings.platform.sizeof_size_t);
#undef CHECK
code = "uint16_t arr[10];\n"
"x = sizeof(arr);";
values = tokenValues(code,"( arr )");
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(10 * sizeof(std::uint16_t), values.back().intvalue);
code = "int sz = sizeof(int32_t[10][20]);";
values = tokenValues(code, "=");
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(sizeof(std::int32_t) * 10 * 20, values.back().intvalue);
code = "struct X { float a; float b; };\n"
"void f() {\n"
" x = sizeof(X);\n"
"}";
values = tokenValues(code, "( X )");
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(8, values.back().intvalue);
code = "struct X { char a; char b; };\n"
"void f() {\n"
" x = sizeof(X);\n"
"}";
values = tokenValues(code, "( X )");
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(2, values.back().intvalue);
code = "struct X { char a; float b; };\n"
"void f() {\n"
" x = sizeof(X);\n"
"}";
values = tokenValues(code, "( X )");
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(8, values.back().intvalue);
code = "struct X { char a; char b; float c; };\n"
"void f() {\n"
" x = sizeof(X);\n"
"}";
values = tokenValues(code, "( X )");
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(8, values.back().intvalue);
code = "struct X { float a; char b; };\n"
"void f() {\n"
" x = sizeof(X);\n"
"}";
values = tokenValues(code, "( X )");
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(8, values.back().intvalue);
code = "struct X { float a; char b; char c; };\n"
"void f() {\n"
" x = sizeof(X);\n"
"}";
values = tokenValues(code, "( X )");
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(8, values.back().intvalue);
code = "struct A { float a; char b; };\n"
"struct X { A a; char b; };\n"
"void f() {\n"
" x = sizeof(X);\n"
"}";
values = tokenValues(code, "( X )");
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(12, values.back().intvalue);
code = "struct T;\n"
"struct S { T& r; };\n"
"struct T { S s{ *this }; };\n"
"void f() {\n"
" sizeof(T) == sizeof(void*);\n"
"}\n";
values = tokenValues(code, "==");
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(1LL, values.back().intvalue);
code = "struct S { int32_t a[2][10] };\n" // #12479
"void f() {\n"
" x = sizeof(S);\n"
"}\n";
values = tokenValues(code, "=");
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(4LL * 2 * 10, values.back().intvalue);
code = "struct S {\n"
" int a[10];\n"
" int b[20];\n"
" int c[30];\n"
"};\n"
"void f() {\n"
" x = sizeof(S);\n"
"}\n";
values = tokenValues(code, "=");
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(4LL * (10 + 20 + 30), values.back().intvalue);
code = "struct S {\n"
" char c;\n"
" int a[4];\n"
"};\n"
"void f() {\n"
" x = sizeof(S);\n"
"}\n";
values = tokenValues(code, "=");
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(4LL * 5, values.back().intvalue);
}
void valueFlowComma()
{
const char* code;
std::list<ValueFlow::Value> values;
code = "void f(int i) {\n"
" int x = (i, 4);\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 3U, 4));
code = "void f(int i) {\n"
" int x = (4, i);\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 3U, 4));
code = "void f() {\n"
" int x = g(3, 4);\n"
" return x;\n"
"}\n";
values = tokenValues(code, ",");
ASSERT_EQUALS(0U, values.size());
}
void valueFlowErrorPath() {
const char *code;
code = "void f() {\n"
" int x = 53;\n"
" a = x;\n"
"}\n";
ASSERT_EQUALS("2,Assignment 'x=53', assigned value is 53\n",
getErrorPathForX(code, 3U));
code = "void f(int y) {\n"
" int x = y;\n"
" a = x;\n"
" y += 12;\n"
" if (y == 32) {}"
"}\n";
ASSERT_EQUALS("2,x is assigned 'y' here.\n"
"5,Assuming that condition 'y==32' is not redundant\n"
"4,Compound assignment '+=', assigned value is 20\n"
"2,x is assigned 'y' here.\n",
getErrorPathForX(code, 3U));
code = "void f1(int x) {\n"
" a = x;\n"
"}\n"
"void f2() {\n"
" int x = 3;\n"
" f1(x+1);\n"
"}\n";
ASSERT_EQUALS("5,Assignment 'x=3', assigned value is 3\n"
"6,Calling function 'f1', 1st argument 'x+1' value is 4\n",
getErrorPathForX(code, 2U));
code = "void f(int a) {\n"
" int x;\n"
" for (x = a; x < 50; x++) {}\n"
" b = x;\n"
"}\n";
ASSERT_EQUALS("3,Assuming that condition 'x<50' is not redundant\n"
"3,Assuming that condition 'x<50' is not redundant\n",
getErrorPathForX(code, 4U));
}
void valueFlowBeforeCondition() {
const char *code;
code = "void f(int x) {\n"
" int a = x;\n"
" if (x == 123) {}\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 2U, 123));
code = "void f(unsigned int x) {\n"
" int a = x;\n"
" if (x >= 1) {}\n"
"}";
TODO_ASSERT_EQUALS(true, false, testValueOfX(code, 2U, 1));
ASSERT_EQUALS(true, testValueOfX(code, 2U, 0));
code = "void f(unsigned int x) {\n"
" int a = x;\n"
" if (x > 0) {}\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 2U, 0));
code = "void f(unsigned int x) {\n"
" int a = x;\n"
" if (x > 1) {}\n" // not zero => don't consider > condition
"}";
ASSERT_EQUALS(false, testValueOfX(code, 2U, 1));
code = "void f(int x) {\n" // not unsigned => don't consider > condition
" int a = x;\n"
" if (x > 0) {}\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 2U, 0));
code = "void f(int *x) {\n"
" *x = 100;\n"
" if (x) {}\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 2U, 0));
code = "extern const int x;\n"
"void f() {\n"
" int a = x;\n"
" if (x == 123) {}\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 123));
// after loop
code = "void f(struct X *x) {\n"
" do {\n"
" if (!x)\n"
" break;\n"
" } while (x->a);\n"
" if (x) {}\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 5U, 0));
ASSERT_EQUALS(false, testValueOfXKnown(code, 3U, 1));
TODO_ASSERT_EQUALS(true, false, testValueOfX(code, 6U, 0));
}
void valueFlowBeforeConditionAssignIncDec() { // assignment / increment
const char *code;
code = "void f(int x) {\n"
" x = 2 + x;\n"
" if (x == 65);\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 2U, 65));
code = "void f(int x) {\n"
" x = y = 2 + x;\n"
" if (x == 65);\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 2U, 65));
code = "void f(int x) {\n"
" a[x++] = 0;\n"
" if (x == 5);\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 2U, 5));
code = "void f(int x) {\n"
" a = x;\n"
" x++;\n"
" if (x == 4);\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 2U, 3));
// compound assignment += , -= , ...
code = "void f(int x) {\n"
" a = x;\n"
" x += 2;\n"
" if (x == 4);\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 2U, 2));
ASSERT_EQUALS(true, testValueOfX(code, 3U, 2));
code = "void f(int x) {\n"
" a = x;\n"
" x -= 2;\n"
" if (x == 4);\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 2U, 6));
ASSERT_EQUALS(true, testValueOfX(code, 3U, 6));
code = "void f(int x) {\n"
" a = x;\n"
" x *= 2;\n"
" if (x == 42);\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 2U, 21));
ASSERT_EQUALS(true, testValueOfX(code, 3U, 21));
code = "void f(int x) {\n"
" a = x;\n"
" x /= 5;\n"
" if (x == 42);\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 2U, 210));
ASSERT_EQUALS(true, testValueOfX(code, 3U, 210));
// bailout: assignment
bailout("void f(int x) {\n"
" x = y;\n"
" if (x == 123) {}\n"
"}");
ASSERT_EQUALS(
"[test.cpp:2]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable y\n",
errout_str());
}
void valueFlowBeforeConditionAndAndOrOrGuard() { // guarding by &&
const char *code;
code = "void f(int x) {\n"
" if (!x || \n" // <- x can be 0
" a/x) {}\n" // <- x can't be 0
" if (x==0) {}\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 2U, 0));
ASSERT_EQUALS(false, testValueOfX(code, 3U, 0));
code = "void f(int *x) {\n"
" ((x=ret())&&\n"
" (*x==0));\n" // <- x is not 0
" if (x==0) {}\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 3U, 0));
code = "void f(int *x) {\n"
" int a = (x && *x == '1');\n"
" int b = a ? atoi(x) : 0;\n" // <- x is not 0
" if (x==0) {}\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 3U, 0));
}
void valueFlowBeforeConditionFunctionCall() { // function calls
const char *code;
code = "void f(int x) {\n"
" a = x;\n"
" setx(x);\n"
" if (x == 1) {}\n"
"}";
ASSERT_EQUALS(true, testValueOfX((std::string("void setx(int x);")+code).c_str(), 2U, 1));
ASSERT_EQUALS(false, testValueOfX((std::string("void setx(int &x);")+code).c_str(), 2U, 1));
ASSERT_EQUALS(true, testValueOfX(code, 2U, 1));
code = "void f(char* x) {\n"
" strcpy(x,\"abc\");\n"
" if (x) {}\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 2U, 0));
code = "void addNewFunction(Scope**scope, const Token**tok);\n"
"void f(Scope *x) {\n"
" x->functionList.back();\n"
" addNewFunction(&x,&tok);\n" // address-of, x can be changed by subfunction
" if (x) {}\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 3U, 0));
code = "void g(int&);"
"void f(int x) {\n"
" g(x);\n"
" if (x == 5);\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 2U, 5));
}
void valueFlowBeforeConditionLoop() { // while, for, do-while
const char *code;
code = "void f(int x) {\n" // loop condition, x is not assigned inside loop => use condition
" a = x;\n" // x can be 37
" while (x == 37) {}\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 2U, 37));
code = "void f(int x) {\n" // loop condition, x is assigned inside loop => don't use condition
" a = x;\n" // don't assume that x can be 37
" while (x != 37) { x++; }\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 2U, 37));
code = "void f(int x) {\n"
" a = x;\n"
" for (; x!=1; x++) { }\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 2U, 1));
code = "void f(menu *x) {\n"
" a = x->parent;\n"
" for (i=0;(i<10) && (x!=0); i++) { x = x->next; }\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 2U, 0));
code = "void f(int x) {\n" // condition inside loop, x is NOT assigned inside loop => use condition
" a = x;\n"
" do {\n"
" if (x==76) {}\n"
" } while (1);\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 2U, 76));
code = "void f(int x) {\n" // conditions inside loop, x is assigned inside do-while => don't use condition
" a = x;\n"
" do {\n"
" if (x!=76) { x=do_something(); }\n"
" } while (1);\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 2U, 76));
code = "void f(X x) {\n" // conditions inside loop, x is assigned inside do-while => don't use condition
" a = x;\n"
" for (i=1;i<=count;i++) {\n"
" BUGON(x==0)\n"
" x = x.next;\n"
" }\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 2U, 0));
code = "struct S {\n" // #12848
" S* next;\n"
" int a;\n"
"};\n"
"void f(S* x, int i) {\n"
" while (x) {\n"
" if (x->a == 0) {\n"
" x = x->next;\n"
" continue;\n"
" }\n"
" if (i == 0)\n"
" break;\n"
" x->a = i--;\n"
" }\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 13U, 0));
}
void valueFlowBeforeConditionTernaryOp() { // bailout: ?:
const char *code;
bailout("void f(int x) {\n"
" y = ((x<0) ? x : ((x==2)?3:4));\n"
"}");
ASSERT_EQUALS(
"[test.cpp:2]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable y\n",
errout_str());
bailout("int f(int x) {\n"
" int r = x ? 1 / x : 0;\n"
" if (x == 0) {}\n"
"}");
code = "void f(int x) {\n"
" int a =v x;\n"
" a = b ? x/2 : 20/x;\n"
" if (x == 123) {}\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 2U, 123));
code = "void f(const s *x) {\n"
" x->a = 0;\n"
" if (x ? x->a : 0) {}\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 2U, 0));
code = "void f(int x, int y) {\n"
" a = x;\n"
" if (y){}\n"
" if (x==123){}\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 2U, 123));
}
void valueFlowBeforeConditionSizeof() { // skip sizeof
const char *code;
code = "void f(int *x) {\n"
" sizeof(x[0]);\n"
" if (x==63){}\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 2U, 63));
code = "void f(int *x) {\n"
" char a[sizeof x.y];\n"
" if (x==0){}\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 2U, 0));
}
void valueFlowBeforeConditionIfElse() { // bailout: if/else/etc
const char *code;
code = "void f(X * x) {\n"
" a = x;\n"
" if ((x != NULL) &&\n"
" (a(x->name, html)) &&\n"
" (a(x->name, body))) {}\n"
" if (x != NULL) { }\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 2U, 0));
ASSERT_EQUALS(true, testValueOfX(code, 3U, 0));
ASSERT_EQUALS(false, testValueOfX(code, 4U, 0));
ASSERT_EQUALS(false, testValueOfX(code, 5U, 0));
bailout("void f(int x) {\n"
" if (x != 123) { b = x; }\n"
" if (x == 123) {}\n"
"}");
ASSERT_EQUALS(
"[test.cpp:2]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable b\n",
errout_str());
code = "void f(int x, bool abc) {\n"
" a = x;\n"
" if (abc) { x = 1; }\n" // <- condition must be false if x is 7 in next line
" if (x == 7) { }\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 2U, 7));
code = "void f(int x, bool abc) {\n"
" a = x;\n"
" if (abc) { x = 7; }\n" // <- condition is probably true
" if (x == 7) { }\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 2U, 7));
}
void valueFlowBeforeConditionGlobalVariables() {
const char *code;
// handle global variables
code = "int x;\n"
"void f() {\n"
" int a = x;\n"
" if (x == 123) {}\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code,3,123));
// bailout when there is function call
code = "class Fred { int x; void clear(); void f(); };\n"
"void Fred::f() {\n"
" int a = x;\n"
" clear();\n" // <- x might be assigned
" if (x == 234) {}\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code,3,234));
}
void valueFlowBeforeConditionSwitch() {
// bailout: switch
// TODO : handle switch/goto more intelligently
bailout("void f(int x, int y) {\n"
" switch (y) {\n"
" case 1: a=x; break;\n"
" case 2: if (x==5) {} break;\n"
" };\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable a\n",
errout_str());
bailout("void f(int x, int y) {\n"
" switch (y) {\n"
" case 1: a=x; return 1;\n"
" case 2: if (x==5) {} break;\n"
" };\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable a\n",
errout_str());
}
void valueFlowBeforeConditionMacro() {
// bailout: condition is a expanded macro
bailout("#define M if (x==123) {}\n"
"void f(int x) {\n"
" a = x;\n"
" M;\n"
"}");
ASSERT_EQUALS_WITHOUT_LINENUMBERS(
"[test.cpp:3]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable a\n"
"[test.cpp:4]: (debug) valueflow.cpp:1260:(valueFlow) bailout: variable 'x', condition is defined in macro\n"
"[test.cpp:4]: (debug) valueflow.cpp:1260:(valueFlow) bailout: variable 'x', condition is defined in macro\n", // duplicate
errout_str());
bailout("#define FREE(obj) ((obj) ? (free((char *) (obj)), (obj) = 0) : 0)\n" // #8349
"void f(int *x) {\n"
" a = x;\n"
" FREE(x);\n"
"}");
ASSERT_EQUALS_WITHOUT_LINENUMBERS(
"[test.cpp:3]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable a\n"
"[test.cpp:4]: (debug) valueflow.cpp:1260:(valueFlow) bailout: variable 'x', condition is defined in macro\n"
"[test.cpp:4]: (debug) valueflow.cpp:1260:(valueFlow) bailout: variable 'x', condition is defined in macro\n", // duplicate
errout_str());
}
void valueFlowBeforeConditionGoto() {
// bailout: goto label (TODO: handle gotos more intelligently)
bailout("void f(int x) {\n"
" if (x == 123) { goto out; }\n"
" a=x;\n" // <- x is not 123
"out:"
" if (x==123){}\n"
"}");
ASSERT_EQUALS_WITHOUT_LINENUMBERS(
"[test.cpp:3]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable a\n"
"[test.cpp:2]: (debug) valueflow.cpp::(valueFlow) bailout: valueFlowAfterCondition: bailing in conditional block\n"
"[test.cpp:2]: (debug) valueflow.cpp::(valueFlow) bailout: valueFlowAfterCondition: bailing in conditional block\n", // duplicate
errout_str());
// #5721 - FP
bailout("static void f(int rc) {\n"
" ABC* abc = getabc();\n"
" if (!abc) { goto out };\n"
"\n"
" abc->majortype = 0;\n"
" if (FAILED(rc)) {}\n"
"\n"
"out:\n"
" if (abc) {}\n"
"}");
ASSERT_EQUALS_WITHOUT_LINENUMBERS(
"[test.cpp:3]: (debug) valueflow.cpp:6730:(valueFlow) bailout: valueFlowAfterCondition: bailing in conditional block\n"
"[test.cpp:3]: (debug) valueflow.cpp:6730:(valueFlow) bailout: valueFlowAfterCondition: bailing in conditional block\n", // duplicate
errout_str());
}
void valueFlowBeforeConditionForward() {
const char* code;
code = "void f(int a) {\n"
" int x = a;\n"
" if (a == 123) {}\n"
" int b = x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 123));
code = "void f(int a) {\n"
" int x = a;\n"
" if (a != 123) {}\n"
" int b = x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 123));
}
void valueFlowBeforeConditionConstructor()
{
const char* code;
code = "struct Fred {\n"
" Fred(int *x)\n"
" : i(*x) {\n" // <- dereference x
" if (!x) {}\n" // <- check x
" }\n"
" int i;\n"
"};\n";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 0));
code = "struct Fred {\n"
" Fred(int *x)\n"
" : i(*x), j(0) {\n" // <- dereference x
" if (!x) {}\n" // <- check x
" }\n"
" int i;\n"
" int j;\n"
"};\n";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 0));
}
void valueFlowAfterAssign() {
const char *code;
code = "void f() {\n"
" int x = 123;\n"
" a = x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 123));
code = "void f() {\n"
" bool x = 32;\n"
" a = x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 1));
code = "void f() {\n"
" int x = 123;\n"
" a = sizeof(x);\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 3U, 123));
code = "void f() {\n"
" int x = 123;\n"
" a = 2 + x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 123));
code = "void f() {\n"
" const int x(321);\n"
" a = x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 321));
code = "void f() {\n"
" int x = 9;\n"
" --x;\n"
" return x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 4U, 9));
ASSERT_EQUALS(true, testValueOfX(code, 4U, 8));
ASSERT_EQUALS("2,Assignment 'x=9', assigned value is 9\n"
"3,x is decremented', new value is 8\n",
getErrorPathForX(code, 4U));
code = "void x() {\n"
" int x = value ? 6 : 0;\n"
" x =\n"
" 1 + x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 4U, 7));
code = "void f() {\n"
" int x = 0;\n"
" y = x += z;\n"
" return x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 4U, 0));
code = "void f() {\n"
" static int x = 2;\n"
" x++;\n"
" return x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 4U, 2));
code = "void f() {\n"
" static int x = 2;\n"
" a >> x;\n"
" return x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 4U, 2));
code = "void f() {\n"
" static int x = 0;\n"
" if (x==0) x = getX();\n"
" return x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 4U, 0));
// truncation
code = "int f() {\n"
" int x = 1.5;\n"
" return x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 1));
code = "int f() {\n"
" unsigned char x = 0x123;\n"
" return x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 0x23));
code = "int f() {\n"
" signed char x = 0xfe;\n"
" return x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, -2));
// function
code = "void f() {\n"
" char *x = 0;\n"
" int success = getx((char**)&x);\n"
" if (success) x[0] = 0;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 4U, 0));
code = "void f() {\n"
" char *x = 0;\n"
" getx(reinterpret_cast<void **>(&x));\n"
" *x = 0;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 4U, 0));
// lambda
code = "void f() {\n"
" int x = 0;\n"
" Q q = [&]() {\n"
" if (x > 0) {}\n"
" x++;\n"
" };\n"
" dosomething(q);\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 4U, 0));
code = "void f() {\n"
" int x = 0;\n"
" dostuff([&]() {\n"
" if (x > 0) {}\n"
" x++;\n"
" });\n"
" dosomething(q);\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 4U, 0));
code = "int f() {\n"
" int x = 1;\n"
" dostuff([&]() {\n"
" x = y;\n"
" });\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 6U, 1));
// ?:
code = "void f() {\n"
" int x = 8;\n"
" a = ((x > 10) ?\n"
" x : 0);\n" // <- x is not 8
"}";
ASSERT_EQUALS(false, testValueOfX(code, 4U, 8));
code = "void f() {\n" // #6973
" char *x = \"\";\n"
" a = ((x[0] == 'U') ?\n"
" x[1] : 0);\n" // <- x is not ""
"}";
ASSERT_EQUALS(false, testValueOfX(code, 4U, "\"\"", ValueFlow::Value::ValueType::TOK));
code = "void f() {\n" // #6973
" char *x = getenv (\"LC_ALL\");\n"
" if (x == NULL)\n"
" x = \"\";\n"
"\n"
" if ( (x[0] == 'U') &&\n" // x can be ""
" (x[1] ?\n" // x can't be ""
" x[3] :\n" // x can't be ""
" x[2] ))\n" // x can't be ""
" {}\n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 6U, "\"\"", ValueFlow::Value::ValueType::TOK));
ASSERT_EQUALS(false, testValueOfX(code, 7U, "\"\"", ValueFlow::Value::ValueType::TOK));
ASSERT_EQUALS(false, testValueOfX(code, 8U, "\"\"", ValueFlow::Value::ValueType::TOK));
ASSERT_EQUALS(false, testValueOfX(code, 9U, "\"\"", ValueFlow::Value::ValueType::TOK));
code = "void f() {\n" // #7599
" t *x = 0;\n"
" y = (a ? 1 : x\n" // <- x is 0
" && x->y ? 1 : 2);" // <- x is not 0
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 0));
ASSERT_EQUALS(false, testValueOfX(code, 4U, 0));
code = "void f() {\n" // #7599
" t *x = 0;\n"
" y = (a ? 1 : !x\n" // <- x is 0
" || x->y ? 1 : 2);" // <- x is not 0
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 0));
ASSERT_EQUALS(false, testValueOfX(code, 4U, 0));
// if/else
code = "void f() {\n"
" int x = 123;\n"
" if (condition) return;\n"
" a = 2 + x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 123));
code = "void f() {\n"
" int x = 1;\n"
" if (condition) x = 2;\n"
" a = 2 + x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 1));
ASSERT_EQUALS(true, testValueOfX(code, 4U, 2));
code = "void f() {\n"
" int x = 123;\n"
" if (condition1) x = 456;\n"
" if (condition2) x = 789;\n"
" a = 2 + x;\n" // <- either assignment "x=123" is redundant or x can be 123 here.
"}";
TODO_ASSERT_EQUALS(true, false, testValueOfX(code, 5U, 123));
code = "void f(int a) {\n"
" int x = 123;\n"
" if (a > 1)\n"
" ++x;\n"
" else\n"
" ++x;\n"
" return 2 + x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 123));
code = "void f() {\n"
" int x = 1;\n"
" if (condition1) x = 2;\n"
" else return;\n"
" a = 2 + x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 5U, 1));
code = "void f(){\n"
" int x = 0;\n"
" if (a>=0) { x = getx(); }\n"
" if (x==0) { return; }\n"
" return 123 / x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 5U, 0));
code = "void f() {\n"
" X *x = getx();\n"
" if(0) { x = 0; }\n"
" else { x->y = 1; }\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 4U, 0));
code = "void f() {\n" // #6239
" int x = 4;\n"
" if(1) { x = 0; }\n"
" a = x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 4U, 4));
code = "void f() {\n"
" int x = 32;\n"
" if (x>=32) return;\n"
" a[x]=0;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 4U, 32));
code = "void f() {\n"
" int x = 32;\n"
" if (x>=32) {\n"
" a[x] = 0;\n" // <- should have possible value 32
" return;\n"
" }\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 32));
code = "void f() {\n"
" int x = 33;\n"
" if (x==33) goto fail;\n"
" a[x]=0;\n"
"fail:\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 4U, 33));
code = "void f() {\n"
" int x = 32;\n"
" if (a==1) { z=x+12; }\n"
" if (a==2) { z=x+32; }\n"
" z = x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 32));
ASSERT_EQUALS(true, testValueOfX(code, 4U, 32));
ASSERT_EQUALS(true, testValueOfX(code, 5U, 32));
code = "void f() {\n" // #5656 - FP
" int x = 0;\n"
" if (!x) {\n"
" x = getx();\n"
" }\n"
" y = x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 6U, 0));
code = "void f(int y) {\n" // alias
" int x = y;\n"
" if (y == 54) {}\n"
" else { a = x; }\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 4U, 54));
code = "void f () {\n"
" ST * x = g_pST;\n"
" if (x->y == 0) {\n"
" x = NULL;\n"
" return 1;\n"
" }\n"
" a = x->y;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 7U, 0));
code = "void f () {\n"
" ST * x = g_pST;\n"
" if (x->y == 0) {\n"
" x = NULL;\n"
" goto label;\n"
" }\n"
" a = x->y;\n"
"label:\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 7U, 0));
code = "void f() {\n" // #5752 - FP
" int *x = 0;\n"
" if (x && *x == 123) {\n"
" getx(*x);\n"
" }\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 4U, 0));
code = "void f() {\n"
" int x = 0;\n"
" if (!x) {}\n"
" else { y = x; }\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 4U, 0));
code = "void f() {\n" // #6118 - FP
" int x = 0;\n"
" x = x & 0x1;\n"
" if (x == 0) { x = 2; }\n"
" y = 42 / x;\n" // <- x is 2
"}";
ASSERT_EQUALS(false, testValueOfX(code, 5U, 0));
ASSERT_EQUALS(true, testValueOfX(code, 5U, 2));
code = "void f() {\n" // #6118 - FN
" int x = 0;\n"
" x = x & 0x1;\n"
" if (x == 0) { x += 2; }\n"
" y = 42 / x;\n" // <- x is 2
"}";
ASSERT_EQUALS(false, testValueOfX(code, 5U, 0));
ASSERT_EQUALS(true, testValueOfX(code, 5U, 2));
code = "void f(int mode) {\n"
" struct ABC *x;\n"
"\n"
" if (mode) { x = &y; }\n"
" else { x = NULL; }\n"
"\n"
" if (!x) exit(1);\n"
"\n"
" a = x->a;\n" // <- x can't be 0
"}";
ASSERT_EQUALS(false, testValueOfX(code, 9U, 0));
code = "void f(int i) {\n"
" bool x = false;\n"
" if (i == 0) { x = true; }\n"
" else if (x && i == 1) {}\n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 0));
code = "void f(int i) {\n"
" bool x = false;\n"
" while(i > 0) {\n"
" i++;\n"
" if (i == 0) { x = true; }\n"
" else if (x && i == 1) {}\n"
" }\n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 6U, 0));
// multivariables
code = "void f(int a) {\n"
" int x = a;\n"
" if (a!=132) { b = x; }\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 3U, 132));
code = "void f(int a) {\n"
" int x = a;\n"
" b = x;\n" // <- line 3
" if (a!=132) {}\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 132));
code = "void f() {\n"
" int a;\n"
" if (n) { a = n; }\n"
" else { a = 0; }\n"
" int x = a;\n"
" if (a > 0) { a = b / x; }\n" // <- line 6
"}";
ASSERT_EQUALS(false, testValueOfX(code, 6U, 0)); // x is not 0 at line 6
code = "void f(int x1) {\n" // #6086
" int x = x1;\n"
" if (x1 >= 3) {\n"
" return;\n"
" }\n"
" a = x;\n" // <- x is not 3
"}";
ASSERT_EQUALS(false, testValueOfX(code, 6U, 3));
code = "int f(int *x) {\n" // #5980
" if (!x) {\n"
" switch (i) {\n"
" default:\n"
" throw std::runtime_error(msg);\n"
" };\n"
" }\n"
" return *x;\n" // <- x is not 0
"}";
ASSERT_EQUALS(false, testValueOfX(code, 8U, 0));
code = "void f(int a) {\n" // #6826
" int x = a ? a : 87;\n"
" if (a && x) {}\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 3U, 87));
code = "void f() {\n"
" int first=-1, x=0;\n"
" do {\n"
" if (first >= 0) { a = x; }\n" // <- x is not 0
" first++; x=3;\n"
" } while (1);\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 4U, 0));
ASSERT_EQUALS(true, testValueOfX(code, 4U, 3));
// pointer/reference to x
code = "int f(void) {\n"
" int x = 2;\n"
" int *px = &x;\n"
" for (int i = 0; i < 1; i++) {\n"
" *px = 1;\n"
" }\n"
" return x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 7U, 2));
code = "int f(void) {\n"
" int x = 5;\n"
" int &rx = x;\n"
" for (int i = 0; i < 1; i++) {\n"
" rx = 1;\n"
" }\n"
" return x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 7U, 5));
// break
code = "void f() {\n"
" for (;;) {\n"
" int x = 1;\n"
" if (!abc()) {\n"
" x = 2;\n"
" break;\n"
" }\n"
" a = x;\n" // <- line 8
" }\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 8U, 2)); // x is not 2 at line 8
code = "void f() {\n"
" int x;\n"
" switch (ab) {\n"
" case A: x = 12; break;\n"
" case B: x = 34; break;\n"
" }\n"
" v = x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 7U, 12));
ASSERT_EQUALS(true, testValueOfX(code, 7U, 34));
code = "void f() {\n" // #5981
" int x;\n"
" switch (ab) {\n"
" case A: x = 12; break;\n"
" case B: x = 34; break;\n"
" }\n"
" switch (ab) {\n"
" case A: v = x; break;\n" // <- x is not 34
" }\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 8U, 34));
// while/for
code = "void f() {\n" // #6138
" ENTRY *x = 0;\n"
" while (x = get()) {\n"
" set(x->value);\n" // <- x is not 0
" }\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 4U, 0));
code = "void f(const int *buf) {\n"
" int x = 0;\n"
" for (int i = 0; i < 10; i++) {\n"
" if (buf[i] == 123) {\n"
" x = i;\n"
" break;\n"
" }\n"
" }\n"
" a = x;\n" // <- x can be 0
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 9U, 0)); // x can be 0 at line 9
code = "void f(const int *buf) {\n"
" int x = 111;\n"
" bool found = false;\n"
" for (int i = 0; i < 10; i++) {\n"
" if (buf[i] == 123) {\n"
" x = i;\n"
" found = true;\n"
" break;\n"
" }\n"
" }\n"
" if (found)\n"
" a = x;\n" // <- x can't be 111
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 12U, 111)); // x can not be 111 at line 9
code = "void f(const int *buf) {\n"
" int x = 0;\n"
" for (int i = 0; i < 10; i++) {\n"
" if (buf[i] == 123) {\n"
" x = i;\n"
" ;\n" // <- no break
" }\n"
" }\n"
" a = x;\n" // <- x can't be 0
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 9U, 0)); // x can be 0 at line 9
ASSERT_EQUALS(false, testValueOfXKnown(code, 9U, 0)); // x can't be known at line 9
code = "void f(const int *buf) {\n"
" int x = 0;\n"
" for (int i = 0; i < 10; i++) {\n"
" if (buf[i] == 123) {\n"
" x = i;\n"
" ;\n" // <- no break
" } else {\n"
" x = 1;\n"
" }\n"
" }\n"
" a = x;\n" // <- x can't be 0
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 11U, 0)); // x can't be 0 at line 11
code = "void f(const int *buf) {\n"
" int i = 0;\n"
" int x = 0;\n"
" while (++i < 10) {\n"
" if (buf[i] == 123) {\n"
" x = i;\n"
" break;\n"
" }\n"
" }\n"
" a = x;\n" // <- x can be 0
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 10U, 0)); // x can be 0 at line 9
code = "bool maybe();\n"
"void f() {\n"
" int x = 0;\n"
" bool found = false;\n"
" while(!found) {\n"
" if (maybe()) {\n"
" x = i;\n"
" found = true;\n"
" }\n"
" }\n"
" a = x;\n" // <- x can't be 0
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 11U, 0));
code = "bool maybe();\n"
"void f() {\n"
" int x = 0;\n"
" bool found = false;\n"
" while(!found) {\n"
" if (maybe()) {\n"
" x = i;\n"
" found = true;\n"
" } else {\n"
" found = false;\n"
" }\n"
" }\n"
" a = x;\n" // <- x can't be 0
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 13U, 0));
code = "bool maybe();\n"
"void f() {\n"
" int x = 0;\n"
" bool found = false;\n"
" while(!found) {\n"
" if (maybe()) {\n"
" x = i;\n"
" break;\n"
" }\n"
" }\n"
" a = x;\n" // <- x can't be 0
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 11U, 0));
code = "bool maybe();\n"
"void f() {\n"
" int x = 0;\n"
" bool found = false;\n"
" while(!found) {\n"
" if (maybe()) {\n"
" x = i;\n"
" found = true;\n"
" break;\n"
" }\n"
" }\n"
" a = x;\n" // <- x can't be 0
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 12U, 0));
code = "void f(const int a[]) {\n" // #6616
" const int *x = 0;\n"
" for (int i = 0; i < 10; i = *x) {\n" // <- x is not 0
" x = a[i];\n"
" }\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 3U, 0));
// alias
code = "void f() {\n" // #7778
" int x = 0;\n"
" int *p = &x;\n"
" x = 3;\n"
" *p = 2;\n"
" a = x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 6U, 3));
TODO_ASSERT_EQUALS(true, false, testValueOfX(code, 6U, 2));
code = "struct Fred {\n"
" static void Create(std::unique_ptr<Wilma> wilma);\n"
" Fred(std::unique_ptr<Wilma> wilma);\n"
" std::unique_ptr<Wilma> mWilma;\n"
"};\n"
"void Fred::Create(std::unique_ptr<Wilma> wilma) {\n"
" auto fred = std::make_shared<Fred>(std::move(wilma));\n"
" fred->mWilma.reset();\n"
"}\n"
"Fred::Fred(std::unique_ptr<Wilma> wilma)\n"
" : mWilma(std::move(wilma)) {}\n";
ASSERT_EQUALS(0, tokenValues(code, "mWilma (").size());
code = "void g(unknown*);\n"
"int f() {\n"
" int a = 1;\n"
" unknown c[] = {{&a}};\n"
" g(c);\n"
" int x = a;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXKnown(code, 7U, 1));
ASSERT_EQUALS(true, testValueOfXInconclusive(code, 7U, 1));
code = "void g(unknown&);\n"
"int f() {\n"
" int a = 1;\n"
" unknown c{&a};\n"
" g(c);\n"
" int x = a;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXKnown(code, 7U, 1));
ASSERT_EQUALS(true, testValueOfXInconclusive(code, 7U, 1));
code = "long foo();\n"
"long bar();\n"
"int test() {\n"
" bool b = true;\n"
" long a = foo();\n"
" if (a != 0)\n"
" return 1;\n"
" a = bar();\n"
" if (a != 0)\n"
" b = false;\n"
" int x = b;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 12U, 0));
ASSERT_EQUALS(false, testValueOfXKnown(code, 12U, 0));
code = "bool f(unsigned char uc) {\n"
" const bool x = uc;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, -1));
ASSERT_EQUALS(false, testValueOfXKnown(code, 3U, 1));
ASSERT_EQUALS(false, testValueOfXKnown(code, 3U, 0));
ASSERT_EQUALS(false, testValueOfXImpossible(code, 3U, 0));
ASSERT_EQUALS(false, testValueOfXImpossible(code, 3U, 1));
code = "struct A {\n"
" int i, j;\n"
" int foo() {\n"
" i = 1;\n"
" j = 2;\n"
" int x = i;\n"
" return x;\n"
" }\n"
"};\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 7U, 1));
// global variable
code = "int x;\n"
"int foo(int y) {\n"
" if (y)\n"
" x = 10;\n"
" return x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 5U, 10));
code = "namespace A { int x; }\n"
"int foo(int y) {\n"
" if (y)\n"
" A::x = 10;\n"
" return A::x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 5U, 10));
// member variable
code = "struct Fred {\n"
" int x;\n"
" int foo(int y) {\n"
" if (y)\n"
" x = 10;\n"
" return x;\n"
" }\n"
"};";
ASSERT_EQUALS(true, testValueOfX(code, 6U, 10));
code = "void f(int i) {\n"
" if (i == 3) {}\n"
" for(int x = i;\n"
" x;\n"
" x++) {}\n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 3));
ASSERT_EQUALS(false, testValueOfXKnown(code, 4U, 3));
code = "void f() {\n"
" for(int x = 3;\n"
" x;\n"
" x++) {}\n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 3));
ASSERT_EQUALS(false, testValueOfXKnown(code, 4U, 3));
code = "void f() {\n"
" constexpr int x(123);\n"
" constexpr int y(x*x);\n"
" return x;\n"
"}";
ASSERT_EQUALS(true, testValueOfXKnown(code, 4U, 123));
code = "void f() {\n"
" static const int x(123);\n"
" static const int y(x*x);\n"
" return x;\n"
"}";
ASSERT_EQUALS(true, testValueOfXKnown(code, 4U, 123));
code = "void f() {\n"
" static int x(123);\n"
" static int y(x*x);\n"
" return x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 123));
code = "bool f() {\n" // #13208
" struct S {\n"
" bool b = true;\n"
" bool get() const { return b; }\n"
" };\n"
" S s;\n"
" s.b = false;\n"
" bool x = s.get();\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXKnown(code, 9U, 1));
}
void valueFlowAfterSwap()
{
const char* code;
code = "int f() {\n"
" int a = 1;\n"
" int b = 2;\n"
" std::swap(a, b);\n"
" int x = a;\n"
" return x;\n"
"}";
ASSERT_EQUALS(true, testValueOfXKnown(code, 6U, 2));
ASSERT_EQUALS(false, testValueOfXKnown(code, 6U, 1));
code = "int f() {\n"
" int a = 1;\n"
" int b = 2;\n"
" std::swap(a, b);\n"
" int x = b;\n"
" return x;\n"
"}";
ASSERT_EQUALS(true, testValueOfXKnown(code, 6U, 1));
ASSERT_EQUALS(false, testValueOfXKnown(code, 6U, 2));
code = "int f() {\n"
" std::string a;\n"
" std::string b=\"42\";\n"
" std::swap(b, a);\n"
" int x = b.size();\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 6U, 0));
ASSERT_EQUALS(false, testValueOfXKnown(code, 6U, 2));
code = "int f() {\n"
" std::string a;\n"
" std::string b=\"42\";\n"
" std::swap(b, a);\n"
" int x = a.size();\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 6U, 2));
ASSERT_EQUALS(false, testValueOfXKnown(code, 6U, 0));
}
void valueFlowAfterCondition() {
const char *code;
// in if
code = "void f(int x) {\n"
" if (x == 123) {\n"
" a = x;\n"
" }\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 123));
code = "void f(int x) {\n"
" if (x != 123) {\n"
" a = x;\n"
" }\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 3U, 123));
code = "void f(int x) {\n"
" if (x > 123) {\n"
" a = x;\n"
" }\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 124));
ASSERT_EQUALS(false, testValueOfX(code, 3U, 123));
code = "void f(int x) {\n"
" if (x < 123) {\n"
" a = x;\n"
" }\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 122));
ASSERT_EQUALS(false, testValueOfX(code, 3U, 123));
// ----
code = "void f(int x) {\n"
" if (123 < x) {\n"
" a = x;\n"
" }\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 124));
ASSERT_EQUALS(false, testValueOfX(code, 3U, 123));
code = "void f(int x) {\n"
" if (123 > x) {\n"
" a = x;\n"
" }\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 122));
ASSERT_EQUALS(false, testValueOfX(code, 3U, 123));
// in else
code = "void f(int x) {\n"
" if (x == 123) {}\n"
" else a = x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 3U, 123));
code = "void f(int x) {\n"
" if (x != 123) {}\n"
" else a = x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 123));
// after if
code = "void f(int x) {\n"
" if (x == 10) {\n"
" x++;\n"
" }\n"
" a = x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 5U, 10));
TODO_ASSERT_EQUALS(true, false, testValueOfX(code, 5U, 11));
// !
code = "void f(int x) {\n"
" if (!x) { a = x; }\n"
" else a = x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 2U, 0));
code = "void f(int x, int y) {\n"
" if (!(x&&y)) { return; }\n"
" a = x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 3U, 0));
code = "void f(int x) {\n"
" if (!x) { { throw new string(); }; }\n"
" a = x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 3U, 0));
code = "void f(int x) {\n"
" if (x != 123) { throw " "; }\n"
" a = x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 123));
code = "void f(int x) {\n"
" if (x != 123) { }\n"
" else { throw " "; }\n"
" a = x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 4U, 123));
code = "void f(int x) {\n"
" if (x == 123) { }\n"
" else { throw " "; }\n"
" a = x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 123));
code = "void f(int x) {\n"
" if (x < 123) { }\n"
" else { a = x; }\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 123));
code = "void f(int x) {\n"
" if (x < 123) { throw \"\"; }\n"
" a = x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 123));
code = "void f(int x) {\n"
" if (x < 123) { }\n"
" else { throw \"\"; }\n"
" a = x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 122));
ASSERT_EQUALS(false, testValueOfX(code, 4U, 123));
code = "void f(int x) {\n"
" if (x > 123) { }\n"
" else { a = x; }\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 123));
code = "void f(int x) {\n"
" if (x > 123) { throw \"\"; }\n"
" a = x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 123));
code = "void f(int x) {\n"
" if (x > 123) { }\n"
" else { throw \"\"; }\n"
" a = x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 124));
ASSERT_EQUALS(false, testValueOfX(code, 4U, 123));
code = "void f(int x) {\n"
" if (x < 123) { return; }\n"
" else { return; }\n"
" a = x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 4U, 124));
ASSERT_EQUALS(false, testValueOfX(code, 4U, 123));
// if (var)
code = "void f(int x) {\n"
" if (x) { a = x; }\n" // <- x is not 0
" else { b = x; }\n" // <- x is 0
" c = x;\n" // <- x might be 0
"}";
ASSERT_EQUALS(false, testValueOfX(code, 2U, 0));
ASSERT_EQUALS(true, testValueOfX(code, 3U, 0));
ASSERT_EQUALS(true, testValueOfX(code, 4U, 0));
// After while
code = "void f(int x) {\n"
" while (x != 3) {}\n"
" a = x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 3));
code = "void f(int x) {\n"
" while (11 != (x = dostuff())) {}\n"
" a = x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 11));
code = "void f(int x) {\n"
" while (11 != (x = dostuff()) && y) {}\n"
" a = x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 11));
code = "void f(int x) {\n"
" while (x = dostuff()) {}\n"
" a = x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 0));
code = "void f(const Token *x) {\n" // #5866
" x = x->next();\n"
" while (x) { x = x->next(); }\n"
" if (x->str()) {}\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 0));
code = "void f(const Token *x) {\n"
" while (0 != (x = x->next)) {}\n"
" x->ab = 0;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 0));
code = "void f(const Token* x) {\n"
" while (0 != (x = x->next)) {}\n"
" if (x->str) {\n" // <- possible value 0
" x = y;\n" // <- this caused some problem
" }\n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 0));
// conditional code after if/else/while
code = "void f(int x) {\n"
" if (x == 2) {}\n"
" if (x > 0)\n"
" a = x;\n" // <- TODO, x can be 2
" else\n"
" b = x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 2));
ASSERT_EQUALS(false, testValueOfX(code, 6U, 2));
// condition with 2nd variable
code = "void f(int x) {\n"
" int y = 0;\n"
" if (x == 7) { y = 1; }\n"
" if (!y)\n"
" a = x;\n" // <- x can not be 7 here
"}";
ASSERT_EQUALS(false, testValueOfX(code, 5U, 7));
code = "void f(struct X *x) {\n"
" bool b = TRUE;\n"
" if(x) { }\n"
" else\n"
" b = FALSE;\n"
" if (b)\n"
" abc(x->value);\n" // <- x is not 0
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 7U, 0));
// In condition, after && and ||
code = "void f(int x) {\n"
" a = (x != 3 ||\n"
" x);\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 3));
code = "void f(int x) {\n"
" a = (x == 4 &&\n"
" x);\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 4));
// protected usage with &&
code = "void f(const Token* x) {\n"
" if (x) {}\n"
" for (; x &&\n"
" x->str() != y; x = x->next()) {}\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 0));
ASSERT_EQUALS(false, testValueOfX(code, 4U, 0));
code = "void f(const Token* x) {\n"
" if (x) {}\n"
" if (x &&\n"
" x->str() != y) {}\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 0));
ASSERT_EQUALS(false, testValueOfX(code, 4U, 0));
// return
code = "void f(int x) {\n" // #6024
" if (x == 5) {\n"
" if (z) return; else return;\n"
" }\n"
" a = x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 5U, 5));
code = "void f(int x) {\n" // #6730
" if (x == 5) {\n"
" if (z) continue; else throw e;\n"
" }\n"
" a = x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 5U, 5));
// TODO: float
code = "void f(float x) {\n"
" if (x == 0.5) {}\n"
" a = x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 3U, 0));
// aliased variable
code = "void f() {\n"
" int x = 1;\n"
" int *data = &x;\n"
" if (!x) {\n"
" calc(data);\n"
" a = x;\n" // <- x might be changed by calc
" }\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 6U, 0));
code = "int* g();\n"
"int f() {\n"
" int * x;\n"
" x = g();\n"
" if (x) { printf(\"\"); }\n"
" return *x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXKnown(code, 6U, 0));
ASSERT_EQUALS(true, testValueOfX(code, 6U, 0));
// volatile variable
code = "void foo(const volatile int &x) {\n"
" if (x==1) {\n"
" return x;\n"
" }"
"}";
ASSERT_EQUALS(false, testValueOfXKnown(code, 3U, 1));
code = "void foo(const std::atomic<int> &x) {\n"
" if (x==2) {\n"
" return x;\n"
" }"
"}";
ASSERT_EQUALS(false, testValueOfXKnown(code, 3U, 2));
code = "int f(int i, int j) {\n"
" if (i == 0) {\n"
" if (j < 0)\n"
" return 0;\n"
" i = j+1;\n"
" }\n"
" int x = i;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 8U, 0));
code = "int f(int i, int j) {\n"
" if (i == 0) {\n"
" if (j < 0)\n"
" return 0;\n"
" if (j < 0)\n"
" i = j+1;\n"
" }\n"
" int x = i;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 9U, 0));
code = "void g(long& a);\n"
"void f(long a) {\n"
" if (a == 0)\n"
" return;\n"
" if (a > 1)\n"
" g(a);\n"
" int x = a;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXImpossible(code, 8U, 0));
code = "int foo(int n) {\n"
" if( n>= 8 ) {\n"
" while(true) {\n"
" n -= 8;\n"
" if( n < 8 )\n"
" break;\n"
" }\n"
" int x = n == 0;\n"
" return x;\n"
" }\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXKnown(code, 9U, 0));
code = "bool c();\n"
"long f() {\n"
" bool stop = false;\n"
" while (!stop) {\n"
" if (c())\n"
" stop = true;\n"
" break;\n"
" }\n"
" int x = !stop;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXImpossible(code, 10U, 1));
ASSERT_EQUALS(false, testValueOfXKnown(code, 10U, 0));
code = "int f(int a, int b) {\n"
" if (!a && !b)\n"
" return;\n"
" if ((!a && b) || (a && !b))\n"
" return;\n"
" int x = a;\n" // <- a is _not_ 0
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 7U, 0));
code = "void f(int x, int y) {\n"
" if (x && y)\n"
" return;\n"
" int a = x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 0));
ASSERT_EQUALS(false, testValueOfXKnown(code, 4U, 0));
ASSERT_EQUALS(false, testValueOfXImpossible(code, 4U, 1));
code = "int f(std::vector<int> a, std::vector<int> b) {\n"
" if (a.empty() && b.empty())\n"
" return 0;\n"
" bool x = a.empty() && !b.empty();\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXKnown(code, 5U, 0));
ASSERT_EQUALS(false, testValueOfXKnown(code, 5U, 1));
ASSERT_EQUALS(false, testValueOfXImpossible(code, 5U, 0));
ASSERT_EQUALS(false, testValueOfXImpossible(code, 5U, 1));
code = "auto f(int i) {\n"
" if (i == 0) return;\n"
" auto x = !i;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 4U, 0));
code = "auto f(int i) {\n"
" if (i == 1) return;\n"
" auto x = !i;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXImpossible(code, 4U, 0));
code = "int g(int x) {\n"
" switch (x) {\n"
" case 1:\n"
" return 1;\n"
" default:\n"
" return 2;\n"
" }\n"
"}\n"
"void f(int x) {\n"
" if (x == 3)\n"
" x = g(0);\n"
" int a = x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 12U, 3));
code = "long long f(const long long& x, const long long& y) {\n"
" switch (s) {\n"
" case 0:\n"
" if (x >= 64)\n"
" return 0;\n"
" return (long long)y << (long long)x;\n"
" case 1:\n"
" if (x >= 64) {\n"
" }\n"
" }\n"
" return 0; \n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 6U, 63));
ASSERT_EQUALS(true, testValueOfXImpossible(code, 6U, 64));
code = "long long f(const long long& x, const long long& y) {\n"
" switch (s) {\n"
" case 0:\n"
" if (x >= 64)\n"
" return 0;\n"
" return long long(y) << long long(x);\n"
" case 1:\n"
" if (x >= 64) {\n"
" }\n"
" }\n"
" return 0; \n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 6U, 63));
ASSERT_EQUALS(true, testValueOfXImpossible(code, 6U, 64));
code = "long long f(const long long& x, const long long& y) {\n"
" switch (s) {\n"
" case 0:\n"
" if (x >= 64)\n"
" return 0;\n"
" return long long{y} << long long{x};\n"
" case 1:\n"
" if (x >= 64) {\n"
" }\n"
" }\n"
" return 0; \n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 6U, 63));
ASSERT_EQUALS(true, testValueOfXImpossible(code, 6U, 64));
code = "int g(int x) { throw 0; }\n"
"void f(int x) {\n"
" if (x == 3)\n"
" x = g(0);\n"
" int a = x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXImpossible(code, 5U, 3));
code = "struct a {\n"
" a *b() const;\n"
" void c();\n"
"};\n"
"void e(a *x) {\n"
" while (x && x->b())\n"
" x = x->b();\n"
" x->c();\n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 8U, 0));
code = "struct a {\n"
" a *b();\n"
" void c();\n"
"};\n"
"void e(a *x) {\n"
" while (x && x->b())\n"
" x = x->b();\n"
" x->c();\n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 8U, 0));
code = "constexpr int f();\n"
"int g() {\n"
" if (f() == 1) {\n"
" int x = f();\n"
" return x;\n"
" }\n"
" return 0;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 5U, 1));
code = "int f(int x) {\n"
" if (x == 1) {\n"
" for(int i=0;i<1;i++) {\n"
" if (x == 1)\n"
" continue;\n"
" }\n"
" }\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 8U, 1));
ASSERT_EQUALS(false, testValueOfXImpossible(code, 8U, 1));
code = "void g(int i) {\n"
" if (i == 1)\n"
" return;\n"
" abort();\n"
"}\n"
"int f(int x) {\n"
" if (x != 0)\n"
" g(x);\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXKnown(code, 9U, 0));
ASSERT_EQUALS(true, testValueOfX(code, 9U, 0));
}
void valueFlowAfterConditionTernary()
{
const char* code;
code = "auto f(int x) {\n"
" return x == 3 ?\n"
" x :\n"
" 0;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 3));
code = "auto f(int x) {\n"
" return x != 3 ?\n"
" 0 :\n"
" x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 3));
code = "auto f(int x) {\n"
" return !(x == 3) ?\n"
" 0 :\n"
" x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 3));
code = "auto f(int* x) {\n"
" return x ?\n"
" x :\n"
" 0;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 3U, 0));
code = "auto f(int* x) {\n"
" return x ?\n"
" 0 :\n"
" x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 0));
code = "bool g(int);\n"
"auto f(int* x) {\n"
" if (!g(x ?\n"
" *x :\n"
" 0)) {}\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 4U, 0));
}
void valueFlowAfterConditionExpr() {
const char* code;
code = "void f(int* p) {\n"
" if (p[0] == 123) {\n"
" int x = p[0];\n"
" int a = x;\n"
" }\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 123));
code = "void f(int y) {\n"
" if (y+1 == 123) {\n"
" int x = y+1;\n"
" int a = x;\n"
" }\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 123));
code = "void f(int y) {\n"
" if (y+1 == 123) {\n"
" int x = y+2;\n"
" int a = x;\n"
" }\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 124));
code = "void f(int y, int z) {\n"
" if (y+z == 123) {\n"
" int x = y+z;\n"
" int a = x;\n"
" }\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 123));
code = "void f(int y, int z) {\n"
" if (y+z == 123) {\n"
" y++;\n"
" int x = y+z;\n"
" int a = x;\n"
" }\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 5U, 123));
code = "void f(int y) {\n"
" if (y++ == 123) {\n"
" int x = y++;\n"
" int a = x;\n"
" }\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 4U, 123));
ASSERT_EQUALS(false, testValueOfX(code, 4U, 124));
ASSERT_EQUALS(false, testValueOfX(code, 4U, 125));
code = "struct A {\n"
" bool g() const;\n"
"};\n"
"void f(A a) {\n"
" if (a.g()) {\n"
" bool x = a.g();\n"
" bool a = x;\n"
" }\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXKnown(code, 7U, 0));
code = "struct A {\n"
" bool g() const;\n"
"};\n"
"void f(A a) {\n"
" if (a.g()) {\n"
" bool x = !a.g();\n"
" bool a = x;\n"
" }\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 7U, 0));
code = "struct A {\n"
" bool g() const;\n"
"};\n"
"void f(A a) {\n"
" if (!a.g()) {\n"
" bool x = a.g();\n"
" bool a = x;\n"
" }\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 7U, 0));
code = "void f(std::vector<int> v) {\n"
" if (v.size() == 3) {\n"
" if (v.size() == 1) {\n"
" int x = 1;\n"
" int a = x;\n"
" }\n"
" }\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 5U, 1));
}
void valueFlowAfterConditionSeveralNot() {
const char *code;
code = "int f(int x, int y) {\n"
" if (x!=0) {}\n"
" return y/x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 0));
code = "int f(int x, int y) {\n"
" if (!!(x != 0)) {\n"
" return y/x;\n"
"}\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 3U, 0));
code = "int f(int x, int y) {\n"
" if (!!!(x != 0)) {\n"
" return y/x;\n"
"}\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 0));
code = "int f(int x, int y) {\n"
" if (!!!!(x != 0)) {\n"
" return y/x;\n"
"}\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 3U, 0));
}
void valueFlowForwardCompoundAssign() {
const char *code;
code = "int f() {\n"
" int x = 123;\n"
" x += 43;\n"
" return x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 166));
ASSERT_EQUALS("2,Assignment 'x=123', assigned value is 123\n"
"3,Compound assignment '+=', assigned value is 166\n",
getErrorPathForX(code, 4U));
code = "int f() {\n"
" int x = 123;\n"
" x /= 0;\n" // don't crash when evaluating x/=0
" return x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 4U, 123));
code = "float f() {\n"
" float x = 123.45f;\n"
" x += 67;\n"
" return x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 4U, (double)123.45f + 67, 0.01));
code = "double f() {\n"
" double x = 123.45;\n"
" x += 67;\n"
" return x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 123.45 + 67, 0.01));
code = "void f() {\n"
" int x = 123;\n"
" x >>= 1;\n"
" return x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 61));
code = "int f() {\n"
" int x = 123;\n"
" x <<= 1;\n"
" return x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 246));
}
void valueFlowForwardCorrelatedVariables() {
const char *code;
code = "void f(int x = 0) {\n"
" bool zero(x==0);\n"
" if (zero) a = x;\n" // <- x is 0
" else b = x;\n" // <- x is not 0
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 0));
ASSERT_EQUALS(false, testValueOfX(code, 4U, 0));
code = "int g();\n"
"int f(bool i, bool j) {\n"
" if (i && j) {}\n"
" else {\n"
" int x = 0;\n"
" if (i)\n"
" x = g();\n"
" return x;\n"
" }\n"
" return 0;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXKnown(code, 8U, 0));
ASSERT_EQUALS(true, testValueOfX(code, 8U, 0));
}
void valueFlowForwardModifiedVariables() {
const char *code;
code = "void f(bool b) {\n"
" int x = 0;\n"
" if (b) x = 1;\n"
" else b = x;\n"
"}";
ASSERT_EQUALS(true, testValueOfXKnown(code, 4U, 0));
code = "void f(int i) {\n"
" int x = 0;\n"
" if (i == 0)\n"
" x = 1;\n"
" else if (!x && i == 1)\n"
" int b = x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 5U, 0));
ASSERT_EQUALS(true, testValueOfXKnown(code, 6U, 0));
}
void valueFlowForwardFunction() {
const char *code;
code = "class C {\n"
"public:\n"
" C(int &i);\n" // non-const argument => might be changed
"};\n"
"int f() {\n"
" int x=1;\n"
" C c(x);\n"
" return x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 8U, 1));
code = "class C {\n"
"public:\n"
" C(const int &i);\n" // const argument => is not changed
"};\n"
"int f() {\n"
" int x=1;\n"
" C c(x);\n"
" return x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 8U, 1));
code = "int f(int *);\n"
"int g() {\n"
" const int a = 1;\n"
" int x = 11;\n"
" c = (a && f(&x));\n"
" if (x == 42) {}\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 6U, 11));
code = "void f() {\n"
" int x = 1;\n"
" exit(x);\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 3U, 1));
code = "void f(jmp_buf env) {\n"
" int x = 1;\n"
" longjmp(env, x);\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 3U, 1));
}
void valueFlowForwardTernary() {
const char *code;
code = "int f() {\n"
" int x=5;\n"
" a = b ? init1(&x) : init2(&x);\n"
" return 1 + x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 5));
ASSERT_EQUALS(false, testValueOfX(code, 4U, 5));
code = "int f(int *p) {\n" // #9008 - gcc ternary ?:
" if (p) return;\n"
" x = *p ? : 1;\n" // <- no explicit expr0
"}";
(void)testValueOfX(code, 1U, 0); // do not crash
code = "void f(int a) {\n" // #8784
" int x = 13;\n"
" if (a == 1) x = 26;\n"
" return a == 1 ? x : 0;\n" // <- x is 26
"}";
ASSERT_EQUALS(false, testValueOfX(code, 4U, 13));
ASSERT_EQUALS(true, testValueOfX(code, 4U, 26));
code = "void f(int* i) {\n"
" if (!i) return;\n"
" int * x = *i == 1 ? i : nullptr;\n"
" int* a = x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 0));
ASSERT_EQUALS(false, testValueOfXImpossible(code, 4U, 0));
}
void valueFlowForwardLambda() {
const char *code;
code = "void f() {\n"
" int x=1;\n"
" auto f = [&](){ a=x; }\n" // x is not 1
" x = 2;\n"
" f();\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 3U, 1));
TODO_ASSERT_EQUALS(true, false, testValueOfX(code, 3U, 2));
code = "void f() {\n"
" int x=3;\n"
" auto f = [&](){ a=x; }\n" // todo: x is 3
" f();\n"
"}";
TODO_ASSERT_EQUALS(true, false, testValueOfX(code, 3U, 3));
code = "void f() {\n"
" int x=3;\n"
" auto f = [&](){ x++; }\n"
" x = 1;\n"
" f();\n"
" int a = x;\n" // x is actually 2
"}";
ASSERT_EQUALS(false, testValueOfX(code, 6U, 1));
ASSERT_EQUALS(false, testValueOfX(code, 6U, 3));
}
void valueFlowForwardTryCatch() {
const char *code;
code = "void g1();\n"
"void g2();\n"
"void f()\n {"
" bool x = false;\n"
" try {\n"
" g1();\n"
" x = true;\n"
" g2();\n"
" }\n"
" catch (...) {\n"
" if (x) {}\n"
" }\n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 11U, 1));
ASSERT_EQUALS(false, testValueOfXKnown(code, 11U, 1));
code = "void g1();\n"
"void g2();\n"
"void f()\n {"
" bool x = true;\n"
" try {\n"
" g1();\n"
" g2();\n"
" }\n"
" catch (...) {\n"
" if (x) {}\n"
" }\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 10U, 1));
}
void valueFlowBitAnd() {
const char *code;
code = "int f(int a) {\n"
" int x = a & 0x80;\n"
" return x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code,3U,0));
ASSERT_EQUALS(true, testValueOfX(code,3U,0x80));
code = "int f(int a) {\n"
" int x = a & 0x80 ? 1 : 2;\n"
" return x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code,3U,0));
ASSERT_EQUALS(false, testValueOfX(code,3U,0x80));
code = "int f() {\n"
" int x = (19 - 3) & 15;\n"
" return x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code,3U,0));
ASSERT_EQUALS(false, testValueOfX(code,3U,16));
}
void valueFlowForwardInconclusiveImpossible() {
const char *code;
code = "void foo() {\n"
" bool valid = f1();\n"
" if (!valid) return;\n"
" std::tie(endVal, valid) = f2();\n"
" bool x = !valid;"
" bool b = x;" // <- not always true
"}\n";
ASSERT_EQUALS(false, testValueOfXKnown(code, 6U, 1));
}
void valueFlowForwardConst()
{
const char* code;
code = "int f() {\n"
" const int i = 2;\n"
" const int x = i+1;\n"
" goto end;\n"
"end:\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 6U, 3));
code = "int f() {\n"
" int i = 2;\n"
" const int& x = i;\n"
" i++;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXKnown(code, 6U, 2));
code = "int f(int a, int b, int c) {\n"
" const int i = 2;\n"
" const int x = i+1;\n"
" if (a == x) { return 0; }\n"
" if (b == x) { return 0; }\n"
" if (c == x) { return 0; }\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 7U, 3));
code = "int f(int a, int b, int c) {\n"
" const int i = 2;\n"
" const int y = i+1;\n"
" const int& x = y;\n"
" if (a == x) { return 0; }\n"
" if (b == x) { return 0; }\n"
" if (c == x) { return 0; }\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 8U, 3));
code = "int f(int a, int b, int c, int x) {\n"
" const int i = 2;\n"
" const int y = i+1;\n"
" if (a == y) { return 0; }\n"
" if (b == y) { return 0; }\n"
" if (c == y) { return 0; }\n"
" if (x == y)\n"
" return x;\n"
" return 0;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 8U, 3));
}
void valueFlowForwardAfterCondition()
{
const char* code;
code = "int g();\n"
"void f() {\n"
" int x = 3;\n"
" int kk = 11;\n"
" for (;;) {\n"
" if (kk > 10) {\n"
" kk = 0;\n"
" x = g();\n"
" }\n"
" kk++;\n"
" int a = x;\n"
" }\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 11U, 3));
code = "int g();\n"
"void f() {\n"
" int x = 3;\n"
" int kk = 11;\n"
" while (true) {\n"
" if (kk > 10) {\n"
" kk = 0;\n"
" x = g();\n"
" }\n"
" kk++;\n"
" int a = x;\n"
" }\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 11U, 3));
code = "int g();\n"
"void f() {\n"
" int x = 3;\n"
" int kk = 11;\n"
" if (true) {\n"
" if (kk > 10) {\n"
" kk = 0;\n"
" x = g();\n"
" }\n"
" kk++;\n"
" int a = x;\n"
" }\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 11U, 3));
}
void valueFlowRightShift() {
const char *code;
/* Set some temporary fixed values to simplify testing */
/*const*/ Settings s = settings;
s.platform.int_bit = 32;
s.platform.long_bit = 64;
s.platform.long_long_bit = MathLib::bigint_bits * 2;
code = "int f(int a) {\n"
" int x = (a & 0xff) >> 16;\n"
" return x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code,3U,0,&s));
code = "int f(unsigned int a) {\n"
" int x = (a % 123) >> 16;\n"
" return x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code,3U,0,&s));
code = "int f(int y) {\n"
" int x = (y & 0xFFFFFFF) >> 31;\n"
" return x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3u, 0));
code = "int f(int y) {\n"
" int x = (y & 0xFFFFFFF) >> 32;\n"
" return x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 3u, 0,&s));
code = "int f(short y) {\n"
" int x = (y & 0xFFFFFF) >> 31;\n"
" return x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3u, 0,&s));
code = "int f(short y) {\n"
" int x = (y & 0xFFFFFF) >> 32;\n"
" return x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 3u, 0,&s));
code = "int f(long y) {\n"
" int x = (y & 0xFFFFFF) >> 63;\n"
" return x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3u, 0,&s));
code = "int f(long y) {\n"
" int x = (y & 0xFFFFFF) >> 64;\n"
" return x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 3u, 0,&s));
code = "int f(long long y) {\n"
" int x = (y & 0xFFFFFF) >> 63;\n"
" return x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3u, 0,&s));
code = "int f(long long y) {\n"
" int x = (y & 0xFFFFFF) >> 64;\n"
" return x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 3u, 0,&s));
code = "int f(long long y) {\n"
" int x = (y & 0xFFFFFF) >> 121;\n"
" return x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 3u, 0,&s));
code = "int f(long long y) {\n"
" int x = (y & 0xFFFFFF) >> 128;\n"
" return x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 3u, 0,&s));
}
void valueFlowFwdAnalysis() {
const char *code;
std::list<ValueFlow::Value> values;
code = "void f() {\n"
" struct Foo foo;\n"
" foo.x = 1;\n"
" x = 0 + foo.x;\n" // <- foo.x is 1
"}";
values = removeSymbolicTok(tokenValues(code, "+"));
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(true, values.front().isKnown());
ASSERT_EQUALS(true, values.front().isIntValue());
ASSERT_EQUALS(1, values.front().intvalue);
code = "void f() {\n"
" S s;\n"
" s.x = 1;\n"
" int y = 10;\n"
" while (s.x < y)\n" // s.x does not have known value
" s.x++;\n"
"}";
values = removeImpossible(tokenValues(code, "<"));
ASSERT_EQUALS(1, values.size());
ASSERT(values.front().isPossible());
ASSERT_EQUALS(1, values.front().intvalue);
code = "void f() {\n"
" S s;\n"
" s.x = 37;\n"
" int y = 10;\n"
" while (s.x < y)\n" // s.x has a known value
" y--;\n"
"}";
values = tokenValues(code, ". x <");
ASSERT(values.size() == 1 &&
values.front().isKnown() &&
values.front().isIntValue() &&
values.front().intvalue == 37);
code = "void f() {\n"
" Hints hints;\n"
" hints.x = 1;\n"
" if (foo)\n"
" hints.x = 2;\n"
" x = 0 + foo.x;\n" // <- foo.x is possible 1, possible 2
"}";
values = removeSymbolicTok(tokenValues(code, "+"));
TODO_ASSERT_EQUALS(2U, 0U, values.size()); // should be 2
// FP: Condition '*b>0' is always true
code = "bool dostuff(const char *x, const char *y);\n"
"void fun(char *s, int *b) {\n"
" for (int i = 0; i < 42; ++i) {\n"
" if (dostuff(s, \"1\")) {\n"
" *b = 1;\n"
" break;\n"
" }\n"
" }\n"
" if (*b > 0) {\n" // *b does not have known value
" }\n"
"}";
values = removeImpossible(tokenValues(code, ">"));
ASSERT_EQUALS(1, values.size());
ASSERT(values.front().isPossible());
ASSERT_EQUALS(1, values.front().intvalue);
code = "void foo() {\n"
" struct ISO_PVD_s pvd;\n"
" pvd.descr_type = 0xff;\n"
" do {\n"
" if (pvd.descr_type == 0xff) {}\n"
" dostuff(&pvd);\n"
" } while (condition)\n"
"}";
values = removeImpossible(tokenValues(code, "=="));
ASSERT_EQUALS(1, values.size());
ASSERT(values.front().isPossible());
ASSERT_EQUALS(1, values.front().intvalue);
// for loops
code = "struct S { int x; };\n" // #9036
"void foo(struct S s) {\n"
" for (s.x = 0; s.x < 127; s.x++) {}\n"
"}";
values = removeImpossible(tokenValues(code, "<"));
values.remove_if([&](const ValueFlow::Value& v) {
return !v.isKnown();
});
ASSERT_EQUALS(true, values.empty());
}
void valueFlowSwitchVariable() {
const char code[] = "void f(int x) {\n"
" a = x - 1;\n" // <- x can be 14
" switch (x) {\n"
" case 14: a=x+2; break;\n" // <- x is 14
" };\n"
" a = x;\n" // <- x can be 14
"}";
ASSERT_EQUALS(true, testConditionalValueOfX(code, 2U, 14));
TODO_ASSERT_EQUALS(true, false, testConditionalValueOfX(code, 4U, 14));
TODO_ASSERT_EQUALS(true, false, testConditionalValueOfX(code, 6U, 14));
ValueFlow::Value value1 = valueOfTok(code, "-");
ASSERT_EQUALS(13, value1.intvalue);
ASSERT(!value1.isKnown());
ValueFlow::Value value2 = valueOfTok(code, "+");
TODO_ASSERT_EQUALS(16, 0, value2.intvalue);
TODO_ASSERT_EQUALS(true, false, value2.isKnown());
}
void valueFlowForLoop() {
const char *code;
ValueFlow::Value value;
code = "void f() {\n"
" for (int x = 0; x < 10; x++)\n"
" a[x] = 0;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 0));
ASSERT_EQUALS(true, testValueOfX(code, 3U, 9));
ASSERT_EQUALS(false, testValueOfX(code, 3U, 10));
code = "void f() {\n"
" int x;\n"
" for (x = 2; x < 1; x++)\n"
" a[x] = 0;\n" // <- not 2
" b = x;\n" // 2
"}";
ASSERT_EQUALS(false, testValueOfX(code, 4U, 2));
ASSERT_EQUALS(true, testValueOfX(code, 5U, 2));
code = "void f() {\n"
" int x;\n"
" for (x = 2; x < 1; ++x)\n"
" a[x] = 0;\n" // <- not 2
" b = x;\n" // 2
"}";
ASSERT_EQUALS(false, testValueOfX(code, 4U, 2));
ASSERT_EQUALS(true, testValueOfX(code, 5U, 2));
code = "enum AB {A,B};\n" // enum => handled by valueForLoop2
"void f() {\n"
" int x;\n"
" for (x = 1; x < B; ++x)\n"
" a[x] = 0;\n" // <- not 1
"}";
ASSERT_EQUALS(false, testValueOfX(code, 5U, 1));
code = "void f(int a) {\n"
" for (int x = a; x < 10; x++)\n"
" a[x] = 0;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 9));
code = "void f() {\n"
" for (int x = 0; x < 5; x += 2)\n"
" a[x] = 0;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 0));
ASSERT_EQUALS(true, testValueOfX(code, 3U, 4));
code = "void f() {\n"
" for (int x = 0; x < 10; x = x + 2)\n"
" a[x] = 0;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 0));
ASSERT_EQUALS(true, testValueOfX(code, 3U, 8));
ASSERT_EQUALS(false, testValueOfX(code, 3U, 10));
code = "void f() {\n"
" for (int x = 0; x < 10; x = x / 0)\n"
" a[x] = 0;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 0)); // don't crash
code = "void f() {\n"
" for (int x = 0; x < 10; x++)\n"
" x<4 ?\n"
" a[x] : 0;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 0));
ASSERT_EQUALS(true, testValueOfX(code, 3U, 9));
ASSERT_EQUALS(false, testValueOfX(code, 4U, 9));
code = "void f() {\n"
" for (int x = 0; x < 10; x++)\n"
" x==0 ?\n"
" 0 : a[x];\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 4U, 0));
code = "void f() {\n" // #5223
" for (int x = 0; x < 300 && x < 18; x++)\n"
" x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 0));
ASSERT_EQUALS(true, testValueOfX(code, 3U, 17));
ASSERT_EQUALS(false, testValueOfX(code, 3U, 299));
code = "void f() {\n"
" int x;\n"
" for (int i = 0; x = bar[i]; i++)\n"
" x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 4U, 0));
code = "void f() {\n"
" const char abc[] = \"abc\";\n"
" int x;\n"
" for (x = 0; abc[x] != '\\0'; x++) {}\n"
" a[x] = 0;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 5U, 3));
code = "void f() {\n" // #5939
" int x;\n"
" for (int x = 0; (x = do_something()) != 0;)\n"
" x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 4U, 0));
code = "void f() {\n"
" int x;\n"
" for (int x = 0; x < 10 && y = do_something();)\n"
" x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 0));
code = "void f() {\n"
" int x,y;\n"
" for (x = 0, y = 0; x < 10, y < 10; x++, y++)\n" // usage of ,
" x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 0));
code = "void foo(double recoveredX) {\n"
" for (double x = 1e-18; x < 1e40; x *= 1.9) {\n"
" double relativeError = (x - recoveredX) / x;\n"
" }\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 3U, 0));
// Ticket #7139
// "<<" in third expression of for
code = "void f(void) {\n"
" int bit, x;\n"
" for (bit = 1, x = 0; bit < 128; bit = bit << 1, x++) {\n"
" z = x;\n" // <- known value [0..6]
" }\n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 0));
ASSERT_EQUALS(true, testValueOfX(code, 4U, 6));
ASSERT_EQUALS(false, testValueOfX(code, 4U, 7));
// &&
code = "void foo() {\n"
" for (int x = 0; x < 10; x++) {\n"
" if (x > 1\n"
" && x) {}" // <- x is not 0
" }\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 4U, 0));
// Known to be true, but it could also be 9
ASSERT_EQUALS(true, testValueOfXKnown(code, 4U, 1));
code = "void foo() {\n"
" for (int x = 0; x < 10; x++) {\n"
" if (x < value\n"
" && x) {}" // <- maybe x is not 9
" }\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 4U, 9));
// ||
code = "void foo() {\n"
" for (int x = 0; x < 10; x++) {\n"
" if (x == 0\n"
" || x) {}" // <- x is not 0
" }\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 4U, 0));
// Known to be true, but it could also be 9
ASSERT_EQUALS(true, testValueOfXKnown(code, 4U, 1));
// After loop
code = "void foo() {\n"
" int x;\n"
" for (x = 0; x < 10; x++) {}\n"
" a = x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 10));
code = "void foo() {\n"
" int x;\n"
" for (x = 0; 2 * x < 20; x++) {}\n"
" a = x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 10));
code = "void foo() {\n" // related with #887
" int x;\n"
" for (x = 0; x < 20; x++) {}\n"
" a = x++;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 20));
code = "void f() {\n"
" int x;\n"
" for (x = 0; x < 5; x++) {}\n"
" if (x == 5) {\n"
" abort();\n"
" }\n"
" a = x;\n" // <- x can't be 5
"}";
ASSERT_EQUALS(false, testValueOfX(code, 7U, 5));
code = "void f() {\n"
" int x;\n"
" for (x = 0; x < 5; x++) {}\n"
" if (x < 5) {}\n"
" else return;\n"
" a = x;\n" // <- x can't be 5
"}";
ASSERT_EQUALS(false, testValueOfX(code, 6U, 5));
// assert after for loop..
code = "static void f() {\n"
" int x;\n"
" int ctls[10];\n"
" for (x = 0; x <= 10; x++) {\n"
" if (cond)\n"
" break;\n"
" }\n"
" assert(x <= 10);\n"
" ctls[x] = 123;\n" // <- x can't be 11
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 9U, 11));
// hang
code = "void f() {\n"
" for(int i = 0; i < 20; i++)\n"
" n = (int)(i < 10 || abs(negWander) < abs(negTravel));\n"
"}";
(void)testValueOfX(code,0,0); // <- don't hang
// crash (daca@home)
code = "void foo(char *z, int n) {\n"
" int i;\n"
" if (fPScript) {\n"
" i = 1;\n"
" } else if (strncmp(&z[n], \"<!--\", 4) == 0) {\n"
" for (i = 4;;) {\n"
" if (z[n] && strncmp(&z[n+i], \"-->\", 3) == 0) ;\n"
" }\n"
" }\n"
"}";
(void)testValueOfX(code,0,0); // <- don't crash
// conditional code in loop
code = "void f(int mask) {\n" // #6000
" for (int x = 10; x < 14; x++) {\n"
" int bit = mask & (1 << i);\n"
" if (bit) {\n"
" if (bit == (1 << 10)) {}\n"
" else { a = x; }\n" // <- x is not 10
" }\n"
" }\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 6U, 10));
// #7886 - valueFlowForLoop must be called after valueFlowAfterAssign
code = "void f() {\n"
" int sz = 4;\n"
" int x,y;\n"
" for(x=0,y=0; x < sz && y < 10; x++)\n"
" a = x;\n" // <- max value is 3
"}";
ASSERT_EQUALS(true, testValueOfX(code, 5U, 3));
code = "void f() {\n"
" int x;\n"
" for (x = 0; x < 10; x++)\n"
" x;\n"
"}";
std::list<ValueFlow::Value> values = tokenValues(code, "x <");
ASSERT(std::none_of(values.cbegin(), values.cend(), std::mem_fn(&ValueFlow::Value::isUninitValue)));
// #9637
code = "void f() {\n"
" unsigned int x = 0;\n"
" for (x = 0; x < 2; x++) {}\n"
"}\n";
value = valueOfTok(code, "x <");
ASSERT(value.isPossible());
ASSERT_EQUALS(0, value.intvalue);
code = "void f() {\n"
" unsigned int x = 0;\n"
" for (;x < 2; x++) {}\n"
"}\n";
value = valueOfTok(code, "x <");
ASSERT(value.isPossible());
ASSERT_EQUALS(0, value.intvalue);
code = "void f() {\n"
" unsigned int x = 1;\n"
" for (x = 0; x < 2; x++) {}\n"
"}\n";
value = valueOfTok(code, "x <");
ASSERT(!value.isKnown());
code = "void b(int* a) {\n" // #10795
" for (*a = 1;;)\n"
" if (0) {}\n"
"}\n"
"struct S { int* a; }\n"
"void b(S& s) {\n"
" for (*s.a = 1;;)\n"
" if (0) {}\n"
"}\n"
"struct T { S s; };\n"
"void b(T& t) {\n"
" for (*&t.s.a[0] = 1;;)\n"
" if (0) {}\n"
"}\n";
ASSERT_NO_THROW(testValueOfX(code, 0, 0));
code = "void f() {\n"
" int p[2];\n"
" for (p[0] = 0; p[0] <= 2; p[0]++) {\n"
" for (p[1] = 0; p[1] <= 2 - p[0]; p[1]++) {}\n"
" }\n"
"}\n";
ASSERT_NO_THROW(testValueOfX(code, 0, 0));
code = "struct C {\n" // #10828
" int& v() { return i; }\n"
" int& w() { return j; }\n"
" int i{}, j{};\n"
"};\n"
"void f() {\n"
" C c;\n"
" for (c.w() = 0; c.w() < 2; c.w()++) {\n"
" for (c.v() = 0; c.v() < 24; c.v()++) {}\n"
" }\n"
"}\n";
ASSERT_NO_THROW(testValueOfX(code, 0, 0));
// #11072
code = "struct a {\n"
" long b;\n"
" long c[6];\n"
" long d;\n"
"};\n"
"void e(long) {\n"
" a f = {0};\n"
" for (f.d = 0; 2; f.d++)\n"
" e(f.c[f.b]);\n"
"}\n";
values = tokenValues(code, ". c");
ASSERT_EQUALS(true, values.empty());
values = tokenValues(code, "[ f . b");
ASSERT_EQUALS(true, values.empty());
code = "void f() {\n" // #13109
" const int a[10] = {};\n"
" for (int n = 0; 1; ++n) {\n"
" (void)a[n];\n"
" break;\n"
" }\n"
"}\n";
values = tokenValues(code, "n ]");
ASSERT_EQUALS(2, values.size());
auto it = values.begin();
ASSERT_EQUALS(-1, it->intvalue);
ASSERT(it->isImpossible());
++it;
ASSERT_EQUALS(0, it->intvalue);
ASSERT(it->isPossible());
code = "void f() {\n"
" const int a[10] = {};\n"
" for (int n = 0; 1; ++n) {\n"
" if (a[n] < 1)\n"
" break;\n"
" }\n"
"}\n";
values = tokenValues(code, "n ]");
ASSERT_EQUALS(2, values.size());
it = values.begin();
ASSERT_EQUALS(-1, it->intvalue);
ASSERT(it->isImpossible());
++it;
ASSERT_EQUALS(0, it->intvalue);
ASSERT(it->isPossible());
code = "void f() {\n"
" const int a[10] = {};\n"
" for (int n = 0; 1; ++n) {\n"
" if (a[n] < 1)\n"
" throw 0;\n"
" }\n"
"}\n";
values = tokenValues(code, "n ]");
ASSERT_EQUALS(2, values.size());
it = values.begin();
ASSERT_EQUALS(-1, it->intvalue);
ASSERT(it->isImpossible());
++it;
ASSERT_EQUALS(0, it->intvalue);
ASSERT(it->isPossible());
code = "void f() {\n"
" const int a[10] = {};\n"
" for (int n = 0; 1; ++n) {\n"
" (void)a[n];\n"
" exit(1);\n"
" }\n"
"}\n";
values = tokenValues(code, "n ]");
ASSERT_EQUALS(2, values.size());
it = values.begin();
ASSERT_EQUALS(-1, it->intvalue);
ASSERT(it->isImpossible());
++it;
ASSERT_EQUALS(0, it->intvalue);
ASSERT(it->isPossible());
code = "void f() {\n"
" const int a[10] = {};\n"
" for (int n = 0; 1; ++n) {\n"
" if (a[n] < 1)\n"
" exit(1);\n"
" }\n"
"}\n";
values = tokenValues(code, "n ]");
ASSERT_EQUALS(2, values.size());
it = values.begin();
ASSERT_EQUALS(-1, it->intvalue);
ASSERT(it->isImpossible());
++it;
ASSERT_EQUALS(0, it->intvalue);
ASSERT(it->isPossible());
}
void valueFlowSubFunction() {
const char *code;
code = "int f(int size) {\n"
" int x = 0;\n"
" if(size>16) {\n"
" x = size;\n"
" int a = x;\n"
" }\n"
" return x;\n"
"}\n"
"void g(){\n"
" f(42);\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 5U, 17));
ASSERT_EQUALS(true, testValueOfX(code, 5U, 42));
ASSERT_EQUALS(true, testValueOfX(code, 7U, 0));
ASSERT_EQUALS(true, testValueOfX(code, 7U, 17));
ASSERT_EQUALS(true, testValueOfX(code, 7U, 42));
code = "void g(int, int) {}\n"
"void f(int x, int y) {\n"
" g(x, y);\n"
"}\n"
"void h() {\n"
" f(0, 0);\n"
" f(1, 1);\n"
" f(2, 2);\n"
" f(3, 3);\n"
" f(4, 4);\n"
" f(5, 5);\n"
" f(6, 6);\n"
" f(7, 7);\n"
" f(8, 8);\n"
" f(9, 9);\n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 0));
ASSERT_EQUALS(true, testValueOfX(code, 3U, 1));
ASSERT_EQUALS(true, testValueOfX(code, 3U, 2));
ASSERT_EQUALS(true, testValueOfX(code, 3U, 3));
ASSERT_EQUALS(true, testValueOfX(code, 3U, 4));
ASSERT_EQUALS(true, testValueOfX(code, 3U, 5));
ASSERT_EQUALS(true, testValueOfX(code, 3U, 6));
ASSERT_EQUALS(true, testValueOfX(code, 3U, 7));
ASSERT_EQUALS(true, testValueOfX(code, 3U, 8));
ASSERT_EQUALS(true, testValueOfX(code, 3U, 9));
code = "int f(int i, int j) {\n"
" if (i == j) {\n"
" int x = i;\n"
" return x;\n"
" }\n"
" return 0;\n"
"}\n"
"int g(int x) {\n"
" f(x, -1);\n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 4U, -1));
code = "void g() {\n"
" const std::vector<int> v;\n"
" f(v);\n"
"}\n"
"void f(const std::vector<int>& w) {\n"
" for (int i = 0; i < w.size(); ++i) {\n"
" int x = i != 0;\n"
" int a = x;\n"
" }\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXKnown(code, 8U, 0));
ASSERT_EQUALS(false, testValueOfXKnown(code, 8U, 1));
code = "void g() {\n"
" const std::vector<int> v;\n"
" f(v);\n"
"}\n"
"void f(const std::vector<int>& w) {\n"
" for (int i = 0; i < w.size(); ++i) {\n"
" int x = i;\n"
" int a = x;\n"
" }\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 8U, -1));
code = "typedef enum {\n"
" K0, K1\n"
"} K;\n"
"bool valid(Object *obj, K x) {\n"
" if (!obj || obj->kind != x)\n"
" return false;\n"
" return x == K0;\n"
"}\n"
"void f(Object *obj) {\n"
" if (valid(obj, K0)) {}\n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 7U, 0));
ASSERT_EQUALS(false, testValueOfXKnown(code, 7U, 0));
code = "int f(int i) {\n"
" int x = abs(i);\n"
" return x;\n"
"}\n"
"void g() {\n"
" f(1);\n"
" f(0);\n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 1));
ASSERT_EQUALS(true, testValueOfX(code, 3U, 0));
code = "void foo(int* p, int* x) {\n"
" bool b1 = (p != NULL);\n"
" bool b2 = b1 && (x != NULL);\n"
" if (b2) {\n"
" *x = 3;\n"
" }\n"
"}\n"
"\n"
"void bar() {\n"
" foo(NULL, NULL);\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 5U, 0));
}
void valueFlowFunctionReturn() {
const char *code;
code = "int f1(int x) {\n"
" return x+1;\n"
"}\n"
"void f2() {\n"
" x = 10 - f1(2);\n"
"}";
ASSERT_EQUALS(7, valueOfTok(code, "-").intvalue);
ASSERT_EQUALS(true, valueOfTok(code, "-").isKnown());
code = "int add(int x, int y) {\n"
" return x+y;\n"
"}\n"
"void f2() {\n"
" x = 2 * add(10+1,4);\n"
"}";
ASSERT_EQUALS(30, valueOfTok(code, "*").intvalue);
ASSERT_EQUALS(true, valueOfTok(code, "*").isKnown());
code = "int one() { return 1; }\n"
"void f() { x = 2 * one(); }";
ASSERT_EQUALS(2, valueOfTok(code, "*").intvalue);
ASSERT_EQUALS(true, valueOfTok(code, "*").isKnown());
code = "int add(int x, int y) {\n"
" return x+y;\n"
"}\n"
"void f2() {\n"
" x = 2 * add(1,add(2,3));\n"
"}";
ASSERT_EQUALS(12, valueOfTok(code, "*").intvalue);
ASSERT_EQUALS(true, valueOfTok(code, "*").isKnown());
code = "int f(int i, X x) {\n"
" if (i)\n"
" return g(std::move(x));\n"
" g(x);\n"
" return 0;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 4U, ValueFlow::Value::MoveKind::MovedVariable));
code = "class A\n"
"{\n"
" int f1(int x) {\n"
" return x+1;\n"
" }\n"
" void f2() {\n"
" x = 10 - f1(2);\n"
" }\n"
"};";
ASSERT_EQUALS(7, valueOfTok(code, "-").intvalue);
ASSERT_EQUALS(true, valueOfTok(code, "-").isKnown());
code = "class A\n"
"{\n"
" virtual int f1(int x) {\n"
" return x+1;\n"
" }\n"
" void f2() {\n"
" x = 10 - f1(2);\n"
" }\n"
"};";
TODO_ASSERT_EQUALS(7, 0, valueOfTok(code, "-").intvalue);
ASSERT_EQUALS(false, valueOfTok(code, "-").isKnown());
code = "struct base {\n"
" virtual int f() { return 0; }\n"
"};\n"
"void g(base* b) {\n"
" int x = b->f();\n"
" return x;\n"
"}\n";
TODO_ASSERT_EQUALS(true, false, testValueOfX(code, 6U, 0));
ASSERT_EQUALS(false, testValueOfXKnown(code, 6U, 0));
code = "struct base {\n"
" virtual int f() { return 0; }\n"
"};\n"
"void g(base& b) {\n"
" int x = b.f();\n"
" return x;\n"
"}\n";
TODO_ASSERT_EQUALS(true, false, testValueOfX(code, 6U, 0));
ASSERT_EQUALS(false, testValueOfXKnown(code, 6U, 0));
code = "struct base {\n"
" virtual int f() { return 0; }\n"
"};\n"
"struct derived : base {\n"
" int f() override { return 1; }\n"
"};\n"
"void g(derived* d) {\n"
" base* b = d;\n"
" int x = b->f();\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 10U, 0));
TODO_ASSERT_EQUALS(true, false, testValueOfX(code, 10U, 1));
code = "struct base {\n"
" virtual int f() final { return 0; }\n"
"};\n"
"void g(base* b) {\n"
" int x = b->f();\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 6U, 0));
code = "int* g(int& i, bool b) {\n"
" if(b)\n"
" return nullptr;\n"
" return &i;\n"
"} \n"
"int f(int i) {\n"
" int* x = g(i, true);\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 8U, 0));
code = "int* g(int& i, bool b) {\n"
" if(b)\n"
" return nullptr;\n"
" return &i;\n"
"} \n"
"int f(int i) {\n"
" int* x = g(i, false);\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXImpossible(code, 8U, 0));
code = "int* g(int& i, bool b) {\n"
" if(b)\n"
" return nullptr;\n"
" return &i;\n"
"} \n"
"int f(int i) {\n"
" int* x = g(i, i == 3);\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 8U, 0));
code = "struct A {\n"
" unsigned i;\n"
" bool f(unsigned x) const {\n"
" return ((i & x) != 0);\n"
" }\n"
"};\n"
"int g(A& a) {\n"
" int x = a.f(2);\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 9U, 0));
ASSERT_EQUALS(false, testValueOfX(code, 9U, 1));
ASSERT_EQUALS(false, testValueOfXImpossible(code, 9U, 0));
ASSERT_EQUALS(false, testValueOfXImpossible(code, 9U, 1));
code = "struct A {\n"
" enum {\n"
" b = 0,\n"
" c = 1,\n"
" d = 2\n"
" };\n"
" bool isb() const {\n"
" return e == b;\n"
" }\n"
" unsigned int e;\n"
"};\n"
"int f(A g) {\n"
" int x = !g.isb();\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 14U, 0));
ASSERT_EQUALS(false, testValueOfX(code, 14U, 1));
code = "bool h(char q);\n"
"bool g(char q) {\n"
" if (!h(q))\n"
" return false;\n"
" return true;\n"
"}\n"
"int f() {\n"
" int x = g(0);\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 9U, 0));
ASSERT_EQUALS(false, testValueOfX(code, 9U, 1));
}
void valueFlowFunctionDefaultParameter() {
const char *code;
code = "class continuous_src_time {\n"
" continuous_src_time(std::complex<double> f, double st = 0.0, double et = infinity) {}\n"
"};";
(void)testValueOfX(code, 2U, 2); // Don't crash (#6494)
}
bool isNotKnownValues(const char code[], const char str[]) {
const auto& values = tokenValues(code, str);
return std::none_of(values.cbegin(), values.cend(), [](const ValueFlow::Value& v) {
return v.isKnown();
});
}
void knownValue() {
const char *code;
ValueFlow::Value value;
ASSERT(valueOfTok("x = 1;", "1").isKnown());
// after assignment
code = "void f() {\n"
" int x = 1;\n"
" return x + 2;\n" // <- known value
"}";
value = valueOfTok(code, "+");
ASSERT_EQUALS(3, value.intvalue);
ASSERT(value.isKnown());
{
code = "void f() {\n"
" int x = 15;\n"
" if (x == 15) { x += 7; }\n" // <- condition is true
"}";
value = valueOfTok(code, "==");
ASSERT_EQUALS(1, value.intvalue);
ASSERT(value.isKnown());
code = "int f() {\n"
" int a = 0, x = 0;\n"
" a = index();\n"
" if (a != 0)\n"
" x = next();\n"
" return x + 1;\n"
"}\n";
value = valueOfTok(code, "+");
ASSERT(value.isPossible());
}
code = "void f() {\n"
" int x;\n"
" if (ab) { x = 7; }\n"
" return x + 2;\n" // <- possible value
"}";
value = valueOfTok(code, "+");
ASSERT_EQUALS(9, value.intvalue);
ASSERT(value.isPossible());
code = "void f(int c) {\n"
" int x = 0;\n"
" if (c) {} else { x++; }\n"
" return x + 2;\n" // <- possible value
"}";
ASSERT(isNotKnownValues(code, "+"));
code = "void f() {\n"
" int x = 0;\n"
" dostuff(&x);\n"
" if (x < 0) {}\n"
"}\n";
ASSERT(isNotKnownValues(code, "<"));
code = "void f() {\n"
" int x = 0;\n"
" dostuff(0 ? ptr : &x);\n"
" if (x < 0) {}\n"
"}\n";
ASSERT(isNotKnownValues(code, "<"));
code = "void f() {\n"
" int x = 0;\n"
" dostuff(unknown ? ptr : &x);\n"
" if (x < 0) {}\n"
"}\n";
ASSERT(isNotKnownValues(code, "<"));
code = "void f() {\n"
" int x = 0;\n"
" fred.dostuff(x);\n"
" if (x < 0) {}\n"
"}\n";
ASSERT(isNotKnownValues(code, "<"));
code = "void dostuff(int x);\n"
"void f() {\n"
" int x = 0;\n"
" dostuff(x);\n"
" if (x < 0) {}\n"
"}\n";
value = valueOfTok(code, "<");
ASSERT_EQUALS(0, value.intvalue);
ASSERT(value.isKnown());
code = "void dostuff(int & x);\n"
"void f() {\n"
" int x = 0;\n"
" dostuff(x);\n"
" if (x < 0) {}\n"
"}\n";
ASSERT(isNotKnownValues(code, "<"));
code = "void dostuff(const int & x);\n"
"void f() {\n"
" int x = 0;\n"
" dostuff(x);\n"
" if (x < 0) {}\n"
"}\n";
value = valueOfTok(code, "<");
ASSERT_EQUALS(0, value.intvalue);
ASSERT(value.isKnown());
code = "void f() {\n"
" int x = 0;\n"
" do {\n"
" if (x < 0) {}\n"
" fred.dostuff(x);\n"
" } while (abc);\n"
"}\n";
ASSERT(isNotKnownValues(code, "<"));
code = "int x;\n"
"void f() {\n"
" x = 4;\n"
" while (1) {\n"
" a = x+2;\n"
" dostuff();\n"
" }\n"
"}";
ASSERT(isNotKnownValues(code, "+"));
code = "void f() {\n"
" int x = 0;\n"
" if (y) { dostuff(x); }\n"
" if (!x) {}\n"
"}\n";
ASSERT(isNotKnownValues(code, "!"));
code = "void f() {\n"
" int x = 0;\n"
" MACRO( v, { if (y) { x++; } } );\n"
" if (!x) {}\n"
"}\n";
ASSERT(isNotKnownValues(code, "!"));
code = "void f() {\n"
" int x = 0;\n"
" for (int i = 0; i < 10; i++) {\n"
" if (cond) {\n"
" x = 1;\n"
" break;\n"
" }\n"
" }\n"
" if (!x) {}\n" // <- possible value
"}";
ASSERT(isNotKnownValues(code, "!"));
code = "void f() {\n" // #8356
" bool b = false;\n"
" for(int x = 3; !b && x < 10; x++) {\n" // <- b has known value
" for(int y = 4; !b && y < 20; y++) {}\n"
" }\n"
"}";
value = valueOfTok(code, "!");
ASSERT_EQUALS(1, value.intvalue);
ASSERT(value.isKnown());
code = "void f() {\n"
" int x = 0;\n"
" switch (state) {\n"
" case 1:\n"
" x = 1;\n"
" break;\n"
" }\n"
" if (!x) {}\n" // <- possible value
"}";
ASSERT(isNotKnownValues(code, "!"));
code = "void f() {\n" // #7049
" int x = 0;\n"
" switch (a) {\n"
" case 1:\n"
" x = 1;\n"
" case 2:\n"
" if (!x) {}\n" // <- possible value
" }\n"
"}";
ASSERT(isNotKnownValues(code, "!"));
code = "void f() {\n"
" int x = 0;\n"
" while (!x) {\n" // <- possible value
" scanf(\"%d\", &x);\n"
" }\n"
"}";
value = valueOfTok(code, "!");
ASSERT_EQUALS(1, value.intvalue);
ASSERT(value.isPossible());
code = "void f() {\n"
" int x = 0;\n"
" do { } while (++x < 12);\n" // <- possible value
"}";
ASSERT(isNotKnownValues(code, "<"));
code = "void f() {\n"
" static int x = 0;\n"
" return x + 1;\n" // <- known value
"}\n";
value = valueOfTok(code, "+");
ASSERT_EQUALS(1, value.intvalue);
ASSERT(value.isKnown());
code = "void f() {\n"
" int x = 0;\n"
"a:\n"
" a = x + 1;\n" // <- possible value
"}";
value = valueOfTok(code, "+");
ASSERT_EQUALS(1, value.intvalue);
ASSERT(value.isPossible());
// in conditional code
code = "void f(int x) {\n"
" if (!x) {\n"
" a = x+1;\n" // <- known value
" }\n"
"}";
value = valueOfTok(code, "+");
ASSERT_EQUALS(1, value.intvalue);
ASSERT(value.isKnown());
code = "void f(int x) {\n"
" if (a && 4==x && y) {\n"
" a = x+12;\n" // <- known value
" }\n"
"}";
value = valueOfTok(code, "+");
ASSERT_EQUALS(16, value.intvalue);
ASSERT(value.isKnown());
// after condition
code = "int f(int x) {\n"
" if (x == 4) {}\n"
" return x + 1;\n" // <- possible value
"}";
value = valueOfTok(code, "+");
ASSERT_EQUALS(5, value.intvalue);
ASSERT(value.isPossible());
code = "int f(int x) {\n"
" if (x < 2) {}\n"
" else if (x >= 2) {}\n" // <- known value
"}";
value = valueOfTok(code, ">=");
ASSERT_EQUALS(1, value.intvalue);
ASSERT(value.isKnown());
code = "int f(int x) {\n"
" if (x < 2) {}\n"
" else if (x > 2) {}\n" // <- possible value
"}";
ASSERT(isNotKnownValues(code, ">"));
// known and possible value
code = "void f() {\n"
" int x = 1;\n"
" int y = 2 + x;\n" // <- known value, don't care about condition
" if (x == 2) {}\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 1)); // value of x can be 1
ASSERT_EQUALS(false, testValueOfX(code, 3U, 2)); // value of x can't be 2
code = "bool f() {\n"
" const int s( 4 );"
" return s == 4;\n" // <- known value
"}";
value = valueOfTok(code, "==");
ASSERT(value.isKnown());
ASSERT_EQUALS(1, value.intvalue);
code = "bool f() {\n"
" const int s{ 4 };"
" return s == 4;\n" // <- known value
"}";
value = valueOfTok(code, "==");
ASSERT(value.isKnown());
ASSERT_EQUALS(1, value.intvalue);
code = "bool f() {\n"
" const int s = int( 4 );"
" return s == 4;\n" // <- known value
"}";
value = valueOfTok(code, "==");
ASSERT(value.isKnown());
ASSERT_EQUALS(1, value.intvalue);
code = "bool f() {\n"
" const int s = int{ 4 };"
" return s == 4;\n" // <- known value
"}";
value = valueOfTok(code, "==");
ASSERT(value.isKnown());
ASSERT_EQUALS(1, value.intvalue);
code = "bool f() {\n"
" const int s = int{};"
" return s == 0;\n" // <- known value
"}";
value = valueOfTok(code, "==");
ASSERT_EQUALS(true, value.isKnown());
ASSERT_EQUALS(1, value.intvalue);
code = "bool f() {\n"
" const int s = int();"
" return s == 0;\n" // <- known value
"}";
value = valueOfTok(code, "==");
ASSERT_EQUALS(true, value.isKnown());
ASSERT_EQUALS(1, value.intvalue);
code = "bool f() {\n"
" const int s{};"
" return s == 0;\n" // <- known value
"}";
value = valueOfTok(code, "==");
ASSERT_EQUALS(true, value.isKnown());
ASSERT_EQUALS(1, value.intvalue);
code = "bool f() {\n"
" int* p{};\n"
" return p == nullptr;\n" // <- known value
"}";
value = valueOfTok(code, "==");
ASSERT_EQUALS(true, value.isKnown());
ASSERT_EQUALS(1, value.intvalue);
code = "bool f() {\n"
" int* p{ nullptr };\n"
" return p == nullptr;\n" // <- known value
"}";
value = valueOfTok(code, "==");
ASSERT_EQUALS(true, value.isKnown());
ASSERT_EQUALS(1, value.intvalue);
code = "bool f() {\n"
" int* p{ 0 };\n"
" return p == nullptr;\n" // <- known value
"}";
value = valueOfTok(code, "==");
ASSERT_EQUALS(true, value.isKnown());
ASSERT_EQUALS(1, value.intvalue);
code = "bool f() {\n"
" int* p = {};\n"
" return p == nullptr;\n" // <- known value
"}";
value = valueOfTok(code, "==");
ASSERT_EQUALS(true, value.isKnown());
ASSERT_EQUALS(1, value.intvalue);
code = "bool f() {\n"
" int i = {};\n"
" return i == 0;\n" // <- known value
"}";
value = valueOfTok(code, "==");
ASSERT_EQUALS(true, value.isKnown());
ASSERT_EQUALS(1, value.intvalue);
code = "bool f() {\n"
" int* p = { 0 };\n"
" return p == nullptr;\n" // <- known value
"}";
value = valueOfTok(code, "==");
ASSERT_EQUALS(true, value.isKnown());
ASSERT_EQUALS(1, value.intvalue);
code = "bool f() {\n"
" int i = { 1 };\n"
" return i == 1;\n" // <- known value
"}";
value = valueOfTok(code, "==");
ASSERT_EQUALS(true, value.isKnown());
ASSERT_EQUALS(1, value.intvalue);
// calculation with known result
code = "int f(int x) { a = x & 0; }"; // <- & is 0
value = valueOfTok(code, "&");
ASSERT_EQUALS(0, value.intvalue);
ASSERT(value.isKnown());
// template parameters are not known
code = "template <int X> void f() { a = X; }\n"
"f<1>();";
value = valueOfTok(code, "1");
ASSERT_EQUALS(1, value.intvalue);
ASSERT_EQUALS(false, value.isKnown());
code = "void f(char c, struct T* t) {\n" // #11894
" (*t->func)(&c, 1, t->ptr);\n"
"}\n";
value = valueOfTok(code, ", 1");
ASSERT_EQUALS(0, value.intvalue);
ASSERT_EQUALS(false, value.isKnown());
}
void valueFlowSizeofForwardDeclaredEnum() {
const char *code = "enum E; sz=sizeof(E);";
(void)valueOfTok(code, "="); // Don't crash (#7775)
}
void valueFlowGlobalVar() {
const char *code;
code = "int x;\n"
"void f() {\n"
" x = 4;\n"
" a = x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 4));
code = "int x;\n"
"void f() {\n"
" if (x == 4) {}\n"
" a = x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 4));
code = "int x;\n"
"void f() {\n"
" x = 42;\n"
" unknownFunction();\n"
" a = x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 5U, 42));
}
void valueFlowGlobalConstVar() {
const char* code;
code = "const int x = 321;\n"
"void f() {\n"
" a = x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 321));
code = "void f(const int x = 1) {\n"
" int a = x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXKnown(code, 2U, 1));
code = "volatile const int x = 42;\n"
"void f(){ int a = x; }\n";
ASSERT_EQUALS(false, testValueOfXKnown(code, 2U, 42));
code = "static const int x = 42;\n"
"void f(){ int a = x; }\n";
ASSERT_EQUALS(true, testValueOfX(code, 2U, 42));
}
void valueFlowGlobalStaticVar() {
const char *code;
code = "static int x = 321;\n"
"void f() {\n"
" a = x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 321));
code = "static int x = 321;\n"
"void f() {\n"
" a = x;\n"
"}"
"void other() { x=a; }\n";
ASSERT_EQUALS(false, testValueOfX(code, 3U, 321));
code = "static int x = 321;\n"
"void f() {\n"
" a = x;\n"
"}"
"void other() { p = &x; }\n";
ASSERT_EQUALS(false, testValueOfX(code, 3U, 321));
code = "static int x = 321;\n"
"void f() {\n"
" a = x;\n"
"}"
"void other() { x++; }\n";
ASSERT_EQUALS(false, testValueOfX(code, 3U, 321));
code = "static int x = 321;\n"
"void f() {\n"
" a = x;\n"
"}"
"void other() { foo(x); }\n";
ASSERT_EQUALS(false, testValueOfX(code, 3U, 321));
code = "static int x = 1;\n" // compound assignment
"void f() {\n"
" a = x;\n"
"}"
"void other() { x += b; }\n";
ASSERT_EQUALS(false, testValueOfX(code, 3U, 1));
}
void valueFlowInlineAssembly() {
const char* code = "void f() {\n"
" int x = 42;\n"
" asm(\"\");\n"
" a = x;\n"
"}";
ASSERT_EQUALS(false, testValueOfX(code, 5U, 42));
}
void valueFlowSameExpression() {
const char* code;
code = "void f(int a) {\n"
" bool x = a == a;\n"
" bool b = x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 1));
code = "void f(int a) {\n"
" bool x = a != a;\n"
" bool b = x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 0));
code = "void f(int a) {\n"
" int x = a - a;\n"
" int b = x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 0));
code = "void f(float a) {\n"
" bool x = a == a;\n"
" bool b = x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 3U, 1));
}
void valueFlowUninit() {
const char* code;
std::list<ValueFlow::Value> values;
code = "void f() {\n"
" int x;\n"
" switch (x) {}\n"
"}";
values = tokenValues(code, "x )");
ASSERT_EQUALS(true, values.size()==1U && values.front().isUninitValue());
code = "void f() {\n"
" const C *c;\n"
" if (c->x() == 4) {}\n"
"}";
values = tokenValues(code, "c .");
ASSERT_EQUALS(true, values.size()==1U && values.front().isUninitValue());
code = "void f() {\n"
" C *c;\n"
" if (c->x() == 4) {}\n"
"}";
values = tokenValues(code, "c .");
ASSERT_EQUALS(true, values.size()==1U && values.front().isUninitValue());
code = "void f() {\n"
" int **x;\n"
" y += 10;\n"
" x = dostuff(sizeof(*x)*y);\n"
"}";
ASSERT_EQUALS(0U, tokenValues(code, "x )").size());
// initialization
code = "int foo() {\n"
" int x;\n"
" *((int *)(&x)) = 12;\n"
" a = x + 1;\n"
"}";
values = tokenValues(code, "x +");
ASSERT_EQUALS(true, values.empty());
// ASSERT_EQUALS(1U, values.size());
// ASSERT(values.front().isIntValue());
// ASSERT_EQUALS(12, values.front().intvalue);
code = "struct AB { int a; };\n" // 11767
"void fp(void) {\n"
" struct AB ab;\n"
" *((int*)(&(ab.a))) = 1;\n"
" x = ab.a + 1;\n" // <- not uninitialized
"}\n";
values = tokenValues(code, "ab . a +");
ASSERT_EQUALS(0, values.size());
// ASSERT_EQUALS(1U, values.size());
// ASSERT(values.front().isIntValue());
// ASSERT_EQUALS(1, values.front().intvalue);
// #8036
code = "void foo() {\n"
" int x;\n"
" f(x=3), return x+3;\n"
"}";
values = tokenValues(code, "x +");
ASSERT_EQUALS(true, values.empty());
// ASSERT_EQUALS(1U, values.size());
// ASSERT(values.front().isIntValue());
// ASSERT_EQUALS(3, values.front().intvalue);
// #8195
code = "void foo(std::istream &is) {\n"
" int x;\n"
" if (is >> x) {\n"
" a = x;\n"
" }\n"
"}";
values = tokenValues(code, "x ; }");
ASSERT_EQUALS(true, values.empty());
// return (#8173)
code = "int repeat() {\n"
" const char *n;\n"
" return((n=42) && *n == 'A');\n"
"}";
values = tokenValues(code, "n ==");
values.remove_if(&isNotUninitValue);
ASSERT_EQUALS(true, values.empty());
// #8233
code = "void foo() {\n"
" int x;\n"
" int y = 1;\n"
" if (y>1)\n"
" x = 1;\n"
" else\n"
" x = 1;\n"
" if (x>1) {}\n"
"}";
ASSERT_EQUALS(true, testValueOfXKnown(code, 8U, 1));
// #8348 - noreturn else
code = "int test_input_int(int a, int b) {\n"
" int x;\n"
" if (a == 1)\n"
" x = b;\n"
" else\n"
" abort();\n"
" a = x + 1;\n"
"}\n";
values = tokenValues(code, "x +");
values.remove_if(&isNotUninitValue);
ASSERT_EQUALS(true, values.empty());
// #8494 - overloaded operator &
code = "void f() {\n"
" int x;\n"
" a & x;\n"
"}";
values = tokenValues(code, "x ; }");
ASSERT_EQUALS(true, values.empty());
code = "void b(bool d, bool e) {\n"
" int c;\n"
" if (d)\n"
" c = 0;\n"
" if (e)\n"
" goto;\n"
" c++;\n"
"}\n";
values = tokenValues(code, "c ++ ; }");
ASSERT_EQUALS(true, values.empty());
code = "void b(bool d, bool e) {\n"
" int c;\n"
" if (d)\n"
" c = 0;\n"
" if (e)\n"
" return;\n"
" c++;\n"
"}\n";
values = tokenValues(code, "c ++ ; }");
ASSERT_EQUALS(true, values.empty());
code = "void b(bool d, bool e) {\n"
" int c;\n"
" if (d)\n"
" c = 0;\n"
" if (e)\n"
" exit();\n"
" c++;\n"
"}\n";
values = tokenValues(code, "c ++ ; }");
ASSERT_EQUALS(true, values.empty());
code = "void b(bool d, bool e) {\n"
" int c;\n"
" if (d)\n"
" c = 0;\n"
" else if (e)\n"
" c = 0;\n"
" c++;\n"
"}\n";
values = tokenValues(code, "c ++ ; }");
TODO_ASSERT_EQUALS(true, false, values.size() == 2);
// ASSERT_EQUALS(true, values.front().isUninitValue() || values.back().isUninitValue());
// ASSERT_EQUALS(true, values.front().isPossible() || values.back().isPossible());
// ASSERT_EQUALS(true, values.front().intvalue == 0 || values.back().intvalue == 0);
code = "void b(bool d, bool e) {\n"
" int c;\n"
" if (d)\n"
" c = 0;\n"
" else if (!d)\n"
" c = 0;\n"
" c++;\n"
"}\n";
values = tokenValues(code, "c ++ ; }");
ASSERT_EQUALS(true, values.size() == 1);
// TODO: Value should be known
ASSERT_EQUALS(true, values.back().isPossible());
ASSERT_EQUALS(true, values.back().intvalue == 0);
code = "void f() {\n" // sqlite
" int szHdr;\n"
" idx = (A<0x80) ? (szHdr = 0) : dostuff(A, (int *)&(szHdr));\n"
" d = szHdr;\n" // szHdr can be 0.
"}";
values = tokenValues(code, "szHdr ; }");
TODO_ASSERT_EQUALS(1, 0, values.size());
if (values.size() == 1) {
ASSERT_EQUALS(false, values.front().isUninitValue());
}
code = "void f () {\n"
" int szHdr;\n"
" idx = ((aKey<0x80) ? ((szHdr)=aKey), 1 : sqlite3GetVarint32(&(szHdr)));\n"
" d = szHdr;\n"
"}";
values = tokenValues(code, "szHdr ; }");
ASSERT_EQUALS(0, values.size());
// #9933
code = "struct MyStruct { size_t value; }\n"
"\n"
"void foo() {\n"
" MyStruct x;\n"
" fread(((char *)&x) + 0, sizeof(x), f);\n"
" if (x.value < 432) {}\n"
"}";
values = tokenValues(code, "x . value");
ASSERT_EQUALS(0, values.size());
// #10166
code = "int f(bool b) {\n"
" int x;\n"
" do {\n"
" if (b) {\n"
" x = 0;\n"
" break;\n"
" }\n"
" } while (true);\n"
" return x;\n"
"}\n";
values = tokenValues(code, "x ; }", ValueFlow::Value::ValueType::UNINIT);
ASSERT_EQUALS(0, values.size());
code = "int f(bool b) {\n"
" int x;\n"
" while (true) {\n"
" if (b) {\n"
" x = 0;\n"
" break;\n"
" }\n"
" }\n"
" return x;\n"
"}\n";
values = tokenValues(code, "x ; }", ValueFlow::Value::ValueType::UNINIT);
ASSERT_EQUALS(0, values.size());
code = "int f(bool b) {\n"
" int x;\n"
" for(;;) {\n"
" if (b) {\n"
" x = 0;\n"
" break;\n"
" }\n"
" }\n"
" return x;\n"
"}\n";
values = tokenValues(code, "x ; }", ValueFlow::Value::ValueType::UNINIT);
ASSERT_EQUALS(0, values.size());
code = "int f(bool b) {\n"
" int x;\n"
" switch (b) {\n"
" case 1: {\n"
" ret = 0;\n"
" break;\n"
" }\n"
" }\n"
" return x;\n"
"}\n";
values = tokenValues(code, "x ; }", ValueFlow::Value::ValueType::UNINIT);
ASSERT_EQUALS(1, values.size());
ASSERT_EQUALS(true, values.front().isUninitValue());
code = "void f(int x) {\n"
" int i;\n"
" if (x > 0) {\n"
" int y = -ENOMEM;\n" // assume constant ENOMEM is nonzero since it's negated
" if (y != 0) return;\n"
" i++;\n"
" }\n"
"}\n";
values = tokenValues(code, "i ++", ValueFlow::Value::ValueType::UNINIT);
ASSERT_EQUALS(0, values.size());
// #11688
code = "void f() {\n"
" int n;\n"
" for (int i = 0; i < 4; i = n)\n" // <- n is initialized in the loop body
" n = 10;\n"
"}";
values = tokenValues(code, "n )", ValueFlow::Value::ValueType::UNINIT);
ASSERT_EQUALS(0, values.size());
// #11774 - function call to init data
code = "struct id_struct { int id; };\n"
"int init(const id_struct **id);\n"
"void fp() {\n"
" const id_struct *id_st;\n"
" init(&id_st);\n"
" if (id_st->id > 0) {}\n"
"}\n";
values = tokenValues(code, ". id", ValueFlow::Value::ValueType::UNINIT);
ASSERT_EQUALS(0, values.size());
// #11777 - false || ...
code = "bool init(int *p);\n"
"\n"
"void uninitvar_FP9() {\n"
" int x;\n"
" if (false || init(&x)) {}\n"
" int b = x+1;\n"
"}";
values = tokenValues(code, "x + 1", ValueFlow::Value::ValueType::UNINIT);
ASSERT_EQUALS(0, values.size());
code = "void g() {\n"
" int y;\n"
" int *q = 1 ? &y : 0;\n"
"}\n";
values = tokenValues(code, "y :", ValueFlow::Value::ValueType::UNINIT);
ASSERT_EQUALS(1, values.size());
ASSERT_EQUALS(true, values.front().isUninitValue());
values = tokenValues(code, "& y :", ValueFlow::Value::ValueType::UNINIT);
ASSERT_EQUALS(1, values.size());
ASSERT_EQUALS(true, values.front().isUninitValue());
// #12012 - function init variable
code = "void init(uintptr_t p);\n"
"void fp() {\n"
" int x;\n"
" init((uintptr_t)&x);\n"
" if (x > 0) {}\n"
"}\n";
values = tokenValues(code, "x >", ValueFlow::Value::ValueType::UNINIT);
ASSERT_EQUALS(0, values.size());
// #12031
code = "bool g(int *p);\n"
"bool h();\n"
"void f(bool b, int y) {\n"
" int x;\n"
" if (b && y > 0) {\n"
" b = g(&x);\n"
" }\n"
" while (b && y > 0) {\n"
" if (x < 0) {}\n"
" break;\n"
" }\n"
"}\n";
values = tokenValues(code, "x <", ValueFlow::Value::ValueType::UNINIT);
ASSERT_EQUALS(0, values.size());
code = "bool do_something(int *p);\n"
"int getY();\n"
"bool bar();\n"
"void foo() {\n"
" bool flag{true};\n"
" int x;\n"
" int y = getY();\n"
" if (flag == true) {\n"
" flag = bar();\n"
" }\n"
" if ((flag == true) && y > 0) {\n"
" flag = do_something(&x);\n"
" }\n"
" for (int i = 0; (flag == true) && i < y; i++) {\n"
" if (x < 0) {}\n"
" }\n"
"}\n";
values = tokenValues(code, "x <", ValueFlow::Value::ValueType::UNINIT);
ASSERT_EQUALS(0, values.size());
code = "void getX(int *p);\n"
"bool do_something();\n"
"void foo() {\n"
" int x;\n"
" bool flag;\n"
" bool success;\n"
" success = do_something();\n"
" flag = success;\n"
" if (success == true) {\n"
" getX(&x);\n"
" }\n"
" for (int i = 0; (flag == true) && (i < x); ++i) {}\n"
"}\n";
values = tokenValues(code, "x ) ; ++ i", ValueFlow::Value::ValueType::UNINIT);
ASSERT_EQUALS(0, values.size());
code = "void g(bool *result, size_t *buflen) {\n" // #12091
" if (*result && *buflen >= 5) {}\n" // <- *buflen might not be initialized
"}\n"
"void f() {\n"
" size_t bytesCopied;\n"
" bool copied_all = true;\n"
" g(&copied_all, &bytesCopied);\n"
"}";
values = tokenValues(code, "buflen >=", ValueFlow::Value::ValueType::UNINIT);
ASSERT_EQUALS(1, values.size());
code = "void foo() {\n"
" int counter = 0;\n"
" int x;\n"
" for (int i = 0; i < 5; i++) {\n"
" if (i % 2 == 0) {\n"
" x = i;\n"
" counter++;\n"
" }\n"
" }\n"
" for (int i = 0; i < counter; i++) {\n"
" if(x > 5) {}\n"
" }\n"
"}\n";
values = tokenValues(code, "x > 5", ValueFlow::Value::ValueType::UNINIT);
ASSERT_EQUALS(0, values.size());
}
void valueFlowConditionExpressions() {
const char* code;
std::list<ValueFlow::Value> values;
// opposite condition
code = "void f(int i, int j) {\n"
" if (i == j) return;\n"
" if(i != j) {}\n"
"}\n";
ASSERT_EQUALS(true, valueOfTok(code, "!=").intvalue == 1);
code = "void f(int i, int j) {\n"
" if (i == j) return;\n"
" i++;\n"
" if (i != j) {}\n"
"}\n";
ASSERT_EQUALS(false, valueOfTok(code, "!=").intvalue == 1);
code = "void f(int i, int j, bool a) {\n"
" if (a) {\n"
" if (i == j) return;\n"
" }\n"
" if (i != j) {}\n"
"}\n";
ASSERT_EQUALS(true, valueOfTok(code, "!=").intvalue == 1);
ASSERT_EQUALS(false, valueOfTok(code, "!=").isKnown());
code = "void f(int i, int j, bool a) {\n"
" if (i != j) {}\n"
" if (i == j) return;\n"
"}\n";
ASSERT_EQUALS(false, valueOfTok(code, "!=").intvalue == 1);
// same expression
code = "void f(int i, int j) {\n"
" if (i != j) return;\n"
" bool x = (i != j);\n"
" bool b = x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 4U, 0));
code = "void f(int i, int j) {\n"
" if (i != j) return;\n"
" i++;\n"
" bool x = (i != j);\n"
" bool b = x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXKnown(code, 5U, 0));
code = "void f(int i, int j, bool a) {\n"
" if (a) {\n"
" if (i != j) return;\n"
" }\n"
" bool x = (i != j);\n"
" bool b = x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXKnown(code, 6U, 0));
code = "void f(int i, int j, bool a) {\n"
" bool x = (i != j);\n"
" bool b = x;\n"
" if (i != j) return;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXKnown(code, 3U, 0));
code = "void f(int i, int j, bool b) {\n"
" if (i == j) { if(b) return; }\n"
" if(i != j) {}\n"
"}\n";
ASSERT_EQUALS(false, valueOfTok(code, "!=").intvalue == 1);
code = "void f(bool b, int i, int j) {\n"
" if (b || i == j) return;\n"
" if(i != j) {}\n"
"}\n";
ASSERT_EQUALS(true, valueOfTok(code, "!=").intvalue == 1);
code = "void f(bool b, int i, int j) {\n"
" if (b && i == j) return;\n"
" if(i != j) {}\n"
"}\n";
ASSERT_EQUALS(true, removeImpossible(tokenValues(code, "!=")).empty());
code = "void f(int i, int j) {\n"
" if (i == j) {\n"
" if (i != j) {}\n"
" }\n"
"}\n";
ASSERT_EQUALS(true, valueOfTok(code, "!=").intvalue == 0);
code = "void f(int i, int j) {\n"
" if (i == j) {} else {\n"
" if (i != j) {}\n"
" }\n"
"}\n";
ASSERT_EQUALS(true, valueOfTok(code, "!=").intvalue == 1);
code = "void f(bool b, int i, int j) {\n"
" if (b && i == j) {\n"
" if (i != j) {}\n"
" }\n"
"}\n";
ASSERT_EQUALS(true, valueOfTok(code, "!=").intvalue == 0);
code = "void f(bool b, int i, int j) {\n"
" if (b || i == j) {\n"
" if (i != j) {}\n"
" }\n"
"}\n";
values = removeImpossible(tokenValues(code, "!="));
ASSERT_EQUALS(1, values.size());
ASSERT_EQUALS(0, values.front().intvalue);
ASSERT_EQUALS(true, values.front().isIntValue());
ASSERT_EQUALS(true, values.front().isPossible());
code = "void f(bool b, int i, int j) {\n"
" if (b || i == j) {} else {\n"
" if (i != j) {}\n"
" }\n"
"}\n";
ASSERT_EQUALS(true, valueOfTok(code, "!=").intvalue == 1);
code = "void f(bool b, int i, int j) {\n"
" if (b && i == j) {} else {\n"
" if (i != j) {}\n"
" }\n"
"}\n";
ASSERT_EQUALS(true, removeImpossible(tokenValues(code, "!=")).empty());
code = "void foo()\n" // #8924
"{\n"
" if ( this->FileIndex >= 0 )\n"
" return;\n"
"\n"
" this->FileIndex = 1 ;\n"
" if ( this->FileIndex < 0 ) {}\n"
"}";
ASSERT_EQUALS(false, valueOfTok(code, "<").intvalue == 1);
code = "int f(int p) {\n"
" int v = 0;\n"
" for (int i = 0; i < 1; ++i) {\n"
" if (p == 0)\n"
" v = 1;\n"
" if (v == 1)\n"
" break;\n"
" }\n"
" int x = v;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXKnown(code, 10U, 0));
ASSERT_EQUALS(false, testValueOfXKnown(code, 10U, 1));
code = "void f() {\n"
" const int size = arrayInfo.num(0);\n"
" if (size <= 0)\n"
" return;\n"
" for (;;)\n"
" if (size > 0) {}\n"
"}\n";
ASSERT_EQUALS(true, valueOfTok(code, "> 0").isKnown());
ASSERT_EQUALS(true, valueOfTok(code, "> 0").intvalue == 1);
// FP #10110
code = "enum FENUMS { NONE = 0, CB = 8 };\n"
"bool calc(int x) {\n"
" if (!x) {\n"
" return false;\n"
" }\n"
"\n"
" if (x & CB) {\n"
" return true;\n"
" }\n"
" return false;\n"
"}\n";
ASSERT_EQUALS(false, valueOfTok(code, "& CB").isKnown());
ASSERT_EQUALS(true, testValueOfXImpossible(code, 7U, 0));
code = "enum FENUMS { NONE = 0, CB = 8 };\n"
"bool calc(int x) {\n"
" if (x) {\n"
" return false;\n"
" }\n"
"\n"
" if ((!x) & CB) {\n"
" return true;\n"
" }\n"
" return false;\n"
"}\n";
ASSERT_EQUALS(true, valueOfTok(code, "& CB").isKnown());
ASSERT_EQUALS(true, testValueOfXKnown(code, 7U, 0));
code = "enum FENUMS { NONE = 0, CB = 8 };\n"
"bool calc(int x) {\n"
" if (!!x) {\n"
" return false;\n"
" }\n"
"\n"
" if (x & CB) {\n"
" return true;\n"
" }\n"
" return false;\n"
"}\n";
ASSERT_EQUALS(true, valueOfTok(code, "& CB").isKnown());
ASSERT_EQUALS(true, testValueOfXKnown(code, 7U, 0));
code = "bool calc(bool x) {\n"
" if (!x) {\n"
" return false;\n"
" }\n"
"\n"
" if (x) {\n"
" return true;\n"
" }\n"
" return false;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 6U, 1));
code = "bool calc(bool x) {\n"
" if (x) {\n"
" return false;\n"
" }\n"
"\n"
" if (!x) {\n"
" return true;\n"
" }\n"
" return false;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 6U, 0));
}
static std::string isPossibleContainerSizeValue(std::list<ValueFlow::Value> values,
MathLib::bigint i,
bool unique = true) {
values.remove_if(std::mem_fn(&ValueFlow::Value::isSymbolicValue));
values.remove_if(std::mem_fn(&ValueFlow::Value::isTokValue));
if (!unique)
values.remove_if(&isNotPossible);
if (values.size() != 1)
return "values.size():" + std::to_string(values.size());
if (!values.front().isContainerSizeValue())
return "ContainerSizeValue";
if (!values.front().isPossible())
return "Possible";
if (values.front().intvalue != i)
return "intvalue:" + std::to_string(values.front().intvalue);
return "";
}
static std::string isImpossibleContainerSizeValue(std::list<ValueFlow::Value> values,
MathLib::bigint i,
bool unique = true) {
values.remove_if(std::mem_fn(&ValueFlow::Value::isSymbolicValue));
values.remove_if(std::mem_fn(&ValueFlow::Value::isTokValue));
if (!unique)
values.remove_if(&isNotImpossible);
if (values.size() != 1)
return "values.size():" + std::to_string(values.size());
if (!values.front().isContainerSizeValue())
return "ContainerSizeValue";
if (!values.front().isImpossible())
return "Impossible";
if (values.front().intvalue != i)
return "intvalue:" + std::to_string(values.front().intvalue);
return "";
}
static std::string isInconclusiveContainerSizeValue(std::list<ValueFlow::Value> values,
MathLib::bigint i,
bool unique = true) {
values.remove_if(std::mem_fn(&ValueFlow::Value::isSymbolicValue));
values.remove_if(std::mem_fn(&ValueFlow::Value::isTokValue));
if (!unique)
values.remove_if(&isNotInconclusive);
if (values.size() != 1)
return "values.size():" + std::to_string(values.size());
if (!values.front().isContainerSizeValue())
return "ContainerSizeValue";
if (!values.front().isInconclusive())
return "Inconclusive";
if (values.front().intvalue != i)
return "intvalue:" + std::to_string(values.front().intvalue);
return "";
}
static std::string isKnownContainerSizeValue(std::list<ValueFlow::Value> values, MathLib::bigint i, bool unique = true) {
values.remove_if(std::mem_fn(&ValueFlow::Value::isSymbolicValue));
values.remove_if(std::mem_fn(&ValueFlow::Value::isTokValue));
if (!unique)
values.remove_if(&isNotKnown);
if (values.size() != 1)
return "values.size():" + std::to_string(values.size());
if (!values.front().isContainerSizeValue())
return "ContainerSizeValue";
if (!values.front().isKnown())
return "Known";
if (values.front().intvalue != i)
return "intvalue:" + std::to_string(values.front().intvalue);
return "";
}
void valueFlowContainerSize() {
const char *code;
// condition
code = "void f(const std::list<int> &ints) {\n"
" if (!static_cast<bool>(ints.empty()))\n"
" ints.front();\n"
"}";
ASSERT_EQUALS("", isImpossibleContainerSizeValue(tokenValues(code, "ints . front"), 0));
// valueFlowContainerReverse
code = "void f(const std::list<int> &ints) {\n"
" ints.front();\n" // <- container can be empty
" if (ints.empty()) {}\n"
"}";
ASSERT_EQUALS("", isPossibleContainerSizeValue(tokenValues(code, "ints . front"), 0));
code = "void f(const std::list<int> &ints) {\n"
" ints.front();\n" // <- container can be empty
" if (ints.size()==0) {}\n"
"}";
ASSERT_EQUALS("", isPossibleContainerSizeValue(tokenValues(code, "ints . front"), 0));
code = "void f(std::list<int> ints) {\n"
" ints.front();\n" // <- no container size
" ints.pop_back();\n"
" if (ints.empty()) {}\n"
"}";
ASSERT_EQUALS("", isPossibleContainerSizeValue(tokenValues(code, "ints . front"), 1));
code = "void f(std::vector<int> v) {\n"
" v[10] = 0;\n" // <- container size can be 10
" if (v.size() == 10) {}\n"
"}";
ASSERT_EQUALS("", isPossibleContainerSizeValue(tokenValues(code, "v ["), 10));
code = "void f(std::vector<std::string> params) {\n"
" switch(x) {\n"
" case CMD_RESPONSE:\n"
" if(y) { break; }\n"
" params[2];\n" // <- container use
" break;\n"
" case CMD_DELETE:\n"
" if (params.size() < 2) { }\n" // <- condition
" break;\n"
" }\n"
"}";
ASSERT(tokenValues(code, "params [ 2 ]").empty());
// valueFlowAfterCondition
code = "void f(const std::vector<std::string>& v) {\n"
" if(v.empty()) {\n"
" v.front();\n"
" }\n"
"}\n";
ASSERT_EQUALS("", isKnownContainerSizeValue(tokenValues(code, "v . front"), 0));
code = "void f(const std::vector<std::string>& v) {\n"
" if(std::empty(v)) {\n"
" v.front();\n"
" }\n"
"}\n";
ASSERT_EQUALS("", isKnownContainerSizeValue(tokenValues(code, "v . front"), 0));
code = "void f(const std::vector<std::string>& v) {\n"
" if(!v.empty()) {\n"
" v.front();\n"
" }\n"
"}\n";
ASSERT_EQUALS("", isImpossibleContainerSizeValue(tokenValues(code, "v . front"), 0));
code = "void f(const std::vector<std::string>& v) {\n"
" if(!v.empty() && v[0] != \"\") {\n"
" v.front();\n"
" }\n"
"}\n";
ASSERT_EQUALS("", isImpossibleContainerSizeValue(tokenValues(code, "v . front"), 0));
// valueFlowContainerForward
code = "void f(const std::list<int> &ints) {\n"
" if (ints.empty()) {}\n"
" ints.front();\n" // <- container can be empty
"}";
ASSERT_EQUALS("", isPossibleContainerSizeValue(tokenValues(code, "ints . front"), 0));
code = "void f(const std::list<int> &ints) {\n"
" if (ints.empty()) { continue; }\n"
" ints.front();\n" // <- no container size
"}";
ASSERT_EQUALS("", isImpossibleContainerSizeValue(tokenValues(code, "ints . front"), 0));
code = "void f(const std::list<int> &ints) {\n"
" if (ints.empty()) { ints.push_back(0); }\n"
" ints.front();\n" // <- container is not empty
"}";
ASSERT(tokenValues(code, "ints . front").empty());
code = "void f(const std::list<int> &ints) {\n"
" if (ints.empty()) {\n"
" ints.front();\n" // <- container is empty
" }\n"
"}";
ASSERT_EQUALS("", isKnownContainerSizeValue(tokenValues(code, "ints . front"), 0));
code = "void f(const std::list<int> &ints) {\n"
" if (ints.size() == 3) {\n"
" ints.front();\n" // <- container size is 3
" }\n"
"}";
ASSERT_EQUALS("", isKnownContainerSizeValue(tokenValues(code, "ints . front"), 3));
code = "void f(const std::list<int> &ints) {\n"
" if (ints.size() <= 3) {\n"
" ints.front();\n" // <- container size is 3
" }\n"
"}";
ASSERT_EQUALS("", isPossibleContainerSizeValue(tokenValues(code, "ints . front"), 3, false));
ASSERT_EQUALS("", isImpossibleContainerSizeValue(tokenValues(code, "ints . front"), 4, false));
code = "void f(const std::list<int> &ints) {\n"
" if (ints.size() >= 3) {\n"
" ints.front();\n" // <- container size is 3
" }\n"
"}";
ASSERT_EQUALS("", isPossibleContainerSizeValue(tokenValues(code, "ints . front"), 3, false));
ASSERT_EQUALS("", isImpossibleContainerSizeValue(tokenValues(code, "ints . front"), 2, false));
code = "void f(const std::list<int> &ints) {\n"
" if (ints.size() < 3) {\n"
" ints.front();\n" // <- container size is 2
" }\n"
"}";
ASSERT_EQUALS("", isPossibleContainerSizeValue(tokenValues(code, "ints . front"), 2, false));
ASSERT_EQUALS("", isImpossibleContainerSizeValue(tokenValues(code, "ints . front"), 3, false));
code = "void f(const std::list<int> &ints) {\n"
" if (ints.size() > 3) {\n"
" ints.front();\n" // <- container size is 4
" }\n"
"}";
ASSERT_EQUALS("", isPossibleContainerSizeValue(tokenValues(code, "ints . front"), 4, false));
ASSERT_EQUALS("", isImpossibleContainerSizeValue(tokenValues(code, "ints . front"), 3, false));
code = "void f(const std::list<int> &ints) {\n"
" if (ints.empty() == false) {\n"
" ints.front();\n" // <- container is not empty
" }\n"
"}";
ASSERT(tokenValues(code, "ints . front").empty());
code = "void f(const std::vector<int> &v) {\n"
" if (v.empty()) {}\n"
" if (!v.empty() && v[10]==0) {}\n" // <- no container size for 'v[10]'
"}";
ASSERT(removeImpossible(tokenValues(code, "v [")).empty());
code = "void f() {\n"
" std::list<int> ints;\n" // No value => ints is empty
" ints.front();\n"
"}";
ASSERT_EQUALS("", isKnownContainerSizeValue(tokenValues(code, "ints . front"), 0));
code = "void f() {\n"
" std::array<int,10> ints;\n" // Array size is 10
" ints.front();\n"
"}";
ASSERT_EQUALS("values.size():2", isKnownContainerSizeValue(tokenValues(code, "ints . front"), 10)); // uninit value
code = "void f() {\n"
" std::string s;\n"
" cin >> s;\n"
" s[0];\n"
"}";
ASSERT(tokenValues(code, "s [").empty());
code = "void f() {\n"
" std::string s = \"abc\";\n" // size of s is 3
" s.size();\n"
"}";
ASSERT_EQUALS("", isKnownContainerSizeValue(tokenValues(code, "s . size"), 3));
code = "void f(const char* p) {\n"
" if (p == nullptr) return;\n"
" std::string s { p };\n" // size of s is unknown
" s.front();\n"
"}";
ASSERT(removeSymbolicTok(tokenValues(code, "s . front")).empty());
code = "void f() {\n"
" std::string s = { 'a', 'b', 'c' };\n" // size of s is 3
" s.size();\n"
"}";
ASSERT_EQUALS("", isKnownContainerSizeValue(tokenValues(code, "s . size"), 3));
code = "void f() {\n"
" std::string s=\"abc\";\n" // size of s is 3
" s += unknown;\n"
" s.size();\n"
"}";
ASSERT(tokenValues(code, "s . size").empty());
code = "void f() {\n"
" std::string s=\"abc\";\n" // size of s is 3
" s += \"def\";\n" // size of s => 6
" s.size();\n"
"}";
ASSERT_EQUALS("", isKnownContainerSizeValue(tokenValues(code, "s . size"), 6));
code = "void f(std::string s) {\n"
" if (s == \"hello\")\n"
" s[40] = c;\n"
"}";
ASSERT_EQUALS("", isKnownContainerSizeValue(tokenValues(code, "s ["), 5));
code = "void f(std::string s) {\n"
" s[40] = c;\n"
" if (s == \"hello\") {}\n"
"}";
ASSERT_EQUALS("", isPossibleContainerSizeValue(tokenValues(code, "s ["), 5));
code = "void f(std::string s) {\n"
" if (s != \"hello\") {}\n"
" s[40] = c;\n"
"}";
ASSERT_EQUALS("", isPossibleContainerSizeValue(tokenValues(code, "s ["), 5));
code = "void f(std::string s) {\n"
" if (s != \"hello\")\n"
" s[40] = c;\n"
"}";
ASSERT(!isImpossibleContainerSizeValue(tokenValues(code, "s ["), 5).empty());
code = "void f() {\n"
" static std::string s;\n"
" if (s.size() == 0)\n"
" s = x;\n"
"}";
ASSERT(tokenValues(code, "s . size").empty());
code = "void f() {\n"
" const uint8_t data[] = { 1, 2, 3 };\n"
" std::vector<uint8_t> v{ data, data + sizeof(data) };\n"
" v.size();\n"
"}";
ASSERT_EQUALS("", isKnownContainerSizeValue(tokenValues(code, "v . size"), 3, false));
// valueFlowContainerForward, loop
code = "void f() {\n"
" std::stack<Token *> links;\n"
" while (!links.empty() || indentlevel)\n"
" links.push(tok);\n"
"}";
ASSERT_EQUALS("", isPossibleContainerSizeValue(tokenValues(code, "links . empty"), 0));
// valueFlowContainerForward, function call
code = "void f() {\n"
" std::list<int> x;\n"
" f(x);\n"
" x.front();\n" // <- unknown container size
"}";
ASSERT(tokenValues(code, "x . front").empty());
code = "void f() {\n" // #8689
" std::list<int> x;\n"
" f<ns::a>(x);\n"
" x.front();\n" // <- unknown container size
"}";
ASSERT(tokenValues(code, "x . front").empty());
code = "void g(std::list<int>&);\n"
"void f() {\n"
" std::list<int> x;\n"
" g(x);\n"
" x.front();\n"
"}";
ASSERT(tokenValues(code, "x . front").empty());
code = "void g(std::list<int>*);\n"
"void f() {\n"
" std::list<int> x;\n"
" g(&x);\n"
" x.front();\n"
"}";
ASSERT(tokenValues(code, "x . front").empty());
code = "void g(std::list<int>* const);\n" // #9434
"void f() {\n"
" std::list<int> x;\n"
" g(&x);\n"
" x.front();\n"
"}";
ASSERT(tokenValues(code, "x . front").empty());
code = "void g(const std::list<int>&);\n"
"void f() {\n"
" std::list<int> x;\n"
" g(x);\n"
" x.front();\n"
"}";
ASSERT_EQUALS("", isKnownContainerSizeValue(tokenValues(code, "x . front"), 0));
code = "void g(std::list<int>);\n"
"void f() {\n"
" std::list<int> x;\n"
" g(x);\n"
" x.front();\n"
"}";
ASSERT_EQUALS("", isKnownContainerSizeValue(tokenValues(code, "x . front"), 0));
code = "void g(int&);\n"
"void f() {\n"
" std::list<int> x;\n"
" g(x[0]);\n"
" x.front();\n"
"}";
ASSERT_EQUALS("", isKnownContainerSizeValue(tokenValues(code, "x . front"), 0));
code = "void g(int&);\n"
"void f() {\n"
" std::list<int> x;\n"
" g(x.back());\n"
" x.front();\n"
"}";
ASSERT_EQUALS("", isKnownContainerSizeValue(tokenValues(code, "x . front"), 0));
code = "void g(std::list<int>&) {}\n"
"void f() {\n"
" std::list<int> x;\n"
" g(x);\n"
" x.front();\n"
"}";
ASSERT_EQUALS("", isKnownContainerSizeValue(tokenValues(code, "x . front"), 0));
code = "void g(std::list<int>& y) { y.push_back(1); }\n"
"void f() {\n"
" std::list<int> x;\n"
" g(x);\n"
" x.front();\n"
"}";
ASSERT(tokenValues(code, "x . front").empty());
code = "void g(std::list<int>*) {}\n"
"void f() {\n"
" std::list<int> x;\n"
" g(&x);\n"
" x.front();\n"
"}";
ASSERT_EQUALS("", isKnownContainerSizeValue(tokenValues(code, "x . front"), 0));
code = "void g(std::list<int>* y) { y->push_back(1); }\n"
"void f() {\n"
" std::list<int> x;\n"
" g(&x);\n"
" x.front();\n"
"}";
ASSERT(tokenValues(code, "x . front").empty());
code = "void h(std::list<int>&);\n"
"void g(std::list<int>& y) { h(y); }\n"
"void f() {\n"
" std::list<int> x;\n"
" g(x);\n"
" x.front();\n"
"}";
ASSERT(tokenValues(code, "x . front").empty());
code = "void h(const std::list<int>&);\n"
"void g(std::list<int>& y) { h(y); }\n"
"void f() {\n"
" std::list<int> x;\n"
" g(x);\n"
" x.front();\n"
"}";
ASSERT_EQUALS("", isKnownContainerSizeValue(tokenValues(code, "x . front"), 0));
code = "void h(const std::list<int>&);\n"
"void g(std::list<int>& y) { h(y); y.push_back(1); }\n"
"void f() {\n"
" std::list<int> x;\n"
" g(x);\n"
" x.front();\n"
"}";
ASSERT(tokenValues(code, "x . front").empty());
code = "void f(std::vector<int> ints) {\n" // #8697
" if (ints.empty())\n"
" abort() << 123;\n"
" ints[0] = 0;\n"
"}";
ASSERT_EQUALS("", isImpossibleContainerSizeValue(tokenValues(code, "ints ["), 0));
code = "struct A {\n" // forward, nested function call, #9424
" double getMessage( std::vector<unsigned char> *message );\n"
"};\n"
"\n"
"struct B {\n"
" A *a;\n"
" double getMessage( std::vector<unsigned char> *message ) { return a->getMessage( message ); }\n"
"};\n"
"\n"
"void foo(B *ptr) {\n"
" std::vector<unsigned char> v;\n"
" ptr->getMessage (&v);\n"
" if (v.size () > 0) {}\n" // <- v has unknown size!
"}";
ASSERT_EQUALS(0U, tokenValues(code, "v . size ( )").size());
// if
code = "bool f(std::vector<int>&) {\n" // #9532
" return false;\n"
"}\n"
"int g() {\n"
" std::vector<int> v;\n"
" if (f(v) || v.empty())\n"
" return 0;\n"
" return v[0];\n"
"}\n";
ASSERT_EQUALS("", isImpossibleContainerSizeValue(tokenValues(code, "v [ 0 ]"), 0));
// container size => yields
code = "void f() {\n"
" std::string s = \"abcd\";\n"
" s.size();\n"
"}";
ASSERT_EQUALS(4, tokenValues(code, "( ) ;").front().intvalue);
code = "void f() {\n"
" std::string s;\n"
" s.empty();\n"
"}";
ASSERT_EQUALS(1, tokenValues(code, "( ) ;").front().intvalue);
// Calculations
code = "void f() {\n"
" std::string s = \"abcd\";\n"
" x = s + s;\n"
"}";
ASSERT_EQUALS("", isKnownContainerSizeValue(tokenValues(code, "+"), 8));
code = "void f(const std::vector<int> &ints) {\n"
" ints.clear();\n"
" ints.front();\n"
"}";
ASSERT_EQUALS("", isKnownContainerSizeValue(tokenValues(code, "ints . front", ValueFlow::Value::ValueType::CONTAINER_SIZE), 0));
code = "void f(const std::vector<int> &ints) {\n"
" ints.resize(3);\n"
" ints.front();\n"
"}";
ASSERT_EQUALS("", isKnownContainerSizeValue(tokenValues(code, "ints . front", ValueFlow::Value::ValueType::CONTAINER_SIZE), 3));
code = "void f(const std::vector<int> &ints) {\n"
" ints.resize(3);\n"
" ints.push_back(3);\n"
" ints.front();\n"
"}";
ASSERT_EQUALS("", isKnownContainerSizeValue(tokenValues(code, "ints . front", ValueFlow::Value::ValueType::CONTAINER_SIZE), 4));
code = "void f(const std::vector<int> &ints) {\n"
" ints.resize(3);\n"
" ints.pop_back();\n"
" ints.front();\n"
"}";
ASSERT_EQUALS("", isKnownContainerSizeValue(tokenValues(code, "ints . front", ValueFlow::Value::ValueType::CONTAINER_SIZE), 2));
code = "int f(bool b) {\n"
" std::map<int, int> m;\n"
" if (b)\n"
" m[0] = 1;\n"
" return m.at(0);\n"
"}\n";
ASSERT_EQUALS("", isPossibleContainerSizeValue(tokenValues(code, "m . at", ValueFlow::Value::ValueType::CONTAINER_SIZE), 0));
code = "struct Base {\n"
" virtual bool GetString(std::string &) const { return false; }\n"
"};\n"
"int f() {\n"
" std::string str;\n"
" Base *b = GetClass();\n"
" if (!b->GetString(str)) {\n"
" return -2;\n"
" }\n"
" else {\n"
" return str.front();\n"
" }\n"
"}\n";
ASSERT_EQUALS(0U, tokenValues(code, "str . front").size());
code = "void f() {\n"
" std::vector<int> ints{};\n"
" ints.front();\n"
"}";
ASSERT_EQUALS("",
isKnownContainerSizeValue(tokenValues(code, "ints . front", ValueFlow::Value::ValueType::CONTAINER_SIZE), 0));
code = "void f() {\n"
" std::vector<int> ints{};\n"
" ints.front();\n"
"}";
ASSERT_EQUALS("",
isKnownContainerSizeValue(tokenValues(code, "ints . front", ValueFlow::Value::ValueType::CONTAINER_SIZE), 0));
code = "void f() {\n"
" std::vector<int> ints{1};\n"
" ints.front();\n"
"}";
ASSERT_EQUALS("",
isKnownContainerSizeValue(tokenValues(code, "ints . front", ValueFlow::Value::ValueType::CONTAINER_SIZE), 1));
code = "void f() {\n"
" std::vector<int> ints{1};\n"
" std::vector<int> ints2{ints.begin(), ints.end()};\n"
" ints2.front();\n"
"}";
ASSERT_EQUALS(
"", isKnownContainerSizeValue(tokenValues(code, "ints2 . front", ValueFlow::Value::ValueType::CONTAINER_SIZE), 1));
code = "void f() {\n"
" std::vector<int> ints = {};\n"
" ints.front();\n"
"}";
ASSERT_EQUALS("",
isKnownContainerSizeValue(tokenValues(code, "ints . front", ValueFlow::Value::ValueType::CONTAINER_SIZE), 0));
code = "void f(std::string str) {\n"
" if (str == \"123\")\n"
" bool x = str.empty();\n"
"}\n";
ASSERT_EQUALS("",
isKnownContainerSizeValue(tokenValues(code, "str . empty", ValueFlow::Value::ValueType::CONTAINER_SIZE), 3));
code = "int f() {\n"
" std::array<int, 10> a = {};\n"
" return a.front();\n"
"}\n";
ASSERT_EQUALS("",
isKnownContainerSizeValue(tokenValues(code, "a . front", ValueFlow::Value::ValueType::CONTAINER_SIZE), 10));
code = "int f(const std::vector<int>& x) {\n"
" if (!x.empty() && x[0] == 0)\n"
" return 2;\n"
" return x.front();\n"
"}\n";
ASSERT_EQUALS("",
isPossibleContainerSizeValue(tokenValues(code, "x . front", ValueFlow::Value::ValueType::CONTAINER_SIZE), 0));
code = "int f(const std::vector<int>& x) {\n"
" if (!(x.empty() || x[0] != 0))\n"
" return 2;\n"
" return x.front();\n"
"}\n";
ASSERT_EQUALS("",
isPossibleContainerSizeValue(tokenValues(code, "x . front", ValueFlow::Value::ValueType::CONTAINER_SIZE), 0));
code = "int f() {\n"
" const size_t len = 6;\n"
" std::vector<char> v;\n"
" v.resize(1 + len);\n"
" return v.front();\n"
"}\n";
ASSERT_EQUALS(
"",
isKnownContainerSizeValue(tokenValues(code, "v . front", ValueFlow::Value::ValueType::CONTAINER_SIZE), 7));
code = "void f(std::string str) {\n"
" if (str == \"123\") {\n"
" bool x = (str == \"\");\n"
" bool a = x;\n"
" }\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 4U, 0));
code = "void f(std::string str) {\n"
" if (str == \"123\") {\n"
" bool x = (str != \"\");\n"
" bool a = x;\n"
" }\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 4U, 1));
code = "void f(std::string str) {\n"
" if (str == \"123\") {\n"
" bool x = (str == \"321\");\n"
" bool a = x;\n"
" }\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXKnown(code, 4U, 1));
code = "void f(std::string str) {\n"
" if (str == \"123\") {\n"
" bool x = (str != \"321\");\n"
" bool a = x;\n"
" }\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXKnown(code, 4U, 0));
code = "void f(std::string str) {\n"
" if (str.size() == 1) {\n"
" bool x = (str == \"123\");\n"
" bool a = x;\n"
" }\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 4U, 0));
code = "bool f(std::string s) {\n"
" if (!s.empty()) {\n"
" bool x = s == \"0\";\n"
" return x;\n"
" }\n"
" return false;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXKnown(code, 4U, 0));
ASSERT_EQUALS(false, testValueOfXKnown(code, 4U, 1));
ASSERT_EQUALS(false, testValueOfXImpossible(code, 4U, 0));
code = "void f() {\n"
" std::vector<int> v;\n"
" int x = v.size();\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 4U, 0));
code = "void f() {\n"
" std::vector<int> v;\n"
" int x = v.empty();\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 4U, 1));
code = "void f() {\n"
" std::vector<int> v;\n"
" int x = std::size(v);\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 4U, 0));
code = "void f() {\n"
" std::vector<int> v;\n"
" int x = std::empty(v);\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 4U, 1));
code = "bool f() {\n"
" std::list<int> x1;\n"
" std::list<int> x2;\n"
" for (int i = 0; i < 10; ++i) {\n"
" std::list<int>& x = (i < 5) ? x1 : x2;\n"
" x.push_back(i);\n"
" }\n"
" return x1.empty() || x2.empty();\n"
"}\n";
ASSERT_EQUALS("", isInconclusiveContainerSizeValue(tokenValues(code, "x1 . empty", ValueFlow::Value::ValueType::CONTAINER_SIZE), 0));
ASSERT_EQUALS("", isInconclusiveContainerSizeValue(tokenValues(code, "x2 . empty", ValueFlow::Value::ValueType::CONTAINER_SIZE), 0));
code = "std::vector<int> g();\n"
"int f(bool b) {\n"
" std::set<int> a;\n"
" std::vector<int> c = g();\n"
" a.insert(c.begin(), c.end());\n"
" return a.size();\n"
"}\n";
ASSERT_EQUALS(true, tokenValues(code, "a . size", ValueFlow::Value::ValueType::CONTAINER_SIZE).empty());
code = "std::vector<int> g();\n"
"std::vector<int> f() {\n"
" std::vector<int> v = g();\n"
" if (!v.empty()) {\n"
" if (v[0] != 0)\n"
" v.clear();\n"
" }\n"
" if (!v.empty() && v[0] != 0) {}\n"
" return v;\n"
"}\n";
ASSERT_EQUALS(
true,
removeImpossible(tokenValues(code, "v [ 0 ] != 0 ) { }", ValueFlow::Value::ValueType::CONTAINER_SIZE)).empty());
code = "std::vector<int> f() {\n"
" std::vector<int> v;\n"
" v.reserve(1);\n"
" v[1] = 42;\n"
" return v;\n"
"}\n";
ASSERT_EQUALS(
"", isKnownContainerSizeValue(tokenValues(code, "v [", ValueFlow::Value::ValueType::CONTAINER_SIZE), 0));
code = "void f() {\n"
" std::vector<int> v(3);\n"
" v.size();\n"
"}";
ASSERT_EQUALS("", isKnownContainerSizeValue(tokenValues(code, "v . size"), 3));
code = "void f() {\n"
" std::vector<int> v({ 1, 2, 3 });\n"
" v.size();\n"
"}";
ASSERT_EQUALS("", isKnownContainerSizeValue(tokenValues(code, "v . size"), 3));
code = "int f() {\n"
" std::vector<std::vector<int>> v;\n"
" auto it = v.begin();\n"
" auto x = it->size();\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 5U, 0));
code = "std::vector<int> g();\n" // #11417
"int f() {\n"
" std::vector<int> v{ g() };\n"
" auto x = v.size();\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXKnown(code, 5U, 1));
code = "std::vector<int> g();\n"
"int f() {\n"
" std::vector<std::vector<int>> v{ g() };\n"
" auto x = v.size();\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 5U, 1));
// #11548
code = "void f(const std::string& a, const std::string& b) {\n"
" if (a.empty() && b.empty()) {}\n"
" else if (a.empty() == false && b.empty() == false) {}\n"
"}\n";
ASSERT(!isImpossibleContainerSizeValue(tokenValues(code, "a . empty ( ) == false"), 0).empty());
code = "bool g(std::vector<int>& v) {\n"
" v.push_back(1);\n"
" int x = v.empty();\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 4U, 0));
code = "std::vector<int> f() { return std::vector<int>(); }";
ASSERT_EQUALS("", isKnownContainerSizeValue(tokenValues(code, "( ) ;"), 0));
code = "std::vector<int> f() { return std::vector<int>{}; }";
ASSERT_EQUALS("", isKnownContainerSizeValue(tokenValues(code, "{ } ;"), 0));
code = "std::vector<int> f() { return {}; }";
ASSERT_EQUALS("", isKnownContainerSizeValue(tokenValues(code, "{ } ;"), 0));
code = "int f() { auto a = std::array<int, 2>{}; return a[1]; }";
ASSERT_EQUALS("values.size():0", isKnownContainerSizeValue(tokenValues(code, "a ["), 0));
code = "void g(std::vector<int>* w) {\n"
" std::vector<int> &r = *w;\n"
" r.push_back(0);\n"
"}\n"
"int f() {\n"
" std::vector<int> v;\n"
" g(&v);\n"
" return v[0];\n"
"}\n";
ASSERT(!isKnownContainerSizeValue(tokenValues(code, "v ["), 0).empty());
ASSERT(!isPossibleContainerSizeValue(tokenValues(code, "v ["), 0).empty());
code = "template<typename T>\n" // #12052
"std::vector<T> g(T);\n"
"int f() {\n"
" const std::vector<int> v{ g(3) };\n"
" auto x = v.size();\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXKnown(code, 6U, 1));
code = "template<typename T>\n"
"std::vector<T> g(const std::stack<T>& s);\n"
"int f() {\n"
" std::stack<int> s{};\n"
" s.push(42);\n"
" s.push(43);\n"
" const std::vector<int> r{ g(s) };\n"
" auto x = r.size();\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXKnown(code, 9U, 1));
code = "int f() {\n" // #12987
" std::string s{\"0\"};\n"
" auto x = s.size();\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 4U, 1));
code = "int f() {\n"
" std::string s;\n"
" s.append(\"0\");\n"
" auto x = s.size();\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 5U, 1));
code = "int f() {\n"
" std::string s;\n"
" s = std::string(\"0\");\n"
" auto x = s.size();\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 5U, 1));
code = "std::string f() {\n" // #12993
" std::string a[1];\n"
" a->clear();\n"
" return a[0];\n"
"}\n";
ASSERT(!isKnownContainerSizeValue(tokenValues(code, "a [ 0"), 0).empty());
code = "void f(const std::string& a) {\n" // #12994
" std::string b = a + \"123\";\n"
" if (b.empty()) {}\n"
"}";
ASSERT_EQUALS("", isImpossibleContainerSizeValue(tokenValues(code, "b ."), 2));
code = "void f(const std::string& a) {\n"
" std::string b = \"123\" + a;\n"
" if (b.empty()) {}\n"
"}";
ASSERT_EQUALS("", isImpossibleContainerSizeValue(tokenValues(code, "b ."), 2));
code = "void f(const std::string& a, const std::string& b) {\n"
" std::string c = a + b + \"123\";\n"
" if (c.empty()) {}\n"
"}";
ASSERT_EQUALS("", isImpossibleContainerSizeValue(tokenValues(code, "c ."), 2));
code = "void f(const std::string& a) {\n"
" std::string b = a + \"123\" + \"456\";\n"
" if (b.empty()) {}\n"
"}";
ASSERT_EQUALS("", isImpossibleContainerSizeValue(tokenValues(code, "b ."), 5));
code = "void f(const std::string& a) {\n"
" std::string b = \"123\" + a + \"456\";\n"
" if (b.empty()) {}\n"
"}";
ASSERT_EQUALS("", isImpossibleContainerSizeValue(tokenValues(code, "b ."), 5));
code = "void f(const std::string& a, const std::string& b) {\n"
" std::string c = \"123\" + a + b;\n"
" if (c.empty()) {}\n"
"}";
ASSERT_EQUALS("", isImpossibleContainerSizeValue(tokenValues(code, "c ."), 2));
code = "void f(const std::string& a) {\n"
" std::string s;\n"
" s.append(a);\n"
" if (s.empty()) {}\n"
"}";
ASSERT_EQUALS("", isPossibleContainerSizeValue(tokenValues(code, "s . empty"), 0));
code = "int f(const std::string& str) {\n"
" std::istringstream iss(str);\n"
" std::vector<std::string> v{ std::istream_iterator<std::string>(iss), {} };\n"
" auto x = v.size();\n"
" return x;\n"
"}";
ASSERT_EQUALS(false, testValueOfXKnown(code, 5U, 2));
code = "auto f() {\n" // #13450
" auto v = std::vector<std::vector<S*>>(3, std::vector<S*>());\n"
" return v[2];\n"
"}";
ASSERT(isKnownContainerSizeValue(tokenValues(code, "v ["), 3).empty());
}
void valueFlowContainerElement()
{
const char* code;
code = "int f() {\n"
" std::vector<int> v = {1, 2, 3, 4};\n"
" int x = v[1];\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 4U, 2));
code = "int f() {\n"
" std::vector<int> v = {1, 2, 3, 4};\n"
" int x = v.at(1);\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 4U, 2));
code = "int f() {\n"
" std::string s = \"hello\";\n"
" int x = s[1];\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 4U, 'e'));
}
void valueFlowDynamicBufferSize() {
const char *code;
const Settings settingsOld = settings;
settings = settingsBuilder(settings).library("posix.cfg").library("bsd.cfg").build();
code = "void* f() {\n"
" void* x = malloc(10);\n"
" return x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 10, ValueFlow::Value::ValueType::BUFFER_SIZE));
code = "void* f() {\n"
" void* x = calloc(4, 5);\n"
" return x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, 20, ValueFlow::Value::ValueType::BUFFER_SIZE));
code = "void* f() {\n"
" const char* y = \"abcd\";\n"
" const char* x = strdup(y);\n"
" return x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 5, ValueFlow::Value::ValueType::BUFFER_SIZE));
code = "void* f() {\n"
" void* y = malloc(10);\n"
" void* x = realloc(y, 20);\n"
" return x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 20, ValueFlow::Value::ValueType::BUFFER_SIZE));
code = "void* f() {\n"
" void* y = calloc(10, 4);\n"
" void* x = reallocarray(y, 20, 5);\n"
" return x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 100, ValueFlow::Value::ValueType::BUFFER_SIZE));
settings = settingsOld;
}
void valueFlowSafeFunctionParameterValues() {
const char *code;
std::list<ValueFlow::Value> values;
/*const*/ Settings s = settingsBuilder().library("std.cfg").build();
s.safeChecks.classes = s.safeChecks.externalFunctions = s.safeChecks.internalFunctions = true;
code = "short f(short x) {\n"
" return x + 0;\n"
"}";
values = removeSymbolicTok(tokenValues(code, "+", &s));
ASSERT_EQUALS(2, values.size());
ASSERT_EQUALS(-0x8000, values.front().intvalue);
ASSERT_EQUALS(0x7fff, values.back().intvalue);
code = "short f(std::string x) {\n"
" return x[10];\n"
"}";
values = tokenValues(code, "x [", &s);
ASSERT_EQUALS(2, values.size());
ASSERT_EQUALS(0, values.front().intvalue);
ASSERT_EQUALS(1000000, values.back().intvalue);
code = "int f(float x) {\n"
" return x;\n"
"}";
values = tokenValues(code, "x ;", &s);
ASSERT_EQUALS(2, values.size());
ASSERT(values.front().floatValue < -1E20);
ASSERT(values.back().floatValue > 1E20);
code = "short f(__cppcheck_low__(0) __cppcheck_high__(100) short x) {\n"
" return x + 0;\n"
"}";
values = removeSymbolicTok(tokenValues(code, "+", &s));
ASSERT_EQUALS(2, values.size());
ASSERT_EQUALS(0, values.front().intvalue);
ASSERT_EQUALS(100, values.back().intvalue);
code = "unsigned short f(unsigned short x) [[expects: x <= 100]] {\n"
" return x + 0;\n"
"}";
values = removeSymbolicTok(tokenValues(code, "+", &s));
values.remove_if([](const ValueFlow::Value& v) {
return v.isImpossible();
});
ASSERT_EQUALS(2, values.size());
ASSERT_EQUALS(0, values.front().intvalue);
ASSERT_EQUALS(100, values.back().intvalue);
}
void valueFlowUnknownFunctionReturn() {
const char code[] = "template <typename T>\n" // #13409
"struct S {\n"
" std::max_align_t T::* m;\n"
" S(std::max_align_t T::* p) : m(p) {}\n"
"};\n";
(void)valueOfTok(code, ":"); // don't crash
}
void valueFlowUnknownFunctionReturnRand() {
const char *code;
std::list<ValueFlow::Value> values;
/*const*/ Settings s = settingsBuilder().library("std.cfg").build();
s.checkUnknownFunctionReturn.insert("rand");
code = "x = rand();";
values = tokenValues(code, "(", &s);
ASSERT_EQUALS(2, values.size());
ASSERT_EQUALS(INT_MIN, values.front().intvalue);
ASSERT_EQUALS(INT_MAX, values.back().intvalue);
}
void valueFlowUnknownFunctionReturnMalloc() { // #4626
const char *code;
const Settings s = settingsBuilder().library("std.cfg").build();
code = "ptr = malloc(10);";
const auto& values = tokenValues(code, "(", &s);
ASSERT_EQUALS(1, values.size());
ASSERT_EQUALS(true, values.front().isIntValue());
ASSERT_EQUALS(true, values.front().isPossible());
ASSERT_EQUALS(0, values.front().intvalue);
}
void valueFlowPointerAliasDeref() {
const char* code;
code = "int f() {\n"
" int a = 123;\n"
" int *p = &a;\n"
" int x = *p;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 5U, 123));
}
void valueFlowCrashIncompleteCode() {
const char* code;
code = "void SlopeFloor::setAttr(const Value &val) {\n"
" int x = val;\n"
" if (x >= -1)\n"
" state = x;\n"
"}\n";
(void)valueOfTok(code, "=");
code = "void a() {\n"
" auto b = [b = 0] {\n"
" if (b) {\n"
" }\n"
" };\n"
"}\n";
(void)valueOfTok(code, "0");
code = "namespace juce {\n"
"PopupMenu::Item& PopupMenu::Item::operator= (Item&&) = default;\n"
"PopupMenu::Options withDeletionCheck (Component& comp) const {\n"
" Options o (*this);\n"
" o.componentToWatchForDeletion = ∁\n"
" o.isWatchingForDeletion = true;\n"
" return o;\n"
"}}\n";
(void)valueOfTok(code, "return");
code = "class dummy_resource : public instrument_resource {\n"
"public:\n"
" int reads;\n"
" static std::list<int> log;\n"
"};\n"
"void dummy_reader_reset() {\n"
" dummy_resource::log.clear();\n"
"}\n";
(void)valueOfTok(code, "log");
code = "struct D : B<int> {\n"
" D(int i, const std::string& s) : B<int>(i, s) {}\n"
"};\n"
"template<> struct B<int>::S {\n"
" int j;\n"
"};\n";
(void)valueOfTok(code, "B");
}
void valueFlowCrash() {
const char* code;
code = "void f(int x) {\n"
" if (0 * (x > 2)) {}\n"
"}\n";
(void)valueOfTok(code, "x");
code = "struct a {\n"
" void b();\n"
"};\n"
"void d(std::vector<a> c) {\n"
" a *e;\n"
" for (auto &child : c)\n"
" e = &child;\n"
" (*e).b();\n"
"}\n";
(void)valueOfTok(code, "e");
code = "const int& f(int, const int& y = 0);\n"
"const int& f(int, const int& y) {\n"
" return y;\n"
"}\n"
"const int& g(int x) {\n"
" const int& r = f(x);\n"
" return r;\n"
"}\n";
(void)valueOfTok(code, "0");
code = "void fa(int &colors) {\n"
" for (int i = 0; i != 6; ++i) {}\n"
"}\n"
"void fb(not_null<int*> parent, int &&colors2) {\n"
" dostuff(1);\n"
"}\n";
(void)valueOfTok(code, "x");
code = "void a() {\n"
" static int x = 0;\n"
" struct c {\n"
" c(c &&) { ++x; }\n"
" };\n"
"}\n";
(void)valueOfTok(code, "x");
code = "void f(){\n"
" struct dwarf_data **pp;\n"
" for (pp = (struct dwarf_data **) (void *) &state->fileline_data;\n"
" *pp != NULL;\n"
" pp = &(*pp)->next)\n"
" ;\n"
"}\n";
(void)valueOfTok(code, "x");
code = "void *foo(void *x);\n"
"void *foo(void *x)\n"
"{\n"
" if (!x)\n"
"yes:\n"
" return &&yes;\n"
" return x;\n"
"}\n";
(void)valueOfTok(code, "x");
code = "void f() {\n"
" std::string a = b[c->d()];\n"
" if(a.empty()) {\n"
" INFO(std::string{\"a\"} + c->d());\n"
" INFO(std::string{\"b\"} + a);\n"
" }\n"
"}\n";
(void)valueOfTok(code, "a");
code = "class A{\n"
" void f() {\n"
" std::string c{s()};\n"
" }\n"
" std::string s() {\n"
" return \"\";\n"
" }\n"
"};\n";
(void)valueOfTok(code, "c");
code = "void f() {\n"
" char* p = 0;\n"
" int pi =\n"
" p == \"a\" ? 1 : p == \"a\" ? 1 : p == \"a\" ? 1 : p == \"a\" ? 1 : p == \"a\" ? 1 \n"
" : p == \"a\" ? 1 : p == \"a\" ? 1 : p == \"a\" ? 1 : p == \"a\" ? 1 : p == \"a\" ? 1 \n"
" : p == \"a\" ? 1 : p == \"a\" ? 1 : p == \"a\" ? 1 : p == \"a\" ? 1 : p == \"a\" ? 1 \n"
" : p == \"a\" ? 1 : p == \"a\" ? 1 : p == \"a\" ? 1 : p == \"a\" ? 1 : p == \"a\" ? 1 \n"
" : p == \"a\" ? 1 : p == \"a\" ? 1 : p == \"a\" ? 1 : p == \"a\" ? 1 : p == \"a\" ? 1 \n"
" : 0;\n"
" int *i2 = 0;\n"
" if (i2) { }\n"
"}\n";
(void)valueOfTok(code, "p");
code = "struct a;\n"
"namespace e {\n"
"struct f {\n"
" struct g {\n"
" enum {} h;\n"
" int arg;\n"
" };\n"
" std::vector<g> i;\n"
"};\n"
"} // namespace e\n"
"void fn1() {\n"
" std::vector<a *> arguments;\n"
" e::f b;\n"
" for (e::f::g c : b.i)\n"
" if (c.h)\n"
" a *const d = arguments[c.arg];\n"
"}\n";
(void)valueOfTok(code, "c");
code = "void h(char* p, int s) {\n"
" char *q = p+s;\n"
" char buf[100];\n"
" char *b = buf;\n"
" ++b;\n"
" if (p < q && buf < b)\n"
" diff = (buf-b);\n"
"}\n";
(void)valueOfTok(code, "diff");
code = "void foo() {\n" // #10462
" std::tuple<float, float, float, float> t4(5.2f, 3.1f, 2.4f, 9.1f), t5(4, 6, 9, 27);\n"
" t4 = t5;\n"
" ASSERT(!(t4 < t5) && t4 <= t5);\n"
"}";
(void)valueOfTok(code, "<=");
code = "void f() {\n"
" unsigned short Xoff = 10;\n"
" unsigned short Nx = 0;\n"
" int last;\n"
" do {\n"
" last = readData(0);\n"
" if (last && (last - Xoff < Nx))\n"
" Nx = last - Xoff;\n"
" } while (last > 0);\n"
"}\n";
(void)valueOfTok(code, "last");
code = "struct a {\n"
" void clear();\n"
" int b();\n"
"};\n"
"struct d {\n"
" void c(int);\n"
" decltype(auto) f() { c(0 != e.b()); }\n"
" a e;\n"
"};\n"
"void d::c(int) { e.clear(); }\n";
(void)valueOfTok(code, "e");
code = "struct a {\n"
" int b;\n"
" int c;\n"
"} f;\n"
"unsigned g;\n"
"struct {\n"
" a d;\n"
"} e;\n"
"void h() {\n"
" if (g && f.c)\n"
" e.d.b = g - f.c;\n"
"}\n";
(void)valueOfTok(code, "e");
code = "struct a {\n"
" std::vector<a> b;\n"
" void c(unsigned d) {\n"
" size_t e = 0;\n"
" size_t f = 0;\n"
" for (auto child : b) {\n"
" f = e;\n"
" e = d - f;\n"
" }\n"
" }\n"
"};\n";
(void)valueOfTok(code, "e");
code = "struct a {\n"
" struct b {\n"
" std::unique_ptr<a> c;\n"
" };\n"
" void d(int, void *);\n"
" void e() {\n"
" d(0, [f = b{}] { return f.c.get(); }());\n"
" }\n"
" void g() {\n"
" if (b *h = 0)\n"
" h->c.get();\n"
" }\n"
"};\n";
(void)valueOfTok(code, "f.c");
code = "void d(fmpz_t a, fmpz_t b) {\n"
" if (fmpz_sgn(0)) {}\n"
" else if (b) {}\n"
"}\n"
"void e(psl2z_t f) {\n"
" f->b;\n"
" d(&f->a, c);\n"
"}\n";
(void)valueOfTok(code, "f");
code = "struct bo {\n"
" int b, c, a, d;\n"
" char e, g, h, i, aa, j, k, l, m, n, o, p, q, r, t, u, v, w, x, y;\n"
" long z, ab, ac, ad, f, ae, af, ag, ah, ai, aj, ak, al, am, an, ao, ap, aq, ar,\n"
" as;\n"
" short at, au, av, aw, ax, ay, az, ba, bb, bc, bd, be, bf, bg, bh, bi, bj, bk,\n"
" bl, bm;\n"
"};\n"
"char bn;\n"
"void bp() {\n"
" bo s;\n"
" if (bn)\n"
" return;\n"
" s;\n"
"}\n";
(void)valueOfTok(code, "s");
code = "int f(int value) { return 0; }\n"
"std::shared_ptr<Manager> g() {\n"
" static const std::shared_ptr<Manager> x{ new M{} };\n"
" return x;\n"
"}\n";
(void)valueOfTok(code, "x");
code = "int* g();\n"
"void f() {\n"
" std::cout << (void*)(std::shared_ptr<int>{ g() }.get());\n"
"}\n";
(void)valueOfTok(code, ".");
code = "class T;\n"
"struct S {\n"
" void f(std::array<T*, 2>& a);\n"
"};\n";
(void)valueOfTok(code, "a");
code = "void f(const char * const x) { !!system(x); }\n";
(void)valueOfTok(code, "x");
code = "struct struct1 {\n"
" int i1;\n"
" int i2;\n"
"};\n"
"struct struct2 {\n"
" char c1;\n"
" struct1 is1;\n"
" char c2[4];\n"
"};\n"
"void f() {\n"
" struct2 a = { 1, 2, 3, {4,5,6,7} }; \n"
"}\n";
(void)valueOfTok(code, "a");
code = "void setDeltas(int life, int age, int multiplier) {\n"
" int dx = 0;\n"
" int dy = 0;\n"
" if (age <= 2 || life < 4) {\n"
" dy = 0;\n"
" dx = (rand() % 3) - 1;\n"
" }\n"
" else if (age < (multiplier * 3)) {\n"
" if (age % (int) (multiplier * 0.5) == 0) dy = -1;\n"
" else dy = 0;\n"
" }\n"
"}\n";
(void)valueOfTok(code, "age");
code = "void a() {\n"
" struct b {\n"
" int d;\n"
" };\n"
" for (b c : {b{}, {}}) {}\n"
"}\n";
(void)valueOfTok(code, "c");
code = "class T {\n"
"private:\n"
" void f() { D& r = dynamic_cast<D&>(*m); }\n"
" void g() { m.reset(new D); }\n"
"private:\n"
" std::shared_ptr<B> m;\n"
"};\n";
(void)valueOfTok(code, "r");
code = "void g(int);\n"
"void f(int x, int y) {\n"
" g(x < y ? : 1);\n"
"};\n";
(void)valueOfTok(code, "?");
code = "struct C {\n"
" explicit C(bool);\n"
" operator bool();\n"
"};\n"
"void f(bool b) {\n"
" const C& c = C(b) ? : C(false);\n"
"};\n";
(void)valueOfTok(code, "?");
code = "struct S {\n"
" void g(std::vector<int> (*f) () = nullptr);\n"
"};\n";
(void)valueOfTok(code, "=");
code = "void f(bool b) {\n" // #11627
" (*printf)(\"%s %i\", strerror(errno), b ? 0 : 1);\n"
"};\n";
(void)valueOfTok(code, "?");
code = "void f(int i) {\n" // #11914
" int& r = i;\n"
" int& q = (&r)[0];\n"
"}\n";
(void)valueOfTok(code, "&");
code = "bool a(int *);\n"
"void fn2(int b) {\n"
" if (b) {\n"
" bool c, d, e;\n"
" if (c && d)\n"
" return;\n"
" if (e && a(&b)) {\n"
" }\n"
" }\n"
"}\n";
(void)valueOfTok(code, "e");
code = "void f(int a, int b, int c) {\n"
" if (c && (a || a && b))\n"
" if (a && b) {}\n"
"}\n";
(void)valueOfTok(code, "a");
code = "void g(const char* fmt, ...);\n" // #12255
"void f(const char* fmt, const char* msg) {\n"
" const char* p = msg;\n"
" g(\"%s\", msg);\n"
"}\n"
"void g(const char* fmt, ...) {\n"
" const char* q = fmt;\n"
" if (*q > 0 && *q < 100) {}\n"
"}\n";
(void)valueOfTok(code, "&&");
code = "void f() { int& a = *&a; }\n"; // #12511
(void)valueOfTok(code, "=");
code = "void g(int*);\n" // #12716
"void f(int a) {\n"
" do {\n"
" if (a)\n"
" break;\n"
" g((int[256]) { 0 });\n"
" } while (true);\n"
"}\n";
(void)valueOfTok(code, "0");
}
void valueFlowHang() {
const char* code;
// #9659
code = "float arr1[4][4] = {0.0};\n"
"float arr2[4][4] = {0.0};\n"
"void f() {\n"
" if(arr1[0][0] == 0.0 &&\n"
" arr1[0][1] == 0.0 &&\n"
" arr1[0][2] == 0.0 &&\n"
" arr1[0][3] == 0.0 &&\n"
" arr1[1][0] == 0.0 &&\n"
" arr1[1][1] == 0.0 &&\n"
" arr1[1][2] == 0.0 &&\n"
" arr1[1][3] == 0.0 &&\n"
" arr1[2][0] == 0.0 &&\n"
" arr1[2][1] == 0.0 &&\n"
" arr1[2][2] == 0.0 &&\n"
" arr1[2][3] == 0.0 &&\n"
" arr1[3][0] == 0.0 &&\n"
" arr1[3][1] == 0.0 &&\n"
" arr1[3][2] == 0.0 &&\n"
" arr1[3][3] == 0.0 &&\n"
" arr2[0][0] == 0.0 &&\n"
" arr2[0][1] == 0.0 &&\n"
" arr2[0][2] == 0.0 &&\n"
" arr2[0][3] == 0.0 &&\n"
" arr2[1][0] == 0.0 &&\n"
" arr2[1][1] == 0.0 &&\n"
" arr2[1][2] == 0.0 &&\n"
" arr2[1][3] == 0.0 &&\n"
" arr2[2][0] == 0.0 &&\n"
" arr2[2][1] == 0.0 &&\n"
" arr2[2][2] == 0.0 &&\n"
" arr2[2][3] == 0.0 &&\n"
" arr2[3][0] == 0.0 &&\n"
" arr2[3][1] == 0.0 &&\n"
" arr2[3][2] == 0.0 &&\n"
" arr2[3][3] == 0.0\n"
" ) {}\n"
"}\n";
(void)valueOfTok(code, "x");
code = "namespace {\n"
"struct a {\n"
" a(...) {}\n"
" a(std::initializer_list<std::pair<int, std::vector<std::vector<a>>>>) {}\n"
"} b{{0, {{&b, &b, &b, &b}}},\n"
" {0,\n"
" {{&b, &b, &b, &b, &b, &b, &b, &b, &b, &b},\n"
" {{&b, &b, &b, &b, &b, &b, &b}}}},\n"
" {0,\n"
" {{&b, &b, &b, &b, &b, &b, &b, &b, &b, &b, &b, &b, &b, &b},\n"
" {&b, &b, &b, &b, &b, &b, &b, &b, &b, &b, &b}}}};\n"
"}\n";
(void)valueOfTok(code, "x");
code = "namespace {\n"
"struct a {\n"
" a(...) {}\n"
" a(std::initializer_list<std::pair<int, std::vector<std::vector<a>>>>) {}\n"
"} b{{0, {{&b}}},\n"
" {0, {{&b}}},\n"
" {0, {{&b}}},\n"
" {0, {{&b}}},\n"
" {0, {{&b}, {&b, &b, &b, &b, &b, &b, &b, &b, &b, &b, {&b}}}},\n"
" {0,\n"
" {{&b},\n"
" {&b, &b, &b, &b, &b, &b, &b, &b, &b, &b, &b, &b, &b, &b, &b, &b, &b, &b,\n"
" &b}}}};\n"
"}\n";
(void)valueOfTok(code, "x");
code = "int &a(int &);\n"
"int &b(int &);\n"
"int &c(int &);\n"
"int &d(int &e) {\n"
" if (!e)\n"
" return a(e);\n"
" if (e > 0)\n"
" return b(e);\n"
" if (e < 0)\n"
" return c(e);\n"
" return e;\n"
"}\n"
"int &a(int &e) { \n"
" if (!e)\n"
" return d(e); \n"
" if (e > 0)\n"
" return b(e);\n"
" if (e < 0)\n"
" return c(e);\n"
" return e;\n"
"}\n"
"int &b(int &e) { \n"
" if (!e)\n"
" return a(e); \n"
" if (e > 0)\n"
" return c(e);\n"
" if (e < 0)\n"
" return d(e);\n"
" return e;\n"
"}\n"
"int &c(int &e) { \n"
" if (!e)\n"
" return a(e); \n"
" if (e > 0)\n"
" return b(e);\n"
" if (e < 0)\n"
" return d(e);\n"
" return e;\n"
"}\n";
(void)valueOfTok(code, "x");
code = "void a() {\n"
" int b = 0;\n"
" do {\n"
" for (;;)\n"
" break;\n"
" } while (b < 1);\n"
"}\n";
(void)valueOfTok(code, "b");
code = "void ParseEvent(tinyxml2::XMLDocument& doc, std::set<Item*>& retItems) {\n"
" auto ParseAddItem = [&](Item* item) {\n"
" return retItems.insert(item).second;\n"
" };\n"
" tinyxml2::XMLElement *root = doc.RootElement();\n"
" for (auto *el = root->FirstChildElement(\"Result\"); el && !ParseAddItem(GetItem(el)); el = el->NextSiblingElement(\"Result\")) ;\n"
" for (auto *el = root->FirstChildElement(\"Result\"); el && !ParseAddItem(GetItem(el)); el = el->NextSiblingElement(\"Result\")) ;\n"
" for (auto *el = root->FirstChildElement(\"Result\"); el && !ParseAddItem(GetItem(el)); el = el->NextSiblingElement(\"Result\")) ;\n"
" for (auto *el = root->FirstChildElement(\"Result\"); el && !ParseAddItem(GetItem(el)); el = el->NextSiblingElement(\"Result\")) ;\n"
" for (auto *el = root->FirstChildElement(\"Result\"); el && !ParseAddItem(GetItem(el)); el = el->NextSiblingElement(\"Result\")) ;\n"
" for (auto *el = root->FirstChildElement(\"Result\"); el && !ParseAddItem(GetItem(el)); el = el->NextSiblingElement(\"Result\")) ;\n"
" for (auto *el = root->FirstChildElement(\"Result\"); el && !ParseAddItem(GetItem(el)); el = el->NextSiblingElement(\"Result\")) ;\n"
" for (auto *el = root->FirstChildElement(\"Result\"); el && !ParseAddItem(GetItem(el)); el = el->NextSiblingElement(\"Result\")) ;\n"
" for (auto *el = root->FirstChildElement(\"Result\"); el && !ParseAddItem(GetItem(el)); el = el->NextSiblingElement(\"Result\")) ;\n"
" for (auto *el = root->FirstChildElement(\"Result\"); el && !ParseAddItem(GetItem(el)); el = el->NextSiblingElement(\"Result\")) ;\n"
" for (auto *el = root->FirstChildElement(\"Result\"); el && !ParseAddItem(GetItem(el)); el = el->NextSiblingElement(\"Result\")) ;\n"
" for (auto *el = root->FirstChildElement(\"Result\"); el && !ParseAddItem(GetItem(el)); el = el->NextSiblingElement(\"Result\")) ;\n"
" for (auto *el = root->FirstChildElement(\"Result\"); el && !ParseAddItem(GetItem(el)); el = el->NextSiblingElement(\"Result\")) ;\n"
" for (auto *el = root->FirstChildElement(\"Result\"); el && !ParseAddItem(GetItem(el)); el = el->NextSiblingElement(\"Result\")) ;\n"
" for (auto *el = root->FirstChildElement(\"Result\"); el && !ParseAddItem(GetItem(el)); el = el->NextSiblingElement(\"Result\")) ;\n"
"}\n";
(void)valueOfTok(code, "root");
code = "bool isCharPotentialOperator(char ch) {\n"
" return (ispunct((unsigned char) ch)\n"
" && ch != '{' && ch != '}'\n"
" && ch != '(' && ch != ')'\n"
" && ch != '[' && ch != ']'\n"
" && ch != ';' && ch != ','\n"
" && ch != '#' && ch != '\\\\'\n"
" && ch != '\\\'' && ch != '\\\"');\n"
"}\n";
(void)valueOfTok(code, "return");
code = "void heapSort() {\n"
" int n = m_size;\n"
" while (n >= 1) {\n"
" swap(0, n - 1);\n"
" }\n"
"}\n";
(void)valueOfTok(code, "swap");
code = "double a;\n"
"int b, c, d, e, f, g;\n"
"void h() { double i, j = i = g = f = e = d = c = b = a; }\n";
(void)valueOfTok(code, "a");
code = "double a, c;\n"
"double *b;\n"
"void d() {\n"
" double e, f, g, h = g = f = e = c = a;\n"
" b[8] = a;\n"
" b[1] = a;\n"
" a;\n"
"}\n";
(void)valueOfTok(code, "a");
code = "void f(int i, int j, int n) {\n"
" if ((j == 0) != (i == 0)) {}\n"
" int t = 0;\n"
" if (j > 0) {\n"
" t = 1;\n"
" if (n < j)\n"
" n = j;\n"
" }\n"
"}\n";
(void)valueOfTok(code, "i");
code = "void f() {\n" // #11701
" std::vector<int> v(500);\n"
" for (int i = 0; i < 500; i++) {\n"
" if (i < 122)\n"
" v[i] = 255;\n"
" else if (i == 122)\n"
" v[i] = 220;\n"
" else if (i < 386)\n"
" v[i] = 196;\n"
" else if (i == 386)\n"
" v[i] = 118;\n"
" else\n"
" v[i] = 0;\n"
" }\n"
"}\n";
(void)valueOfTok(code, "i");
code = "void f() {\n"
" if (llabs(0x80000000ffffffffL) == 0x7fffffff00000001L) {}\n"
"}\n";
(void)valueOfTok(code, "f");
code = "struct T {\n"
" T();\n"
" static T a[6][64];\n"
" static T b[2][64];\n"
" static T c[64][64];\n"
" static T d[2][64];\n"
" static T e[64];\n"
" static T f[64];\n"
"};\n";
(void)valueOfTok(code, "(");
}
void valueFlowCrashConstructorInitialization() { // #9577
const char* code;
code = "void Error()\n"
"{\n"
" VfsPath path(\"\");\n"
" path = path / amtype;\n"
" size_t base = 0;\n"
" VfsPath standard(\"standard\");\n"
" if (path != standard)\n"
" {\n"
" }\n"
"}";
(void)valueOfTok(code, "path");
code = "void Error()\n"
"{\n"
" VfsPath path;\n"
" path = path / amtype;\n"
" size_t base = 0;\n"
" VfsPath standard(\"standard\");\n"
" if (path != standard)\n"
" {\n"
" }\n"
"}";
(void)valueOfTok(code, "path");
code = "struct S {\n"
" std::string to_string() const {\n"
" return { this->p , (size_t)this->n };\n"
" }\n"
" const char* p;\n"
" int n;\n"
"};\n"
"void f(S s, std::string& str) {\n"
" str += s.to_string();\n"
"}\n";
(void)valueOfTok(code, "s");
code = "void a(int e, int d, int c, int h) {\n"
" std::vector<int> b;\n"
" std::vector<int> f;\n"
" if (b == f && h)\n"
" return;\n"
" if (b == f && b == f && c && e < d) {}\n"
"}\n";
(void)valueOfTok(code, "b");
}
void valueFlowUnknownMixedOperators() {
const char *code= "int f(int a, int b, bool x) {\n"
" if (a == 1 && (!(b == 2 && x))) {\n"
" } else {\n"
" if (x) {\n"
" }\n"
" }\n"
"\n"
" return 0;\n"
"}";
ASSERT_EQUALS(false, testValueOfXKnown(code, 4U, 1));
}
void valueFlowSolveExpr()
{
const char* code;
code = "int f(int x) {\n"
" if ((64 - x) == 8)\n"
" return x;\n"
" return 0;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 3U, 56));
code = "int f(int x) {\n"
" if ((x - 64) == 8)\n"
" return x;\n"
" return 0;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 3U, 72));
code = "int f(int x) {\n"
" if ((x - 64) == 8)\n"
" return x;\n"
" return 0;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 3U, 72));
code = "int f(int x) {\n"
" if ((x + 64) == 8)\n"
" return x;\n"
" return 0;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 3U, -56));
code = "int f(int x) {\n"
" if ((x * 2) == 8)\n"
" return x;\n"
" return 0;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 3U, 4));
code = "int f(int x) {\n"
" if ((x ^ 64) == 8)\n"
" return x;\n"
" return 0;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 3U, 72));
code = "int f(int i) {\n"
" int j = i + 64;\n"
" int x = j;\n"
" return x;\n"
"}\n";
TODO_ASSERT_EQUALS(true, false, testValueOfXKnown(code, 4U, "i", 64));
}
void valueFlowIdempotent() {
const char *code;
code = "void f(bool a, bool b) {\n"
" bool x = true;\n"
" if (a)\n"
" x = x && b;\n"
" bool result = x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXKnown(code, 5U, 1));
code = "void f(bool a, bool b) {\n"
" bool x = false;\n"
" if (a)\n"
" x = x && b;\n"
" bool result = x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 5U, 0));
code = "void f(bool a, bool b) {\n"
" bool x = true;\n"
" if (a)\n"
" x = x || b;\n"
" bool result = x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 5U, 1));
code = "void f(bool a, bool b) {\n"
" bool x = false;\n"
" if (a)\n"
" x = x || b;\n"
" bool result = x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXKnown(code, 5U, 0));
code = "void foo() {\n"
" int x = 0;\n"
" for (int i = 0; i < 5; i++) {\n"
" int y = 0;\n"
" for (int j = 0; j < 10; j++)\n"
" y++;\n"
" if (y >= x)\n"
" x = y;\n"
" }\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXKnown(code, 10U, 0));
}
void valueFlowUnsigned() {
const char *code;
code = "auto f(uint32_t i) {\n"
" auto x = i;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, -1));
code = "auto f(uint32_t i) {\n"
" auto x = (int32_t)i;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXImpossible(code, 3U, -1));
code = "auto f(uint32_t i) {\n"
" auto x = (int64_t)i;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, -1));
code = "size_t g();\n"
"auto f(uint16_t j) {\n"
" auto x = g() - j;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXImpossible(code, 4U, 0));
ASSERT_EQUALS(true, testValueOfXImpossible(code, 4U, -1));
code = "auto f(uint32_t i) {\n"
" auto x = (i + 1) % 16;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXImpossible(code, 3U, 0));
ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, -1));
code = "auto f(uint32_t i) {\n"
" auto x = i ^ 3;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXImpossible(code, 3U, 2));
ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, -1));
code = "auto f(uint32_t i) {\n"
" auto x = i & 3;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXImpossible(code, 3U, 2));
ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, -1));
}
void valueFlowMod() {
const char *code;
code = "auto f(int i) {\n"
" auto x = i % 2;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, 2));
code = "auto f(int i) {\n"
" auto x = !(i % 2);\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXImpossible(code, 3U, 0));
ASSERT_EQUALS(false, testValueOfXImpossible(code, 3U, 1));
}
void valueFlowIncDec() {
const char *code;
std::list<ValueFlow::Value> values;
// #11591
code = "int f() {\n"
" const int a[1] = {};\n"
" unsigned char i = 255;\n"
" ++i;\n"
" return a[i];\n"
"}\n";
values = tokenValues(code, "i ]");
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(0LLU, values.back().intvalue);
code = "int f() {\n"
" const int a[1] = {};\n"
" unsigned char i = 255;\n"
" return a[++i];\n"
"}\n";
values = tokenValues(code, "++");
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(0LLU, values.back().intvalue);
code = "int f() {\n"
" const int a[128] = {};\n"
" char b = -128;\n"
" return a[--b];\n"
"}\n";
values = tokenValues(code, "--");
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(127LLU, values.back().intvalue);
}
void valueFlowNotNull()
{
const char* code;
code = "int f(const std::string &str) {\n"
" int x = str.c_str();\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, 0));
code = "int f(const std::string_view &str) {\n"
" int x = str.c_str();\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXImpossible(code, 3U, 0));
code = "auto f() {\n"
" std::shared_ptr<int> x = std::make_shared<int>(1);\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, 0));
code = "auto f() {\n"
" std::unique_ptr<int> x = std::make_unique<int>(1);\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, 0));
code = "struct A {\n"
" A* f() {\n"
" A* x = this;\n"
" return x;\n"
" }\n"
"};\n";
ASSERT_EQUALS(true, testValueOfXImpossible(code, 4U, 0));
}
void valueFlowSymbolic() {
const char* code;
code = "int f(int i) {\n"
" int j = i;\n"
" int x = i;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 4U, "j", 0));
ASSERT_EQUALS(true, testValueOfXKnown(code, 4U, "i", 0));
code = "int f(int i) {\n"
" int j = i;\n"
" int x = j;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 4U, "i", 0));
ASSERT_EQUALS(true, testValueOfXKnown(code, 4U, "j", 0));
code = "void g(int&);\n"
"int f(int i) {\n"
" int j = i;\n"
" g(i);\n"
" int x = i;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 6U, "i", 0));
ASSERT_EQUALS(false, testValueOfXKnown(code, 6U, "j", 0));
code = "int f(int i) {\n"
" int j = i;\n"
" j++;\n"
" int x = i == j;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 5U, 0));
code = "int f(int i) {\n"
" int j = i;\n"
" i++;\n"
" int x = i - j;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 5U, 1));
code = "int f(int i) {\n"
" int j = i;\n"
" i++;\n"
" int x = i > j;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 5U, 1));
code = "int f(int i) {\n"
" int j = i;\n"
" j++;\n"
" int x = j > i;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 5U, 1));
code = "int f(int i) {\n"
" int j = i++;\n"
" int x = i++;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXKnown(code, 4U, "i++", 0));
code = "float foo() {\n"
" float f = 1.0f;\n"
" float x = f;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXKnown(code, 4U, "1.0f", 0));
code = "int foo(float f) {\n"
" float g = f;\n"
" int x = f == g;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXKnown(code, 4U, 1));
code = "int f(int i) {\n"
" for(int j = i;;j++) {\n"
" int x = j;\n"
" return x;\n"
" }\n"
" return 0;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXKnown(code, 4U, "i", 0));
ASSERT_EQUALS(false, testValueOfXKnown(code, 4U, "i", 1));
ASSERT_EQUALS(true, testValueOfXKnown(code, 4U, "j", 0));
code = "void f(int x) {\n"
" int y = x + 1;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXKnown(code, 3U, "y", 0));
ASSERT_EQUALS(true, testValueOfXKnown(code, 3U, "y", -1));
code = "void f(int x) {\n"
" int y = x * 2;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXKnown(code, 3U, "y", 0));
code = "int f(int i, int j) {\n"
" if (i == j) {\n"
" int x = i - j;\n"
" return x;\n"
" }\n"
" return 0;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 4U, 0));
code = "void f(int x, int y) {\n"
" if (x == y) {\n"
" int a = x;\n"
" }\n"
"}";
ASSERT_EQUALS(true, testValueOfXKnown(code, 3U, "y", 0));
code = "void f(int x, int y) {\n"
" if (x != y) {\n"
" int a = x;\n"
" }\n"
"}";
ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, "y", 0));
code = "void f(int x, int y) {\n"
" if (x < y) {\n"
" int a = x;\n"
" }\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, "y", -1));
ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, "y", 0));
code = "void f(int x, int y) {\n"
" if (x <= y) {\n"
" int a = x;\n"
" }\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, "y", 0));
ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, "y", 1));
code = "void f(int x, int y) {\n"
" if (x > y) {\n"
" int a = x;\n"
" }\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, "y", 1));
ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, "y", 0));
code = "void f(int x, int y) {\n"
" if (x >= y) {\n"
" int a = x;\n"
" }\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code, 3U, "y", 0));
ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, "y", -1));
code = "void f(int y) {\n"
" int x = y - 1;\n"
" if (y == 1)\n"
" int a = x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 4U, 0));
code = "void f(int y) {\n"
" int x = y * y;\n"
" if (y == 2)\n"
" int a = x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 4U, 4));
code = "void f(int x, int y) {\n"
" if (x == y*y)\n"
" if (y == 2)\n"
" int a = x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 4U, 4));
code = "void f(int x, int y) {\n"
" if (x > y*y)\n"
" if (y == 2)\n"
" int a = x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXImpossible(code, 4U, 4));
code = "void f(int x, int y) {\n"
" if (x != y*y)\n"
" if (y == 2)\n"
" int a = x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXImpossible(code, 4U, 4));
code = "void f(int x, int y) {\n"
" if (x >= y*y)\n"
" if (y == 2)\n"
" int a = x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXImpossible(code, 4U, 3));
code = "void f(int x, int y) {\n"
" if (x == y*y)\n"
" if (y != 2)\n"
" int a = x;\n"
"}\n";
TODO_ASSERT_EQUALS(true, false, testValueOfXImpossible(code, 4U, 4));
code = "void f(int x, int y) {\n"
" if (x == y*y)\n"
" if (y > 2)\n"
" int a = x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 4U, 9));
code = "struct A {\n"
" A* b();\n"
" int c() const;\n"
"};\n"
"void f(A *d) {\n"
" if (!d || d->c() != 1)\n"
" return;\n"
" A * y = d;\n"
" d = d->b();\n"
" A * x = d;\n"
" A* z = x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 11U, "d", 0));
ASSERT_EQUALS(false, testValueOfXImpossible(code, 11U, 0));
code = "void f(int * p, int len) {\n"
" for(int x = 0; x < len; ++x) {\n"
" p[x] = 1;\n"
" }\n"
"}\n";
ASSERT_EQUALS(true, testValueOfX(code, 3U, "len", -1));
ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, "len", 0));
code = "int f(int x) {\n"
" int i = 64 - x;\n"
" if(i < 8)\n"
" return x;\n"
" return 0;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 4U, 71));
TODO_ASSERT_EQUALS(true, false, testValueOfX(code, 4U, 56));
code = "int b(int a) {\n"
" unsigned long x = a ? 6 : 4;\n"
" assert(x < 6 && x > 0);\n"
" return 1 / x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 4U, 0));
code = "void f(int k) {\n"
" int x = k;\n"
" int j = k;\n"
" x--;\n"
" if (k != 0) {\n"
" x;\n"
" }\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 6U, -1));
ASSERT_EQUALS(true, testValueOfXImpossible(code, 6U, -1));
code = "char* f() {\n"
" char *x = malloc(10);\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 3U, "malloc(10)", 0));
}
void valueFlowSymbolicIdentity()
{
const char* code;
code = "void f(int a) {\n"
" int x = a*1;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 3U, "a", 0));
code = "void f(int a) {\n"
" int x = a/1;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 3U, "a", 0));
code = "void f(int a) {\n"
" int x = a+0;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 3U, "a", 0));
code = "void f(int a) {\n"
" int x = a-0;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 3U, "a", 0));
code = "void f(int a) {\n"
" int x = a^0;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 3U, "a", 0));
code = "void f(int a) {\n"
" int x = a|0;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 3U, "a", 0));
code = "void f(int a) {\n"
" int x = a>>0;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 3U, "a", 0));
code = "void f(int a) {\n"
" int x = a<<0;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 3U, "a", 0));
code = "void f(int a) {\n"
" int x = 0>>a;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXKnown(code, 3U, "a", 0));
code = "void f(int a) {\n"
" int x = 0<<a;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXKnown(code, 3U, "a", 0));
}
void valueFlowSymbolicStrlen()
{
const char* code;
code = "int f(char *s) {\n"
" size_t len = strlen(s);\n"
" int x = s[len];\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 4U, 0));
code = "int f(char *s, size_t i) {\n"
" if (i < strlen(s)) {\n"
" int x = s[i];\n"
" return x;\n"
" }\n"
" return 0;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXImpossible(code, 4U, 0));
code = "int f(char *s, size_t i) {\n"
" if (i < strlen(s)) {\n"
" int x = s[i] != ' ';\n"
" return x;\n"
" }\n"
" return 0;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXKnown(code, 4U, 1));
code = "int f(char *s, size_t i) {\n"
" if (i == strlen(s)) {}\n"
" int x = s[i];\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfXKnown(code, 4U, 0));
ASSERT_EQUALS(true, testValueOfX(code, 4U, 0));
}
void valueFlowSmartPointer()
{
const char* code;
code = "int* df(int* expr);\n"
"int * f() {\n"
" std::unique_ptr<int> x;\n"
" x.reset(df(x.release()));\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 5U, 0));
}
void valueFlowImpossibleMinMax()
{
const char* code;
code = "void f(int a, int b) {\n"
" int x = a < b ? a : b;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, "a", 1));
ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, "b", 1));
code = "void f(int a, int b) {\n"
" int x = a > b ? a : b;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, "a", -1));
ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, "b", -1));
code = "void f(int a, int b) {\n"
" int x = a > b ? b : a;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, "a", 1));
ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, "b", 1));
code = "void f(int a, int b) {\n"
" int x = a < b ? b : a;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, "a", -1));
ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, "b", -1));
code = "void f(int a) {\n"
" int x = a < 0 ? a : 0;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, "a", 1));
ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, 1));
code = "void f(int a) {\n"
" int x = a > 0 ? a : 0;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, "a", -1));
ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, -1));
code = "void f(int a) {\n"
" int x = a > 0 ? 0 : a;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, "a", 1));
ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, 1));
code = "void f(int a) {\n"
" int x = a < 0 ? 0 : a;\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, "a", -1));
ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, -1));
}
void valueFlowImpossibleIncDec()
{
const char* code;
code = "int f() {\n"
" for(int i = 0; i < 5; i++) {\n"
" int x = i;\n"
" return x;\n"
" }\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXImpossible(code, 4U, -1));
code = "void f(int N, int z) {\n"
" std::vector<int> a(N);\n"
" int m = -1;\n"
" m = 0;\n"
" for (int k = 0; k < N; k++) {\n"
" int x = m + k;\n"
" if (z == a[x]) {}\n"
" }\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXImpossible(code, 7U, -1));
ASSERT_EQUALS(false, testValueOfXKnown(code, 7U, -1));
}
void valueFlowImpossibleUnknownConstant()
{
const char* code;
code = "void f(bool b) {\n"
" if (b) {\n"
" int x = -ENOMEM;\n" // assume constant ENOMEM is nonzero since it's negated
" if (x != 0) return;\n"
" }\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXImpossible(code, 4U, 0));
}
void valueFlowContainerEqual()
{
const char* code;
code = "bool f() {\n"
" std::string s = \"abc\";\n"
" bool x = (s == \"def\");\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 4U, 0));
code = "bool f() {\n"
" std::string s = \"abc\";\n"
" bool x = (s != \"def\");\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 4U, 1));
code = "bool f() {\n"
" std::vector<int> v1 = {1, 2};\n"
" std::vector<int> v2 = {1, 2};\n"
" bool x = (v1 == v2);\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 5U, 1));
code = "bool f() {\n"
" std::vector<int> v1 = {1, 2};\n"
" std::vector<int> v2 = {1, 2};\n"
" bool x = (v1 != v2);\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 5U, 0));
code = "bool f(int i) {\n"
" std::vector<int> v1 = {i, i+1};\n"
" std::vector<int> v2 = {i};\n"
" bool x = (v1 == v2);\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(true, testValueOfXKnown(code, 5U, 0));
code = "bool f(int i, int j) {\n"
" std::vector<int> v1 = {i, i};\n"
" std::vector<int> v2 = {i, j};\n"
" bool x = (v1 == v2);\n"
" return x;\n"
"}\n";
ASSERT_EQUALS(false, testValueOfX(code, 5U, 1));
ASSERT_EQUALS(false, testValueOfX(code, 5U, 0));
}
void valueFlowBailoutIncompleteVar() { // #12526
bailout(
"int f1() {\n"
" return VALUE_1;\n"
"}\n"
"\n"
"int f2() {\n"
" return VALUE_2;\n"
"}\n"
);
ASSERT_EQUALS_WITHOUT_LINENUMBERS(
"[test.cpp:2]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable VALUE_1\n"
"[test.cpp:6]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable VALUE_2\n",
errout_str());
}
void performanceIfCount() {
/*const*/ Settings s(settings);
s.vfOptions.maxIfCount = 1;
const char *code;
code = "int f() {\n"
" if (x>0){}\n"
" if (y>0){}\n"
" int a = 14;\n"
" return a+1;\n"
"}\n";
ASSERT_EQUALS(0U, tokenValues(code, "+", &s).size());
ASSERT_EQUALS(1U, tokenValues(code, "+").size());
// Do not skip all functions
code = "void g(int i) {\n"
" if (i == 1) {}\n"
" if (i == 2) {}\n"
"}\n"
"int f() {\n"
" std::vector<int> v;\n"
" return v.front();\n"
"}\n";
ASSERT_EQUALS(1U, tokenValues(code, "v .", &s).size());
}
};
REGISTER_TEST(TestValueFlow)
| null |
959 | cpp | cppcheck | testsimplifyusing.cpp | test/testsimplifyusing.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "errortypes.h"
#include "fixture.h"
#include "helpers.h"
#include "platform.h"
#include "settings.h"
#include "token.h"
#include "tokenize.h"
#include "tokenlist.h"
#include "utils.h"
#include <cstddef>
#include <sstream>
#include <string>
#include <vector>
class TestSimplifyUsing : public TestFixture {
public:
TestSimplifyUsing() : TestFixture("TestSimplifyUsing") {}
private:
const Settings settings0 = settingsBuilder().severity(Severity::style).build();
void run() override {
TEST_CASE(simplifyUsing1);
TEST_CASE(simplifyUsing2);
TEST_CASE(simplifyUsing3);
TEST_CASE(simplifyUsing4);
TEST_CASE(simplifyUsing5);
TEST_CASE(simplifyUsing6);
TEST_CASE(simplifyUsing7);
TEST_CASE(simplifyUsing8);
TEST_CASE(simplifyUsing9);
TEST_CASE(simplifyUsing10);
TEST_CASE(simplifyUsing11);
TEST_CASE(simplifyUsing12);
TEST_CASE(simplifyUsing13);
TEST_CASE(simplifyUsing14);
TEST_CASE(simplifyUsing15);
TEST_CASE(simplifyUsing16);
TEST_CASE(simplifyUsing17);
TEST_CASE(simplifyUsing18);
TEST_CASE(simplifyUsing19);
TEST_CASE(simplifyUsing20);
TEST_CASE(simplifyUsing21);
TEST_CASE(simplifyUsing22);
TEST_CASE(simplifyUsing23);
TEST_CASE(simplifyUsing24);
TEST_CASE(simplifyUsing25);
TEST_CASE(simplifyUsing26); // #11090
TEST_CASE(simplifyUsing27);
TEST_CASE(simplifyUsing28);
TEST_CASE(simplifyUsing29);
TEST_CASE(simplifyUsing30);
TEST_CASE(simplifyUsing31);
TEST_CASE(simplifyUsing32);
TEST_CASE(simplifyUsing33);
TEST_CASE(simplifyUsing34);
TEST_CASE(simplifyUsing8970);
TEST_CASE(simplifyUsing8971);
TEST_CASE(simplifyUsing8976);
TEST_CASE(simplifyUsing9040);
TEST_CASE(simplifyUsing9042);
TEST_CASE(simplifyUsing9191);
TEST_CASE(simplifyUsing9381);
TEST_CASE(simplifyUsing9385);
TEST_CASE(simplifyUsing9388);
TEST_CASE(simplifyUsing9518);
TEST_CASE(simplifyUsing9757);
TEST_CASE(simplifyUsing10008);
TEST_CASE(simplifyUsing10054);
TEST_CASE(simplifyUsing10136);
TEST_CASE(simplifyUsing10171);
TEST_CASE(simplifyUsing10172);
TEST_CASE(simplifyUsing10173);
TEST_CASE(simplifyUsing10335);
TEST_CASE(simplifyUsing10720);
TEST_CASE(scopeInfo1);
TEST_CASE(scopeInfo2);
}
#define tok(...) tok_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
std::string tok_(const char* file, int line, const char (&code)[size], Platform::Type type = Platform::Type::Native, bool debugwarnings = true, bool preprocess = false) {
const Settings settings = settingsBuilder(settings0).certainty(Certainty::inconclusive).debugwarnings(debugwarnings).platform(type).build();
if (preprocess) {
Tokenizer tokenizer(settings, *this);
std::vector<std::string> files(1, "test.cpp");
PreprocessorHelper::preprocess(code, files, tokenizer, *this);
std::istringstream istr(code);
ASSERT_LOC(tokenizer.list.createTokens(istr, "test.cpp"), file, line); // TODO: this creates the tokens a second time
ASSERT_LOC(tokenizer.simplifyTokens1(""), file, line);
return tokenizer.tokens()->stringifyList(nullptr);
}
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
return tokenizer.tokens()->stringifyList(nullptr);
}
void simplifyUsing1() {
const char code[] = "class A\n"
"{\n"
"public:\n"
" using duplicate = wchar_t;\n"
" void foo() {}\n"
"};\n"
"using duplicate = A;\n"
"int main()\n"
"{\n"
" duplicate a;\n"
" a.foo();\n"
" A::duplicate c = 0;\n"
"}";
const char expected[] =
"class A "
"{ "
"public: "
""
"void foo ( ) { } "
"} ; "
"int main ( ) "
"{ "
"A a ; "
"a . foo ( ) ; "
"wchar_t c ; c = 0 ; "
"}";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyUsing2() {
const char code[] = "class A;\n"
"using duplicate = A;\n"
"class A\n"
"{\n"
"public:\n"
"using duplicate = wchar_t;\n"
"duplicate foo() { wchar_t b; return b; }\n"
"};";
const char expected[] =
"class A ; "
"class A "
"{ "
"public: "
""
"wchar_t foo ( ) { wchar_t b ; return b ; } "
"} ;";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyUsing3() {
const char code[] = "class A {};\n"
"using duplicate = A;\n"
"wchar_t foo()\n"
"{\n"
"using duplicate = wchar_t;\n"
"duplicate b;\n"
"return b;\n"
"}\n"
"int main()\n"
"{\n"
"duplicate b;\n"
"}";
const char expected[] =
"class A { } ; "
"wchar_t foo ( ) "
"{ "
""
"wchar_t b ; "
"return b ; "
"} "
"int main ( ) "
"{ "
"A b ; "
"}";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyUsing4() {
const char code[] = "using s32 = int;\n"
"using u32 = unsigned int;\n"
"void f()\n"
"{\n"
" s32 ivar = -2;\n"
" u32 uvar = 2;\n"
" return uvar / ivar;\n"
"}";
const char expected[] =
"void f ( ) "
"{ "
"int ivar ; ivar = -2 ; "
"unsigned int uvar ; uvar = 2 ; "
"return uvar / ivar ; "
"}";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyUsing5() {
const char code[] =
"using YY_BUFFER_STATE = struct yy_buffer_state *;\n"
"void f()\n"
"{\n"
" YY_BUFFER_STATE state;\n"
"}";
const char expected[] =
"void f ( ) "
"{ "
"yy_buffer_state * state ; "
"}";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyUsing6() {
const char code[] =
"namespace VL {\n"
" using float_t = float;\n"
" inline VL::float_t fast_atan2(VL::float_t y, VL::float_t x){}\n"
"}";
const char expected[] =
"namespace VL { "
""
"float fast_atan2 ( float y , float x ) { } "
"}";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyUsing7() {
const char code[] = "using abc = int; "
"Fred :: abc f ;";
const char expected[] = "Fred :: abc f ;";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyUsing8() {
const char code[] = "using INT = int;\n"
"using UINT = unsigned int;\n"
"using PINT = int *;\n"
"using PUINT = unsigned int *;\n"
"using RINT = int &;\n"
"using RUINT = unsigned int &;\n"
"using RCINT = const int &;\n"
"using RCUINT = const unsigned int &;\n"
"INT ti;\n"
"UINT tui;\n"
"PINT tpi;\n"
"PUINT tpui;\n"
"RINT tri;\n"
"RUINT trui;\n"
"RCINT trci;\n"
"RCUINT trcui;";
const char expected[] =
"int ti ; "
"unsigned int tui ; "
"int * tpi ; "
"unsigned int * tpui ; "
"int & tri ; "
"unsigned int & trui ; "
"const int & trci ; "
"const unsigned int & trcui ;";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyUsing9() {
const char code[] = "using S = struct s;\n"
"using PS = S *;\n"
"using T = struct t { int a; };\n"
"using TP = T *;\n"
"using U = struct { int a; };\n"
"using V = U *;\n"
"using W = struct { int a; } *;\n"
"S s;\n"
"PS ps;\n"
"T t;\n"
"TP tp;\n"
"U u;\n"
"V v;\n"
"W w;";
const char expected[] =
"struct t { int a ; } ; "
"struct U { int a ; } ; "
"struct Unnamed0 { int a ; } ; "
"s s ; "
"s * ps ; "
"t t ; "
"t * tp ; "
"U u ; "
"U * v ; "
"Unnamed0 * w ;";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyUsing10() {
const char code[] = "using S = union s;\n"
"using PS = S *;\n"
"using T = union t { int a; float b ; };\n"
"using TP = T *;\n"
"using U = union { int a; float b; };\n"
"using V = U *;\n"
"using W = union { int a; float b; } *;\n"
"S s;\n"
"PS ps;\n"
"T t;\n"
"TP tp;\n"
"U u;\n"
"V v;\n"
"W w;";
const char expected[] =
"union t { int a ; float b ; } ; "
"union U { int a ; float b ; } ; "
"union Unnamed0 { int a ; float b ; } ; "
"s s ; "
"s * ps ; "
"t t ; "
"t * tp ; "
"U u ; "
"U * v ; "
"Unnamed0 * w ;";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyUsing11() {
const char code[] = "using abc = enum { a = 0 , b = 1 , c = 2 };\n"
"using XYZ = enum xyz { x = 0 , y = 1 , z = 2 };\n"
"abc e1;\n"
"XYZ e2;";
const char expected[] = "enum abc { a = 0 , b = 1 , c = 2 } ; "
"enum xyz { x = 0 , y = 1 , z = 2 } ; "
"abc e1 ; "
"xyz e2 ;";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyUsing12() {
const char code[] = "using V1 = vector<int>;\n"
"using V2 = std::vector<int>;\n"
"using V3 = std::vector<std::vector<int> >;\n"
"using IntListIterator = std::list<int>::iterator;\n"
"V1 v1;\n"
"V2 v2;\n"
"V3 v3;\n"
"IntListIterator iter;";
const char expected[] = "vector < int > v1 ; "
"std :: vector < int > v2 ; "
"std :: vector < std :: vector < int > > v3 ; "
"std :: list < int > :: iterator iter ;";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyUsing13() {
const char code[] = "using Func = std::pair<int(*)(void*), void*>;\n"
"using CallQueue = std::vector<Func>;\n"
"int main() {\n"
" CallQueue q;\n"
"}";
const char expected[] = "int main ( ) { "
"std :: vector < std :: pair < int ( * ) ( void * ) , void * > > q ; "
"}";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
void simplifyUsing14() {
const char code[] = "template <typename F, unsigned int N> struct E"
"{"
" using v = E<F,(N>0)?(N-1):0>;"
" using val = typename add<v,v>::val;"
" FP_M(val);"
"};"
"template <typename F> struct E <F,0>"
"{"
" using nal = typename D<1>::val;"
" FP_M(val);"
"};";
TODO_ASSERT_THROW(tok(code, Platform::Type::Native, false), InternalError); // TODO: Do not throw AST validation exception
//ASSERT_EQUALS("", errout_str());
}
void simplifyUsing15() {
{
const char code[] = "using frame = char [10];\n"
"frame f;";
const char expected[] = "char f [ 10 ] ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "using frame = unsigned char [10];\n"
"frame f;";
const char expected[] = "unsigned char f [ 10 ] ;";
ASSERT_EQUALS(expected, tok(code));
}
}
void simplifyUsing16() {
const char code[] = "using MOT8 = char;\n"
"using CHFOO = MOT8 [4096];\n"
"using STRFOO = struct {\n"
" CHFOO freem;\n"
"};\n"
"STRFOO s;";
const char expected[] = "struct STRFOO { "
"char freem [ 4096 ] ; "
"} ; "
"STRFOO s ;";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
void simplifyUsing17() {
const char code[] = "class C1 {};\n"
"using S1 = class S1 {};\n"
"using S2 = class S2 : public C1 {};\n"
"using S3 = class {};\n"
"using S4 = class : public C1 {};\n"
"S1 s1;\n"
"S2 s2;\n"
"S3 s3;\n"
"S4 s4;";
const char expected[] = "class C1 { } ; "
"class S1 { } ; "
"class S2 : public C1 { } ; "
"class S3 { } ; "
"class S4 : public C1 { } ; "
"S1 s1 ; "
"S2 s2 ; "
"S3 s3 ; "
"S4 s4 ;";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyUsing18() {
const char code[] = "{ { { using a = a; using a; } } }";
(void)tok(code); // don't crash
}
void simplifyUsing19() {
const char code[] = "namespace a {\n"
"using b = int;\n"
"void foo::c() { }\n"
"void foo::d() { }\n"
"void foo::e() {\n"
" using b = float;\n"
"}\n"
"}";
(void)tok(code); // don't hang
ignore_errout(); // we are not interested in the output
}
void simplifyUsing20() {
const char code[] = "namespace a {\n"
"namespace b {\n"
"namespace c {\n"
"namespace d {\n"
"namespace e {\n"
"namespace f {\n"
"namespace g {\n"
"using Changeset = ::IAdaptionCallback::Changeset;\n"
"using EProperty = searches::EProperty;\n"
"using ChangesetValueType = Changeset::value_type;\n"
"namespace {\n"
" template <class T>\n"
" auto modify(std::shared_ptr<T>& p) -> boost::optional<decltype(p->modify())> {\n"
" return nullptr;\n"
" }\n"
" template <class T>\n"
" std::list<T> getValidElements() {\n"
" return nullptr;\n"
" }\n"
"}\n"
"std::shared_ptr<ResourceConfiguration>\n"
"foo::getConfiguration() {\n"
" return nullptr;\n"
"}\n"
"void\n"
"foo::doRegister(const Input & Input) {\n"
" UNUSED( Input );\n"
"}\n"
"foo::MicroServiceReturnValue\n"
"foo::post(SearchesPtr element, const Changeset& changeset)\n"
"{\n"
" using EProperty = ab::ep;\n"
" static std::map<EProperty, std::pair<ElementPropertyHandler, CheckComponentState>> updateHandlers =\n"
" {\n"
" {EProperty::Needle, {&RSISearchesResource::updateNeedle, &RSISearchesResource::isSearcherReady}},\n"
" {EProperty::SortBy, {&RSISearchesResource::updateResultsSorting, &RSISearchesResource::isSearcherReady}}\n"
" };\n"
" return nullptr;\n"
"}\n"
"}}}}}}}";
(void)tok(code); // don't hang
ignore_errout(); // we do not care about the output
}
void simplifyUsing21() {
const char code[] = "using a = b;\n"
"enum {}";
(void)tok(code); // don't crash
}
void simplifyUsing22() {
const char code[] = "namespace aa { namespace bb { namespace cc { namespace dd { namespace ee {\n"
"class fff {\n"
"public:\n"
" using icmsp = std::shared_ptr<aa::bb::ee::cm::api::icm>;\n"
"private:\n"
" using Connection = boost::signals2::connection;\n"
" using ESdk = sdk::common::api::Sdk::ESdk;\n"
" using co = aa::bb::ee::com::api::com2;\n"
"};\n"
"fff::fff() : m_icm(icm) {\n"
" using ESdk = aa::bb::sdk::common::api::Sdk::ESdk;\n"
"}\n"
"}}}}}";
const char expected[] = "namespace aa { namespace bb { namespace cc { namespace dd { namespace ee { "
"class fff { "
"public: "
"private: "
"} ; "
"fff :: fff ( ) : m_icm ( icm ) { "
"} "
"} } } } }";
ASSERT_EQUALS(expected, tok(code)); // don't hang
ignore_errout(); // we do not care about the output
}
void simplifyUsing23() {
const char code[] = "class cmcch {\n"
"public:\n"
" cmcch(icmsp const& icm, Rtnf&& rtnf = {});\n"
"private:\n"
" using escs = aa::bb::cc::dd::ee;\n"
"private:\n"
" icmsp m_icm;\n"
" mutable std::atomic<rt> m_rt;\n"
"};\n"
"cmcch::cmcch(cmcch::icmsp const& icm, Rtnf&& rtnf)\n"
" : m_icm(icm)\n"
" , m_rt{rt::UNKNOWN_} {\n"
" using escs = yy::zz::aa::bb::cc::dd::ee;\n"
"}";
const char expected[] = "class cmcch { "
"public: "
"cmcch ( const icmsp & icm , Rtnf && rtnf = { } ) ; "
"private: "
"private: "
"icmsp m_icm ; "
"mutable std :: atomic < rt > m_rt ; "
"} ; "
"cmcch :: cmcch ( const cmcch :: icmsp & icm , Rtnf && rtnf ) "
": m_icm ( icm ) "
", m_rt { rt :: UNKNOWN_ } { "
"}";
ASSERT_EQUALS(expected, tok(code)); // don't hang
}
void simplifyUsing24() {
const char code[] = "using value_type = const ValueFlow::Value;\n"
"value_type vt;";
const char expected[] = "const ValueFlow :: Value vt ;";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyUsing25() {
const char code[] = "struct UnusualType {\n"
" using T = vtkm::Id;\n"
" T X;\n"
"};\n"
"namespace vtkm {\n"
"template <>\n"
"struct VecTraits<UnusualType> : VecTraits<UnusualType::T> { };\n"
"}";
const char expected[] = "struct UnusualType { "
"vtkm :: Id X ; "
"} ; "
"namespace vtkm { "
"struct VecTraits<UnusualType> : VecTraits < vtkm :: Id > { } ; "
"}";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyUsing26() { // #11090
const char code[] = "namespace M {\n"
" struct A;\n"
" struct B;\n"
" struct C;\n"
" template<typename T>\n"
" struct F {};\n"
" template<>\n"
" struct F<B> : F<A> {};\n"
" template<>\n"
" struct F<C> : F<A> {};\n"
"}\n"
"namespace N {\n"
" using namespace M;\n"
" using A = void;\n"
"}\n";
const char expected[] = "namespace M { "
"struct A ; struct B ; struct C ; "
"struct F<C> ; struct F<B> ; struct F<A> ; "
"struct F<B> : F<A> { } ; struct F<C> : F<A> { } ; "
"} "
"namespace N { "
"using namespace M ; "
"} "
"struct M :: F<A> { } ;";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyUsing27() { // #11670
const char code[] = "namespace N {\n"
" template <class T>\n"
" struct S {\n"
" using iterator = T*;\n"
" iterator begin();\n"
" };\n"
"}\n"
"using I = N::S<int>;\n"
"void f() {\n"
" I::iterator iter;\n"
"}\n";
const char expected[] = "namespace N { struct S<int> ; } "
"void f ( ) { int * iter ; } "
"struct N :: S<int> { int * begin ( ) ; } ;";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyUsing28() { // #11795
const char code[] = "void f() {\n"
" using T = int;\n"
" T* p{ new T };\n"
"}\n";
const char expected[] = "void f ( ) { int * p { new int } ; }";
ASSERT_EQUALS(expected, tok(code, Platform::Type::Native, /*debugwarnings*/ true));
ASSERT_EQUALS("", errout_str());
}
void simplifyUsing29() { // #11981
const char code[] = "using T = int*;\n"
"void f(T = T()) {}\n";
const char expected[] = "void f ( int * = ( int * ) 0 ) { }";
ASSERT_EQUALS(expected, tok(code, Platform::Type::Native, /*debugwarnings*/ true));
ASSERT_EQUALS("", errout_str());
}
void simplifyUsing30() {
{
const char code[] = "using std::to_string;\n" // #8454
"void f() {\n"
" std::string str = to_string(1);\n"
"}\n";
const char expected[] = "void f ( ) { std :: string str ; str = std :: to_string ( 1 ) ; }";
ASSERT_EQUALS(expected, tok(code, Platform::Type::Native, /*debugwarnings*/ true));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "using std::cout, std::endl, std::cerr, std::ostringstream;\n"
"cerr << \"abc\";\n";
const char expected[] = "std :: cerr << \"abc\" ;";
ASSERT_EQUALS(expected, tok(code, Platform::Type::Native, /*debugwarnings*/ true));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "using std::string_view_literals::operator\"\"sv;\n";
const char expected[] = "using std :: string_view_literals :: operator\"\"sv ;";
ASSERT_EQUALS(expected, tok(code, Platform::Type::Native, /*debugwarnings*/ true));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "template <typename T>\n"
"class vector : public ::std::vector<T> {\n"
"public:\n"
" using ::std::vector<T>::vector;\n"
" vector() {}\n"
"};\n"
"vector <int> v;\n";
const char expected[] = "class vector<int> ; "
"vector<int> v ; "
"class vector<int> : public :: std :: vector<int> { "
"public: "
"using vector<int> = :: std :: vector<int> :: vector<int> ; "
"vector<int> ( ) { } "
"} ;";
ASSERT_EQUALS(expected, tok(code, Platform::Type::Native, /*debugwarnings*/ true));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "using namespace ::std;\n"
"void f(const char* c) {\n"
" cout << std::string(c) << \"abc\";\n"
"}\n";
const char expected[] = "using namespace :: std ; " // TODO: simplify cout?
"void f ( const char * c ) { "
"cout << std :: string ( c ) << \"abc\" ; "
"}";
ASSERT_EQUALS(expected, tok(code, Platform::Type::Native, /*debugwarnings*/ true));
ASSERT_EQUALS(
"[test.cpp:3]: (debug) valueFlowConditionExpressions bailout: Skipping function due to incomplete variable cout\n",
errout_str());
}
{
const char code[] = "class T : private std::vector<std::pair<std::string, const int*>> {\n" // #12521
" using std::vector<std::pair<std::string, const int*>>::empty;\n"
"};\n";
const char expected[] = "class T : private std :: vector < std :: pair < std :: string , const int * > > { "
"using empty = std :: vector < std :: pair < std :: string , const int * > > :: empty ; "
"} ;";
ASSERT_EQUALS(expected, tok(code, Platform::Type::Native, /*debugwarnings*/ true));
ASSERT_EQUALS("", errout_str());
}
}
void simplifyUsing31() { // #11899
const char code[] = "struct B {\n"
" B();\n"
" void f();\n"
"};\n"
"struct D : B {\n"
" using B::B;\n"
" void g() {\n"
" B::f();\n"
" }\n"
" B b;\n"
"};\n";
const char expected[] = "struct B { "
"B ( ) ; "
"void f ( ) ; "
"} ; "
"struct D : B { "
"using B = B :: B ; "
"void g ( ) { "
"B :: f ( ) ; "
"} "
"B b ; "
"} ;";
ASSERT_EQUALS(expected, tok(code, Platform::Type::Native, /*debugwarnings*/ true));
ASSERT_EQUALS("", errout_str());
}
void simplifyUsing32() {
const char code[] = "using T = int*;\n" // #11430
"T f() { return T{}; }\n"
"T g() { return T(malloc(4)); }\n";
const char expected[] = "int * f ( ) { return ( int * ) 0 ; } "
"int * g ( ) { return ( int * ) ( malloc ( 4 ) ) ; }";
ASSERT_EQUALS(expected, tok(code, Platform::Type::Native, /*debugwarnings*/ true));
ASSERT_EQUALS("", errout_str());
const char code2[] = "struct S {\n" // #13095
" using reference_type = int&;\n"
" reference_type get();\n"
" int i;\n"
"};\n"
"auto S::get() -> reference_type {\n"
" return i;\n"
"}\n";
const char expected2[] = "struct S { "
"int & get ( ) ; "
"int i ; "
"} ; "
"auto S :: get ( ) . int & { return i ; }";
ASSERT_EQUALS(expected2, tok(code2, Platform::Type::Native, /*debugwarnings*/ true));
TODO_ASSERT_EQUALS("",
"[test.cpp:6]: (debug) auto token with no type.\n"
"", errout_str());
}
void simplifyUsing33() { // #13090
const char code[] = "namespace N {\n"
" using T = int;\n"
" T f() { return (T)0; }\n"
"}\n"
"struct S {\n"
" using U = int;\n"
" U g() { return (U)0; }\n"
"};\n";
const char expected[] = "namespace N { "
"int f ( ) { return ( int ) 0 ; } "
"} "
"struct S { "
"int g ( ) { return ( int ) 0 ; } "
"} ;";
ASSERT_EQUALS(expected, tok(code, Platform::Type::Native, /*debugwarnings*/ true));
ASSERT_EQUALS("", errout_str());
}
void simplifyUsing34() { // #13295
const char code[] = "struct A {\n"
" static const int a = 1;\n"
"};\n"
"using B = struct A;\n"
"void g(int);\n"
"void f() {\n"
" g({ B::a });\n"
"}\n";
const char expected[] = "struct A { "
"static const int a = 1 ; "
"} ; "
"void g ( int ) ; "
"void f ( ) { "
"g ( { A :: a } ) ; "
"}";
ASSERT_EQUALS(expected, tok(code, Platform::Type::Native, /*debugwarnings*/ true));
ASSERT_EQUALS("", errout_str());
}
void simplifyUsing8970() {
const char code[] = "using V = std::vector<int>;\n"
"struct A {\n"
" V p;\n"
"};";
const char expected[] = "struct A { "
"std :: vector < int > p ; "
"} ;";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyUsing8971() {
const char code[] = "class A {\n"
"public:\n"
" using V = std::vector<double>;\n"
"};\n"
"using V = std::vector<int>;\n"
"class I {\n"
"private:\n"
" A::V v_;\n"
" V v2_;\n"
"};";
const char expected[] = "class A { "
"public: "
"} ; "
"class I { "
"private: "
"std :: vector < double > v_ ; "
"std :: vector < int > v2_ ; "
"} ;";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyUsing8976() {
const char code[] = "using mystring = std::string;";
const char exp[] = ";";
ASSERT_EQUALS(exp, tok(code));
}
void simplifyUsing9040() {
const char code[] = "using BOOL = unsigned; int i;";
const char exp[] = "int i ;";
ASSERT_EQUALS(exp, tok(code, Platform::Type::Unix32));
ASSERT_EQUALS(exp, tok(code, Platform::Type::Unix64));
ASSERT_EQUALS(exp, tok(code, Platform::Type::Win32A));
ASSERT_EQUALS(exp, tok(code, Platform::Type::Win32W));
ASSERT_EQUALS(exp, tok(code, Platform::Type::Win64));
}
void simplifyUsing9042() {
const char code[] = "template <class T>\n"
"class c {\n"
" int i = 0;\n"
" c() { i--; }\n"
"};\n"
"template <class T>\n"
"class s {};\n"
"using BOOL = char;";
const char exp[] = "template < class T > "
"class c { "
"int i ; i = 0 ; "
"c ( ) { i -- ; } "
"} ; "
"template < class T > class s { } ;";
ASSERT_EQUALS(exp, tok(code, Platform::Type::Win64));
}
void simplifyUsing9191() {
const char code[] = "namespace NS1 {\n"
" namespace NS2 {\n"
" using _LONG = signed long long;\n"
" }\n"
"}\n"
"void f1() {\n"
" using namespace NS1;\n"
" NS2::_LONG A;\n"
"}\n"
"void f2() {\n"
" using namespace NS1::NS2;\n"
" _LONG A;\n"
"}";
const char exp[] = "void f1 ( ) { "
"using namespace NS1 ; "
"signed long long A ; "
"} "
"void f2 ( ) { "
"using namespace NS1 :: NS2 ; "
"signed long long A ; "
"}";
ASSERT_EQUALS(exp, tok(code));
ASSERT_EQUALS("", errout_str());
}
void simplifyUsing9381() {
const char code[] = "namespace ns {\n"
" class Result;\n"
" using UniqueResultPtr = std::unique_ptr<Result>;\n"
" class A {\n"
" public:\n"
" void func(UniqueResultPtr);\n"
" };\n"
" void A::func(UniqueResultPtr) {\n"
" }\n"
"}";
const char exp[] = "namespace ns { "
"class Result ; "
"class A { "
"public: "
"void func ( std :: unique_ptr < Result > ) ; "
"} ; "
"void A :: func ( std :: unique_ptr < Result > ) { "
"} "
"}";
ASSERT_EQUALS(exp, tok(code));
}
void simplifyUsing9385() {
{
const char code[] = "class A {\n"
"public:\n"
" using Foo = int;\n"
" A(Foo foo);\n"
" ~A();\n"
" void func(Foo foo);\n"
"};\n"
"A::A(Foo) { }\n"
"A::~A() { Foo foo; }\n"
"void A::func(Foo) { }";
const char exp[] = "class A { "
"public: "
"A ( int foo ) ; "
"~ A ( ) ; "
"void func ( int foo ) ; "
"} ; "
"A :: A ( int ) { } "
"A :: ~ A ( ) { int foo ; } "
"void A :: func ( int ) { }";
ASSERT_EQUALS(exp, tok(code));
}
{
const char code[] = "class A {\n"
"public:\n"
" struct B {\n"
" using Foo = int;\n"
" B(Foo foo);\n"
" ~B();\n"
" void func(Foo foo);\n"
" };\n"
"};\n"
"A::B::B(Foo) { }\n"
"A::B::~B() { Foo foo; }\n"
"void A::B::func(Foo) { }";
const char exp[] = "class A { "
"public: "
"struct B { "
"B ( int foo ) ; "
"~ B ( ) ; "
"void func ( int foo ) ; "
"} ; "
"} ; "
"A :: B :: B ( int ) { } "
"A :: B :: ~ B ( ) { int foo ; } "
"void A :: B :: func ( int ) { }";
ASSERT_EQUALS(exp, tok(code));
}
}
void simplifyUsing9388() {
const char code[] = "class A {\n"
"public:\n"
" using Type = int;\n"
" A(Type&);\n"
" Type& t_;\n"
"};\n"
"A::A(Type& t) : t_(t) { }";
const char exp[] = "class A { "
"public: "
"A ( int & ) ; "
"int & t_ ; "
"} ; "
"A :: A ( int & t ) : t_ ( t ) { }";
ASSERT_EQUALS(exp, tok(code));
}
void simplifyUsing9518() {
const char code[] = "namespace a {\n"
"using a = enum {};\n"
"}";
const char exp[] = "namespace a { "
"enum a { } ; "
"}";
ASSERT_EQUALS(exp, tok(code));
}
void simplifyUsing9757() {
const char code[] = "enum class Type_t { Nil = 0 };\n"
"template<Type_t type> class MappedType { };\n"
"template<> class MappedType<Type_t::Nil> { using type = void; };\n"
"std::string to_string (Example::Type_t type) {\n"
" switch (type) {}\n"
"}";
const char exp[] = "enum class Type_t { Nil = 0 } ; "
"class MappedType<Type_t::Nil> ; "
"template < Type_t type > class MappedType { } ; "
"class MappedType<Type_t::Nil> { } ; "
"std :: string to_string ( Example :: Type_t type ) { "
"switch ( type ) { } }";
ASSERT_EQUALS(exp, tok(code));
}
void simplifyUsing10008() {
const char code[] = "namespace ns {\n"
" using ArrayType = std::vector<int>;\n"
"}\n"
"using namespace ns;\n"
"static void f() {\n"
" const ArrayType arr;\n"
"}";
const char exp[] = "using namespace ns ; "
"static void f ( ) { "
"const std :: vector < int > arr ; "
"}";
ASSERT_EQUALS(exp, tok(code));
}
void simplifyUsing10054() { // debug: Executable scope 'x' with unknown function.
{
// original example: using "namespace external::ns1;" but redundant qualification
const char code[] = "namespace external {\n"
" namespace ns1 {\n"
" template <int size> struct B { };\n"
" using V = B<sizeof(bool)>;\n"
" }\n"
"}\n"
"namespace ns {\n"
" struct A {\n"
" void f(external::ns1::V);\n"
" };\n"
"}\n"
"using namespace external::ns1;\n"
"namespace ns {\n"
" void A::f(external::ns1::V) {}\n"
"}";
const char exp[] = "namespace external { "
"namespace ns1 { "
"struct B<1> ; "
"} "
"} "
"namespace ns { "
"struct A { "
"void f ( external :: ns1 :: B<1> ) ; "
"} ; "
"} "
"using namespace external :: ns1 ; "
"namespace ns { "
"void A :: f ( external :: ns1 :: B<1> ) { } "
"} "
"struct external :: ns1 :: B<1> { } ;";
ASSERT_EQUALS(exp, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
// no using "namespace external::ns1;"
const char code[] = "namespace external {\n"
" namespace ns1 {\n"
" template <int size> struct B { };\n"
" using V = B<sizeof(bool)>;\n"
" }\n"
"}\n"
"namespace ns {\n"
" struct A {\n"
" void f(external::ns1::V);\n"
" };\n"
"}\n"
"namespace ns {\n"
" void A::f(external::ns1::V) {}\n"
"}";
const char exp[] = "namespace external { "
"namespace ns1 { "
"struct B<1> ; "
"} "
"} "
"namespace ns { "
"struct A { "
"void f ( external :: ns1 :: B<1> ) ; "
"} ; "
"} "
"namespace ns { "
"void A :: f ( external :: ns1 :: B<1> ) { } "
"} "
"struct external :: ns1 :: B<1> { } ;";
ASSERT_EQUALS(exp, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
// using "namespace external::ns1;" without redundant qualification
const char code[] = "namespace external {\n"
" namespace ns1 {\n"
" template <int size> struct B { };\n"
" using V = B<sizeof(bool)>;\n"
" }\n"
"}\n"
"namespace ns {\n"
" struct A {\n"
" void f(external::ns1::V);\n"
" };\n"
"}\n"
"using namespace external::ns1;\n"
"namespace ns {\n"
" void A::f(V) {}\n"
"}";
const char exp[] = "namespace external { "
"namespace ns1 { "
"struct B<1> ; "
"} "
"} "
"namespace ns { "
"struct A { "
"void f ( external :: ns1 :: B<1> ) ; "
"} ; "
"} "
"using namespace external :: ns1 ; "
"namespace ns { "
"void A :: f ( external :: ns1 :: B<1> ) { } "
"} "
"struct external :: ns1 :: B<1> { } ;";
ASSERT_EQUALS(exp, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
// using "namespace external::ns1;" without redundant qualification on declaration and definition
const char code[] = "namespace external {\n"
" namespace ns1 {\n"
" template <int size> struct B { };\n"
" using V = B<sizeof(bool)>;\n"
" }\n"
"}\n"
"using namespace external::ns1;\n"
"namespace ns {\n"
" struct A {\n"
" void f(V);\n"
" };\n"
"}\n"
"namespace ns {\n"
" void A::f(V) {}\n"
"}";
const char exp[] = "namespace external { "
"namespace ns1 { "
"struct B<1> ; "
"} "
"} "
"using namespace external :: ns1 ; "
"namespace ns { "
"struct A { "
"void f ( external :: ns1 :: B<1> ) ; "
"} ; "
"} "
"namespace ns { "
"void A :: f ( external :: ns1 :: B<1> ) { } "
"} "
"struct external :: ns1 :: B<1> { } ;";
ASSERT_EQUALS(exp, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "namespace external {\n"
" template <int size> struct B { };\n"
" namespace ns1 {\n"
" using V = B<sizeof(bool)>;\n"
" }\n"
"}\n"
"namespace ns {\n"
" struct A {\n"
" void f(external::ns1::V);\n"
" };\n"
"}\n"
"namespace ns {\n"
" void A::f(external::ns1::V) {}\n"
"}";
const char exp[] = "namespace external { "
"struct B<1> ; "
"} "
"namespace ns { "
"struct A { "
"void f ( external :: B<1> ) ; "
"} ; "
"} "
"namespace ns { "
"void A :: f ( external :: B<1> ) { } "
"} "
"struct external :: B<1> { } ;";
ASSERT_EQUALS(exp, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "template <int size> struct B { };\n"
"namespace external {\n"
" namespace ns1 {\n"
" using V = B<sizeof(bool)>;\n"
" }\n"
"}\n"
"namespace ns {\n"
" struct A {\n"
" void f(external::ns1::V);\n"
" };\n"
"}\n"
"namespace ns {\n"
" void A::f(external::ns1::V) {}\n"
"}";
const char exp[] = "struct B<1> ; "
"namespace ns { "
"struct A { "
"void f ( B<1> ) ; "
"} ; "
"} "
"namespace ns { "
"void A :: f ( B<1> ) { } "
"} "
"struct B<1> { } ;";
ASSERT_EQUALS(exp, tok(code));
ASSERT_EQUALS("", errout_str());
}
}
void simplifyUsing10136() {
{
const char code[] = "class B {\n"
"public:\n"
" using V = std::vector<char>;\n"
" virtual void f(const V&) const = 0;\n"
"};\n"
"class A final : public B {\n"
"public:\n"
" void f(const V&) const override;\n"
"};\n"
"void A::f(const std::vector<char>&) const { }";
const char exp[] = "class B { "
"public: "
"virtual void f ( const std :: vector < char > & ) const = 0 ; "
"} ; "
"class A : public B { "
"public: "
"void f ( const std :: vector < char > & ) const override ; "
"} ; "
"void A :: f ( const std :: vector < char > & ) const { }";
ASSERT_EQUALS(exp, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "namespace NS1 {\n"
" class B {\n"
" public:\n"
" using V = std::vector<char>;\n"
" virtual void f(const V&) const = 0;\n"
" };\n"
"}\n"
"namespace NS2 {\n"
" class A : public NS1::B {\n"
" public:\n"
" void f(const V&) const override;\n"
" };\n"
" namespace NS3 {\n"
" class C : public A {\n"
" public:\n"
" void f(const V&) const override;\n"
" };\n"
" void C::f(const V&) const { }\n"
" }\n"
" void A::f(const V&) const { }\n"
"}\n"
"void foo() {\n"
" NS2::A a;\n"
" NS2::NS3::C c;\n"
" NS1::B::V v;\n"
" a.f(v);\n"
" c.f(v);\n"
"}";
const char exp[] = "namespace NS1 { "
"class B { "
"public: "
"virtual void f ( const std :: vector < char > & ) const = 0 ; "
"} ; "
"} "
"namespace NS2 { "
"class A : public NS1 :: B { "
"public: "
"void f ( const std :: vector < char > & ) const override ; "
"} ; "
"namespace NS3 { "
"class C : public A { "
"public: "
"void f ( const std :: vector < char > & ) const override ; "
"} ; "
"void C :: f ( const std :: vector < char > & ) const { } "
"} "
"void A :: f ( const std :: vector < char > & ) const { } "
"} "
"void foo ( ) { "
"NS2 :: A a ; "
"NS2 :: NS3 :: C c ; "
"std :: vector < char > v ; "
"a . f ( v ) ; "
"c . f ( v ) ; "
"}";
ASSERT_EQUALS(exp, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "foo::ResultCodes_e\n"
"GemImpl::setR(const ::foo::s _ipSource)\n"
"{\n"
" M3_LOG_EE_DEBUG();\n"
" using MLSource = foo::s::Literal;\n"
" auto ret = foo::ResultCodes_e::NO_ERROR;\n"
" M3_LOG_INFO(\"foo(\" << static_cast<int>(_ipSource) << \")\");\n"
" return ret;\n"
"}\n"
"foo::ResultCodes_e\n"
"GemImpl::getF(::foo::s &_ipSource)\n"
"{\n"
" M3_LOG_EE_DEBUG();\n"
" auto ret = foo::ResultCodes_e::NO_ERROR;\n"
" return ret;\n"
"}\n"
"foo::ResultCodes_e\n"
"GemImpl::setF(const ::foo::s _ipSource)\n"
"{\n"
" M3_LOG_EE_DEBUG();\n"
" using MLSource = foo::s::Literal;\n"
" auto ret = foo::ResultCodes_e::NO_ERROR;\n"
" return ret;\n"
"}";
(void)tok(code); // don't crash
ignore_errout(); // we do not care about the output
}
}
void simplifyUsing10171() {
const char code[] = "namespace ns {\n"
" class A {\n"
" public:\n"
" using V = std::vector<unsigned char>;\n"
" virtual void f(const V&) const = 0;\n"
" };\n"
" class B : public A {\n"
" public:\n"
" void f(const V&) const override;\n"
" };\n"
"}\n"
"namespace ns {\n"
" void B::f(const std::vector<unsigned char>&) const { }\n"
"}";
const char exp[] = "namespace ns { "
"class A { "
"public: "
"virtual void f ( const std :: vector < unsigned char > & ) const = 0 ; "
"} ; "
"class B : public A { "
"public: "
"void f ( const std :: vector < unsigned char > & ) const override ; "
"} ; "
"} "
"namespace ns { "
"void B :: f ( const std :: vector < unsigned char > & ) const { } "
"}";
ASSERT_EQUALS(exp, tok(code));
ASSERT_EQUALS("", errout_str());
}
void simplifyUsing10172() {
{
const char code[] = "namespace ns {\n"
" class A {\n"
" public:\n"
" using h = std::function<void()>;\n"
" };\n"
" class B : public A {\n"
" void f(h);\n"
" };\n"
"}\n"
"namespace ns {\n"
" void B::f(h) { }\n"
"}";
const char exp[] = "namespace ns { "
"class A { "
"public: "
"} ; "
"class B : public A { "
"void f ( std :: function < void ( ) > ) ; "
"} ; "
"} "
"namespace ns { "
"void B :: f ( std :: function < void ( ) > ) { } "
"}";
ASSERT_EQUALS(exp, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "namespace ns {\n"
"namespace external {\n"
"class A {\n"
"public: \n"
" using h = std::function<void()>;\n"
"};\n"
"class B : public A {\n"
" void f(h);\n"
"};\n"
"}\n"
"}\n"
"namespace ns {\n"
"namespace external {\n"
"void B::f(h) {}\n"
"}\n"
"}";
const char exp[] = "namespace ns { "
"namespace external { "
"class A { "
"public: "
"} ; "
"class B : public A { "
"void f ( std :: function < void ( ) > ) ; "
"} ; "
"} "
"} "
"namespace ns { "
"namespace external { "
"void B :: f ( std :: function < void ( ) > ) { } "
"} "
"}";
ASSERT_EQUALS(exp, tok(code));
ASSERT_EQUALS("", errout_str());
}
}
void simplifyUsing10173() {
{
const char code[] = "std::ostream & operator<<(std::ostream &s, const Pr<st> p) {\n"
" return s;\n"
"}\n"
"void foo() {\n"
" using Pr = d::Pr<st>;\n"
" Pr p;\n"
"}\n"
"void bar() {\n"
" Pr<st> p;\n"
"}";
const char exp[] = "std :: ostream & operator<< ( std :: ostream & s , const Pr < st > p ) { "
"return s ; "
"} "
"void foo ( ) { "
"d :: Pr < st > p ; "
"} "
"void bar ( ) { "
"Pr < st > p ; "
"}";
ASSERT_EQUALS(exp, tok(code));
ASSERT_EQUALS("", errout_str());
}
{
const char code[] = "namespace defsa {\n"
"void xxx::foo() {\n"
" using NS1 = v1::l;\n"
"}\n"
"void xxx::bar() {\n"
" using NS1 = v1::l;\n"
"}\n"
"void xxx::foobar() {\n"
" using NS1 = v1::l;\n"
"}\n"
"}";
const char exp[] = "namespace defsa { "
"void xxx :: foo ( ) { "
"} "
"void xxx :: bar ( ) { "
"} "
"void xxx :: foobar ( ) { "
"} "
"}";
ASSERT_EQUALS(exp, tok(code));
ignore_errout(); // we do not care about the output
}
}
void simplifyUsing10335() {
const char code[] = "using uint8_t = unsigned char;\n"
"enum E : uint8_t { E0 };";
const char exp[] = "enum E : unsigned char { E0 } ;";
ASSERT_EQUALS(exp, tok(code));
}
void simplifyUsing10720() { // hang/segmentation fault
const char code[] = "template <typename... Ts>\n"
"struct S {};\n"
"#define STAMP(thiz, prev) using thiz = S<prev, prev, prev, prev, prev, prev, prev, prev, prev, prev>;\n"
"STAMP(A, int);\n"
"STAMP(B, A);\n"
"STAMP(C, B);\n";
(void)tok(code, Platform::Type::Native, /*debugwarnings*/ true, /*preprocess*/ true);
ASSERT(startsWith(errout_str(), "[test.cpp:6]: (debug) Failed to parse 'using C = S < S < S < int"));
}
void scopeInfo1() {
const char code[] = "struct A {\n"
" enum class Mode { UNKNOWN, ENABLED, NONE, };\n"
"};\n"
"\n"
"namespace spdlog { class logger; }\n"
"using LoggerPtr = std::shared_ptr<spdlog::logger>;";
(void)tok(code);
ASSERT_EQUALS("", errout_str());
}
void scopeInfo2() {
const char code[] = "struct A {\n"
" using Map = std::map<int, int>;\n"
" Map values;\n"
"};\n"
"\n"
"static void getInitialProgramState(const A::Map& vars = A::Map {})\n"
"{}\n";
(void)tok(code);
ASSERT_EQUALS("", errout_str());
}
};
REGISTER_TEST(TestSimplifyUsing)
| null |
960 | cpp | cppcheck | testcppcheck.cpp | test/testcppcheck.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "color.h"
#include "cppcheck.h"
#include "errorlogger.h"
#include "filesettings.h"
#include "fixture.h"
#include "helpers.h"
#include "settings.h"
#include "simplecpp.h"
#include <algorithm>
#include <list>
#include <string>
#include <vector>
class TestCppcheck : public TestFixture {
public:
TestCppcheck() : TestFixture("TestCppcheck") {}
private:
class ErrorLogger2 : public ErrorLogger {
public:
std::list<std::string> ids;
std::list<ErrorMessage> errmsgs;
private:
void reportOut(const std::string & /*outmsg*/, Color /*c*/ = Color::Reset) override {}
void reportErr(const ErrorMessage &msg) override {
ids.push_back(msg.id);
errmsgs.push_back(msg);
}
};
void run() override {
TEST_CASE(getErrorMessages);
TEST_CASE(checkWithFile);
TEST_CASE(checkWithFS);
TEST_CASE(suppress_error_library);
TEST_CASE(unique_errors);
TEST_CASE(isPremiumCodingStandardId);
TEST_CASE(getDumpFileContentsRawTokens);
TEST_CASE(getDumpFileContentsLibrary);
TEST_CASE(getClangFlagsIncludeFile);
}
void getErrorMessages() const {
ErrorLogger2 errorLogger;
CppCheck::getErrorMessages(errorLogger);
ASSERT(!errorLogger.ids.empty());
// Check if there are duplicate error ids in errorLogger.id
std::string duplicate;
for (std::list<std::string>::const_iterator it = errorLogger.ids.cbegin();
it != errorLogger.ids.cend();
++it) {
if (std::find(errorLogger.ids.cbegin(), it, *it) != it) {
duplicate = "Duplicate ID: " + *it;
break;
}
}
ASSERT_EQUALS("", duplicate);
// Check for error ids from this class.
bool foundPurgedConfiguration = false;
bool foundTooManyConfigs = false;
bool foundMissingInclude = false; // #11984
bool foundMissingIncludeSystem = false; // #11984
for (const std::string & it : errorLogger.ids) {
if (it == "purgedConfiguration")
foundPurgedConfiguration = true;
else if (it == "toomanyconfigs")
foundTooManyConfigs = true;
else if (it == "missingInclude")
foundMissingInclude = true;
else if (it == "missingIncludeSystem")
foundMissingIncludeSystem = true;
}
ASSERT(foundPurgedConfiguration);
ASSERT(foundTooManyConfigs);
ASSERT(foundMissingInclude);
ASSERT(foundMissingIncludeSystem);
}
void checkWithFile() const
{
ScopedFile file("test.cpp",
"int main()\n"
"{\n"
" int i = *((int*)0);\n"
" return 0;\n"
"}");
ErrorLogger2 errorLogger;
CppCheck cppcheck(errorLogger, false, {});
ASSERT_EQUALS(1, cppcheck.check(FileWithDetails(file.path())));
// TODO: how to properly disable these warnings?
errorLogger.ids.erase(std::remove_if(errorLogger.ids.begin(), errorLogger.ids.end(), [](const std::string& id) {
return id == "logChecker";
}), errorLogger.ids.end());
ASSERT_EQUALS(1, errorLogger.ids.size());
ASSERT_EQUALS("nullPointer", *errorLogger.ids.cbegin());
}
void checkWithFS() const
{
ScopedFile file("test.cpp",
"int main()\n"
"{\n"
" int i = *((int*)0);\n"
" return 0;\n"
"}");
ErrorLogger2 errorLogger;
CppCheck cppcheck(errorLogger, false, {});
FileSettings fs{file.path()};
ASSERT_EQUALS(1, cppcheck.check(fs));
// TODO: how to properly disable these warnings?
errorLogger.ids.erase(std::remove_if(errorLogger.ids.begin(), errorLogger.ids.end(), [](const std::string& id) {
return id == "logChecker";
}), errorLogger.ids.end());
ASSERT_EQUALS(1, errorLogger.ids.size());
ASSERT_EQUALS("nullPointer", *errorLogger.ids.cbegin());
}
void suppress_error_library() const
{
ScopedFile file("test.cpp",
"int main()\n"
"{\n"
" int i = *((int*)0);\n"
" return 0;\n"
"}");
ErrorLogger2 errorLogger;
CppCheck cppcheck(errorLogger, false, {});
const char xmldata[] = R"(<def format="2"><markup ext=".cpp" reporterrors="false"/></def>)";
const Settings s = settingsBuilder().libraryxml(xmldata, sizeof(xmldata)).build();
cppcheck.settings() = s;
ASSERT_EQUALS(0, cppcheck.check(FileWithDetails(file.path())));
// TODO: how to properly disable these warnings?
errorLogger.ids.erase(std::remove_if(errorLogger.ids.begin(), errorLogger.ids.end(), [](const std::string& id) {
return id == "logChecker";
}), errorLogger.ids.end());
ASSERT_EQUALS(0, errorLogger.ids.size());
}
// TODO: hwo to actually get duplicated findings
void unique_errors() const
{
ScopedFile file("inc.h",
"inline void f()\n"
"{\n"
" (void)*((int*)0);\n"
"}");
ScopedFile test_file_a("a.cpp",
"#include \"inc.h\"");
ScopedFile test_file_b("b.cpp",
"#include \"inc.h\"");
ErrorLogger2 errorLogger;
CppCheck cppcheck(errorLogger, false, {});
ASSERT_EQUALS(1, cppcheck.check(FileWithDetails(test_file_a.path())));
ASSERT_EQUALS(1, cppcheck.check(FileWithDetails(test_file_b.path())));
// TODO: how to properly disable these warnings?
errorLogger.errmsgs.erase(std::remove_if(errorLogger.errmsgs.begin(), errorLogger.errmsgs.end(), [](const ErrorMessage& msg) {
return msg.id == "logChecker";
}), errorLogger.errmsgs.end());
// the internal errorlist is cleared after each check() call
ASSERT_EQUALS(2, errorLogger.errmsgs.size());
auto it = errorLogger.errmsgs.cbegin();
ASSERT_EQUALS("nullPointer", it->id);
++it;
ASSERT_EQUALS("nullPointer", it->id);
}
void isPremiumCodingStandardId() const {
ErrorLogger2 errorLogger;
CppCheck cppcheck(errorLogger, false, {});
cppcheck.settings().premiumArgs = "";
ASSERT_EQUALS(false, cppcheck.isPremiumCodingStandardId("misra-c2012-0.0"));
ASSERT_EQUALS(false, cppcheck.isPremiumCodingStandardId("misra-c2023-0.0"));
ASSERT_EQUALS(false, cppcheck.isPremiumCodingStandardId("premium-misra-c2012-0.0"));
ASSERT_EQUALS(false, cppcheck.isPremiumCodingStandardId("premium-misra-c2023-0.0"));
ASSERT_EQUALS(false, cppcheck.isPremiumCodingStandardId("premium-misra-c++2008-0.0.0"));
ASSERT_EQUALS(false, cppcheck.isPremiumCodingStandardId("premium-misra-c++2023-0.0.0"));
ASSERT_EQUALS(false, cppcheck.isPremiumCodingStandardId("premium-cert-int50-cpp"));
ASSERT_EQUALS(false, cppcheck.isPremiumCodingStandardId("premium-autosar-0-0-0"));
cppcheck.settings().premiumArgs = "--misra-c-2012 --cert-c++-2016 --autosar";
ASSERT_EQUALS(true, cppcheck.isPremiumCodingStandardId("misra-c2012-0.0"));
ASSERT_EQUALS(true, cppcheck.isPremiumCodingStandardId("misra-c2023-0.0"));
ASSERT_EQUALS(true, cppcheck.isPremiumCodingStandardId("premium-misra-c2012-0.0"));
ASSERT_EQUALS(true, cppcheck.isPremiumCodingStandardId("premium-misra-c2023-0.0"));
ASSERT_EQUALS(true, cppcheck.isPremiumCodingStandardId("premium-misra-c++2008-0.0.0"));
ASSERT_EQUALS(true, cppcheck.isPremiumCodingStandardId("premium-misra-c++2023-0.0.0"));
ASSERT_EQUALS(true, cppcheck.isPremiumCodingStandardId("premium-cert-int50-cpp"));
ASSERT_EQUALS(true, cppcheck.isPremiumCodingStandardId("premium-autosar-0-0-0"));
}
void getDumpFileContentsRawTokens() const {
ErrorLogger2 errorLogger;
CppCheck cppcheck(errorLogger, false, {});
cppcheck.settings() = settingsBuilder().build();
cppcheck.settings().relativePaths = true;
cppcheck.settings().basePaths.emplace_back("/some/path");
std::vector<std::string> files{"/some/path/test.cpp"};
simplecpp::TokenList tokens1(files);
const std::string expected = " <rawtokens>\n"
" <file index=\"0\" name=\"test.cpp\"/>\n"
" </rawtokens>\n";
ASSERT_EQUALS(expected, cppcheck.getDumpFileContentsRawTokens(files, tokens1));
}
void getDumpFileContentsLibrary() const {
ErrorLogger2 errorLogger;
CppCheck cppcheck(errorLogger, false, {});
cppcheck.settings().libraries.emplace_back("std.cfg");
std::vector<std::string> files{ "/some/path/test.cpp" };
const std::string expected1 = " <library lib=\"std.cfg\"/>\n";
ASSERT_EQUALS(expected1, cppcheck.getLibraryDumpData());
cppcheck.settings().libraries.emplace_back("posix.cfg");
const std::string expected2 = " <library lib=\"std.cfg\"/>\n <library lib=\"posix.cfg\"/>\n";
ASSERT_EQUALS(expected2, cppcheck.getLibraryDumpData());
}
void getClangFlagsIncludeFile() const {
ErrorLogger2 errorLogger;
CppCheck cppcheck(errorLogger, false, {});
cppcheck.settings().userIncludes.emplace_back("1.h");
ASSERT_EQUALS("-x c --include 1.h ", cppcheck.getClangFlags(Standards::Language::C));
}
// TODO: test suppressions
// TODO: test all with FS
};
REGISTER_TEST(TestCppcheck)
| null |
961 | cpp | cppcheck | testother.cpp | test/testother.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "checkother.h"
#include "errortypes.h"
#include "fixture.h"
#include "helpers.h"
#include "platform.h"
#include "settings.h"
#include "standards.h"
#include "tokenize.h"
#include <cstddef>
#include <string>
#include <vector>
class TestOther : public TestFixture {
public:
TestOther() : TestFixture("TestOther") {}
private:
/*const*/ Settings _settings = settingsBuilder().library("std.cfg").build();
void run() override {
TEST_CASE(emptyBrackets);
TEST_CASE(zeroDiv1);
TEST_CASE(zeroDiv2);
TEST_CASE(zeroDiv3);
TEST_CASE(zeroDiv4);
TEST_CASE(zeroDiv5);
TEST_CASE(zeroDiv6);
TEST_CASE(zeroDiv7); // #4930
TEST_CASE(zeroDiv8);
TEST_CASE(zeroDiv9);
TEST_CASE(zeroDiv10);
TEST_CASE(zeroDiv11);
TEST_CASE(zeroDiv12);
TEST_CASE(zeroDiv13);
TEST_CASE(zeroDiv14); // #1169
TEST_CASE(zeroDiv15); // #8319
TEST_CASE(zeroDiv16); // #11158
TEST_CASE(zeroDiv17); // #9931
TEST_CASE(zeroDiv18);
TEST_CASE(zeroDiv19);
TEST_CASE(zeroDiv20); // #11175
TEST_CASE(zeroDivCond); // division by zero / useless condition
TEST_CASE(nanInArithmeticExpression);
TEST_CASE(varScope1);
TEST_CASE(varScope2);
TEST_CASE(varScope3);
TEST_CASE(varScope4);
TEST_CASE(varScope5);
TEST_CASE(varScope6);
TEST_CASE(varScope7);
TEST_CASE(varScope8);
TEST_CASE(varScope9); // classes may have extra side-effects
TEST_CASE(varScope10); // Undefined macro FOR
TEST_CASE(varScope11); // #2475 - struct initialization is not inner scope
TEST_CASE(varScope12);
TEST_CASE(varScope13); // variable usage in inner loop
TEST_CASE(varScope14);
TEST_CASE(varScope15); // #4573 if-else-if
TEST_CASE(varScope16);
TEST_CASE(varScope17);
TEST_CASE(varScope18);
TEST_CASE(varScope20); // Ticket #5103
TEST_CASE(varScope21); // Ticket #5382
TEST_CASE(varScope22); // Ticket #5684
TEST_CASE(varScope23); // Ticket #6154
TEST_CASE(varScope24); // pointer / reference
TEST_CASE(varScope25); // time_t
TEST_CASE(varScope26); // range for loop, map
TEST_CASE(varScope27); // #7733 - #if
TEST_CASE(varScope28); // #10527
TEST_CASE(varScope29); // #10888
TEST_CASE(varScope30); // #8541
TEST_CASE(varScope31); // #11099
TEST_CASE(varScope32); // #11441
TEST_CASE(varScope33);
TEST_CASE(varScope34);
TEST_CASE(varScope35);
TEST_CASE(varScope36); // #12158
TEST_CASE(varScope37); // #12158
TEST_CASE(varScope38);
TEST_CASE(varScope39);
TEST_CASE(varScope40);
TEST_CASE(varScope41); // #11845
TEST_CASE(varScope42);
TEST_CASE(oldStylePointerCast);
TEST_CASE(invalidPointerCast);
TEST_CASE(passedByValue);
TEST_CASE(passedByValue_nonConst);
TEST_CASE(passedByValue_externC);
TEST_CASE(constVariable);
TEST_CASE(constParameterCallback);
TEST_CASE(constPointer);
TEST_CASE(constArray);
TEST_CASE(switchRedundantAssignmentTest);
TEST_CASE(switchRedundantOperationTest);
TEST_CASE(switchRedundantBitwiseOperationTest);
TEST_CASE(unreachableCode);
TEST_CASE(redundantContinue);
TEST_CASE(suspiciousCase);
TEST_CASE(suspiciousEqualityComparison);
TEST_CASE(suspiciousUnaryPlusMinus); // #8004
TEST_CASE(suspiciousFloatingPointCast);
TEST_CASE(selfAssignment);
TEST_CASE(trac1132);
TEST_CASE(testMisusedScopeObjectDoesNotPickFunction1);
TEST_CASE(testMisusedScopeObjectDoesNotPickFunction2);
TEST_CASE(testMisusedScopeObjectPicksClass);
TEST_CASE(testMisusedScopeObjectPicksStruct);
TEST_CASE(testMisusedScopeObjectDoesNotPickIf);
TEST_CASE(testMisusedScopeObjectDoesNotPickConstructorDeclaration);
TEST_CASE(testMisusedScopeObjectDoesNotPickFunctor);
TEST_CASE(testMisusedScopeObjectDoesNotPickLocalClassConstructors);
TEST_CASE(testMisusedScopeObjectDoesNotPickUsedObject);
TEST_CASE(testMisusedScopeObjectDoesNotPickPureC);
TEST_CASE(testMisusedScopeObjectDoesNotPickNestedClass);
TEST_CASE(testMisusedScopeObjectInConstructor);
TEST_CASE(testMisusedScopeObjectStandardType);
TEST_CASE(testMisusedScopeObjectNamespace);
TEST_CASE(testMisusedScopeObjectAssignment); // #11371
TEST_CASE(trac2071);
TEST_CASE(trac2084);
TEST_CASE(trac3693);
TEST_CASE(clarifyCalculation);
TEST_CASE(clarifyStatement);
TEST_CASE(duplicateBranch);
TEST_CASE(duplicateBranch1); // tests extracted by http://www.viva64.com/en/b/0149/ ( Comparison between PVS-Studio and cppcheck ): Errors detected in Quake 3: Arena by PVS-Studio: Fragment 2
TEST_CASE(duplicateBranch2); // empty macro
TEST_CASE(duplicateBranch3);
TEST_CASE(duplicateBranch4);
TEST_CASE(duplicateBranch5); // make sure the Token attributes are compared
TEST_CASE(duplicateBranch6);
TEST_CASE(duplicateExpression1);
TEST_CASE(duplicateExpression2); // ticket #2730
TEST_CASE(duplicateExpression3); // ticket #3317
TEST_CASE(duplicateExpression4); // ticket #3354 (++)
TEST_CASE(duplicateExpression5); // ticket #3749 (macros with same values)
TEST_CASE(duplicateExpression6); // ticket #4639
TEST_CASE(duplicateExpression7);
TEST_CASE(duplicateExpression8);
TEST_CASE(duplicateExpression9); // #9320
TEST_CASE(duplicateExpression10); // #9485
TEST_CASE(duplicateExpression11); // #8916 (function call)
TEST_CASE(duplicateExpression12); // #10026
TEST_CASE(duplicateExpression13); // #7899
TEST_CASE(duplicateExpression14); // #9871
TEST_CASE(duplicateExpression15); // #10650
TEST_CASE(duplicateExpression16); // #10569
TEST_CASE(duplicateExpression17); // #12036
TEST_CASE(duplicateExpression18);
TEST_CASE(duplicateExpressionLoop);
TEST_CASE(duplicateValueTernary);
TEST_CASE(duplicateExpressionTernary); // #6391
TEST_CASE(duplicateExpressionTemplate); // #6930
TEST_CASE(duplicateExpressionCompareWithZero);
TEST_CASE(oppositeExpression);
TEST_CASE(duplicateVarExpression);
TEST_CASE(duplicateVarExpressionUnique);
TEST_CASE(duplicateVarExpressionAssign);
TEST_CASE(duplicateVarExpressionCrash);
TEST_CASE(multiConditionSameExpression);
TEST_CASE(checkSignOfUnsignedVariable);
TEST_CASE(checkSignOfPointer);
TEST_CASE(checkSuspiciousSemicolon1);
TEST_CASE(checkSuspiciousSemicolon2);
TEST_CASE(checkSuspiciousSemicolon3);
TEST_CASE(checkSuspiciousComparison);
TEST_CASE(checkInvalidFree);
TEST_CASE(checkRedundantCopy);
TEST_CASE(checkNegativeShift);
TEST_CASE(incompleteArrayFill);
TEST_CASE(redundantVarAssignment);
TEST_CASE(redundantVarAssignment_trivial);
TEST_CASE(redundantVarAssignment_struct);
TEST_CASE(redundantVarAssignment_union);
TEST_CASE(redundantVarAssignment_7133);
TEST_CASE(redundantVarAssignment_stackoverflow);
TEST_CASE(redundantVarAssignment_lambda);
TEST_CASE(redundantVarAssignment_loop);
TEST_CASE(redundantVarAssignment_after_switch);
TEST_CASE(redundantVarAssignment_pointer);
TEST_CASE(redundantVarAssignment_pointer_parameter);
TEST_CASE(redundantVarAssignment_array);
TEST_CASE(redundantVarAssignment_switch_break);
TEST_CASE(redundantInitialization);
//TEST_CASE(redundantMemWrite); // FIXME: temporary hack
TEST_CASE(redundantAssignmentSameValue);
TEST_CASE(varFuncNullUB);
TEST_CASE(checkCastIntToCharAndBack); // ticket #160
TEST_CASE(checkCommaSeparatedReturn);
TEST_CASE(checkPassByReference);
TEST_CASE(checkComparisonFunctionIsAlwaysTrueOrFalse);
TEST_CASE(integerOverflow); // #5895
TEST_CASE(redundantPointerOp);
TEST_CASE(test_isSameExpression);
TEST_CASE(raceAfterInterlockedDecrement);
TEST_CASE(testUnusedLabel);
TEST_CASE(testEvaluationOrder);
TEST_CASE(testEvaluationOrderSelfAssignment);
TEST_CASE(testEvaluationOrderMacro);
TEST_CASE(testEvaluationOrderSequencePointsFunctionCall);
TEST_CASE(testEvaluationOrderSequencePointsComma);
TEST_CASE(testEvaluationOrderSizeof);
TEST_CASE(testUnsignedLessThanZero);
TEST_CASE(doubleMove1);
TEST_CASE(doubleMoveMemberInitialization1);
TEST_CASE(doubleMoveMemberInitialization2);
TEST_CASE(doubleMoveMemberInitialization3); // #9974
TEST_CASE(doubleMoveMemberInitialization4);
TEST_CASE(moveAndAssign1);
TEST_CASE(moveAndAssign2);
TEST_CASE(moveAssignMoveAssign);
TEST_CASE(moveAndReset1);
TEST_CASE(moveAndReset2);
TEST_CASE(moveResetMoveReset);
TEST_CASE(moveAndFunctionParameter);
TEST_CASE(moveAndFunctionParameterReference);
TEST_CASE(moveAndFunctionParameterConstReference);
TEST_CASE(moveAndFunctionParameterUnknown);
TEST_CASE(moveAndReturn);
TEST_CASE(moveAndClear);
TEST_CASE(movedPointer);
TEST_CASE(moveAndAddressOf);
TEST_CASE(partiallyMoved);
TEST_CASE(moveAndLambda);
TEST_CASE(moveInLoop);
TEST_CASE(moveCallback);
TEST_CASE(moveClassVariable);
TEST_CASE(forwardAndUsed);
TEST_CASE(moveAndReference);
TEST_CASE(moveForRange);
TEST_CASE(moveTernary);
TEST_CASE(funcArgNamesDifferent);
TEST_CASE(funcArgOrderDifferent);
TEST_CASE(cpp11FunctionArgInit); // #7846 - "void foo(int declaration = {}) {"
TEST_CASE(shadowVariables);
TEST_CASE(knownArgument);
TEST_CASE(knownArgumentHiddenVariableExpression);
TEST_CASE(knownArgumentTernaryOperator);
TEST_CASE(checkComparePointers);
TEST_CASE(unusedVariableValueTemplate); // #8994
TEST_CASE(moduloOfOne);
TEST_CASE(sameExpressionPointers);
TEST_CASE(checkOverlappingWrite);
TEST_CASE(constVariableArrayMember); // #10371
TEST_CASE(knownPointerToBool);
TEST_CASE(iterateByValue);
}
#define check(...) check_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
void check_(const char* file, int line, const char (&code)[size], bool cpp = true, bool inconclusive = true, bool runSimpleChecks=true, bool verbose=false, Settings* settings = nullptr) {
if (!settings) {
settings = &_settings;
}
settings->severity.enable(Severity::style);
settings->severity.enable(Severity::warning);
settings->severity.enable(Severity::portability);
settings->severity.enable(Severity::performance);
settings->standards.c = Standards::CLatest;
settings->standards.cpp = Standards::CPPLatest;
settings->certainty.setEnabled(Certainty::inconclusive, inconclusive);
settings->verbose = verbose;
// Tokenize..
SimpleTokenizer tokenizer(*settings, *this);
ASSERT_LOC(tokenizer.tokenize(code, cpp), file, line);
// Check..
runChecks<CheckOther>(tokenizer, this);
(void)runSimpleChecks; // TODO Remove this
}
template<size_t size>
void check_(const char* file, int line, const char (&code)[size], Settings *s) {
check_(file, line, code, true, true, true, false, s);
}
#define checkP(...) checkP_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
void checkP_(const char* file, int line, const char (&code)[size], const char *filename = "test.cpp") {
Settings* settings = &_settings;
settings->severity.enable(Severity::style);
settings->severity.enable(Severity::warning);
settings->severity.enable(Severity::portability);
settings->severity.enable(Severity::performance);
settings->standards.c = Standards::CLatest;
settings->standards.cpp = Standards::CPPLatest;
settings->certainty.enable(Certainty::inconclusive);
std::vector<std::string> files(1, filename);
Tokenizer tokenizer(*settings, *this);
PreprocessorHelper::preprocess(code, files, tokenizer, *this);
// Tokenizer..
ASSERT_LOC(tokenizer.simplifyTokens1(""), file, line);
// Check..
runChecks<CheckOther>(tokenizer, this);
}
template<size_t size>
void checkInterlockedDecrement(const char (&code)[size]) {
/*const*/ Settings settings = settingsBuilder().platform(Platform::Type::Win32A).build();
check(code, true, false, true, false, &settings);
}
void emptyBrackets() {
check("{\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void zeroDiv1() { // floating point division by zero => no error
check("void foo() {\n"
" cout << 1. / 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" cout << 42 / (double)0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" cout << 42 / (float)0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" cout << 42 / (int)0;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Division by zero.\n", errout_str());
}
void zeroDiv2() {
check("void foo()\n"
"{\n"
" int sum = 0;\n"
" for(int i = 0; i < n; i ++)\n"
" {\n"
" sum += i;\n"
" }\n"
" cout<<b/sum;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void zeroDiv3() {
check("int foo(int i) {\n"
" return i / 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Division by zero.\n", errout_str());
check("int foo(int i) {\n"
" return i % 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Division by zero.\n", errout_str());
check("void foo(int& i) {\n"
" i /= 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Division by zero.\n", errout_str());
check("void foo(int& i) {\n"
" i %= 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Division by zero.\n", errout_str());
check("uint8_t foo(uint8_t i) {\n"
" return i / 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Division by zero.\n", errout_str());
}
void zeroDiv4() {
check("void f()\n"
"{\n"
" long a = b / 0x6;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f()\n"
"{\n"
" long a = b / 0x0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(long b)\n"
"{\n"
" long a = b / 0x0;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Division by zero.\n", errout_str());
check("void f()\n"
"{\n"
" long a = b / 0L;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(long b)\n"
"{\n"
" long a = b / 0L;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Division by zero.\n", errout_str());
check("void f()\n"
"{\n"
" long a = b / 0ul;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(long b)\n"
"{\n"
" long a = b / 0ul;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Division by zero.\n", errout_str());
// Don't warn about floating points (gcc doesn't warn either)
// and floating points are handled differently than integers.
check("void f()\n"
"{\n"
" long a = b / 0.0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f()\n"
"{\n"
" long a = b / 0.5;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void zeroDiv5() {
check("void f()\n"
"{ { {\n"
" long a = b / 0;\n"
"} } }");
ASSERT_EQUALS("", errout_str());
check("void f(long b)\n"
"{ { {\n"
" long a = b / 0;\n"
"} } }");
ASSERT_EQUALS("[test.cpp:3]: (error) Division by zero.\n", errout_str());
}
void zeroDiv6() {
check("void f()\n"
"{ { {\n"
" int a = b % 0;\n"
"} } }");
ASSERT_EQUALS("", errout_str());
check("void f(int b)\n"
"{ { {\n"
" int a = b % 0;\n"
"} } }");
ASSERT_EQUALS("[test.cpp:3]: (error) Division by zero.\n", errout_str());
}
void zeroDiv7() {
// unknown types for x and y --> do not warn
check("void f() {\n"
" int a = x/2*3/0;\n"
" int b = y/2*3%0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x, int y) {\n"
" int a = x/2*3/0;\n"
" int b = y/2*3%0;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Division by zero.\n"
"[test.cpp:3]: (error) Division by zero.\n", errout_str());
}
void zeroDiv8() {
// #5584 - FP when function is unknown
check("void f() {\n"
" int a = 0;\n"
" do_something(a);\n"
" return 4 / a;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error, inconclusive) Division by zero.\n", errout_str());
}
void zeroDiv9() {
// #6403 FP zerodiv - inside protecting if-clause
check("void foo() {\n"
" double fStepHelp = 0;\n"
" if( (rOuterValue >>= fStepHelp) ) {\n"
" if( fStepHelp != 0.0) {\n"
" double fStepMain = 1;\n"
" sal_Int32 nIntervalCount = static_cast< sal_Int32 >(fStepMain / fStepHelp);\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void zeroDiv10() {
// #5402 false positive: (error) Division by zero -- with boost::format
check("int main() {\n"
" std::cout\n"
" << boost::format(\" %d :: %s <> %s\") % 0 % \"a\" % \"b\"\n"
" << std::endl;\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void zeroDiv11() {
check("void f(int a) {\n"
" int res = (a+2)/0;\n"
" int res = (a*2)/0;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Division by zero.\n"
"[test.cpp:3]: (error) Division by zero.\n", errout_str());
check("void f() {\n"
" int res = (a+2)/0;\n"
" int res = (a*2)/0;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void zeroDiv12() {
// #8141
check("intmax_t f() {\n"
" return 1 / imaxabs(0);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Division by zero.\n", errout_str());
}
void zeroDiv13() {
// #7324
check("int f () {\n"
" int dividend = 10;\n"
" int divisor = 1;\n"
" dividend = dividend / (--divisor);\n"
" return dividend;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (error) Division by zero.\n", errout_str());
}
void zeroDiv14() {
check("void f() {\n" // #1169
" double dx = 1.;\n"
" int ix = 1;\n"
" int i = 1;\n"
" std::cout << ix / (i >> 1) << std::endl;\n"
" std::cout << dx / (i >> 1) << std::endl;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5]: (error) Division by zero.\n", errout_str());
}
void zeroDiv15() { // #8319
check("int f(int i) { return i - 1; }\n"
"int f() {\n"
" const int d = 1;\n"
" const int r = 1 / f(d);\n"
" return r;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (error) Division by zero.\n", errout_str());
}
// #11158
void zeroDiv16()
{
check("int f(int i) {\n"
" int number = 10, a = 0;\n"
" for (int count = 0; count < 2; count++) {\n"
" a += (i / number) % 10;\n"
" number = number / 10;\n"
" }\n"
" return a;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("int f(int i) {\n"
" int number = 10, a = 0;\n"
" for (int count = 0; count < 2; count++) {\n"
" int x = number / 10;\n"
" a += (i / number) % 10;\n"
" number = x;\n"
" }\n"
" return a;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void zeroDiv17() { // #9931
check("int f(int len) {\n"
" int sz = sizeof(void*[255]) / 255;\n"
" int x = len % sz;\n"
" return x;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void zeroDiv18()
{
check("int f(int x, int y) {\n"
" if (x == y) {}\n"
" return 1 / (x-y);\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:2] -> [test.cpp:3]: (warning) Either the condition 'x==y' is redundant or there is division by zero at line 3.\n",
errout_str());
}
void zeroDiv19()
{
check("void f() {\n" // #2456
" for (int i = 0;;)\n"
" int j = 10 / i;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Division by zero.\n", errout_str());
}
void zeroDiv20()
{
check("uint16_t f(void)\n" // #11175
"{\n"
" uint16_t x = 0xFFFFU;\n" // UINT16_MAX=0xFFFF
" return 42/(++x);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Division by zero.\n", errout_str());
}
void zeroDivCond() {
check("void f(unsigned int x) {\n"
" int y = 17 / x;\n"
" if (x > 0) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:2]: (warning) Either the condition 'x>0' is redundant or there is division by zero at line 2.\n", errout_str());
check("void f(unsigned int x) {\n"
" int y = 17 / x;\n"
" if (x >= 1) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:2]: (warning) Either the condition 'x>=1' is redundant or there is division by zero at line 2.\n", errout_str());
check("void f(int x) {\n"
" int y = 17 / x;\n"
" if (x == 0) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:2]: (warning) Either the condition 'x==0' is redundant or there is division by zero at line 2.\n", errout_str());
check("void f(unsigned int x) {\n"
" int y = 17 / x;\n"
" if (x != 0) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:2]: (warning) Either the condition 'x!=0' is redundant or there is division by zero at line 2.\n", errout_str());
// function call
check("void f1(int x, int y) { c=x/y; }\n"
"void f2(unsigned int y) {\n"
" f1(123,y);\n"
" if (y>0){}\n"
"}");
ASSERT_EQUALS(
"[test.cpp:4] -> [test.cpp:1]: (warning) Either the condition 'y>0' is redundant or there is division by zero at line 1.\n",
errout_str());
// avoid false positives when variable is changed after division
check("void f() {\n"
" unsigned int x = do_something();\n"
" int y = 17 / x;\n"
" x = some+calculation;\n"
" if (x != 0) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
{
// function is called that might modify global variable
check("void do_something();\n"
"int x;\n"
"void f() {\n"
" int y = 17 / x;\n"
" do_something();\n"
" if (x != 0) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
// function is called. but don't care, variable is local
check("void do_something();\n"
"void f() {\n"
" int x = some + calculation;\n"
" int y = 17 / x;\n"
" do_something();\n"
" if (x != 0) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:6] -> [test.cpp:4]: (warning) Either the condition 'x!=0' is redundant or there is division by zero at line 4.\n", errout_str());
}
check("void do_something(int value);\n"
"void f(int x) {\n"
" int y = 17 / x;\n"
" do_something(x);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int x;\n"
"void f() {\n"
" int y = 17 / x;\n"
" while (y || x == 0) { x--; }\n"
"}");
ASSERT_EQUALS("", errout_str());
// ticket 5033 segmentation fault (valid code) in CheckOther::checkZeroDivisionOrUselessCondition
check("void f() {\n"
"double* p1= new double[1];\n"
"double* p2= new double[1];\n"
"double* p3= new double[1];\n"
"double* pp[3] = {p1,p2,p3};\n"
"}");
ASSERT_EQUALS("", errout_str());
// #5105 - FP
check("int f(int a, int b) {\n"
" int r = a / b;\n"
" if (func(b)) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
// Unknown types for b and c --> do not warn
check("int f(int d) {\n"
" int r = (a?b:c) / d;\n"
" if (d == 0) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f(int a) {\n"
" int r = a ? 1 / a : 0;\n"
" if (a == 0) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f(int a) {\n"
" int r = (a == 0) ? 0 : 1 / a;\n"
" if (a == 0) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int g();\n"
"void f(int b) {\n"
" int x = g();\n"
" if (x == 0) {}\n"
" else if (x > 0) {}\n"
" else\n"
" a = b / -x;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct A {\n"
" int x;\n"
"};\n"
"int f(A* a) {\n"
" if (a->x == 0) \n"
" a->x = 1;\n"
" return 1/a->x;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #10049
check("int f(int argc) {\n"
" int quotient, remainder;\n"
" remainder = argc % 2;\n"
" argc = 2;\n"
" quotient = argc;\n"
" if (quotient != 0) \n"
" return quotient;\n"
" return remainder;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #11315
checkP("#define STATIC_ASSERT(c) \\\n"
"do { enum { sa = 1/(int)(!!(c)) }; } while (0)\n"
"void f() {\n"
" STATIC_ASSERT(sizeof(int) == sizeof(FOO));\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #11505
check("void f(uint16_t num, uint8_t radix) {\n"
" int c = num % radix;\n"
" num /= radix;\n"
" if (!num) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void nanInArithmeticExpression() {
check("void f()\n"
"{\n"
" double x = 3.0 / 0.0 + 1.0;\n"
" printf(\"%f\", x);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Using NaN/Inf in a computation.\n", errout_str());
check("void f()\n"
"{\n"
" double x = 3.0 / 0.0 - 1.0;\n"
" printf(\"%f\", x);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Using NaN/Inf in a computation.\n", errout_str());
check("void f()\n"
"{\n"
" double x = 1.0 + 3.0 / 0.0;\n"
" printf(\"%f\", x);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Using NaN/Inf in a computation.\n", errout_str());
check("void f()\n"
"{\n"
" double x = 1.0 - 3.0 / 0.0;\n"
" printf(\"%f\", x);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Using NaN/Inf in a computation.\n", errout_str());
check("void f()\n"
"{\n"
" double x = 3.0 / 0.0;\n"
" printf(\"%f\", x);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void varScope1() {
check("unsigned short foo()\n"
"{\n"
" test_client CClient;\n"
" try\n"
" {\n"
" if (CClient.Open())\n"
" {\n"
" return 0;\n"
" }\n"
" }\n"
" catch (...)\n"
" {\n"
" return 2;\n"
" }\n"
"\n"
" try\n"
" {\n"
" CClient.Close();\n"
" }\n"
" catch (...)\n"
" {\n"
" return 2;\n"
" }\n"
"\n"
" return 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void varScope2() {
check("int foo()\n"
"{\n"
" Error e;\n"
" e.SetValue(12);\n"
" throw e;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void varScope3() {
check("void foo()\n"
"{\n"
" int i;\n"
" int *p = 0;\n"
" if (abc)\n"
" {\n"
" p = &i;\n"
" }\n"
" *p = 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void varScope4() {
check("void foo()\n"
"{\n"
" int i;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void varScope5() {
check("void f(int x)\n"
"{\n"
" int i = 0;\n"
" if (x) {\n"
" for ( ; i < 10; ++i) ;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) The scope of the variable 'i' can be reduced.\n", errout_str());
check("void f(int x) {\n"
" const unsigned char i = 0;\n"
" if (x) {\n"
" for ( ; i < 10; ++i) ;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x)\n"
"{\n"
" int i = 0;\n"
" if (x) {b()}\n"
" else {\n"
" for ( ; i < 10; ++i) ;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) The scope of the variable 'i' can be reduced.\n", errout_str());
}
void varScope6() {
check("void f(int x)\n"
"{\n"
" int i = x;\n"
" if (a) {\n"
" x++;\n"
" }\n"
" if (b) {\n"
" c(i);\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n" // #5398
" bool success = false;\n"
" int notReducable(someClass.getX(&success));\n"
" if (success) {\n"
" foo(notReducable);\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(Test &test) {\n"
" int& x = test.getData();\n"
" if (test.process())\n"
" x = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f()\n"
"{\n"
"int foo = 0;\n"
"std::vector<int> vec(10);\n"
"BOOST_FOREACH(int& i, vec)\n"
"{\n"
" foo += 1;\n"
" if(foo == 10)\n"
" {\n"
" return 0;\n"
" }\n"
"}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int &x)\n"
"{\n"
" int n = 1;\n"
" do\n"
" {\n"
" ++n;\n"
" ++x;\n"
" } while (x);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void varScope7() {
check("void f(int x)\n"
"{\n"
" int y = 0;\n"
" b(y);\n"
" if (x) {\n"
" y++;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void varScope8() {
check("void test() {\n"
" float edgeResistance=1;\n"
" std::vector<int> edges;\n"
" BOOST_FOREACH(int edge, edges) {\n"
" edgeResistance = (edge+1) / 2.0;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) The scope of the variable 'edgeResistance' can be reduced.\n", errout_str());
}
void varScope9() {
// classes may have extra side effects
check("class fred {\n"
"public:\n"
" void x();\n"
"};\n"
"void test(int a) {\n"
" fred f;\n"
" if (a == 2) {\n"
" f.x();\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void varScope10() {
check("int f()\n"
"{\n"
" int x = 0;\n"
" FOR {\n"
" foo(x++);\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void varScope11() {
check("int f() {\n"
" int x = 0;\n"
" AB ab = { x, 0 };\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f() {\n"
" int x = 0;\n"
" if (a == 0) { ++x; }\n"
" AB ab = { x, 0 };\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f() {\n"
" int x = 0;\n"
" if (a == 0) { ++x; }\n"
" if (a == 1) { AB ab = { x, 0 }; }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void varScope12() {
check("void f(int x) {\n"
" int i[5];\n"
" int* j = y;\n"
" if (x)\n"
" foo(i);\n"
" foo(j);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) The scope of the variable 'i' can be reduced.\n", errout_str());
check("void f(int x) {\n"
" int i[5];\n"
" int* j;\n"
" if (x)\n"
" j = i;\n"
" foo(j);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
" const bool b = true;\n"
" x++;\n"
" if (x == 5)\n"
" foo(b);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
" const bool b = x;\n"
" x++;\n"
" if (x == 5)\n"
" foo(b);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void varScope13() {
// #2770
check("void f() {\n"
" int i = 0;\n"
" forever {\n"
" if (i++ == 42) { break; }\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void varScope14() {
// #3941
check("void f() {\n"
" const int i( foo());\n"
" if(a) {\n"
" for ( ; i < 10; ++i) ;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void varScope15() {
// #4573
check("void f() {\n"
" int a,b,c;\n"
" if (a);\n"
" else if(b);\n"
" else if(c);\n"
" else;\n"
"}", true, false);
ASSERT_EQUALS("", errout_str());
}
void varScope16() {
check("void f() {\n"
" int a = 0;\n"
" while((++a) < 56) {\n"
" foo();\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int a = 0;\n"
" do {\n"
" foo();\n"
" } while((++a) < 56);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int a = 0;\n"
" do {\n"
" a = 64;\n"
" foo(a);\n"
" } while((++a) < 56);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int a = 0;\n"
" do {\n"
" a = 64;\n"
" foo(a);\n"
" } while(z());\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) The scope of the variable 'a' can be reduced.\n", errout_str());
}
void varScope17() {
check("void f() {\n"
" int x;\n"
" if (a) {\n"
" x = stuff(x);\n"
" morestuff(x);\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) The scope of the variable 'x' can be reduced.\n", errout_str());
check("void f() {\n"
" int x;\n"
" if (a) {\n"
" x = stuff(x);\n"
" morestuff(x);\n"
" }\n"
" if (b) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) The scope of the variable 'x' can be reduced.\n", errout_str());
}
void varScope18() {
check("void f() {\n"
" short x;\n"
"\n"
" switch (ab) {\n"
" case A:\n"
" break;\n"
" case B:\n"
" default:\n"
" break;\n"
" }\n"
"\n"
" if (c) {\n"
" x = foo();\n"
" do_something(x);\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) The scope of the variable 'x' can be reduced.\n", errout_str());
check("void f() {\n"
" short x;\n"
"\n"
" switch (ab) {\n"
" case A:\n"
" x = 10;\n"
" break;\n"
" case B:\n"
" default:\n"
" break;\n"
" }\n"
"\n"
" if (c) {\n"
" x = foo();\n"
" do_something(x);\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" short x;\n"
"\n"
" switch (ab) {\n"
" case A:\n"
" if(c)\n"
" do_something(x);\n"
" break;\n"
" case B:\n"
" default:\n"
" break;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) The scope of the variable 'x' can be reduced.\n", errout_str());
check("void f() {\n"
" short x;\n"
"\n"
" switch (ab) {\n"
" case A:\n"
" if(c)\n"
" do_something(x);\n"
" break;\n"
" case B:\n"
" default:\n"
" if(d)\n"
" do_something(x);\n"
" break;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void varScope20() { // Ticket #5103 - constant variable only used in inner scope
check("int f(int a) {\n"
" const int x = 234;\n"
" int b = a;\n"
" if (b > 32) b = x;\n"
" return b;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void varScope21() { // Ticket #5382 - initializing two-dimensional array
check("int test() {\n"
" int test_value = 3;\n"
" int test_array[1][1] = { { test_value } };\n"
" return sizeof(test_array);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void varScope22() { // Ticket #5684 - "The scope of the variable 'p' can be reduced" - But it can not.
check("void foo() {\n"
" int* p( 42 );\n"
" int i = 0;\n"
" while ( i != 100 ) {\n"
" *p = i;\n"
" ++p;\n"
" ++i;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// try to avoid an obvious false negative after applying the fix for the example above:
check("void foo() {\n"
" int* p( 42 );\n"
" int i = 0;\n"
" int dummy = 0;\n"
" while ( i != 100 ) {\n"
" p = & dummy;\n"
" *p = i;\n"
" ++p;\n"
" ++i;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) The scope of the variable 'p' can be reduced.\n", errout_str());
}
void varScope23() { // #6154: Don't suggest to reduce scope if inner scope is a lambda
check("int main() {\n"
" size_t myCounter = 0;\n"
" Test myTest([&](size_t aX){\n"
" std::cout << myCounter += aX << std::endl;\n"
" });\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void varScope24() {
check("void f(Foo x) {\n"
" Foo &r = x;\n"
" if (cond) {\n"
" r.dostuff();\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) The scope of the variable 'r' can be reduced.\n", errout_str());
check("void f(Foo x) {\n"
" Foo foo = x;\n"
" if (cond) {\n"
" foo.dostuff();\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void varScope25() {
check("void f() {\n"
" time_t currtime;\n"
" if (a) {\n"
" currtime = time(&dummy);\n"
" if (currtime > t) {}\n"
" }\n"
"}", false);
ASSERT_EQUALS("[test.c:2]: (style) The scope of the variable 'currtime' can be reduced.\n", errout_str());
}
void varScope26() {
check("void f(const std::map<int,int> &m) {\n"
" for (auto it : m) {\n"
" if (cond1) {\n"
" int& key = it.first;\n"
" if (cond2) { dostuff(key); }\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void varScope27() {
checkP("void f() {\n"
" int x = 0;\n"
"#ifdef X\n"
"#endif\n"
" if (id == ABC) { return x; }\n"
"}");
ASSERT_EQUALS("", errout_str());
checkP("void f() {\n"
"#ifdef X\n"
"#endif\n"
" int x = 0;\n"
" if (id == ABC) { return x; }\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) The scope of the variable 'x' can be reduced.\n", errout_str());
}
void varScope28() {
check("void f() {\n" // #10527
" int i{};\n"
" if (double d = g(i); d == 1.0) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void varScope29() { // #10888
check("enum E { E0 };\n"
"struct S { int i; };\n"
"void f(int b) {\n"
" enum E e;\n"
" struct S s;\n"
" if (b) {\n"
" e = E0;\n"
" s.i = 0;\n"
" g(e, s);\n"
" }\n"
"}\n", false);
ASSERT_EQUALS("[test.c:4]: (style) The scope of the variable 'e' can be reduced.\n"
"[test.c:5]: (style) The scope of the variable 's' can be reduced.\n",
errout_str());
check("void f(bool b) {\n"
" std::string s;\n"
" if (b) {\n"
" s = \"abc\";\n"
" g(s);\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) The scope of the variable 's' can be reduced.\n", errout_str());
check("auto foo(std::vector<int>& vec, bool flag) {\n"
" std::vector<int> dummy;\n"
" std::vector<int>::iterator iter;\n"
" if (flag)\n"
" iter = vec.begin();\n"
" else {\n"
" dummy.push_back(42);\n"
" iter = dummy.begin();\n"
" }\n"
" return *iter;\n"
"}");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'vec' can be declared as reference to const\n", errout_str());
check("auto& foo(std::vector<int>& vec, bool flag) {\n"
" std::vector<int> dummy;\n"
" std::vector<int>::iterator iter;\n"
" if (flag)\n"
" iter = vec.begin();\n"
" else {\n"
" dummy.push_back(42);\n"
" iter = dummy.begin();\n"
" }\n"
" return *iter;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void varScope30() { // #8541
check("bool f(std::vector<int>& v, int i) {\n"
" int n = 0;\n"
" bool b = false;\n"
" std::for_each(v.begin(), v.end(), [&](int j) {\n"
" if (j == i) {\n"
" ++n;\n"
" if (n > 5)\n"
" b = true;\n"
" }\n"
" });\n"
" return b;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void varScope31() { // #11099
check("bool g(std::vector<int>&);\n"
"void h(std::vector<int>);\n"
"void f0(std::vector<int> v) {\n"
" std::vector<int> w{ v };\n"
" bool b = g(v);\n"
" if (b)\n"
" h(w);\n"
" h(v);\n"
"}\n"
"void f1(std::vector<int> v) {\n"
" std::vector<int> w{ v.begin(), v.end() };\n"
" bool b = g(v);\n"
" if (b)\n"
" h(w);\n"
" h(v);\n"
"}\n"
"void f2(std::vector<int> v) {\n"
" std::vector<int> w{ 10, 0, std::allocator<int>() };\n" // FN
" bool b = g(v);\n"
" if (b)\n"
" h(w);\n"
" h(v);\n"
"}\n"
"void f3(std::vector<int> v) {\n"
" std::vector<int> w{ 10, 0 };\n" // warn
" bool b = g(v);\n"
" if (b)\n"
" h(w);\n"
" h(v);\n"
"}\n"
"void f4(std::vector<int> v) {\n"
" std::vector<int> w{ 10 };\n" // warn
" bool b = g(v);\n"
" if (b)\n"
" h(w);\n"
" h(v);\n"
"}\n"
"void f5(std::vector<int> v) {\n"
" std::vector<int> w(v);\n"
" bool b = g(v);\n"
" if (b)\n"
" h(w);\n"
" h(v);\n"
"}\n"
"void f6(std::vector<int> v) {\n"
" std::vector<int> w(v.begin(), v.end());\n"
" bool b = g(v);\n"
" if (b)\n"
" h(w);\n"
" h(v);\n"
"}\n"
"void f7(std::vector<int> v) {\n"
" std::vector<int> w(10, 0, std::allocator<int>);\n" // FN
" bool b = g(v);\n"
" if (b)\n"
" h(w);\n"
" h(v);\n"
"}\n"
"void f8(std::vector<int> v) {\n"
" std::vector<int> w(10, 0);\n" // warn
" bool b = g(v);\n"
" if (b)\n"
" h(w);\n"
" h(v);\n"
"}\n"
"void f9(std::vector<int> v) {\n"
" std::vector<int> w(10);\n" // warn
" bool b = g(v);\n"
" if (b)\n"
" h(w);\n"
" h(v);\n"
"}\n"
"void f10(std::vector<int> v) {\n"
" std::vector<int> w{};\n" // warn
" bool b = g(v);\n"
" if (b)\n"
" h(w);\n"
" h(v);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:25]: (style) The scope of the variable 'w' can be reduced.\n"
"[test.cpp:32]: (style) The scope of the variable 'w' can be reduced.\n"
"[test.cpp:60]: (style) The scope of the variable 'w' can be reduced.\n"
"[test.cpp:67]: (style) The scope of the variable 'w' can be reduced.\n"
"[test.cpp:74]: (style) The scope of the variable 'w' can be reduced.\n",
errout_str());
}
void varScope32() { // #11441
check("template <class F>\n"
"std::vector<int> g(F, const std::vector<int>&);\n"
"void f(const std::vector<int>&v) {\n"
" std::vector<int> w;\n"
" for (auto x : v)\n"
" w = g([&]() { x; }, w);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:6]: (warning) Unused variable value 'x'\n", errout_str());
}
void varScope33() { // #11131
check("struct S {\n"
" const std::string& getStr() const;\n"
" void mutate();\n"
" bool getB() const;\n"
"};\n"
"void g(S& s) {\n"
" std::string str = s.getStr();\n"
" s.mutate();\n"
" if (s.getB()) {\n"
" if (str == \"abc\") {}\n"
" }\n"
"}\n"
"void g(char* s, bool b) {\n"
" int i = strlen(s);\n"
" s[0] = '\\0';\n"
" if (b) {\n"
" if (i == 5) {}\n"
" }\n"
"}\n"
"void f(const S& s) {\n"
" std::string str = s.getStr();\n"
" std::string str2{ s.getStr() };\n"
" std::string str3(s.getStr());\n"
" if (s.getB()) {\n"
" if (str == \"abc\") {}\n"
" if (str2 == \"abc\") {}\n"
" if (str3 == \"abc\") {}\n"
" }\n"
"}\n"
"void f(const char* s, bool b) {\n"
" int i = strlen(s);\n"
" if (b) {\n"
" if (i == 5) {}\n"
" }\n"
"}\n"
"void f(int j, bool b) {\n"
" int k = j;\n"
" if (b) {\n"
" if (k == 5) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("[test.cpp:21]: (style) The scope of the variable 'str' can be reduced.\n"
"[test.cpp:22]: (style) The scope of the variable 'str2' can be reduced.\n"
"[test.cpp:23]: (style) The scope of the variable 'str3' can be reduced.\n"
"[test.cpp:31]: (style) The scope of the variable 'i' can be reduced.\n"
"[test.cpp:37]: (style) The scope of the variable 'k' can be reduced.\n",
errout_str());
}
void varScope34() { // #11742
check("void f() {\n"
" bool b = false;\n"
" int i = 1;\n"
" for (int k = 0; k < 20; ++k) {\n"
" b = !b;\n"
" if (b)\n"
" i++;\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void varScope35() { // #11845
check("void f(int err, const char* src) {\n"
" const char* msg = \"Success\";\n"
" char buf[42];\n"
" if (err != 0)\n"
" msg = strcpy(buf, src);\n"
" printf(\"%d: %s\\n\", err, msg);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("char* g(char* dst, const char* src);\n"
"void f(int err, const char* src) {\n"
" const char* msg = \"Success\";\n"
" char buf[42];\n"
" if (err != 0)\n"
" msg = g(buf, src);\n"
" printf(\"%d: %s\\n\", err, msg);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("char* g(char* dst, const char* src);\n"
"void f(int err, const char* src) {\n"
" const char* msg = \"Success\";\n"
" char buf[42];\n"
" if (err != 0)\n"
" g(buf, src);\n"
" printf(\"%d: %s\\n\", err, msg);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (style) The scope of the variable 'buf' can be reduced.\n", errout_str());
}
void varScope36() {
// #12158
check("void f( uint32_t value ) {\n"
" uint32_t i = 0U;\n"
" if ( value > 100U ) { }\n"
" else if( value > 50U ) { }\n"
" else{\n"
" for( i = 0U; i < 5U; i++ ) {}\n"
" }\n"
"}\n", true, false);
ASSERT_EQUALS("[test.cpp:2]: (style) The scope of the variable 'i' can be reduced.\n", errout_str());
}
void varScope37() {
// #12158
check("void f( uint32_t value ) {\n"
" uint32_t i = 0U;\n"
" if ( value > 100U ) { }\n"
" else {\n"
" if( value > 50U ) { }\n"
" else{\n"
" for( i = 0U; i < 5U; i++ ) {}\n"
" }\n"
" }\n"
"}\n", true, false);
ASSERT_EQUALS("[test.cpp:2]: (style) The scope of the variable 'i' can be reduced.\n", errout_str());
}
void varScope38() {
checkP("bool dostuff();\n" // #12519
"#define DOSTUFF(c) if (c < 5) { if (c) b = dostuff(); }\n"
"#define DOSTUFFEX(c) { bool b = false; DOSTUFF(c); }\n"
"void f(int a) {\n"
" DOSTUFFEX(a);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void varScope39() {
check("struct S {\n" // #12405
" void f(const std::string&) const;\n"
" const int* g(std::string&) const;\n"
"};\n"
"void h(int);\n"
"void S::f(const std::string& s) const {\n"
" std::string n = s;\n"
" const int* a = g(n);\n"
" if (n == \"abc\") {\n"
" h(a[0]);\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void varScope40() {
checkP("#define NUM (-999.9)\n" // #8862
"double f(int i) {\n"
" double a = NUM;\n"
" double b = -NUM;\n"
" double c = -1.0 * NUM;\n"
" if (i == 1) {\n"
" return a;\n"
" }\n"
" if (i == 2) {\n"
" return b;\n"
" }\n"
" if (i == 3) {\n"
" return c;\n"
" }\n"
" return 0.0;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) The scope of the variable 'a' can be reduced.\n"
"[test.cpp:4]: (style) The scope of the variable 'b' can be reduced.\n"
"[test.cpp:5]: (style) The scope of the variable 'c' can be reduced.\n",
errout_str());
check("struct S { int a; };\n" // #12618
"int f(const S* s, int i) {\n"
" int x = s->a;\n"
" const int b[] = { 1, 2, 3 };\n"
" int y = b[1];\n"
" if (i)\n"
" return x + y;\n"
" return 0;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) The scope of the variable 'x' can be reduced.\n"
"[test.cpp:5]: (style) The scope of the variable 'y' can be reduced.\n",
errout_str());
}
void varScope41() { // #11845
check("void get_errmsg(const char **msg, char *buf, size_t bufsiz, int err);\n"
"void test(int err)\n"
"{\n"
" const char *msg = \"Success\";\n"
" char buf[42];\n"
" if (err != 0)\n"
" get_errmsg(&msg, buf, sizeof(buf), err);\n"
" printf(\"%d: %s\\n\", err, msg);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void get_errmsg(char *buf, size_t bufsiz, int err);\n"
"void test(int err)\n"
"{\n"
" const char *msg = \"Success\";\n"
" char buf[42];\n"
" if (err != 0)\n"
" get_errmsg(buf, sizeof(buf), err);\n"
" printf(\"%d: %s\\n\", err, msg);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5]: (style) The scope of the variable 'buf' can be reduced.\n", errout_str());
}
void varScope42() {
check("void f(const char **, char *);\n"
"void g(int e) {\n"
" const char *msg = \"Something\";\n"
" char buf[42];\n"
" if (e != 0)\n"
" f(&msg, buf);\n"
" printf(\"result: %s\\n\", msg);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(char *, char *);\n"
"void g(int e) {\n"
" char msg [42] = \"Something\";\n"
" char buf[42];\n"
" if (e != 0)\n"
" f(msg, buf);\n"
" printf(\"result: %s\\n\", msg);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(const char *, char *);\n"
"void g(int e) {\n"
" const char *msg = \"Something\";\n"
" char buf[42];\n"
" if (e != 0)\n"
" f(msg, buf);\n"
" printf(\"result: %s\\n\", msg);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (style) The scope of the variable 'buf' can be reduced.\n", errout_str());
check("void f(int **, char *);\n"
"void g(int e) {\n"
" int *msg = calloc(0, sizeof(*msg));\n"
" char buf[42];\n"
" if (e != 0)\n"
" f(&msg, buf);\n"
" printf(\"result: %d\\n\", *msg);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (style) The scope of the variable 'buf' can be reduced.\n", errout_str());
check("void f(const char *&, const char *&);\n"
"void g(int e) {\n"
" const char *msg = \"Something\";\n"
" char *buf = malloc(42);\n"
" if (e != 0)\n"
" f(msg, buf);\n"
" printf(\"result: %d\\n\", msg);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void g(const char* format, ...);\n"
"void f(bool b) {\n"
" const char* s = \"abc\";\n"
" if (b)\n"
" g(\"%d %s\", 1, s);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) The scope of the variable 's' can be reduced.\n", errout_str());
}
#define checkOldStylePointerCast(...) checkOldStylePointerCast_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
void checkOldStylePointerCast_(const char* file, int line, const char (&code)[size], Standards::cppstd_t std = Standards::CPPLatest) {
const Settings settings = settingsBuilder().severity(Severity::style).cpp(std).build();
// Tokenize..
SimpleTokenizer tokenizerCpp(settings, *this);
ASSERT_LOC(tokenizerCpp.tokenize(code), file, line);
CheckOther checkOtherCpp(&tokenizerCpp, &settings, this);
checkOtherCpp.warningOldStylePointerCast();
}
void oldStylePointerCast() {
checkOldStylePointerCast("class Base;\n"
"void foo()\n"
"{\n"
" Base * b = (Base *) derived;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) C-style pointer casting\n", errout_str());
checkOldStylePointerCast("class Base;\n"
"void foo()\n"
"{\n"
" Base * b = (const Base *) derived;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) C-style pointer casting\n", errout_str());
checkOldStylePointerCast("class Base;\n"
"void foo()\n"
"{\n"
" Base * b = (const Base * const) derived;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) C-style pointer casting\n", errout_str());
checkOldStylePointerCast("class Base;\n"
"void foo()\n"
"{\n"
" Base * b = (volatile Base *) derived;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) C-style pointer casting\n", errout_str());
checkOldStylePointerCast("class Base;\n"
"void foo()\n"
"{\n"
" Base * b = (volatile Base * const) derived;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) C-style pointer casting\n", errout_str());
checkOldStylePointerCast("class Base;\n"
"void foo()\n"
"{\n"
" Base * b = (const volatile Base *) derived;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) C-style pointer casting\n", errout_str());
checkOldStylePointerCast("class Base;\n"
"void foo()\n"
"{\n"
" Base * b = (const volatile Base * const) derived;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) C-style pointer casting\n", errout_str());
checkOldStylePointerCast("class Base;\n"
"void foo()\n"
"{\n"
" Base * b = (const Base *) ( new Derived() );\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) C-style pointer casting\n", errout_str());
checkOldStylePointerCast("class Base;\n"
"void foo()\n"
"{\n"
" Base * b = (const Base *) new Derived();\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) C-style pointer casting\n", errout_str());
checkOldStylePointerCast("class Base;\n"
"void foo()\n"
"{\n"
" Base * b = (const Base *) new short[10];\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) C-style pointer casting\n", errout_str());
checkOldStylePointerCast("class B;\n"
"class A\n"
"{\n"
" virtual void abc(B *) const = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkOldStylePointerCast("class B;\n"
"class A\n"
"{\n"
" virtual void abc(const B *) const = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #3630
checkOldStylePointerCast("class SomeType;\n"
"class X : public Base {\n"
" X() : Base((SomeType*)7) {}\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (style) C-style pointer casting\n", errout_str());
checkOldStylePointerCast("class SomeType;\n"
"class X : public Base {\n"
" X() : Base((SomeType*)var) {}\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (style) C-style pointer casting\n", errout_str());
checkOldStylePointerCast("class SomeType;\n"
"class X : public Base {\n"
" X() : Base((SomeType*)0) {}\n"
"};");
ASSERT_EQUALS("", errout_str());
// #5560
checkOldStylePointerCast("class C;\n"
"\n"
"class B\n"
"{ virtual G* createGui(S*, C*) const = 0; };\n"
"\n"
"class MS : public M\n"
"{ virtual void addController(C*) override {} };", Standards::CPP03);
ASSERT_EQUALS("", errout_str());
// #6164
checkOldStylePointerCast("class Base {};\n"
"class Derived: public Base {};\n"
"void testCC() {\n"
" std::vector<Base*> v;\n"
" v.push_back((Base*)new Derived);\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (style) C-style pointer casting\n", errout_str());
// #7709
checkOldStylePointerCast("typedef struct S S;\n"
"typedef struct S SS;\n"
"typedef class C C;\n"
"typedef long LONG;\n"
"typedef long* LONGP;\n"
"struct T {};\n"
"typedef struct T TT;\n"
"typedef struct T2 {} TT2;\n"
"void f(int* i) {\n"
" S* s = (S*)i;\n"
" SS* ss = (SS*)i;\n"
" struct S2* s2 = (struct S2*)i;\n"
" C* c = (C*)i;\n"
" class C2* c2 = (class C2*)i;\n"
" long* l = (long*)i;\n"
" LONG* l2 = (LONG*)i;\n"
" LONGP l3 = (LONGP)i;\n"
" TT* tt = (TT*)i;\n"
" TT2* tt2 = (TT2*)i;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:10]: (style) C-style pointer casting\n"
"[test.cpp:11]: (style) C-style pointer casting\n"
"[test.cpp:12]: (style) C-style pointer casting\n"
"[test.cpp:13]: (style) C-style pointer casting\n"
"[test.cpp:14]: (style) C-style pointer casting\n"
"[test.cpp:15]: (style) C-style pointer casting\n"
"[test.cpp:16]: (style) C-style pointer casting\n"
"[test.cpp:17]: (style) C-style pointer casting\n"
"[test.cpp:18]: (style) C-style pointer casting\n"
"[test.cpp:19]: (style) C-style pointer casting\n",
errout_str());
// #8649
checkOldStylePointerCast("struct S {};\n"
"void g(S*& s);\n"
"void f(int i) {\n"
" g((S*&)i);\n"
" S*& r = (S*&)i;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (style) C-style pointer casting\n"
"[test.cpp:5]: (style) C-style pointer casting\n",
errout_str());
// #10823
checkOldStylePointerCast("void f(void* p) {\n"
" auto h = reinterpret_cast<void (STDAPICALLTYPE*)(int)>(p);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #5210
checkOldStylePointerCast("void f(void* v1, void* v2) {\n"
" T** p1 = (T**)v1;\n"
" T*** p2 = (T***)v2;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) C-style pointer casting\n"
"[test.cpp:3]: (style) C-style pointer casting\n",
errout_str());
// #12446
checkOldStylePointerCast("namespace N { struct S {}; }\n"
"union U {\n"
" int i;\n"
" char c[4];\n"
"};\n"
"void f(void* p) {\n"
" auto ps = (N::S*)p;\n"
" auto pu = (union U*)p;\n"
" auto pv = (std::vector<int>*)(p);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:7]: (style) C-style pointer casting\n"
"[test.cpp:8]: (style) C-style pointer casting\n"
"[test.cpp:9]: (style) C-style pointer casting\n",
errout_str());
// #12447
checkOldStylePointerCast("void f(const int& i) {\n"
" int& r = (int&)i;\n"
" r = 0;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) C-style reference casting\n", errout_str());
// #11430
checkOldStylePointerCast("struct B {\n"
" float* data() const;\n"
"};\n"
"namespace N {\n"
" bool f(float* v);\n"
"}\n"
"bool g(B& b) {\n"
" using float_ptr = float*;\n"
" return N::f(float_ptr(b.data()));\n"
"}\n");
ASSERT_EQUALS("[test.cpp:9]: (style) C-style pointer casting\n", errout_str());
}
#define checkInvalidPointerCast(...) checkInvalidPointerCast_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
void checkInvalidPointerCast_(const char* file, int line, const char (&code)[size], bool portability = true, bool inconclusive = false) {
/*const*/ Settings settings = settingsBuilder().severity(Severity::warning).severity(Severity::portability, portability).certainty(Certainty::inconclusive, inconclusive).build();
settings.platform.defaultSign = 's';
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
CheckOther checkOtherCpp(&tokenizer, &settings, this);
checkOtherCpp.invalidPointerCast();
}
void invalidPointerCast() {
checkInvalidPointerCast("void test() {\n"
" float *f = new float[10];\n"
" delete [] (double*)f;\n"
" delete [] (long double const*)(new float[10]);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (portability) Casting between float * and double * which have an incompatible binary data representation.\n"
"[test.cpp:4]: (portability) Casting between float * and const long double * which have an incompatible binary data representation.\n", errout_str());
checkInvalidPointerCast("void test(const float* f) {\n"
" double *d = (double*)f;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (portability) Casting between const float * and double * which have an incompatible binary data representation.\n", errout_str());
checkInvalidPointerCast("void test(double* d1) {\n"
" long double *ld = (long double*)d1;\n"
" double *d2 = (double*)ld;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (portability) Casting between double * and long double * which have an incompatible binary data representation.\n"
"[test.cpp:3]: (portability) Casting between long double * and double * which have an incompatible binary data representation.\n", errout_str());
checkInvalidPointerCast("char* test(int* i) {\n"
" long double *d = (long double*)(i);\n"
" double *d = (double*)(i);\n"
" float *f = reinterpret_cast<float*>(i);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (portability) Casting between signed int * and long double * which have an incompatible binary data representation.\n"
"[test.cpp:3]: (portability) Casting between signed int * and double * which have an incompatible binary data representation.\n"
"[test.cpp:4]: (portability) Casting between signed int * and float * which have an incompatible binary data representation.\n", errout_str());
checkInvalidPointerCast("float* test(unsigned int* i) {\n"
" return (float*)i;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (portability) Casting between unsigned int * and float * which have an incompatible binary data representation.\n", errout_str());
checkInvalidPointerCast("float* test(unsigned int* i) {\n"
" return (float*)i[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
checkInvalidPointerCast("float* test(double& d) {\n"
" return (float*)&d;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (portability) Casting between double * and float * which have an incompatible binary data representation.\n", errout_str());
checkInvalidPointerCast("void test(float* data) {\n"
" f.write((char*)data,sizeof(float));\n"
"}", true, false);
ASSERT_EQUALS("", errout_str());
checkInvalidPointerCast("void test(float* data) {\n"
" f.write((char*)data,sizeof(float));\n"
"}", true, true); // #3639
ASSERT_EQUALS("[test.cpp:2]: (portability, inconclusive) Casting from float * to signed char * is not portable due to different binary data representations on different platforms.\n", errout_str());
checkInvalidPointerCast("long long* test(float* f) {\n"
" return (long long*)f;\n"
"}", false);
ASSERT_EQUALS("", errout_str());
checkInvalidPointerCast("long long* test(float* f, char* c) {\n"
" foo((long long*)f);\n"
" return reinterpret_cast<long long*>(c);\n"
"}", true);
ASSERT_EQUALS("[test.cpp:2]: (portability) Casting from float * to signed long long * is not portable due to different binary data representations on different platforms.\n", errout_str());
checkInvalidPointerCast("Q_DECLARE_METATYPE(int*)"); // #4135 - don't crash
}
void passedByValue() {
check("void f(const std::string str) {}");
ASSERT_EQUALS("[test.cpp:1]: (performance) Function parameter 'str' should be passed by const reference.\n", errout_str());
check("void f(std::unique_ptr<std::string> ptr) {}");
ASSERT_EQUALS("", errout_str());
check("void f(const std::shared_ptr<std::string> ptr) {}");
ASSERT_EQUALS("", errout_str());
check("void f(const std::function<F> ptr) {}");
ASSERT_EQUALS("", errout_str());
{
check("void f(const std::pair<int,int> x) {}");
ASSERT_EQUALS("", errout_str());
check("void f(const std::pair<std::string,std::string> x) {}");
TODO_ASSERT_EQUALS("error", "", errout_str());
}
check("void f(const std::string::size_type x) {}");
ASSERT_EQUALS("", errout_str());
check("class Foo;\nvoid f(const Foo foo) {}"); // Unknown class
ASSERT_EQUALS("[test.cpp:2]: (performance, inconclusive) Function parameter 'foo' should be passed by const reference.\n", errout_str());
check("class Foo { std::vector<int> v; };\nvoid f(const Foo foo) {}"); // Large class (STL member)
ASSERT_EQUALS("[test.cpp:2]: (performance) Function parameter 'foo' should be passed by const reference.\n", errout_str());
check("class Foo { int i; };\nvoid f(const Foo foo) {}"); // Small class
ASSERT_EQUALS("", errout_str());
check("class Foo { int i[6]; };\nvoid f(const Foo foo) {}"); // Large class (array)
ASSERT_EQUALS("[test.cpp:2]: (performance) Function parameter 'foo' should be passed by const reference.\n", errout_str());
check("class Foo { std::string* s; };\nvoid f(const Foo foo) {}"); // Small class (pointer)
ASSERT_EQUALS("", errout_str());
check("class Foo { static std::string s; };\nvoid f(const Foo foo) {}"); // Small class (static member)
ASSERT_EQUALS("", errout_str());
check("class X { std::string s; }; class Foo : X { };\nvoid f(const Foo foo) {}"); // Large class (inherited)
ASSERT_EQUALS("[test.cpp:2]: (performance) Function parameter 'foo' should be passed by const reference.\n", errout_str());
check("class X { std::string s; }; class Foo { X x; };\nvoid f(const Foo foo) {}"); // Large class (inherited)
ASSERT_EQUALS("[test.cpp:2]: (performance) Function parameter 'foo' should be passed by const reference.\n", errout_str());
check("void f(const std::string &str) {}");
ASSERT_EQUALS("", errout_str());
// The idiomatic way of passing a std::string_view is by value
check("void f(const std::string_view str) {}");
ASSERT_EQUALS("", errout_str());
check("void f(std::string_view str) {}");
ASSERT_EQUALS("", errout_str());
check("void f(const std::string_view &str) {}");
ASSERT_EQUALS("", errout_str());
check("void f(const std::vector<int> v) {}");
ASSERT_EQUALS("[test.cpp:1]: (performance) Function parameter 'v' should be passed by const reference.\n", errout_str());
check("void f(const std::vector<std::string> v) {}");
ASSERT_EQUALS("[test.cpp:1]: (performance) Function parameter 'v' should be passed by const reference.\n", errout_str());
check("void f(const std::vector<std::string>::size_type s) {}");
ASSERT_EQUALS("", errout_str());
check("void f(const std::vector<int> &v) {}");
ASSERT_EQUALS("", errout_str());
check("void f(const std::map<int,int> &v) {}");
ASSERT_EQUALS("", errout_str());
check("void f(const std::map<int,int> v) {}");
ASSERT_EQUALS("[test.cpp:1]: (performance) Function parameter 'v' should be passed by const reference.\n", errout_str());
check("void f(const std::map<std::string,std::string> v) {}");
ASSERT_EQUALS("[test.cpp:1]: (performance) Function parameter 'v' should be passed by const reference.\n", errout_str());
check("void f(const std::map<int,std::string> v) {}");
ASSERT_EQUALS("[test.cpp:1]: (performance) Function parameter 'v' should be passed by const reference.\n", errout_str());
check("void f(const std::map<std::string,int> v) {}");
ASSERT_EQUALS("[test.cpp:1]: (performance) Function parameter 'v' should be passed by const reference.\n", errout_str());
check("void f(const std::streamoff pos) {}");
ASSERT_EQUALS("", errout_str());
check("void f(std::initializer_list<int> i) {}");
ASSERT_EQUALS("", errout_str());
// #5824
check("void log(const std::string& file, int line, const std::string& function, const std::string str, ...) {}");
ASSERT_EQUALS("", errout_str());
// #5534
check("struct float3 { };\n"
"typedef float3 vec;\n"
"class Plane {\n"
" vec Refract(vec &vec) const;\n"
" bool IntersectLinePlane(const vec &planeNormal);\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class X {\n"
" virtual void func(const std::string str) {}\n"
"};");
ASSERT_EQUALS("[test.cpp:2]: (performance) Function parameter 'str' should be passed by const reference.\n", errout_str());
check("enum X;\n"
"void foo(X x1){}\n");
ASSERT_EQUALS("", errout_str());
check("enum X { a, b, c };\n"
"void foo(X x2){}\n");
ASSERT_EQUALS("", errout_str());
check("enum X { a, b, c };\n"
"enum X;"
"void foo(X x3){}\n");
ASSERT_EQUALS("", errout_str());
check("enum X;\n"
"enum X { a, b, c };"
"void foo(X x4){}\n");
ASSERT_EQUALS("", errout_str());
check("union U {\n"
" char* pc;\n"
" short* ps;\n"
" int* pi;\n"
"};\n"
"void f(U u) {}\n");
ASSERT_EQUALS("", errout_str());
check("struct S { char A[8][8]; };\n"
"void f(S s) {}\n");
ASSERT_EQUALS("[test.cpp:2]: (performance) Function parameter 's' should be passed by const reference.\n", errout_str());
check("union U {\n" // don't crash
" int a;\n"
" decltype(nullptr) b;\n"
"};\n"
"int* f(U u) { return u.b; }\n");
ASSERT_EQUALS("", errout_str());
check("struct B { virtual int f(std::string s) = 0; };\n" // #11432
"struct D1 : B {\n"
" int f(std::string s) override { s += 'a'; return s.size(); }\n"
"}\n"
"struct D2 : B {\n"
" int f(std::string s) override { return s.size(); }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("int x(int);\n"
"void f(std::vector<int> v, int& j) {\n"
" for (int i : v)\n"
" j = i;\n"
"}\n"
"void fn(std::vector<int> v) {\n"
" for (int& i : v)\n"
" i = x(i);\n"
"}\n"
"void g(std::vector<int> v, int& j) {\n"
" for (int i = 0; i < v.size(); ++i)\n"
" j = v[i];\n"
"}\n"
"void gn(std::vector<int> v) {\n"
" for (int i = 0; i < v.size(); ++i)\n"
" v[i] = x(i);\n"
"}\n"
"void h(std::vector<std::vector<int>> v, int& j) {\n"
" for (int i = 0; i < v.size(); ++i)\n"
" j = v[i][0];\n"
"}\n"
"void hn(std::vector<std::vector<int>> v) {\n"
" for (int i = 0; i < v.size(); ++i)\n"
" v[i][0] = x(i);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (performance) Function parameter 'v' should be passed by const reference.\n"
"[test.cpp:10]: (performance) Function parameter 'v' should be passed by const reference.\n"
"[test.cpp:18]: (performance) Function parameter 'v' should be passed by const reference.\n",
errout_str());
check("struct S {\n" // #11995
" explicit S(std::string s) noexcept;\n"
" std::string m;\n"
"};\n"
"S::S(std::string s) noexcept : m(std::move(s)) {}\n"
"struct T {\n"
" explicit S(std::string s) noexcept(true);\n"
" std::string m;\n"
"};\n"
"T::T(std::string s) noexcept(true) : m(std::move(s)) {}\n");
ASSERT_EQUALS("", errout_str());
check("namespace N {\n" // #12086
" void g(int);\n"
"}\n"
"void f(std::vector<int> v) {\n"
" N::g(v[0]);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (performance) Function parameter 'v' should be passed by const reference.\n", errout_str());
check("void f(const std::string& s, std::string t) {\n" // #12083
" const std::string& v = !s.empty() ? s : t;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:1]: (performance) Function parameter 't' should be passed by const reference.\n", errout_str());
/*const*/ Settings settings0 = settingsBuilder(_settings).platform(Platform::Type::Unix64).build();
check("struct S {\n" // #12138
" union {\n"
" int a = 0;\n"
" int x;\n"
" };\n"
" union {\n"
" int b = 0;\n"
" int y;\n"
" };\n"
" union {\n"
" int c = 0;\n"
" int z;\n"
" };\n"
"};\n"
"void f(S s) {\n"
" if (s.x > s.y) {}\n"
"}\n", /*cpp*/ true, /*inconclusive*/ true, /*runSimpleChecks*/ true, /*verbose*/ false, &settings0);
ASSERT_EQUALS("", errout_str());
check("struct S { std::list<int> l; };\n" // #12147
"class C { public: std::list<int> l; };\n"
"bool f(S s) {\n"
" return s.l.empty();\n"
"}\n"
"bool f(C c) {\n"
" return c.l.empty();\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (performance) Function parameter 's' should be passed by const reference.\n"
"[test.cpp:6]: (performance) Function parameter 'c' should be passed by const reference.\n",
errout_str());
check("struct S { std::list<int> a[1][1]; };\n"
"bool f(S s) {\n"
" return s.a[0][0].empty();\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (performance) Function parameter 's' should be passed by const reference.\n",
errout_str());
check("struct S {\n"
" enum class E : std::uint8_t { E0 };\n"
" static void f(S::E e) {\n"
" if (e == S::E::E0) {}\n"
" }\n"
" char a[20];\n"
"};\n");
ASSERT_EQUALS("", errout_str());
check("void f(const std::vector<int> v[2]);\n" // #13052
"void g(const std::vector<int> v[2]);\n"
"void g(const std::vector<int> v[2]) {}\n"
"int h(const std::array<std::vector<int>, 2> a) { return a[0][0]; }\n");
ASSERT_EQUALS("[test.cpp:4]: (performance) Function parameter 'a' should be passed by const reference.\n", errout_str());
/*const*/ Settings settings1 = settingsBuilder().platform(Platform::Type::Win64).build();
check("using ui64 = unsigned __int64;\n"
"ui64 Test(ui64 one, ui64 two) { return one + two; }\n",
/*cpp*/ true, /*inconclusive*/ true, /*runSimpleChecks*/ true, /*verbose*/ false, &settings1);
ASSERT_EQUALS("", errout_str());
}
void passedByValue_nonConst() {
check("void f(std::string str) {}");
ASSERT_EQUALS("[test.cpp:1]: (performance) Function parameter 'str' should be passed by const reference.\n", errout_str());
check("void f(std::string str) {\n"
" return str + x;\n"
"}");
ASSERT_EQUALS("[test.cpp:1]: (performance) Function parameter 'str' should be passed by const reference.\n", errout_str());
check("void f(std::string str) {\n"
" std::cout << str;\n"
"}");
ASSERT_EQUALS("[test.cpp:1]: (performance) Function parameter 'str' should be passed by const reference.\n", errout_str());
check("void f(std::string str) {\n"
" std::cin >> str;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(std::string str) {\n"
" std::string s2 = str;\n"
"}");
ASSERT_EQUALS("[test.cpp:1]: (performance) Function parameter 'str' should be passed by const reference.\n", errout_str());
check("void f(std::string str) {\n"
" std::string& s2 = str;\n"
"}");
ASSERT_EQUALS("[test.cpp:1]: (performance) Function parameter 'str' should be passed by const reference.\n"
"[test.cpp:2]: (style) Variable 's2' can be declared as reference to const\n",
errout_str());
check("void f(std::string str) {\n"
" const std::string& s2 = str;\n"
"}");
ASSERT_EQUALS("[test.cpp:1]: (performance) Function parameter 'str' should be passed by const reference.\n", errout_str());
check("void f(std::string str) {\n"
" str = \"\";\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(std::string str) {\n"
" foo(str);\n" // It could be that foo takes str as non-const-reference
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(const std::string& str);\n"
"void f(std::string str) {\n"
" foo(str);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (performance) Function parameter 'str' should be passed by const reference.\n", errout_str());
check("void foo(std::string str);\n"
"void f(std::string str) {\n"
" foo(str);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (performance) Function parameter 'str' should be passed by const reference.\n", errout_str());
check("void foo(std::string& str);\n"
"void f(std::string str) {\n"
" foo(str);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(std::string* str);\n"
"void f(std::string str) {\n"
" foo(&str);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(int& i1, const std::string& str, int& i2);\n"
"void f(std::string str) {\n"
" foo((a+b)*c, str, x);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (performance) Function parameter 'str' should be passed by const reference.\n", errout_str());
check("std::string f(std::string str) {\n"
" str += x;\n"
" return str;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("class X {\n"
" std::string s;\n"
" void func() const;\n"
"};\n"
"Y f(X x) {\n"
" x.func();\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (performance) Function parameter 'x' should be passed by const reference.\n", errout_str());
check("class X {\n"
" void func();\n"
"};\n"
"Y f(X x) {\n"
" x.func();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("class X {\n"
" void func(std::string str) {}\n"
"};");
ASSERT_EQUALS("[test.cpp:2]: (performance) Function parameter 'str' should be passed by const reference.\n", errout_str());
check("class X {\n"
" virtual void func(std::string str) {}\n" // Do not warn about virtual functions, if 'str' is not declared as const
"};");
ASSERT_EQUALS("", errout_str());
check("class X {\n"
" char a[1024];\n"
"};\n"
"class Y : X {\n"
" char b;\n"
"};\n"
"void f(Y y) {\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (performance) Function parameter 'y' should be passed by const reference.\n", errout_str());
check("class X {\n"
" void* a;\n"
" void* b;\n"
"};\n"
"class Y {\n"
" void* a;\n"
" void* b;\n"
" char c;\n"
"};\n"
"void f(X x, Y y) {\n"
"}");
ASSERT_EQUALS("[test.cpp:10]: (performance) Function parameter 'y' should be passed by const reference.\n", errout_str());
{
// 8-byte data should be passed by const reference on 32-bit platform but not on 64-bit platform
const char code[] = "class X {\n"
" uint64_t a;\n"
" uint64_t b;\n"
"};\n"
"void f(X x) {}";
/*const*/ Settings s32 = settingsBuilder(_settings).platform(Platform::Type::Unix32).build();
check(code, &s32);
ASSERT_EQUALS("[test.cpp:5]: (performance) Function parameter 'x' should be passed by const reference.\n", errout_str());
/*const*/ Settings s64 = settingsBuilder(_settings).platform(Platform::Type::Unix64).build();
check(code, &s64);
ASSERT_EQUALS("", errout_str());
}
check("Writer* getWriter();\n"
"\n"
"void foo(Buffer& buffer) {\n"
" getWriter()->operator<<(buffer);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void passedByValue_externC() {
check("struct X { int a[5]; }; void f(X v) { }");
ASSERT_EQUALS("[test.cpp:1]: (performance) Function parameter 'v' should be passed by const reference.\n", errout_str());
check("extern \"C\" { struct X { int a[5]; }; void f(X v) { } }");
ASSERT_EQUALS("", errout_str());
check("struct X { int a[5]; }; extern \"C\" void f(X v) { }");
ASSERT_EQUALS("", errout_str());
check("struct X { int a[5]; }; void f(const X v);");
ASSERT_EQUALS("[test.cpp:1]: (performance) Function parameter 'v' should be passed by const reference.\n", errout_str());
check("extern \"C\" { struct X { int a[5]; }; void f(const X v); }");
ASSERT_EQUALS("", errout_str());
check("struct X { int a[5]; }; extern \"C\" void f(const X v) { }");
ASSERT_EQUALS("", errout_str());
}
void constVariable() {
check("int f(std::vector<int> x) {\n"
" int& i = x[0];\n"
" return i;\n"
"}");
ASSERT_EQUALS("[test.cpp:1]: (performance) Function parameter 'x' should be passed by const reference.\n"
"[test.cpp:2]: (style) Variable 'i' can be declared as reference to const\n",
errout_str());
check("int f(std::vector<int>& x) {\n"
" return x[0];\n"
"}");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'x' can be declared as reference to const\n", errout_str());
check("int f(std::vector<int> x) {\n"
" const int& i = x[0];\n"
" return i;\n"
"}");
ASSERT_EQUALS("[test.cpp:1]: (performance) Function parameter 'x' should be passed by const reference.\n", errout_str());
check("int f(std::vector<int> x) {\n"
" static int& i = x[0];\n"
" return i;\n"
"}");
ASSERT_EQUALS("[test.cpp:1]: (performance) Function parameter 'x' should be passed by const reference.\n", errout_str());
check("int f(std::vector<int> x) {\n"
" int& i = x[0];\n"
" i++;\n"
" return i;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int& f(std::vector<int>& x) {\n"
" x.push_back(1);\n"
" int& i = x[0];\n"
" return i;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f(const std::vector<int>& x) {\n"
" return x[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int& f(std::vector<int>& x) {\n"
" return x[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
check("const int& f(std::vector<int>& x) {\n"
" return x[0];\n"
"}");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'x' can be declared as reference to const\n", errout_str());
check("int f(std::vector<int>& x) {\n"
" x[0]++;\n"
" return x[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct A { int a; };\n"
"A f(std::vector<A>& x) {\n"
" x[0].a = 1;\n"
" return x[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct A { int a(); };\n"
"A f(std::vector<A>& x) {\n"
" x[0].a();\n"
" return x[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int g(int& x);\n"
"int f(std::vector<int>& x) {\n"
" g(x[0]);\n"
" return x[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
check("template<class T>\n"
"T f(T& x) {\n"
" return x[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
check("template<class T>\n"
"T f(T&& x) {\n"
" return x[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
check("template<class T>\n"
"T f(T& x) {\n"
" return x[0];\n"
"}\n"
"void h() { std::vector<int> v; h(v); }");
ASSERT_EQUALS("", errout_str());
check("int f(int& x) {\n"
" return std::move(x);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(std::ostream& os) {\n"
" os << \"Hello\";\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void g(int*);\n"
"void f(int& x) {\n"
" g(&x);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct A { A(int*); };\n"
"A f(int& x) {\n"
" return A(&x);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct A { A(int*); };\n"
"A f(int& x) {\n"
" return A{&x};\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int& x, int& y) {\n"
" y++;\n"
"}");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'x' can be declared as reference to const\n", errout_str());
check("struct A {\n"
" explicit A(int& y) : x(&y) {}\n"
" int * x = nullptr;\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct A {\n"
" std::vector<int> v;\n"
" void swap(A& a) {\n"
" v.swap(a.v);\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct A {\n"
" template<class T>\n"
" void f();\n"
" template<class T>\n"
" void f() const;\n"
"};\n"
"void g(A& a) {\n"
" a.f<int>();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(std::vector<int>& v) {\n"
" for(auto&& x:v)\n"
" x = 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(std::vector<int>& v) {\n"
" for(auto x:v)\n"
" x = 1;\n"
"}");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'v' can be declared as reference to const\n", errout_str());
check("void f(std::vector<int>& v) {\n"
" for(auto& x:v) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Variable 'x' can be declared as reference to const\n",
errout_str());
check("void f(std::vector<int>& v) {\n" // #10980
" for (int& i : v)\n"
" if (i == 0) {}\n"
" for (const int& i : v)\n"
" if (i == 0) {}\n"
" for (auto& i : v)\n"
" if (i == 0) {}\n"
" for (const auto& i : v)\n"
" if (i == 0) {}\n"
" v.clear();\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Variable 'i' can be declared as reference to const\n"
"[test.cpp:6]: (style) Variable 'i' can be declared as reference to const\n",
errout_str());
check("void f(std::vector<int>& v) {\n"
" for(const auto& x:v) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'v' can be declared as reference to const\n", errout_str());
check("void f(int& i) {\n"
" int& j = i;\n"
" j++;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(std::vector<int>& v) {\n"
" int& i = v[0];\n"
" i++;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(std::map<unsigned int, std::map<std::string, unsigned int> >& m, unsigned int i) {\n"
" std::map<std::string, unsigned int>& members = m[i];\n"
" members.clear();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct A {\n"
" int& x;\n"
" A(int& y) : x(y)\n"
" {}\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct A {\n"
" A(int& x);\n"
"};\n"
"struct B : A {\n"
" B(int& x) : A(x)\n"
" {}\n"
"};");
ASSERT_EQUALS("", errout_str());
check("void f(bool b, int& x, int& y) {\n"
" auto& z = x;\n"
" auto& w = b ? y : z;\n"
" w = 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct S {\n"
" int i;\n"
"};\n"
"int& f(S& s) {\n"
" return s.i;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int* f(std::list<int>& x, unsigned int y) {\n"
" for (int& m : x) {\n"
" if (m == y)\n"
" return &m;\n"
" }\n"
" return nullptr;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int& f(std::list<int>& x, int& y) {\n"
" for (int& m : x) {\n"
" if (m == y)\n"
" return m;\n"
" }\n"
" return y;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool from_string(int& t, const std::string& s) {\n"
" std::istringstream iss(s);\n"
" return !(iss >> t).fail();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #9710
check("class a {\n"
" void operator()(int& i) const {\n"
" i++;\n"
" }\n"
"};\n"
"void f(int& i) {\n"
" a()(i);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("class a {\n"
" void operator()(int& i) const {\n"
" i++;\n"
" }\n"
"};\n"
"void f(int& i) {\n"
" a x;\n"
" x(i);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("class a {\n"
" void operator()(const int& i) const;\n"
"};\n"
"void f(int& i) {\n"
" a x;\n"
" x(i);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (style) Parameter 'i' can be declared as reference to const\n", errout_str());
//cast or assignment to a non-const reference should prevent the warning
check("struct T { void dostuff() const {}};\n"
"void a(T& x) {\n"
" x.dostuff();\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Parameter 'x' can be declared as reference to const\n", errout_str());
check("struct T : public U { void dostuff() const {}};\n"
"void a(T& x) {\n"
" x.dostuff();\n"
" const T& z = x;\n" // Make sure we find all assignments
" T& y = x;\n"
" y.mutate();\n" // to avoid warnings that y can be const
"}");
ASSERT_EQUALS("", errout_str());
check("struct T : public U { void dostuff() const {}};\n"
"void a(T& x) {\n"
" x.dostuff();\n"
" const U& y = x\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Parameter 'x' can be declared as reference to const\n", errout_str());
check("struct T : public U { void dostuff() const {}};\n"
"void a(T& x) {\n"
" x.dostuff();\n"
" U& y = x;\n"
" y.mutate();\n" // to avoid warnings that y can be const
"}");
ASSERT_EQUALS("", errout_str());
check("struct T : public U { void dostuff() const {}};\n"
"void a(T& x) {\n"
" x.dostuff();\n"
" my<fancy>::type& y = x;\n" // we don't know if y is const or not
" y.mutate();\n" // to avoid warnings that y can be const
"}");
ASSERT_EQUALS("", errout_str());
check("struct T : public U { void dostuff() const {}};\n"
"void a(T& x) {\n"
" x.dostuff();\n"
" const U& y = static_cast<const U&>(x);\n"
" y.mutate();\n" // to avoid warnings that y can be const
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Parameter 'x' can be declared as reference to const\n", errout_str());
check("struct T : public U { void dostuff() const {}};\n"
"void a(T& x) {\n"
" x.dostuff();\n"
" U& y = static_cast<U&>(x);\n"
" y.mutate();\n" // to avoid warnings that y can be const
"}");
ASSERT_EQUALS("", errout_str());
check("struct T : public U { void dostuff() const {}};\n"
"void a(T& x) {\n"
" x.dostuff();\n"
" const U& y = dynamic_cast<const U&>(x)\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Parameter 'x' can be declared as reference to const\n", errout_str());
check("struct T : public U { void dostuff() const {}};\n"
"void a(T& x) {\n"
" x.dostuff();\n"
" const U& y = dynamic_cast<U const &>(x);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Parameter 'x' can be declared as reference to const\n", errout_str());
check("struct T : public U { void dostuff() const {}};\n"
"void a(T& x) {\n"
" x.dostuff();\n"
" const U& y = dynamic_cast<U & const>(x);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Parameter 'x' can be declared as reference to const\n", errout_str());
check("struct T : public U { void dostuff() const {}};\n"
"void a(T& x) {\n"
" x.dostuff();\n"
" U& y = dynamic_cast<U&>(x);\n"
" y.mutate();\n" // to avoid warnings that y can be const
"}");
ASSERT_EQUALS("", errout_str());
check("struct T : public U { void dostuff() const {}};\n"
"void a(T& x) {\n"
" x.dostuff();\n"
" const U& y = dynamic_cast<typename const U&>(x);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Parameter 'x' can be declared as reference to const\n", errout_str());
check("struct T : public U { void dostuff() const {}};\n"
"void a(T& x) {\n"
" x.dostuff();\n"
" U& y = dynamic_cast<typename U&>(x);\n"
" y.mutate();\n" // to avoid warnings that y can be const
"}");
ASSERT_EQUALS("", errout_str());
check("struct T : public U { void dostuff() const {}};\n"
"void a(T& x) {\n"
" x.dostuff();\n"
" U* y = dynamic_cast<U*>(&x);\n"
" y->mutate();\n" // to avoid warnings that y can be const
"}");
ASSERT_EQUALS("", errout_str());
check("struct T : public U { void dostuff() const {}};\n"
"void a(T& x) {\n"
" x.dostuff();\n"
" const U * y = dynamic_cast<const U *>(&x);\n"
" y->mutate();\n" // to avoid warnings that y can be const
"}");
TODO_ASSERT_EQUALS("can be const", errout_str(), ""); //Currently taking the address is treated as a non-const operation when it should depend on what we do with it
check("struct T : public U { void dostuff() const {}};\n"
"void a(T& x) {\n"
" x.dostuff();\n"
" U const * y = dynamic_cast<U const *>(&x);\n"
" y->mutate();\n" // to avoid warnings that y can be const
"}");
TODO_ASSERT_EQUALS("can be const", errout_str(), ""); //Currently taking the address is treated as a non-const operation when it should depend on what we do with it
check("struct T : public U { void dostuff() const {}};\n"
"void a(T& x) {\n"
" x.dostuff();\n"
" const U const * const * const * const y = dynamic_cast<const U const * const * const * const>(&x);\n"
" y->mutate();\n" // to avoid warnings that y can be const
"}");
ASSERT_EQUALS("", errout_str());
check("struct T : public U { void dostuff() const {}};\n"
"void a(T& x) {\n"
" x.dostuff();\n"
" const U const * const * const * const y = dynamic_cast<const U const * const * const * const>(&x);\n"
" y->mutate();\n" // to avoid warnings that y can be const
"}");
TODO_ASSERT_EQUALS("can be const", errout_str(), ""); //Currently taking the address is treated as a non-const operation when it should depend on what we do with it
check("struct T : public U { void dostuff() const {}};\n"
"void a(T& x) {\n"
" x.dostuff();\n"
" const U const * const * * const y = dynamic_cast<const U const * const * * const>(&x);\n"
" y->mutate();\n" // to avoid warnings that y can be const
"}");
ASSERT_EQUALS("", errout_str());
check("struct T : public U { void dostuff() const {}};\n"
"void a(T& x) {\n"
" x.dostuff();\n"
" my::fancy<typename type const *> const * const * const y = dynamic_cast<my::fancy<typename type const *> const * const * const>(&x);\n"
" y->mutate();\n" // to avoid warnings that y can be const
"}");
ASSERT_EQUALS("", errout_str());
check("struct T : public U { void dostuff() const {}};\n"
"void a(T& x) {\n"
" x.dostuff();\n"
" const U& y = (const U&)(x);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) C-style reference casting\n"
"[test.cpp:2]: (style) Parameter 'x' can be declared as reference to const\n",
errout_str());
check("struct T : public U { void dostuff() const {}};\n"
"void a(T& x) {\n"
" x.dostuff();\n"
" U& y = (U&)(x);\n"
" y.mutate();\n" // to avoid warnings that y can be const
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) C-style reference casting\n", errout_str());
check("struct T : public U { void dostuff() const {}};\n"
"void a(T& x) {\n"
" x.dostuff();\n"
" const U& y = (typename const U&)(x);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) C-style reference casting\n"
"[test.cpp:2]: (style) Parameter 'x' can be declared as reference to const\n",
errout_str());
check("struct T : public U { void dostuff() const {}};\n"
"void a(T& x) {\n"
" x.dostuff();\n"
" U& y = (typename U&)(x);\n"
" y.mutate();\n" // to avoid warnings that y can be const
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) C-style reference casting\n", errout_str());
check("struct T : public U { void dostuff() const {}};\n"
"void a(T& x) {\n"
" x.dostuff();\n"
" U* y = (U*)(&x);\n"
" y->mutate();\n" // to avoid warnings that y can be const
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) C-style pointer casting\n", errout_str());
check("struct C { void f() const; };\n" // #9875 - crash
"\n"
"void foo(C& x) {\n"
" x.f();\n"
" foo( static_cast<U2>(0) );\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Parameter 'x' can be declared as reference to const\n", errout_str());
check("class a {\n"
" void foo(const int& i) const;\n"
" void operator()(int& i) const;\n"
"};\n"
"void f(int& i) {\n"
" a()(i);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("class a {\n"
" void operator()(const int& i) const;\n"
"};\n"
"void f(int& i) {\n"
" a()(i);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (style) Parameter 'i' can be declared as reference to const\n", errout_str());
// #9767
check("void fct1(MyClass& object) {\n"
" fct2([&](void){}, object);\n"
"}\n"
"bool fct2(std::function<void()> lambdaExpression, MyClass& object) {\n"
" object.modify();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #9778
check("struct A {};\n"
"struct B : A {};\n"
"B& f(A& x) {\n"
" return static_cast<B&>(x);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #10002
check("using A = int*;\n"
"void f(const A& x) {\n"
" ++(*x);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #10086
check("struct V {\n"
" V& get(typename std::vector<V>::size_type i) {\n"
" std::vector<V>& arr = v;\n"
" return arr[i];\n"
" }\n"
" std::vector<V> v;\n"
"};\n");
ASSERT_EQUALS("", errout_str());
check("void e();\n"
"void g(void);\n"
"void h(void);\n"
"void ah(void);\n"
"void ai(void);\n"
"void j(void);\n"
"void e(void);\n"
"void k(void);\n"
"void l(void);\n"
"void m(void);\n"
"void n(void);\n"
"void o(void);\n"
"void q(void);\n"
"void r(void);\n"
"void t(void);\n"
"void u(void);\n"
"void v(void);\n"
"void w(void);\n"
"void z(void);\n"
"void aj(void);\n"
"void am(void);\n"
"void g(void);\n"
"void h(void);\n"
"void ah(void);\n"
"void an(void);\n"
"void e(void);\n"
"void k(void);\n"
"void ao(wchar_t *d);\n"
"void ah(void);\n"
"void e(void);\n"
"void an(void);\n"
"void e(void);\n"
"void k(void);\n"
"void g(void);\n"
"void ah(void);\n"
"void an(void);\n"
"void e(void);\n"
"void e(void);\n"
"void e(void);\n"
"void k(void);\n"
"void g(void);\n"
"void ah(void);\n"
"void an(void);\n"
"void e(void);\n"
"void e(void);\n"
"void k(void);\n"
"void g(void);\n"
"void h(void);\n"
"void ah(void);\n"
"void an(void);\n"
"void e(void);\n"
"void k(void);\n"
"void e(void);\n"
"void g(void);\n"
"void ah(void);\n"
"void k(void);\n"
"void an(void);\n"
"void e(void);\n"
"void e(void);\n"
"void e(void);\n"
"void k(void);\n"
"void g(void);\n"
"void h(void);\n"
"void ah(void);\n"
"void k(void);\n"
"void an(void);\n"
"void k(void);\n"
"void e(void);\n"
"void g(void);\n"
"void ah(void);\n"
"void e(void);\n"
"void k(void);\n"
"void g(void);\n"
"void h(void);\n"
"void ah(void);\n"
"void an(void);\n"
"void an(void);\n"
"void k(void);\n"
"void e(void);\n"
"void e(void);\n"
"void e(void);\n"
"void g(void);\n"
"void k(void);\n"
"void g(void);\n"
"void h(void);\n"
"void ah(void);\n"
"void an(void);\n"
"void k(void);\n"
"void k(void);\n"
"void e(void);\n"
"void g(void);\n"
"void g(void);\n"
"void ah(void);\n"
"void an(void);\n"
"void e(void);\n"
"void k(void);\n"
"void e(void);\n"
"void ap(wchar_t *c, int d);\n"
"void ah(void);\n"
"void an(void);\n"
"void g(void);\n"
"void h(void);\n"
"void ah(void);\n"
"void aq(char *b, size_t d, char *c, int a);\n"
"void ar(char *b, size_t d, char *c, va_list a);\n"
"void k(void);\n"
"void g(void);\n"
"void g(void);\n"
"void h(void);\n"
"void ah(void);\n"
"void an(void);\n"
"void k(void);\n"
"void k(void);\n"
"void e(void);\n"
"void g(void);\n"
"void g(void);\n"
"void as(std::string s);\n"
"void at(std::ifstream &f);\n"
"void au(std::istream &f);\n"
"void av(std::string &aa, std::wstring &ab);\n"
"void aw(bool b, double x, double y);\n"
"void ax(int i);\n"
"void ay(std::string c, std::wstring a);\n"
"void az(const std::locale &ac);\n"
"void an();\n"
"void ba(std::ifstream &f);\n"
"void bb(std::istream &f) {\n"
"f.read(NULL, 0);\n"
"}\n"
"void h(void) {\n"
"struct tm *tm = 0;\n"
"(void)std::asctime(tm);\n"
"(void)std::asctime(0);\n"
"}\n"
"void bc(size_t ae) {\n"
"wchar_t *ad = 0, *af = 0;\n"
"struct tm *ag = 0;\n"
"(void)std::wcsftime(ad, ae, af, ag);\n"
"(void)std::wcsftime(0, ae, 0, 0);\n"
"}\n"
"void k(void) {}\n"
"void bd(void);\n"
"void be(void);\n"
"void bf(int b);\n"
"void e(void);\n"
"void e(void);\n"
"void bg(wchar_t *p);\n"
"void bh(const std::list<int> &ak, const std::list<int> &al);\n"
"void ah();\n"
"void an();\n"
"void h();");
ASSERT_EQUALS("[test.cpp:131]: (style) Variable 'tm' can be declared as pointer to const\n"
"[test.cpp:136]: (style) Variable 'af' can be declared as pointer to const\n"
"[test.cpp:137]: (style) Variable 'ag' can be declared as pointer to const\n",
errout_str());
check("class C\n"
"{\n"
"public:\n"
" explicit C(int&);\n"
"};\n"
"\n"
"class D\n"
"{\n"
"public:\n"
" explicit D(int&);\n"
"\n"
"private:\n"
" C c;\n"
"};\n"
"\n"
"D::D(int& i)\n"
" : c(i)\n"
"{\n"
"}");
ASSERT_EQUALS("", errout_str());
check("class C\n"
"{\n"
"public:\n"
" explicit C(int&);\n"
"};\n"
"\n"
"class D\n"
"{\n"
"public:\n"
" explicit D(int&) noexcept;\n"
"\n"
"private:\n"
" C c;\n"
"};\n"
"\n"
"D::D(int& i) noexcept\n"
" : c(i)\n"
"{}");
ASSERT_EQUALS("", errout_str());
check("class C\n"
"{\n"
"public:\n"
" explicit C(const int&);\n"
"};\n"
"\n"
"class D\n"
"{\n"
"public:\n"
" explicit D(int&);\n"
"\n"
"private:\n"
" C c;\n"
"};\n"
"\n"
"D::D(int& i)\n"
" : c(i)\n"
"{\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:16]: (style) Parameter 'i' can be declared as reference to const\n", "", errout_str());
check("class C\n"
"{\n"
"public:\n"
" explicit C(int);\n"
"};\n"
"\n"
"class D\n"
"{\n"
"public:\n"
" explicit D(int&);\n"
"\n"
"private:\n"
" C c;\n"
"};\n"
"\n"
"D::D(int& i)\n"
" : c(i)\n"
"{\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:16]: (style) Parameter 'i' can be declared as reference to const\n", "", errout_str());
check("class C\n"
"{\n"
"public:\n"
" explicit C(int, int);\n"
"};\n"
"\n"
"class D\n"
"{\n"
"public:\n"
" explicit D(int&);\n"
"\n"
"private:\n"
" C c;\n"
"};\n"
"\n"
"D::D(int& i)\n"
" : c(0, i)\n"
"{\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:16]: (style) Parameter 'i' can be declared as reference to const\n", "", errout_str());
check("void f(std::map<int, std::vector<int>> &map) {\n" // #10266
" for (auto &[slave, panels] : map)\n"
" panels.erase(it);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct S { void f(); int i; };\n"
"void call_f(S& s) { (s.*(&S::f))(); }\n");
ASSERT_EQUALS("", errout_str());
check("struct S { int a[1]; };\n"
"void f(S& s) { int* p = s.a; *p = 0; }\n");
ASSERT_EQUALS("", errout_str());
check("struct Foo {\n" // #9910
" int* p{};\n"
" int* get() { return p; }\n"
" const int* get() const { return p; }\n"
"};\n"
"struct Bar {\n"
" int j{};\n"
" void f(Foo& foo) const { int* q = foo.get(); *q = j; }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
check("struct S {\n" // #10679
" void g(long L, const C*& PC) const;\n"
" void g(long L, C*& PC);\n"
"};\n"
"void f(S& s) {\n"
" C* PC{};\n"
" s.g(0, PC);\n"
"};\n");
ASSERT_EQUALS("", errout_str());
// #10785
check("template <class T, class C>\n"
"struct d {\n"
" T& g(C& c, T C::*f) { return c.*f; }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
check("void f(std::map<int, int>& m) {\n"
" std::cout << m[0] << std::endl;\n"
"};\n");
ASSERT_EQUALS("", errout_str());
check("void f(std::vector<std::map<int, int>>& v) {\n" // #11607
" for (auto& m : v)\n"
" std::cout << m[0];\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct S { int i; };\n" // #11473
"void f(std::vector<std::vector<S>>&m, int*& p) {\n"
" auto& a = m[0];\n"
" for (auto& s : a) {\n"
" p = &s.i;\n"
" return;\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("int& g(int* p, int& r) {\n" // #11625
" if (p)\n"
" return *p;\n"
" return r;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("template <typename T> void f(std::vector<T*>& d, const std::vector<T*>& s) {\n" // #11632
" for (const auto& e : s) {\n"
" T* newE = new T(*e);\n"
" d.push_back(newE);\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #11682
check("struct b {\n"
" void mutate();\n"
"};\n"
"struct c {\n"
" const b& get() const;\n"
" b get();\n"
"};\n"
"struct d {\n"
" void f(c& e) const {\n"
" e.get().mutate();\n"
" }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
check("struct B { virtual void f() const {} };\n" // #11528
"struct D : B {};\n"
"void g(B* b) {\n"
" D* d = dynamic_cast<D*>(b);\n"
" if (d)\n"
" d->f();\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:4]: (style) Variable 'd' can be declared as pointer to const\n",
errout_str());
check("void g(const int*);\n"
"void f(const std::vector<int*>&v) {\n"
" for (int* i : v)\n"
" g(i);\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:3]: (style) Variable 'i' can be declared as pointer to const\n",
errout_str());
check("struct A {\n" // #11225
" A();\n"
" virtual ~A();\n"
"};\n"
"struct B : A {};\n"
"void f(A* a) {\n"
" const B* b = dynamic_cast<const B*>(a);\n"
"}\n"
"void g(A* a) {\n"
" const B* b = (const B*)a;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:10]: (style) C-style pointer casting\n"
"[test.cpp:6]: (style) Parameter 'a' can be declared as pointer to const\n"
"[test.cpp:9]: (style) Parameter 'a' can be declared as pointer to const\n",
errout_str());
check("void g(int*);\n"
"void f(std::vector<int>& v) {\n"
" g(v.data());\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void g(const int*);\n"
"void f(std::vector<int>& v) {\n"
" g(v.data());\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Parameter 'v' can be declared as reference to const\n", errout_str());
check("struct a {\n"
" template <class T>\n"
" void mutate();\n"
"};\n"
"struct b {};\n"
"template <class T>\n"
"void f(a& x) {\n"
" x.mutate<T>();\n"
"}\n"
"template <class T>\n"
"void f(const b&)\n"
"{}\n"
"void g(a& c) { f<int>(c); }\n");
ASSERT_EQUALS("", errout_str());
check("struct S {\n"
" template <typename T>\n"
" T* g() {\n"
" return reinterpret_cast<T*>(m);\n"
" }\n"
" template <typename T>\n"
" const T* g() const {\n"
" return reinterpret_cast<const T*>(m);\n"
" }\n"
" char* m;\n"
"};\n"
"void f(S& s) {\n"
" const int* p = s.g<int>();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct S { int x; };\n" // #11818
"std::istream& f(std::istream& is, S& s) {\n"
" return is >> s.x;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("bool f(std::string& s1, std::string& s2) {\n" // #12203
" return &s1 == &s2;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 's1' can be declared as reference to const\n"
"[test.cpp:1]: (style) Parameter 's2' can be declared as reference to const\n",
errout_str());
check("void f(int& r) {\n" // #12214
" (void)(true);\n"
" if (r) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'r' can be declared as reference to const\n", errout_str());
check("struct S { void f(int&); };\n" // #12216
"void g(S& s, int& r, void (S::* p2m)(int&)) {\n"
" (s.*p2m)(r);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct S {\n"
" void f(int& r) { p = &r; }\n"
" int* p;\n"
"};\n"
"void g(std::vector<int>& v1, std::vector<int*>& v2) {\n"
" std::transform(v1.begin(), v1.end(), v2.begin(), [](auto& x) { return &x; });\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("class T;\n" // #11869
"class E {\n"
"public:\n"
" class F {\n"
" public:\n"
" explicit F(const T* t);\n"
" };\n"
"};\n"
"void f(T& t) {\n"
" std::list<E::F> c(1, E::F(&t));\n"
"}\n");
ASSERT_EQUALS("[test.cpp:9]: (style) Parameter 't' can be declared as reference to const\n", errout_str());
check("struct T;\n"
"struct U {\n"
" struct V { explicit V(const T* p); };\n"
"};\n"
"void g(U::V v);\n"
"void f(T& t) {\n"
" g(U::V(&t));\n"
"}\n");
ASSERT_EQUALS("[test.cpp:6]: (style) Parameter 't' can be declared as reference to const\n", errout_str());
check("void f1(std::vector<int>& v) {\n" // #11207
" auto it = v.cbegin();\n"
" while (it != v.cend()) {\n"
" if (*it > 12) {}\n"
" ++it;\n"
" }\n"
"}\n"
"void f2(std::vector<int>& v) {\n"
" auto it = v.begin();\n"
" while (it != v.end()) {\n"
" if (*it > 12) {}\n"
" ++it;\n"
" }\n"
"}\n");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'v' can be declared as reference to const\n"
"[test.cpp:8]: (style) Parameter 'v' can be declared as reference to const\n",
errout_str());
check("void cb(const std::string&);\n" // #12349, #12350, #12351
"void f(std::string& s) {\n"
" const std::string& str(s);\n"
" cb(str);\n"
"}\n"
"void g(std::string& s) {\n"
" const std::string& str{ s };\n"
" cb(str);\n"
"}\n"
"void h(std::string* s) {\n"
" const std::string& str(*s);\n"
" cb(str);\n"
"}\n"
"void k(std::string* s) {\n"
" const std::string& str = *s;\n"
" cb(str);\n"
"}\n"
"void m(std::string& s) {\n"
" const std::string str(s);\n"
" cb(str);\n"
"}\n"
"void n(std::string* s) {\n"
" const std::string& str(*s);\n"
" cb(str);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Parameter 's' can be declared as reference to const\n"
"[test.cpp:6]: (style) Parameter 's' can be declared as reference to const\n"
"[test.cpp:18]: (style) Parameter 's' can be declared as reference to const\n"
"[test.cpp:10]: (style) Parameter 's' can be declared as pointer to const\n"
"[test.cpp:14]: (style) Parameter 's' can be declared as pointer to const\n"
"[test.cpp:22]: (style) Parameter 's' can be declared as pointer to const\n",
errout_str());
check("struct S {\n"
" S(std::string& r);\n"
"};\n"
"void f(std::string& str) {\n"
" const S& s(str);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct C {\n" // #10052
" int& operator()(int);\n"
"};\n"
"void f(std::vector<C>& c) {\n"
" c[0](5) = 12;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("int f(int& t) {\n" // #11713
" return 0;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 't' can be declared as reference to const\n", errout_str());
check("void f(std::list<std::string>& v) {\n" // #12202
" v.remove_if([](std::string& s) {\n"
" return true;\n"
" });\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Parameter 's' can be declared as reference to const\n", errout_str());
check("struct S {\n" // #12762
" std::vector<int> m;\n"
" void f();\n"
"};\n"
"void S::f() {\n"
" std::vector<int>& r = m;\n"
" g(r[0] * 2);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:6]: (style) Variable 'r' can be declared as reference to const\n", errout_str());
check("std::iostream& get();\n" // #12940
"std::iostream& Fun() {\n"
" auto lam = []() -> std::iostream& {\n"
" std::iostream& ios = get();\n"
" return ios;\n"
" };\n"
" return lam();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct S { int x[3]; };\n" // #13226
"void g(int a, int* b);\n"
"void f(int a, S& s) {\n"
" return g(a, s.x);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct S { std::vector<int> v; };\n" // #13317
"struct T { S s; };\n"
"int f(S& s) {\n"
" for (std::vector<int>::const_iterator it = s.v.cbegin(); it != s.v.cend(); ++it) {}\n"
" return *s.v.cbegin();\n"
"}\n"
"int f(T& t) {\n"
" return *t.s.v.cbegin();\n"
"}\n"
"int f(std::vector<int>& v) {\n"
" return *v.cbegin();\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) Parameter 's' can be declared as reference to const\n"
"[test.cpp:7]: (style) Parameter 't' can be declared as reference to const\n"
"[test.cpp:10]: (style) Parameter 'v' can be declared as reference to const\n",
errout_str());
}
void constParameterCallback() {
check("int callback(std::vector<int>& x) { return x[0]; }\n"
"void f() { dostuff(callback); }");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:1]: (style) Parameter 'x' can be declared as reference to const. However it seems that 'callback' is a callback function, if 'x' is declared with const you might also need to cast function pointer(s).\n", errout_str());
// #9906
check("class EventEngine : public IEventEngine {\n"
"public:\n"
" EventEngine();\n"
"\n"
"private:\n"
" void signalEvent(ev::sig& signal, int revents);\n"
"};\n"
"\n"
"EventEngine::EventEngine() {\n"
" mSigWatcher.set<EventEngine, &EventEngine::signalEvent>(this);\n"
"}\n"
"\n"
"void EventEngine::signalEvent(ev::sig& signal, int revents) {\n"
" switch (signal.signum) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:10] -> [test.cpp:13]: (style) Parameter 'signal' can be declared as reference to const. However it seems that 'signalEvent' is a callback function, if 'signal' is declared with const you might also need to cast function pointer(s).\n", errout_str());
check("void f(int* p) {}\n" // 12843
"void g(std::map<void(*)(int*), int>&m) {\n"
" m[&f] = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:1]: (style) Parameter 'p' can be declared as pointer to const. "
"However it seems that 'f' is a callback function, if 'p' is declared with const you might also need to cast function pointer(s).\n",
errout_str());
}
void constPointer() {
check("void foo(int *p) { return *p; }");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'p' can be declared as pointer to const\n", errout_str());
check("void foo(int *p) { x = *p; }");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'p' can be declared as pointer to const\n", errout_str());
check("void foo(int *p) { int &ref = *p; ref = 12; }");
ASSERT_EQUALS("", errout_str());
check("void foo(int *p) { x = *p + 10; }");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'p' can be declared as pointer to const\n", errout_str());
check("void foo(int *p) { return p[10]; }");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'p' can be declared as pointer to const\n", errout_str());
check("void foo(int *p) { int &ref = p[0]; ref = 12; }");
ASSERT_EQUALS("", errout_str());
check("void foo(int *p) { x[*p] = 12; }");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'p' can be declared as pointer to const\n", errout_str());
check("void foo(int *p) { if (p) {} }");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'p' can be declared as pointer to const\n", errout_str());
check("void foo(int *p) { if (p || x) {} }");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'p' can be declared as pointer to const\n", errout_str());
check("void foo(int *p) { if (p == 0) {} }");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'p' can be declared as pointer to const\n", errout_str());
check("void foo(int *p) { if (!p) {} }");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'p' can be declared as pointer to const\n", errout_str());
check("void foo(int *p) { if (*p > 123) {} }");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'p' can be declared as pointer to const\n", errout_str());
check("void foo(int *p) { return *p + 1; }");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'p' can be declared as pointer to const\n", errout_str());
check("void foo(int *p) { return *p > 1; }");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'p' can be declared as pointer to const\n", errout_str());
check("void foo(const int* c) { if (c == 0) {}; }");
ASSERT_EQUALS("", errout_str());
check("struct a { void b(); };\n"
"struct c {\n"
" a* d;\n"
" a& g() { return *d; }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
check("struct a { void b(); };\n"
"struct c { a* d; };\n"
"void e(c);\n");
ASSERT_EQUALS("", errout_str());
check("struct V {\n"
" V& get(typename std::vector<V>::size_type i, std::vector<V>* arr) {\n"
" return arr->at(i);\n"
" }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
check("struct A {};\n"
"struct B : A {};\n"
"B* f(A* x) {\n"
" return static_cast<B*>(x);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("int f(std::vector<int>* x) {\n"
" int& i = (*x)[0];\n"
" i++;\n"
" return i;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct A { int a; };\n"
"A f(std::vector<A>* x) {\n"
" x->front().a = 1;\n"
" return x->front();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(std::vector<int>* v) {\n"
" for(auto&& x:*v)\n"
" x = 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct A {\n"
" int* x;\n"
" A(int* y) : x(y)\n"
" {}\n"
"};");
ASSERT_EQUALS("", errout_str());
check("void f(bool b, int* x, int* y) {\n"
" int* z = x;\n"
" int* w = b ? y : z;\n"
" *w = 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(bool b, int* x, int* y) {\n"
" int& z = *x;\n"
" int& w = b ? *y : z;\n"
" w = 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("class Base { virtual void dostuff(int *p) = 0; };\n" // #10397
"class Derived: public Base { int x; void dostuff(int *p) override { x = *p; } };");
ASSERT_EQUALS("", errout_str());
check("struct Data { char buf[128]; };\n" // #10483
"void encrypt(Data& data) {\n"
" const char a[] = \"asfasd\";\n"
" memcpy(data.buf, &a, sizeof(a));\n"
"}");
ASSERT_EQUALS("", errout_str());
// #10547
check("void foo(std::istream &istr) {\n"
" unsigned char x[2];\n"
" istr >> x[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
// #10744
check("S& f() {\n"
" static S* p = new S();\n"
" return *p;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #10471
check("void f(std::array<int, 1> const& i) {\n"
" if (i[0] == 0) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #10466
check("typedef void* HWND;\n"
"void f(const std::vector<HWND>&v) {\n"
" for (const auto* h : v)\n"
" if (h) {}\n"
" for (const auto& h : v)\n"
" if (h) {}\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:5]: (style) Variable 'h' can be declared as pointer to const\n",
errout_str());
check("void f(const std::vector<int*>& v) {\n"
" for (const auto& p : v)\n"
" if (p == nullptr) {}\n"
" for (const auto* p : v)\n"
" if (p == nullptr) {}\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:2]: (style) Variable 'p' can be declared as pointer to const\n",
errout_str());
check("void f(std::vector<int*>& v) {\n"
" for (const auto& p : v)\n"
" if (p == nullptr) {}\n"
" for (const auto* p : v)\n"
" if (p == nullptr) {}\n"
" for (const int* const& p : v)\n"
" if (p == nullptr) {}\n"
" for (const int* p : v)\n"
" if (p == nullptr) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'v' can be declared as reference to const\n"
"[test.cpp:2]: (style) Variable 'p' can be declared as pointer to const\n",
errout_str());
check("void f(std::vector<const int*>& v) {\n"
" for (const auto& p : v)\n"
" if (p == nullptr) {}\n"
" for (const auto* p : v)\n"
" if (p == nullptr) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'v' can be declared as reference to const\n", errout_str());
check("void f(const std::vector<const int*>& v) {\n"
" for (const auto& p : v)\n"
" if (p == nullptr) {}\n"
" for (const auto* p : v)\n"
" if (p == nullptr) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(const int* const p) {\n"
" if (p == nullptr) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void g(int*);\n"
"void f(int* const* pp) {\n"
" int* p = pp[0];\n"
" g(p);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("template <typename T>\n"
"struct S {\n"
" static bool f(const T& t) { return t != nullptr; }\n"
"};\n"
"S<int*> s;\n");
ASSERT_EQUALS("", errout_str());
check("typedef void* HWND;\n" // #11084
"void f(const HWND h) {\n"
" if (h == nullptr) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("using HWND = void*;\n"
"void f(const HWND h) {\n"
" if (h == nullptr) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("typedef int A;\n"
"void f(A* x) {\n"
" if (x == nullptr) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Parameter 'x' can be declared as pointer to const\n", errout_str());
check("using A = int;\n"
"void f(A* x) {\n"
" if (x == nullptr) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Parameter 'x' can be declared as pointer to const\n", errout_str());
check("struct S { void v(); };\n" // #11095
"void f(S* s) {\n"
" (s - 1)->v();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(std::vector<int*>& v) {\n" // #11085
" for (int* p : v) {\n"
" if (p) {}\n"
" }\n"
" for (auto* p : v) {\n"
" if (p) {}\n"
" }\n"
" v.clear();\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Variable 'p' can be declared as pointer to const\n"
"[test.cpp:5]: (style) Variable 'p' can be declared as pointer to const\n",
errout_str());
check("void f() {\n"
" char a[1][1];\n"
" char* b[1];\n"
" b[0] = a[0];\n"
" **b = 0;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("ptrdiff_t f(int *p0, int *p1) {\n" // #11148
" return p0 - p1;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'p0' can be declared as pointer to const\n"
"[test.cpp:1]: (style) Parameter 'p1' can be declared as pointer to const\n",
errout_str());
check("void f() {\n"
" std::array<int, 1> a{}, b{};\n"
" const std::array<int, 1>& r = a;\n"
" if (r == b) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct S {};\n" // #11599
"void g(S);\n"
"void h(const S&);\n"
"void h(int, int, const S&);\n"
"void i(S&);\n"
"void j(const S*);\n"
"void j(int, int, const S*);\n"
"void f1(S* s) {\n"
" g(*s);\n"
"}\n"
"void f2(S* s) {\n"
" h(*s);\n"
"}\n"
"void f3(S* s) {\n"
" h(1, 2, *s);\n"
"}\n"
"void f4(S* s) {\n"
" i(*s);\n"
"}\n"
"void f5(S& s) {\n"
" j(&s);\n"
"}\n"
"void f6(S& s) {\n"
" j(1, 2, &s);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:20]: (style) Parameter 's' can be declared as reference to const\n"
"[test.cpp:23]: (style) Parameter 's' can be declared as reference to const\n"
"[test.cpp:8]: (style) Parameter 's' can be declared as pointer to const\n"
"[test.cpp:11]: (style) Parameter 's' can be declared as pointer to const\n"
"[test.cpp:14]: (style) Parameter 's' can be declared as pointer to const\n",
errout_str());
check("void g(int, const int*);\n"
"void h(const int*);\n"
"void f(int* p) {\n"
" g(1, p);\n"
" h(p);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) Parameter 'p' can be declared as pointer to const\n",
errout_str());
check("void f(int, const int*);\n"
"void f(int i, int* p) {\n"
" f(i, const_cast<const int*>(p));\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct S { int a; };\n"
"void f(std::vector<S>& v, int b) {\n"
" size_t n = v.size();\n"
" for (size_t i = 0; i < n; i++) {\n"
" S& s = v[i];\n"
" if (!(b & s.a))\n"
" continue;\n"
" }\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5]: (style) Variable 's' can be declared as reference to const\n", errout_str()); // don't crash
check("void f(int& i) {\n"
" new (&i) int();\n"
"}\n");
ASSERT_EQUALS("", errout_str()); // don't crash
check("void f(int& i) {\n"
" int& r = i;\n"
" if (!&r) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Variable 'r' can be declared as reference to const\n", errout_str()); // don't crash
check("class C;\n" // #11646
"void g(const C* const p);\n"
"void f(C* c) {\n"
" g(c);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) Parameter 'c' can be declared as pointer to const\n", errout_str());
check("typedef void (*cb_t)(int*);\n" // #11674
"void cb(int* p) {\n"
" if (*p) {}\n"
"}\n"
"void g(cb_t);\n"
"void f() {\n"
" g(cb);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:7] -> [test.cpp:2]: (style) Parameter 'p' can be declared as pointer to const. "
"However it seems that 'cb' is a callback function, if 'p' is declared with const you might also need to cast function pointer(s).\n",
errout_str());
check("typedef void (*cb_t)(int*);\n"
"void cb(int* p) {\n"
" if (*p) {}\n"
"}\n"
"void g(cb_t);\n"
"void f() {\n"
" g(::cb);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:7] -> [test.cpp:2]: (style) Parameter 'p' can be declared as pointer to const. "
"However it seems that 'cb' is a callback function, if 'p' is declared with const you might also need to cast function pointer(s).\n",
errout_str());
check("void f1(std::vector<int>* p) {\n" // #11681
" if (p->empty()) {}\n" // warn
"}\n"
"void f2(std::vector<int>* p) {\n"
" p->resize(0);\n"
"}\n"
"struct S {\n"
" void h1() const;\n"
" void h2();\n"
" int i;\n"
"};\n"
"void k(int&);\n"
"void g1(S* s) {\n"
" s->h1();\n" // warn
"}\n"
"void g1(S* s) {\n"
" s->h2();\n"
"}\n"
"void g1(S* s) {\n"
" if (s->i) {}\n" // warn
"}\n"
"void g2(S* s) {\n"
" s->i = 0;\n"
"}\n"
"void g3(S* s) {\n"
" k(s->i);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'p' can be declared as pointer to const\n"
"[test.cpp:13]: (style) Parameter 's' can be declared as pointer to const\n"
"[test.cpp:19]: (style) Parameter 's' can be declared as pointer to const\n",
errout_str());
check("struct S {\n" // #11573
" const char* g() const {\n"
" return m;\n"
" }\n"
" const char* m;\n"
"};\n"
"struct T { std::vector<S*> v; };\n"
"void f(T* t, const char* n) {\n"
" for (const auto* p : t->v)\n"
" if (strcmp(p->g(), n) == 0) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:8]: (style) Parameter 't' can be declared as pointer to const\n",
errout_str());
check("void f(int*& p, int* q) {\n"
" p = q;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct S { int a[1]; };\n"
"void f(S* s) {\n"
" if (s->a[0]) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Parameter 's' can be declared as pointer to const\n",
errout_str());
check("size_t f(char* p) {\n" // #11842
" return strlen(p);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'p' can be declared as pointer to const\n", errout_str());
check("void f(int* p) {\n" // #11862
" long long j = *(p++);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'p' can be declared as pointer to const\n",
errout_str());
check("void f(void *p, size_t nmemb, size_t size, int (*cmp)(const void *, const void *)) {\n"
" qsort(p, nmemb, size, cmp);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void g(bool *r, std::size_t *b) {\n" // #12129
" if (*r && *b >= 5) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'r' can be declared as pointer to const\n"
"[test.cpp:1]: (style) Parameter 'b' can be declared as pointer to const\n",
errout_str());
check("void f(int i) {\n" // #12185
" void* p = &i;\n"
" std::cout << p << '\\n';\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Variable 'p' can be declared as pointer to const\n",
errout_str());
check("struct S { const T* t; };\n" // #12206
"void f(S* s) {\n"
" if (s->t.i) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Parameter 's' can be declared as pointer to const\n",
errout_str());
check("void f(char *a1, char *a2) {\n" // #12252
" char* b = new char[strlen(a1) + strlen(a2) + 2];\n"
" sprintf(b, \"%s_%s\", a1, a2);\n"
" delete[] b;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'a1' can be declared as pointer to const\n"
"[test.cpp:1]: (style) Parameter 'a2' can be declared as pointer to const\n",
errout_str());
check("int f(int* p) {\n" // #11713
" return 0;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'p' can be declared as pointer to const\n",
errout_str());
check("void f(int *src, int* dst) {\n" // #12518
" *dst++ = (int)*src++;\n"
" *dst++ = static_cast<int>(*src++);\n"
" *dst = (int)*src;\n"
"}\n"
"void g(int* dst) {\n"
" (int&)*dst = 5;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'src' can be declared as pointer to const\n",
errout_str());
check("struct S {};\n"
"void f(T* t) {\n"
" S* s = (S*)t->p;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) C-style pointer casting\n"
"[test.cpp:3]: (style) Variable 's' can be declared as pointer to const\n",
errout_str()); // don't crash
check("struct S { int i; };\n" // #12205
"void f(S* s) {\n"
" (void)s->i;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Parameter 's' can be declared as pointer to const\n",
errout_str());
check("void f(int* a, int* b, int i) {\n" // #13072
" a[b[i]] = 0;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'b' can be declared as pointer to const\n",
errout_str());
check("int f(int* a, int* b, int i) {\n" // #13085
" a[*(b + i)] = 0;\n"
" return *(b + i);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'b' can be declared as pointer to const\n",
errout_str());
check("struct S { int a; };\n" // #13286
"void f(struct S* s) {\n"
" if ((--s)->a >= 0) {}\n"
"}\n"
"void g(struct S* s) {\n"
" --s;\n"
" if (s->a >= 0) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Parameter 's' can be declared as pointer to const\n"
"[test.cpp:5]: (style) Parameter 's' can be declared as pointer to const\n",
errout_str());
}
void constArray() {
check("void f(std::array<int, 2>& a) {\n"
" if (a[0]) {}\n"
"}\n"
"void g(std::array<int, 2>& a) {\n"
" a.fill(0);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'a' can be declared as const array\n", errout_str());
check("int f() {\n"
" static int i[1] = {};\n"
" return i[0];\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Variable 'i' can be declared as const array\n", errout_str());
check("int f() {\n"
" static int i[] = { 0 };\n"
" int j = i[0] + 1;\n"
" return j;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Variable 'i' can be declared as const array\n", errout_str());
check("void f(int i) {\n"
" const char *tmp;\n"
" char* a[] = { \"a\", \"aa\" };\n"
" static char* b[] = { \"b\", \"bb\" };\n"
" tmp = a[i];\n"
" printf(\"%s\", tmp);\n"
" tmp = b[i];\n"
" printf(\"%s\", tmp);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'a' can be declared as const array\n"
"[test.cpp:4]: (style) Variable 'b' can be declared as const array\n",
errout_str());
check("int f(int i, int j) {\n" // #13069
" int a[3][4] = {\n"
" { 2, 2, -1, -1 },\n"
" { 2, -1, 2, -1 },\n"
" { 2, -1, -1, 2 },\n"
" };\n"
" return a[j][i];\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Variable 'a' can be declared as const array\n",
errout_str());
check("void f(int n, int v[42]) {\n" // #12796
" int j = 0;\n"
" for (int i = 0; i < n; ++i) {\n"
" j += 1;\n"
" if (j == 1) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'v' can be declared as const array\n",
errout_str());
}
void switchRedundantAssignmentTest() {
check("void foo()\n"
"{\n"
" int y = 1;\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" y = 2;\n"
" case 3:\n"
" y = 3;\n"
" }\n"
" bar(y);\n"
"}");
ASSERT_EQUALS("[test.cpp:7] -> [test.cpp:9]: (style) Variable 'y' is reassigned a value before the old one has been used. 'break;' missing?\n", errout_str());
check("void foo()\n"
"{\n"
" int y = 1;\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" {\n"
" y = 2;\n"
" }\n"
" case 3:\n"
" y = 3;\n"
" }\n"
" bar(y);\n"
"}");
ASSERT_EQUALS("[test.cpp:8] -> [test.cpp:11]: (style) Variable 'y' is reassigned a value before the old one has been used. 'break;' missing?\n", errout_str());
check("void foo()\n"
"{\n"
" int y = 1;\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" y = 2;\n"
" case 3:\n"
" if (x)\n"
" {\n"
" y = 3;\n"
" }\n"
" }\n"
" bar(y);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo()\n"
"{\n"
" int y = 1;\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" {\n"
" y = 2;\n"
" if (z)\n"
" printf(\"%d\", y);\n"
" }\n"
" case 3:\n"
" y = 3;\n"
" }\n"
" bar(y);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo()\n"
"{\n"
" int x = a;\n"
" int y = 1;\n"
" switch (x)\n"
" {\n"
" case 2:\n"
" x = 2;\n"
" case 3:\n"
" y = 3;\n"
" }\n"
" bar(y);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo()\n"
"{\n"
" int y = 1;\n"
" switch (x)\n"
" {\n"
" case 2:\n"
" y = 2;\n"
" break;\n"
" case 3:\n"
" y = 3;\n"
" }\n"
" bar(y);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo()\n"
"{\n"
" int y = 1;\n"
" while(xyz()) {\n"
" switch (x)\n"
" {\n"
" case 2:\n"
" y = 2;\n"
" continue;\n"
" case 3:\n"
" y = 3;\n"
" }\n"
" bar(y);\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo()\n"
"{\n"
" int y = 1;\n"
" while(xyz()) {\n"
" switch (x)\n"
" {\n"
" case 2:\n"
" y = 2;\n"
" throw e;\n"
" case 3:\n"
" y = 3;\n"
" }\n"
" bar(y);\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo()\n"
"{\n"
" int y = 1;\n"
" switch (x)\n"
" {\n"
" case 2:\n"
" y = 2;\n"
" printf(\"%d\", y);\n"
" case 3:\n"
" y = 3;\n"
" }\n"
" bar(y);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo()\n"
"{\n"
" int y = 1;\n"
" switch (x)\n"
" {\n"
" case 2:\n"
" y = 2;\n"
" bar();\n"
" case 3:\n"
" y = 3;\n"
" }\n"
" bar(y);\n"
"}");
ASSERT_EQUALS("[test.cpp:7] -> [test.cpp:10]: (style) Variable 'y' is reassigned a value before the old one has been used. 'break;' missing?\n", errout_str());
check("void bar() {}\n" // bar isn't noreturn
"void foo()\n"
"{\n"
" int y = 1;\n"
" switch (x)\n"
" {\n"
" case 2:\n"
" y = 2;\n"
" bar();\n"
" case 3:\n"
" y = 3;\n"
" }\n"
" bar(y);\n"
"}");
ASSERT_EQUALS("[test.cpp:8] -> [test.cpp:11]: (style) Variable 'y' is reassigned a value before the old one has been used. 'break;' missing?\n", errout_str());
check("void foo(int a) {\n"
" char str[10];\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" strcpy(str, \"a'\");\n"
" case 3:\n"
" strcpy(str, \"b'\");\n"
" }\n"
"}", true, false, false);
TODO_ASSERT_EQUALS("[test.cpp:6] -> [test.cpp:8]: (style) Buffer 'str' is being written before its old content has been used. 'break;' missing?\n",
"",
errout_str());
check("void foo(int a) {\n"
" char str[10];\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" strncpy(str, \"a'\");\n"
" case 3:\n"
" strncpy(str, \"b'\");\n"
" }\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:6] -> [test.cpp:8]: (style) Buffer 'str' is being written before its old content has been used. 'break;' missing?\n",
"",
errout_str());
check("void foo(int a) {\n"
" char str[10];\n"
" int z = 0;\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" strcpy(str, \"a'\");\n"
" z++;\n"
" case 3:\n"
" strcpy(str, \"b'\");\n"
" z++;\n"
" }\n"
"}", true, false, false);
TODO_ASSERT_EQUALS("[test.cpp:7] -> [test.cpp:10]: (style) Buffer 'str' is being written before its old content has been used. 'break;' missing?\n",
"",
errout_str());
check("void foo(int a) {\n"
" char str[10];\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" strcpy(str, \"a'\");\n"
" break;\n"
" case 3:\n"
" strcpy(str, \"b'\");\n"
" break;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(int a) {\n"
" char str[10];\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" strcpy(str, \"a'\");\n"
" printf(str);\n"
" case 3:\n"
" strcpy(str, \"b'\");\n"
" }\n"
"}", true, false, false);
ASSERT_EQUALS("", errout_str());
// Ticket #5158 "segmentation fault (valid code)"
check("typedef struct ct_data_s {\n"
" union {\n"
" char freq;\n"
" } fc;\n"
"} ct_data;\n"
"typedef struct internal_state {\n"
" struct ct_data_s dyn_ltree[10];\n"
"} deflate_state;\n"
"void f(deflate_state *s) {\n"
" s->dyn_ltree[0].fc.freq++;\n"
"}\n", true, false, false);
ASSERT_EQUALS("", errout_str());
// Ticket #6132 "crash: daca: kvirc CheckOther::checkRedundantAssignment()"
check("void HttpFileTransfer :: transferTerminated ( bool bSuccess ) {\n"
"if ( m_szCompletionCallback . isNull ( ) ) {\n"
"KVS_TRIGGER_EVENT ( KviEvent_OnHTTPGetTerminated , out ? out : ( g_pApp . activeConsole ( ) ) , & vParams )\n"
"} else {\n"
"KviKvsScript :: run ( m_szCompletionCallback , out ? out : ( g_pApp . activeConsole ( ) ) , & vParams ) ;\n"
"}\n"
"}\n", true, false, true);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int x;\n"
" switch (state) {\n"
" case 1: x = 3; goto a;\n"
" case 1: x = 6; goto a;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void switchRedundantOperationTest() {
check("void foo()\n"
"{\n"
" int y = 1;\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" ++y;\n"
" case 3:\n"
" y = 3;\n"
" }\n"
" bar(y);\n"
"}");
ASSERT_EQUALS("[test.cpp:7] -> [test.cpp:9]: (style) Variable 'y' is reassigned a value before the old one has been used. 'break;' missing?\n", errout_str());
check("void foo()\n"
"{\n"
" int y = 1;\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" {\n"
" ++y;\n"
" }\n"
" case 3:\n"
" y = 3;\n"
" }\n"
" bar(y);\n"
"}");
ASSERT_EQUALS("[test.cpp:8] -> [test.cpp:11]: (style) Variable 'y' is reassigned a value before the old one has been used. 'break;' missing?\n", errout_str());
check("void foo()\n"
"{\n"
" int y = 1;\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" (void)y;\n"
" case 3:\n"
" ++y;\n"
" }\n"
" bar(y);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo()\n"
"{\n"
" int y = 1;\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" ++y;\n"
" case 3:\n"
" ++y;\n"
" }\n"
" bar(y);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo()\n"
"{\n"
" int y = 1;\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" --y;\n"
" case 3:\n"
" y = 3;\n"
" }\n"
" bar(y);\n"
"}");
ASSERT_EQUALS("[test.cpp:7] -> [test.cpp:9]: (style) Variable 'y' is reassigned a value before the old one has been used. 'break;' missing?\n", errout_str());
check("void foo()\n"
"{\n"
" int y = 1;\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" {\n"
" --y;\n"
" }\n"
" case 3:\n"
" y = 3;\n"
" }\n"
" bar(y);\n"
"}");
ASSERT_EQUALS("[test.cpp:8] -> [test.cpp:11]: (style) Variable 'y' is reassigned a value before the old one has been used. 'break;' missing?\n", errout_str());
check("void foo()\n"
"{\n"
" int y = 1;\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" (void)y;\n"
" case 3:\n"
" --y;\n"
" }\n"
" bar(y);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo()\n"
"{\n"
" int y = 1;\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" --y;\n"
" case 3:\n"
" --y;\n"
" }\n"
" bar(y);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo()\n"
"{\n"
" int y = 1;\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" y++;\n"
" case 3:\n"
" y = 3;\n"
" }\n"
" bar(y);\n"
"}");
ASSERT_EQUALS("[test.cpp:7] -> [test.cpp:9]: (style) Variable 'y' is reassigned a value before the old one has been used. 'break;' missing?\n", errout_str());
check("void foo()\n"
"{\n"
" int y = 1;\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" {\n"
" y++;\n"
" }\n"
" case 3:\n"
" y = 3;\n"
" }\n"
" bar(y);\n"
"}");
ASSERT_EQUALS("[test.cpp:8] -> [test.cpp:11]: (style) Variable 'y' is reassigned a value before the old one has been used. 'break;' missing?\n", errout_str());
check("void foo()\n"
"{\n"
" int y = 1;\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" y = 2;\n"
" case 3:\n"
" y++;\n"
" }\n"
" bar(y);\n"
"}", true, false, false);
ASSERT_EQUALS("", errout_str());
check("void foo()\n"
"{\n"
" int y = 1;\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" y++;\n"
" case 3:\n"
" y++;\n"
" }\n"
" bar(y);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo()\n"
"{\n"
" int y = 1;\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" y--;\n"
" case 3:\n"
" y = 3;\n"
" }\n"
" bar(y);\n"
"}");
ASSERT_EQUALS("[test.cpp:7] -> [test.cpp:9]: (style) Variable 'y' is reassigned a value before the old one has been used. 'break;' missing?\n", errout_str());
check("void foo()\n"
"{\n"
" int y = 1;\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" {\n"
" y--;\n"
" }\n"
" case 3:\n"
" y = 3;\n"
" }\n"
" bar(y);\n"
"}");
ASSERT_EQUALS("[test.cpp:8] -> [test.cpp:11]: (style) Variable 'y' is reassigned a value before the old one has been used. 'break;' missing?\n", errout_str());
check("void foo()\n"
"{\n"
" int y = 1;\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" y = 2;\n"
" case 3:\n"
" y--;\n"
" }\n"
" bar(y);\n"
"}", true, false, false);
ASSERT_EQUALS("", errout_str());
check("void foo()\n"
"{\n"
" int y = 1;\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" y--;\n"
" case 3:\n"
" y--;\n"
" }\n"
" bar(y);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo()\n"
"{\n"
" int y = 1;\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" y++;\n"
" case 3:\n"
" if (x)\n"
" {\n"
" y = 3;\n"
" }\n"
" }\n"
" bar(y);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo()\n"
"{\n"
" int y = 1;\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" {\n"
" y++;\n"
" if (y)\n"
" printf(\"%d\", y);\n"
" }\n"
" case 3:\n"
" y = 3;\n"
" }\n"
" bar(y);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo()\n"
"{\n"
" int x = a;\n"
" int y = 1;\n"
" switch (x)\n"
" {\n"
" case 2:\n"
" x++;\n"
" case 3:\n"
" y++;\n"
" }\n"
" bar(y);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo()\n"
"{\n"
" int y = 1;\n"
" switch (x)\n"
" {\n"
" case 2:\n"
" y++;\n"
" break;\n"
" case 3:\n"
" y = 3;\n"
" }\n"
" bar(y);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo()\n"
"{\n"
" int y = 1;\n"
" while(xyz()) {\n"
" switch (x)\n"
" {\n"
" case 2:\n"
" y++;\n"
" continue;\n"
" case 3:\n"
" y = 3;\n"
" }\n"
" bar(y);\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo()\n"
"{\n"
" int y = 1;\n"
" while(xyz()) {\n"
" switch (x)\n"
" {\n"
" case 2:\n"
" y++;\n"
" throw e;\n"
" case 3:\n"
" y = 3;\n"
" }\n"
" bar(y);\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo()\n"
"{\n"
" int y = 1;\n"
" switch (x)\n"
" {\n"
" case 2:\n"
" y++;\n"
" printf(\"%d\", y);\n"
" case 3:\n"
" y = 3;\n"
" }\n"
" bar(y);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo()\n"
"{\n"
" int y = 1;\n"
" switch (x)\n"
" {\n"
" case 2:\n"
" y++;\n"
" bar();\n"
" case 3:\n"
" y = 3;\n"
" }\n"
" bar(y);\n"
"}");
ASSERT_EQUALS("[test.cpp:7] -> [test.cpp:10]: (style) Variable 'y' is reassigned a value before the old one has been used. 'break;' missing?\n", errout_str());
check("bool f() {\n"
" bool ret = false;\n"
" switch (switchCond) {\n"
" case 1:\n"
" ret = true;\n"
" break;\n"
" case 31:\n"
" ret = true;\n"
" break;\n"
" case 54:\n"
" ret = true;\n"
" break;\n"
" };\n"
" ret = true;\n"
" return ret;\n"
"}");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:14]: (style) Variable 'ret' is reassigned a value before the old one has been used.\n"
"[test.cpp:8] -> [test.cpp:14]: (style) Variable 'ret' is reassigned a value before the old one has been used.\n"
"[test.cpp:11] -> [test.cpp:14]: (style) Variable 'ret' is reassigned a value before the old one has been used.\n",
errout_str());
}
void switchRedundantBitwiseOperationTest() {
check("void foo(int a)\n"
"{\n"
" int y = 1;\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" y |= 3;\n"
" case 3:\n"
" y |= 3;\n"
" break;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (style) Redundant bitwise operation on 'y' in 'switch' statement. 'break;' missing?\n", errout_str());
check("void foo(int a)\n"
"{\n"
" int y = 1;\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" y = y | 3;\n"
" case 3:\n"
" y = y | 3;\n"
" break;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (style) Redundant bitwise operation on 'y' in 'switch' statement. 'break;' missing?\n", errout_str());
check("void foo(int a)\n"
"{\n"
" int y = 1;\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" y |= 3;\n"
" default:\n"
" y |= 3;\n"
" break;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (style) Redundant bitwise operation on 'y' in 'switch' statement. 'break;' missing?\n", errout_str());
check("void foo(int a)\n"
"{\n"
" int y = 1;\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" y |= 3;\n"
" default:\n"
" if (z)\n"
" y |= 3;\n"
" break;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(int a)\n"
"{\n"
" int y = 1;\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" y |= z;\n"
" z++\n"
" default:\n"
" y |= z;\n"
" break;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(int a)\n"
"{\n"
" int y = 1;\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" y |= 3;\n"
" bar(y);\n"
" case 3:\n"
" y |= 3;\n"
" break;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(int a)\n"
"{\n"
" int y = 1;\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" y |= 3;\n"
" y = 4;\n"
" case 3:\n"
" y |= 3;\n"
" break;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:7] -> [test.cpp:8]: (style) Variable 'y' is reassigned a value before the old one has been used.\n", errout_str());
check("void foo(int a)\n"
"{\n"
" int y = 1;\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" y &= 3;\n"
" case 3:\n"
" y &= 3;\n"
" break;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (style) Redundant bitwise operation on 'y' in 'switch' statement. 'break;' missing?\n", errout_str());
check("void foo(int a)\n"
"{\n"
" int y = 1;\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" y |= 3;\n"
" break;\n"
" case 3:\n"
" y |= 3;\n"
" break;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(int a)\n"
"{\n"
" int y = 1;\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" y ^= 3;\n"
" case 3:\n"
" y ^= 3;\n"
" break;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(int a)\n"
"{\n"
" int y = 1;\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" y |= 2;\n"
" case 3:\n"
" y |= 3;\n"
" break;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(int a)\n"
"{\n"
" int y = 1;\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" y &= 2;\n"
" case 3:\n"
" y &= 3;\n"
" break;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(int a)\n"
"{\n"
" int y = 1;\n"
" switch (a)\n"
" {\n"
" case 2:\n"
" y |= 2;\n"
" case 3:\n"
" y &= 2;\n"
" break;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void unreachableCode() {
check("void foo(int a) {\n"
" while(1) {\n"
" if (a++ >= 100) {\n"
" break;\n"
" continue;\n"
" }\n"
" }\n"
"}", true, false, false);
ASSERT_EQUALS("[test.cpp:5]: (style) Consecutive return, break, continue, goto or throw statements are unnecessary.\n", errout_str());
check("int foo(int a) {\n"
" return 0;\n"
" return(a-1);\n"
"}", true, false, false);
ASSERT_EQUALS("[test.cpp:3]: (style) Consecutive return, break, continue, goto or throw statements are unnecessary.\n", errout_str());
check("int foo(int a) {\n"
" A:"
" return(0);\n"
" goto A;\n"
"}", true, false, false);
ASSERT_EQUALS("[test.cpp:3]: (style) Consecutive return, break, continue, goto or throw statements are unnecessary.\n", errout_str());
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <function name=\"exit\">\n"
" <noreturn>true</noreturn>\n"
" <arg nr=\"1\"/>\n"
" </function>\n"
"</def>";
/*const*/ Settings settings = settingsBuilder().libraryxml(xmldata, sizeof(xmldata)).build();
check("void foo() {\n"
" exit(0);\n"
" break;\n"
"}", true, false, false, false, &settings);
ASSERT_EQUALS("[test.cpp:3]: (style) Consecutive return, break, continue, goto or throw statements are unnecessary.\n", errout_str());
check("class NeonSession {\n"
" void exit();\n"
"};\n"
"void NeonSession::exit()\n"
"{\n"
" SAL_INFO(\"ucb.ucp.webdav\", \"neon commands cannot be aborted\");\n"
"}", true, false, false, false, &settings);
ASSERT_EQUALS("", errout_str());
check("void NeonSession::exit()\n"
"{\n"
" SAL_INFO(\"ucb.ucp.webdav\", \"neon commands cannot be aborted\");\n"
"}", true, false, false, false, &settings);
ASSERT_EQUALS("", errout_str());
check("void foo() { xResAccess->exit(); }", true, false, false, false, &settings);
ASSERT_EQUALS("", errout_str());
check("void foo(int a)\n"
"{\n"
" switch(a) {\n"
" case 0:\n"
" printf(\"case 0\");\n"
" break;\n"
" break;\n"
" case 1:\n"
" c++;\n"
" break;\n"
" }\n"
"}", true, false, false);
ASSERT_EQUALS("[test.cpp:7]: (style) Consecutive return, break, continue, goto or throw statements are unnecessary.\n", errout_str());
check("void foo(int a)\n"
"{\n"
" switch(a) {\n"
" case 0:\n"
" printf(\"case 0\");\n"
" break;\n"
" case 1:\n"
" c++;\n"
" break;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(int a)\n"
"{\n"
" while(true) {\n"
" if (a++ >= 100) {\n"
" break;\n"
" break;\n"
" }\n"
" }\n"
"}", true, false, false);
ASSERT_EQUALS("[test.cpp:6]: (style) Consecutive return, break, continue, goto or throw statements are unnecessary.\n", errout_str());
check("void foo(int a)\n"
"{\n"
" while(true) {\n"
" if (a++ >= 100) {\n"
" continue;\n"
" continue;\n"
" }\n"
" a+=2;\n"
" }\n"
"}", true, false, false);
ASSERT_EQUALS("[test.cpp:6]: (style) Consecutive return, break, continue, goto or throw statements are unnecessary.\n", errout_str());
check("void foo(int a)\n"
"{\n"
" while(true) {\n"
" if (a++ >= 100) {\n"
" continue;\n"
" }\n"
" a+=2;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int foo() {\n"
" throw 0;\n"
" return 1;\n"
"}", true, false, false);
ASSERT_EQUALS("[test.cpp:3]: (style) Consecutive return, break, continue, goto or throw statements are unnecessary.\n", errout_str());
check("void foo() {\n"
" throw 0;\n"
" return;\n"
"}", true, false, false);
ASSERT_EQUALS("[test.cpp:3]: (style) Consecutive return, break, continue, goto or throw statements are unnecessary.\n", errout_str());
check("int foo() {\n"
" throw = 0;\n"
" return 1;\n"
"}", false, false, false);
ASSERT_EQUALS("", errout_str());
check("int foo() {\n"
" return 0;\n"
" return 1;\n"
"}", true, false, false, false);
ASSERT_EQUALS("[test.cpp:3]: (style) Consecutive return, break, continue, goto or throw statements are unnecessary.\n", errout_str());
check("int foo() {\n"
" return 0;\n"
" foo();\n"
"}", true, false, false);
ASSERT_EQUALS("[test.cpp:3]: (style) Statements following 'return' will never be executed.\n", errout_str());
check("int foo(int unused) {\n"
" return 0;\n"
" (void)unused;\n"
"}", true, false, false);
ASSERT_EQUALS("", errout_str());
check("int foo(int unused1, int unused2) {\n"
" return 0;\n"
" (void)unused1;\n"
" (void)unused2;\n"
"}", true, false, false);
ASSERT_EQUALS("", errout_str());
check("int foo(int unused1, int unused2) {\n"
" return 0;\n"
" (void)unused1;\n"
" (void)unused2;\n"
" foo();\n"
"}", true, false, false);
ASSERT_EQUALS("[test.cpp:5]: (style) Statements following 'return' will never be executed.\n", errout_str());
check("int foo() {\n"
" if(bar)\n"
" return 0;\n"
" return 124;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int foo() {\n"
" while(bar) {\n"
" return 0;\n"
" return 0;\n"
" return 0;\n"
" return 0;\n"
" }\n"
" return 124;\n"
"}", true, false, false);
ASSERT_EQUALS("[test.cpp:4]: (style) Consecutive return, break, continue, goto or throw statements are unnecessary.\n", errout_str());
check("void foo() {\n"
" while(bar) {\n"
" return;\n"
" break;\n"
" }\n"
"}", true, false, false);
ASSERT_EQUALS("[test.cpp:4]: (style) Consecutive return, break, continue, goto or throw statements are unnecessary.\n", errout_str());
// #5707
check("extern int i,j;\n"
"int foo() {\n"
" switch(i) {\n"
" default: j=1; break;\n"
" }\n"
" return 0;\n"
" j=2;\n"
"}", true, false, false);
ASSERT_EQUALS("[test.cpp:7]: (style) Statements following 'return' will never be executed.\n", errout_str());
check("int foo() {\n"
" return 0;\n"
" label:\n"
" throw 0;\n"
"}", true, false, false);
ASSERT_EQUALS("[test.cpp:3]: (style) Label 'label' is not used.\n", errout_str());
check("struct A {\n"
" virtual void foo (P & Val) throw ();\n"
" virtual void foo1 (P & Val) throw ();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int foo() {\n"
" goto label;\n"
" while (true) {\n"
" bar();\n"
" label:\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str()); // #3457
check("int foo() {\n"
" goto label;\n"
" do {\n"
" bar();\n"
" label:\n"
" } while (true);\n"
"}");
ASSERT_EQUALS("", errout_str()); // #3457
check("int foo() {\n"
" goto label;\n"
" for (;;) {\n"
" bar();\n"
" label:\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str()); // #3457
// #3383. TODO: Use preprocessor
check("int foo() {\n"
"\n" // #ifdef A
" return 0;\n"
"\n" // #endif
" return 1;\n"
"}", true, false, false);
ASSERT_EQUALS("", errout_str());
check("int foo() {\n"
"\n" // #ifdef A
" return 0;\n"
"\n" // #endif
" return 1;\n"
"}", true, true, false);
ASSERT_EQUALS("[test.cpp:5]: (style, inconclusive) Consecutive return, break, continue, goto or throw statements are unnecessary.\n", errout_str());
// #4711 lambda functions
check("int f() {\n"
" return g([](int x){(void)x+1; return x;});\n"
"}",
true,
false,
false);
ASSERT_EQUALS("", errout_str());
// #4756
check("template <>\n"
"inline uint16_t htobe(uint16_t value) {\n"
" return ( __extension__ ({\n"
" register unsigned short int __v, __x = (unsigned short int) (value);\n"
" if (__builtin_constant_p (__x))\n"
" __v = ((unsigned short int) ((((__x) >> 8) & 0xff) | (((__x) & 0xff) << 8)));\n"
" else\n"
" __asm__ (\"rorw $8, %w0\" : \"=r\" (__v) : \"0\" (__x) : \"cc\");\n"
" (void)__v;\n"
" }));\n"
"}", true, false, false);
ASSERT_EQUALS("", errout_str());
// #6008
check("static std::function< int ( int, int ) > GetFunctor() {\n"
" return [](int a_, int b_) -> int {\n"
" int sum = a_ + b_;\n"
" return sum;\n"
" };\n"
"}", true, false, false);
ASSERT_EQUALS("", errout_str());
// #5789
check("struct per_state_info {\n"
" uint64_t enter, exit;\n"
" uint64_t events;\n"
" per_state_info() : enter(0), exit(0), events(0) {}\n"
"};", true, false, false);
ASSERT_EQUALS("", errout_str());
// #6664
check("void foo() {\n"
" (beat < 100) ? (void)0 : exit(0);\n"
" bar();\n"
"}", true, false, false, false, &settings);
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" (beat < 100) ? exit(0) : (void)0;\n"
" bar();\n"
"}", true, false, false, false, &settings);
ASSERT_EQUALS("", errout_str());
// #8261
// TODO Do not throw AST validation exception
TODO_ASSERT_THROW(check("void foo() {\n"
" (beat < 100) ? (void)0 : throw(0);\n"
" bar();\n"
"}", true, false, false, false, &settings), InternalError);
//ASSERT_EQUALS("", errout_str());
check("int foo() {\n"
" exit(0);\n"
" return 1;\n" // <- clarify for tools that function does not continue..
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" enum : uint8_t { A, B } var = A;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkP("#define INB(x) __extension__ ({ u_int tmp = (x); inb(tmp); })\n" // #4739
"static unsigned char cmos_hal_read(unsigned index) {\n"
" unsigned short port_0, port_1;\n"
" assert(!verify_cmos_byte_index(index));\n"
" if (index < 128) {\n"
" port_0 = 0x70;\n"
" port_1 = 0x71;\n"
" }\n"
" else {\n"
" port_0 = 0x72;\n"
" port_1 = 0x73;\n"
" }\n"
" OUTB(index, port_0);\n"
" return INB(port_1);\n"
"}\n", "test.c");
ASSERT_EQUALS("", errout_str());
check("[[noreturn]] void n();\n"
"void f() {\n"
" n();\n"
" g();\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (style) Statements following noreturn function 'n()' will never be executed.\n", errout_str());
check("void f() {\n"
" exit(1);\n"
" g();\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) Statements following noreturn function 'exit()' will never be executed.\n", errout_str());
check("void f() {\n"
" do {\n"
" break;\n"
" g();\n"
" } while (0);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (style) Statements following 'break' will never be executed.\n", errout_str());
check("void f() {\n" // #12244
" {\n"
" std::cout << \"x\";\n"
" return;\n"
" }\n"
" std::cout << \"y\";\n"
"}\n");
ASSERT_EQUALS("[test.cpp:6]: (style) Statements following 'return' will never be executed.\n", errout_str());
check("void f() {\n"
" {\n"
" std::cout << \"x\";\n"
" exit(1);\n"
" }\n"
" std::cout << \"y\";\n"
"}\n");
ASSERT_EQUALS("[test.cpp:6]: (style) Statements following noreturn function 'exit()' will never be executed.\n", errout_str());
}
void redundantContinue() {
check("void f() {\n" // #11195
" for (int i = 0; i < 10; ++i) {\n"
" printf(\"i = %d\\n\", i);\n"
" continue;\n"
" }\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (style) 'continue' is redundant since it is the last statement in a loop.\n", errout_str());
check("void f() {\n"
" int i = 0;"
" do {\n"
" ++i;\n"
" printf(\"i = %d\\n\", i);\n"
" continue;\n"
" } while (i < 10);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5]: (style) 'continue' is redundant since it is the last statement in a loop.\n", errout_str());
check("int f() {\n" // #13475
" { return 0; };\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("int f(int i) {\n" // #13478
" int x = 0;\n"
" switch (i) {\n"
" { case 0: x = 5; break; }\n"
" { case 1: x = 7; break; }\n"
" }\n"
" return x;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void suspiciousCase() {
check("void foo() {\n"
" switch(a) {\n"
" case A&&B:\n"
" foo();\n"
" case (A||B):\n"
" foo();\n"
" case A||B:\n"
" foo();\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning, inconclusive) Found suspicious case label in switch(). Operator '&&' probably doesn't work as intended.\n"
"[test.cpp:5]: (warning, inconclusive) Found suspicious case label in switch(). Operator '||' probably doesn't work as intended.\n"
"[test.cpp:7]: (warning, inconclusive) Found suspicious case label in switch(). Operator '||' probably doesn't work as intended.\n", errout_str());
check("void foo() {\n"
" switch(a) {\n"
" case 1:\n"
" a=A&&B;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// TODO Do not throw AST validation exception
TODO_ASSERT_THROW(check("void foo() {\n"
" switch(a) {\n"
" case A&&B?B:A:\n"
" foo();\n"
" }\n"
"}"), InternalError);
//ASSERT_EQUALS("", errout_str());
}
void suspiciousEqualityComparison() {
check("void foo(int c) {\n"
" if (x) c == 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning, inconclusive) Found suspicious equality comparison. Did you intend to assign a value instead?\n", errout_str());
check("void foo(const int* c) {\n"
" if (x) *c == 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning, inconclusive) Found suspicious equality comparison. Did you intend to assign a value instead?\n", errout_str());
check("void foo(int c) {\n"
" if (c == 1) {\n"
" c = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(int c) {\n"
" c == 1;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning, inconclusive) Found suspicious equality comparison. Did you intend to assign a value instead?\n", errout_str());
check("void foo(int c) {\n"
" for (int i = 0; i == 10; i ++) {\n"
" a ++;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(int c) {\n"
" for (i == 0; i < 10; i ++) {\n"
" c ++;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning, inconclusive) Found suspicious equality comparison. Did you intend to assign a value instead?\n", errout_str());
check("void foo(int c) {\n"
" for (i == 1; i < 10; i ++) {\n"
" c ++;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning, inconclusive) Found suspicious equality comparison. Did you intend to assign a value instead?\n", errout_str());
check("void foo(int c) {\n"
" for (i == 2; i < 10; i ++) {\n"
" c ++;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning, inconclusive) Found suspicious equality comparison. Did you intend to assign a value instead?\n", errout_str());
check("void foo(int c) {\n"
" for (int i = 0; i < 10; i == c) {\n"
" c ++;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning, inconclusive) Found suspicious equality comparison. Did you intend to assign a value instead?\n", errout_str());
check("void foo(int c) {\n"
" for (; running == 1;) {\n"
" c ++;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(int c) {\n"
" printf(\"%i\", ({x==0;}));\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(int arg) {\n"
" printf(\"%i\", ({int x = do_something(); x == 0;}));\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(int x) {\n"
" printf(\"%i\", ({x == 0; x > 0 ? 10 : 20}));\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning, inconclusive) Found suspicious equality comparison. Did you intend to assign a value instead?\n", errout_str());
check("void foo(int x) {\n"
" for (const Token* end = tok->link(); tok != end; tok = (tok == end) ? end : tok->next()) {\n"
" x++;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(int x) {\n"
" for (int i = (x == 0) ? 0 : 5; i < 10; i ++) {\n"
" x++;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(int x) {\n"
" for (int i = 0; i < 10; i += (x == 5) ? 1 : 2) {\n"
" x++;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void suspiciousUnaryPlusMinus() { // #8004
check("int g() { return 1; }\n"
"void f() {\n"
" +g();\n"
" -g();\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (warning, inconclusive) Found suspicious operator '+', result is not used.\n"
"[test.cpp:4]: (warning, inconclusive) Found suspicious operator '-', result is not used.\n",
errout_str());
check("void f(int i) {\n"
" +i;\n"
" -i;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (warning, inconclusive) Found suspicious operator '+', result is not used.\n"
"[test.cpp:3]: (warning, inconclusive) Found suspicious operator '-', result is not used.\n",
errout_str());
}
void suspiciousFloatingPointCast() {
check("double f(double a, double b, float c) {\n"
" return a + (float)b + c;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Floating-point cast causes loss of precision.\n", errout_str());
check("double f(double a, double b, float c) {\n"
" return a + static_cast<float>(b) + c;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Floating-point cast causes loss of precision.\n", errout_str());
check("long double f(long double a, long double b, float c) {\n"
" return a + (double)b + c;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Floating-point cast causes loss of precision.\n", errout_str());
check("void g(int, double);\n"
"void h(double);\n"
"void f(double d) {\n"
" g(1, (float)d);\n"
" h((float)d);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (style) Floating-point cast causes loss of precision.\n"
"[test.cpp:5]: (style) Floating-point cast causes loss of precision.\n",
errout_str());
}
void selfAssignment() {
check("void foo()\n"
"{\n"
" int x = 1;\n"
" x = x;\n"
" return 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Redundant assignment of 'x' to itself.\n", errout_str());
check("void foo()\n"
"{\n"
" int x = x;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Redundant assignment of 'x' to itself.\n", errout_str());
check("struct A { int b; };\n"
"void foo(A* a1, A* a2) {\n"
" a1->b = a1->b;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Redundant assignment of 'a1->b' to itself.\n", errout_str());
check("int x;\n"
"void f()\n"
"{\n"
" x = x = 3;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Redundant assignment of 'x' to itself.\n", errout_str());
// #4073 (segmentation fault)
check("void Foo::myFunc( int a )\n"
"{\n"
" if (a == 42)\n"
" a = a;\n"
"}");
check("void foo()\n"
"{\n"
" int x = 1;\n"
" x = x + 1;\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo()\n"
"{\n"
" int *x = getx();\n"
" *x = x;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" BAR *x = getx();\n"
" x = x;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Redundant assignment of 'x' to itself.\n", errout_str());
// #2502 - non-primitive type -> there might be some side effects
check("void foo()\n"
"{\n"
" Fred fred; fred = fred;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
" x = (x == 0);"
" func(x);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
" x = (x != 0);"
" func(x);\n"
"}");
ASSERT_EQUALS("", errout_str());
// ticket #3001 - false positive
check("void foo(int x) {\n"
" x = x ? x : 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #3800 - false negative when variable is extern
check("extern int i;\n"
"void f() {\n"
" i = i;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Redundant assignment of 'i' to itself.\n", errout_str());
// #4291 - id for variables accessed through 'this'
check("class Foo {\n"
" int var;\n"
" void func();\n"
"};\n"
"void Foo::func() {\n"
" this->var = var;\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (style) Redundant assignment of 'this->var' to itself.\n", errout_str());
check("class Foo {\n"
" int var;\n"
" void func(int var);\n"
"};\n"
"void Foo::func(int var) {\n"
" this->var = var;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #6406 - designated initializer doing bogus self assignment
check("struct callbacks {\n"
" void (*s)(void);\n"
"};\n"
"void something(void) {}\n"
"void f() {\n"
" struct callbacks ops = { .s = ops.s };\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:6]: (style) Redundant assignment of 'something' to itself.\n", "", errout_str());
check("class V\n"
"{\n"
"public:\n"
" V()\n"
" {\n"
" x = y = z = 0.0;\n"
" }\n"
" V( double x, const double y_, const double &z_)\n"
" {\n"
" x = x; y = y; z = z;\n"
" }\n"
" double x, y, z;\n"
"};");
ASSERT_EQUALS("[test.cpp:10]: (style) Redundant assignment of 'x' to itself.\n"
"[test.cpp:10]: (style) Redundant assignment of 'y' to itself.\n"
"[test.cpp:10]: (style) Redundant assignment of 'z' to itself.\n", errout_str());
check("void f(int i) { i = !!i; }");
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" int x = 1;\n"
" int &ref = x;\n"
" ref = x;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (style) Redundant assignment of 'ref' to itself.\n", errout_str());
check("class Foo {\n" // #9850
" int i{};\n"
" void modify();\n"
" void method() {\n"
" Foo copy = *this;\n"
" modify();\n"
" *this = copy;\n"
" }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
check("struct S {\n" // #11383
" void f() {\n"
" int x = 42;"
" auto l2 = [i = i, x, y = 0]() { return i + x + y; };\n"
" }\n"
" int i;\n"
"};\n");
ASSERT_EQUALS("", errout_str());
check("void f() {\n" // #10337
" int b[2] = { 1, 2 };\n"
" int idx = 0;\n"
" int& i = b[idx];\n"
" idx++;\n"
" i = b[idx];\n"
"};\n");
ASSERT_EQUALS("", errout_str());
check("void g(int*);\n" // #12390
"void f() {\n"
" int o = s.i;\n"
" g(&s.i);\n"
" s.i = o;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void trac1132() {
check("class Lock\n"
"{\n"
"public:\n"
" Lock(int i)\n"
" {\n"
" std::cout << \"Lock \" << i << std::endl;\n"
" }\n"
" ~Lock()\n"
" {\n"
" std::cout << \"~Lock\" << std::endl;\n"
" }\n"
"};\n"
"int main()\n"
"{\n"
" Lock(123);\n"
" std::cout << \"hello\" << std::endl;\n"
" return 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:15]: (style) Instance of 'Lock' object is destroyed immediately.\n", errout_str());
}
void trac3693() {
check("struct A{\n"
" enum {\n"
" b = 300\n"
" };\n"
"};\n"
"const int DFLT_TIMEOUT = A::b % 1000000 ;\n", true, false, false);
ASSERT_EQUALS("", errout_str());
}
void testMisusedScopeObjectDoesNotPickFunction1() {
check("int main ( )\n"
"{\n"
" CouldBeFunction ( 123 ) ;\n"
" return 0 ;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void testMisusedScopeObjectDoesNotPickFunction2() {
check("struct error {\n"
" error() {}\n"
"};\n"
"\n"
"class parser {\n"
"public:\n"
" void error() const {}\n"
"\n"
" void foo() const {\n"
" error();\n"
" do_something();\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void testMisusedScopeObjectPicksClass() {
check("class NotAFunction ;\n"
"int function ( )\n"
"{\n"
" NotAFunction ( 123 );\n"
" return 0 ;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Instance of 'NotAFunction' object is destroyed immediately.\n", errout_str());
}
void testMisusedScopeObjectPicksStruct() {
check("struct NotAClass;\n"
"bool func ( )\n"
"{\n"
" NotAClass ( 123 ) ;\n"
" return true ;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Instance of 'NotAClass' object is destroyed immediately.\n", errout_str());
}
void testMisusedScopeObjectDoesNotPickIf() {
check("bool func( int a , int b , int c )\n"
"{\n"
" if ( a > b ) return c == a ;\n"
" return b == a ;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void testMisusedScopeObjectDoesNotPickConstructorDeclaration() {
check("class Something : public SomethingElse\n"
"{\n"
"public:\n"
"~Something ( ) ;\n"
"Something ( ) ;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void testMisusedScopeObjectDoesNotPickFunctor() {
check("class IncrementFunctor\n"
"{\n"
"public:\n"
" void operator()(int &i)\n"
" {\n"
" ++i;\n"
" }\n"
"};\n"
"\n"
"int main()\n"
"{\n"
" int a = 1;\n"
" IncrementFunctor()(a);\n"
" return a;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void testMisusedScopeObjectDoesNotPickLocalClassConstructors() {
check("void f() {\n"
" class Foo {\n"
" Foo() { }\n"
" Foo(int a) { }\n"
" Foo(int a, int b) { }\n"
" };\n"
" Foo();\n"
" do_something();\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (style) Instance of 'Foo' object is destroyed immediately.\n", errout_str());
}
void testMisusedScopeObjectDoesNotPickUsedObject() {
check("struct Foo {\n"
" void bar() {\n"
" }\n"
"};\n"
"\n"
"void fn() {\n"
" Foo().bar();\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void testMisusedScopeObjectDoesNotPickPureC() {
// Ticket #2352
const char code[] = "struct cb_watch_bool {\n"
" int a;\n"
"};\n"
"\n"
"void f()\n"
"{\n"
" cb_watch_bool();\n"
" do_something();\n"
"}\n";
check(code, true);
ASSERT_EQUALS("[test.cpp:7]: (style) Instance of 'cb_watch_bool' object is destroyed immediately.\n", errout_str());
check(code, false);
ASSERT_EQUALS("", errout_str());
// Ticket #2639
check("struct stat { int a; int b; };\n"
"void stat(const char *fn, struct stat *);\n"
"\n"
"void foo() {\n"
" stat(\"file.txt\", &st);\n"
" do_something();\n"
"}");
ASSERT_EQUALS("",errout_str());
check("struct AMethodObject {\n" // #4336
" AMethodObject(double, double, double);\n"
"};\n"
"struct S {\n"
" static void A(double, double, double);\n"
"};\n"
"void S::A(double const a1, double const a2, double const a3) {\n"
" AMethodObject(a1, a2, a3);\n"
"}\n");
ASSERT_EQUALS("",errout_str());
}
void testMisusedScopeObjectDoesNotPickNestedClass() {
const char code[] = "class ios_base {\n"
"public:\n"
" class Init {\n"
" public:\n"
" };\n"
"};\n"
"class foo {\n"
"public:\n"
" foo();\n"
" void Init(int);\n"
"};\n"
"foo::foo() {\n"
" Init(0);\n"
" do_something();\n"
"}\n";
check(code, true);
ASSERT_EQUALS("", errout_str());
}
void testMisusedScopeObjectInConstructor() {
const char code[] = "class Foo {\n"
"public:\n"
" Foo(char x) {\n"
" Foo(x, 0);\n"
" do_something();\n"
" }\n"
" Foo(char x, int y) { }\n"
"};\n";
check(code, true);
ASSERT_EQUALS("[test.cpp:4]: (style) Instance of 'Foo' object is destroyed immediately.\n", errout_str());
}
void testMisusedScopeObjectStandardType() {
check("int g();\n"
"void f(int i) {\n"
" int();\n"
" int(0);\n"
" int( g() );\n" // don't warn
" int{};\n"
" int{ 0 };\n"
" int{ i };\n"
" int{ g() };\n" // don't warn
" g();\n"
"}\n", true);
ASSERT_EQUALS("[test.cpp:3]: (style) Instance of 'int' object is destroyed immediately.\n"
"[test.cpp:4]: (style) Instance of 'int' object is destroyed immediately.\n"
"[test.cpp:6]: (style) Instance of 'int' object is destroyed immediately.\n"
"[test.cpp:7]: (style) Instance of 'int' object is destroyed immediately.\n"
"[test.cpp:8]: (style) Instance of 'int' object is destroyed immediately.\n",
errout_str());
check("void f(int j) {\n"
" for (; bool(j); ) {}\n"
"}\n", true);
ASSERT_EQUALS("", errout_str());
check("void g() {\n"
" float (f);\n"
" float (*p);\n"
"}\n", true);
ASSERT_EQUALS("", errout_str());
check("int f(int i) {\n"
" void();\n"
" return i;\n"
"}\n", true);
ASSERT_EQUALS("", errout_str());
}
void testMisusedScopeObjectNamespace() {
check("namespace M {\n" // #4779
" namespace N {\n"
" struct S {};\n"
" }\n"
"}\n"
"int f() {\n"
" M::N::S();\n"
" return 0;\n"
"}\n", true);
ASSERT_EQUALS("[test.cpp:7]: (style) Instance of 'M::N::S' object is destroyed immediately.\n", errout_str());
check("void f() {\n" // #10057
" std::string(\"abc\");\n"
" std::string{ \"abc\" };\n"
" std::pair<int, int>(1, 2);\n"
" (void)0;\n"
"}\n", true);
ASSERT_EQUALS("[test.cpp:2]: (style) Instance of 'std::string' object is destroyed immediately.\n"
"[test.cpp:3]: (style) Instance of 'std::string' object is destroyed immediately.\n"
"[test.cpp:4]: (style) Instance of 'std::pair' object is destroyed immediately.\n",
errout_str());
check("struct S {\n" // #10083
" void f() {\n"
" std::lock_guard<std::mutex>(m);\n"
" }\n"
" void g() {\n"
" std::scoped_lock<std::mutex>(m);\n"
" }\n"
" void h() {\n"
" std::scoped_lock(m);\n"
" }\n"
" std::mutex m;\n"
"}\n", true);
ASSERT_EQUALS("[test.cpp:3]: (style) Instance of 'std::lock_guard' object is destroyed immediately.\n"
"[test.cpp:6]: (style) Instance of 'std::scoped_lock' object is destroyed immediately.\n"
"[test.cpp:9]: (style) Instance of 'std::scoped_lock' object is destroyed immediately.\n",
errout_str());
check("struct S { int i; };\n"
"namespace {\n"
" S s() { return ::S{42}; }\n"
"}\n", true);
ASSERT_EQUALS("", errout_str());
}
void testMisusedScopeObjectAssignment() { // #11371
check("struct S;\n"
"S f();\n"
"S& g();\n"
"S&& h();\n"
"S* i();\n"
"void t0() { f() = {}; }\n"
"void t1() { g() = {}; }\n"
"void t2() { h() = {}; }\n"
"void t3() { *i() = {}; }\n", true);
ASSERT_EQUALS("[test.cpp:6]: (style) Instance of 'S' object is destroyed immediately, assignment has no effect.\n", errout_str());
}
void trac2084() {
check("void f()\n"
"{\n"
" struct sigaction sa;\n"
"\n"
" { sigaction(SIGHUP, &sa, 0); };\n"
" { sigaction(SIGINT, &sa, 0); };\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void trac2071() {
check("void f() {\n"
" struct AB {\n"
" AB(int a) { }\n"
" };\n"
"\n"
" const AB ab[3] = { AB(0), AB(1), AB(2) };\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void clarifyCalculation() {
check("int f(char c) {\n"
" return 10 * (c == 0) ? 1 : 2;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Clarify calculation precedence for '*' and '?'.\n", errout_str());
check("void f(char c) {\n"
" printf(\"%i\", 10 * (c == 0) ? 1 : 2);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Clarify calculation precedence for '*' and '?'.\n", errout_str());
check("void f() {\n"
" return (2*a)?b:c;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(char c) {\n"
" printf(\"%i\", a + b ? 1 : 2);\n"
"}",true,false,false);
ASSERT_EQUALS("[test.cpp:2]: (style) Clarify calculation precedence for '+' and '?'.\n", errout_str());
check("void f() {\n"
" std::cout << x << y ? 2 : 3;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Clarify calculation precedence for '<<' and '?'.\n", errout_str());
check("void f() {\n"
" int ab = a - b ? 2 : 3;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Clarify calculation precedence for '-' and '?'.\n", errout_str());
check("void f() {\n"
" int ab = a | b ? 2 : 3;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Clarify calculation precedence for '|' and '?'.\n", errout_str());
// ticket #195
check("int f(int x, int y) {\n"
" return x >> ! y ? 8 : 2;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Clarify calculation precedence for '>>' and '?'.\n", errout_str());
check("int f() {\n"
" return shift < sizeof(int64_t)*8 ? 1 : 2;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() { a = *p ? 1 : 2; }");
ASSERT_EQUALS("", errout_str());
check("void f(int x) { const char *p = x & 1 ? \"1\" : \"0\"; }");
ASSERT_EQUALS("", errout_str());
check("void foo() { x = a % b ? \"1\" : \"0\"; }");
ASSERT_EQUALS("", errout_str());
check("void f(int x) { return x & 1 ? '1' : '0'; }");
ASSERT_EQUALS("", errout_str());
check("void f(int x) { return x & 16 ? 1 : 0; }");
ASSERT_EQUALS("", errout_str());
check("void f(int x) { return x % 16 ? 1 : 0; }");
ASSERT_EQUALS("", errout_str());
check("enum {X,Y}; void f(int x) { return x & Y ? 1 : 0; }");
ASSERT_EQUALS("", errout_str());
}
void clarifyStatement() {
check("char* f(char* c) {\n"
" *c++;\n"
" return c;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:2]: (warning, inconclusive) Found suspicious operator '*', result is not used.\n"
"[test.cpp:2]: (warning) In expression like '*A++' the result of '*' is unused. Did you intend to write '(*A)++;'?\n",
errout_str());
check("char* f(char** c) {\n"
" *c[5]--;\n"
" return *c;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:2]: (warning, inconclusive) Found suspicious operator '*', result is not used.\n"
"[test.cpp:2]: (warning) In expression like '*A++' the result of '*' is unused. Did you intend to write '(*A)++;'?\n",
errout_str());
check("void f(Foo f) {\n"
" *f.a++;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:2]: (warning, inconclusive) Found suspicious operator '*', result is not used.\n"
"[test.cpp:2]: (warning) In expression like '*A++' the result of '*' is unused. Did you intend to write '(*A)++;'?\n",
errout_str());
check("void f(Foo f) {\n"
" *f.a[5].v[3]++;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:2]: (warning, inconclusive) Found suspicious operator '*', result is not used.\n"
"[test.cpp:2]: (warning) In expression like '*A++' the result of '*' is unused. Did you intend to write '(*A)++;'?\n",
errout_str());
check("void f(Foo f) {\n"
" *f.a(1, 5).v[x + y]++;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:2]: (warning, inconclusive) Found suspicious operator '*', result is not used.\n"
"[test.cpp:2]: (warning) In expression like '*A++' the result of '*' is unused. Did you intend to write '(*A)++;'?\n",
errout_str());
check("char* f(char* c) {\n"
" (*c)++;\n"
" return c;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(char* c) {\n"
" bar(*c++);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("char*** f(char*** c) {\n"
" ***c++;\n"
" return c;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:2]: (warning, inconclusive) Found suspicious operator '*', result is not used.\n"
"[test.cpp:2]: (warning) In expression like '*A++' the result of '*' is unused. Did you intend to write '(*A)++;'?\n",
errout_str());
check("char** f(char*** c) {\n"
" **c[5]--;\n"
" return **c;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:2]: (warning, inconclusive) Found suspicious operator '*', result is not used.\n"
"[test.cpp:2]: (warning) In expression like '*A++' the result of '*' is unused. Did you intend to write '(*A)++;'?\n",
errout_str());
check("char*** f(char*** c) {\n"
" (***c)++;\n"
" return c;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(const int*** p) {\n" // #10923
" delete[] **p;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void *f(char** c) {\n"
" bar(**c++);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void *f(char* p) {\n"
" for (p = path; *p++;) ;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" std::array<std::array<double,3>,3> array;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(const std::vector<int*>& v) {\n" // #12088
" for (auto it = v.begin(); it != v.end(); delete *it++);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void duplicateBranch() {
check("void f(int a, int &b) {\n"
" if (a)\n"
" b = 1;\n"
" else\n"
" b = 1;\n"
"}");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:2]: (style, inconclusive) Found duplicate branches for 'if' and 'else'.\n", errout_str());
check("void f(int a, int &b) {\n"
" if (a) {\n"
" if (a == 1)\n"
" b = 2;\n"
" else\n"
" b = 2;\n"
" } else\n"
" b = 1;\n"
"}");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:3]: (style, inconclusive) Found duplicate branches for 'if' and 'else'.\n", errout_str());
check("void f(int a, int &b) {\n"
" if (a == 1)\n"
" b = 1;\n"
" else {\n"
" if (a)\n"
" b = 2;\n"
" else\n"
" b = 2;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:7] -> [test.cpp:5]: (style, inconclusive) Found duplicate branches for 'if' and 'else'.\n", errout_str());
check("int f(int signed, unsigned char value) {\n"
" int ret;\n"
" if (signed)\n"
" ret = (signed char)value;\n" // cast must be kept so the simplifications and verification is skipped
" else\n"
" ret = (unsigned char)value;\n"
" return ret;\n"
"}", true, false, false);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" if (b)\n"
" __asm__(\"mov ax, bx\");\n"
" else\n"
" __asm__(\"mov bx, bx\");\n"
"}");
ASSERT_EQUALS("", errout_str()); // #3407
check("void f() {\n"
" if (b)\n"
" __asm__(\"mov ax, bx\");\n"
" else\n"
" __asm__(\"mov ax, bx\");\n"
"}");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:2]: (style, inconclusive) Found duplicate branches for 'if' and 'else'.\n", errout_str());
}
void duplicateBranch1() {
// tests inspired by http://www.viva64.com/en/b/0149/ ( Comparison between PVS-Studio and cppcheck )
// Errors detected in Quake 3: Arena by PVS-Studio: Fragment 2
check("void f()\n"
"{\n"
" if (front < 0)\n"
" frac = front/(front-back);\n"
" else\n"
" frac = front/(front-back);\n"
"}");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:3]: (style, inconclusive) Found duplicate branches for 'if' and 'else'.\n", errout_str());
check("void f()\n"
"{\n"
" if (front < 0)\n"
" { frac = front/(front-back);}\n"
" else\n"
" frac = front/((front-back));\n"
"}");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:3]: (style, inconclusive) Found duplicate branches for 'if' and 'else'.\n", errout_str());
// No message about empty branches (#5354)
check("void f()\n"
"{\n"
" if (front < 0)\n"
" {}\n"
" else\n"
" {}\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void duplicateBranch2() {
checkP("#define DOSTUFF1 ;\n"
"#define DOSTUFF2 ;\n"
"void f(int x) {\n" // #4329
" if (x)\n"
" DOSTUFF1\n"
" else\n"
" DOSTUFF2\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void duplicateBranch3() {
check("void f(bool b, int i) {\n"
" int j = i;\n"
" if (b) {\n"
" x = i;\n"
" } else {\n"
" x = j;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:5] -> [test.cpp:3]: (style, inconclusive) Found duplicate branches for 'if' and 'else'.\n"
"[test.cpp:2]: (style) The scope of the variable 'j' can be reduced.\n",
errout_str());
check("void f(bool b, int i) {\n"
" int j = i;\n"
" i++;\n"
" if (b) {\n"
" x = i;\n"
" } else {\n"
" x = j;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void duplicateBranch4() {
check("void* f(bool b) {\n"
" if (b) {\n"
" return new A::Y(true);\n"
" } else {\n"
" return new A::Z(true);\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void duplicateBranch5() {
check("void f(bool b) {\n"
" int j;\n"
" if (b) {\n"
" unsigned int i = 0;\n"
" j = i;\n"
" } else {\n"
" unsigned int i = 0;\n"
" j = i;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:6] -> [test.cpp:3]: (style, inconclusive) Found duplicate branches for 'if' and 'else'.\n", errout_str());
check("void f(bool b) {\n"
" int j;\n"
" if (b) {\n"
" unsigned int i = 0;\n"
" j = i;\n"
" } else {\n"
" unsigned int i = 0;\n"
" j = 1;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(bool b) {\n"
" int j;\n"
" if (b) {\n"
" unsigned int i = 0;\n"
" } else {\n"
" int i = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(bool b) {\n"
" int j;\n"
" if (b) {\n"
" unsigned int i = 0;\n"
" j = i;\n"
" } else {\n"
" int i = 0;\n"
" j = i;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void duplicateBranch6() {
check("void f(bool b) {\n"
" if (b) {\n"
" } else {\n"
" int i = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(bool b) {\n"
" if (b) {\n"
" int i = 0;\n"
" } else {\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void duplicateExpression1() {
check("void foo(int a) {\n"
" if (a == a) { }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Same expression on both sides of '=='.\n", errout_str());
check("void fun(int b) {\n"
" return a && a ||\n"
" b == b &&\n"
" d > d &&\n"
" e < e &&\n"
" f ;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Same expression on both sides of '&&'.\n"
"[test.cpp:3]: (style) Same expression on both sides of '=='.\n"
"[test.cpp:4]: (style) Same expression on both sides of '>'.\n"
"[test.cpp:5]: (style) Same expression on both sides of '<'.\n", errout_str());
check("void foo() {\n"
" return a && a;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Same expression on both sides of '&&'.\n", errout_str());
check("void foo() {\n"
" a = b && b;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Same expression on both sides of '&&'.\n", errout_str());
check("void foo(int b) {\n"
" f(a,b == b);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Same expression on both sides of '=='.\n", errout_str());
check("void foo(int b) {\n"
" f(b == b, a);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Same expression on both sides of '=='.\n", errout_str());
check("void foo() {\n"
" if (x!=2 || x!=2) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Same expression on both sides of '||'.\n", errout_str());
check("void foo(int a, int b) {\n"
" if ((a < b) && (b > a)) { }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Same expression on both sides of '&&' because 'a<b' and 'b>a' represent the same value.\n", errout_str());
check("void foo(int a, int b) {\n"
" if ((a <= b) && (b >= a)) { }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Same expression on both sides of '&&' because 'a<=b' and 'b>=a' represent the same value.\n", errout_str());
check("void foo() {\n"
" if (x!=2 || y!=3 || x!=2) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Same expression 'x!=2' found multiple times in chain of '||' operators.\n", errout_str());
check("void foo() {\n"
" if (x!=2 && (x=y) && x!=2) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" if (a && b || a && b) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Same expression on both sides of '||'.\n", errout_str());
check("void foo() {\n"
" if (a && b || b && c) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" if (a && b | b && c) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Same expression on both sides of '|'.\n", errout_str());
check("void foo() {\n"
" if ((a + b) | (a + b)) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Same expression on both sides of '|'.\n", errout_str());
check("void foo() {\n"
" if ((a | b) & (a | b)) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Same expression on both sides of '&'.\n", errout_str());
check("void foo(int a, int b) {\n"
" if ((a | b) == (a | b)) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Same expression on both sides of '=='.\n", errout_str());
check("void foo() {\n"
" if (a1[a2[c & 0xff] & 0xff]) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void d(const char f, int o, int v)\n"
"{\n"
" if (((f=='R') && (o == 1) && ((v < 2) || (v > 99))) ||\n"
" ((f=='R') && (o == 2) && ((v < 2) || (v > 99))) ||\n"
" ((f=='T') && (o == 2) && ((v < 200) || (v > 9999)))) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f(int x) { return x+x; }");
ASSERT_EQUALS("", errout_str());
check("void f(int x) { while (x+=x) ; }");
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" if (a && b && b) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Same expression on both sides of '&&'.\n", errout_str());
check("void foo() {\n"
" if (a || b || b) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Same expression on both sides of '||'.\n", errout_str());
check("void foo() {\n"
" if (a / 1000 / 1000) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int foo(int i) {\n"
" return i/i;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Same expression on both sides of '/'.\n", errout_str());
check("void foo() {\n"
" if (a << 1 << 1) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f() { return !!y; }"); // No FP
ASSERT_EQUALS("", errout_str());
// make sure there are not "same expression" fp when there are different casts
check("void f(long x) { if ((int32_t)x == (int64_t)x) {} }",
true, // filename
false, // inconclusive
false, // runSimpleChecks
false, // verbose
nullptr // settings
);
ASSERT_EQUALS("", errout_str());
// make sure there are not "same expression" fp when there are different ({}) expressions
check("void f(long x) { if (({ 1+2; }) == ({3+4;})) {} }");
ASSERT_EQUALS("", errout_str());
// #5535: Reference named like its type
check("void foo() { UMSConfig& UMSConfig = GetUMSConfiguration(); }");
ASSERT_EQUALS("[test.cpp:1]: (style) Variable 'UMSConfig' can be declared as reference to const\n", errout_str());
// #3868 - false positive (same expression on both sides of |)
check("void f(int x) {\n"
" a = x ? A | B | C\n"
" : A | B;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(const Bar &bar) {\n"
" bool a = bar.isSet() && bar->isSet();\n"
" bool b = bar.isSet() && bar.isSet();\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Same expression on both sides of '&&'.\n", errout_str());
check("void foo(int a, int b) {\n"
" if ((b + a) | (a + b)) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Same expression on both sides of '|' because 'b+a' and 'a+b' represent the same value.\n", errout_str());
check("void foo(const std::string& a, const std::string& b) {\n"
" return a.find(b+\"&\") || a.find(\"&\"+b);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(int a, int b) {\n"
" if ((b > a) | (a > b)) {}\n" // > is not commutative
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(double a, double b) {\n"
" if ((b + a) > (a + b)) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) The comparison 'b+a > a+b' is always false because 'b+a' and 'a+b' represent the same value.\n", errout_str());
check("void f(int x) {\n"
" if ((x == 1) && (x == 0x00000001))\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Same expression on both sides of '&&' because 'x==1' and 'x==0x00000001' represent the same value.\n", errout_str());
check("void f() {\n"
" enum { Four = 4 };\n"
" if (Four == 4) {}"
"}", true, true, false);
ASSERT_EQUALS("[test.cpp:3]: (style) The comparison 'Four == 4' is always true.\n",
errout_str());
check("void f() {\n"
" enum { Four = 4 };\n"
" static_assert(Four == 4, \"\");\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" enum { Four = 4 };\n"
" _Static_assert(Four == 4, \"\");\n"
"}", false);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" enum { Four = 4 };\n"
" static_assert(4 == Four, \"\");\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" enum { FourInEnumOne = 4 };\n"
" enum { FourInEnumTwo = 4 };\n"
" if (FourInEnumOne == FourInEnumTwo) {}\n"
"}", true, true, false);
ASSERT_EQUALS("[test.cpp:4]: (style) The comparison 'FourInEnumOne == FourInEnumTwo' is always true because 'FourInEnumOne' and 'FourInEnumTwo' represent the same value.\n",
errout_str());
check("void f() {\n"
" enum { FourInEnumOne = 4 };\n"
" enum { FourInEnumTwo = 4 };\n"
" static_assert(FourInEnumOne == FourInEnumTwo, \"\");\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(int a, int b) {\n"
" if (sizeof(a) == sizeof(a)) { }\n"
" if (sizeof(a) == sizeof(b)) { }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Same expression on both sides of '=='.\n", errout_str());
check("float bar(int) __attribute__((pure));\n"
"char foo(int) __attribute__((pure));\n"
"int test(int a, int b) {\n"
" if (bar(a) == bar(a)) { }\n"
" if (unknown(a) == unknown(a)) { }\n"
" if (foo(a) == foo(a)) { }\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (style) Same expression on both sides of '=='.\n", errout_str());
}
void duplicateExpression2() { // check if float is NaN or Inf
check("int f(long double ldbl, double dbl, float flt) {\n" // ticket #2730
" if (ldbl != ldbl) have_nan = 1;\n"
" if (!(dbl == dbl)) have_nan = 1;\n"
" if (flt != flt) have_nan = 1;\n"
" return have_nan;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("float f(float x) { return x-x; }"); // ticket #4485 (Inf)
ASSERT_EQUALS("", errout_str());
check("float f(float x) { return (X double)x == (X double)x; }", true, false, false);
ASSERT_EQUALS("", errout_str());
check("struct X { float f; };\n"
"float f(struct X x) { return x.f == x.f; }");
ASSERT_EQUALS("", errout_str());
check("struct X { int i; };\n"
"int f(struct X x) { return x.i == x.i; }");
ASSERT_EQUALS("[test.cpp:2]: (style) Same expression on both sides of '=='.\n", errout_str());
// #5284 - when type is unknown, assume it's float
check("int f() { return x==x; }");
ASSERT_EQUALS("", errout_str());
}
void duplicateExpression3() {
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <function name=\"mystrcmp\">\n"
" <pure/>\n"
" <arg nr=\"1\"/>\n"
" <arg nr=\"2\"/>\n"
" </function>\n"
"</def>";
/*const*/ Settings settings = settingsBuilder().libraryxml(xmldata, sizeof(xmldata)).build();
check("void foo() {\n"
" if (x() || x()) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct A {\n"
" void foo() const;\n"
" bool bar() const;\n"
"};\n"
"void A::foo() const {\n"
" if (bar() && bar()) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (style) Same expression on both sides of '&&'.\n", errout_str());
check("struct A {\n"
" void foo();\n"
" bool bar();\n"
" bool bar() const;\n"
"};\n"
"void A::foo() {\n"
" if (bar() && bar()) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("class B {\n"
" void bar(int i);\n"
"};\n"
"class A {\n"
" void bar(int i) const;\n"
"};\n"
"void foo() {\n"
" B b;\n"
" A a;\n"
" if (b.bar(1) && b.bar(1)) {}\n"
" if (a.bar(1) && a.bar(1)) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:11]: (style) Same expression on both sides of '&&'.\n", errout_str());
check("class D { void strcmp(); };\n"
"void foo() {\n"
" D d;\n"
" if (d.strcmp() && d.strcmp()) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" if ((mystrcmp(a, b) == 0) || (mystrcmp(a, b) == 0)) {}\n"
"}", true, false, true, false, &settings);
ASSERT_EQUALS("[test.cpp:2]: (style) Same expression on both sides of '||'.\n", errout_str());
check("void GetValue() { return rand(); }\n"
"void foo() {\n"
" if ((GetValue() == 0) || (GetValue() == 0)) { dostuff(); }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void __attribute__((const)) GetValue() { return X; }\n"
"void foo() {\n"
" if ((GetValue() == 0) || (GetValue() == 0)) { dostuff(); }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Same expression on both sides of '||'.\n", errout_str());
check("void GetValue() __attribute__((const));\n"
"void GetValue() { return X; }\n"
"void foo() {\n"
" if ((GetValue() == 0) || (GetValue() == 0)) { dostuff(); }\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Same expression on both sides of '||'.\n", errout_str());
check("void foo() {\n"
" if (str == \"(\" || str == \"(\") {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Same expression on both sides of '||'.\n", errout_str());
check("void foo() {\n"
" if (bar(a) && !strcmp(a, b) && bar(a) && !strcmp(a, b)) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
// #5334
check("void f(C *src) {\n"
" if (x<A*>(src) || x<B*>(src))\n"
" a++;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(A *src) {\n"
" if (dynamic_cast<B*>(src) || dynamic_cast<B*>(src)) {}\n"
"}\n", true, false, false); // don't run simplifications
ASSERT_EQUALS("[test.cpp:2]: (style) Same expression on both sides of '||'.\n", errout_str());
// #5819
check("Vector func(Vector vec1) {\n"
" return fabs(vec1 & vec1 & vec1);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("Vector func(int vec1) {\n"
" return fabs(vec1 & vec1 & vec1);\n"
"}");
ASSERT_EQUALS(
"[test.cpp:2]: (style) Same expression on both sides of '&'.\n"
"[test.cpp:2]: (style) Same expression on both sides of '&'.\n", // duplicate
errout_str());
}
void duplicateExpression4() {
check("void foo() {\n"
" if (*a++ != b || *a++ != b) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" if (*a-- != b || *a-- != b) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
// assignment
check("void f() {\n"
" while (*(a+=2)==*(b+=2) && *(a+=2)==*(b+=2)) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void duplicateExpression5() { // #3749 - macros with same values
check("void f() {\n"
" if ($a == $a) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
checkP("#define X 1\n"
"#define Y 1\n"
"void f() {\n"
" if (X == X) {}\n"
" if (X == Y) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (style) Same expression on both sides of '=='.\n", errout_str());
checkP("#define X 1\n"
"#define Y X\n"
"void f() {\n"
" if (X == Y) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void duplicateExpression6() { // #4639
check("float IsNan(float value) { return !(value == value); }\n"
"double IsNan(double value) { return !(value == value); }\n"
"long double IsNan(long double value) { return !(value == value); }");
ASSERT_EQUALS("", errout_str());
}
void duplicateExpression7() {
check("void f() {\n"
" const int i = sizeof(int);\n"
" if ( i != sizeof (int)){}\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) The comparison 'i != sizeof(int)' is always false because 'i' and 'sizeof(int)' represent the same value.\n", errout_str());
check("void f() {\n"
" const int i = sizeof(int);\n"
" if ( sizeof (int) != i){}\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) The comparison 'sizeof(int) != i' is always false because 'sizeof(int)' and 'i' represent the same value.\n", errout_str());
check("void f(int a = 1) { if ( a != 1){}}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int a = 1;\n"
" if ( a != 1){}\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) The comparison 'a != 1' is always false.\n", errout_str());
check("void f() {\n"
" int a = 1;\n"
" int b = 1;\n"
" if ( a != b){}\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3] -> [test.cpp:4]: (style) The comparison 'a != b' is always false because 'a' and 'b' represent the same value.\n", errout_str());
check("void f() {\n"
" int a = 1;\n"
" int b = a;\n"
" if ( a != b){}\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (style) The comparison 'a != b' is always false because 'a' and 'b' represent the same value.\n", errout_str());
check("void use(int);\n"
"void f() {\n"
" int a = 1;\n"
" int b = 1;\n"
" use(b);\n"
" if ( a != 1){}\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:6]: (style) The comparison 'a != 1' is always false.\n", errout_str());
check("void use(int);\n"
"void f() {\n"
" int a = 1;\n"
" use(a);\n"
" a = 2;\n"
" if ( a != 1){}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void use(int);\n"
"void f() {\n"
" int a = 2;\n"
" use(a);\n"
" a = 1;\n"
" if ( a != 1){}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("const int a = 1;\n"
"void f() {\n"
" if ( a != 1){}\n"
"}");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:3]: (style) The comparison 'a != 1' is always false.\n", errout_str());
check("int a = 1;\n"
" void f() {\n"
" if ( a != 1){}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" static const int a = 1;\n"
" if ( a != 1){}\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) The comparison 'a != 1' is always false.\n", errout_str());
check("void f() {\n"
" static int a = 1;\n"
" if ( a != 1){}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int a = 1;\n"
" if ( a != 1){\n"
" a++;\n"
" }}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) The comparison 'a != 1' is always false.\n", errout_str());
check("void f(int b) {\n"
" int a = 1;\n"
" while (b) {\n"
" if ( a != 1){}\n"
" a++;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool f(bool a, bool b) {\n"
" const bool c = a;\n"
" return a && b && c;\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) Same expression 'a' found multiple times in chain of '&&' operators because 'a' and 'c' represent the same value.\n",
errout_str());
// 6906
check("void f(const bool b) {\n"
" const bool b1 = !b;\n"
" if(!b && b1){}\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) Same expression on both sides of '&&' because '!b' and 'b1' represent the same value.\n", errout_str());
// 7284
check("void f(void) {\n"
" if (a || !!a) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Same expression on both sides of '||' because 'a' and '!!a' represent the same value.\n", errout_str());
// 8205
check("void f(int x) {\n"
" int Diag = 0;\n"
" switch (x) {\n"
" case 12:\n"
" if (Diag==0) {}\n"
" break;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:5]: (style) The comparison 'Diag == 0' is always true.\n", errout_str());
// #9744
check("void f(const std::vector<int>& ints) {\n"
" int i = 0;\n"
" for (int p = 0; i < ints.size(); ++i) {\n"
" if (p == 0) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (style) The comparison 'p == 0' is always true.\n", errout_str());
// #11820
check("unsigned f(unsigned x) {\n"
" return x - !!x;\n"
"}\n"
"unsigned g(unsigned x) {\n"
" return !!x - x;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void duplicateExpression8() {
check("void f() {\n"
" int a = 1;\n"
" int b = a;\n"
" a = 2;\n"
" if ( b != a){}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int * a, int i) { int b = a[i]; a[i] = 2; if ( b != a[i]){}}");
ASSERT_EQUALS("", errout_str());
check("void f(int * a, int i) { int b = *a; *a = 2; if ( b != *a){}}");
ASSERT_EQUALS("", errout_str());
check("struct A { int f() const; };\n"
"A g();\n"
"void foo() {\n"
" for (A x = A();;) {\n"
" const int a = x.f();\n"
" x = g();\n"
" if (x.f() == a) break;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f(int i);\n"
"struct A {\n"
" enum E { B, C };\n"
" bool f(E);\n"
"};\n"
"void foo() {\n"
" A a;\n"
" const bool x = a.f(A::B);\n"
" const bool y = a.f(A::C);\n"
" if(!x && !y) return;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" const bool x = a.f(A::B);\n"
" const bool y = a.f(A::C);\n"
" if (!x && !y) return;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(bool * const b);\n"
"void foo() {\n"
" bool x = true;\n"
" bool y = true;\n"
" f(&x);\n"
" if (!x && !y) return;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" const int a = {};\n"
" if(a == 1) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("volatile const int var = 42;\n"
"void f() { if(var == 42) {} }");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int a = 0;\n"
" struct b c;\n"
" c.a = &a;\n"
" g(&c);\n"
" if (a == 0) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void duplicateExpression9() {
// #9320
check("void f() {\n"
" uint16_t x = 1000;\n"
" uint8_t y = x;\n"
" if (x != y) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void duplicateExpression10() {
// #9485
check("int f() {\n"
" const int a = 1;\n"
" const int b = a-1;\n"
" const int c = a+1;\n"
" return c;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void duplicateExpression11() {
check("class Fred {\n"
"public:\n"
" double getScale() const { return m_range * m_zoom; }\n"
" void setZoom(double z) { m_zoom = z; }\n"
" void dostuff(int);\n"
"private:\n"
" double m_zoom;\n"
" double m_range;\n"
"};\n"
"\n"
"void Fred::dostuff(int x) {\n"
" if (x == 43) {\n"
" double old_scale = getScale();\n"
" setZoom(m_zoom + 1);\n"
" double scale_ratio = getScale() / old_scale;\n" // <- FP
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void duplicateExpression12() { //#10026
check("int f(const std::vector<int> &buffer, const uint8_t index)\n"
"{\n"
" int var = buffer[index - 1];\n"
" return buffer[index - 1] - var;\n" // <<
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (style) Same expression on both sides of '-' because 'buffer[index-1]' and 'var' represent the same value.\n", errout_str());
}
void duplicateExpression13() { //#7899
check("void f() {\n"
" if (sizeof(long) == sizeof(long long)) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void duplicateExpression14() { //#9871
check("int f() {\n"
" int k = 7;\n"
" int* f = &k;\n"
" int* g = &k;\n"
" return (f + 4 != g + 4);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4] -> [test.cpp:5]: (style) The comparison 'f+4 != g+4' is always false because 'f+4' and 'g+4' represent the same value.\n", errout_str());
}
void duplicateExpression15() { //#10650
check("bool f() {\n"
" const int i = int(0);\n"
" return i == 0;\n"
"}\n"
"bool g() {\n"
" const int i = int{ 0 };\n"
" return i == 0;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) The comparison 'i == 0' is always true.\n"
"[test.cpp:6] -> [test.cpp:7]: (style) The comparison 'i == 0' is always true.\n",
errout_str());
}
void duplicateExpression16() {
check("void f(const std::string& a) {\n" //#10569
" if ((a == \"x\") ||\n"
" (a == \"42\") ||\n"
" (a == \"y\") ||\n"
" (a == \"42\")) {}\n"
"}\n"
"void g(const std::string& a) {\n"
" if ((a == \"42\") ||\n"
" (a == \"x\") ||\n"
" (a == \"42\") ||\n"
" (a == \"y\")) {}\n"
"}\n"
"void h(const std::string& a) {\n"
" if ((a == \"42\") ||\n"
" (a == \"x\") ||\n"
" (a == \"y\") ||\n"
" (a == \"42\")) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:4]: (style) Same expression 'a==\"42\"' found multiple times in chain of '||' operators.\n"
"[test.cpp:7] -> [test.cpp:9]: (style) Same expression 'a==\"42\"' found multiple times in chain of '||' operators.\n"
"[test.cpp:13] -> [test.cpp:16]: (style) Same expression 'a==\"42\"' found multiple times in chain of '||' operators.\n",
errout_str());
check("void f(const char* s) {\n" // #6371
" if (*s == '\x0F') {\n"
" if (!s[1] || !s[2] || !s[1])\n"
" break;\n"
" }\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) Same expression '!s[1]' found multiple times in chain of '||' operators.\n", errout_str());
}
void duplicateExpression17() {
check("enum { E0 };\n" // #12036
"void f() {\n"
" if (0 > E0) {}\n"
" if (E0 > 0) {}\n"
" if (E0 == 0) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) The comparison '0 > E0' is always false.\n"
"[test.cpp:4]: (style) The comparison 'E0 > 0' is always false.\n"
"[test.cpp:5]: (style) The comparison 'E0 == 0' is always true.\n",
errout_str());
check("struct S {\n" // #12040, #12044
" static const int I = 0;\n"
" enum { E0 };\n"
" enum F { F0 };\n"
" void f() {\n"
" if (0 > I) {}\n"
" if (0 > S::I) {}\n"
" if (0 > E0) {}\n"
" if (0 > S::E0) {}\n"
" }\n"
"};\n"
"void g() {\n"
" if (0 > S::I) {}\n"
" if (0 > S::E0) {}\n"
" if (0 > S::F::F0) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:6]: (style) The comparison '0 > I' is always false.\n"
"[test.cpp:2] -> [test.cpp:7]: (style) The comparison '0 > S::I' is always false.\n"
"[test.cpp:8]: (style) The comparison '0 > E0' is always false.\n"
"[test.cpp:9]: (style) The comparison '0 > S::E0' is always false.\n"
"[test.cpp:2] -> [test.cpp:13]: (style) The comparison '0 > S::I' is always false.\n"
"[test.cpp:14]: (style) The comparison '0 > S::E0' is always false.\n"
"[test.cpp:15]: (style) The comparison '0 > S::F::F0' is always false.\n",
errout_str());
check("template<typename T, typename U>\n" // #12122
"void f() {\n"
" static_assert(std::is_same<T, U>::value || std::is_integral<T>::value);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void duplicateExpression18() {
checkP("#if defined(ABC)\n" // #13218
"#define MACRO1 (0x1)\n"
"#else\n"
"#define MACRO1 (0)\n"
"#endif\n"
"#if defined(XYZ)\n"
"#define MACRO2 (0x2)\n"
"#else\n"
"#define MACRO2 (0)\n"
"#endif\n"
"#define MACRO_ALL (MACRO1 | MACRO2)\n"
"void f() {\n"
" if (MACRO_ALL == 0) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void duplicateExpressionLoop() {
check("void f() {\n"
" int a = 1;\n"
" while ( a != 1){}\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) The comparison 'a != 1' is always false.\n", errout_str());
check("void f() { int a = 1; while ( a != 1){ a++; }}");
ASSERT_EQUALS("", errout_str());
check("void f() { int a = 1; for ( int i=0; i < 3 && a != 1; i++){ a++; }}");
ASSERT_EQUALS("", errout_str());
check("void f(int b) { int a = 1; while (b) { if ( a != 1){} b++; } a++; }");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" for(int i = 0; i < 10;) {\n"
" if( i != 0 ) {}\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) The comparison 'i != 0' is always false.\n", errout_str());
check("void f() {\n"
" for(int i = 0; i < 10;) {\n"
" if( i != 0 ) {}\n"
" i++;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" for(int i = 0; i < 10;) {\n"
" if( i != 0 ) { i++; }\n"
" i++;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" for(int i = 0; i < 10;) {\n"
" if( i != 0 ) { i++; }\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int i = 0;\n"
" while(i < 10) {\n"
" if( i != 0 ) {}\n"
" i++;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int b) {\n"
" while (b) {\n"
" int a = 1;\n"
" if ( a != 1){}\n"
" b++;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (style) The comparison 'a != 1' is always false.\n", errout_str());
check("struct T {\n" // #11083
" std::string m;\n"
" const std::string & str() const { return m; }\n"
" T* next();\n"
"};\n"
"void f(T* t) {\n"
" const std::string& s = t->str();\n"
" while (t && t->str() == s)\n"
" t = t->next();\n"
" do {\n"
" t = t->next();\n"
" } while (t && t->str() == s);\n"
" for (; t && t->str() == s; t = t->next());\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void duplicateExpressionTernary() { // #6391
check("void f() {\n"
" return A ? x : x;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Same expression in both branches of ternary operator.\n", errout_str());
check("int f(bool b, int a) {\n"
" const int c = a;\n"
" return b ? a : c;\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) Same expression in both branches of ternary operator.\n", errout_str());
check("void f() {\n"
" return A ? x : z;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(unsigned char c) {\n"
" x = y ? (signed char)c : (unsigned char)c;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("std::string stringMerge(std::string const& x, std::string const& y) {\n" // #7938
" return ((x > y) ? (y + x) : (x + y));\n"
"}");
ASSERT_EQUALS("", errout_str());
// #6426
{
const char code[] = "void foo(bool flag) {\n"
" bar( (flag) ? ~0u : ~0ul);\n"
"}";
/*const*/ Settings settings = _settings;
settings.platform.sizeof_int = 4;
settings.platform.int_bit = 32;
settings.platform.sizeof_long = 4;
settings.platform.long_bit = 32;
check(code, &settings);
ASSERT_EQUALS("[test.cpp:2]: (style) Same value in both branches of ternary operator.\n", errout_str());
settings.platform.sizeof_long = 8;
settings.platform.long_bit = 64;
check(code, &settings);
ASSERT_EQUALS("", errout_str());
}
}
void duplicateValueTernary() {
check("void f() {\n"
" if( a ? (b ? false:false): false ) ;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Same value in both branches of ternary operator.\n", errout_str());
check("int f1(int a) {return (a == 1) ? (int)1 : 1; }");
ASSERT_EQUALS("[test.cpp:1]: (style) Same value in both branches of ternary operator.\n", errout_str());
check("int f2(int a) {return (a == 1) ? (int)1 : (int)1; }");
ASSERT_EQUALS("[test.cpp:1]: (style) Same value in both branches of ternary operator.\n", errout_str());
check("int f3(int a) {return (a == 1) ? 1 : (int)1; }");
ASSERT_EQUALS("[test.cpp:1]: (style) Same value in both branches of ternary operator.\n", errout_str());
check("int f4(int a) {return (a == 1) ? 1 : 1; }");
ASSERT_EQUALS("[test.cpp:1]: (style) Same value in both branches of ternary operator.\n", errout_str());
check("int f5(int a) {return (a == (int)1) ? (int)1 : 1; }");
ASSERT_EQUALS("[test.cpp:1]: (style) Same value in both branches of ternary operator.\n", errout_str());
check("int f6(int a) {return (a == (int)1) ? (int)1 : (int)1; }");
ASSERT_EQUALS("[test.cpp:1]: (style) Same value in both branches of ternary operator.\n", errout_str());
check("int f7(int a) {return (a == (int)1) ? 1 : (int)1; }");
ASSERT_EQUALS("[test.cpp:1]: (style) Same value in both branches of ternary operator.\n", errout_str());
check("int f8(int a) {return (a == (int)1) ? 1 : 1; }");
ASSERT_EQUALS("[test.cpp:1]: (style) Same value in both branches of ternary operator.\n", errout_str());
check("struct Foo {\n"
" std::vector<int> bar{1,2,3};\n"
" std::vector<int> baz{4,5,6};\n"
"};\n"
"void f() {\n"
" Foo foo;\n"
" it = true ? foo.bar.begin() : foo.baz.begin();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(bool b) {\n"
" std::vector<int> bar{1,2,3};\n"
" std::vector<int> baz{4,5,6};\n"
" std::vector<int> v = b ? bar : baz;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(bool q) {\n" // #9570
" static int a = 0;\n"
" static int b = 0;\n"
" int& x = q ? a : b;\n"
" ++x;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct S { int a, b; };\n" // #10107
"S f(bool x, S s) {\n"
" (x) ? f.a = 42 : f.b = 42;\n"
" return f;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("float f(float x) {\n" // # 11368
" return (x >= 0.0) ? 0.0 : -0.0;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void duplicateExpressionTemplate() {
check("template <int I> void f() {\n" // #6930
" if (I >= 0 && I < 3) {}\n"
"}\n"
"\n"
"static auto a = f<0>();");
ASSERT_EQUALS("", errout_str());
check("template<typename T>\n" // #7754
"void f() {\n"
" if (std::is_same_v<T, char> || std::is_same_v<T, unsigned char>) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("typedef long long int64_t;"
"template<typename T>\n"
"void f() {\n"
" if (std::is_same_v<T, long> || std::is_same_v<T, int64_t>) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkP("#define int32_t int"
"template<typename T>\n"
"void f() {\n"
" if (std::is_same_v<T, int> || std::is_same_v<T, int32_t>) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkP("#define F(v) (v) != 0\n" // #12392
"template<class T>\n"
"void f() {\n"
" if (F(0)) {}\n"
"}\n"
"void g() {\n"
" f<int>();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void duplicateExpressionCompareWithZero() {
check("void f(const int* x, bool b) {\n"
" if ((x && b) || (x != 0 && b)) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Same expression on both sides of '||' because 'x&&b' and 'x!=0&&b' represent the same value.\n", errout_str());
check("void f(const int* x, bool b) {\n"
" if ((x != 0 && b) || (x && b)) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Same expression on both sides of '||' because 'x!=0&&b' and 'x&&b' represent the same value.\n", errout_str());
check("void f(const int* x, bool b) {\n"
" if ((x && b) || (b && x != 0)) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Same expression on both sides of '||' because 'x&&b' and 'b&&x!=0' represent the same value.\n", errout_str());
check("void f(const int* x, bool b) {\n"
" if ((!x && b) || (x == 0 && b)) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Same expression on both sides of '||' because '!x&&b' and 'x==0&&b' represent the same value.\n", errout_str());
check("void f(const int* x, bool b) {\n"
" if ((x == 0 && b) || (!x && b)) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Same expression on both sides of '||' because 'x==0&&b' and '!x&&b' represent the same value.\n", errout_str());
check("void f(const int* x, bool b) {\n"
" if ((!x && b) || (b && x == 0)) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Same expression on both sides of '||' because '!x&&b' and 'b&&x==0' represent the same value.\n", errout_str());
check("struct A {\n"
" int* getX() const;\n"
" bool getB() const;\n"
" void f() {\n"
" if ((getX() && getB()) || (getX() != 0 && getB())) {}\n"
" }\n"
"};\n");
ASSERT_EQUALS("[test.cpp:5]: (style) Same expression on both sides of '||' because 'getX()&&getB()' and 'getX()!=0&&getB()' represent the same value.\n", errout_str());
check("void f(const int* x, bool b) {\n"
" if ((x && b) || (x == 0 && b)) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(const int* x, bool b) {\n"
" if ((!x && b) || (x != 0 && b)) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void oppositeExpression() {
check("void f(bool a) { if(a && !a) {} }");
ASSERT_EQUALS("[test.cpp:1]: (style) Opposite expression on both sides of '&&'.\n", errout_str());
check("void f(bool a) { if(a != !a) {} }");
ASSERT_EQUALS("[test.cpp:1]: (style) Opposite expression on both sides of '!='.\n", errout_str());
check("void f(bool a) { if( a == !(a) ) {}}");
ASSERT_EQUALS("[test.cpp:1]: (style) Opposite expression on both sides of '=='.\n", errout_str());
check("void f(bool a) { if( a != !(a) ) {}}");
ASSERT_EQUALS("[test.cpp:1]: (style) Opposite expression on both sides of '!='.\n", errout_str());
check("void f(bool a) { if( !(a) == a ) {}}");
ASSERT_EQUALS("[test.cpp:1]: (style) Opposite expression on both sides of '=='.\n", errout_str());
check("void f(bool a) { if( !(a) != a ) {}}");
ASSERT_EQUALS("[test.cpp:1]: (style) Opposite expression on both sides of '!='.\n", errout_str());
check("void f(bool a) { if( !(!a) == !(a) ) {}}");
ASSERT_EQUALS("[test.cpp:1]: (style) Opposite expression on both sides of '=='.\n", errout_str());
check("void f(bool a) { if( !(!a) != !(a) ) {}}");
ASSERT_EQUALS("[test.cpp:1]: (style) Opposite expression on both sides of '!='.\n", errout_str());
check("void f1(bool a) {\n"
" const bool b = a;\n"
" if( a == !(b) ) {}\n"
" if( b == !(a) ) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) Opposite expression on both sides of '=='.\n"
"[test.cpp:2] -> [test.cpp:4]: (style) Opposite expression on both sides of '=='.\n", errout_str());
check("void f2(const bool *a) {\n"
" const bool b = *a;\n"
" if( *a == !(b) ) {}\n"
" if( b == !(*a) ) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) Opposite expression on both sides of '=='.\n"
"[test.cpp:2] -> [test.cpp:4]: (style) Opposite expression on both sides of '=='.\n", errout_str());
check("void f(bool a) { a = !a; }");
ASSERT_EQUALS("", errout_str());
check("void f(int a) { if( a < -a ) {}}");
ASSERT_EQUALS("[test.cpp:1]: (style) Opposite expression on both sides of '<'.\n", errout_str());
check("void f(int a) { a -= -a; }");
ASSERT_EQUALS("", errout_str());
check("void f(int a) { a = a / (-a); }");
ASSERT_EQUALS("", errout_str());
check("bool f(int i){ return !((i - 1) & i); }");
ASSERT_EQUALS("", errout_str());
check("bool f(unsigned i){ return (x > 0) && (x & (x-1)) == 0; }");
ASSERT_EQUALS("", errout_str());
check("void A::f(bool a, bool c)\n"
"{\n"
" const bool b = a;\n"
" if(c) { a = false; }\n"
" if(b && !a) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(bool c) {\n"
" const bool b = a;\n"
" if(c) { a = false; }\n"
" if(b && !a) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" bool x = a;\n"
" dostuff();\n"
" if (x && a) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" const bool b = g();\n"
" if (!b && g()) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(const bool *a) {\n"
" const bool b = a[42];\n"
" if( b == !(a[42]) ) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) Opposite expression on both sides of '=='.\n", errout_str());
check("void f(const bool *a) {\n"
" const bool b = a[42];\n"
" if( a[42] == !(b) ) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) Opposite expression on both sides of '=='.\n", errout_str());
check("void f(const bool *a) {\n"
" const bool b = *a;\n"
" if( b == !(*a) ) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) Opposite expression on both sides of '=='.\n", errout_str());
check("void f(const bool *a) {\n"
" const bool b = *a;\n"
" if( *a == !(b) ) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) Opposite expression on both sides of '=='.\n", errout_str());
check("void f(uint16_t u) {\n" // #9342
" if (u != (u & -u))\n"
" return false;\n"
" if (u != (-u & u))\n"
" return false;\n"
" return true;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void duplicateVarExpression() {
check("int f() __attribute__((pure));\n"
"int g() __attribute__((pure));\n"
"void test() {\n"
" int i = f();\n"
" int j = f();\n"
"}");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:4]: (style) Same expression used in consecutive assignments of 'i' and 'j'.\n", errout_str());
check("struct Foo { int f() const; int g() const; };\n"
"void test() {\n"
" Foo f = Foo{};\n"
" int i = f.f();\n"
" int j = f.f();\n"
"}");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:4]: (style) Same expression used in consecutive assignments of 'i' and 'j'.\n", errout_str());
check("struct Foo { int f() const; int g() const; };\n"
"void test() {\n"
" Foo f = Foo{};\n"
" Foo f2 = Foo{};\n"
" int i = f.f();\n"
" int j = f.f();\n"
"}");
ASSERT_EQUALS("[test.cpp:6] -> [test.cpp:5]: (style) Same expression used in consecutive assignments of 'i' and 'j'.\n", errout_str());
check("int f() __attribute__((pure));\n"
"int g() __attribute__((pure));\n"
"void test() {\n"
" int i = 1 + f();\n"
" int j = 1 + f();\n"
"}");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:4]: (style) Same expression used in consecutive assignments of 'i' and 'j'.\n", errout_str());
check("int f() __attribute__((pure));\n"
"int g() __attribute__((pure));\n"
"void test() {\n"
" int i = f() + 1;\n"
" int j = 1 + f();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f() __attribute__((pure));\n"
"int g() __attribute__((pure));\n"
"void test() {\n"
" int x = f();\n"
" int i = x + 1;\n"
" int j = f() + 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f() __attribute__((pure));\n"
"int g() __attribute__((pure));\n"
"void test() {\n"
" int i = f() + f();\n"
" int j = f() + f();\n"
"}");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:4]: (style) Same expression used in consecutive assignments of 'i' and 'j'.\n", errout_str());
check("int f(int) __attribute__((pure));\n"
"int g(int) __attribute__((pure));\n"
"void test() {\n"
" int i = f(0);\n"
" int j = f(0);\n"
"}");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:4]: (style) Same expression used in consecutive assignments of 'i' and 'j'.\n", errout_str());
check("int f(int) __attribute__((pure));\n"
"int g(int) __attribute__((pure));\n"
"void test() {\n"
" const int x = 0;\n"
" int i = f(0);\n"
" int j = f(x);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void test(const int * p, const int * q) {\n"
" int i = *p;\n"
" int j = *p;\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:2]: (style) Same expression used in consecutive assignments of 'i' and 'j'.\n", errout_str());
check("struct A { int x; int y; };"
"void test(A a) {\n"
" int i = a.x;\n"
" int j = a.x;\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:2]: (style) Same expression used in consecutive assignments of 'i' and 'j'.\n", errout_str());
check("void test() {\n"
" int i = 0;\n"
" int j = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void test() {\n"
" int i = -1;\n"
" int j = -1;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f(int);\n"
"void test() {\n"
" int i = f(0);\n"
" int j = f(1);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f();\n"
"int g();\n"
"void test() {\n"
" int i = f() || f();\n"
" int j = f() && f();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct Foo {};\n"
"void test() {\n"
" Foo i = Foo();\n"
" Foo j = Foo();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct Foo {};\n"
"void test() {\n"
" Foo i = Foo{};\n"
" Foo j = Foo{};\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct Foo { int f() const; float g() const; };\n"
"void test() {\n"
" Foo f = Foo{};\n"
" int i = f.f();\n"
" int j = f.f();\n"
"}");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:4]: (style, inconclusive) Same expression used in consecutive assignments of 'i' and 'j'.\n", errout_str());
check("struct Foo { int f(); int g(); };\n"
"void test() {\n"
" Foo f = Foo{};\n"
" int i = f.f();\n"
" int j = f.f();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void test() {\n"
" int i = f();\n"
" int j = f();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void test(int x) {\n"
" int i = ++x;\n"
" int j = ++x;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void test(int x) {\n"
" int i = x++;\n"
" int j = x++;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void test(int x) {\n"
" int i = --x;\n"
" int j = --x;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void test(int x) {\n"
" int i = x--;\n"
" int j = x--;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void test(int x) {\n"
" int i = x + 1;\n"
" int j = 1 + x;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void duplicateVarExpressionUnique() {
check("struct SW { int first; };\n"
"void foo(SW* x) {\n"
" int start = x->first;\n"
" int end = x->first;\n"
"}");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:3]: (style, inconclusive) Same expression used in consecutive assignments of 'start' and 'end'.\n"
"[test.cpp:2]: (style) Parameter 'x' can be declared as pointer to const\n",
errout_str());
check("struct SW { int first; };\n"
"void foo(SW* x, int i, int j) {\n"
" int start = x->first;\n"
" int end = x->first;\n"
"}");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:3]: (style, inconclusive) Same expression used in consecutive assignments of 'start' and 'end'.\n"
"[test.cpp:2]: (style) Parameter 'x' can be declared as pointer to const\n",
errout_str());
check("struct Foo { int f() const; };\n"
"void test() {\n"
" Foo f = Foo{};\n"
" int i = f.f();\n"
" int j = f.f();\n"
"}");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:4]: (style, inconclusive) Same expression used in consecutive assignments of 'i' and 'j'.\n", errout_str());
check("void test(const int * p) {\n"
" int i = *p;\n"
" int j = *p;\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:2]: (style, inconclusive) Same expression used in consecutive assignments of 'i' and 'j'.\n", errout_str());
check("struct Foo { int f() const; int g(int) const; };\n"
"void test() {\n"
" Foo f = Foo{};\n"
" int i = f.f();\n"
" int j = f.f();\n"
"}");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:4]: (style, inconclusive) Same expression used in consecutive assignments of 'i' and 'j'.\n", errout_str());
check("struct Foo { int f() const; };\n"
"void test() {\n"
" Foo f = Foo{};\n"
" int i = f.f();\n"
" int j = f.f();\n"
"}");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:4]: (style, inconclusive) Same expression used in consecutive assignments of 'i' and 'j'.\n", errout_str());
}
void duplicateVarExpressionAssign() {
check("struct A { int x; int y; };"
"void use(int);\n"
"void test(A a) {\n"
" int i = a.x;\n"
" int j = a.x;\n"
" use(i);\n"
" i = j;\n"
"}");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:3]: (style, inconclusive) Same expression used in consecutive assignments of 'i' and 'j'.\n", errout_str());
check("struct A { int x; int y; };"
"void use(int);\n"
"void test(A a) {\n"
" int i = a.x;\n"
" int j = a.x;\n"
" use(j);\n"
" j = i;\n"
"}");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:3]: (style, inconclusive) Same expression used in consecutive assignments of 'i' and 'j'.\n", errout_str());
check("struct A { int x; int y; };"
"void use(int);\n"
"void test(A a) {\n"
" int i = a.x;\n"
" int j = a.x;\n"
" use(j);\n"
" if (i == j) {}\n"
"}");
ASSERT_EQUALS(
"[test.cpp:4] -> [test.cpp:3]: (style, inconclusive) Same expression used in consecutive assignments of 'i' and 'j'.\n"
"[test.cpp:3] -> [test.cpp:4] -> [test.cpp:6]: (style) The comparison 'i == j' is always true because 'i' and 'j' represent the same value.\n",
errout_str());
check("struct A { int x; int y; };"
"void use(int);\n"
"void test(A a) {\n"
" int i = a.x;\n"
" int j = a.x;\n"
" use(j);\n"
" if (i == a.x) {}\n"
"}");
ASSERT_EQUALS(
"[test.cpp:4] -> [test.cpp:3]: (style, inconclusive) Same expression used in consecutive assignments of 'i' and 'j'.\n"
"[test.cpp:3] -> [test.cpp:6]: (style) The comparison 'i == a.x' is always true because 'i' and 'a.x' represent the same value.\n",
errout_str());
check("struct A { int x; int y; };"
"void use(int);\n"
"void test(A a) {\n"
" int i = a.x;\n"
" int j = a.x;\n"
" use(i);\n"
" if (j == a.x) {}\n"
"}");
ASSERT_EQUALS(
"[test.cpp:4] -> [test.cpp:3]: (style, inconclusive) Same expression used in consecutive assignments of 'i' and 'j'.\n"
"[test.cpp:4] -> [test.cpp:6]: (style) The comparison 'j == a.x' is always true because 'j' and 'a.x' represent the same value.\n",
errout_str());
// Issue #8612
check("struct P\n"
"{\n"
" void func();\n"
" bool operator==(const P&) const;\n"
"};\n"
"struct X\n"
"{\n"
" P first;\n"
" P second;\n"
"};\n"
"bool bar();\n"
"void baz(const P&);\n"
"void foo(const X& x)\n"
"{\n"
" P current = x.first;\n"
" P previous = x.first;\n"
" while (true)\n"
" {\n"
" baz(current);\n"
" if (bar() && previous == current)\n"
" {\n"
" current.func();\n"
" }\n"
" previous = current;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:16] -> [test.cpp:15]: (style, inconclusive) Same expression used in consecutive assignments of 'current' and 'previous'.\n", errout_str());
}
void duplicateVarExpressionCrash() {
// Issue #8624
check("struct X {\n"
" X();\n"
" int f() const;\n"
"};\n"
"void run() {\n"
" X x;\n"
" int a = x.f();\n"
" int b = x.f();\n"
" (void)a;\n"
" (void)b;\n"
"}");
ASSERT_EQUALS("[test.cpp:8] -> [test.cpp:7]: (style, inconclusive) Same expression used in consecutive assignments of 'a' and 'b'.\n", errout_str());
// Issue #8712
check("void f() {\n"
" unsigned char d;\n"
" d = d % 5;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("template <typename T>\n"
"T f() {\n"
" T x = T();\n"
"}\n"
"int &a = f<int&>();");
ASSERT_EQUALS("", errout_str());
// Issue #8713
check("class A {\n"
" int64_t B = 32768;\n"
" P<uint8_t> m = MakeP<uint8_t>(B);\n"
"};\n"
"void f() {\n"
" uint32_t a = 42;\n"
" uint32_t b = uint32_t(A ::B / 1024);\n"
" int32_t c = int32_t(a / b);\n"
"}");
ASSERT_EQUALS("", errout_str());
// Issue #8709
check("a b;\n"
"void c() {\n"
" switch (d) { case b:; }\n"
" double e(b);\n"
" if(e <= 0) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
// #10718
// Should probably not be inconclusive
check("struct a {\n"
" int b() const;\n"
" auto c() -> decltype(0) {\n"
" a d;\n"
" int e = d.b(), f = d.b();\n"
" return e + f;\n"
" }\n"
"};\n");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:5]: (style, inconclusive) Same expression used in consecutive assignments of 'e' and 'f'.\n", errout_str());
}
void multiConditionSameExpression() {
check("void f() {\n"
" int val = 0;\n"
" if (val < 0) continue;\n"
" if ((val > 0)) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) The comparison 'val < 0' is always false.\n"
"[test.cpp:2] -> [test.cpp:4]: (style) The comparison 'val > 0' is always false.\n", errout_str());
check("void f() {\n"
" int val = 0;\n"
" int *p = &val;n"
" val = 1;\n"
" if (*p < 0) continue;\n"
" if ((*p > 0)) {}\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:3]: (style) Variable 'p' can be declared as pointer to const\n",
errout_str());
check("void f() {\n"
" int val = 0;\n"
" int *p = &val;\n"
" if (*p < 0) continue;\n"
" if ((*p > 0)) {}\n"
"}\n");
TODO_ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) The comparison '*p < 0' is always false.\n"
"[test.cpp:2] -> [test.cpp:4]: (style) The comparison '*p > 0' is always false.\n",
"[test.cpp:3]: (style) Variable 'p' can be declared as pointer to const\n",
errout_str());
check("void f() {\n"
" int val = 0;\n"
" if (val < 0) {\n"
" if ((val > 0)) {}\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) The comparison 'val < 0' is always false.\n"
"[test.cpp:2] -> [test.cpp:4]: (style) The comparison 'val > 0' is always false.\n", errout_str());
check("void f() {\n"
" int val = 0;\n"
" if (val < 0) {\n"
" if ((val < 0)) {}\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) The comparison 'val < 0' is always false.\n"
"[test.cpp:2] -> [test.cpp:4]: (style) The comparison 'val < 0' is always false.\n", errout_str());
check("void f() {\n"
" int activate = 0;\n"
" int foo = 0;\n"
" if (activate) {}\n"
" else if (foo) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void checkSignOfUnsignedVariable() {
check("void foo() {\n"
" for(unsigned char i = 10; i >= 0; i--) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Unsigned expression 'i' can't be negative so it is unnecessary to test it.\n", errout_str());
check("void foo(bool b) {\n"
" for(unsigned int i = 10; b || i >= 0; i--) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Unsigned expression 'i' can't be negative so it is unnecessary to test it.\n", errout_str());
{
const char code[] = "void foo(unsigned int x) {\n"
" if (x < 0) {}\n"
"}";
check(code, true, false, true, false);
ASSERT_EQUALS("[test.cpp:2]: (style) Checking if unsigned expression 'x' is less than zero.\n", errout_str());
check(code, true, false, true, true);
ASSERT_EQUALS("[test.cpp:2]: (style) Checking if unsigned expression 'x' is less than zero.\n", errout_str());
}
check("void foo(unsigned int x) {\n"
" if (x < 0u) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Checking if unsigned expression 'x' is less than zero.\n", errout_str());
check("void foo(int x) {\n"
" if (x < 0) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
{
const char code[] = "void foo(unsigned x) {\n"
" int y = 0;\n"
" if (x < y) {}\n"
"}";
check(code, true, false, true, false);
ASSERT_EQUALS("[test.cpp:3]: (style) Checking if unsigned expression 'x' is less than zero.\n", errout_str());
check(code, true, false, true, true);
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) Checking if unsigned expression 'x' is less than zero.\n", errout_str());
}
check("void foo(unsigned x) {\n"
" int y = 0;\n"
" if (b)\n"
" y = 1;\n"
" if (x < y) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(unsigned int x) {\n"
" if (0 > x) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Checking if unsigned expression 'x' is less than zero.\n", errout_str());
check("void foo(unsigned int x) {\n"
" if (0UL > x) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Checking if unsigned expression 'x' is less than zero.\n", errout_str());
check("void foo(int x) {\n"
" if (0 > x) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(unsigned int x) {\n"
" if (x >= 0) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Unsigned expression 'x' can't be negative so it is unnecessary to test it.\n", errout_str());
check("void foo(unsigned int x, unsigned y) {\n"
" if (x - y >= 0) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Unsigned expression 'x-y' can't be negative so it is unnecessary to test it.\n", errout_str());
check("void foo(unsigned int x) {\n"
" if (x >= 0ull) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Unsigned expression 'x' can't be negative so it is unnecessary to test it.\n", errout_str());
check("void foo(int x) {\n"
" if (x >= 0) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(unsigned int x) {\n"
" if (0 <= x) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Unsigned expression 'x' can't be negative so it is unnecessary to test it.\n", errout_str());
check("void foo(unsigned int x) {\n"
" if (0ll <= x) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Unsigned expression 'x' can't be negative so it is unnecessary to test it.\n", errout_str());
check("void foo(int x) {\n"
" if (0 <= x) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(unsigned int x, bool y) {\n"
" if (x < 0 && y) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Checking if unsigned expression 'x' is less than zero.\n", errout_str());
check("void foo(int x, bool y) {\n"
" if (x < 0 && y) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(unsigned int x, bool y) {\n"
" if (0 > x && y) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Checking if unsigned expression 'x' is less than zero.\n", errout_str());
check("void foo(int x, bool y) {\n"
" if (0 > x && y) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(unsigned int x, bool y) {\n"
" if (x >= 0 && y) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Unsigned expression 'x' can't be negative so it is unnecessary to test it.\n", errout_str());
check("void foo(int x, bool y) {\n"
" if (x >= 0 && y) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(unsigned int x, bool y) {\n"
" if (y && x < 0) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Checking if unsigned expression 'x' is less than zero.\n", errout_str());
check("void foo(int x, bool y) {\n"
" if (y && x < 0) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(unsigned int x, bool y) {\n"
" if (y && 0 > x) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Checking if unsigned expression 'x' is less than zero.\n", errout_str());
check("void foo(int x, bool y) {\n"
" if (y && 0 > x) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(unsigned int x, bool y) {\n"
" if (y && x >= 0) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Unsigned expression 'x' can't be negative so it is unnecessary to test it.\n", errout_str());
check("void foo(int x, bool y) {\n"
" if (y && x >= 0) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(unsigned int x, bool y) {\n"
" if (x < 0 || y) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Checking if unsigned expression 'x' is less than zero.\n", errout_str());
check("void foo(int x, bool y) {\n"
" if (x < 0 || y) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(unsigned int x, bool y) {\n"
" if (0 > x || y) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Checking if unsigned expression 'x' is less than zero.\n", errout_str());
check("void foo(int x, bool y) {\n"
" if (0 > x || y) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(unsigned int x, bool y) {\n"
" if (x >= 0 || y) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Unsigned expression 'x' can't be negative so it is unnecessary to test it.\n", errout_str());
check("void foo(int x, bool y) {\n"
" if (x >= 0 || y) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
// #3233 - FP when template is used (template parameter is numeric constant)
{
const char code[] = "template<int n> void foo(unsigned int x) {\n"
" if (x <= n);\n"
"}\n"
"foo<0>();";
check(code, true, false);
ASSERT_EQUALS("", errout_str());
check(code, true, true);
ASSERT_EQUALS("", errout_str());
}
{
check("template<int n> void foo(unsigned int x) {\n"
"if (x <= 0);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Checking if unsigned expression 'x' is less than zero.\n", errout_str());
}
// #8836
check("uint32_t value = 0xFUL;\n"
"void f() {\n"
" if (value < 0u)\n"
" {\n"
" value = 0u;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Checking if unsigned expression 'value' is less than zero.\n", errout_str());
// #9040
/*const*/ Settings settings1 = settingsBuilder().platform(Platform::Type::Win64).build();
check("using BOOL = unsigned;\n"
"int i;\n"
"bool f() {\n"
" return i >= 0;\n"
"}\n", &settings1);
ASSERT_EQUALS("", errout_str());
// #10612
check("void f(void) {\n"
" const uint32_t x = 0;\n"
" constexpr const auto y = 0xFFFFU;\n"
" if (y < x) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Checking if unsigned expression 'y' is less than zero.\n", errout_str());
// #12387
check("template<typename T>\n"
"void f(T t) {\n"
" if constexpr (std::numeric_limits<T>::is_signed) {\n"
" if (t < 0) {}\n"
" }\n"
"}\n"
"void g() {\n"
" f<uint32_t>(0);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void checkSignOfPointer() {
check("void foo(const int* x) {\n"
" if (x >= 0) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) A pointer can not be negative so it is either pointless or an error to check if it is not.\n", errout_str());
{
const char code[] = "void foo(const int* x) {\n"
" int y = 0;\n"
" if (x >= y) {}\n"
"}";
check(code, true, false, true, false);
ASSERT_EQUALS("[test.cpp:3]: (style) A pointer can not be negative so it is either pointless or an error to check if it is not.\n", errout_str());
check(code, true, false, true, true);
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) A pointer can not be negative so it is either pointless or an error to check if it is not.\n", errout_str());
}
check("void foo(const int* x) {\n"
" if (*x >= 0) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(const int* x) {\n"
" if (x < 0) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) A pointer can not be negative so it is either pointless or an error to check if it is.\n", errout_str());
{
const char code[] = "void foo(const int* x) {\n"
" unsigned y = 0u;\n"
" if (x < y) {}\n"
"}";
check(code, true, false, true, false);
ASSERT_EQUALS("[test.cpp:3]: (style) A pointer can not be negative so it is either pointless or an error to check if it is.\n", errout_str());
check(code, true, false, true, true);
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) A pointer can not be negative so it is either pointless or an error to check if it is.\n", errout_str());
}
check("void foo(const int* x) {\n"
" if (*x < 0) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(const int* x, const int* y) {\n"
" if (x - y < 0) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(const int* x, const int* y) {\n"
" if (x - y <= 0) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(const int* x, const int* y) {\n"
" if (x - y > 0) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(const int* x, const int* y) {\n"
" if (x - y >= 0) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(const Bar* x) {\n"
" if (0 <= x) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) A pointer can not be negative so it is either pointless or an error to check if it is not.\n", errout_str());
check("struct S {\n"
" int* ptr;\n"
"};\n"
"void foo(S* first) {\n"
" if (first.ptr >= 0) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (style) A pointer can not be negative so it is either pointless or an error to check if it is not.\n"
"[test.cpp:4]: (style) Parameter 'first' can be declared as pointer to const\n",
errout_str());
check("struct S {\n"
" int* ptr;\n"
"};\n"
"void foo(S* first, S* second) {\n"
" if((first.ptr - second.ptr) >= 0) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Parameter 'first' can be declared as pointer to const\n"
"[test.cpp:4]: (style) Parameter 'second' can be declared as pointer to const\n",
errout_str());
check("struct S {\n"
" int* ptr;\n"
"};\n"
"void foo(S* first) {\n"
" if((first.ptr) >= 0) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (style) A pointer can not be negative so it is either pointless or an error to check if it is not.\n"
"[test.cpp:4]: (style) Parameter 'first' can be declared as pointer to const\n",
errout_str());
check("struct S {\n"
" int* ptr;\n"
"};\n"
"void foo(S* first, S* second) {\n"
" if(0 <= first.ptr - second.ptr) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Parameter 'first' can be declared as pointer to const\n"
"[test.cpp:4]: (style) Parameter 'second' can be declared as pointer to const\n",
errout_str());
check("struct S {\n"
" int* ptr;\n"
"};\n"
"void foo(S* first, S* second) {\n"
" if(0 <= (first.ptr - second.ptr)) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Parameter 'first' can be declared as pointer to const\n"
"[test.cpp:4]: (style) Parameter 'second' can be declared as pointer to const\n",
errout_str());
check("struct S {\n"
" int* ptr;\n"
"};\n"
"void foo(S* first, S* second) {\n"
" if(first.ptr - second.ptr < 0) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Parameter 'first' can be declared as pointer to const\n"
"[test.cpp:4]: (style) Parameter 'second' can be declared as pointer to const\n",
errout_str());
check("struct S {\n"
" int* ptr;\n"
"};\n"
"void foo(S* first, S* second) {\n"
" if((first.ptr - second.ptr) < 0) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Parameter 'first' can be declared as pointer to const\n"
"[test.cpp:4]: (style) Parameter 'second' can be declared as pointer to const\n",
errout_str());
check("struct S {\n"
" int* ptr;\n"
"};\n"
"void foo(S* first, S* second) {\n"
" if(0 > first.ptr - second.ptr) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Parameter 'first' can be declared as pointer to const\n"
"[test.cpp:4]: (style) Parameter 'second' can be declared as pointer to const\n",
errout_str());
check("struct S {\n"
" int* ptr;\n"
"};\n"
"void foo(S* first, S* second) {\n"
" if(0 > (first.ptr - second.ptr)) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Parameter 'first' can be declared as pointer to const\n"
"[test.cpp:4]: (style) Parameter 'second' can be declared as pointer to const\n",
errout_str());
check("void foo(const int* x) {\n"
" if (0 <= x[0]) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(Bar* x) {\n"
" if (0 <= x.y) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'x' can be declared as pointer to const\n", errout_str());
check("void foo(Bar* x) {\n"
" if (0 <= x->y) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'x' can be declared as pointer to const\n", errout_str());
check("void foo(Bar* x, Bar* y) {\n"
" if (0 <= x->y - y->y ) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'x' can be declared as pointer to const\n"
"[test.cpp:1]: (style) Parameter 'y' can be declared as pointer to const\n",
errout_str());
check("void foo(const Bar* x) {\n"
" if (0 > x) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) A pointer can not be negative so it is either pointless or an error to check if it is.\n", errout_str());
check("void foo(const int* x) {\n"
" if (0 > x[0]) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(Bar* x) {\n"
" if (0 > x.y) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'x' can be declared as pointer to const\n", errout_str());
check("void foo(Bar* x) {\n"
" if (0 > x->y) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'x' can be declared as pointer to const\n", errout_str());
check("void foo() {\n"
" int (*t)(void *a, void *b);\n"
" if (t(a, b) < 0) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" int (*t)(void *a, void *b);\n"
" if (0 > t(a, b)) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct object_info { int *typep; };\n"
"void packed_object_info(struct object_info *oi) {\n"
" if (oi->typep < 0);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) A pointer can not be negative so it is either pointless or an error to check if it is.\n"
"[test.cpp:2]: (style) Parameter 'oi' can be declared as pointer to const\n",
errout_str());
check("struct object_info { int typep[10]; };\n"
"void packed_object_info(struct object_info *oi) {\n"
" if (oi->typep < 0);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) A pointer can not be negative so it is either pointless or an error to check if it is.\n"
"[test.cpp:2]: (style) Parameter 'oi' can be declared as pointer to const\n",
errout_str());
check("struct object_info { int *typep; };\n"
"void packed_object_info(struct object_info *oi) {\n"
" if (*oi->typep < 0);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Parameter 'oi' can be declared as pointer to const\n", errout_str());
}
void checkSuspiciousSemicolon1() {
check("void foo() {\n"
" for(int i = 0; i < 10; ++i);\n"
"}");
ASSERT_EQUALS("", errout_str());
// Empty block
check("void foo() {\n"
" for(int i = 0; i < 10; ++i); {\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Suspicious use of ; at the end of 'for' statement.\n", errout_str());
check("void foo() {\n"
" while (!quit); {\n"
" do_something();\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Suspicious use of ; at the end of 'while' statement.\n", errout_str());
}
void checkSuspiciousSemicolon2() {
check("void foo() {\n"
" if (i == 1); {\n"
" do_something();\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Suspicious use of ; at the end of 'if' statement.\n", errout_str());
// Seen this in the wild
check("void foo() {\n"
" if (Match());\n"
" do_something();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" if (Match());\n"
" else\n"
" do_something();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" if (i == 1)\n"
" ;\n"
" {\n"
" do_something();\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" if (i == 1);\n"
"\n"
" {\n"
" do_something();\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void checkSuspiciousSemicolon3() {
checkP("#define REQUIRE(code) {code}\n"
"void foo() {\n"
" if (x == 123);\n"
" REQUIRE(y=z);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void checkSuspiciousComparison() {
checkP("void f(int a, int b) {\n"
" a > b;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning, inconclusive) Found suspicious operator '>', result is not used.\n", errout_str());
checkP("void f() {\n" // #10607
" for (auto p : m)\n"
" std::vector<std::pair<std::string, std::string>> k;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void checkInvalidFree() {
check("void foo(char *p) {\n"
" char *a; a = malloc(1024);\n"
" free(a + 10);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Mismatching address is freed. The address you get from malloc() must be freed without offset.\n", errout_str());
check("void foo(char *p) {\n"
" char *a; a = malloc(1024);\n"
" free(a - 10);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Mismatching address is freed. The address you get from malloc() must be freed without offset.\n", errout_str());
check("void foo(char *p) {\n"
" char *a; a = malloc(1024);\n"
" free(10 + a);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Mismatching address is freed. The address you get from malloc() must be freed without offset.\n", errout_str());
check("void foo(char *p) {\n"
" char *a; a = new char[1024];\n"
" delete[] (a + 10);\n"
"}");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'p' can be declared as pointer to const\n"
"[test.cpp:3]: (error) Mismatching address is deleted. The address you get from new must be deleted without offset.\n",
errout_str());
check("void foo(char *p) {\n"
" char *a; a = new char;\n"
" delete a + 10;\n"
"}");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'p' can be declared as pointer to const\n"
"[test.cpp:3]: (error) Mismatching address is deleted. The address you get from new must be deleted without offset.\n",
errout_str());
check("void foo(char *p) {\n"
" char *a; a = new char;\n"
" bar(a);\n"
" delete a + 10;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(char *p) {\n"
" char *a; a = new char;\n"
" char *b; b = new char;\n"
" bar(a);\n"
" delete a + 10;\n"
" delete b + 10;\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Mismatching address is deleted. The address you get from new must be deleted without offset.\n", errout_str());
check("void foo(char *p) {\n"
" char *a; a = new char;\n"
" char *b; b = new char;\n"
" bar(a, b);\n"
" delete a + 10;\n"
" delete b + 10;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(char *p) {\n"
" char *a; a = new char;\n"
" bar()\n"
" delete a + 10;\n"
"}");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'p' can be declared as pointer to const\n"
"[test.cpp:4]: (error) Mismatching address is deleted. The address you get from new must be deleted without offset.\n",
errout_str());
check("void foo(size_t xx) {\n"
" char *ptr; ptr = malloc(42);\n"
" ptr += xx;\n"
" free(ptr + 1 - xx);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Mismatching address is freed. The address you get from malloc() must be freed without offset.\n", errout_str());
check("void foo(size_t xx) {\n"
" char *ptr; ptr = malloc(42);\n"
" std::cout << ptr;\n"
" ptr = otherPtr;\n"
" free(otherPtr - xx - 1);\n"
"}");
ASSERT_EQUALS(
"[test.cpp:2]: (style) Variable 'ptr' can be declared as pointer to const\n",
errout_str());
}
void checkRedundantCopy() {
check("const std::string& getA(){static std::string a;return a;}\n"
"void foo() {\n"
" const std::string a = getA();\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (performance, inconclusive) Use const reference for 'a' to avoid unnecessary data copying.\n", errout_str());
check("class A { public: A() {} char x[100]; };\n"
"const A& getA(){static A a;return a;}\n"
"int main()\n"
"{\n"
" const A a = getA();\n"
" return 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (performance, inconclusive) Use const reference for 'a' to avoid unnecessary data copying.\n", errout_str());
check("const int& getA(){static int a;return a;}\n"
"int main()\n"
"{\n"
" const int a = getA();\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("const int& getA(){static int a;return a;}\n"
"int main()\n"
"{\n"
" int getA = 0;\n"
" const int a = getA + 3;\n"
" return 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:4]: (style) Local variable \'getA\' shadows outer function\n", errout_str());
check("class A { public: A() {} char x[100]; };\n"
"const A& getA(){static A a;return a;}\n"
"int main()\n"
"{\n"
" const A a(getA());\n"
" return 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (performance, inconclusive) Use const reference for 'a' to avoid unnecessary data copying.\n", errout_str());
check("const int& getA(){static int a;return a;}\n"
"int main()\n"
"{\n"
" const int a(getA());\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("class A{\n"
"public:A(int a=0){_a = a;}\n"
"A operator+(const A & a){return A(_a+a._a);}\n"
"private:int _a;};\n"
"const A& getA(){static A a;return a;}\n"
"int main()\n"
"{\n"
" const A a = getA() + 1;\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("class A{\n"
"public:A(int a=0){_a = a;}\n"
"A operator+(const A & a){return A(_a+a._a);}\n"
"private:int _a;};\n"
"const A& getA(){static A a;return a;}\n"
"int main()\n"
"{\n"
" const A a(getA()+1);\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #5190 - FP when creating object with constructor that takes a reference
check("class A {};\n"
"class B { B(const A &a); };\n"
"const A &getA();\n"
"void f() {\n"
" const B b(getA());\n"
"}");
ASSERT_EQUALS("", errout_str());
check("class A {};\n"
"class B { B(const A& a); };\n"
"const A& getA();\n"
"void f() {\n"
" const B b{ getA() };\n"
"}");
ASSERT_EQUALS("", errout_str());
// #5618
const char code5618[] = "class Token {\n"
"public:\n"
" const std::string& str();\n"
"};\n"
"void simplifyArrayAccessSyntax() {\n"
" for (Token *tok = list.front(); tok; tok = tok->next()) {\n"
" const std::string temp = tok->str();\n"
" tok->str(tok->strAt(2));\n"
" }\n"
"}";
check(code5618, true, true);
ASSERT_EQUALS("", errout_str());
check(code5618, true, false);
ASSERT_EQUALS("", errout_str());
// #5890 - crash: wesnoth desktop_util.cpp / unicode.hpp
check("typedef std::vector<char> X;\n"
"X f<X>(const X &in) {\n"
" const X s = f<X>(in);\n"
" return f<X>(s);\n"
"}");
ASSERT_EQUALS("", errout_str());
// #7981 - False positive redundantCopyLocalConst - const ref argument to ctor
check("class CD {\n"
" public:\n"
" CD(const CD&);\n"
" static const CD& getOne();\n"
"};\n"
" \n"
"void foo() {\n"
" const CD cd(CD::getOne());\n"
"}", true, true);
ASSERT_EQUALS("", errout_str());
check("struct S {\n" // #10545
" int modify();\n"
" const std::string& get() const;\n"
"};\n"
"std::string f(S& s) {\n"
" const std::string old = s.get();\n"
" int i = s.modify();\n"
" if (i != 0)\n"
" return old;\n"
" return {};\n"
"}", true, /*inconclusive*/ true);
ASSERT_EQUALS("", errout_str());
check("struct X { int x; };\n" // #10191
"struct S {\n"
" X _x;\n"
" X& get() { return _x; }\n"
" void modify() { _x.x += 42; }\n"
" int copy() {\n"
" const X x = get();\n"
" modify();\n"
" return x.x;\n"
" }\n"
" int constref() {\n"
" const X& x = get();\n"
" modify();\n"
" return x.x;\n"
" }\n"
"};\n", true, /*inconclusive*/ true);
ASSERT_EQUALS("", errout_str());
// #10704
check("struct C {\n"
" std::string str;\n"
" const std::string& get() const { return str; }\n"
"};\n"
"struct D {\n"
" C c;\n"
" bool f() const {\n"
" std::string s = c.get();\n"
" return s.empty();\n"
" }\n"
"};\n");
ASSERT_EQUALS("[test.cpp:8]: (performance, inconclusive) Use const reference for 's' to avoid unnecessary data copying.\n", errout_str());
check("struct C {\n"
" const std::string & get() const { return m; }\n"
" std::string m;\n"
"};\n"
"C getC();\n"
"void f() {\n"
" const std::string s = getC().get();\n"
"}\n"
"void g() {\n"
" std::string s = getC().get();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct S {\n" // #12139
" int x, y;\n"
"};\n"
"struct T {\n"
" S s;\n"
" const S& get() const { return s; }\n"
"};\n"
"void f(const T& t) {\n"
" const S a = t.get();\n"
" if (a.x > a.y) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct S {\n" // #12740
" const std::string & get() const { return m; }\n"
" void set(const std::string& v) { m = v; }\n"
" std::string m;\n"
"};\n"
"struct T {\n"
" void f();\n"
" S* s;\n"
"};\n"
"void T::f() {\n"
" const std::string o = s->get();\n"
" s->set(\"abc\");\n"
" s->set(o);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct S {\n" // #12196
" std::string s;\n"
" const std::string& get() const { return s; }\n"
"};\n"
"struct T {\n"
" S* m;\n"
" void f();\n"
"};\n"
"struct U {\n"
" explicit U(S* p);\n"
" void g();\n"
" S* n;\n"
"};\n"
"void T::f() {\n"
" U u(m);\n"
" const std::string c = m->get();\n"
" u.g();\n"
" if (c == m->get()) {}\n"
"}\n");
TODO_ASSERT_EQUALS("",
"[test.cpp:16] -> [test.cpp:18]: (style) The comparison 'c == m->get()' is always true because 'c' and 'm->get()' represent the same value.\n",
errout_str());
check("struct S {\n" // #12925
" const std::string & f() const { return str; }\n"
" std::string str;\n"
"};\n"
"void f(const S* s) {\n"
" const std::string v{ s->f() };\n"
" if (v.empty()) {}\n"
"}\n"
"void g(const S* s) {\n"
" const std::string w(s->f());\n"
" if (w.empty()) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:6]: (performance, inconclusive) Use const reference for 'v' to avoid unnecessary data copying.\n"
"[test.cpp:10]: (performance, inconclusive) Use const reference for 'w' to avoid unnecessary data copying.\n",
errout_str());
check("struct T {\n"
" std::string s;\n"
" const std::string& get() const { return s; }\n"
"};\n"
"void f(const T& t) {\n"
" const auto s = t.get();\n"
" if (s.empty()) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:6]: (performance, inconclusive) Use const reference for 's' to avoid unnecessary data copying.\n", errout_str());
}
void checkNegativeShift() {
check("void foo()\n"
"{\n"
" int a; a = 123;\n"
" (void)(a << -1);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Shifting by a negative value is undefined behaviour\n", errout_str());
check("void foo()\n"
"{\n"
" int a; a = 123;\n"
" (void)(a >> -1);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Shifting by a negative value is undefined behaviour\n", errout_str());
check("void foo()\n"
"{\n"
" int a; a = 123;\n"
" a <<= -1;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Shifting by a negative value is undefined behaviour\n", errout_str());
check("void foo()\n"
"{\n"
" int a; a = 123;\n"
" a >>= -1;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Shifting by a negative value is undefined behaviour\n", errout_str());
check("void foo()\n"
"{\n"
" std::cout << -1;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo()\n"
"{\n"
" std::cout << a << -1 ;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo()\n"
"{\n"
" std::cout << 3 << -1 ;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" x = (-10+2) << 3;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (portability) Shifting a negative value is technically undefined behaviour\n", errout_str());
check("x = y ? z << $-1 : 0;");
ASSERT_EQUALS("", errout_str());
// Negative LHS
check("const int x = -1 >> 2;");
ASSERT_EQUALS("[test.cpp:1]: (portability) Shifting a negative value is technically undefined behaviour\n", errout_str());
// #6383 - unsigned type
check("const int x = (unsigned int)(-1) >> 2;");
ASSERT_EQUALS("", errout_str());
// #7814 - UB happening in valueflowcode when it tried to compute shifts.
check("int shift1() { return 1 >> -1 ;}\n"
"int shift2() { return 1 << -1 ;}\n"
"int shift3() { return -1 >> 1 ;}\n"
"int shift4() { return -1 << 1 ;}");
ASSERT_EQUALS("[test.cpp:1]: (error) Shifting by a negative value is undefined behaviour\n"
"[test.cpp:2]: (error) Shifting by a negative value is undefined behaviour\n"
"[test.cpp:3]: (portability) Shifting a negative value is technically undefined behaviour\n"
"[test.cpp:4]: (portability) Shifting a negative value is technically undefined behaviour\n", errout_str());
check("void f(int i) {\n" // #12916
" if (i < 0) {\n"
" g(\"abc\" << i);\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #13326
check("template<int b>\n"
"int f(int a)\n"
"{\n"
" if constexpr (b >= 0) {\n"
" return a << b;\n"
" } else {\n"
" return a << -b;\n"
" }\n"
"}\n"
"int g() {\n"
" return f<1>(2)\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("template<int b>\n"
"int f(int a)\n"
"{\n"
" if constexpr (b >= 0) {\n"
" return a << b;\n"
" } else {\n"
" return a << -b;\n"
" }\n"
"}\n"
"int g() {\n"
" return f<-1>(2)\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void incompleteArrayFill() {
check("void f() {\n"
" int a[5];\n"
" memset(a, 123, 5);\n"
" memcpy(a, b, 5);\n"
" memmove(a, b, 5);\n"
"}");
ASSERT_EQUALS(// TODO "[test.cpp:4] -> [test.cpp:5]: (performance) Buffer 'a' is being written before its old content has been used.\n"
"[test.cpp:3]: (warning, inconclusive) Array 'a' is filled incompletely. Did you forget to multiply the size given to 'memset()' with 'sizeof(*a)'?\n"
"[test.cpp:4]: (warning, inconclusive) Array 'a' is filled incompletely. Did you forget to multiply the size given to 'memcpy()' with 'sizeof(*a)'?\n"
"[test.cpp:5]: (warning, inconclusive) Array 'a' is filled incompletely. Did you forget to multiply the size given to 'memmove()' with 'sizeof(*a)'?\n", errout_str());
check("int a[5];\n"
"namespace Z { struct B { int a[5]; } b; }\n"
"void f() {\n"
" memset(::a, 123, 5);\n"
" memset(Z::b.a, 123, 5);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:4]: (warning, inconclusive) Array '::a' is filled incompletely. Did you forget to multiply the size given to 'memset()' with 'sizeof(*::a)'?\n"
"[test.cpp:5]: (warning, inconclusive) Array 'Z::b.a' is filled incompletely. Did you forget to multiply the size given to 'memset()' with 'sizeof(*Z::b.a)'?\n",
"[test.cpp:4]: (warning, inconclusive) Array '::a' is filled incompletely. Did you forget to multiply the size given to 'memset()' with 'sizeof(*::a)'?\n", errout_str());
check("void f() {\n"
" Foo* a[5];\n"
" memset(a, 'a', 5);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning, inconclusive) Array 'a' is filled incompletely. Did you forget to multiply the size given to 'memset()' with 'sizeof(*a)'?\n", errout_str());
check("class Foo {int a; int b;};\n"
"void f() {\n"
" Foo a[5];\n"
" memset(a, 'a', 5);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (warning, inconclusive) Array 'a' is filled incompletely. Did you forget to multiply the size given to 'memset()' with 'sizeof(*a)'?\n", errout_str());
check("void f() {\n"
" Foo a[5];\n" // Size of foo is unknown
" memset(a, 'a', 5);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" char a[5];\n"
" memset(a, 'a', 5);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int a[5];\n"
" memset(a+15, 'a', 5);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" bool a[5];\n"
" memset(a, false, 5);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (portability, inconclusive) Array 'a' might be filled incompletely. Did you forget to multiply the size given to 'memset()' with 'sizeof(*a)'?\n", errout_str());
}
void redundantVarAssignment() {
setMultiline();
// Simple tests
check("void f(int i) {\n"
" i = 1;\n"
" i = 1;\n"
"}");
ASSERT_EQUALS("test.cpp:3:style:Variable 'i' is reassigned a value before the old one has been used.\n"
"test.cpp:2:note:i is assigned\n"
"test.cpp:3:note:i is overwritten\n", errout_str());
// non-local variable => only show warning when inconclusive is used
check("int i;\n"
"void f() {\n"
" i = 1;\n"
" i = 1;\n"
"}");
ASSERT_EQUALS("test.cpp:4:style:Variable 'i' is reassigned a value before the old one has been used.\n"
"test.cpp:3:note:i is assigned\n"
"test.cpp:4:note:i is overwritten\n", errout_str());
check("void f() {\n"
" int i;\n"
" i = 1;\n"
" i = 1;\n"
"}");
ASSERT_EQUALS("test.cpp:4:style:Variable 'i' is reassigned a value before the old one has been used.\n"
"test.cpp:3:note:i is assigned\n"
"test.cpp:4:note:i is overwritten\n", errout_str());
check("void f() {\n"
" static int i;\n"
" i = 1;\n"
" i = 1;\n"
"}");
TODO_ASSERT_EQUALS("error", "", errout_str());
check("void f() {\n"
" int i[10];\n"
" i[2] = 1;\n"
" i[2] = 1;\n"
"}");
ASSERT_EQUALS("test.cpp:4:style:Variable 'i[2]' is reassigned a value before the old one has been used.\n"
"test.cpp:3:note:i[2] is assigned\n"
"test.cpp:4:note:i[2] is overwritten\n", errout_str());
check("void f(int x) {\n"
" int i[10];\n"
" i[x] = 1;\n"
" x=1;\n"
" i[x] = 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(const int x) {\n"
" int i[10];\n"
" i[x] = 1;\n"
" i[x] = 1;\n"
"}");
ASSERT_EQUALS("test.cpp:4:style:Variable 'i[x]' is reassigned a value before the old one has been used.\n"
"test.cpp:3:note:i[x] is assigned\n"
"test.cpp:4:note:i[x] is overwritten\n", errout_str());
// Testing different types
check("void f() {\n"
" Foo& bar = foo();\n"
" bar = x;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" Foo& bar = foo();\n"
" bar = x;\n"
" bar = y;\n"
"}");
TODO_ASSERT_EQUALS("error", "", errout_str());
check("void f() {\n"
" Foo& bar = foo();\n" // #4425. bar might refer to something global, etc.
" bar = y();\n"
" foo();\n"
" bar = y();\n"
"}");
ASSERT_EQUALS("", errout_str());
// Tests with function call between assignment
check("void f(int i) {\n"
" i = 1;\n"
" bar();\n"
" i = 1;\n"
"}");
ASSERT_EQUALS("test.cpp:4:style:Variable 'i' is reassigned a value before the old one has been used.\n"
"test.cpp:2:note:i is assigned\n"
"test.cpp:4:note:i is overwritten\n", errout_str());
check("int i;\n"
"void f() {\n"
" i = 1;\n"
" bar();\n" // Global variable might be accessed in bar()
" i = 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" static int i;\n"
" i = 1;\n"
" bar();\n" // bar() might call f() recursively. This could be a false positive in more complex examples (when value of i is used somewhere. See #4229)
" i = 2;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int i;\n"
" i = 1;\n"
" bar();\n"
" i = 1;\n"
"}");
ASSERT_EQUALS("test.cpp:5:style:Variable 'i' is reassigned a value before the old one has been used.\n"
"test.cpp:3:note:i is assigned\n"
"test.cpp:5:note:i is overwritten\n", errout_str());
check("void bar(int i) {}\n"
"void f(int i) {\n"
" i = 1;\n"
" bar(i);\n" // Passed as argument
" i = 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" Foo bar = foo();\n"
" bar();\n" // #5568. operator() called
" bar = y();\n"
"}");
ASSERT_EQUALS("", errout_str());
// Branch tests
check("void f(int i) {\n"
" i = 1;\n"
" if(x)\n"
" i = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int i) {\n"
" if(x)\n"
" i = 0;\n"
" i = 1;\n"
" i = 2;\n"
"}");
ASSERT_EQUALS("test.cpp:5:style:Variable 'i' is reassigned a value before the old one has been used.\n"
"test.cpp:4:note:i is assigned\n"
"test.cpp:5:note:i is overwritten\n", errout_str());
// #4513
check("int x;\n"
"int g() {\n"
" return x*x;\n"
"}\n"
"void f() {\n"
" x = 2;\n"
" x = g();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int g() {\n"
" return x*x;\n"
"}\n"
"void f(int x) {\n"
" x = 2;\n"
" x = g();\n"
"}");
ASSERT_EQUALS("test.cpp:6:style:Variable 'x' is reassigned a value before the old one has been used.\n"
"test.cpp:5:note:x is assigned\n"
"test.cpp:6:note:x is overwritten\n", errout_str());
check("void f() {\n"
" Foo& bar = foo();\n"
" bar = x;\n"
" bar = y();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("class C {\n"
" int x;\n"
" void g() { return x * x; }\n"
" void f();\n"
"};\n"
"\n"
"void C::f() {\n"
" x = 2;\n"
" x = g();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("class C {\n"
" int x;\n"
" void g() { return x*x; }\n"
" void f(Foo z);\n"
"};\n"
"\n"
"void C::f(Foo z) {\n"
" x = 2;\n"
" x = z.g();\n"
"}");
ASSERT_EQUALS("", errout_str());
// ({ })
check("void f() {\n"
" int x;\n"
" x = 321;\n"
" x = ({ asm(123); })\n"
"}");
ASSERT_EQUALS("", errout_str());
// from #3103 (avoid a false negative)
check("int foo(){\n"
" int x;\n"
" x = 1;\n"
" x = 1;\n"
" return x + 1;\n"
"}");
ASSERT_EQUALS("test.cpp:4:style:Variable 'x' is reassigned a value before the old one has been used.\n"
"test.cpp:3:note:x is assigned\n"
"test.cpp:4:note:x is overwritten\n", errout_str());
// from #3103 (avoid a false positive)
check("int foo(){\n"
" int x;\n"
" x = 1;\n"
" if (y)\n" // <-- cppcheck does not know anything about 'y'
" x = 2;\n"
" return x + 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
// initialization, assignment with 0
check("void f() {\n" // Ticket #4356
" int x = 0;\n" // <- ignore initialization with 0
" x = 3;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" state_t *x = NULL;\n"
" x = dostuff();\n"
"}");
ASSERT_EQUALS(
"test.cpp:2:style:Variable 'x' can be declared as pointer to const\n",
errout_str());
check("void f() {\n"
" state_t *x;\n"
" x = NULL;\n"
" x = dostuff();\n"
"}");
ASSERT_EQUALS(
"test.cpp:2:style:Variable 'x' can be declared as pointer to const\n",
errout_str());
check("int foo() {\n" // #4420
" int x;\n"
" bar(++x);\n"
" x = 5;\n"
" return bar(x);\n"
"}");
ASSERT_EQUALS("", errout_str());
// struct member..
check("struct AB { int a; int b; };\n"
"\n"
"int f() {\n"
" struct AB ab;\n"
" ab.a = 1;\n"
" ab.a = 2;\n"
" return ab.a;\n"
"}");
ASSERT_EQUALS("test.cpp:6:style:Variable 'ab.a' is reassigned a value before the old one has been used.\n"
"test.cpp:5:note:ab.a is assigned\n"
"test.cpp:6:note:ab.a is overwritten\n", errout_str());
check("struct AB { int a; int b; };\n"
"\n"
"int f() {\n"
" struct AB ab;\n"
" ab.a = 1;\n"
" ab = do_something();\n"
" return ab.a;\n"
"}");
TODO_ASSERT_EQUALS("error", "", errout_str());
check("struct AB { int a; int b; };\n"
"\n"
"int f() {\n"
" struct AB ab;\n"
" ab.a = 1;\n"
" do_something(&ab);\n"
" ab.a = 2;\n"
" return ab.a;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct AB { int a; int b; };\n"
"\n"
"int f(DO_SOMETHING do_something) {\n"
" struct AB ab;\n"
" ab.a = 1;\n"
" do_something(&ab);\n"
" ab.a = 2;\n"
" return ab.a;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct AB { int a; int b; };\n"
"\n"
"int f(struct AB *ab) {\n"
" ab->a = 1;\n"
" ab->b = 2;\n"
" ab++;\n"
" ab->a = 1;\n"
" ab->b = 2;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct AB { int a; int b; };\n"
"\n"
"int f(struct AB *ab) {\n"
" ab->a = 1;\n"
" ab->b = 2;\n"
" ab = x;\n"
" ab->a = 1;\n"
" ab->b = 2;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(struct AB *ab) {\n" // #
" ab->data->x = 1;\n"
" ab = &ab1;\n"
" ab->data->x = 2;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #5964
check("void func(char *buffer, const char *format, int precision, unsigned value) {\n"
" (precision < 0) ? sprintf(buffer, format, value) : sprintf(buffer, format, precision, value);\n"
"}");
ASSERT_EQUALS("", errout_str());
// don't crash
check("struct data {\n"
" struct { int i; } fc;\n"
"};\n"
"struct state {\n"
" struct data d[123];\n"
"};\n"
"void func(struct state *s) {\n"
" s->foo[s->x++] = 2;\n"
" s->d[1].fc.i++;\n"
"}");
// #6525 - inline assembly
check("void f(int i) {\n"
" i = 1;\n"
" asm(\"foo\");\n"
" i = 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #6555
check("void foo() {\n"
" char *p = 0;\n"
" try {\n"
" p = fred();\n"
" p = wilma();\n"
" }\n"
" catch (...) {\n"
" barney(p);\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" char *p = 0;\n"
" try {\n"
" p = fred();\n"
" p = wilma();\n"
" }\n"
" catch (...) {\n"
" barney(x);\n"
" }\n"
"}");
ASSERT_EQUALS("test.cpp:2:style:The scope of the variable 'p' can be reduced.\n"
"test.cpp:2:style:Variable 'p' can be declared as pointer to const\n",
errout_str());
check("void foo() {\n"
" char *p = 0;\n"
" try {\n"
" if(z) {\n"
" p = fred();\n"
" p = wilma();\n"
" }\n"
" }\n"
" catch (...) {\n"
" barney(p);\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// Member variable pointers
check("void podMemPtrs() {\n"
" int POD::*memptr;\n"
" memptr = &POD::a;\n"
" memptr = &POD::b;\n"
" if (memptr)\n"
" memptr = 0;\n"
"}");
ASSERT_EQUALS("test.cpp:4:style:Variable 'memptr' is reassigned a value before the old one has been used.\n"
"test.cpp:3:note:memptr is assigned\n"
"test.cpp:4:note:memptr is overwritten\n", errout_str());
// Pointer function argument (#3857)
check("void f(float * var)\n"
"{\n"
" var[0] = 0.2f;\n"
" var[0] = 0.2f;\n" // <-- is initialized twice
"}");
ASSERT_EQUALS("test.cpp:4:style:Variable 'var[0]' is reassigned a value before the old one has been used.\n"
"test.cpp:3:note:var[0] is assigned\n"
"test.cpp:4:note:var[0] is overwritten\n", errout_str());
check("void f(float * var)\n"
"{\n"
" *var = 0.2f;\n"
" *var = 0.2f;\n" // <-- is initialized twice
"}");
ASSERT_EQUALS("test.cpp:4:style:Variable '*var' is reassigned a value before the old one has been used.\n"
"test.cpp:3:note:*var is assigned\n"
"test.cpp:4:note:*var is overwritten\n", errout_str());
// Volatile variables
check("void f() {\n"
" volatile char *reg = (volatile char *)0x12345;\n"
" *reg = 12;\n"
" *reg = 34;\n"
"}");
ASSERT_EQUALS("test.cpp:2:style:C-style pointer casting\n", errout_str());
check("void f(std::map<int, int>& m, int key, int value) {\n" // #6379
" m[key] = value;\n"
" m[key] = value;\n"
"}\n");
ASSERT_EQUALS("test.cpp:3:style:Variable 'm[key]' is reassigned a value before the old one has been used.\n"
"test.cpp:2:note:m[key] is assigned\n"
"test.cpp:3:note:m[key] is overwritten\n",
errout_str());
}
void redundantVarAssignment_trivial() {
check("void f() {\n"
" int a = 0;\n"
" a = 4;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int a;\n"
" a = 0;\n"
" a = 4;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" unsigned a;\n"
" a = 0u;\n"
" a = 2u;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" void* a;\n"
" a = (void*)0;\n"
" a = p;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:2]: (style) Variable 'a' can be declared as pointer to const\n",
errout_str());
check("void f() {\n"
" void* a;\n"
" a = (void*)0U;\n"
" a = p;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:2]: (style) Variable 'a' can be declared as pointer to const\n",
errout_str());
}
void redundantVarAssignment_struct() {
check("struct foo {\n"
" int a,b;\n"
"};\n"
"\n"
"int main() {\n"
" struct foo x;\n"
" x.a = _mm_set1_ps(1.0);\n"
" x.a = _mm_set1_ps(2.0);\n"
"}");
ASSERT_EQUALS("[test.cpp:7] -> [test.cpp:8]: (style) Variable 'x.a' is reassigned a value before the old one has been used.\n", errout_str());
check("void f() {\n"
" struct AB ab;\n"
" ab.x = 23;\n"
" ab.y = 41;\n"
" ab.x = 1;\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:5]: (style) Variable 'ab.x' is reassigned a value before the old one has been used.\n", errout_str());
check("void f() {\n"
" struct AB ab = {0};\n"
" ab = foo();\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void redundantVarAssignment_union() {
// Ticket #5115 "redundantAssignment when using a union"
check("void main(void)\n"
"{\n"
" short lTotal = 0;\n"
" union\n"
" {\n"
" short l1;\n"
" struct\n"
" {\n"
" unsigned char b1;\n"
" unsigned char b2;\n"
" } b;\n"
" } u;\n"
" u.l1 = 1;\n"
" lTotal += u.b.b1;\n"
" u.l1 = 2;\n" //Should not show RedundantAssignment
"}", true, false, false);
ASSERT_EQUALS("", errout_str());
// Ticket #5115 "redundantAssignment when using a union"
check("void main(void)\n"
"{\n"
" short lTotal = 0;\n"
" union\n"
" {\n"
" short l1;\n"
" struct\n"
" {\n"
" unsigned char b1;\n"
" unsigned char b2;\n"
" } b;\n"
" } u;\n"
" u.l1 = 1;\n"
" u.l1 = 2;\n"
"}", true, false, false);
ASSERT_EQUALS("[test.cpp:13] -> [test.cpp:14]: (style) Variable 'u.l1' is reassigned a value before the old one has been used.\n", errout_str());
// Ticket #10093 "redundantAssignment when using a union"
check("typedef union fixed32_union {\n"
" struct {\n"
" unsigned32 abcd;\n"
" } u32;\n"
" struct {\n"
" unsigned16 ab;\n"
" unsigned16 cd;\n"
" } u16;"
" struct {\n"
" unsigned8 a;\n"
" unsigned8 b;\n"
" unsigned8 c;\n"
" unsigned8 d;\n"
" } b;\n"
"} fixed32;\n"
"void func1(void) {\n"
" fixed32 m;\n"
" m.u16.ab = 47;\n"
" m.u16.cd = 0;\n"
" m.u16.ab = m.u32.abcd / 53;\n"
"}", true, false, false);
ASSERT_EQUALS("", errout_str());
// Ticket #10093 "redundantAssignment when using a union"
check("typedef union{\n"
" char as_char[4];\n"
" int as_int;\n"
"} union_t;\n"
"void fn(char *data, int len) {\n"
" int i;\n"
" for (i = 0; i < len; i++)\n"
" data[i] = 'a';\n"
"}\n"
"int main(int argc, char *argv[]) {\n"
" union_t u;\n"
" u.as_int = 42;\n"
" fn(&u.as_char[0], 4);\n"
" u.as_int = 0;\n"
"}", true, false, false);
ASSERT_EQUALS("", errout_str());
// Ticket #5115 "redundantAssignment when using a union"
check("void foo(char *ptr) {\n"
" union {\n"
" char * s8;\n"
" unsigned long long u64;\n"
" } addr;\n"
" addr.s8 = ptr;\n"
" addr.u64 += 8;\n"
"}", true, false, false);
ASSERT_EQUALS("", errout_str());
check("struct S {\n" // #12895
" int x, y;\n"
"};\n"
"union U {\n"
" S* s;\n"
"};\n"
"void f(const U& Src, const U& Dst) {\n"
" Dst.s->x = Src.s->x;\n"
" Dst.s->y = Src.s->y;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void redundantVarAssignment_7133() {
// #7133
check("sal_Int32 impl_Export() {\n"
" try {\n"
" try {\n"
" uno::Sequence< uno::Any > aArgs(2);\n"
" beans::NamedValue aValue;\n"
" aValue.Name = \"DocumentHandler\";\n"
" aValue.Value <<= xDocHandler;\n"
" aArgs[0] <<= aValue;\n"
" aValue.Name = \"Model\";\n"
" aValue.Value <<= xDocumentComp;\n"
" aArgs[1] <<= aValue;\n"
" }\n"
" catch (const uno::Exception&) {\n"
" }\n"
" }\n"
" catch (const uno::Exception&) {\n"
" }\n"
"}", true, true);
ASSERT_EQUALS("", errout_str());
check("void ConvertBitmapData(sal_uInt16 nDestBits) {\n"
" BitmapBuffer aSrcBuf;\n"
" aSrcBuf.mnBitCount = nSrcBits;\n"
" BitmapBuffer aDstBuf;\n"
" aSrcBuf.mnBitCount = nDestBits;\n"
" bConverted = ::ImplFastBitmapConversion( aDstBuf, aSrcBuf, aTwoRects );\n"
"}", false);
ASSERT_EQUALS("[test.c:3] -> [test.c:5]: (style) Variable 'aSrcBuf.mnBitCount' is reassigned a value before the old one has been used.\n", errout_str());
check("void ConvertBitmapData(sal_uInt16 nDestBits) {\n"
" BitmapBuffer aSrcBuf;\n"
" aSrcBuf.mnBitCount = nSrcBits;\n"
" BitmapBuffer aDstBuf;\n"
" aSrcBuf.mnBitCount = nDestBits;\n"
" bConverted = ::ImplFastBitmapConversion( aDstBuf, aSrcBuf, aTwoRects );\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:5]: (style) Variable 'aSrcBuf.mnBitCount' is reassigned a value before the old one has been used.\n",
errout_str());
check("class C { void operator=(int x); };\n" // #8368 - assignment operator might have side effects => inconclusive
"void f() {\n"
" C c;\n"
" c = x;\n"
" c = x;\n"
"}");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:5]: (style, inconclusive) Variable 'c' is reassigned a value before the old one has been used if variable is no semaphore variable.\n", errout_str());
}
void redundantVarAssignment_stackoverflow() {
check("typedef struct message_node {\n"
" char code;\n"
" size_t size;\n"
" struct message_node *next, *prev;\n"
"} *message_list;\n"
"static message_list remove_message_from_list(message_list m) {\n"
" m->prev->next = m->next;\n"
" m->next->prev = m->prev;\n"
" return m->next;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void redundantVarAssignment_lambda() {
// #7152
check("int foo() {\n"
" int x = 0, y = 0;\n"
" auto f = [&]() { if (x < 5) ++y; };\n"
" x = 2;\n"
" f();\n"
" x = 6;\n"
" f();\n"
" return y;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #10228
check("std::tuple<int, int> g();\n"
"void h(int);\n"
"void f() {\n"
" auto [a, b] = g();\n"
" auto l = [a = a]() { h(i); };\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void redundantVarAssignment_loop() {
check("void f() {\n"
" char buf[10];\n"
" int i;\n"
" for (i = 0; i < 4; i++)\n"
" buf[i] = 131;\n"
" buf[i] = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void bar() {\n" // #9262 do-while with break
" int x = 0;\n"
" x = 432;\n"
" do {\n"
" if (foo()) break;\n"
" x = 1;\n"
" } while (false);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(int num) {\n" // #9420 FP
" int a = num;\n"
" for (int b = 0; b < num; a = b++)\n"
" dostuff(a);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(int num) {\n" // #9420 FN
" int a = num;\n"
" for (int b = 0; b < num; a = b++);\n"
"}");
TODO_ASSERT_EQUALS("error", "", errout_str());
}
void redundantVarAssignment_after_switch() {
check("void f(int x) {\n" // #7907
" int ret;\n"
" switch (x) {\n"
" case 123:\n"
" ret = 1;\n" // redundant assignment
" break;\n"
" }\n"
" ret = 3;\n"
"}");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:8]: (style) Variable 'ret' is reassigned a value before the old one has been used.\n", errout_str());
}
void redundantVarAssignment_pointer() {
check("void f(int *ptr) {\n"
" int *x = ptr + 1;\n"
" *x = 23;\n"
" foo(ptr);\n"
" *x = 32;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #8997
check("void f() {\n"
" char x[2];\n"
" char* p = x;\n"
" *p = 1;\n"
" p += 1;\n"
" *p = 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void redundantVarAssignment_pointer_parameter() {
check("void f(int *p) {\n"
" *p = 1;\n"
" if (condition) return;\n"
" *p = 2;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void redundantVarAssignment_array() {
check("void f() {\n"
" int arr[10];\n"
" int i = 0;\n"
" arr[i] = 1;\n"
" i += 2;\n"
" arr[i] = 3;\n"
" dostuff(arr);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void redundantVarAssignment_switch_break() {
// #10058
check("void f(int a, int b) {\n"
" int ret = 0;\n"
" switch (a) {\n"
" case 1:\n"
" ret = 543;\n"
" if (b) break;\n"
" ret = 1;\n"
" break;\n"
" }"
" return ret;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int a, int b) {\n"
" int ret = 0;\n"
" switch (a) {\n"
" case 1:\n"
" ret = 543;\n"
" if (b) break;\n"
" ret = 1;\n"
" break;\n"
" }"
"}");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:7]: (style) Variable 'ret' is reassigned a value before the old one has been used.\n", errout_str());
}
void redundantInitialization() {
setMultiline();
check("void f() {\n"
" int err = -ENOMEM;\n"
" err = dostuff();\n"
"}");
ASSERT_EQUALS("test.cpp:3:style:Redundant initialization for 'err'. The initialized value is overwritten before it is read.\n"
"test.cpp:2:note:err is initialized\n"
"test.cpp:3:note:err is overwritten\n",
errout_str());
check("void f() {\n"
" struct S s = {1,2,3};\n"
" s = dostuff();\n"
"}");
ASSERT_EQUALS("test.cpp:3:style:Redundant initialization for 's'. The initialized value is overwritten before it is read.\n"
"test.cpp:2:note:s is initialized\n"
"test.cpp:3:note:s is overwritten\n",
errout_str());
check("void f() {\n"
" int *p = NULL;\n"
" p = dostuff();\n"
"}");
ASSERT_EQUALS(
"test.cpp:2:style:Variable 'p' can be declared as pointer to const\n",
errout_str());
// "trivial" initialization => do not warn
check("void f() {\n"
" struct S s = {0};\n"
" s = dostuff();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("namespace N { enum E {e0,e1}; }\n"
"void f() {\n"
" N::E e = N::e0;\n" // #9261
" e = dostuff();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n" // #10143
" std::shared_ptr<int> i = g();\n"
" h();\n"
" i = nullptr;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("int f(const std::vector<int>& v) {\n" // #9815
" int i = g();\n"
" i = std::distance(v.begin(), std::find_if(v.begin(), v.end(), [=](int j) { return i == j; }));\n"
" return i;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
// cppcheck-suppress unusedPrivateFunction
void redundantMemWrite() {
// Simple tests
// cppcheck-suppress unreachableCode - remove when code is enabled again
check("void f() {\n"
" char a[10];\n"
" memcpy(a, foo, bar);\n"
" memset(a, 0, bar);\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (performance) Buffer 'a' is being written before its old content has been used.\n", errout_str());
check("void f() {\n"
" char a[10];\n"
" strcpy(a, foo);\n"
" strncpy(a, 0, bar);\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (performance) Buffer 'a' is being written before its old content has been used.\n", errout_str());
check("void f() {\n"
" char a[10];\n"
" sprintf(a, \"foo\");\n"
" memmove(a, 0, bar);\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (performance) Buffer 'a' is being written before its old content has been used.\n", errout_str());
check("void f(char *filename) {\n"
" char *p = strrchr(filename,'.');\n"
" strcpy(p, \"foo\");\n"
" dostuff(filename);\n"
" strcpy(p, \"foo\");\n"
"}");
ASSERT_EQUALS("", errout_str());
// Writing to different parts of a buffer
check("void f(void* a) {\n"
" memcpy(a, foo, bar);\n"
" memset(a+5, 0, bar);\n"
"}");
ASSERT_EQUALS("", errout_str());
// Use variable as second argument
check("void f(void* a, void* b) {\n"
" memset(a, 0, 5);\n"
" memcpy(b, a, 5);\n"
" memset(a, 1, 5);\n"
"}");
ASSERT_EQUALS("", errout_str());
// strcat is special
check("void f() {\n"
" char a[10];\n"
" strcpy(a, foo);\n"
" strcat(a, bar);\n" // Not redundant
" strcpy(a, x);\n" // Redundant
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:5]: (performance) Buffer 'a' is being written before its old content has been used.\n", errout_str());
// Tests with function call between copy
check("void f() {\n"
" char a[10];\n"
" snprintf(a, foo, bar);\n"
" bar();\n"
" memset(a, 0, size);\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:5]: (performance) Buffer 'a' is being written before its old content has been used.\n", errout_str());
check("void* a;\n"
"void f() {\n"
" memset(a, 0, size);\n"
" bar();\n" // Global variable might be accessed in bar()
" memset(a, 0, size);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" char a[10];\n"
" memset(a, 0, size);\n"
" bar();\n"
" memset(a, 0, size);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:5]: (performance) Buffer 'a' is being written before its old content has been used.\n", "", errout_str());
check("void bar(void* a) {}\n"
"void f(void* a) {\n"
" memset(a, 0, size);\n"
" bar(a);\n" // Passed as argument
" memset(a, 0, size);\n"
"}");
ASSERT_EQUALS("", errout_str());
// Branch tests
check("void f(void* a) {\n"
" memset(a, 0, size);\n"
" if(x)\n"
" memset(a, 0, size);\n"
"}");
ASSERT_EQUALS("", errout_str());
// #4455 - initialization of local buffer
check("void f(void) {"
" char buf[10];\n"
" memset(buf, 0, 10);\n"
" strcpy(buf, string);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(void) {\n"
" char buf[10] = {0};\n"
" memset(buf, 0, 10);\n"
" strcpy(buf, string);\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (performance) Buffer 'buf' is being written before its old content has been used.\n", errout_str());
// #5689 - use return value of strcpy
check("int f(void* a) {\n"
" int i = atoi(strcpy(a, foo));\n"
" strncpy(a, 0, bar);\n"
" return i;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #7175 - read+write
check("void f() {\n"
" char buf[100];\n"
" strcpy(buf, x);\n"
" strcpy(buf, dostuff(buf));\n" // <- read + write
" strcpy(buf, x);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" char buf[100];\n"
" strcpy(buf, x);\n"
" strcpy(buf, dostuff(buf));\n"
" strcpy(buf, x);\n"
"}");
TODO_ASSERT_EQUALS("error", "", errout_str());
}
void redundantAssignmentSameValue() {
check("int main() {\n" // #11642
" int a = 0;\n"
" int b = a;\n"
" int c = 1;\n"
" a = b;\n"
" return a * b * c;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:5]: (style) Variable 'a' is assigned an expression that holds the same value.\n", errout_str());
check("int main() {\n"
" int a = 0;\n"
" int b = a;\n"
" int c = 1;\n"
" a = b + 1;\n"
" return a * b * c;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("int main() {\n"
" int a = 0;\n"
" int b = a;\n"
" int c = 1;\n"
" a = b = 5;\n"
" return a * b * c;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:5]: (style) Redundant initialization for 'b'. The initialized value is overwritten before it is read.\n", errout_str());
check("int f(int i) {\n" // #12874
" int j = i + 1;\n"
" if (i > 5)\n"
" j = i;\n"
" return j;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct S {\n" // #12894
" std::string a;\n"
" void f(const S& s);\n"
" void g(const S& s);\n"
"};\n"
"void S::f(const S& s) {\n"
" std::string x = a;\n"
" this->operator=(s);\n"
" a = x;\n"
"}\n"
"void S::g(const S& s) {\n"
" std::string x = a;\n"
" operator=(s);\n"
" a = x;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void varFuncNullUB() { // #4482
check("void a(...);\n"
"void b() { a(NULL); }");
ASSERT_EQUALS("[test.cpp:2]: (portability) Passing NULL after the last typed argument to a variadic function leads to undefined behaviour.\n", errout_str());
check("void a(char *p, ...);\n"
"void b() { a(NULL, 2); }");
ASSERT_EQUALS("", errout_str());
}
void checkCastIntToCharAndBack() { // #160
// check getchar
check("void f() {\n"
"unsigned char c; c = getchar();\n"
" while( c != EOF)\n"
" {\n"
" bar(c);\n"
" c = getchar();\n"
" } ;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Storing getchar() return value in char variable and then comparing with EOF.\n", errout_str());
check("void f() {\n"
"unsigned char c = getchar();\n"
" while( EOF != c)\n"
" {\n"
" bar(c);\n"
" } ;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Storing getchar() return value in char variable and then comparing with EOF.\n", errout_str());
check("void f() {\n"
" unsigned char c; c = getchar();\n"
" while( EOF != c )\n"
" {\n"
" bar(c);\n"
" c = getchar();\n"
" } ;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Storing getchar() return value in char variable and then comparing with EOF.\n", errout_str());
check("void f() {\n"
" unsigned char c;\n"
" while( EOF != ( c = getchar() ) )\n"
" {\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Storing getchar() return value in char variable and then comparing with EOF.\n", errout_str());
check("void f() {\n"
" int i; i = getchar();\n"
" while( i != EOF)\n"
" {\n"
" bar(i);\n"
" i = getchar();\n"
" } ;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int i; i = getchar();\n"
" while( EOF != i )\n"
" {\n"
" bar(i);\n"
" i = getchar();\n"
" } ;\n"
"}");
ASSERT_EQUALS("", errout_str());
// check getc
check("void f (FILE * pFile){\n"
"unsigned char c;\n"
"do {\n"
" c = getc (pFile);\n"
"} while (c != EOF)"
"}");
ASSERT_EQUALS("[test.cpp:5]: (warning) Storing getc() return value in char variable and then comparing with EOF.\n", errout_str());
check("void f (FILE * pFile){\n"
"unsigned char c;\n"
"do {\n"
" c = getc (pFile);\n"
"} while (EOF != c)"
"}");
ASSERT_EQUALS("[test.cpp:5]: (warning) Storing getc() return value in char variable and then comparing with EOF.\n", errout_str());
check("void f (FILE * pFile){\n"
"int i;\n"
"do {\n"
" i = getc (pFile);\n"
"} while (i != EOF)"
"}");
ASSERT_EQUALS("", errout_str());
check("void f (FILE * pFile){\n"
"int i;\n"
"do {\n"
" i = getc (pFile);\n"
"} while (EOF != i)"
"}");
ASSERT_EQUALS("", errout_str());
// check fgetc
check("void f (FILE * pFile){\n"
"unsigned char c;\n"
"do {\n"
" c = fgetc (pFile);\n"
"} while (c != EOF)"
"}");
ASSERT_EQUALS("[test.cpp:5]: (warning) Storing fgetc() return value in char variable and then comparing with EOF.\n", errout_str());
check("void f (FILE * pFile){\n"
"char c;\n"
"do {\n"
" c = fgetc (pFile);\n"
"} while (EOF != c)"
"}");
ASSERT_EQUALS("[test.cpp:5]: (warning) Storing fgetc() return value in char variable and then comparing with EOF.\n", errout_str());
check("void f (FILE * pFile){\n"
"signed char c;\n"
"do {\n"
" c = fgetc (pFile);\n"
"} while (EOF != c)"
"}");
ASSERT_EQUALS("", errout_str());
check("void f (FILE * pFile){\n"
"int i;\n"
"do {\n"
" i = fgetc (pFile);\n"
"} while (i != EOF)"
"}");
ASSERT_EQUALS("", errout_str());
check("void f (FILE * pFile){\n"
"int i;\n"
"do {\n"
" i = fgetc (pFile);\n"
"} while (EOF != i)"
"}");
ASSERT_EQUALS("", errout_str());
// cin.get()
check("void f(){\n"
" char ch; ch = std::cin.get();\n"
" while (EOF != ch) {\n"
" std::cout << ch;\n"
" ch = std::cin.get();\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Storing cin.get() return value in char variable and then comparing with EOF.\n", errout_str());
check("void f(){\n"
" char ch; ch = std::cin.get();\n"
" while (ch != EOF) {\n"
" std::cout << ch;\n"
" ch = std::cin.get();\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Storing cin.get() return value in char variable and then comparing with EOF.\n", errout_str());
check("void f(){\n"
" int i; i = std::cin.get();\n"
" while ( EOF != i ) {\n"
" std::cout << i;\n"
" i = std::cin.get();\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(){\n"
" int i; i = std::cin.get();\n"
" while ( i != EOF ) {\n"
" std::cout << i;\n"
" i = std::cin.get();\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void checkCommaSeparatedReturn() {
check("int fun(int a) {\n"
" if (a < 0)\n"
" return a++,\n"
" do_something();\n"
"}", true, false, false);
TODO_ASSERT_EQUALS("[test.cpp:3]: (style) Comma is used in return statement. The comma can easily be misread as a ';'.\n", "", errout_str());
check("int fun(int a) {\n"
" if (a < 0)\n"
" return a++, do_something();\n"
"}", true, false, false);
ASSERT_EQUALS("", errout_str());
check("int fun(int a) {\n"
" if (a < 0)\n"
" return a+5,\n"
" do_something();\n"
"}", true, false, false);
TODO_ASSERT_EQUALS("[test.cpp:3]: (style) Comma is used in return statement. The comma can easily be misread as a ';'.\n", "", errout_str());
check("int fun(int a) {\n"
" if (a < 0)\n"
" return a+5, do_something();\n"
"}", true, false, false);
ASSERT_EQUALS("", errout_str());
check("int fun(int a) {\n"
" if (a < 0)\n"
" return c<int,\nint>::b;\n"
"}", true, false, false);
ASSERT_EQUALS("", errout_str());
// #4943 take care of C++11 initializer lists
check("std::vector<Foo> Bar() {\n"
" return\n"
" {\n"
" { \"1\" },\n"
" { \"2\" },\n"
" { \"3\" }\n"
" };\n"
"}", true, false, false);
ASSERT_EQUALS("", errout_str());
}
void checkPassByReference() {
// #8570 passByValue when std::move is used
check("struct A\n"
"{\n"
" std::vector<int> x;\n"
"};\n"
"\n"
"struct B\n"
"{\n"
" explicit B(A a) : a(std::move(a)) {}\n"
" void Init(A _a) { a = std::move(_a); }\n"
" A a;"
"};", true, false, true);
ASSERT_EQUALS("", errout_str());
check("struct A\n"
"{\n"
" std::vector<int> x;\n"
"};\n"
"\n"
"struct B\n"
"{\n"
" explicit B(A a) : a{std::move(a)} {}\n"
" void Init(A _a) { a = std::move(_a); }\n"
" A a;"
"};", true, false, true);
ASSERT_EQUALS("", errout_str());
check("struct A\n"
"{\n"
" std::vector<int> x;\n"
"};\n"
"\n"
"struct B\n"
"{\n"
" B(A a, A a2) : a{std::move(a)}, a2{std::move(a2)} {}\n"
" void Init(A _a) { a = std::move(_a); }\n"
" A a;"
" A a2;"
"};", true, false, true);
ASSERT_EQUALS("", errout_str());
check("struct A\n"
"{\n"
" std::vector<int> x;\n"
"};\n"
"\n"
"struct B\n"
"{\n"
" B(A a, A a2) : a{std::move(a)}, a2{a2} {}\n"
" void Init(A _a) { a = std::move(_a); }\n"
" A a;"
" A a2;"
"};", true, false, true);
ASSERT_EQUALS("[test.cpp:8]: (performance) Function parameter 'a2' should be passed by const reference.\n", errout_str());
check("struct A\n"
"{\n"
" std::vector<int> x;\n"
"};\n"
"\n"
"struct B\n"
"{\n"
" B(A a, A a2) : a{std::move(a)}, a2(a2) {}\n"
" void Init(A _a) { a = std::move(_a); }\n"
" A a;"
" A a2;"
"};", true, false, true);
ASSERT_EQUALS("[test.cpp:8]: (performance) Function parameter 'a2' should be passed by const reference.\n", errout_str());
check("std::map<int, int> m;\n" // #10817
"void f(const decltype(m)::const_iterator i) {}");
ASSERT_EQUALS("", errout_str());
check("int (*pf) (std::vector<int>) = nullptr;\n" // #12118
"int f(std::vector<int> v) {\n"
" return v.size();\n"
"}\n"
"void g() {\n"
" pf = f;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:6] -> [test.cpp:2]: (performance) Function parameter 'v' should be passed by const reference. However it seems that 'f' is a callback function.\n",
errout_str());
check("template<typename T> struct A;\n" // #12621
"template<typename T>\n"
"struct B { A<T> a; };\n"
"template<typename T>\n"
"struct A { B<T> b; };\n"
"template<typename T>\n"
"struct C : public virtual A<T>, public virtual B<T> {\n"
" A<T> x;\n"
" B<T> y;\n"
" C(A<T> x_, B<T> y_) : x(x_), y(y_) {}\n"
"};\n");
ASSERT_EQUALS("", errout_str()); // don't crash
}
void checkComparisonFunctionIsAlwaysTrueOrFalse() {
// positive test
check("bool f(int x){\n"
" return isless(x,x);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Comparison of two identical variables with isless(x,x) always evaluates to false.\n", errout_str());
check("bool f(int x){\n"
" return isgreater(x,x);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Comparison of two identical variables with isgreater(x,x) always evaluates to false.\n", errout_str());
check("bool f(int x){\n"
" return islessgreater(x,x);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Comparison of two identical variables with islessgreater(x,x) always evaluates to false.\n", errout_str());
check("bool f(int x){\n"
" return islessequal(x,x);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Comparison of two identical variables with islessequal(x,x) always evaluates to true.\n", errout_str());
check("bool f(int x){\n"
" return isgreaterequal(x,x);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Comparison of two identical variables with isgreaterequal(x,x) always evaluates to true.\n", errout_str());
// no warning should be reported for
check("bool f(int x, int y){\n"
" return isgreaterequal(x,y) && islessequal(x,y) && islessgreater(x,y) && isgreater(x,y) && isless(x,y);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void integerOverflow() { // 5895
// no signed integer overflow should happen
check("void f(unsigned long long ull) {\n"
" if (ull == 0x89504e470d0a1a0a || ull == 0x8a4d4e470d0a1a0a) ;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void redundantPointerOp() {
check("int *f(int *x) {\n"
" return &*x;\n"
"}\n", true, true);
ASSERT_EQUALS("[test.cpp:2]: (style) Redundant pointer operation on 'x' - it's already a pointer.\n", errout_str());
check("int *f(int *y) {\n"
" return &(*y);\n"
"}\n", true, true);
ASSERT_EQUALS("[test.cpp:2]: (style) Redundant pointer operation on 'y' - it's already a pointer.\n", errout_str());
check("int f() {\n" // #10991
" int value = 4;\n"
" int result1 = *(&value);\n"
" int result2 = *&value;\n"
" return result1 + result2;\n"
"}\n", true, true);
ASSERT_EQUALS("[test.cpp:3]: (style) Redundant pointer operation on 'value' - it's already a variable.\n"
"[test.cpp:4]: (style) Redundant pointer operation on 'value' - it's already a variable.\n",
errout_str());
check("void f(int& a, int b) {\n"
" *(&a) = b;\n"
"}\n", true, true);
ASSERT_EQUALS("[test.cpp:2]: (style) Redundant pointer operation on 'a' - it's already a variable.\n",
errout_str());
check("void f(int**& p) {}\n", true, true);
ASSERT_EQUALS("", errout_str());
checkP("#define RESTORE(ORIG, COPY) { *ORIG = *COPY; }\n"
"void f(int* p, int i) {\n"
" RESTORE(p, &i);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// no warning for bitwise AND
check("void f(const int *b) {\n"
" int x = 0x20 & *b;\n"
"}\n", true, true);
ASSERT_EQUALS("", errout_str());
// No message for double pointers to structs
check("void f(struct foo **my_struct) {\n"
" char **pass_to_func = &(*my_struct)->buf;\n"
"}\n", true, true);
ASSERT_EQUALS("", errout_str());
// another double pointer to struct - with an array
check("void f(struct foo **my_struct) {\n"
" char **pass_to_func = &(*my_struct)->buf[10];\n"
"}\n", true, true);
ASSERT_EQUALS("", errout_str());
// double pointer to array
check("void f(char **ptr) {\n"
" int *x = &(*ptr)[10];\n"
"}\n", true, true);
ASSERT_EQUALS("[test.cpp:2]: (style) Variable 'x' can be declared as pointer to const\n", errout_str());
// function calls
check("void f(Mutex *mut) {\n"
" pthread_mutex_lock(&*mut);\n"
"}\n", true, false);
ASSERT_EQUALS("[test.cpp:2]: (style) Redundant pointer operation on 'mut' - it's already a pointer.\n", errout_str());
// make sure we got the AST match for "(" right
check("void f(char *ptr) {\n"
" if (&*ptr == NULL)\n"
" return;\n"
"}\n", true, true);
ASSERT_EQUALS("[test.cpp:2]: (style) Redundant pointer operation on 'ptr' - it's already a pointer.\n", errout_str());
// no warning for macros
checkP("#define MUTEX_LOCK(m) pthread_mutex_lock(&(m))\n"
"void f(struct mutex *mut) {\n"
" MUTEX_LOCK(*mut);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkP("#define B(op) bar(op)\n"
"#define C(orf) B(&orf)\n"
"void foo(const int * pkey) {\n"
" C(*pkey);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void test_isSameExpression() { // see #5738
check("bool isInUnoIncludeFile(StringRef name) {"
" return name.startswith(SRCDIR \"/com/\") || name.startswith(SRCDIR \"/uno/\");\n"
"};", true, false);
ASSERT_EQUALS("", errout_str());
}
void raceAfterInterlockedDecrement() {
checkInterlockedDecrement("void f() {\n"
" int counter = 0;\n"
" InterlockedDecrement(&counter);\n"
" whatever();\n"
"}");
ASSERT_EQUALS("", errout_str());
checkInterlockedDecrement("void f() {\n"
" int counter = 0;\n"
" InterlockedDecrement(&counter);\n"
" if (counter)\n"
" return;\n"
" destroy();\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Race condition: non-interlocked access after InterlockedDecrement(). Use InterlockedDecrement() return value instead.\n", errout_str());
checkInterlockedDecrement("void f() {\n"
" int counter = 0;\n"
" InterlockedDecrement(&counter);\n"
" if (!counter)\n"
" destroy();\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Race condition: non-interlocked access after InterlockedDecrement(). Use InterlockedDecrement() return value instead.\n", errout_str());
checkInterlockedDecrement("void f() {\n"
" int counter = 0;\n"
" InterlockedDecrement(&counter);\n"
" if (counter > 0)\n"
" return;\n"
" destroy();\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Race condition: non-interlocked access after InterlockedDecrement(). Use InterlockedDecrement() return value instead.\n", errout_str());
checkInterlockedDecrement("void f() {\n"
" int counter = 0;\n"
" InterlockedDecrement(&counter);\n"
" if (0 < counter)\n"
" return;\n"
" destroy();\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Race condition: non-interlocked access after InterlockedDecrement(). Use InterlockedDecrement() return value instead.\n", errout_str());
checkInterlockedDecrement("void f() {\n"
" int counter = 0;\n"
" InterlockedDecrement(&counter);\n"
" if (counter == 0)\n"
" destroy();\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Race condition: non-interlocked access after InterlockedDecrement(). Use InterlockedDecrement() return value instead.\n", errout_str());
checkInterlockedDecrement("void f() {\n"
" int counter = 0;\n"
" InterlockedDecrement(&counter);\n"
" if (0 == counter)\n"
" destroy();\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Race condition: non-interlocked access after InterlockedDecrement(). Use InterlockedDecrement() return value instead.\n", errout_str());
checkInterlockedDecrement("void f() {\n"
" int counter = 0;\n"
" InterlockedDecrement(&counter);\n"
" if (0 != counter)\n"
" return;\n"
" destroy()\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Race condition: non-interlocked access after InterlockedDecrement(). Use InterlockedDecrement() return value instead.\n", errout_str());
checkInterlockedDecrement("void f() {\n"
" int counter = 0;\n"
" InterlockedDecrement(&counter);\n"
" if (counter != 0)\n"
" return;\n"
" destroy()\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Race condition: non-interlocked access after InterlockedDecrement(). Use InterlockedDecrement() return value instead.\n", errout_str());
checkInterlockedDecrement("void f() {\n"
" int counter = 0;\n"
" InterlockedDecrement(&counter);\n"
" if (counter <= 0)\n"
" destroy();\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Race condition: non-interlocked access after InterlockedDecrement(). Use InterlockedDecrement() return value instead.\n", errout_str());
checkInterlockedDecrement("void f() {\n"
" int counter = 0;\n"
" InterlockedDecrement(&counter);\n"
" if (0 >= counter)\n"
" destroy();\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Race condition: non-interlocked access after InterlockedDecrement(). Use InterlockedDecrement() return value instead.\n", errout_str());
checkInterlockedDecrement("void f() {\n"
" int counter = 0;\n"
" int newCount = InterlockedDecrement(&counter);\n"
" if (newCount)\n"
" return;\n"
" destroy();\n"
"}");
ASSERT_EQUALS("", errout_str());
checkInterlockedDecrement("void f() {\n"
" int counter = 0;\n"
" int newCount = InterlockedDecrement(&counter);\n"
" if (!newCount)\n"
" destroy();\n"
"}");
ASSERT_EQUALS("", errout_str());
checkInterlockedDecrement("void f() {\n"
" int counter = 0;\n"
" int newCount = InterlockedDecrement(&counter);\n"
" if (newCount > 0)\n"
" return;\n"
" destroy();\n"
"}");
ASSERT_EQUALS("", errout_str());
checkInterlockedDecrement("void f() {\n"
" int counter = 0;\n"
" int newCount = InterlockedDecrement(&counter);\n"
" if (0 < newCount)\n"
" return;\n"
" destroy();\n"
"}");
ASSERT_EQUALS("", errout_str());
checkInterlockedDecrement("void f() {\n"
" int counter = 0;\n"
" int newCount = InterlockedDecrement(&counter);\n"
" if (newCount == 0)\n"
" destroy();\n"
"}");
ASSERT_EQUALS("", errout_str());
checkInterlockedDecrement("void f() {\n"
" int counter = 0;\n"
" int newCount = InterlockedDecrement(&counter);\n"
" if (0 == newCount)\n"
" destroy();\n"
"}");
ASSERT_EQUALS("", errout_str());
checkInterlockedDecrement("void f() {\n"
" int counter = 0;\n"
" int newCount = InterlockedDecrement(&counter);\n"
" if (0 != newCount)\n"
" return;\n"
" destroy()\n"
"}");
ASSERT_EQUALS("", errout_str());
checkInterlockedDecrement("void f() {\n"
" int counter = 0;\n"
" int newCount = InterlockedDecrement(&counter);\n"
" if (newCount != 0)\n"
" return;\n"
" destroy()\n"
"}");
ASSERT_EQUALS("", errout_str());
checkInterlockedDecrement("void f() {\n"
" int counter = 0;\n"
" int newCount = InterlockedDecrement(&counter);\n"
" if (newCount <= 0)\n"
" destroy();\n"
"}");
ASSERT_EQUALS("", errout_str());
checkInterlockedDecrement("void f() {\n"
" int counter = 0;\n"
" int newCount = InterlockedDecrement(&counter);\n"
" if (0 >= newCount)\n"
" destroy;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkInterlockedDecrement("int f() {\n"
" int counter = 0;\n"
" if (InterlockedDecrement(&counter) == 0) {\n"
" destroy();\n"
" return 0;\n"
" } else {\n"
" return counter;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (error) Race condition: non-interlocked access after InterlockedDecrement(). Use InterlockedDecrement() return value instead.\n", errout_str());
checkInterlockedDecrement("int f() {\n"
" int counter = 0;\n"
" if (::InterlockedDecrement(&counter) == 0) {\n"
" destroy();\n"
" return 0;\n"
" } else {\n"
" return counter;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (error) Race condition: non-interlocked access after InterlockedDecrement(). Use InterlockedDecrement() return value instead.\n", errout_str());
checkInterlockedDecrement("int f() {\n"
" int counter = 0;\n"
" if (InterlockedDecrement(&counter) == 0) {\n"
" destroy();\n"
" return 0;\n"
" }\n"
" return counter;\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (error) Race condition: non-interlocked access after InterlockedDecrement(). Use InterlockedDecrement() return value instead.\n", errout_str());
checkInterlockedDecrement("int f() {\n"
" int counter = 0;\n"
" if (::InterlockedDecrement(&counter) == 0) {\n"
" destroy();\n"
" return 0;\n"
" }\n"
" return counter;\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (error) Race condition: non-interlocked access after InterlockedDecrement(). Use InterlockedDecrement() return value instead.\n", errout_str());
checkInterlockedDecrement("int f() {\n"
" int counter = 0;\n"
" if (InterlockedDecrement(&counter) == 0) {\n"
" destroy();\n"
" return 0;\n"
" } else\n"
" return counter;\n"
" \n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (error) Race condition: non-interlocked access after InterlockedDecrement(). Use InterlockedDecrement() return value instead.\n", errout_str());
checkInterlockedDecrement("int f() {\n"
" int counter = 0;\n"
" if (::InterlockedDecrement(&counter) == 0) {\n"
" destroy();\n"
" return 0;\n"
" } else\n"
" return counter;\n"
" \n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (error) Race condition: non-interlocked access after InterlockedDecrement(). Use InterlockedDecrement() return value instead.\n", errout_str());
}
void testUnusedLabel() {
check("void f() {\n"
" label:\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Label 'label' is not used.\n", errout_str());
check("void f() {\n"
" label:\n"
" foo();\n"
" goto label;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" label:\n"
" foo();\n"
" goto label;\n"
"}\n"
"void g() {\n"
" label:\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (style) Label 'label' is not used.\n", errout_str());
check("void f() {\n"
" switch(a) {\n"
" default:\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" class X {\n"
" protected:\n"
" };\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" class X {\n"
" my_protected:\n"
" };\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int test(char art) {\n"
" switch (art) {\n"
" caseZERO:\n"
" return 0;\n"
" case1:\n"
" return 1;\n"
" case 2:\n"
" return 2;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Label 'caseZERO' is not used. Should this be a 'case' of the enclosing switch()?\n"
"[test.cpp:5]: (warning) Label 'case1' is not used. Should this be a 'case' of the enclosing switch()?\n", errout_str());
check("int test(char art) {\n"
" switch (art) {\n"
" case 2:\n"
" return 2;\n"
" }\n"
" label:\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (style) Label 'label' is not used.\n", errout_str());
}
#define checkCustomSettings(...) checkCustomSettings_(__FILE__, __LINE__, __VA_ARGS__)
void checkCustomSettings_(const char* file, int line, const char code[], bool cpp = true, bool inconclusive = true, bool runSimpleChecks=true, bool verbose=false, Settings* settings = nullptr) {
if (!settings) {
settings = &_settings;
}
settings->certainty.setEnabled(Certainty::inconclusive, inconclusive);
settings->verbose = verbose;
// Tokenize..
SimpleTokenizer tokenizer(*settings, *this);
ASSERT_LOC(tokenizer.tokenize(code, cpp), file, line);
// Check..
runChecks<CheckOther>(tokenizer, this);
(void)runSimpleChecks; // TODO Remove this
}
void checkCustomSettings_(const char* file, int line, const char code[], Settings *s) {
checkCustomSettings_(file, line, code, true, true, true, false, s);
}
void testEvaluationOrder() {
check("void f() {\n"
" int x = dostuff();\n"
" return x + x++;\n"
"}", false);
ASSERT_EQUALS("[test.c:3]: (error) Expression 'x+x++' depends on order of evaluation of side effects\n", errout_str());
// #7226
check("long int f1(const char *exp) {\n"
" return strtol(++exp, (char **)&exp, 10);\n"
"}", false);
ASSERT_EQUALS("", errout_str());
check("long int f1(const char *exp) {\n"
" return dostuff(++exp, exp, 10);\n"
"}", false);
ASSERT_EQUALS("[test.c:2]: (error) Expression '++exp,exp' depends on order of evaluation of side effects\n", errout_str());
check("void f() {\n"
" int a;\n"
" while (a=x(), a==123) {}\n"
"}", false);
ASSERT_EQUALS("", errout_str());
// # 8717
check("void f(int argc, char *const argv[]) {\n"
" char **local_argv = safe_malloc(sizeof (*local_argv));\n"
" int local_argc = 0;\n"
" local_argv[local_argc++] = argv[0];\n"
"}\n", false);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int x = 0;\n"
" return 0 + x++;\n"
"}\n", false);
ASSERT_EQUALS("", errout_str());
check("void f(int x, int y) {\n"
" int a[10];\n"
" a[x+y] = a[y+x]++;;\n"
"}\n", false);
ASSERT_EQUALS("[test.c:3]: (error) Expression 'a[x+y]=a[y+x]++' depends on order of evaluation of side effects\n", errout_str());
check("void f(int i) {\n"
" int n = ++i + i;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Expression '++i+i' depends on order of evaluation of side effects\n", errout_str());
check("long int f1(const char *exp) {\n"
" return dostuff(++exp, ++exp, 10);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (portability) Expression '++exp,++exp' depends on order of evaluation of side effects. Behavior is Unspecified according to c++17\n"
"[test.cpp:2]: (portability) Expression '++exp,++exp' depends on order of evaluation of side effects. Behavior is Unspecified according to c++17\n", errout_str());
check("void f(int i) {\n"
" int n = (~(-(++i)) + i);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Expression '~(-(++i))+i' depends on order of evaluation of side effects\n", errout_str());
/*const*/ Settings settings11 = settingsBuilder(_settings).cpp(Standards::CPP11).build();
checkCustomSettings("void f(int i) {\n"
" i = i++ + 2;\n"
"}", &settings11);
ASSERT_EQUALS("[test.cpp:2]: (error) Expression 'i+++2' depends on order of evaluation of side effects\n", errout_str());
}
void testEvaluationOrderSelfAssignment() {
// self assignment
check("void f() {\n"
" int x = x = y + 1;\n"
"}", false);
ASSERT_EQUALS(
"[test.c:2]: (style) Redundant assignment of 'x' to itself.\n"
"[test.c:2]: (style) Redundant assignment of 'x' to itself.\n", // duplicate
errout_str());
}
void testEvaluationOrderMacro() {
// macro, don't bailout (#7233)
checkP("#define X x\n"
"void f(int x) {\n"
" return x + X++;\n"
"}", "test.c");
ASSERT_EQUALS("[test.c:3]: (error) Expression 'x+x++' depends on order of evaluation of side effects\n", errout_str());
}
void testEvaluationOrderSequencePointsFunctionCall() {
// FP
check("void f(int id) {\n"
" id = dostuff(id += 42);\n"
"}", false);
ASSERT_EQUALS("", errout_str());
// FN
check("void f(int id) {\n"
" id = id + dostuff(id += 42);\n"
"}", false);
TODO_ASSERT_EQUALS("error", "", errout_str());
}
void testEvaluationOrderSequencePointsComma() {
check("int f(void) {\n"
" int t;\n"
" return (unsigned char)(t=1,t^c);\n"
"}", false);
ASSERT_EQUALS("", errout_str());
check("void f(void) {\n"
" int t;\n"
" dostuff(t=1,t^c);\n"
"}", false);
ASSERT_EQUALS("[test.c:3]: (error) Expression 't=1,t^c' depends on order of evaluation of side effects\n", errout_str());
check("void f(void) {\n"
" int t;\n"
" dostuff((t=1,t),2);\n"
"}", false);
ASSERT_EQUALS("", errout_str());
// #8230
check("void hprf(const char* fp) {\n"
" do\n"
" ;\n"
" while (++fp, (*fp) <= 0177);\n"
"}\n", false);
ASSERT_EQUALS("", errout_str());
check("void hprf(const char* fp) {\n"
" do\n"
" ;\n"
" while (i++, ++fp, (*fp) <= 0177);\n"
"}\n", false);
ASSERT_EQUALS("", errout_str());
check("void f(const char* fp) {\n"
" do\n"
" ;\n"
" while (f(++fp, (*fp) <= 7));\n"
"}\n", false);
ASSERT_EQUALS("[test.c:4]: (error) Expression '++fp,(*fp)<=7' depends on order of evaluation of side effects\n", errout_str());
}
void testEvaluationOrderSizeof() {
check("void f(char *buf) {\n"
" dostuff(buf++, sizeof(*buf));"
"}", false);
ASSERT_EQUALS("", errout_str());
}
void testUnsignedLessThanZero() {
check("struct d {\n"
" unsigned n;\n"
"};\n"
"void f(void) {\n"
" struct d d;\n"
" d.n = 3;\n"
"\n"
" if (d.n < 0) {\n"
" return;\n"
" }\n"
"\n"
" if (0 > d.n) {\n"
" return;\n"
" }\n"
"}", false);
ASSERT_EQUALS("[test.c:8]: (style) Checking if unsigned expression 'd.n' is less than zero.\n"
"[test.c:12]: (style) Checking if unsigned expression 'd.n' is less than zero.\n",
errout_str());
}
void doubleMove1() {
check("void g(A a);\n"
"void f() {\n"
" A a;\n"
" g(std::move(a));\n"
" g(std::move(a));\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (warning) Access of moved variable 'a'.\n", errout_str());
}
void doubleMoveMemberInitialization1() {
check("class A\n"
"{\n"
" A(B && b)\n"
" :b1(std::move(b))\n"
" {\n"
" b2 = std::move(b);\n"
" }\n"
" B b1;\n"
" B b2;\n"
"};");
ASSERT_EQUALS("[test.cpp:6]: (warning) Access of moved variable 'b'.\n", errout_str());
}
void doubleMoveMemberInitialization2() {
check("class A\n"
"{\n"
" A(B && b)\n"
" :b1(std::move(b)),\n"
" b2(std::move(b))\n"
" {}\n"
" B b1;\n"
" B b2;\n"
"};");
ASSERT_EQUALS("[test.cpp:5]: (warning) Access of moved variable 'b'.\n", errout_str());
}
void doubleMoveMemberInitialization3() { // #9974
check("struct A { int i; };\n"
"struct B { A a1; A a2; };\n"
"B f() {\n"
" A a1 = { 1 };\n"
" A a2 = { 2 };\n"
" return { .a1 = std::move(a1), .a2 = std::move(a2) };\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void doubleMoveMemberInitialization4() { // #11440
check("struct S { void f(int); };\n"
"struct T {\n"
" T(int c, S&& d) : c{ c }, d{ std::move(d) } { d.f(c); }\n"
" int c;\n"
" S d;\n"
"};\n");
ASSERT_EQUALS("[test.cpp:3]: (warning, inconclusive) Access of moved variable 'd'.\n", errout_str());
}
void moveAndAssign1() {
check("A g(A a);\n"
"void f() {\n"
" A a;\n"
" a = g(std::move(a));\n"
" a = g(std::move(a));\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void moveAndAssign2() {
check("A g(A a);\n"
"void f() {\n"
" A a;\n"
" B b = g(std::move(a));\n"
" C c = g(std::move(a));\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (warning) Access of moved variable 'a'.\n", errout_str());
}
void moveAssignMoveAssign() {
check("void h(A a);\n"
"void f() {"
" A a;\n"
" g(std::move(a));\n"
" h(a);\n"
" a = b;\n"
" h(a);\n"
" g(std::move(a));\n"
" h(a);\n"
" a = b;\n"
" h(a);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (warning) Access of moved variable 'a'.\n"
"[test.cpp:8]: (warning) Access of moved variable 'a'.\n", errout_str());
}
void moveAndReset1() {
check("A g(A a);\n"
"void f() {\n"
" A a;\n"
" a.reset(g(std::move(a)));\n"
" a.reset(g(std::move(a)));\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void moveAndReset2() {
check("A g(A a);\n"
"void f() {\n"
" A a;\n"
" A b;\n"
" A c;\n"
" b.reset(g(std::move(a)));\n"
" c.reset(g(std::move(a)));\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (warning) Access of moved variable 'a'.\n", errout_str());
}
void moveResetMoveReset() {
check("void h(A a);\n"
"void f() {"
" A a;\n"
" g(std::move(a));\n"
" h(a);\n"
" a.reset(b);\n"
" h(a);\n"
" g(std::move(a));\n"
" h(a);\n"
" a.reset(b);\n"
" h(a);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (warning) Access of moved variable 'a'.\n"
"[test.cpp:8]: (warning) Access of moved variable 'a'.\n", errout_str());
}
void moveAndFunctionParameter() {
check("void g(A a);\n"
"void f() {\n"
" A a;\n"
" A b = std::move(a);\n"
" g(a);\n"
" A c = a;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (warning) Access of moved variable 'a'.\n"
"[test.cpp:6]: (warning) Access of moved variable 'a'.\n", errout_str());
}
void moveAndFunctionParameterReference() {
check("void g(A & a);\n"
"void f() {\n"
" A a;\n"
" A b = std::move(a);\n"
" g(a);\n"
" A c = a;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void moveAndFunctionParameterConstReference() {
check("void g(A const & a);\n"
"void f() {\n"
" A a;\n"
" A b = std::move(a);\n"
" g(a);\n"
" A c = a;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (warning) Access of moved variable 'a'.\n"
"[test.cpp:6]: (warning) Access of moved variable 'a'.\n", errout_str());
}
void moveAndFunctionParameterUnknown() {
check("void f() {\n"
" A a;\n"
" A b = std::move(a);\n"
" g(a);\n"
" A c = a;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (warning, inconclusive) Access of moved variable 'a'.\n"
"[test.cpp:5]: (warning, inconclusive) Access of moved variable 'a'.\n", errout_str());
}
void moveAndReturn() {
check("int f(int i) {\n"
" A a;\n"
" A b;\n"
" g(std::move(a));\n"
" if (i)\n"
" return g(std::move(b));\n"
" return h(std::move(a),std::move(b));\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (warning) Access of moved variable 'a'.\n", errout_str());
}
void moveAndClear() {
check("void f() {\n"
" V v;\n"
" g(std::move(v));\n"
" v.clear();\n"
" if (v.empty()) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void movedPointer() {
check("void f() {\n"
" P p;\n"
" g(std::move(p));\n"
" x = p->x;\n"
" y = p->y;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (warning) Access of moved variable 'p'.\n"
"[test.cpp:5]: (warning) Access of moved variable 'p'.\n", errout_str());
}
void moveAndAddressOf() {
check("void f() {\n"
" std::string s1 = x;\n"
" std::string s2 = std::move(s1);\n"
" p = &s1;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void partiallyMoved() {
check("void f() {\n"
" A a;\n"
" gx(std::move(a).x());\n"
" gy(std::move(a).y());\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void moveAndLambda() {
check("void f() {\n"
" A a;\n"
" auto h = [a=std::move(a)](){return g(std::move(a));};"
" b = a;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void moveInLoop()
{
check("void g(std::string&& s);\n"
"void f() {\n"
" std::string p;\n"
" while(true)\n"
" g(std::move(p));\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5]: (warning) Access of moved variable 'p'.\n", errout_str());
check("std::list<int> g(std::list<int>&&);\n"
"void f(std::list<int>l) {\n"
" for(int i = 0; i < 10; ++i) {\n"
" for (auto &j : g(std::move(l))) { (void)j; }\n"
" }\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (style) Variable 'j' can be declared as reference to const\n"
"[test.cpp:4]: (warning) Access of moved variable 'l'.\n",
errout_str());
}
void moveCallback()
{
check("bool f(std::function<void()>&& callback);\n"
"void func(std::function<void()> callback) {\n"
" if(!f(std::move(callback)))\n"
" callback();\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (warning) Access of moved variable 'callback'.\n", errout_str());
}
void moveClassVariable()
{
check("struct B {\n"
" virtual void f();\n"
"};\n"
"struct D : B {\n"
" void f() override {\n"
" auto p = std::unique_ptr<D>(new D(std::move(m)));\n"
" }\n"
" D(std::unique_ptr<int> c) : m(std::move(c)) {}\n"
" std::unique_ptr<int> m;\n"
"};\n");
ASSERT_EQUALS("", errout_str());
}
void forwardAndUsed() {
check("template<typename T>\n"
"void f(T && t) {\n"
" g(std::forward<T>(t));\n"
" T s = t;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (warning) Access of forwarded variable 't'.\n", errout_str());
}
void moveAndReference() { // #9791
check("void g(std::string&&);\n"
"void h(const std::string&);\n"
"void f() {\n"
" std::string s;\n"
" const std::string& r = s;\n"
" g(std::move(s));\n"
" h(r);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:7]: (warning) Access of moved variable 'r'.\n", errout_str());
}
void moveForRange()
{
check("struct C {\n"
" void f() {\n"
" for (auto r : mCategory.find(std::move(mWhere))) {}\n"
" }\n"
" cif::category mCategory;\n"
" cif::condition mWhere;\n"
"};\n");
ASSERT_EQUALS("", errout_str());
}
void moveTernary()
{
check("void gA(std::string);\n" // #12174
"void gB(std::string);\n"
"void f(bool b) {\n"
" std::string s = \"abc\";\n"
" b ? gA(std::move(s)) : gB(std::move(s));\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("int gA(std::string);\n"
"int gB(std::string);\n"
"void h(int);\n"
"void f(bool b) {\n"
" std::string s = \"abc\";\n"
" h(b ? gA(std::move(s)) : gB(std::move(s)));\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("int gA(int, std::string);\n"
"int gB(int, std::string);\n"
"int h(int);\n"
"void f(bool b) {\n"
" std::string s = \"abc\";\n"
" h(b ? h(gA(5, std::move(s))) : h(gB(7, std::move(s))));\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void funcArgNamesDifferent() {
check("void func1(int a, int b, int c);\n"
"void func1(int a, int b, int c) { }\n"
"void func2(int a, int b, int c);\n"
"void func2(int A, int B, int C) { }\n"
"class Fred {\n"
" void func1(int a, int b, int c);\n"
" void func2(int a, int b, int c);\n"
" void func3(int a = 0, int b = 0, int c = 0);\n"
" void func4(int a = 0, int b = 0, int c = 0);\n"
"};\n"
"void Fred::func1(int a, int b, int c) { }\n"
"void Fred::func2(int A, int B, int C) { }\n"
"void Fred::func3(int a, int b, int c) { }\n"
"void Fred::func4(int A, int B, int C) { }");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (style, inconclusive) Function 'func2' argument 1 names different: declaration 'a' definition 'A'.\n"
"[test.cpp:3] -> [test.cpp:4]: (style, inconclusive) Function 'func2' argument 2 names different: declaration 'b' definition 'B'.\n"
"[test.cpp:3] -> [test.cpp:4]: (style, inconclusive) Function 'func2' argument 3 names different: declaration 'c' definition 'C'.\n"
"[test.cpp:7] -> [test.cpp:12]: (style, inconclusive) Function 'func2' argument 1 names different: declaration 'a' definition 'A'.\n"
"[test.cpp:7] -> [test.cpp:12]: (style, inconclusive) Function 'func2' argument 2 names different: declaration 'b' definition 'B'.\n"
"[test.cpp:7] -> [test.cpp:12]: (style, inconclusive) Function 'func2' argument 3 names different: declaration 'c' definition 'C'.\n"
"[test.cpp:9] -> [test.cpp:14]: (style, inconclusive) Function 'func4' argument 1 names different: declaration 'a' definition 'A'.\n"
"[test.cpp:9] -> [test.cpp:14]: (style, inconclusive) Function 'func4' argument 2 names different: declaration 'b' definition 'B'.\n"
"[test.cpp:9] -> [test.cpp:14]: (style, inconclusive) Function 'func4' argument 3 names different: declaration 'c' definition 'C'.\n", errout_str());
}
void funcArgOrderDifferent() {
check("void func1(int a, int b, int c);\n"
"void func1(int a, int b, int c) { }\n"
"void func2(int a, int b, int c);\n"
"void func2(int c, int b, int a) { }\n"
"void func3(int, int b, int c);\n"
"void func3(int c, int b, int a) { }\n"
"class Fred {\n"
" void func1(int a, int b, int c);\n"
" void func2(int a, int b, int c);\n"
" void func3(int a = 0, int b = 0, int c = 0);\n"
" void func4(int, int b = 0, int c = 0);\n"
"};\n"
"void Fred::func1(int a, int b, int c) { }\n"
"void Fred::func2(int c, int b, int a) { }\n"
"void Fred::func3(int c, int b, int a) { }\n"
"void Fred::func4(int c, int b, int a) { }\n",
true, false);
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (warning) Function 'func2' argument order different: declaration 'a, b, c' definition 'c, b, a'\n"
"[test.cpp:5] -> [test.cpp:6]: (warning) Function 'func3' argument order different: declaration ', b, c' definition 'c, b, a'\n"
"[test.cpp:9] -> [test.cpp:14]: (warning) Function 'func2' argument order different: declaration 'a, b, c' definition 'c, b, a'\n"
"[test.cpp:10] -> [test.cpp:15]: (warning) Function 'func3' argument order different: declaration 'a, b, c' definition 'c, b, a'\n"
"[test.cpp:11] -> [test.cpp:16]: (warning) Function 'func4' argument order different: declaration ', b, c' definition 'c, b, a'\n", errout_str());
}
// #7846 - Syntax error when using C++11 braced-initializer in default argument
void cpp11FunctionArgInit() {
// syntax error is not expected
ASSERT_NO_THROW(check("\n void foo(int declaration = {}) {"
"\n for (int i = 0; i < 10; i++) {}\n"
"\n }"
"\n "));
ASSERT_EQUALS("", errout_str());
}
void shadowVariables() {
check("int x;\n"
"void f() { int x; }");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:2]: (style) Local variable \'x\' shadows outer variable\n", errout_str());
check("int x();\n"
"void f() { int x; }");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:2]: (style) Local variable \'x\' shadows outer function\n", errout_str());
check("struct C {\n"
" C(int x) : x(x) {}\n" // <- we do not want a FP here
" int x;\n"
"};");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" if (cond) {int x;}\n" // <- not a shadow variable
" int x;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int size() {\n"
" int size;\n" // <- not a shadow variable
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n" // #8954 - lambda
" int x;\n"
" auto f = [](){ int x; }"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) { int x; }");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:1]: (style) Local variable 'x' shadows outer argument\n", errout_str());
check("class C { C(); void foo() { static int C = 0; } }"); // #9195 - shadow constructor
ASSERT_EQUALS("", errout_str());
check("struct C {\n" // #10091 - shadow destructor
" ~C();\n"
" void f() {\n"
" bool C{};\n"
" }\n"
"};\n"
"C::~C() = default;");
ASSERT_EQUALS("", errout_str());
// 10752 - no
check("struct S {\n"
" int i;\n"
"\n"
" static int foo() {\n"
" int i = 0;\n"
" return i;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct S {\n"
" int i{};\n"
" void f() { int i; }\n"
"};\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) Local variable 'i' shadows outer variable\n", errout_str());
check("struct S {\n"
" int i{};\n"
" std::vector<int> v;\n"
" void f() const { for (const int& i : v) {} }\n"
"};\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:4]: (style) Local variable 'i' shadows outer variable\n", errout_str());
check("struct S {\n" // #10405
" F* f{};\n"
" std::list<F> fl;\n"
" void S::f() const;\n"
"};\n"
"void S::f() const {\n"
" for (const F& f : fl) {}\n"
"};\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:7]: (style) Local variable 'f' shadows outer variable\n", errout_str());
check("extern int a;\n"
"int a;\n"
"static int f(void) {\n"
" int a;\n"
" return 0;\n"
"}\n", false);
ASSERT_EQUALS("[test.c:1] -> [test.c:4]: (style) Local variable 'a' shadows outer variable\n", errout_str());
check("int f() {\n" // #12591
" int g = 0;\n"
" return g;\n"
"}\n"
"int g() { return 1; }\n");
ASSERT_EQUALS("", errout_str());
}
void knownArgument() {
check("void g(int);\n"
"void f(int x) {\n"
" g((x & 0x01) >> 7);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Argument '(x&0x01)>>7' to function g is always 0. It does not matter what value 'x' has.\n", errout_str());
check("void g(int);\n"
"void f(int x) {\n"
" g((int)((x & 0x01) >> 7));\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Argument '(int)((x&0x01)>>7)' to function g is always 0. It does not matter what value 'x' has.\n", errout_str());
check("void g(int, int);\n"
"void f(int x) {\n"
" g(x, (x & 0x01) >> 7);\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3]: (style) Argument '(x&0x01)>>7' to function g is always 0. It does not matter what value 'x' has.\n",
errout_str());
check("void g(int);\n"
"void f(int x) {\n"
" g(0);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void g(int);\n"
"void h() { return 1; }\n"
"void f(int x) {\n"
" g(h());\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void g(int);\n"
"void f(int x) {\n"
" g(std::strlen(\"a\"));\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void g(int);\n"
"void f(int x) {\n"
" g((int)0);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void g(Foo *);\n"
"void f() {\n"
" g(reinterpret_cast<Foo*>(0));\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void g(int);\n"
"void f(int x) {\n"
" x = 0;\n"
" g(x);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void g(int);\n"
"void f() {\n"
" const int x = 0;\n"
" g(x + 1);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void g(int);\n"
"void f() {\n"
" char i = 1;\n"
" g(static_cast<int>(i));\n"
"}");
ASSERT_EQUALS("", errout_str());
check("char *yytext;\n"
"void re_init_scanner() {\n"
" int size = 256;\n"
" yytext = xmalloc(size * sizeof *yytext);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(const char *c) {\n"
" if (*c == '+' && (operand || !isalnum(*c))) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
// #8986
check("void f(int);\n"
"void g() {\n"
" const int x[] = { 10, 10 };\n"
" f(x[0]);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int);\n"
"void g() {\n"
" int x[] = { 10, 10 };\n"
" f(x[0]);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'x' can be declared as const array\n", errout_str());
check("struct A { int x; };"
"void g(int);\n"
"void f(int x) {\n"
" A y;\n"
" y.x = 1;\n"
" g(y.x);\n"
"}");
ASSERT_EQUALS("", errout_str());
// allow known argument value in assert call
check("void g(int);\n"
"void f(int x) {\n"
" ASSERT((int)((x & 0x01) >> 7));\n"
"}");
ASSERT_EQUALS("", errout_str());
// #9905 - expression that does not use integer calculation at all
check("void foo() {\n"
" const std::string heading = \"Interval\";\n"
" std::cout << std::setw(heading.length());\n"
"}");
ASSERT_EQUALS("", errout_str());
// #9909 - struct member with known value
check("struct LongStack {\n"
" int maxsize;\n"
"};\n"
"\n"
"void growLongStack(LongStack* self) {\n"
" self->maxsize = 32;\n"
" dostuff(self->maxsize * sizeof(intptr_t));\n"
"}");
ASSERT_EQUALS("", errout_str());
// #11894
check("struct S {\n"
" int *p, n;\n"
"};\n"
"S* g() {\n"
" S* s = static_cast<S*>(calloc(1, sizeof(S)));\n"
" s->n = 100;\n"
" s->p = static_cast<int*>(malloc(s->n * sizeof(int)));\n"
" return s;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #11679
check("bool g(int);\n"
"void h(int);\n"
"int k(int a) { h(a); return 0; }\n"
"void f(int i) {\n"
" if (g(k(i))) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #11889
check("struct S {\n"
" int a[5];\n"
" void f(int i);\n"
"}\n"
"void g(int);\n"
"void S::f(int i) {\n"
" if (a[i] == 1) {\n"
" a[i] = 0;\n"
" g(a[i]);\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #11927
check("void f(func_t func, int i) {\n"
" (func)(i, 0);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct S { void operator()(int, int); };\n"
"void f(int i) {\n"
" S()(i, 1);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(int& r) {\n"
" g(static_cast<char>(r = 42));\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct S { int i; };\n"
"void f(int i) {\n"
" const int a[] = { i - 1 * i, 0 };\n"
" auto s = S{ i - 1 * i };\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) Argument 'i-1*i' to init list { is always 0. It does not matter what value 'i' has.\n"
"[test.cpp:4]: (style) Argument 'i-1*i' to constructor S is always 0. It does not matter what value 'i' has.\n",
errout_str());
checkP("#define MACRO(X) std::abs(X ? 0 : a)\n"
"int f(int a) {\n"
" return MACRO(true);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void knownArgumentHiddenVariableExpression() {
// #9914 - variable expression is explicitly hidden
check("void f(int x) {\n"
" dostuff(x && false);\n"
" dostuff(false && x);\n"
" dostuff(x || true);\n"
" dostuff(true || x);\n"
" dostuff(x * 0);\n"
" dostuff(0 * x);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) Argument 'false&&x' to function dostuff is always 0. Constant literal calculation disable/hide variable expression 'x'.\n"
"[test.cpp:5]: (style) Argument 'true||x' to function dostuff is always 1. Constant literal calculation disable/hide variable expression 'x'.\n"
"[test.cpp:6]: (style) Argument 'x*0' to function dostuff is always 0. Constant literal calculation disable/hide variable expression 'x'.\n"
"[test.cpp:7]: (style) Argument '0*x' to function dostuff is always 0. Constant literal calculation disable/hide variable expression 'x'.\n", errout_str());
}
void knownArgumentTernaryOperator() { // #10374
check("void f(bool a, bool b) {\n"
" const T* P = nullptr; \n"
" long N = 0; \n"
" const bool c = foo(); \n"
" bar(P, N); \n"
" if (c ? a : b)\n"
" baz(P, N); \n"
"}");
ASSERT_EQUALS("", errout_str());
}
void checkComparePointers() {
check("int f() {\n"
" const int foo[1] = {0};\n"
" const int bar[1] = {0};\n"
" int diff = 0;\n"
" if(foo > bar) {\n"
" diff = 1;\n"
" }\n"
" return diff;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:2] -> [test.cpp:5] -> [test.cpp:3] -> [test.cpp:5] -> [test.cpp:5]: (error) Comparing pointers that point to different objects\n",
errout_str());
check("bool f() {\n"
" int x = 0;\n"
" int y = 0;\n"
" int* xp = &x;\n"
" int* yp = &y;\n"
" return xp > yp;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:2] -> [test.cpp:4] -> [test.cpp:3] -> [test.cpp:5] -> [test.cpp:6]: (error) Comparing pointers that point to different objects\n"
"[test.cpp:4]: (style) Variable 'xp' can be declared as pointer to const\n"
"[test.cpp:5]: (style) Variable 'yp' can be declared as pointer to const\n",
errout_str());
check("bool f() {\n"
" int x = 0;\n"
" int y = 1;\n"
" return &x > &y;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:2] -> [test.cpp:4] -> [test.cpp:3] -> [test.cpp:4] -> [test.cpp:4]: (error) Comparing pointers that point to different objects\n",
errout_str());
check("struct A {int data;};\n"
"bool f() {\n"
" A x;\n"
" A y;\n"
" int* xp = &x.data;\n"
" int* yp = &y.data;\n"
" return xp > yp;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3] -> [test.cpp:5] -> [test.cpp:4] -> [test.cpp:6] -> [test.cpp:7]: (error) Comparing pointers that point to different objects\n"
"[test.cpp:5]: (style) Variable 'xp' can be declared as pointer to const\n"
"[test.cpp:6]: (style) Variable 'yp' can be declared as pointer to const\n",
errout_str());
check("struct A {int data;};\n"
"bool f(A ix, A iy) {\n"
" A* x = &ix;\n"
" A* y = &iy;\n"
" int* xp = &x->data;\n"
" int* yp = &y->data;\n"
" return xp > yp;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:2] -> [test.cpp:3] -> [test.cpp:5] -> [test.cpp:2] -> [test.cpp:4] -> [test.cpp:6] -> [test.cpp:7]: (error) Comparing pointers that point to different objects\n"
"[test.cpp:5]: (style) Variable 'xp' can be declared as pointer to const\n"
"[test.cpp:6]: (style) Variable 'yp' can be declared as pointer to const\n",
errout_str());
check("bool f(int * xp, int* yp) {\n"
" return &xp > &yp;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:1] -> [test.cpp:2] -> [test.cpp:1] -> [test.cpp:2] -> [test.cpp:2]: (error) Comparing pointers that point to different objects\n",
errout_str());
check("int f() {\n"
" int x = 0;\n"
" int y = 1;\n"
" return &x - &y;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:2] -> [test.cpp:4] -> [test.cpp:3] -> [test.cpp:4] -> [test.cpp:4]: (error) Subtracting pointers that point to different objects\n",
errout_str());
check("bool f() {\n"
" int x[2] = {1, 2}m;\n"
" int* xp = &x[0];\n"
" int* yp = &x[1];\n"
" return xp > yp;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'xp' can be declared as pointer to const\n"
"[test.cpp:4]: (style) Variable 'yp' can be declared as pointer to const\n",
errout_str());
check("bool f(const int * xp, const int* yp) {\n"
" return xp > yp;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool f(const int & x, const int& y) {\n"
" return &x > &y;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int& g();\n"
"bool f() {\n"
" const int& x = g();\n"
" const int& y = g();\n"
" const int* xp = &x;\n"
" const int* yp = &y;\n"
" return xp > yp;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct A {int data;};\n"
"bool f(A ix) {\n"
" A* x = &ix;\n"
" A* y = x;\n"
" int* xp = &x->data;\n"
" int* yp = &y->data;\n"
" return xp > yp;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (style) Variable 'xp' can be declared as pointer to const\n"
"[test.cpp:6]: (style) Variable 'yp' can be declared as pointer to const\n",
errout_str());
check("struct S { int i; };\n" // #11576
"int f(S s) {\n"
" return &s.i - (int*)&s;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) C-style pointer casting\n", errout_str());
check("struct S { int i; };\n"
"int f(S s1, S s2) {\n"
" return &s1.i - reinterpret_cast<int*>(&s2);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3] -> [test.cpp:2] -> [test.cpp:3] -> [test.cpp:3]: (error) Subtracting pointers that point to different objects\n",
errout_str());
check("struct S { int a; int b; };\n" // #12422
"int f() {\n"
" S s;\n"
" return &s.b - &s.a;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void unusedVariableValueTemplate() {
check("#include <functional>\n"
"class A\n"
"{\n"
"public:\n"
" class Hash\n"
" {\n"
" public:\n"
" std::size_t operator()(const A& a) const\n"
" {\n"
" (void)a;\n"
" return 0;\n"
" }\n"
" };\n"
"};\n"
"namespace std\n"
"{\n"
" template <>\n"
" struct hash<A>\n"
" {\n"
" std::size_t operator()(const A& a) const noexcept\n"
" {\n"
" return A::Hash{}(a);\n"
" }\n"
" };\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void moduloOfOne() {
check("void f(unsigned int x) {\n"
" int y = x % 1;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Modulo of one is always equal to zero\n", errout_str());
check("void f() {\n"
" for (int x = 1; x < 10; x++) {\n"
" int y = 100 % x;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int i, int j) {\n" // #11191
" const int c = pow(2, i);\n"
" if (j % c) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void sameExpressionPointers() {
check("int f(int *i);\n"
"void g(int *a, const int *b) {\n"
" int c = *a;\n"
" f(a);\n"
" if (b && c != *a) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void checkOverlappingWrite() {
// union
check("void foo() {\n"
" union { int i; float f; } u;\n"
" u.i = 0;\n"
" u.i = u.f;\n" // <- error
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Overlapping read/write of union is undefined behavior\n", errout_str());
check("void foo() {\n" // #11013
" union { struct { uint8_t a; uint8_t b; }; uint16_t c; } u;\n"
" u.a = u.b = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
// memcpy
check("void foo() {\n"
" char a[10];\n"
" memcpy(&a[5], &a[4], 2u);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Overlapping read/write in memcpy() is undefined behavior\n", errout_str());
check("void foo() {\n"
" char a[10];\n"
" memcpy(a+5, a+4, 2u);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Overlapping read/write in memcpy() is undefined behavior\n", errout_str());
check("void foo() {\n"
" char a[10];\n"
" memcpy(a, a+1, 2u);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Overlapping read/write in memcpy() is undefined behavior\n", errout_str());
check("void foo() {\n"
" char a[8];\n"
" memcpy(&a[0], &a[4], 4u);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("_Bool a[10];\n" // #10350
"void foo() {\n"
" memcpy(&a[5], &a[4], 2u * sizeof(a[0]));\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Overlapping read/write in memcpy() is undefined behavior\n", errout_str());
check("int K[2];\n" // #12638
"void f(int* p) {\n"
" memcpy(&K[0], &K[1], sizeof(K[0]));\n"
" memcpy(&K[1], &K[0], sizeof(K[0]));\n"
" memcpy(p, p + 1, sizeof(*p));\n"
" memcpy(p + 1, p, sizeof(*p));\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int K[2];\n"
"void f(int* p) {\n"
" memcpy(&K[0], &K[1], 2 * sizeof(K[0]));\n"
" memcpy(&K[1], &K[0], 2 *sizeof(K[0]));\n"
" memcpy(p, p + 1, 2 * sizeof(*p));\n"
" memcpy(p + 1, p, 2 * sizeof(*p));\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Overlapping read/write in memcpy() is undefined behavior\n"
"[test.cpp:4]: (error) Overlapping read/write in memcpy() is undefined behavior\n"
"[test.cpp:5]: (error) Overlapping read/write in memcpy() is undefined behavior\n"
"[test.cpp:6]: (error) Overlapping read/write in memcpy() is undefined behavior\n",
errout_str());
// wmemcpy
check("void foo() {\n"
" wchar_t a[10];\n"
" wmemcpy(&a[5], &a[4], 2u);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Overlapping read/write in wmemcpy() is undefined behavior\n", errout_str());
check("void foo() {\n"
" wchar_t a[10];\n"
" wmemcpy(a+5, a+4, 2u);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Overlapping read/write in wmemcpy() is undefined behavior\n", errout_str());
check("void foo() {\n"
" wchar_t a[10];\n"
" wmemcpy(a, a+1, 2u);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Overlapping read/write in wmemcpy() is undefined behavior\n", errout_str());
// strcpy
check("void foo(char *ptr) {\n"
" strcpy(ptr, ptr);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Overlapping read/write in strcpy() is undefined behavior\n", errout_str());
}
void constVariableArrayMember() { // #10371
check("class Foo {\n"
"public:\n"
" Foo();\n"
" int GetVal() const { return m_Arr[0]; }\n"
" int m_Arr[1];\n"
"};\n");
ASSERT_EQUALS("", errout_str());
}
void knownPointerToBool()
{
check("void g(bool);\n"
"void f() {\n"
" int i = 5;\n"
" int* p = &i;\n"
" g(p);\n"
" g(&i);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5]: (style) Pointer expression 'p' converted to bool is always true.\n"
"[test.cpp:6]: (style) Pointer expression '&i' converted to bool is always true.\n",
errout_str());
check("void f() {\n"
" const int* x = nullptr;\n"
" std::empty(x);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" const int* x = nullptr;\n"
" std::empty(const_cast<int*>(x));\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct A { bool x; };\n"
"bool f(A* a) {\n"
" if (a) {\n"
" return a->x;\n"
" }\n"
" return false;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct A { int* x; };\n"
"bool f(A a) {\n"
" if (a.x) {\n"
" return a.x;\n"
" }\n"
" return false;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (style) Pointer expression 'a.x' converted to bool is always true.\n", errout_str());
check("void f(bool* b) { if (b) *b = true; }");
ASSERT_EQUALS("", errout_str());
check("bool f() {\n"
" int* x = nullptr;\n"
" return bool(x);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) Pointer expression 'x' converted to bool is always false.\n", errout_str());
check("bool f() {\n"
" int* x = nullptr;\n"
" return bool{x};\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) Pointer expression 'x' converted to bool is always false.\n", errout_str());
check("struct A { A(bool); };\n"
"A f() {\n"
" int* x = nullptr;\n"
" return A(x);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (style) Pointer expression 'x' converted to bool is always false.\n", errout_str());
check("struct A { A(bool); };\n"
"A f() {\n"
" int* x = nullptr;\n"
" return A{x};\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (style) Pointer expression 'x' converted to bool is always false.\n", errout_str());
check("struct B { virtual void f() {} };\n" // #11929
"struct D : B {};\n"
"void g(B* b) {\n"
" if (!b)\n"
" return;\n"
" if (dynamic_cast<D*>(b)) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("bool (*ptr)();\n" // #12170
"void f() {\n"
" if (!ptr || !ptr()) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void g(bool b[2]);\n" // #12822
"void f() {\n"
" bool b[2] = {};\n"
" g(b);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void iterateByValue() {
check("void f() {\n" // #9684
" const std::set<std::string> ss = { \"a\", \"b\", \"c\" };\n"
" for (auto s : ss)\n"
" (void)s.size();\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (performance) Range variable 's' should be declared as const reference.\n",
errout_str());
}
};
REGISTER_TEST(TestOther)
| null |
962 | cpp | cppcheck | redirect.h | test/redirect.h | null | // Cppcheck - A tool for static C/C++ code analysis
// Copyright (C) 2007-2024 Cppcheck team.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#ifndef REDIRECT_H
#define REDIRECT_H
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
/**
* @brief Utility class for capturing cout and cerr to ostringstream buffers
* for later use. Uses RAII to stop redirection when the object goes out of
* scope.
* NOTE: This is *not* thread-safe.
*/
class RedirectOutputError {
public:
/** Set up redirection, flushing anything in the pipes. */
RedirectOutputError() {
// flush all old output
std::cout.flush();
std::cerr.flush();
_oldCout = std::cout.rdbuf(); // back up cout's streambuf
_oldCerr = std::cerr.rdbuf(); // back up cerr's streambuf
std::cout.rdbuf(_out.rdbuf()); // assign streambuf to cout
std::cerr.rdbuf(_err.rdbuf()); // assign streambuf to cerr
}
/** Revert cout and cerr behaviour */
~RedirectOutputError() noexcept(false) {
std::cout.rdbuf(_oldCout); // restore cout's original streambuf
std::cerr.rdbuf(_oldCerr); // restore cerrs's original streambuf
{
const std::string s = _out.str();
if (!s.empty())
throw std::runtime_error("unconsumed stdout: " + s); // cppcheck-suppress exceptThrowInDestructor - FP #11031
}
{
const std::string s = _err.str();
if (!s.empty())
throw std::runtime_error("consumed stderr: " + s);
}
}
/** Return what would be printed to cout. */
std::string getOutput() {
std::string s = _out.str();
_out.str("");
return s;
}
/** Return what would be printed to cerr. */
std::string getErrout() {
std::string s = _err.str();
_err.str("");
return s;
}
private:
std::ostringstream _out;
std::ostringstream _err;
std::streambuf *_oldCout;
std::streambuf *_oldCerr;
};
class SuppressOutput {
public:
/** Set up suppression, flushing anything in the pipes. */
SuppressOutput() {
// flush all old output
std::cout.flush();
std::cerr.flush();
_oldCout = std::cout.rdbuf(); // back up cout's streambuf
_oldCerr = std::cerr.rdbuf(); // back up cerr's streambuf
std::cout.rdbuf(nullptr); // disable cout
std::cerr.rdbuf(nullptr); // disable cerr
}
/** Revert cout and cerr behaviour */
~SuppressOutput() {
std::cout.rdbuf(_oldCout); // restore cout's original streambuf
std::cerr.rdbuf(_oldCerr); // restore cerrs's original streambuf
}
private:
std::streambuf *_oldCout;
std::streambuf *_oldCerr;
};
#define REDIRECT RedirectOutputError redir
#define GET_REDIRECT_OUTPUT redir.getOutput()
#define GET_REDIRECT_ERROUT redir.getErrout()
#define SUPPRESS SuppressOutput supprout
class RedirectInput {
public:
explicit RedirectInput(const std::string &input) : _in(input) {
_oldCin = std::cin.rdbuf(); // back up cin's streambuf
std::cin.rdbuf(_in.rdbuf()); // assign streambuf to cin
}
~RedirectInput() noexcept {
std::cin.rdbuf(_oldCin); // restore cin's original streambuf
}
private:
std::istringstream _in;
std::streambuf* _oldCin;
};
#endif
| null |
963 | cpp | cppcheck | testprocessexecutor.cpp | test/testprocessexecutor.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "processexecutor.h"
#include "redirect.h"
#include "settings.h"
#include "filesettings.h"
#include "fixture.h"
#include "helpers.h"
#include "suppressions.h"
#include "timer.h"
#include <cstdlib>
#include <list>
#include <memory>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
class TestProcessExecutorBase : public TestFixture {
public:
TestProcessExecutorBase(const char * const name, bool useFS) : TestFixture(name), useFS(useFS) {}
private:
/*const*/ Settings settings = settingsBuilder().library("std.cfg").build();
bool useFS;
std::string fprefix() const
{
if (useFS)
return "processfs";
return "process";
}
struct CheckOptions
{
CheckOptions() = default;
bool quiet = true;
SHOWTIME_MODES showtime = SHOWTIME_MODES::SHOWTIME_NONE;
const char* plistOutput = nullptr;
std::vector<std::string> filesList;
bool clangTidy = false;
bool executeCommandCalled = false;
std::string exe;
std::vector<std::string> args;
};
/**
* Execute check using n jobs for y files which are have
* identical data, given within data.
*/
void check(unsigned int jobs, int files, int result, const std::string &data, const CheckOptions& opt = make_default_obj{}) {
std::list<FileSettings> fileSettings;
std::list<FileWithDetails> filelist;
if (opt.filesList.empty()) {
for (int i = 1; i <= files; ++i) {
std::string f_s = fprefix() + "_" + std::to_string(i) + ".cpp";
filelist.emplace_back(f_s, data.size());
if (useFS) {
fileSettings.emplace_back(std::move(f_s), data.size());
}
}
}
else {
for (const auto& f : opt.filesList)
{
filelist.emplace_back(f, data.size());
if (useFS) {
fileSettings.emplace_back(f, data.size());
}
}
}
/*const*/ Settings s = settings;
s.jobs = jobs;
s.showtime = opt.showtime;
s.quiet = opt.quiet;
if (opt.plistOutput)
s.plistOutput = opt.plistOutput;
bool executeCommandCalled = false;
std::string exe;
std::vector<std::string> args;
// NOLINTNEXTLINE(performance-unnecessary-value-param)
auto executeFn = [&executeCommandCalled, &exe, &args](std::string e,std::vector<std::string> a,std::string,std::string&){
executeCommandCalled = true;
exe = std::move(e);
args = std::move(a);
return EXIT_SUCCESS;
};
std::vector<std::unique_ptr<ScopedFile>> scopedfiles;
scopedfiles.reserve(filelist.size());
for (std::list<FileWithDetails>::const_iterator i = filelist.cbegin(); i != filelist.cend(); ++i)
scopedfiles.emplace_back(new ScopedFile(i->path(), data));
// clear files list so only fileSettings are used
if (useFS)
filelist.clear();
ProcessExecutor executor(filelist, fileSettings, s, s.supprs.nomsg, *this, executeFn);
ASSERT_EQUALS(result, executor.check());
ASSERT_EQUALS(opt.executeCommandCalled, executeCommandCalled);
ASSERT_EQUALS(opt.exe, exe);
ASSERT_EQUALS(opt.args.size(), args.size());
for (std::size_t i = 0; i < args.size(); ++i)
{
ASSERT_EQUALS(opt.args[i], args[i]);
}
}
void run() override {
#if !defined(WIN32) && !defined(__MINGW32__) && !defined(__CYGWIN__)
TEST_CASE(deadlock_with_many_errors);
TEST_CASE(many_threads);
TEST_CASE(many_threads_showtime);
TEST_CASE(many_threads_plist);
TEST_CASE(no_errors_more_files);
TEST_CASE(no_errors_less_files);
TEST_CASE(no_errors_equal_amount_files);
TEST_CASE(one_error_less_files);
TEST_CASE(one_error_several_files);
TEST_CASE(clangTidy);
TEST_CASE(showtime_top5_file);
TEST_CASE(showtime_top5_summary);
TEST_CASE(showtime_file);
TEST_CASE(showtime_summary);
TEST_CASE(showtime_file_total);
TEST_CASE(suppress_error_library);
TEST_CASE(unique_errors);
#endif // !WIN32
}
void deadlock_with_many_errors() {
std::ostringstream oss;
oss << "int main()\n"
<< "{\n";
const int num_err = 1;
for (int i = 0; i < num_err; i++) {
oss << " {int i = *((int*)0);}\n";
}
oss << " return 0;\n"
<< "}\n";
const int num_files = 3;
check(2, num_files, num_files, oss.str());
ASSERT_EQUALS(1LL * num_err * num_files, cppcheck::count_all_of(errout_str(), "(error) Null pointer dereference: (int*)0"));
}
void many_threads() {
const int num_files = 100;
check(16, num_files, num_files,
"int main()\n"
"{\n"
" int i = *((int*)0);\n"
" return 0;\n"
"}");
ASSERT_EQUALS(num_files, cppcheck::count_all_of(errout_str(), "(error) Null pointer dereference: (int*)0"));
}
// #11249 - reports TSAN errors
void many_threads_showtime() {
SUPPRESS;
check(16, 100, 100,
"int main()\n"
"{\n"
" int i = *((int*)0);\n"
" return 0;\n"
"}", dinit(CheckOptions, $.showtime = SHOWTIME_MODES::SHOWTIME_SUMMARY));
// we are not interested in the results - so just consume them
ignore_errout();
}
void many_threads_plist() {
const std::string plistOutput = "plist_" + fprefix() + "/";
ScopedFile plistFile("dummy", "", plistOutput);
check(16, 100, 100,
"int main()\n"
"{\n"
" int i = *((int*)0);\n"
" return 0;\n"
"}", dinit(CheckOptions, $.plistOutput = plistOutput.c_str()));
// we are not interested in the results - so just consume them
ignore_errout();
}
void no_errors_more_files() {
check(2, 3, 0,
"int main()\n"
"{\n"
" return 0;\n"
"}");
}
void no_errors_less_files() {
check(2, 1, 0,
"int main()\n"
"{\n"
" return 0;\n"
"}");
}
void no_errors_equal_amount_files() {
check(2, 2, 0,
"int main()\n"
"{\n"
" return 0;\n"
"}");
}
void one_error_less_files() {
check(2, 1, 1,
"int main()\n"
"{\n"
" {int i = *((int*)0);}\n"
" return 0;\n"
"}");
ASSERT_EQUALS("[" + fprefix() + "_1.cpp:3]: (error) Null pointer dereference: (int*)0\n", errout_str());
}
void one_error_several_files() {
const int num_files = 20;
check(2, num_files, num_files,
"int main()\n"
"{\n"
" {int i = *((int*)0);}\n"
" return 0;\n"
"}");
ASSERT_EQUALS(num_files, cppcheck::count_all_of(errout_str(), "(error) Null pointer dereference: (int*)0"));
}
void clangTidy() {
// TODO: we currently only invoke it with ImportProject::FileSettings
if (!useFS)
return;
#ifdef _WIN32
constexpr char exe[] = "clang-tidy.exe";
#else
constexpr char exe[] = "clang-tidy";
#endif
(void)exe;
const std::string file = fprefix() + "_1.cpp";
// TODO: the invocation cannot be checked as the code is called in the forked process
check(2, 1, 0,
"int main()\n"
"{\n"
" return 0;\n"
"}",
dinit(CheckOptions,
$.quiet = false,
$.clangTidy = true /*,
$.executeCommandCalled = true,
$.exe = exe,
$.args = {"-quiet", "-checks=*,-clang-analyzer-*,-llvm*", file, "--"}*/));
ASSERT_EQUALS("Checking " + file + " ...\n", output_str());
}
// TODO: provide data which actually shows values above 0
// TODO: should this be logged only once like summary?
void showtime_top5_file() {
REDIRECT; // should not cause TSAN failures as the showtime logging is synchronized
check(2, 2, 0,
"int main() {}",
dinit(CheckOptions,
$.showtime = SHOWTIME_MODES::SHOWTIME_TOP5_FILE));
// for each file: top5 results + overall + empty line
const std::string output_s = GET_REDIRECT_OUTPUT;
// for each file: top5 results + overall + empty line
TODO_ASSERT_EQUALS(static_cast<long long>(5 + 1 + 1) * 2, 0, cppcheck::count_all_of(output_s, '\n'));
}
void showtime_top5_summary() {
REDIRECT;
check(2, 2, 0,
"int main() {}",
dinit(CheckOptions,
$.showtime = SHOWTIME_MODES::SHOWTIME_TOP5_SUMMARY));
const std::string output_s = GET_REDIRECT_OUTPUT;
// once: top5 results + overall + empty line
TODO_ASSERT_EQUALS(5 + 1 + 1, 2, cppcheck::count_all_of(output_s, '\n'));
// should only report the top5 once
ASSERT(output_s.find("1 result(s)") == std::string::npos);
TODO_ASSERT(output_s.find("2 result(s)") != std::string::npos);
}
void showtime_file() {
REDIRECT; // should not cause TSAN failures as the showtime logging is synchronized
check(2, 2, 0,
"int main() {}",
dinit(CheckOptions,
$.showtime = SHOWTIME_MODES::SHOWTIME_FILE));
const std::string output_s = GET_REDIRECT_OUTPUT;
TODO_ASSERT_EQUALS(2, 0, cppcheck::count_all_of(output_s, "Overall time:"));
}
void showtime_summary() {
REDIRECT; // should not cause TSAN failures as the showtime logging is synchronized
check(2, 2, 0,
"int main() {}",
dinit(CheckOptions,
$.showtime = SHOWTIME_MODES::SHOWTIME_SUMMARY));
const std::string output_s = GET_REDIRECT_OUTPUT;
// should only report the actual summary once
ASSERT(output_s.find("1 result(s)") == std::string::npos);
TODO_ASSERT(output_s.find("2 result(s)") != std::string::npos);
}
void showtime_file_total() {
REDIRECT; // should not cause TSAN failures as the showtime logging is synchronized
check(2, 2, 0,
"int main() {}",
dinit(CheckOptions,
$.showtime = SHOWTIME_MODES::SHOWTIME_FILE_TOTAL));
const std::string output_s = GET_REDIRECT_OUTPUT;
TODO_ASSERT(output_s.find("Check time: " + fprefix() + "_1.cpp: ") != std::string::npos);
TODO_ASSERT(output_s.find("Check time: " + fprefix() + "_2.cpp: ") != std::string::npos);
}
void suppress_error_library() {
SUPPRESS;
const Settings settingsOld = settings;
const char xmldata[] = R"(<def format="2"><markup ext=".cpp" reporterrors="false"/></def>)";
settings = settingsBuilder().libraryxml(xmldata, sizeof(xmldata)).build();
check(2, 1, 0,
"int main()\n"
"{\n"
" int i = *((int*)0);\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
settings = settingsOld;
}
void unique_errors() {
SUPPRESS;
ScopedFile inc_h(fprefix() + ".h",
"inline void f()\n"
"{\n"
" (void)*((int*)0);\n"
"}");
check(2, 2, 2,
"#include \"" + inc_h.name() +"\"");
// this is made unique by the executor
ASSERT_EQUALS("[" + inc_h.name() + ":3]: (error) Null pointer dereference: (int*)0\n", errout_str());
}
// TODO: test whole program analysis
};
class TestProcessExecutorFiles : public TestProcessExecutorBase {
public:
TestProcessExecutorFiles() : TestProcessExecutorBase("TestProcessExecutorFiles", false) {}
};
class TestProcessExecutorFS : public TestProcessExecutorBase {
public:
TestProcessExecutorFS() : TestProcessExecutorBase("TestProcessExecutorFS", true) {}
};
REGISTER_TEST(TestProcessExecutorFiles)
REGISTER_TEST(TestProcessExecutorFS)
| null |
964 | cpp | cppcheck | helpers.cpp | test/helpers.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "helpers.h"
#include "filelister.h"
#include "filesettings.h"
#include "library.h"
#include "path.h"
#include "pathmatch.h"
#include "preprocessor.h"
#include <cerrno>
#include <cstdio>
#include <iostream>
#include <fstream>
#include <list>
#include <map>
#include <stdexcept>
#include <utility>
#include <vector>
#ifdef _WIN32
#include <windows.h>
#else
#include <sys/stat.h>
#include <unistd.h>
#endif
#include <simplecpp.h>
#include "xml.h"
class SuppressionList;
const Settings SimpleTokenizer::s_settings;
// TODO: better path-only usage
ScopedFile::ScopedFile(std::string name, const std::string &content, std::string path)
: mName(std::move(name))
, mPath(Path::toNativeSeparators(std::move(path)))
, mFullPath(Path::join(mPath, mName))
{
if (!mPath.empty() && mPath != Path::getCurrentPath()) {
if (Path::isDirectory(mPath))
throw std::runtime_error("ScopedFile(" + mFullPath + ") - directory already exists");
#ifdef _WIN32
if (!CreateDirectoryA(mPath.c_str(), nullptr))
throw std::runtime_error("ScopedFile(" + mFullPath + ") - could not create directory");
#else
if (mkdir(mPath.c_str(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) != 0)
throw std::runtime_error("ScopedFile(" + mFullPath + ") - could not create directory");
#endif
}
if (Path::isFile(mFullPath))
throw std::runtime_error("ScopedFile(" + mFullPath + ") - file already exists");
std::ofstream of(mFullPath);
if (!of.is_open())
throw std::runtime_error("ScopedFile(" + mFullPath + ") - could not open file");
of << content;
}
ScopedFile::~ScopedFile() {
const int remove_res = std::remove(mFullPath.c_str());
if (remove_res != 0) {
std::cout << "ScopedFile(" << mFullPath + ") - could not delete file (" << remove_res << ")" << std::endl;
}
if (!mPath.empty() && mPath != Path::getCurrentPath()) {
// TODO: remove all files
// TODO: simplify the function call
// hack to be able to delete *.plist output files
std::list<FileWithDetails> files;
const std::string res = FileLister::addFiles(files, mPath, {".plist"}, false, PathMatch({}));
if (!res.empty()) {
std::cout << "ScopedFile(" << mPath + ") - generating file list failed (" << res << ")" << std::endl;
}
for (const auto &f : files)
{
const std::string &file = f.path();
const int rm_f_res = std::remove(file.c_str());
if (rm_f_res != 0) {
std::cout << "ScopedFile(" << mPath + ") - could not delete '" << file << "' (" << rm_f_res << ")" << std::endl;
}
}
#ifdef _WIN32
if (!RemoveDirectoryA(mPath.c_str())) {
std::cout << "ScopedFile(" << mFullPath + ") - could not delete folder (" << GetLastError() << ")" << std::endl;
}
#else
const int rmdir_res = rmdir(mPath.c_str());
if (rmdir_res == -1) {
const int err = errno;
std::cout << "ScopedFile(" << mFullPath + ") - could not delete folder (" << err << ")" << std::endl;
}
#endif
}
}
// TODO: we should be using the actual Preprocessor implementation
std::string PreprocessorHelper::getcode(const Settings& settings, ErrorLogger& errorlogger, const std::string &filedata, const std::string &cfg, const std::string &filename, SuppressionList *inlineSuppression)
{
std::map<std::string, std::string> cfgcode = getcode(settings, errorlogger, filedata.c_str(), std::set<std::string>{cfg}, filename, inlineSuppression);
const auto it = cfgcode.find(cfg);
if (it == cfgcode.end())
return "";
return it->second;
}
std::map<std::string, std::string> PreprocessorHelper::getcode(const Settings& settings, ErrorLogger& errorlogger, const char code[], const std::string &filename, SuppressionList *inlineSuppression)
{
return getcode(settings, errorlogger, code, {}, filename, inlineSuppression);
}
std::map<std::string, std::string> PreprocessorHelper::getcode(const Settings& settings, ErrorLogger& errorlogger, const char code[], std::set<std::string> cfgs, const std::string &filename, SuppressionList *inlineSuppression)
{
simplecpp::OutputList outputList;
std::vector<std::string> files;
std::istringstream istr(code);
simplecpp::TokenList tokens(istr, files, Path::simplifyPath(filename), &outputList);
Preprocessor preprocessor(settings, errorlogger);
if (inlineSuppression)
preprocessor.inlineSuppressions(tokens, *inlineSuppression);
preprocessor.removeComments(tokens);
preprocessor.simplifyPragmaAsm(tokens);
preprocessor.reportOutput(outputList, true);
if (Preprocessor::hasErrors(outputList))
return {};
std::map<std::string, std::string> cfgcode;
if (cfgs.empty())
cfgs = preprocessor.getConfigs(tokens);
for (const std::string & config : cfgs) {
try {
// TODO: also preserve location information when #include exists - enabling that will fail since #line is treated like a regular token
cfgcode[config] = preprocessor.getcode(tokens, config, files, std::string(code).find("#file") != std::string::npos);
} catch (const simplecpp::Output &) {
cfgcode[config] = "";
}
}
return cfgcode;
}
void PreprocessorHelper::preprocess(const char code[], std::vector<std::string> &files, Tokenizer& tokenizer, ErrorLogger& errorlogger)
{
// TODO: make sure the given Tokenizer has not been used yet
// TODO: get rid of stream
std::istringstream istr(code);
const simplecpp::TokenList tokens1(istr, files, files[0]);
Preprocessor preprocessor(tokenizer.getSettings(), errorlogger);
simplecpp::TokenList tokens2 = preprocessor.preprocess(tokens1, "", files, true);
// Tokenizer..
tokenizer.list.createTokens(std::move(tokens2));
std::list<Directive> directives = preprocessor.createDirectives(tokens1);
tokenizer.setDirectives(std::move(directives));
}
// TODO: get rid of this
void PreprocessorHelper::preprocess(const char code[], std::vector<std::string> &files, Tokenizer& tokenizer, ErrorLogger& errorlogger, const simplecpp::DUI& dui)
{
// TODO: make sure the given Tokenizer has not been used yet
std::istringstream istr(code);
const simplecpp::TokenList tokens1(istr, files, files[0]);
// Preprocess..
simplecpp::TokenList tokens2(files);
std::map<std::string, simplecpp::TokenList*> filedata;
// TODO: provide and handle outputList
simplecpp::preprocess(tokens2, tokens1, files, filedata, dui);
// Tokenizer..
tokenizer.list.createTokens(std::move(tokens2));
const Preprocessor preprocessor(tokenizer.getSettings(), errorlogger);
std::list<Directive> directives = preprocessor.createDirectives(tokens1);
tokenizer.setDirectives(std::move(directives));
}
std::vector<RemarkComment> PreprocessorHelper::getRemarkComments(const char code[], ErrorLogger& errorLogger)
{
std::vector<std::string> files{"test.cpp"};
std::istringstream istr(code);
const simplecpp::TokenList tokens1(istr, files, files[0]);
const Settings settings;
const Preprocessor preprocessor(settings, errorLogger);
return preprocessor.getRemarkComments(tokens1);
}
bool LibraryHelper::loadxmldata(Library &lib, const char xmldata[], std::size_t len)
{
tinyxml2::XMLDocument doc;
return (tinyxml2::XML_SUCCESS == doc.Parse(xmldata, len)) && (lib.load(doc).errorcode == Library::ErrorCode::OK);
}
bool LibraryHelper::loadxmldata(Library &lib, Library::Error& liberr, const char xmldata[], std::size_t len)
{
tinyxml2::XMLDocument doc;
if (tinyxml2::XML_SUCCESS != doc.Parse(xmldata, len))
return false;
liberr = lib.load(doc);
return true;
}
Library::Error LibraryHelper::loadxmldoc(Library &lib, const tinyxml2::XMLDocument& doc)
{
return lib.load(doc);
}
| null |
965 | cpp | cppcheck | testoptions.cpp | test/testoptions.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "options.h"
#include "fixture.h"
#include <functional>
#include <set>
#include <string>
class TestOptions : public TestFixture {
public:
TestOptions()
: TestFixture("TestOptions") {}
private:
void run() override {
TEST_CASE(which_test);
TEST_CASE(which_test_method);
TEST_CASE(no_test_method);
TEST_CASE(not_quiet);
TEST_CASE(quiet);
TEST_CASE(not_help);
TEST_CASE(help);
TEST_CASE(help_long);
TEST_CASE(multiple_testcases);
TEST_CASE(multiple_testcases_ignore_duplicates);
TEST_CASE(invalid_switches);
TEST_CASE(summary);
TEST_CASE(dry_run);
}
void which_test() const {
const char* argv[] = {"./test_runner", "TestClass"};
options args(sizeof argv / sizeof argv[0], argv);
ASSERT(std::set<std::string> {"TestClass"} == args.which_test());
}
void which_test_method() const {
const char* argv[] = {"./test_runner", "TestClass::TestMethod"};
options args(sizeof argv / sizeof argv[0], argv);
ASSERT(std::set<std::string> {"TestClass::TestMethod"} == args.which_test());
}
void no_test_method() const {
const char* argv[] = {"./test_runner"};
options args(sizeof argv / sizeof argv[0], argv);
ASSERT(std::set<std::string> {""} == args.which_test());
}
void not_quiet() const {
const char* argv[] = {"./test_runner", "TestClass::TestMethod", "-v"};
options args(sizeof argv / sizeof argv[0], argv);
ASSERT_EQUALS(false, args.quiet());
}
void quiet() const {
const char* argv[] = {"./test_runner", "TestClass::TestMethod", "-q"};
options args(sizeof argv / sizeof argv[0], argv);
ASSERT_EQUALS(true, args.quiet());
}
void not_help() const {
const char* argv[] = {"./test_runner", "TestClass::TestMethod", "-v"};
options args(sizeof argv / sizeof argv[0], argv);
ASSERT_EQUALS(false, args.help());
}
void help() const {
const char* argv[] = {"./test_runner", "TestClass::TestMethod", "-h"};
options args(sizeof argv / sizeof argv[0], argv);
ASSERT_EQUALS(true, args.help());
}
void help_long() const {
const char* argv[] = {"./test_runner", "TestClass::TestMethod", "--help"};
options args(sizeof argv / sizeof argv[0], argv);
ASSERT_EQUALS(true, args.help());
}
void multiple_testcases() const {
const char* argv[] = {"./test_runner", "TestClass::TestMethod", "TestClass::AnotherTestMethod"};
options args(sizeof argv / sizeof argv[0], argv);
std::set<std::string> expected {"TestClass::TestMethod", "TestClass::AnotherTestMethod"};
ASSERT(expected == args.which_test());
}
void multiple_testcases_ignore_duplicates() const {
const char* argv[] = {"./test_runner", "TestClass::TestMethod", "TestClass"};
options args(sizeof argv / sizeof argv[0], argv);
std::set<std::string> expected {"TestClass"};
ASSERT(expected == args.which_test());
}
void invalid_switches() const {
const char* argv[] = {"./test_runner", "TestClass::TestMethod", "-a", "-v", "-q"};
options args(sizeof argv / sizeof argv[0], argv);
std::set<std::string> expected {"TestClass::TestMethod"};
ASSERT(expected == args.which_test());
ASSERT_EQUALS(true, args.quiet());
}
void summary() const {
const char* argv[] = {"./test_runner", "TestClass::TestMethod", "-n"};
options args(sizeof argv / sizeof argv[0], argv);
ASSERT_EQUALS(false, args.summary());
}
void dry_run() const {
const char* argv[] = {"./test_runner", "TestClass::TestMethod", "-d"};
options args(sizeof argv / sizeof argv[0], argv);
ASSERT_EQUALS(true, args.dry_run());
}
};
REGISTER_TEST(TestOptions)
| null |
966 | cpp | cppcheck | testpath.cpp | test/testpath.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "path.h"
#include "fixture.h"
#include "helpers.h"
#include "standards.h"
#include <list>
#include <set>
#include <string>
#include <vector>
class TestPath : public TestFixture {
public:
TestPath() : TestFixture("TestPath") {}
private:
void run() override {
TEST_CASE(removeQuotationMarks);
TEST_CASE(acceptFile);
TEST_CASE(getCurrentPath);
TEST_CASE(getCurrentExecutablePath);
TEST_CASE(isAbsolute);
TEST_CASE(getRelative);
TEST_CASE(get_path_from_filename);
TEST_CASE(join);
TEST_CASE(isDirectory);
TEST_CASE(isFile);
TEST_CASE(sameFileName);
TEST_CASE(getFilenameExtension);
TEST_CASE(identify);
TEST_CASE(identifyWithCppProbe);
TEST_CASE(is_header);
TEST_CASE(simplifyPath);
TEST_CASE(getAbsolutePath);
TEST_CASE(exists);
}
void removeQuotationMarks() const {
// Path::removeQuotationMarks()
ASSERT_EQUALS("index.cpp", Path::removeQuotationMarks("index.cpp"));
ASSERT_EQUALS("index.cpp", Path::removeQuotationMarks("\"index.cpp"));
ASSERT_EQUALS("index.cpp", Path::removeQuotationMarks("index.cpp\""));
ASSERT_EQUALS("index.cpp", Path::removeQuotationMarks("\"index.cpp\""));
ASSERT_EQUALS("path to/index.cpp", Path::removeQuotationMarks("\"path to\"/index.cpp"));
ASSERT_EQUALS("path to/index.cpp", Path::removeQuotationMarks("\"path to/index.cpp\""));
ASSERT_EQUALS("the/path to/index.cpp", Path::removeQuotationMarks("the/\"path to\"/index.cpp"));
ASSERT_EQUALS("the/path to/index.cpp", Path::removeQuotationMarks("\"the/path to/index.cpp\""));
}
void acceptFile() const {
ASSERT(Path::acceptFile("index.c"));
ASSERT(Path::acceptFile("index.cpp"));
ASSERT(Path::acceptFile("index.invalid.cpp"));
ASSERT(Path::acceptFile("index.invalid.Cpp"));
ASSERT(Path::acceptFile("index.invalid.C"));
ASSERT(Path::acceptFile("index.invalid.C++"));
ASSERT(Path::acceptFile("index.")==false);
ASSERT(Path::acceptFile("index")==false);
ASSERT(Path::acceptFile("")==false);
ASSERT(Path::acceptFile("C")==false);
// don't accept any headers
ASSERT_EQUALS(false, Path::acceptFile("index.h"));
ASSERT_EQUALS(false, Path::acceptFile("index.hpp"));
const std::set<std::string> extra = { ".extra", ".header" };
ASSERT(Path::acceptFile("index.c", extra));
ASSERT(Path::acceptFile("index.cpp", extra));
ASSERT(Path::acceptFile("index.extra", extra));
ASSERT(Path::acceptFile("index.header", extra));
ASSERT(Path::acceptFile("index.h", extra)==false);
ASSERT(Path::acceptFile("index.hpp", extra)==false);
}
void getCurrentPath() const {
ASSERT_EQUALS(true, Path::isAbsolute(Path::getCurrentPath()));
}
void getCurrentExecutablePath() const {
ASSERT_EQUALS(false, Path::getCurrentExecutablePath("").empty());
}
void isAbsolute() const {
#ifdef _WIN32
ASSERT_EQUALS(true, Path::isAbsolute("C:\\foo\\bar"));
ASSERT_EQUALS(true, Path::isAbsolute("C:/foo/bar"));
ASSERT_EQUALS(true, Path::isAbsolute("\\\\foo\\bar"));
ASSERT_EQUALS(false, Path::isAbsolute("foo\\bar"));
ASSERT_EQUALS(false, Path::isAbsolute("foo/bar"));
ASSERT_EQUALS(false, Path::isAbsolute("foo.cpp"));
ASSERT_EQUALS(false, Path::isAbsolute("C:foo.cpp"));
ASSERT_EQUALS(false, Path::isAbsolute("C:foo\\bar.cpp"));
ASSERT_EQUALS(false, Path::isAbsolute("bar.cpp"));
TODO_ASSERT_EQUALS(true, false, Path::isAbsolute("\\"));
#else
ASSERT_EQUALS(true, Path::isAbsolute("/foo/bar"));
ASSERT_EQUALS(true, Path::isAbsolute("/"));
ASSERT_EQUALS(false, Path::isAbsolute("foo/bar"));
ASSERT_EQUALS(false, Path::isAbsolute("foo.cpp"));
#endif
}
void getRelative() const {
const std::vector<std::string> basePaths = {
"", // Don't crash with empty paths
"C:/foo",
"C:/bar/",
"C:/test.cpp"
};
ASSERT_EQUALS("x.c", Path::getRelativePath("C:/foo/x.c", basePaths));
ASSERT_EQUALS("y.c", Path::getRelativePath("C:/bar/y.c", basePaths));
ASSERT_EQUALS("foo/y.c", Path::getRelativePath("C:/bar/foo/y.c", basePaths));
ASSERT_EQUALS("C:/test.cpp", Path::getRelativePath("C:/test.cpp", basePaths));
ASSERT_EQUALS("C:/foobar/test.cpp", Path::getRelativePath("C:/foobar/test.cpp", basePaths));
}
void get_path_from_filename() const {
ASSERT_EQUALS("", Path::getPathFromFilename("index.h"));
ASSERT_EQUALS("/tmp/", Path::getPathFromFilename("/tmp/index.h"));
ASSERT_EQUALS("a/b/c/", Path::getPathFromFilename("a/b/c/index.h"));
ASSERT_EQUALS("a/b/c/", Path::getPathFromFilename("a/b/c/"));
}
void join() const {
ASSERT_EQUALS("a", Path::join("a", ""));
ASSERT_EQUALS("a", Path::join("", "a"));
ASSERT_EQUALS("a/b", Path::join("a", "b"));
ASSERT_EQUALS("a/b", Path::join("a/", "b"));
ASSERT_EQUALS("/b", Path::join("a", "/b"));
}
void isDirectory() const {
ScopedFile file("testpath.txt", "", "testpath");
ScopedFile file2("testpath2.txt", "");
ASSERT_EQUALS(false, Path::isDirectory("testpath.txt"));
ASSERT_EQUALS(true, Path::isDirectory("testpath"));
ASSERT_EQUALS(false, Path::isDirectory("testpath/testpath.txt"));
ASSERT_EQUALS(false, Path::isDirectory("testpath2.txt"));
}
void isFile() const {
ScopedFile file("testpath.txt", "", "testpath");
ScopedFile file2("testpath2.txt", "");
ASSERT_EQUALS(false, Path::isFile("testpath"));
ASSERT_EQUALS(false, Path::isFile("testpath.txt"));
ASSERT_EQUALS(true, Path::isFile("testpath/testpath.txt"));
ASSERT_EQUALS(true, Path::isFile("testpath2.txt"));
}
void sameFileName() const {
ASSERT(Path::sameFileName("test", "test"));
// case sensitivity cases
#if defined(_WIN32) || (defined(__APPLE__) && defined(__MACH__))
ASSERT(Path::sameFileName("test", "Test"));
ASSERT(Path::sameFileName("test", "TesT"));
ASSERT(Path::sameFileName("test.h", "test.H"));
ASSERT(Path::sameFileName("test.hh", "test.Hh"));
ASSERT(Path::sameFileName("test.hh", "test.hH"));
#else
ASSERT(!Path::sameFileName("test", "Test"));
ASSERT(!Path::sameFileName("test", "TesT"));
ASSERT(!Path::sameFileName("test.h", "test.H"));
ASSERT(!Path::sameFileName("test.hh", "test.Hh"));
ASSERT(!Path::sameFileName("test.hh", "test.hH"));
#endif
}
void getFilenameExtension() const {
ASSERT_EQUALS("", Path::getFilenameExtension("test"));
ASSERT_EQUALS("", Path::getFilenameExtension("Test"));
ASSERT_EQUALS(".h", Path::getFilenameExtension("test.h"));
ASSERT_EQUALS(".h", Path::getFilenameExtension("Test.h"));
ASSERT_EQUALS("", Path::getFilenameExtension("test", true));
ASSERT_EQUALS("", Path::getFilenameExtension("Test", true));
ASSERT_EQUALS(".h", Path::getFilenameExtension("test.h", true));
ASSERT_EQUALS(".h", Path::getFilenameExtension("Test.h", true));
// case sensitivity cases
#if defined(_WIN32) || (defined(__APPLE__) && defined(__MACH__))
ASSERT_EQUALS(".h", Path::getFilenameExtension("test.H"));
ASSERT_EQUALS(".hh", Path::getFilenameExtension("test.Hh"));
ASSERT_EQUALS(".hh", Path::getFilenameExtension("test.hH"));
ASSERT_EQUALS(".h", Path::getFilenameExtension("test.H", true));
ASSERT_EQUALS(".hh", Path::getFilenameExtension("test.Hh", true));
ASSERT_EQUALS(".hh", Path::getFilenameExtension("test.hH", true));
#else
ASSERT_EQUALS(".H", Path::getFilenameExtension("test.H"));
ASSERT_EQUALS(".Hh", Path::getFilenameExtension("test.Hh"));
ASSERT_EQUALS(".hH", Path::getFilenameExtension("test.hH"));
ASSERT_EQUALS(".h", Path::getFilenameExtension("test.H", true));
ASSERT_EQUALS(".hh", Path::getFilenameExtension("test.Hh", true));
ASSERT_EQUALS(".hh", Path::getFilenameExtension("test.hH", true));
#endif
}
void identify() const {
Standards::Language lang;
bool header;
ASSERT_EQUALS(Standards::Language::None, Path::identify("", false));
ASSERT_EQUALS(Standards::Language::None, Path::identify("c", false));
ASSERT_EQUALS(Standards::Language::None, Path::identify("cpp", false));
ASSERT_EQUALS(Standards::Language::None, Path::identify("h", false));
ASSERT_EQUALS(Standards::Language::None, Path::identify("hpp", false));
// TODO: what about files starting with a "."?
//ASSERT_EQUALS(Standards::Language::None, Path::identify(".c", false));
//ASSERT_EQUALS(Standards::Language::None, Path::identify(".cpp", false));
//ASSERT_EQUALS(Standards::Language::None, Path::identify(".h", false));
//ASSERT_EQUALS(Standards::Language::None, Path::identify(".hpp", false));
// C
ASSERT_EQUALS(Standards::Language::C, Path::identify("index.c", false));
ASSERT_EQUALS(Standards::Language::C, Path::identify("index.cl", false));
ASSERT_EQUALS(Standards::Language::C, Path::identify("C:\\foo\\index.c", false));
ASSERT_EQUALS(Standards::Language::C, Path::identify("/mnt/c/foo/index.c", false));
// In unix .C is considered C++
#ifdef _WIN32
ASSERT_EQUALS(Standards::Language::C, Path::identify("C:\\foo\\index.C", false));
#endif
lang = Path::identify("index.c", false, &header);
ASSERT_EQUALS(Standards::Language::C, lang);
ASSERT_EQUALS(false, header);
// C++
ASSERT_EQUALS(Standards::Language::CPP, Path::identify("index.cpp", false));
ASSERT_EQUALS(Standards::Language::CPP, Path::identify("index.cxx", false));
ASSERT_EQUALS(Standards::Language::CPP, Path::identify("index.cc", false));
ASSERT_EQUALS(Standards::Language::CPP, Path::identify("index.c++", false));
ASSERT_EQUALS(Standards::Language::CPP, Path::identify("index.tpp", false));
ASSERT_EQUALS(Standards::Language::CPP, Path::identify("index.txx", false));
ASSERT_EQUALS(Standards::Language::CPP, Path::identify("index.ipp", false));
ASSERT_EQUALS(Standards::Language::CPP, Path::identify("index.ixx", false));
ASSERT_EQUALS(Standards::Language::CPP, Path::identify("C:\\foo\\index.cpp", false));
ASSERT_EQUALS(Standards::Language::CPP, Path::identify("C:\\foo\\index.Cpp", false));
ASSERT_EQUALS(Standards::Language::CPP, Path::identify("/mnt/c/foo/index.cpp", false));
ASSERT_EQUALS(Standards::Language::CPP, Path::identify("/mnt/c/foo/index.Cpp", false));
// TODO: check for case-insenstive filesystem instead
// In unix .C is considered C++
#if !defined(_WIN32) && !(defined(__APPLE__) && defined(__MACH__))
ASSERT_EQUALS(Standards::Language::CPP, Path::identify("index.C", false));
#else
ASSERT_EQUALS(Standards::Language::C, Path::identify("index.C", false));
#endif
lang = Path::identify("index.cpp", false, &header);
ASSERT_EQUALS(Standards::Language::CPP, lang);
ASSERT_EQUALS(false, header);
// headers
lang = Path::identify("index.h", false, &header);
ASSERT_EQUALS(Standards::Language::C, lang);
ASSERT_EQUALS(true, header);
lang = Path::identify("index.hpp", false, &header);
ASSERT_EQUALS(Standards::Language::CPP, lang);
ASSERT_EQUALS(true, header);
lang = Path::identify("index.hxx", false, &header);
ASSERT_EQUALS(Standards::Language::CPP, lang);
ASSERT_EQUALS(true, header);
lang = Path::identify("index.h++", false, &header);
ASSERT_EQUALS(Standards::Language::CPP, lang);
ASSERT_EQUALS(true, header);
lang = Path::identify("index.hh", false, &header);
ASSERT_EQUALS(Standards::Language::CPP, lang);
ASSERT_EQUALS(true, header);
ASSERT_EQUALS(Standards::Language::None, Path::identify("index.header", false));
ASSERT_EQUALS(Standards::Language::None, Path::identify("index.htm", false));
ASSERT_EQUALS(Standards::Language::None, Path::identify("index.html", false));
}
#define identifyWithCppProbeInternal(...) identifyWithCppProbeInternal_(__FILE__, __LINE__, __VA_ARGS__)
void identifyWithCppProbeInternal_(const char* file, int line, const std::string& filename, const std::string& marker, Standards::Language std) const
{
const ScopedFile f(filename, marker);
ASSERT_EQUALS_LOC_MSG(std, Path::identify(f.path(), true), filename + "\n" + marker, file, line);
}
void identifyWithCppProbe() const
{
const std::list<std::string> markers_cpp = {
"// -*- C++ -*-",
"// -*-C++-*-",
"// -*- Mode: C++; -*-",
"// -*-Mode: C++;-*-",
"// -*- Mode:C++; -*-",
"// -*-Mode:C++;-*-",
"// -*- Mode: C++ -*-",
"// -*-Mode: C++-*-",
"// -*- Mode:C++ -*-",
"// -*-Mode:C++-*-",
"// -*- Mode: C++; c-basic-offset: 8 -*-",
"// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*-",
"// -*- c++ -*-",
"// -*- mode: c++; -*-",
"/* -*- C++ -*- */",
"/* -*- C++ -*-",
"//-*- C++ -*-",
" //-*- C++ -*-",
"\t//-*- C++ -*-",
"\t //-*- C++ -*-",
" \t//-*- C++ -*-",
"//-*- C++ -*- ",
"//-*- C++ -*- \n",
"// -----*- C++ -*-----",
"// comment-*- C++ -*-comment",
"// -*- C++ -*-\n",
"//-*- C++ -*-\r// comment",
"//-*- C++ -*-\n// comment",
"//-*- C++ -*-\r\n// comment",
"/* -*-C++-*- */",
"/*-*-C++-*-*/",
" /*-*-C++-*-*/",
};
for (const auto& f : { "cppprobe.h", "cppprobe" }) {
for (const auto& m : markers_cpp) {
identifyWithCppProbeInternal(f, m, Standards::Language::CPP);
}
}
const std::list<std::string> markers_c = {
"-*- C++ -*-", // needs to be in comment
"// -*- C++", // no end marker
"// -*- C++ --*-", // incorrect end marker
"// -*- C++/-*-", // unexpected character
"// comment\n// -*- C++ -*-", // not on the first line
"// comment\r// -*- C++ -*-", // not on the first line
"// comment\r\n// -*- C++ -*-", // not on the first line
"// -*- C -*-",
"// -*- Mode: C; -*-",
"// -*- f90 -*-",
"// -*- fortran -*-",
"// -*- c-basic-offset: 2 -*-",
"// -*- c-basic-offset:4; indent-tabs-mode:nil -*-",
"// ", // no marker
"// -*-", // incomplete marker
"/*", // no marker
"/**/", // no marker
"/*\n*/", // no marker
"/* */", // no marker
"/* \n*/", // no marker
"/* -*-", // incomplete marker
"/* \n-*-", // incomplete marker
"/* \n-*- C++ -*-", // not on the first line
"/* \n-*- C++ -*- */" // not on the first line
};
for (const auto& m : markers_c) {
identifyWithCppProbeInternal("cppprobe.h", m, Standards::Language::C);
}
for (const auto& m : markers_c) {
identifyWithCppProbeInternal("cppprobe", m, Standards::Language::None);
}
}
void is_header() const {
ASSERT(Path::isHeader("index.h"));
ASSERT(Path::isHeader("index.hpp"));
ASSERT(Path::isHeader("index.hxx"));
ASSERT(Path::isHeader("index.h++"));
ASSERT(Path::isHeader("index.hh"));
ASSERT(Path::isHeader("index.c")==false);
ASSERT(Path::isHeader("index.cpp")==false);
ASSERT(Path::isHeader("index.header")==false);
ASSERT(Path::isHeader("index.htm")==false);
ASSERT(Path::isHeader("index.html")==false);
}
void simplifyPath() const {
ASSERT_EQUALS("file.cpp", Path::simplifyPath("file.cpp"));
ASSERT_EQUALS("../file.cpp", Path::simplifyPath("../file.cpp"));
ASSERT_EQUALS("file.cpp", Path::simplifyPath("test/../file.cpp"));
ASSERT_EQUALS("../file.cpp", Path::simplifyPath("../test/../file.cpp"));
ASSERT_EQUALS("file.cpp", Path::simplifyPath("./file.cpp"));
ASSERT_EQUALS("../file.cpp", Path::simplifyPath("./../file.cpp"));
ASSERT_EQUALS("file.cpp", Path::simplifyPath("./test/../file.cpp"));
ASSERT_EQUALS("../file.cpp", Path::simplifyPath("./../test/../file.cpp"));
ASSERT_EQUALS("test/", Path::simplifyPath("test/"));
ASSERT_EQUALS("../test/", Path::simplifyPath("../test/"));
ASSERT_EQUALS("../", Path::simplifyPath("../test/.."));
ASSERT_EQUALS("../", Path::simplifyPath("../test/../"));
ASSERT_EQUALS("/home/file.cpp", Path::simplifyPath("/home/test/../file.cpp"));
ASSERT_EQUALS("/file.cpp", Path::simplifyPath("/home/../test/../file.cpp"));
ASSERT_EQUALS("C:/home/file.cpp", Path::simplifyPath("C:/home/test/../file.cpp"));
ASSERT_EQUALS("C:/file.cpp", Path::simplifyPath("C:/home/../test/../file.cpp"));
ASSERT_EQUALS("../file.cpp", Path::simplifyPath("..\\file.cpp"));
ASSERT_EQUALS("file.cpp", Path::simplifyPath("test\\..\\file.cpp"));
ASSERT_EQUALS("../file.cpp", Path::simplifyPath("..\\test\\..\\file.cpp"));
ASSERT_EQUALS("file.cpp", Path::simplifyPath(".\\file.cpp"));
ASSERT_EQUALS("../file.cpp", Path::simplifyPath(".\\..\\file.cpp"));
ASSERT_EQUALS("file.cpp", Path::simplifyPath(".\\test\\..\\file.cpp"));
ASSERT_EQUALS("../file.cpp", Path::simplifyPath(".\\..\\test\\..\\file.cpp"));
ASSERT_EQUALS("test/", Path::simplifyPath("test\\"));
ASSERT_EQUALS("../test/", Path::simplifyPath("..\\test\\"));
ASSERT_EQUALS("../", Path::simplifyPath("..\\test\\.."));
ASSERT_EQUALS("../", Path::simplifyPath("..\\test\\..\\"));
ASSERT_EQUALS("C:/home/file.cpp", Path::simplifyPath("C:\\home\\test\\..\\file.cpp"));
ASSERT_EQUALS("C:/file.cpp", Path::simplifyPath("C:\\home\\..\\test\\..\\file.cpp"));
ASSERT_EQUALS("//home/file.cpp", Path::simplifyPath("\\\\home\\test\\..\\file.cpp"));
ASSERT_EQUALS("//file.cpp", Path::simplifyPath("\\\\home\\..\\test\\..\\file.cpp"));
}
void getAbsolutePath() const {
const std::string cwd = Path::getCurrentPath();
ScopedFile file("testabspath.txt", "");
std::string expected = Path::toNativeSeparators(Path::join(cwd, "testabspath.txt"));
ASSERT_EQUALS(expected, Path::getAbsoluteFilePath("testabspath.txt"));
ASSERT_EQUALS(expected, Path::getAbsoluteFilePath("./testabspath.txt"));
ASSERT_EQUALS(expected, Path::getAbsoluteFilePath(".\\testabspath.txt"));
ASSERT_EQUALS(expected, Path::getAbsoluteFilePath("test/../testabspath.txt"));
ASSERT_EQUALS(expected, Path::getAbsoluteFilePath("test\\..\\testabspath.txt"));
ASSERT_EQUALS(expected, Path::getAbsoluteFilePath("./test/../testabspath.txt"));
ASSERT_EQUALS(expected, Path::getAbsoluteFilePath(".\\test\\../testabspath.txt"));
ASSERT_EQUALS(expected, Path::getAbsoluteFilePath(Path::join(cwd, "testabspath.txt")));
std::string cwd_up = Path::getPathFromFilename(cwd);
cwd_up.pop_back(); // remove trailing slash
ASSERT_EQUALS(cwd_up, Path::getAbsoluteFilePath(Path::join(cwd, "..")));
ASSERT_EQUALS(cwd_up, Path::getAbsoluteFilePath(Path::join(cwd, "../")));
ASSERT_EQUALS(cwd_up, Path::getAbsoluteFilePath(Path::join(cwd, "..\\")));
ASSERT_EQUALS(cwd_up, Path::getAbsoluteFilePath(Path::join(cwd, "./../")));
ASSERT_EQUALS(cwd_up, Path::getAbsoluteFilePath(Path::join(cwd, ".\\..\\")));
ASSERT_EQUALS(cwd, Path::getAbsoluteFilePath("."));
#ifndef _WIN32
TODO_ASSERT_EQUALS(cwd, "", Path::getAbsoluteFilePath("./"));
TODO_ASSERT_EQUALS(cwd, "", Path::getAbsoluteFilePath(".\\"));
#else
ASSERT_EQUALS(cwd, Path::getAbsoluteFilePath("./"));
ASSERT_EQUALS(cwd, Path::getAbsoluteFilePath(".\\"));
#endif
ASSERT_EQUALS("", Path::getAbsoluteFilePath(""));
#ifndef _WIN32
// the underlying realpath() call only returns something if the path actually exists
ASSERT_THROW_EQUALS_2(Path::getAbsoluteFilePath("testabspath2.txt"), std::runtime_error, "path 'testabspath2.txt' does not exist");
#else
ASSERT_EQUALS(Path::toNativeSeparators(Path::join(cwd, "testabspath2.txt")), Path::getAbsoluteFilePath("testabspath2.txt"));
#endif
#ifdef _WIN32
// determine an existing drive letter
std::string drive = Path::getCurrentPath().substr(0, 2);
ASSERT_EQUALS(drive + "", Path::getAbsoluteFilePath(drive + "\\"));
ASSERT_EQUALS(drive + "\\path", Path::getAbsoluteFilePath(drive + "\\path"));
ASSERT_EQUALS(drive + "\\path", Path::getAbsoluteFilePath(drive + "\\path\\"));
ASSERT_EQUALS(drive + "\\path\\files.txt", Path::getAbsoluteFilePath(drive + "\\path\\files.txt"));
ASSERT_EQUALS(drive + "", Path::getAbsoluteFilePath(drive + "//"));
ASSERT_EQUALS(drive + "\\path", Path::getAbsoluteFilePath(drive + "//path"));
ASSERT_EQUALS(drive + "\\path", Path::getAbsoluteFilePath(drive + "//path/"));
ASSERT_EQUALS(drive + "\\path\\files.txt", Path::getAbsoluteFilePath(drive + "//path/files.txt"));
ASSERT_EQUALS(drive + "\\path", Path::getAbsoluteFilePath(drive + "\\\\path"));
ASSERT_EQUALS(drive + "", Path::getAbsoluteFilePath(drive + "/"));
ASSERT_EQUALS(drive + "\\path", Path::getAbsoluteFilePath(drive + "/path"));
drive[0] = static_cast<char>(toupper(drive[0]));
ASSERT_EQUALS(drive + "\\path", Path::getAbsoluteFilePath(drive + "\\path"));
ASSERT_EQUALS(drive + "\\path", Path::getAbsoluteFilePath(drive + "/path"));
drive[0] = static_cast<char>(tolower(drive[0]));
ASSERT_EQUALS(drive + "\\path", Path::getAbsoluteFilePath(drive + "\\path"));
ASSERT_EQUALS(drive + "\\path", Path::getAbsoluteFilePath(drive + "/path"));
ASSERT_EQUALS("1:\\path\\files.txt", Path::getAbsoluteFilePath("1:\\path\\files.txt")); // treated as valid drive
ASSERT_EQUALS(
Path::toNativeSeparators(Path::join(Path::getCurrentPath(), "CC:\\path\\files.txt")),
Path::getAbsoluteFilePath("CC:\\path\\files.txt")); // treated as filename
ASSERT_EQUALS("1:\\path\\files.txt", Path::getAbsoluteFilePath("1:/path/files.txt")); // treated as valid drive
ASSERT_EQUALS(
Path::toNativeSeparators(Path::join(Path::getCurrentPath(), "CC:\\path\\files.txt")),
Path::getAbsoluteFilePath("CC:/path/files.txt")); // treated as filename
#endif
#ifndef _WIN32
ASSERT_THROW_EQUALS_2(Path::getAbsoluteFilePath("C:\\path\\files.txt"), std::runtime_error, "path 'C:\\path\\files.txt' does not exist");
#endif
// TODO: test UNC paths
// TODO: test with symlinks
}
void exists() const {
ScopedFile file("testpath.txt", "", "testpath");
ScopedFile file2("testpath2.txt", "");
ASSERT_EQUALS(true, Path::exists("testpath"));
ASSERT_EQUALS(true, Path::exists("testpath/testpath.txt"));
ASSERT_EQUALS(true, Path::exists("testpath2.txt"));
ASSERT_EQUALS(false, Path::exists("testpath2"));
ASSERT_EQUALS(false, Path::exists("testpath/testpath2.txt"));
ASSERT_EQUALS(false, Path::exists("testpath.txt"));
}
};
REGISTER_TEST(TestPath)
| null |
967 | cpp | cppcheck | testvaarg.cpp | test/testvaarg.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "checkvaarg.h"
#include "errortypes.h"
#include "fixture.h"
#include "helpers.h"
#include "settings.h"
#include <cstddef>
class TestVaarg : public TestFixture {
public:
TestVaarg() : TestFixture("TestVaarg") {}
private:
const Settings settings = settingsBuilder().severity(Severity::warning).build();
#define check(code) check_(code, __FILE__, __LINE__)
template<size_t size>
void check_(const char (&code)[size], const char* file, int line) {
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
// Check..
runChecks<CheckVaarg>(tokenizer, this);
}
void run() override {
TEST_CASE(wrongParameterTo_va_start);
TEST_CASE(referenceAs_va_start);
TEST_CASE(va_end_missing);
TEST_CASE(va_list_usedBeforeStarted);
TEST_CASE(va_start_subsequentCalls);
TEST_CASE(unknownFunctionScope);
}
void wrongParameterTo_va_start() {
check("void Format(char* szFormat, char* szBuffer, size_t nSize, ...) {\n"
" va_list arg_ptr;\n"
" va_start(arg_ptr, szFormat);\n"
" va_end(arg_ptr);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) 'szFormat' given to va_start() is not last named argument of the function. Did you intend to pass 'nSize'?\n", errout_str());
check("void Format(char* szFormat, char* szBuffer, size_t nSize, ...) {\n"
" va_list arg_ptr;\n"
" va_start(arg_ptr, szBuffer);\n"
" va_end(arg_ptr);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) 'szBuffer' given to va_start() is not last named argument of the function. Did you intend to pass 'nSize'?\n", errout_str());
check("void Format(char* szFormat, char* szBuffer, size_t nSize, ...) {\n"
" va_list arg_ptr;\n"
" va_start(arg_ptr, nSize);\n"
" va_end(arg_ptr);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int main(int argc, char *argv[]) {\n"
" long(^addthem)(const char *, ...) = ^long(const char *format, ...) {\n"
" va_list argp;\n"
" va_start(argp, format);\n"
" c = va_arg(argp, int);\n"
" };\n"
"}"); // Don't crash (#6032)
ASSERT_EQUALS("[test.cpp:6]: (error) va_list 'argp' was opened but not closed by va_end().\n", errout_str());
check("void Format(char* szFormat, char* szBuffer, size_t nSize, ...) {\n"
" va_list arg_ptr;\n"
" va_start(arg_ptr);\n"
" va_end(arg_ptr);\n"
"}"); // Don't crash if less than expected arguments are given.
ASSERT_EQUALS("", errout_str());
check("void assertf_fail(const char *assertion, const char *file, int line, const char *func, const char* msg, ...) {\n"
" struct A {\n"
" A(char* buf, int size) {}\n"
" void printf(const char * format, ...) {\n"
" va_list args;\n"
" va_start(args, format);\n"
" va_end(args);\n"
" }\n"
" };\n"
"}"); // Inner class (#6453)
ASSERT_EQUALS("", errout_str());
}
void referenceAs_va_start() {
check("void Format(char* szFormat, char (&szBuffer)[_Size], ...) {\n"
" va_list arg_ptr;\n"
" va_start(arg_ptr, szBuffer);\n"
" va_end(arg_ptr);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Using reference 'szBuffer' as parameter for va_start() results in undefined behaviour.\n", errout_str());
check("void Format(char* szFormat, char (*szBuffer)[_Size], ...) {\n"
" va_list arg_ptr;\n"
" va_start(arg_ptr, szBuffer);\n"
" va_end(arg_ptr);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void va_end_missing() {
check("void Format(char* szFormat, char (*szBuffer)[_Size], ...) {\n"
" va_list arg_ptr;\n"
" va_start(arg_ptr, szBuffer);\n"
" va_end(arg_ptr);\n"
"}");
ASSERT_EQUALS("", errout_str());
// #6186
check("void Format(char* szFormat, char (*szBuffer)[_Size], ...) {\n"
" va_list arg_ptr;\n"
" va_start(arg_ptr, szBuffer);\n"
" try {\n"
" throw sth;\n"
" } catch(...) {\n"
" va_end(arg_ptr);\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void Format(char* szFormat, char (*szBuffer)[_Size], ...) {\n"
" va_list arg_ptr;\n"
" va_start(arg_ptr, szBuffer);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) va_list 'arg_ptr' was opened but not closed by va_end().\n", errout_str());
check("void Format(char* szFormat, char (*szBuffer)[_Size], ...) {\n"
" va_list arg_ptr;\n"
" va_start(arg_ptr, szBuffer);\n"
" if(sth) return;\n"
" va_end(arg_ptr);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) va_list 'arg_ptr' was opened but not closed by va_end().\n", errout_str());
// #8124
check("void f(int n, ...)\n"
"{\n"
" va_list ap;\n"
" va_start(ap, n);\n"
" std::vector<std::string> v(n);\n"
" std::generate_n(v.begin(), n, [&ap]()\n"
" {\n"
" return va_arg(ap, const char*);\n"
" });\n"
" va_end(ap);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int n, ...)\n"
"{\n"
" va_list ap;\n"
" va_start(ap, n);\n"
" std::vector<std::string> v(n);\n"
" std::generate_n(v.begin(), n, [&ap]()\n"
" {\n"
" return va_arg(ap, const char*);\n"
" });\n"
"}");
ASSERT_EQUALS("[test.cpp:10]: (error) va_list 'ap' was opened but not closed by va_end().\n", errout_str());
}
void va_list_usedBeforeStarted() {
check("void Format(char* szFormat, char (*szBuffer)[_Size], ...) {\n"
" va_list arg_ptr;\n"
" return va_arg(arg_ptr, float);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) va_list 'arg_ptr' used before va_start() was called.\n", errout_str());
check("void Format(char* szFormat, char (*szBuffer)[_Size], ...) {\n"
" va_list arg_ptr;\n"
" foo(arg_ptr);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) va_list 'arg_ptr' used before va_start() was called.\n", errout_str());
check("void Format(char* szFormat, char (*szBuffer)[_Size], ...) {\n"
" va_list arg_ptr;\n"
" va_copy(f, arg_ptr);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) va_list 'arg_ptr' used before va_start() was called.\n", errout_str());
check("void Format(char* szFormat, char (*szBuffer)[_Size], ...) {\n"
" va_list arg_ptr;\n"
" va_start(arg_ptr, szBuffer);\n"
" va_end(arg_ptr);\n"
" return va_arg(arg_ptr, float);\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) va_list 'arg_ptr' used before va_start() was called.\n", errout_str());
check("void Format(char* szFormat, char (*szBuffer)[_Size], ...) {\n"
" va_list arg_ptr;\n"
" va_end(arg_ptr);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) va_list 'arg_ptr' used before va_start() was called.\n", errout_str());
check("void Format(char* szFormat, char (*szBuffer)[_Size], ...) {\n"
" va_list arg_ptr;\n"
" va_start(arg_ptr, szBuffer);\n"
" va_end(arg_ptr);\n"
" va_start(arg_ptr, szBuffer);\n"
" foo(va_arg(arg_ptr, float));\n"
" va_end(arg_ptr);\n"
"}");
ASSERT_EQUALS("", errout_str());
// #6066
check("void Format(va_list v1) {\n"
" va_list v2;\n"
" va_copy(v2, v1);\n"
" foo(va_arg(v1, float));\n"
" va_end(v2);\n"
"}");
ASSERT_EQUALS("", errout_str());
// #7527
check("void foo(int flag1, int flag2, ...) {\n"
" switch (flag1) {\n"
" default:\n"
" va_list vargs;\n"
" va_start(vargs, flag2);\n"
" if (flag2) {\n"
" va_end(vargs);\n"
" break;\n"
" }\n"
" int data = va_arg(vargs, int);\n"
" va_end(vargs);\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// #7533
check("void action_push(int type, ...) {\n"
" va_list args;\n"
" va_start(args, type);\n"
" switch (push_mode) {\n"
" case UNDO:\n"
" list_add(&act->node, &to_redo);\n"
" break;\n"
" case REDO:\n"
" list_add(&act->node, &to_undo);\n"
" break;\n"
" }\n"
" va_end(args);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void action_push(int type, ...) {\n"
" va_list args;\n"
" va_start(args, type);\n"
" switch (push_mode) {\n"
" case UNDO:\n"
" list_add(&act->node, &to_redo);\n"
" va_end(args);\n"
" break;\n"
" case REDO:\n"
" list_add(&act->node, &to_undo);\n"
" va_end(args);\n"
" break;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void action_push(int type, ...) {\n"
" va_list args;\n"
" va_start(args, type);\n"
" switch (push_mode) {\n"
" case UNDO:\n"
" list_add(&act->node, &to_redo);\n"
" break;\n"
" case REDO:\n"
" list_add(&act->node, &to_undo);\n"
" va_end(args);\n"
" break;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:13]: (error) va_list 'args' was opened but not closed by va_end().\n", errout_str());
// #8043
check("void redisvFormatCommand(char *format, va_list ap, bool flag) {\n"
" va_list _cpy;\n"
" va_copy(_cpy, ap);\n"
" if (flag)\n"
" goto fmt_valid;\n"
" va_end(_cpy);\n"
" goto format_err;\n"
"fmt_valid:\n"
" sdscatvprintf(curarg, _format, _cpy);\n"
" va_end(_cpy);\n"
"format_err:\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void va_start_subsequentCalls() {
check("void Format(char* szFormat, char (*szBuffer)[_Size], ...) {\n"
" va_list arg_ptr;\n"
" va_start(arg_ptr, szBuffer);\n"
" va_start(arg_ptr, szBuffer);\n"
" va_end(arg_ptr);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) va_start() or va_copy() called subsequently on 'arg_ptr' without va_end() in between.\n", errout_str());
check("void Format(char* szFormat, char (*szBuffer)[_Size], ...) {\n"
" va_list vl1;\n"
" va_start(vl1, szBuffer);\n"
" va_copy(vl1, vl1);\n"
" va_end(vl1);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) va_start() or va_copy() called subsequently on 'vl1' without va_end() in between.\n", errout_str());
check("void Format(char* szFormat, char (*szBuffer)[_Size], ...) {\n"
" va_list arg_ptr;\n"
" va_start(arg_ptr, szBuffer);\n"
" va_end(arg_ptr);\n"
" va_start(arg_ptr, szBuffer);\n"
" va_end(arg_ptr);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void unknownFunctionScope() {
check("void BG_TString::Format() {\n"
" BG_TChar * f;\n"
" va_start(args,f);\n"
" BG_TString result(f);\n"
"}");
ASSERT_EQUALS("", errout_str());
// #7559
check("void mowgli_object_message_broadcast(mowgli_object_t *self, const char *name, ...) {\n"
" va_list va;\n"
" MOWGLI_LIST_FOREACH(n, self->klass->message_handlers.head) {\n"
" if (!strcasecmp(sig2->name, name))\n"
" break;\n"
" }\n"
" va_start(va, name);\n"
" va_end(va);\n"
"}");
}
};
REGISTER_TEST(TestVaarg)
| null |
968 | cpp | cppcheck | testmemleak.cpp | test/testmemleak.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "checkmemoryleak.h"
#include "errortypes.h"
#include "fixture.h"
#include "helpers.h"
#include "settings.h"
#include "symboldatabase.h"
#include "token.h"
#include <cstddef>
#include <list>
class TestMemleak : public TestFixture {
public:
TestMemleak() : TestFixture("TestMemleak") {}
private:
const Settings settings;
void run() override {
TEST_CASE(testFunctionReturnType);
TEST_CASE(open);
}
#define functionReturnType(code) functionReturnType_(code, __FILE__, __LINE__)
template<size_t size>
CheckMemoryLeak::AllocType functionReturnType_(const char (&code)[size], const char* file, int line) {
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
const CheckMemoryLeak c(&tokenizer, this, &settings);
return (c.functionReturnType)(&tokenizer.getSymbolDatabase()->scopeList.front().functionList.front());
}
void testFunctionReturnType() {
{
const char code[] = "const char *foo()\n"
"{ return 0; }";
ASSERT_EQUALS(CheckMemoryLeak::No, functionReturnType(code));
}
{
const char code[] = "Fred *newFred()\n"
"{ return new Fred; }";
ASSERT_EQUALS(CheckMemoryLeak::New, functionReturnType(code));
}
{
const char code[] = "char *foo()\n"
"{ return new char[100]; }";
ASSERT_EQUALS(CheckMemoryLeak::NewArray, functionReturnType(code));
}
{
const char code[] = "char *foo()\n"
"{\n"
" char *p = new char[100];\n"
" return p;\n"
"}";
ASSERT_EQUALS(CheckMemoryLeak::NewArray, functionReturnType(code));
}
}
void open() {
const char code[] = "class A {\n"
" static int open() {\n"
" return 1;\n"
" }\n"
"\n"
" A() {\n"
" int ret = open();\n"
" }\n"
"};\n";
SimpleTokenizer tokenizer(settings, *this);
ASSERT(tokenizer.tokenize(code));
// there is no allocation
const Token *tok = Token::findsimplematch(tokenizer.tokens(), "ret =");
const CheckMemoryLeak check(&tokenizer, nullptr, &settings);
ASSERT_EQUALS(CheckMemoryLeak::No, check.getAllocationType(tok->tokAt(2), 1));
}
};
REGISTER_TEST(TestMemleak)
class TestMemleakInFunction : public TestFixture {
public:
TestMemleakInFunction() : TestFixture("TestMemleakInFunction") {}
private:
const Settings settings = settingsBuilder().library("std.cfg").library("posix.cfg").build();
#define check(...) check_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
void check_(const char* file, int line, const char (&code)[size]) {
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
// Check for memory leaks..
CheckMemoryLeakInFunction checkMemoryLeak(&tokenizer, &settings, this);
checkMemoryLeak.checkReallocUsage();
}
void run() override {
TEST_CASE(realloc1);
TEST_CASE(realloc2);
TEST_CASE(realloc3);
TEST_CASE(realloc4);
TEST_CASE(realloc5);
TEST_CASE(realloc7);
TEST_CASE(realloc8);
TEST_CASE(realloc9);
TEST_CASE(realloc10);
TEST_CASE(realloc11);
TEST_CASE(realloc12);
TEST_CASE(realloc13);
TEST_CASE(realloc14);
TEST_CASE(realloc15);
TEST_CASE(realloc16);
TEST_CASE(realloc17);
TEST_CASE(realloc18);
TEST_CASE(realloc19);
TEST_CASE(realloc20);
TEST_CASE(realloc21);
TEST_CASE(realloc22);
TEST_CASE(realloc23);
TEST_CASE(realloc24); // #9228
}
void realloc1() {
check("void foo()\n"
"{\n"
" char *a = (char *)malloc(10);\n"
" a = realloc(a, 100);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Common realloc mistake: \'a\' nulled but not freed upon failure\n", errout_str());
}
void realloc2() {
check("void foo()\n"
"{\n"
" char *a = (char *)malloc(10);\n"
" a = (char *)realloc(a, 100);\n"
" free(a);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Common realloc mistake: \'a\' nulled but not freed upon failure\n", errout_str());
}
void realloc3() {
check("void foo()\n"
"{\n"
" char *a = 0;\n"
" if ((a = realloc(a, 100)) == NULL)\n"
" return;\n"
" free(a);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void realloc4() {
check("void foo()\n"
"{\n"
" static char *a = 0;\n"
" if ((a = realloc(a, 100)) == NULL)\n"
" return;\n"
" free(a);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:5]: (error) Memory leak: a\n",
"[test.cpp:4]: (error) Common realloc mistake: \'a\' nulled but not freed upon failure\n",
errout_str());
}
void realloc5() {
check("void foo()\n"
"{\n"
" char *buf;\n"
" char *new_buf;\n"
" buf = calloc( 10 );\n"
" new_buf = realloc ( buf, 20);\n"
" if ( !new_buf )\n"
" free(buf);\n"
" else\n"
" free(new_buf);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void realloc7() {
check("bool foo(size_t nLen, char* pData)\n"
"{\n"
" pData = (char*) realloc(pData, sizeof(char) + (nLen + 1)*sizeof(char));\n"
" if ( pData == NULL )\n"
" {\n"
" return false;\n"
" }\n"
" free(pData);\n"
" return true;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void realloc8() {
check("void foo()\n"
"{\n"
" char *origBuf = m_buf;\n"
" m_buf = (char *) realloc (m_buf, m_capacity + growBy);\n"
" if (!m_buf) {\n"
" m_buf = origBuf;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void realloc9() {
check("void foo()\n"
"{\n"
" x = realloc(x,100);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void realloc10() {
check("void foo() {\n"
" char *pa, *pb;\n"
" pa = pb = malloc(10);\n"
" pa = realloc(pa, 20);"
" exit();\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void realloc11() {
check("void foo() {\n"
" char *p;\n"
" p = realloc(p, size);\n"
" if (!p)\n"
" error();\n"
" usep(p);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void realloc12() {
check("void foo(int x)\n"
"{\n"
" char *a = 0;\n"
" if ((a = realloc(a, x + 100)) == NULL)\n"
" return;\n"
" free(a);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void realloc13() {
check("void foo()\n"
"{\n"
" char **str;\n"
" *str = realloc(*str,100);\n"
" free (*str);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Common realloc mistake: \'str\' nulled but not freed upon failure\n", errout_str());
}
void realloc14() {
check("void foo() {\n"
" char *p;\n"
" p = realloc(p, size + 1);\n"
" if (!p)\n"
" error();\n"
" usep(p);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void realloc15() {
check("bool foo() {\n"
" char ** m_options;\n"
" m_options = (char**)realloc( m_options, 2 * sizeof(char*));\n"
" if( m_options == NULL )\n"
" return false;\n"
" return true;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Common realloc mistake: \'m_options\' nulled but not freed upon failure\n", errout_str());
}
void realloc16() {
check("void f(char *zLine) {\n"
" zLine = realloc(zLine, 42);\n"
" if (zLine) {\n"
" free(zLine);\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void realloc17() {
check("void foo()\n"
"{\n"
" void ***a = malloc(sizeof(a));\n"
" ***a = realloc(***(a), sizeof(a) * 2);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Common realloc mistake: \'a\' nulled but not freed upon failure\n", errout_str());
}
void realloc18() {
check("void foo()\n"
"{\n"
" void *a = malloc(sizeof(a));\n"
" a = realloc((void*)a, sizeof(a) * 2);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Common realloc mistake: \'a\' nulled but not freed upon failure\n", errout_str());
}
void realloc19() {
check("void foo()\n"
"{\n"
" void *a = malloc(sizeof(a));\n"
" a = (realloc((void*)((a)), sizeof(a) * 2));\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Common realloc mistake: \'a\' nulled but not freed upon failure\n", errout_str());
}
void realloc20() {
check("void foo()\n"
"{\n"
" void *a = malloc(sizeof(a));\n"
" a = realloc((a) + 1, sizeof(a) * 2);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void realloc21() {
check("char *foo(char *bs0)\n"
"{\n"
" char *bs = bs0;\n"
" bs = realloc(bs, 100);\n"
" if (bs == NULL) return bs0;\n"
" return bs;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void realloc22() {
check("void foo(char **bsp)\n"
"{\n"
" char *bs = *bsp;\n"
" bs = realloc(bs, 100);\n"
" if (bs == NULL) return;\n"
" *bsp = bs;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void realloc23() {
check("void foo(struct ABC *s)\n"
"{\n"
" uint32_t *cigar = s->cigar;\n"
" if (!(cigar = realloc(cigar, 100 * sizeof(*cigar))))\n"
" return;\n"
" s->cigar = cigar;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void realloc24() { // #9228
check("void f() {\n"
"void *a = NULL;\n"
"a = realloc(a, 20);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
"void *a = NULL;\n"
"a = malloc(10);\n"
"a = realloc(a, 20);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Common realloc mistake: \'a\' nulled but not freed upon failure\n", errout_str());
check("void f() {\n"
"void *a = nullptr;\n"
"a = malloc(10);\n"
"a = realloc(a, 20);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Common realloc mistake: \'a\' nulled but not freed upon failure\n", errout_str());
check("void f(char *b) {\n"
"void *a = NULL;\n"
"a = b;\n"
"a = realloc(a, 20);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
};
REGISTER_TEST(TestMemleakInFunction)
class TestMemleakInClass : public TestFixture {
public:
TestMemleakInClass() : TestFixture("TestMemleakInClass") {}
private:
const Settings settings = settingsBuilder().severity(Severity::warning).severity(Severity::style).library("std.cfg").build();
/**
* Tokenize and execute leak check for given code
* @param code Source code
*/
template<size_t size>
void check_(const char* file, int line, const char (&code)[size]) {
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
// Check for memory leaks..
CheckMemoryLeakInClass checkMemoryLeak(&tokenizer, &settings, this);
(checkMemoryLeak.check)();
}
void run() override {
TEST_CASE(class1);
TEST_CASE(class2);
TEST_CASE(class3);
TEST_CASE(class4);
TEST_CASE(class6);
TEST_CASE(class7);
TEST_CASE(class8);
TEST_CASE(class9);
TEST_CASE(class10);
TEST_CASE(class11);
TEST_CASE(class12);
TEST_CASE(class13);
TEST_CASE(class14);
TEST_CASE(class15);
TEST_CASE(class16);
TEST_CASE(class17);
TEST_CASE(class18);
TEST_CASE(class19); // ticket #2219
TEST_CASE(class20);
TEST_CASE(class21); // ticket #2517
TEST_CASE(class22); // ticket #3012
TEST_CASE(class23); // ticket #3303
TEST_CASE(class24); // ticket #3806 - false positive in copy constructor
TEST_CASE(class25); // ticket #4367 - false positive implementation for destructor is not seen
TEST_CASE(class26); // ticket #10789
TEST_CASE(class27); // ticket #8126
TEST_CASE(staticvar);
TEST_CASE(free_member_in_sub_func);
TEST_CASE(mismatch1);
TEST_CASE(mismatch2); // #5659
// allocating member variable in public function
TEST_CASE(func1);
TEST_CASE(func2);
}
void class1() {
check("class Fred\n"
"{\n"
"private:\n"
" char *str1;\n"
" char *str2;\n"
"public:\n"
" Fred();\n"
" ~Fred();\n"
"};\n"
"\n"
"Fred::Fred()\n"
"{\n"
" str1 = new char[10];\n"
" str2 = new char[10];\n"
"}\n"
"\n"
"Fred::~Fred()\n"
"{\n"
" delete [] str2;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Class 'Fred' is unsafe, 'Fred::str1' can leak by wrong usage.\n", errout_str());
check("class Fred\n"
"{\n"
"private:\n"
" char *str1;\n"
" char *str2;\n"
"public:\n"
" Fred()\n"
" {\n"
" str1 = new char[10];\n"
" str2 = new char[10];\n"
" }\n"
" ~Fred()\n"
" {\n"
" delete [] str2;\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (style) Class 'Fred' is unsafe, 'Fred::str1' can leak by wrong usage.\n", errout_str());
}
void class2() {
check("class Fred\n"
"{\n"
"private:\n"
" char *str1;\n"
"public:\n"
" Fred();\n"
" ~Fred();\n"
"};\n"
"\n"
"Fred::Fred()\n"
"{\n"
" str1 = new char[10];\n"
"}\n"
"\n"
"Fred::~Fred()\n"
"{\n"
" free(str1);\n"
"}");
ASSERT_EQUALS("[test.cpp:17]: (error) Mismatching allocation and deallocation: Fred::str1\n", errout_str());
check("class Fred\n"
"{\n"
"private:\n"
" char *str1;\n"
"public:\n"
" Fred()\n"
" {\n"
" str1 = new char[10];\n"
" }\n"
" ~Fred()\n"
" {\n"
" free(str1);\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:12]: (error) Mismatching allocation and deallocation: Fred::str1\n", errout_str());
}
void class3() {
check("class Token;\n"
"\n"
"class Tokenizer\n"
"{\n"
"private:\n"
" Token *_tokens;\n"
"\n"
"public:\n"
" Tokenizer();\n"
" ~Tokenizer();\n"
" void deleteTokens(Token *tok);\n"
"};\n"
"\n"
"Tokenizer::Tokenizer()\n"
"{\n"
" _tokens = new Token;\n"
"}\n"
"\n"
"Tokenizer::~Tokenizer()\n"
"{\n"
" deleteTokens(_tokens);\n"
"}\n"
"\n"
"void Tokenizer::deleteTokens(Token *tok)\n"
"{\n"
" while (tok)\n"
" {\n"
" Token *next = tok->next();\n"
" delete tok;\n"
" tok = next;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("class Token;\n"
"\n"
"class Tokenizer\n"
"{\n"
"private:\n"
" Token *_tokens;\n"
"\n"
"public:\n"
" Tokenizer()\n"
" {\n"
" _tokens = new Token;\n"
" }\n"
" ~Tokenizer()\n"
" {\n"
" deleteTokens(_tokens);\n"
" }\n"
" void deleteTokens(Token *tok)\n"
" {\n"
" while (tok)\n"
" {\n"
" Token *next = tok->next();\n"
" delete tok;\n"
" tok = next;\n"
" }\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void class4() {
check("struct ABC;\n"
"class Fred\n"
"{\n"
"private:\n"
" void addAbc(ABC *abc);\n"
"public:\n"
" void click();\n"
"};\n"
"\n"
"void Fred::addAbc(ABC* abc)\n"
"{\n"
" AbcPosts->Add(abc);\n"
"}\n"
"\n"
"void Fred::click()\n"
"{\n"
" ABC *p = new ABC;\n"
" addAbc( p );\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct ABC;\n"
"class Fred\n"
"{\n"
"private:\n"
" void addAbc(ABC* abc)\n"
" {\n"
" AbcPosts->Add(abc);\n"
" }\n"
"public:\n"
" void click()\n"
" {\n"
" ABC *p = new ABC;\n"
" addAbc( p );\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void class6() {
check("class Fred\n"
"{\n"
"public:\n"
" void foo();\n"
"};\n"
"\n"
"void Fred::foo()\n"
"{\n"
" char *str = new char[100];\n"
" delete [] str;\n"
" hello();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("class Fred\n"
"{\n"
"public:\n"
" void foo()\n"
" {\n"
" char *str = new char[100];\n"
" delete [] str;\n"
" hello();\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void class7() {
check("class Fred\n"
"{\n"
"public:\n"
" int *i;\n"
" Fred();\n"
" ~Fred();\n"
"};\n"
"\n"
"Fred::Fred()\n"
"{\n"
" this->i = new int;\n"
"}\n"
"Fred::~Fred()\n"
"{\n"
" delete this->i;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("class Fred\n"
"{\n"
"public:\n"
" int *i;\n"
" Fred()\n"
" {\n"
" this->i = new int;\n"
" }\n"
" ~Fred()\n"
" {\n"
" delete this->i;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void class8() {
check("class A\n"
"{\n"
"public:\n"
" void a();\n"
" void doNothing() { }\n"
"};\n"
"\n"
"void A::a()\n"
"{\n"
" int* c = new int(1);\n"
" delete c;\n"
" doNothing(c);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("class A\n"
"{\n"
"public:\n"
" void a()\n"
" {\n"
" int* c = new int(1);\n"
" delete c;\n"
" doNothing(c);\n"
" }\n"
" void doNothing() { }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void class9() {
check("class A\n"
"{\n"
"public:\n"
" int * p;\n"
" A();\n"
" ~A();\n"
"};\n"
"\n"
"A::A()\n"
"{ p = new int; }\n"
"\n"
"A::~A()\n"
"{ delete (p); }");
ASSERT_EQUALS("", errout_str());
check("class A\n"
"{\n"
"public:\n"
" int * p;\n"
" A()\n"
" { p = new int; }\n"
" ~A()\n"
" { delete (p); }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void class10() {
check("class A\n"
"{\n"
"public:\n"
" int * p;\n"
" A();\n"
"};\n"
"A::A()\n"
"{ p = new int; }");
ASSERT_EQUALS("[test.cpp:4]: (style) Class 'A' is unsafe, 'A::p' can leak by wrong usage.\n", errout_str());
check("class A\n"
"{\n"
"public:\n"
" int * p;\n"
" A() { p = new int; }\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (style) Class 'A' is unsafe, 'A::p' can leak by wrong usage.\n", errout_str());
}
void class11() {
check("class A\n"
"{\n"
"public:\n"
" int * p;\n"
" A() : p(new int[10])\n"
" { }"
"};");
ASSERT_EQUALS("[test.cpp:4]: (style) Class 'A' is unsafe, 'A::p' can leak by wrong usage.\n", errout_str());
check("class A\n"
"{\n"
"public:\n"
" int * p;\n"
" A();\n"
"};\n"
"A::A() : p(new int[10])\n"
"{ }");
ASSERT_EQUALS("[test.cpp:4]: (style) Class 'A' is unsafe, 'A::p' can leak by wrong usage.\n", errout_str());
}
void class12() {
check("class A\n"
"{\n"
"private:\n"
" int *p;\n"
"public:\n"
" A();\n"
" ~A();\n"
" void cleanup();"
"};\n"
"\n"
"A::A()\n"
"{ p = new int[10]; }\n"
"\n"
"A::~A()\n"
"{ }\n"
"\n"
"void A::cleanup()\n"
"{ delete [] p; }");
ASSERT_EQUALS("[test.cpp:4]: (style) Class 'A' is unsafe, 'A::p' can leak by wrong usage.\n", errout_str());
check("class A\n"
"{\n"
"private:\n"
" int *p;\n"
"public:\n"
" A()\n"
" { p = new int[10]; }\n"
" ~A()\n"
" { }\n"
" void cleanup()\n"
" { delete [] p; }\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (style) Class 'A' is unsafe, 'A::p' can leak by wrong usage.\n", errout_str());
}
void class13() {
check("class A\n"
"{\n"
"private:\n"
" int *p;\n"
"public:\n"
" A();\n"
" ~A();\n"
" void foo();"
"};\n"
"\n"
"A::A()\n"
"{ }\n"
"\n"
"A::~A()\n"
"{ }\n"
"\n"
"void A::foo()\n"
"{ p = new int[10]; delete [] p; }");
ASSERT_EQUALS("[test.cpp:17]: (warning) Possible leak in public function. The pointer 'p' is not deallocated before it is allocated.\n", errout_str());
check("class A\n"
"{\n"
"private:\n"
" int *p;\n"
"public:\n"
" A()\n"
" { }\n"
" ~A()\n"
" { }\n"
" void foo()\n"
" { p = new int[10]; delete [] p; }\n"
"};");
ASSERT_EQUALS("[test.cpp:11]: (warning) Possible leak in public function. The pointer 'p' is not deallocated before it is allocated.\n", errout_str());
}
void class14() {
check("class A\n"
"{\n"
" int *p;\n"
"public:\n"
" void init();\n"
"};\n"
"\n"
"void A::init()\n"
"{ p = new int[10]; }");
ASSERT_EQUALS("[test.cpp:9]: (warning) Possible leak in public function. The pointer 'p' is not deallocated before it is allocated.\n"
"[test.cpp:3]: (style) Class 'A' is unsafe, 'A::p' can leak by wrong usage.\n", errout_str());
check("class A\n"
"{\n"
" int *p;\n"
"public:\n"
" void init()\n"
" { p = new int[10]; }\n"
"};");
ASSERT_EQUALS("[test.cpp:6]: (warning) Possible leak in public function. The pointer 'p' is not deallocated before it is allocated.\n"
"[test.cpp:3]: (style) Class 'A' is unsafe, 'A::p' can leak by wrong usage.\n", errout_str());
check("class A\n"
"{\n"
" int *p;\n"
"public:\n"
" void init();\n"
"};\n"
"\n"
"void A::init()\n"
"{ p = new int; }");
ASSERT_EQUALS("[test.cpp:9]: (warning) Possible leak in public function. The pointer 'p' is not deallocated before it is allocated.\n"
"[test.cpp:3]: (style) Class 'A' is unsafe, 'A::p' can leak by wrong usage.\n", errout_str());
check("class A\n"
"{\n"
" int *p;\n"
"public:\n"
" void init()\n"
" { p = new int; }\n"
"};");
ASSERT_EQUALS("[test.cpp:6]: (warning) Possible leak in public function. The pointer 'p' is not deallocated before it is allocated.\n"
"[test.cpp:3]: (style) Class 'A' is unsafe, 'A::p' can leak by wrong usage.\n", errout_str());
check("class A\n"
"{\n"
" int *p;\n"
"public:\n"
" void init();\n"
"};\n"
"\n"
"void A::init()\n"
"{ p = malloc(sizeof(int)*10); }");
ASSERT_EQUALS("[test.cpp:9]: (warning) Possible leak in public function. The pointer 'p' is not deallocated before it is allocated.\n"
"[test.cpp:3]: (style) Class 'A' is unsafe, 'A::p' can leak by wrong usage.\n", errout_str());
check("class A\n"
"{\n"
" int *p;\n"
"public:\n"
" void init()\n"
" { p = malloc(sizeof(int)*10); }\n"
"};");
ASSERT_EQUALS("[test.cpp:6]: (warning) Possible leak in public function. The pointer 'p' is not deallocated before it is allocated.\n"
"[test.cpp:3]: (style) Class 'A' is unsafe, 'A::p' can leak by wrong usage.\n", errout_str());
}
void class15() {
check("class A\n"
"{\n"
" int *p;\n"
"public:\n"
" A();\n"
" ~A() { delete [] p; }\n"
"};\n"
"A::A()\n"
"{ p = new int[10]; }");
ASSERT_EQUALS("", errout_str());
check("class A\n"
"{\n"
" int *p;\n"
"public:\n"
" A()\n"
" { p = new int[10]; }\n"
" ~A() { delete [] p; }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class A\n"
"{\n"
" int *p;\n"
"public:\n"
" A();\n"
" ~A() { delete p; }\n"
"};\n"
"A::A()\n"
"{ p = new int; }");
ASSERT_EQUALS("", errout_str());
check("class A\n"
"{\n"
" int *p;\n"
"public:\n"
" A()\n"
" { p = new int; }\n"
" ~A() { delete p; }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class A\n"
"{\n"
" int *p;\n"
"public:\n"
" A();\n"
" ~A() { free(p); }\n"
"};\n"
"A::A()\n"
"{ p = malloc(sizeof(int)*10); }");
ASSERT_EQUALS("", errout_str());
check("class A\n"
"{\n"
" int *p;\n"
"public:\n"
" A()\n"
" { p = malloc(sizeof(int)*10); }\n"
" ~A() { free(p); }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void class16() {
// Ticket #1510
check("class A\n"
"{\n"
" int *a;\n"
" int *b;\n"
"public:\n"
" A() { a = b = new int[10]; }\n"
" ~A() { delete [] a; }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void class17() {
// Ticket #1557
check("class A {\n"
"private:\n"
" char *pd;\n"
"public:\n"
" void foo();\n"
"};\n"
"\n"
"void A::foo()\n"
"{\n"
" A::pd = new char[12];\n"
" delete [] A::pd;\n"
"}");
ASSERT_EQUALS("[test.cpp:10]: (warning) Possible leak in public function. The pointer 'pd' is not deallocated before it is allocated.\n", errout_str());
check("class A {\n"
"private:\n"
" char *pd;\n"
"public:\n"
" void foo()\n"
" {\n"
" pd = new char[12];\n"
" delete [] pd;\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:7]: (warning) Possible leak in public function. The pointer 'pd' is not deallocated before it is allocated.\n", errout_str());
check("class A {\n"
"private:\n"
" char *pd;\n"
"public:\n"
" void foo();\n"
"};\n"
"\n"
"void A::foo()\n"
"{\n"
" pd = new char[12];\n"
" delete [] pd;\n"
"}");
ASSERT_EQUALS("[test.cpp:10]: (warning) Possible leak in public function. The pointer 'pd' is not deallocated before it is allocated.\n", errout_str());
}
void class18() {
// Ticket #853
check("class A : public x\n"
"{\n"
"public:\n"
" A()\n"
" {\n"
" a = new char[10];\n"
" foo(a);\n"
" }\n"
"private:\n"
" char *a;\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class A : public x\n"
"{\n"
"public:\n"
" A();\n"
"private:\n"
" char *a;\n"
"};\n"
"A::A()\n"
"{\n"
" a = new char[10];\n"
" foo(a);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void class19() {
// Ticket #2219
check("class Foo\n"
"{\n"
"private:\n"
" TRadioButton* rp1;\n"
" TRadioButton* rp2;\n"
"public:\n"
" Foo();\n"
"};\n"
"Foo::Foo()\n"
"{\n"
" rp1 = new TRadioButton(this);\n"
" rp2 = new TRadioButton(this);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("class TRadioButton { };\n"
"class Foo\n"
"{\n"
"private:\n"
" TRadioButton* rp1;\n"
" TRadioButton* rp2;\n"
"public:\n"
" Foo();\n"
"};\n"
"Foo::Foo()\n"
"{\n"
" rp1 = new TRadioButton;\n"
" rp2 = new TRadioButton;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (style) Class 'Foo' is unsafe, 'Foo::rp1' can leak by wrong usage.\n"
"[test.cpp:6]: (style) Class 'Foo' is unsafe, 'Foo::rp2' can leak by wrong usage.\n", errout_str());
check("class TRadioButton { };\n"
"class Foo\n"
"{\n"
"private:\n"
" TRadioButton* rp1;\n"
" TRadioButton* rp2;\n"
"public:\n"
" Foo();\n"
" ~Foo();\n"
"};\n"
"Foo::Foo()\n"
"{\n"
" rp1 = new TRadioButton;\n"
" rp2 = new TRadioButton;\n"
"}\n"
"Foo::~Foo()\n"
"{\n"
" delete rp1;\n"
" delete rp2;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void class20() {
check("namespace ns1 {\n"
" class Fred\n"
" {\n"
" private:\n"
" char *str1;\n"
" char *str2;\n"
" public:\n"
" Fred()\n"
" {\n"
" str1 = new char[10];\n"
" str2 = new char[10];\n"
" }\n"
" ~Fred()\n"
" {\n"
" delete [] str2;\n"
" }\n"
" };\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (style) Class 'Fred' is unsafe, 'Fred::str1' can leak by wrong usage.\n", errout_str());
check("namespace ns1 {\n"
" class Fred\n"
" {\n"
" private:\n"
" char *str1;\n"
" char *str2;\n"
" public:\n"
" Fred();\n"
" ~Fred();\n"
" };\n"
"\n"
" Fred::Fred()\n"
" {\n"
" str1 = new char[10];\n"
" str2 = new char[10];\n"
" }\n"
"\n"
" Fred::~Fred()\n"
" {\n"
" delete [] str2;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (style) Class 'Fred' is unsafe, 'Fred::str1' can leak by wrong usage.\n", errout_str());
check("namespace ns1 {\n"
" class Fred\n"
" {\n"
" private:\n"
" char *str1;\n"
" char *str2;\n"
" public:\n"
" Fred();\n"
" ~Fred();\n"
" };\n"
"}\n"
"ns1::Fred::Fred()\n"
"{\n"
" str1 = new char[10];\n"
" str2 = new char[10];\n"
"}\n"
"\n"
"ns1::Fred::~Fred()\n"
"{\n"
" delete [] str2;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (style) Class 'Fred' is unsafe, 'Fred::str1' can leak by wrong usage.\n", errout_str());
check("namespace ns1 {\n"
" namespace ns2 {\n"
" class Fred\n"
" {\n"
" private:\n"
" char *str1;\n"
" char *str2;\n"
" public:\n"
" Fred();\n"
" ~Fred();\n"
" };\n"
" }\n"
"}\n"
"ns1::ns2::Fred::Fred()\n"
"{\n"
" str1 = new char[10];\n"
" str2 = new char[10];\n"
"}\n"
"\n"
"ns1::ns2::Fred::~Fred()\n"
"{\n"
" delete [] str2;\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (style) Class 'Fred' is unsafe, 'Fred::str1' can leak by wrong usage.\n", errout_str());
check("namespace ns1 {\n"
" namespace ns2 {\n"
" namespace ns3 {\n"
" class Fred\n"
" {\n"
" private:\n"
" char *str1;\n"
" char *str2;\n"
" public:\n"
" Fred();\n"
" ~Fred();\n"
" };\n"
" }\n"
" }\n"
"}\n"
"ns1::ns2::ns3::Fred::Fred()\n"
"{\n"
" str1 = new char[10];\n"
" str2 = new char[10];\n"
"}\n"
"\n"
"ns1::ns2::ns3::Fred::~Fred()\n"
"{\n"
" delete [] str2;\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (style) Class 'Fred' is unsafe, 'Fred::str1' can leak by wrong usage.\n", errout_str());
}
void class21() { // ticket #2517
check("struct B { };\n"
"struct C\n"
"{\n"
" B * b;\n"
" C(B * x) : b(x) { }\n"
"};\n"
"class A\n"
"{\n"
" B *b;\n"
" C *c;\n"
"public:\n"
" A() : b(new B()), c(new C(b)) { }\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:9]: (style) Class 'A' is unsafe, 'A::b' can leak by wrong usage.\n"
"[test.cpp:10]: (style) Class 'A' is unsafe, 'A::c' can leak by wrong usage.\n",
"[test.cpp:9]: (style) Class 'A' is unsafe, 'A::b' can leak by wrong usage.\n",
errout_str());
check("struct B { };\n"
"struct C\n"
"{\n"
" B * b;\n"
" C(B * x) : b(x) { }\n"
"};\n"
"class A\n"
"{\n"
" B *b;\n"
" C *c;\n"
"public:\n"
" A()\n"
" {\n"
" b = new B();\n"
" c = new C(b);\n"
" }\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:9]: (style) Class 'A' is unsafe, 'A::b' can leak by wrong usage.\n"
"[test.cpp:10]: (style) Class 'A' is unsafe, 'A::c' can leak by wrong usage.\n",
"[test.cpp:9]: (style) Class 'A' is unsafe, 'A::b' can leak by wrong usage.\n",
errout_str());
}
void class22() { // ticket #3012 - false positive
check("class Fred {\n"
"private:\n"
" int * a;\n"
"private:\n"
" Fred() { a = new int; }\n"
" ~Fred() { (delete(a), (a)=NULL); }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void class23() { // ticket #3303 - false positive
check("class CDataImpl {\n"
"public:\n"
" CDataImpl() { m_refcount = 1; }\n"
" void Release() { if (--m_refcount == 0) delete this; }\n"
"private:\n"
" int m_refcount;\n"
"};\n"
"\n"
"class CData {\n"
"public:\n"
" CData() : m_impl(new CDataImpl()) { }\n"
" ~CData() { if (m_impl) m_impl->Release(); }\n"
"private:\n"
" CDataImpl *m_impl;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void class24() { // ticket #3806 - false positive in copy constructor
check("class Fred {\n"
"private:\n"
" int * a;\n"
"public:\n"
" Fred(const Fred &fred) { a = new int; }\n"
" ~Fred() { delete a; }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void class25() { // ticket #4367 - false positive when implementation for destructor is not seen
check("class Fred {\n"
"private:\n"
" int * a;\n"
"public:\n"
" Fred() { a = new int; }\n"
" ~Fred();\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void class26() { // ticket #10789 - crash
check("class C;\n"
"struct S {\n"
" S() { p = new C; }\n"
" ~S();\n"
" C* p;\n"
"};\n"
"S::~S() = default;\n");
ASSERT_EQUALS("[test.cpp:5]: (style) Class 'S' is unsafe, 'S::p' can leak by wrong usage.\n", errout_str());
}
void class27() { // ticket #8126 - array of pointers
check("struct S {\n"
" S() {\n"
" for (int i = 0; i < 5; i++)\n"
" a[i] = new char[3];\n"
" }\n"
" char* a[5];\n"
"};\n");
ASSERT_EQUALS("[test.cpp:6]: (style) Class 'S' is unsafe, 'S::a' can leak by wrong usage.\n", errout_str());
}
void staticvar() {
check("class A\n"
"{\n"
"private:\n"
" static int * p;\n"
"public:"
" A()\n"
" {\n"
" if (!p)\n"
" p = new int[100];\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void free_member_in_sub_func() {
// Member function
check("class Tokenizer\n"
"{\n"
"public:\n"
" Tokenizer();\n"
" ~Tokenizer();\n"
"\n"
"private:\n"
" int *_tokens;\n"
" static void deleteTokens(int *tok);\n"
"};\n"
"\n"
"Tokenizer::Tokenizer()\n"
"{\n"
" _tokens = new int;\n"
"}\n"
"\n"
"Tokenizer::~Tokenizer()\n"
"{\n"
" deleteTokens(_tokens);\n"
" _tokens = 0;\n"
"}\n"
"\n"
"void Tokenizer::deleteTokens(int *tok)\n"
"{\n"
" delete tok;\n"
"}");
ASSERT_EQUALS("", errout_str());
// Global function
check("void deleteTokens(int *tok)\n"
"{\n"
" delete tok;\n"
"}\n"
"class Tokenizer\n"
"{\n"
"public:\n"
" Tokenizer();\n"
" ~Tokenizer();\n"
"\n"
"private:\n"
" int *_tokens;\n"
"};\n"
"\n"
"Tokenizer::Tokenizer()\n"
"{\n"
" _tokens = new int;\n"
"}\n"
"\n"
"Tokenizer::~Tokenizer()\n"
"{\n"
" deleteTokens(_tokens);\n"
" _tokens = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void mismatch1() {
check("class A\n"
"{\n"
"public:\n"
" A(int i);\n"
" ~A();\n"
"private:\n"
" char* pkt_buffer;\n"
"};\n"
"\n"
"A::A(int i)\n"
"{\n"
" pkt_buffer = new char[8192];\n"
" if (i != 1) {\n"
" delete pkt_buffer;\n"
" pkt_buffer = 0;\n"
" }\n"
"}\n"
"\n"
"A::~A() {\n"
" delete [] pkt_buffer;\n"
"}");
ASSERT_EQUALS("[test.cpp:14]: (error) Mismatching allocation and deallocation: A::pkt_buffer\n", errout_str());
check("struct S {\n" // 5678
" ~S();\n"
" void f();\n"
" int* p;\n"
"};\n"
"void S::f() {\n"
" p = new char[1];\n"
" delete p;\n"
" p = 0;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:8]: (error) Mismatching allocation and deallocation: S::p\n", errout_str());
}
void mismatch2() { // #5659
check("namespace NS\n"
"{\n"
"class Foo\n"
"{\n"
"public:\n"
" void fct();\n"
"\n"
"private:\n"
" char* data_;\n"
"};\n"
"}\n"
"\n"
"using namespace NS;\n"
"\n"
"void Foo::fct()\n"
"{\n"
" data_ = new char[42];\n"
" delete data_;\n"
" data_ = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:17]: (warning) Possible leak in public function. The pointer 'data_' is not deallocated before it is allocated.\n"
"[test.cpp:18]: (error) Mismatching allocation and deallocation: Foo::data_\n", errout_str());
check("namespace NS\n"
"{\n"
"class Foo\n"
"{\n"
"public:\n"
" void fct(int i);\n"
"\n"
"private:\n"
" char* data_;\n"
"};\n"
"}\n"
"\n"
"using namespace NS;\n"
"\n"
"void Foo::fct(int i)\n"
"{\n"
" data_ = new char[42];\n"
" delete data_;\n"
" data_ = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:17]: (warning) Possible leak in public function. The pointer 'data_' is not deallocated before it is allocated.\n"
"[test.cpp:18]: (error) Mismatching allocation and deallocation: Foo::data_\n", errout_str());
}
void func1() {
check("class Fred\n"
"{\n"
"private:\n"
" char *s;\n"
"public:\n"
" Fred() { s = 0; }\n"
" ~Fred() { free(s); }\n"
" void xy()\n"
" { s = malloc(100); }\n"
"};");
ASSERT_EQUALS("[test.cpp:9]: (warning) Possible leak in public function. The pointer 's' is not deallocated before it is allocated.\n", errout_str());
check("class Fred\n"
"{\n"
"public:\n"
" Fred() { s = 0; }\n"
" ~Fred() { free(s); }\n"
" void xy()\n"
" { s = malloc(100); }\n"
"private:\n"
" char *s;\n"
"};");
ASSERT_EQUALS("[test.cpp:7]: (warning) Possible leak in public function. The pointer 's' is not deallocated before it is allocated.\n", errout_str());
}
void func2() {
check("class Fred\n"
"{\n"
"private:\n"
" char *s;\n"
"public:\n"
" Fred() { s = 0; }\n"
" ~Fred() { free(s); }\n"
" const Fred & operator = (const Fred &f)\n"
" { s = malloc(100); }\n"
"};");
ASSERT_EQUALS("[test.cpp:9]: (warning) Possible leak in public function. The pointer 's' is not deallocated before it is allocated.\n", errout_str());
}
};
REGISTER_TEST(TestMemleakInClass)
class TestMemleakStructMember : public TestFixture {
public:
TestMemleakStructMember() : TestFixture("TestMemleakStructMember") {}
private:
const Settings settings = settingsBuilder().library("std.cfg").library("posix.cfg").build();
template<size_t size>
void check_(const char* file, int line, const char (&code)[size], bool cpp = true) {
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code, cpp), file, line);
// Check for memory leaks..
CheckMemoryLeakStructMember checkMemoryLeakStructMember(&tokenizer, &settings, this);
(checkMemoryLeakStructMember.check)();
}
void run() override {
// testing that errors are detected
TEST_CASE(err);
// handle / bail out when "goto" is found
TEST_CASE(goto_);
// Don't report errors if the struct is returned
TEST_CASE(ret1);
TEST_CASE(ret2);
// assignments
TEST_CASE(assign1);
TEST_CASE(assign2);
TEST_CASE(assign3);
TEST_CASE(assign4); // #11019
// Failed allocation
TEST_CASE(failedAllocation);
TEST_CASE(function1); // Deallocating in function
TEST_CASE(function2); // #2848: Taking address in function
TEST_CASE(function3); // #3024: kernel list
TEST_CASE(function4); // #3038: Deallocating in function
TEST_CASE(function5); // #10381, #10382, #10158
// Handle if-else
TEST_CASE(ifelse);
// Linked list
TEST_CASE(linkedlist);
// struct variable is a global variable
TEST_CASE(globalvar);
// local struct variable
TEST_CASE(localvars);
// struct variable is a reference variable
TEST_CASE(refvar);
// Segmentation fault in CheckMemoryLeakStructMember
TEST_CASE(trac5030);
TEST_CASE(varid); // #5201: Analysis confused by (variable).attribute notation
TEST_CASE(varid_2); // #5315: Analysis confused by ((variable).attribute) notation
TEST_CASE(customAllocation);
TEST_CASE(lambdaInScope); // #9793
}
void err() {
check("static void foo()\n"
"{\n"
" struct ABC *abc = malloc(sizeof(struct ABC));\n"
" abc->a = malloc(10);\n"
" free(abc);\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Memory leak: abc.a\n", errout_str());
check("static void foo()\n"
"{\n"
" struct ABC *abc = malloc(sizeof(struct ABC));\n"
" abc->a = malloc(10);\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Memory leak: abc.a\n", errout_str());
check("static ABC * foo()\n"
"{\n"
" ABC *abc = malloc(sizeof(ABC));\n"
" abc->a = malloc(10);\n"
" abc->b = malloc(10);\n"
" if (abc->b == 0)\n"
" {\n"
" return 0;\n"
" }\n"
" return abc;\n"
"}");
ASSERT_EQUALS("[test.cpp:8]: (error) Memory leak: abc.a\n", errout_str());
check("static void foo(int a)\n"
"{\n"
" ABC *abc = malloc(sizeof(ABC));\n"
" abc->a = malloc(10);\n"
" if (a == 1)\n"
" {\n"
" free(abc->a);\n"
" return;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:10]: (error) Memory leak: abc.a\n", errout_str());
}
void goto_() {
check("static void foo()\n"
"{\n"
" struct ABC *abc = malloc(sizeof(struct ABC));\n"
" abc->a = malloc(10);\n"
" if (abc->a)\n"
" { goto out; }\n"
" free(abc);\n"
" return;\n"
"out:\n"
" free(abc->a);\n"
" free(abc);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void ret1() {
check("static ABC * foo()\n"
"{\n"
" struct ABC *abc = malloc(sizeof(struct ABC));\n"
" abc->a = malloc(10);\n"
" return abc;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("static void foo(struct ABC *abc)\n"
"{\n"
" abc->a = malloc(10);\n"
"}");
ASSERT_EQUALS("", errout_str());
// #7302
check("void* foo() {\n"
" struct ABC abc;\n"
" abc.a = malloc(10);\n"
" return abc.a;\n"
"}", false);
ASSERT_EQUALS("", errout_str());
check("void* foo() {\n"
" struct ABC abc;\n"
" abc.a = malloc(10);\n"
" return abc.b;\n"
"}", false);
ASSERT_EQUALS("[test.c:4]: (error) Memory leak: abc.a\n", errout_str());
}
void ret2() {
check("static ABC * foo()\n"
"{\n"
" struct ABC *abc = malloc(sizeof(struct ABC));\n"
" abc->a = malloc(10);\n"
" return &abc->self;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void assign1() {
check("static void foo()\n"
"{\n"
" struct ABC *abc = abc1;\n"
" abc->a = malloc(10);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("static void foo()\n"
"{\n"
" struct ABC *abc;\n"
" abc1 = abc = malloc(sizeof(ABC));\n"
" abc->a = malloc(10);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("static void foo()\n"
"{\n"
" struct msn_entry *ptr;\n"
" ptr = malloc(sizeof(struct msn_entry));\n"
" ptr->msn = malloc(100);\n"
" back = ptr;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void assign2() {
check("static void foo() {\n"
" struct ABC *abc = malloc(123);\n"
" abc->a = abc->b = malloc(10);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void assign3() {
check("void f(struct s *f1) {\n"
" struct s f2;\n"
" f2.a = malloc(100);\n"
" *f1 = f2;\n"
"}", false);
ASSERT_EQUALS("", errout_str());
}
void assign4() {
check("struct S { int a, b, c; };\n" // #11019
"void f() {\n"
" struct S s;\n"
" *&s.a = open(\"xx.log\", O_RDONLY);\n"
" ((s).b) = open(\"xx.log\", O_RDONLY);\n"
" (&s)->c = open(\"xx.log\", O_RDONLY);\n"
"}\n", false);
ASSERT_EQUALS("[test.c:7]: (error) Resource leak: s.a\n"
"[test.c:7]: (error) Resource leak: s.b\n"
"[test.c:7]: (error) Resource leak: s.c\n",
errout_str());
check("struct S { int *p, *q; };\n" // #7705
"void f(S s) {\n"
" s.p = new int[10];\n"
" s.q = malloc(40);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5]: (error) Memory leak: s.p\n"
"[test.cpp:5]: (error) Memory leak: s.q\n",
errout_str());
check("struct S** f(struct S** s) {\n" // don't throw
" struct S** ret = malloc(sizeof(*ret));\n"
" ret[0] = malloc(sizeof(**s));\n"
" ret[0]->g = strdup(s[0]->g);\n"
" return ret;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void run_rcmd(enum rcommand rcmd, rsh_session *sess, char *cmd) {\n"
" sess->fp = popen(cmd, rcmd == RSH_PIPE_READ ? \"r\" : \"w\");\n"
"}\n", false);
ASSERT_EQUALS("", errout_str());
check("struct S { char* a[2]; };\n"
"enum E { E0, E1 };\n"
"void f(struct S* s, enum E e, const char* n) {\n"
" free(s->a[e]);\n"
" s->a[e] = strdup(n);\n"
"}\n", false);
ASSERT_EQUALS("", errout_str());
check("void f(struct S** s, const char* c) {\n"
" *s = malloc(sizeof(struct S));\n"
" (*s)->value = strdup(c);\n"
"}\n", false);
ASSERT_EQUALS("", errout_str());
check("struct S {\n"
" size_t mpsz;\n"
" void* hdr;\n"
"};\n"
"void f(struct S s[static 1U], int fd, size_t size) {\n"
" s->mpsz = size;\n"
" s->hdr = mmap(NULL, s->mpsz, PROT_READ, MAP_SHARED, fd, 0);\n"
"}\n", false);
ASSERT_EQUALS("", errout_str());
check("void f(type_t t) {\n"
" t->p = malloc(10);\n"
" t->x.p = malloc(10);\n"
" t->y[2].p = malloc(10);\n"
"}\n", false);
ASSERT_EQUALS("", errout_str());
}
void failedAllocation() {
check("static struct ABC * foo()\n"
"{\n"
" struct ABC *abc = malloc(sizeof(struct ABC));\n"
" abc->a = malloc(10);\n"
" if (!abc->a)\n"
" {\n"
" free(abc);\n"
" return 0;\n"
" }\n"
" return abc;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void function1() {
// Not found function => assume that the function may deallocate
check("static void foo()\n"
"{\n"
" struct ABC *abc = malloc(sizeof(struct ABC));\n"
" abc->a = malloc(10);\n"
" func(abc);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("static void foo()\n"
"{\n"
" struct ABC *abc = malloc(sizeof(struct ABC));\n"
" abclist.push_back(abc);\n"
" abc->a = malloc(10);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
// #2848: Taking address in function 'assign'
void function2() {
check("void f() {\n"
" A a = { 0 };\n"
" a.foo = (char *) malloc(10);\n"
" assign(&a);\n"
"}", false);
ASSERT_EQUALS("", errout_str());
}
// #3024: kernel list
void function3() {
check("void f() {\n"
" struct ABC *abc = malloc(100);\n"
" abc.a = (char *) malloc(10);\n"
" list_add_tail(&abc->list, head);\n"
"}", false);
ASSERT_EQUALS("", errout_str());
}
// #3038: deallocating in function
void function4() {
check("void a(char *p) { char *x = p; free(x); }\n"
"void b() {\n"
" struct ABC abc;\n"
" abc.a = (char *) malloc(10);\n"
" a(abc.a);\n"
"}", false);
ASSERT_EQUALS("", errout_str());
}
void function5() {
check("struct s f() {\n" // #10381
" struct s s1;\n"
" s1->x = malloc(1);\n"
" return (s1);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct nc_rpc nc_rpc_getconfig() {\n" // #10382
" struct nc_rpc rpc;\n"
" rpc->filter = malloc(1);\n"
" return (nc_rpc)rpc;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("T* f(const char *str) {\n" // #10158
" S* s = malloc(sizeof(S));\n"
" s->str = strdup(str);\n"
" return NewT(s);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("typedef struct s { char* str; } attr_t;\n" // #10152
"attr_t* f(int type) {\n"
" attr_t a;\n"
" switch (type) {\n"
" case 1:\n"
" a.str = strdup(\"?\");\n"
" break;\n"
" default:\n"
" return NULL;\n"
" }\n"
" return g(&a);\n"
"}\n");
TODO_ASSERT_EQUALS("", "[test.cpp:9]: (error) Memory leak: a.str\n", errout_str());
}
void ifelse() {
check("static void foo()\n"
"{\n"
" struct ABC *abc = malloc(sizeof(struct ABC));\n"
" if (x)"
" {\n"
" abc->a = malloc(10);\n"
" }\n"
" else\n"
" {\n"
" free(abc);\n"
" return;\n"
" }\n"
" free(abc->a);\n"
" free(abc);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void linkedlist() {
// #3904 - false positive when linked list is used
check("static void foo() {\n"
" struct ABC *abc = malloc(sizeof(struct ABC));\n"
" abc->next = malloc(sizeof(struct ABC));\n"
" abc->next->next = NULL;\n"
"\n"
" while (abc) {\n"
" struct ABC *next = abc->next;\n"
" free(abc);\n"
" abc = next;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void globalvar() {
check("struct ABC *abc;\n"
"\n"
"static void foo()\n"
"{\n"
" abc = malloc(sizeof(struct ABC));\n"
" abc->a = malloc(10);\n"
" return;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
// Ticket #933 Leaks with struct members not detected
void localvars() {
// Test error case
const char code1[] = "struct A {\n"
" FILE* f;\n"
" char* c;\n"
" void* m;\n"
"};\n"
"\n"
"void func() {\n"
" struct A a;\n"
" a.f = fopen(\"test\", \"r\");\n"
" a.c = new char[12];\n"
" a.m = malloc(12);\n"
"}";
check(code1, true);
ASSERT_EQUALS("[test.cpp:12]: (error) Resource leak: a.f\n"
"[test.cpp:12]: (error) Memory leak: a.c\n"
"[test.cpp:12]: (error) Memory leak: a.m\n", errout_str());
check(code1, false);
ASSERT_EQUALS("[test.c:12]: (error) Resource leak: a.f\n"
"[test.c:12]: (error) Memory leak: a.m\n", errout_str());
// Test OK case
const char code2[] = "struct A {\n"
" FILE* f;\n"
" char* c;\n"
" void* m;\n"
"};\n"
"\n"
"void func() {\n"
" struct A a;\n"
" a.f = fopen(\"test\", \"r\");\n"
" a.c = new char[12];\n"
" a.m = malloc(12);\n"
" fclose(a.f);\n"
" delete [] a.c;\n"
" free(a.m);\n"
"}";
check(code2, true);
ASSERT_EQUALS("", errout_str());
// Test unknown struct. In C++, it might have a destructor
const char code3[] = "void func() {\n"
" struct A a;\n"
" a.f = fopen(\"test\", \"r\");\n"
"}";
check(code3, true);
ASSERT_EQUALS("", errout_str());
check(code3, false);
ASSERT_EQUALS("[test.c:4]: (error) Resource leak: a.f\n", errout_str());
// Test struct with destructor
const char code4[] = "struct A {\n"
" FILE* f;\n"
" ~A();\n"
"};\n"
"void func() {\n"
" struct A a;\n"
" a.f = fopen(\"test\", \"r\");\n"
"}";
check(code4, true);
ASSERT_EQUALS("", errout_str());
}
void refvar() { // #8116
check("struct Test\n"
"{\n"
" int* data;\n"
"};\n"
"\n"
"void foo(Test* x)\n"
"{\n"
" Test& y = *x;\n"
" y.data = malloc(10);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
// don't crash
void trac5030() {
check("bool bob( char const **column_ptrs ) {\n"
"unique_ptr<char[]>otherbuffer{new char[otherbufsize+1]};\n"
"char *const oldbuffer = otherbuffer.get();\n"
"int const oldbufsize = otherbufsize;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void varid() { // #5201
check("struct S {\n"
" void *state_check_buff;\n"
"};\n"
"void f() {\n"
" S s;\n"
" (s).state_check_buff = (void* )malloc(1);\n"
" if (s.state_check_buff == 0)\n"
" return;\n"
"}", false);
ASSERT_EQUALS("[test.c:9]: (error) Memory leak: s.state_check_buff\n", errout_str());
}
void varid_2() { // #5315
check("typedef struct foo { char *realm; } foo;\n"
"void build_principal() {\n"
" foo f;\n"
" ((f)->realm) = strdup(realm);\n"
" if(f->realm == NULL) {}\n"
"}", false);
ASSERT_EQUALS("[test.c:6]: (error) Memory leak: f.realm\n", errout_str());
}
void customAllocation() { // #4770
check("char *myalloc(void) {\n"
" return malloc(100);\n"
"}\n"
"void func() {\n"
" struct ABC abc;\n"
" abc.a = myalloc();\n"
"}", false);
ASSERT_EQUALS("[test.c:7]: (error) Memory leak: abc.a\n", errout_str());
}
void lambdaInScope() {
check( // #9793
"struct S { int * p{nullptr}; };\n"
"int main()\n"
"{\n"
" S s;\n"
" s.p = new int[10];\n"
" for (int i = 0; i < 10; ++i) {\n"
" s.p[i] = []() { return 1; }();\n"
" }\n"
" delete[] s.p;\n"
" return 0;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check(
"struct S { int* p; };\n"
"void f() {\n"
" auto g = []() {\n"
" S s;\n"
" s.p = new int;\n"
" };\n"
"}\n", true);
ASSERT_EQUALS("[test.cpp:6]: (error) Memory leak: s.p\n", errout_str());
check(
"struct S { int* p; };\n"
"void f() {\n"
" S s;\n"
" s.p = new int;\n"
" auto g = [&]() {\n"
" delete s.p;\n"
" };\n"
" g();\n"
"}\n"
"void h() {\n"
" S s;\n"
" s.p = new int;\n"
" [&]() {\n"
" delete s.p;\n"
" }();\n"
"}\n", true);
ASSERT_EQUALS("", errout_str());
}
};
REGISTER_TEST(TestMemleakStructMember)
class TestMemleakNoVar : public TestFixture {
public:
TestMemleakNoVar() : TestFixture("TestMemleakNoVar") {}
private:
const Settings settings = settingsBuilder().certainty(Certainty::inconclusive).severity(Severity::warning).library("std.cfg").library("posix.cfg").build();
template<size_t size>
void check_(const char* file, int line, const char (&code)[size]) {
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
// Check for memory leaks..
CheckMemoryLeakNoVar checkMemoryLeakNoVar(&tokenizer, &settings, this);
(checkMemoryLeakNoVar.check)();
}
void run() override {
// pass allocated memory to function..
TEST_CASE(functionParameter);
// never use leakable resource
TEST_CASE(missingAssignment);
// pass allocated memory to function using a smart pointer
TEST_CASE(smartPointerFunctionParam);
TEST_CASE(resourceLeak);
// Test getAllocationType for subfunction
TEST_CASE(getAllocationType);
TEST_CASE(crash1); // #10729
TEST_CASE(openDevNull); // #9653
}
void functionParameter() {
// standard function..
check("void x() {\n"
" strcpy(a, strdup(p));\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Allocation with strdup, strcpy doesn't release it.\n", errout_str());
check("char *x() {\n"
" char *ret = strcpy(malloc(10), \"abc\");\n"
" return ret;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("char *x() {\n"
" return strcpy(malloc(10), \"abc\");\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void x() {\n"
" free(malloc(10));\n"
"}");
ASSERT_EQUALS("", errout_str());
// user function..
check("void set_error(const char *msg) {\n"
"}\n"
"\n"
"void x() {\n"
" set_error(strdup(p));\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:5]: (error) Allocation with strdup, set_error doesn't release it.\n", "", errout_str());
check("void f()\n"
"{\n"
" int fd;\n"
" fd = mkstemp(strdup(\"/tmp/file.XXXXXXXX\"));\n"
" close(fd);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:4]: (error) Allocation with strdup, mkstemp doesn't release it.\n", "", errout_str());
check("void f()\n"
"{\n"
" if(TRUE || strcmp(strdup(a), b));\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Allocation with strdup, strcmp doesn't release it.\n", errout_str());
check("void f()\n"
"{\n"
" if(!strcmp(strdup(a), b) == 0);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Allocation with strdup, strcmp doesn't release it.\n", errout_str());
check("void f()\n"
"{\n"
" 42, strcmp(strdup(a), b);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Allocation with strdup, strcmp doesn't release it.\n", errout_str());
check("void f() {\n"
" assert(freopen(\"/dev/null\", \"r\", stdin));\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void x() {\n"
" strcpy(a, (void*)strdup(p));\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Allocation with strdup, strcpy doesn't release it.\n", errout_str());
check("void* malloc1() {\n"
" return (malloc(1));\n"
"}");
ASSERT_EQUALS("", errout_str());
check("char *x() {\n"
" char *ret = (char*)strcpy(malloc(10), \"abc\");\n"
" return ret;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" free(malloc(1));\n"
" strcpy(a, strdup(p));\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Allocation with strdup, strcpy doesn't release it.\n", errout_str());
check("void f() {\n"
" memcmp(calloc(10, 10), strdup(q), 100);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Allocation with calloc, memcmp doesn't release it.\n"
"[test.cpp:2]: (error) Allocation with strdup, memcmp doesn't release it.\n", errout_str());
check("void* f(int size) {\n"
" return (void*) malloc(size);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int* f(int size) {\n"
" return static_cast<int*>(malloc(size));\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() { if (new int[42]) {} }\n" // #10857
"void g() { if (malloc(42)) {} }\n");
ASSERT_EQUALS("[test.cpp:1]: (error) Allocation with new, if doesn't release it.\n"
"[test.cpp:2]: (error) Allocation with malloc, if doesn't release it.\n",
errout_str());
check("const char* string(const char* s) {\n"
" StringSet::iterator it = strings_.find(s);\n"
" if (it != strings_.end())\n"
" return *it;\n"
" return *strings_.insert(it, std::strcpy(new char[std::strlen(s) + 1], s));\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct S {\n"
" static void load(const QString& projPath) {\n"
" if (proj_)\n"
" return;\n"
" proj_ = new ProjectT(projPath);\n"
" proj_->open(new OpenCallback());\n"
" }\n"
"private:\n"
" static Core::ProjectBase* proj_;\n"
"};\n");
ASSERT_EQUALS("", errout_str());
check("void f(const std::string& s, int n) {\n"
" std::unique_ptr<char[]> u;\n"
" u.reset(strcpy(new char[n], s.c_str()));\n"
"};\n");
ASSERT_EQUALS("", errout_str());
check("struct S { char* p; };\n"
"void f(S* s, int N) {\n"
" s->p = s->p ? strcpy(new char[N], s->p) : nullptr;\n"
"};\n");
ASSERT_EQUALS("", errout_str());
check("struct S {};\n" // #11866
"void f(bool b);\n"
"void g() {\n"
" f(new int());\n"
" f(new std::vector<int>());\n"
" f(new S());\n"
" f(new tm());\n"
" f(malloc(sizeof(S)));\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (error) Allocation with new, f doesn't release it.\n"
"[test.cpp:5]: (error) Allocation with new, f doesn't release it.\n"
"[test.cpp:6]: (error) Allocation with new, f doesn't release it.\n"
"[test.cpp:7]: (error) Allocation with new, f doesn't release it.\n"
"[test.cpp:8]: (error) Allocation with malloc, f doesn't release it.\n",
errout_str());
check("void f(uintptr_t u);\n"
"void g() {\n"
" f((uintptr_t)new int());\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(uint8_t u);\n"
"void g() {\n"
" f((uint8_t)new int());\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Allocation with new, f doesn't release it.\n",
errout_str());
check("void f(int i, T t);\n"
"void g(int i, U* u);\n"
"void h() {\n"
" f(1, new int());\n"
" g(1, new int());\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(T t);\n"
"struct U {};\n"
"void g() {\n"
" f(new U());\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void missingAssignment() {
check("void x()\n"
"{\n"
" malloc(10);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Return value of allocation function 'malloc' is not stored.\n", errout_str());
check("void x()\n"
"{\n"
" calloc(10, 1);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Return value of allocation function 'calloc' is not stored.\n", errout_str());
check("void x()\n"
"{\n"
" strdup(\"Test\");\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Return value of allocation function 'strdup' is not stored.\n", errout_str());
check("void x()\n"
"{\n"
" (char*) malloc(10);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Return value of allocation function 'malloc' is not stored.\n", errout_str());
check("void x()\n"
"{\n"
" char* ptr = malloc(10);\n"
" foo(ptr);\n"
" free(ptr);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f( void ) {\n" // FP: #11246
" void* address = malloc( 1 );\n"
" int ok = address != 0;\n"
" if ( ok )\n"
" free( address ), address = 0;\n"
" return 0;\n"
"} ");
ASSERT_EQUALS("", errout_str());
check("char** x(const char* str) {\n"
" char* ptr[] = { malloc(10), malloc(5), strdup(str) };\n"
" return ptr;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void x()\n"
"{\n"
" 42,malloc(42);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Return value of allocation function 'malloc' is not stored.\n", errout_str());
check("void *f()\n"
"{\n"
" return malloc(10);\n"
"}\n"
"void x()\n"
"{\n"
" f();\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (error) Return value of allocation function 'f' is not stored.\n", errout_str());
check("void f()\n" // #8100
"{\n"
" auto lambda = [](){return malloc(10);};\n"
"}\n"
"void x()\n"
"{\n"
" f();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void *f() {\n" // #8848
" struct S { void *alloc() { return malloc(10); } };\n"
"}\n"
"void x()\n"
"{\n"
" f();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void x()\n"
"{\n"
" if(!malloc(5)) fail();\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Return value of allocation function 'malloc' is not stored.\n", errout_str());
check("FOO* factory() {\n"
" FOO* foo = new (std::nothrow) FOO;\n"
" return foo;\n"
"}");
ASSERT_EQUALS("", errout_str());
// Ticket #6536
check("struct S { S(int) {} };\n"
"void foo(int i) {\n"
" S socket(i);\n"
"}");
ASSERT_EQUALS("", errout_str());
// Ticket #6693
check("struct CTest {\n"
" void Initialise();\n"
" void malloc();\n"
"};\n"
"void CTest::Initialise() {\n"
" malloc();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo() {\n" // #7348 - cast
" p = (::X*)malloc(42);\n"
"}");
ASSERT_EQUALS("", errout_str());
// #7182 "crash: CheckMemoryLeak::functionReturnType()"
check("template<typename... Ts> auto unary_right_comma (Ts... ts) { return (ts , ...); }\n"
"template<typename T, typename... Ts> auto binary_left_comma (T x, Ts... ts) { return (x , ... , ts); }\n"
"int main() {\n"
" unary_right_comma (a);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" new int[10];\n"
" new int[10][5];\n"
" new int[10]();\n"
" new int[10]{};\n"
" new int[] { 1, 2, 3 };\n"
" new std::string;\n"
" new int;\n"
" new int();\n"
" new int(1);\n"
" new int{};\n"
" new int{ 1 };\n"
" new uint8_t[4];\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Return value of allocation function 'new' is not stored.\n"
"[test.cpp:3]: (error) Return value of allocation function 'new' is not stored.\n"
"[test.cpp:4]: (error) Return value of allocation function 'new' is not stored.\n"
"[test.cpp:5]: (error) Return value of allocation function 'new' is not stored.\n"
"[test.cpp:6]: (error) Return value of allocation function 'new' is not stored.\n"
"[test.cpp:7]: (error) Return value of allocation function 'new' is not stored.\n"
"[test.cpp:8]: (error) Return value of allocation function 'new' is not stored.\n"
"[test.cpp:9]: (error) Return value of allocation function 'new' is not stored.\n"
"[test.cpp:10]: (error) Return value of allocation function 'new' is not stored.\n"
"[test.cpp:11]: (error) Return value of allocation function 'new' is not stored.\n"
"[test.cpp:12]: (error) Return value of allocation function 'new' is not stored.\n"
"[test.cpp:13]: (error) Return value of allocation function 'new' is not stored.\n",
errout_str());
check("void f(int* p) {\n"
" new auto('c');\n"
" new(p) int;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:2]: (error) Return value of allocation function 'new' is not stored.\n"
"[test.cpp:3]: (error) Return value of allocation function 'new' is not stored.\n",
"",
errout_str());
check("void g(int* p) {\n"
" new QWidget;\n"
" new QWidget();\n"
" new QWidget{ this };\n"
" h(new int[10], 1);\n"
" h(new int[10][5], 1);\n"
" h(new int[10](), 1);\n"
" h(new int[10]{}, 1);\n"
" h(new int[] { 1, 2, 3 }, 1);\n"
" h(new auto('c'), 1);\n"
" h(new std::string, 1);\n"
" h(new int, 1);\n"
" h(new int{}, 1);\n"
" h(new int(), 1);\n"
" h(new int{ 1 }, 1);\n"
" h(new int(1), 1);\n"
" h(new(p) int, 1);\n"
" h(new QWidget, 1);\n"
" C{ new int[10], 1 };\n"
" C{ new int[10](), 1 };\n"
" C{ new int[10]{}, 1 };\n"
" C{ new int[] { 1, 2, 3 }, 1 };\n"
" C{ new auto('c'), 1 };\n"
" C{ new std::string, 1 };\n"
" C{ new int, 1 };\n"
" C{ new int{}, 1 };\n"
" C{ new int(), 1 };\n"
" C{ new int{ 1 }, 1 };\n"
" C{ new int(1), 1 };\n"
" C{ new(p) int, 1 };\n"
" C{ new QWidget, 1 };\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(bool b) { if (b && malloc(42)) {} }\n" // // #10858
"void g(bool b) { if (b || malloc(42)) {} }\n");
ASSERT_EQUALS("[test.cpp:1]: (error) Return value of allocation function 'malloc' is not stored.\n"
"[test.cpp:2]: (error) Return value of allocation function 'malloc' is not stored.\n",
errout_str());
check("void f0(const bool b) { b ? new int : nullptr; }\n" // #11155
"void f1(const bool b) { b ? nullptr : new int; }\n"
"int* g0(const bool b) { return b ? new int : nullptr; }\n"
"void g1(const bool b) { h(b, b ? nullptr : new int); }\n");
ASSERT_EQUALS("[test.cpp:1]: (error) Return value of allocation function 'new' is not stored.\n"
"[test.cpp:2]: (error) Return value of allocation function 'new' is not stored.\n",
errout_str());
check("void f() {\n" // #11157
" switch (*new int) { case 42: break; }\n"
" switch (*malloc(42)) { case 42: break; }\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (error) Allocation with new, switch doesn't release it.\n"
"[test.cpp:3]: (error) Allocation with malloc, switch doesn't release it.\n",
errout_str());
check("void f() {\n"
" Ref<StringBuffer> remove(new StringBuffer());\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f() {\n" // #11039
" delete new int;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f() {\n" // #11327
" int* p = (new int[3]) + 1;\n"
" delete[] &p[-1];\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void smartPointerFunctionParam() {
check("void x() {\n"
" f(shared_ptr<int>(new int(42)), g());\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning, inconclusive) Unsafe allocation. If g() throws, memory could be leaked. Use make_shared<int>() instead.\n", errout_str());
check("void x() {\n"
" h(12, f(shared_ptr<int>(new int(42)), g()));\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning, inconclusive) Unsafe allocation. If g() throws, memory could be leaked. Use make_shared<int>() instead.\n", errout_str());
check("void x() {\n"
" f(unique_ptr<int>(new int(42)), g());\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning, inconclusive) Unsafe allocation. If g() throws, memory could be leaked. Use make_unique<int>() instead.\n", errout_str());
check("void x() {\n"
" f(g(), shared_ptr<int>(new int(42)));\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning, inconclusive) Unsafe allocation. If g() throws, memory could be leaked. Use make_shared<int>() instead.\n", errout_str());
check("void x() {\n"
" f(g(), unique_ptr<int>(new int(42)));\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning, inconclusive) Unsafe allocation. If g() throws, memory could be leaked. Use make_unique<int>() instead.\n", errout_str());
check("void x() {\n"
" f(shared_ptr<char>(new char), make_unique<int>(32));\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning, inconclusive) Unsafe allocation. If make_unique<int>() throws, memory could be leaked. Use make_shared<char>() instead.\n", errout_str());
check("void x() {\n"
" f(g(124), h(\"test\", 234), shared_ptr<char>(new char));\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning, inconclusive) Unsafe allocation. If h() throws, memory could be leaked. Use make_shared<char>() instead.\n", errout_str());
check("void x() {\n"
" f(shared_ptr<std::string>(new std::string(\"\")), g<std::string>());\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning, inconclusive) Unsafe allocation. If g<std::string>() throws, memory could be leaked. Use make_shared<std::string>() instead.\n", errout_str());
check("void g(int x) throw() { }\n"
"void x() {\n"
" f(g(124), shared_ptr<char>(new char));\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void __declspec(nothrow) g(int x) { }\n"
"void x() {\n"
" f(g(124), shared_ptr<char>(new char));\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void resourceLeak() {
check("bool f(const char* name)\n" // FP: #12253
"{\n"
" FILE* fp = fopen(name, \"r\");\n"
" bool result = (fp == nullptr);\n"
" if (result) return !result;\n"
" fclose(fp);\n"
" return result;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" fopen(\"file.txt\", \"r\");\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Return value of allocation function 'fopen' is not stored.\n", errout_str());
check("void foo() {\n"
" FILE f* = fopen(\"file.txt\", \"r\");\n"
" freopen(\"file.txt\", \"r\", f);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Return value of allocation function 'freopen' is not stored.\n", errout_str());
check("void foo() {\n"
" freopen(\"file.txt\", \"r\", stdin);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct Holder {\n"
" Holder(FILE* f) : file(f) {}\n"
" ~Holder() { fclose(file); }\n"
" FILE* file;\n"
"};\n"
"void foo() {\n"
" Holder h ( fopen(\"file.txt\", \"r\"));\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct Holder {\n"
" Holder(FILE* f) : file(f) {}\n"
" ~Holder() { fclose(file); }\n"
" FILE* file;\n"
"};\n"
"void foo() {\n"
" Holder ( fopen(\"file.txt\", \"r\"));\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct Holder {\n"
" Holder(FILE* f) : file(f) {}\n"
" ~Holder() { fclose(file); }\n"
" FILE* file;\n"
"};\n"
"void foo() {\n"
" Holder h { fopen(\"file.txt\", \"r\")};\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct Holder {\n"
" Holder(FILE* f) : file(f) {}\n"
" ~Holder() { fclose(file); }\n"
" FILE* file;\n"
"};\n"
"void foo() {\n"
" Holder h = fopen(\"file.txt\", \"r\");\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct Holder {\n"
" Holder(FILE* f) : file(f) {}\n"
" ~Holder() { fclose(file); }\n"
" FILE* file;\n"
"};\n"
"void foo() {\n"
" Holder { fopen(\"file.txt\", \"r\")};\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct Holder {\n"
" Holder(int i, FILE* f) : file(f) {}\n"
" ~Holder() { fclose(file); }\n"
" FILE* file;\n"
"};\n"
"void foo() {\n"
" Holder { 0, fopen(\"file.txt\", \"r\")};\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void getAllocationType() {
// #7845
check("class Thing { Thing(); };\n"
"Thing * makeThing() { Thing *thing = new Thing; return thing; }\n"
"\n"
"void f() {\n"
" makeThing();\n"
"}");
ASSERT_EQUALS("", errout_str());
// #10631
check("struct Thing {\n"
" Thing();\n"
"};\n"
"std::vector<Thing*> g_things;\n"
"Thing* makeThing() {\n"
" Thing* n = new Thing();\n"
" return n;\n"
"}\n"
"Thing::Thing() {\n"
" g_things.push_back(this);\n"
"}\n"
"void f() {\n"
" makeThing();\n"
" for(Thing* t : g_things) {\n"
" delete t;\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void crash1() { // #10729
check("void foo() {\n"
" extern void *realloc (void *ptr, size_t size);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" extern void *malloc (size_t size);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void openDevNull() {
check("void f() {\n" // #9653
" (void)open(\"/dev/null\", O_RDONLY);\n"
" open(\"/dev/null\", O_WRONLY);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
};
REGISTER_TEST(TestMemleakNoVar)
| null |
969 | cpp | cppcheck | fixture.cpp | test/fixture.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "fixture.h"
#include "cppcheck.h"
#include "errortypes.h"
#include "helpers.h"
#include "library.h"
#include "options.h"
#include "redirect.h"
#include <algorithm>
#include <cstdio>
#include <cctype>
#include <exception>
#include <iostream>
#include <set>
#include <sstream>
#include <string>
#include "xml.h"
/**
* TestRegistry
**/
namespace {
struct CompareFixtures {
bool operator()(const TestInstance* lhs, const TestInstance* rhs) const {
return lhs->classname < rhs->classname;
}
};
}
using TestSet = std::set<TestInstance*, CompareFixtures>;
namespace {
class TestRegistry {
TestSet _tests;
public:
static TestRegistry &theInstance() {
static TestRegistry testreg;
return testreg;
}
void addTest(TestInstance *t) {
_tests.insert(t);
}
const TestSet &tests() const {
return _tests;
}
};
}
TestInstance::TestInstance(const char * _name)
: classname(_name)
{
TestRegistry::theInstance().addTest(this);
}
/**
* TestFixture
**/
std::ostringstream TestFixture::errmsg;
unsigned int TestFixture::countTests;
std::size_t TestFixture::fails_counter = 0;
std::size_t TestFixture::todos_counter = 0;
std::size_t TestFixture::succeeded_todos_counter = 0;
TestFixture::TestFixture(const char * const _name)
: classname(_name)
{}
bool TestFixture::prepareTest(const char testname[])
{
mVerbose = false;
mTemplateFormat.clear();
mTemplateLocation.clear();
CppCheck::resetTimerResults();
prepareTestInternal();
// Check if tests should be executed
if (testToRun.empty() || testToRun == testname) {
// Tests will be executed - prepare them
mTestname = testname;
++countTests;
if (quiet_tests) {
std::putchar('.'); // Use putchar to write through redirection of std::cout/cerr
std::fflush(stdout);
} else {
std::cout << classname << "::" << mTestname << std::endl;
}
return !dry_run;
}
return false;
}
void TestFixture::teardownTest()
{
teardownTestInternal();
{
const std::string s = errout_str();
if (!s.empty())
throw std::runtime_error("unconsumed ErrorLogger err: " + s);
}
{
const std::string s = output_str();
if (!s.empty())
throw std::runtime_error("unconsumed ErrorLogger out: " + s);
}
}
std::string TestFixture::getLocationStr(const char * const filename, const unsigned int linenr) const
{
return std::string(filename) + ':' + std::to_string(linenr) + '(' + classname + "::" + mTestname + ')';
}
static std::string writestr(const std::string &str, bool gccStyle = false)
{
std::ostringstream ostr;
if (gccStyle)
ostr << '\"';
for (std::string::const_iterator i = str.cbegin(); i != str.cend(); ++i) {
if (*i == '\n') {
ostr << "\\n";
if ((i+1) != str.end() && !gccStyle)
ostr << std::endl;
} else if (*i == '\t')
ostr << "\\t";
else if (*i == '\"')
ostr << "\\\"";
else if (std::isprint(static_cast<unsigned char>(*i)))
ostr << *i;
else
ostr << "\\x" << std::hex << short{*i};
}
if (!str.empty() && !gccStyle)
ostr << std::endl;
else if (gccStyle)
ostr << '\"';
return ostr.str();
}
void TestFixture::assert_(const char * const filename, const unsigned int linenr, const bool condition) const
{
if (!condition) {
++fails_counter;
errmsg << getLocationStr(filename, linenr) << ": Assertion failed." << std::endl << "_____" << std::endl;
}
}
void TestFixture::assertFailure(const char* const filename, const unsigned int linenr, const std::string& expected, const std::string& actual, const std::string& msg) const
{
++fails_counter;
errmsg << getLocationStr(filename, linenr) << ": Assertion failed. " << std::endl
<< "Expected: " << std::endl
<< writestr(expected) << std::endl
<< "Actual: " << std::endl
<< writestr(actual) << std::endl;
if (!msg.empty())
errmsg << "Hint:" << std::endl << msg << std::endl;
errmsg << "_____" << std::endl;
}
void TestFixture::assertEquals(const char * const filename, const unsigned int linenr, const std::string &expected, const std::string &actual, const std::string &msg) const
{
if (expected != actual) {
assertFailure(filename, linenr, expected, actual, msg);
}
}
std::string TestFixture::deleteLineNumber(const std::string &message)
{
std::string result(message);
// delete line number in "...:NUMBER:..."
std::string::size_type pos = 0;
while ((pos = result.find(':', pos)) != std::string::npos) {
// get number
if (pos + 1 == result.find_first_of("0123456789", pos + 1)) {
const std::string::size_type after = result.find_first_not_of("0123456789", pos + 1);
if (after != std::string::npos
&& result.at(after) == ':') {
// erase NUMBER
result.erase(pos + 1, after - pos - 1);
pos = after;
} else {
++pos;
}
} else {
++pos;
}
}
return result;
}
void TestFixture::assertEqualsWithoutLineNumbers(const char * const filename, const unsigned int linenr, const std::string &expected, const std::string &actual, const std::string &msg) const
{
assertEquals(filename, linenr, deleteLineNumber(expected), deleteLineNumber(actual), msg);
}
void TestFixture::assertEquals(const char * const filename, const unsigned int linenr, const char expected[], const std::string& actual, const std::string &msg) const
{
assertEquals(filename, linenr, std::string(expected), actual, msg);
}
void TestFixture::assertEquals(const char * const filename, const unsigned int linenr, const char expected[], const char actual[], const std::string &msg) const
{
assertEquals(filename, linenr, std::string(expected), std::string(actual), msg);
}
void TestFixture::assertEquals(const char * const filename, const unsigned int linenr, const std::string& expected, const char actual[], const std::string &msg) const
{
assertEquals(filename, linenr, expected, std::string(actual), msg);
}
void TestFixture::assertEquals(const char * const filename, const unsigned int linenr, const long long expected, const long long actual, const std::string &msg) const
{
if (expected != actual) {
assertEquals(filename, linenr, std::to_string(expected), std::to_string(actual), msg);
}
}
void TestFixture::assertEqualsDouble(const char * const filename, const unsigned int linenr, const double expected, const double actual, const double tolerance, const std::string &msg) const
{
if (expected < (actual - tolerance) || expected > (actual + tolerance)) {
std::ostringstream ostr1;
ostr1 << expected;
std::ostringstream ostr2;
ostr2 << actual;
assertEquals(filename, linenr, ostr1.str(), ostr2.str(), msg);
}
}
void TestFixture::todoAssertEquals(const char * const filename, const unsigned int linenr,
const std::string &wanted,
const std::string ¤t,
const std::string &actual) const
{
if (wanted == actual) {
errmsg << getLocationStr(filename, linenr) << ": Assertion succeeded unexpectedly. "
<< "Result: " << writestr(wanted, true) << std::endl << "_____" << std::endl;
++succeeded_todos_counter;
} else {
assertEquals(filename, linenr, current, actual);
++todos_counter;
}
}
void TestFixture::todoAssertEquals(const char* const filename, const unsigned int linenr,
const char wanted[],
const char current[],
const std::string& actual) const
{
todoAssertEquals(filename, linenr, std::string(wanted), std::string(current), actual);
}
void TestFixture::todoAssertEquals(const char * const filename, const unsigned int linenr, const long long wanted, const long long current, const long long actual) const
{
todoAssertEquals(filename, linenr, std::to_string(wanted), std::to_string(current), std::to_string(actual));
}
void TestFixture::assertThrow(const char * const filename, const unsigned int linenr) const
{
++fails_counter;
errmsg << getLocationStr(filename, linenr) << ": Assertion succeeded. "
<< "The expected exception was thrown" << std::endl << "_____" << std::endl;
}
void TestFixture::assertThrowFail(const char * const filename, const unsigned int linenr) const
{
++fails_counter;
errmsg << getLocationStr(filename, linenr) << ": Assertion failed. "
<< "The expected exception was not thrown" << std::endl << "_____" << std::endl;
}
void TestFixture::assertNoThrowFail(const char * const filename, const unsigned int linenr) const
{
++fails_counter;
std::string ex_msg;
try {
// cppcheck-suppress rethrowNoCurrentException
throw;
}
catch (const InternalError& e) {
ex_msg = e.errorMessage;
}
catch (const std::exception& e) {
ex_msg = e.what();
}
catch (...) {
ex_msg = "unknown exception";
}
errmsg << getLocationStr(filename, linenr) << ": Assertion failed. "
<< "Unexpected exception was thrown: " << ex_msg << std::endl << "_____" << std::endl;
}
void TestFixture::printHelp()
{
std::cout << "Testrunner - run Cppcheck tests\n"
"\n"
"Syntax:\n"
" testrunner [OPTIONS] [TestClass::TestCase...]\n"
" run all test cases:\n"
" testrunner\n"
" run all test cases in TestClass:\n"
" testrunner TestClass\n"
" run TestClass::TestCase:\n"
" testrunner TestClass::TestCase\n"
" run all test cases in TestClass1 and TestClass2::TestCase:\n"
" testrunner TestClass1 TestClass2::TestCase\n"
"\n"
"Options:\n"
" -q Do not print the test cases that have run.\n"
" -h, --help Print this help.\n"
" -n Print no summaries.\n"
" -d Do not execute the tests.\n";
}
void TestFixture::run(const std::string &str)
{
testToRun = str;
try {
if (quiet_tests) {
std::cout << '\n' << classname << ':';
SUPPRESS;
run();
}
else
run();
}
catch (const InternalError& e) {
++fails_counter;
errmsg << classname << "::" << mTestname << " - InternalError: " << e.errorMessage << std::endl;
}
catch (const std::exception& error) {
++fails_counter;
errmsg << classname << "::" << mTestname << " - Exception: " << error.what() << std::endl;
}
catch (...) {
++fails_counter;
errmsg << classname << "::" << mTestname << " - Unknown exception" << std::endl;
}
}
void TestFixture::processOptions(const options& args)
{
quiet_tests = args.quiet();
dry_run = args.dry_run();
exename = args.exe();
}
std::size_t TestFixture::runTests(const options& args)
{
countTests = 0;
errmsg.str("");
// TODO: bail out when given class/test is not found?
for (std::string classname : args.which_test()) {
std::string testname;
if (classname.find("::") != std::string::npos) {
testname = classname.substr(classname.find("::") + 2);
classname.erase(classname.find("::"));
}
for (TestInstance * test : TestRegistry::theInstance().tests()) {
if (classname.empty() || test->classname == classname) {
TestFixture* fixture = test->create();
fixture->processOptions(args);
fixture->run(testname);
}
}
}
if (args.summary() && !args.dry_run()) {
std::cout << "\n\nTesting Complete\nNumber of tests: " << countTests << std::endl;
std::cout << "Number of todos: " << todos_counter;
if (succeeded_todos_counter > 0)
std::cout << " (" << succeeded_todos_counter << " succeeded)";
std::cout << std::endl;
}
// calling flush here, to do all output before the error messages (in case the output is buffered)
std::cout.flush();
if (args.summary() && !args.dry_run()) {
std::cerr << "Tests failed: " << fails_counter << std::endl << std::endl;
}
std::cerr << errmsg.str();
std::cerr.flush();
return fails_counter + succeeded_todos_counter;
}
void TestFixture::reportOut(const std::string & outmsg, Color /*c*/)
{
mOutput << outmsg << std::endl;
}
void TestFixture::reportErr(const ErrorMessage &msg)
{
if (msg.severity == Severity::internal)
return;
if (msg.severity == Severity::information && msg.id == "normalCheckLevelMaxBranches")
return;
const std::string errormessage(msg.toString(mVerbose, mTemplateFormat, mTemplateLocation));
mErrout << errormessage << std::endl;
}
void TestFixture::setTemplateFormat(const std::string &templateFormat)
{
if (templateFormat == "multiline") {
mTemplateFormat = "{file}:{line}:{severity}:{message}";
mTemplateLocation = "{file}:{line}:note:{info}";
}
else if (templateFormat == "simple") { // TODO: use the existing one in CmdLineParser
mTemplateFormat = "{file}:{line}:{column}: {severity}:{inconclusive:inconclusive:} {message} [{id}]";
mTemplateLocation = "";
}
else {
mTemplateFormat = templateFormat;
mTemplateLocation = "";
}
}
TestFixture::SettingsBuilder& TestFixture::SettingsBuilder::checkLevel(Settings::CheckLevel level) {
settings.setCheckLevel(level);
return *this;
}
TestFixture::SettingsBuilder& TestFixture::SettingsBuilder::library(const char lib[]) {
if (REDUNDANT_CHECK && std::find(settings.libraries.cbegin(), settings.libraries.cend(), lib) != settings.libraries.cend())
throw std::runtime_error("redundant setting: libraries (" + std::string(lib) + ")");
// TODO: exename is not yet set
const Library::ErrorCode lib_error = settings.library.load(fixture.exename.c_str(), lib).errorcode;
if (lib_error != Library::ErrorCode::OK)
throw std::runtime_error("loading library '" + std::string(lib) + "' failed - " + std::to_string(static_cast<int>(lib_error)));
// strip extension
std::string lib_s(lib);
const std::string ext(".cfg");
const auto pos = lib_s.find(ext);
if (pos != std::string::npos)
lib_s.erase(pos, ext.size());
settings.libraries.emplace_back(lib_s);
return *this;
}
TestFixture::SettingsBuilder& TestFixture::SettingsBuilder::platform(Platform::Type type)
{
const std::string platformStr = Platform::toString(type);
if (REDUNDANT_CHECK && settings.platform.type == type)
throw std::runtime_error("redundant setting: platform (" + platformStr + ")");
std::string errstr;
// TODO: exename is not yet set
if (!settings.platform.set(platformStr, errstr, {fixture.exename}))
throw std::runtime_error("platform '" + platformStr + "' not found");
return *this;
}
TestFixture::SettingsBuilder& TestFixture::SettingsBuilder::libraryxml(const char xmldata[], std::size_t len)
{
tinyxml2::XMLDocument doc;
const tinyxml2::XMLError xml_error = doc.Parse(xmldata, len);
if (tinyxml2::XML_SUCCESS != xml_error)
throw std::runtime_error(std::string("loading library XML data failed - ") + tinyxml2::XMLDocument::ErrorIDToName(xml_error));
const Library::ErrorCode lib_error = LibraryHelper::loadxmldoc(settings.library, doc).errorcode;
if (lib_error != Library::ErrorCode::OK)
throw std::runtime_error("loading library XML failed - " + std::to_string(static_cast<int>(lib_error)));
return *this;
}
| null |
970 | cpp | cppcheck | testsingleexecutor.cpp | test/testsingleexecutor.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "cppcheck.h"
#include "filesettings.h"
#include "fixture.h"
#include "helpers.h"
#include "redirect.h"
#include "settings.h"
#include "singleexecutor.h"
#include "suppressions.h"
#include "timer.h"
#include <cstdlib>
#include <list>
#include <memory>
#include <string>
#include <utility>
#include <vector>
class TestSingleExecutorBase : public TestFixture {
protected:
TestSingleExecutorBase(const char * const name, bool useFS) : TestFixture(name), useFS(useFS) {}
private:
/*const*/ Settings settings = settingsBuilder().library("std.cfg").build();
bool useFS;
std::string fprefix() const
{
if (useFS)
return "singlefs";
return "single";
}
static std::string zpad3(int i)
{
if (i < 10)
return "00" + std::to_string(i);
if (i < 100)
return "0" + std::to_string(i);
return std::to_string(i);
}
struct CheckOptions
{
CheckOptions() = default;
bool quiet = true;
SHOWTIME_MODES showtime = SHOWTIME_MODES::SHOWTIME_NONE;
const char* plistOutput = nullptr;
std::vector<std::string> filesList;
bool clangTidy = false;
bool executeCommandCalled = false;
std::string exe;
std::vector<std::string> args;
};
void check(int files, int result, const std::string &data, const CheckOptions& opt = make_default_obj{}) {
std::list<FileSettings> fileSettings;
std::list<FileWithDetails> filelist;
if (opt.filesList.empty()) {
for (int i = 1; i <= files; ++i) {
std::string f_s = fprefix() + "_" + zpad3(i) + ".cpp";
filelist.emplace_back(f_s, data.size());
if (useFS) {
fileSettings.emplace_back(std::move(f_s), data.size());
}
}
}
else {
for (const auto& f : opt.filesList)
{
filelist.emplace_back(f, data.size());
if (useFS) {
fileSettings.emplace_back(f, data.size());
}
}
}
/*const*/ Settings s = settings;
s.showtime = opt.showtime;
s.quiet = opt.quiet;
if (opt.plistOutput)
s.plistOutput = opt.plistOutput;
s.clangTidy = opt.clangTidy;
bool executeCommandCalled = false;
std::string exe;
std::vector<std::string> args;
// NOLINTNEXTLINE(performance-unnecessary-value-param)
CppCheck cppcheck(*this, true, [&executeCommandCalled, &exe, &args](std::string e,std::vector<std::string> a,std::string,std::string&){
executeCommandCalled = true;
exe = std::move(e);
args = std::move(a);
return EXIT_SUCCESS;
});
cppcheck.settings() = s;
std::vector<std::unique_ptr<ScopedFile>> scopedfiles;
scopedfiles.reserve(filelist.size());
for (std::list<FileWithDetails>::const_iterator i = filelist.cbegin(); i != filelist.cend(); ++i)
scopedfiles.emplace_back(new ScopedFile(i->path(), data));
// clear files list so only fileSettings are used
if (useFS)
filelist.clear();
SingleExecutor executor(cppcheck, filelist, fileSettings, s, s.supprs.nomsg, *this);
ASSERT_EQUALS(result, executor.check());
ASSERT_EQUALS(opt.executeCommandCalled, executeCommandCalled);
ASSERT_EQUALS(opt.exe, exe);
ASSERT_EQUALS(opt.args.size(), args.size());
for (std::size_t i = 0; i < args.size(); ++i)
{
ASSERT_EQUALS(opt.args[i], args[i]);
}
}
void run() override {
TEST_CASE(many_files);
TEST_CASE(many_files_showtime);
TEST_CASE(many_files_plist);
TEST_CASE(no_errors_more_files);
TEST_CASE(no_errors_less_files);
TEST_CASE(no_errors_equal_amount_files);
TEST_CASE(one_error_less_files);
TEST_CASE(one_error_several_files);
TEST_CASE(clangTidy);
TEST_CASE(showtime_top5_file);
TEST_CASE(showtime_top5_summary);
TEST_CASE(showtime_file);
TEST_CASE(showtime_summary);
TEST_CASE(showtime_file_total);
TEST_CASE(suppress_error_library);
TEST_CASE(unique_errors);
}
void many_files() {
const int num_files = 100;
check(num_files, num_files,
"int main()\n"
"{\n"
" int i = *((int*)0);\n"
" return 0;\n"
"}", dinit(CheckOptions,
$.quiet = false));
{
std::string expected;
for (int i = 1; i <= num_files; ++i) {
expected += "Checking " + fprefix() + "_" + zpad3(i) + ".cpp ...\n";
expected += std::to_string(i) + "/100 files checked " + std::to_string(i) + "% done\n";
}
ASSERT_EQUALS(expected, output_str());
}
{
std::string expected;
for (int i = 1; i <= num_files; ++i) {
expected += "[" + fprefix() + "_" + zpad3(i) + ".cpp:3]: (error) Null pointer dereference: (int*)0\n";
}
ASSERT_EQUALS(expected, errout_str());
}
}
void many_files_showtime() {
SUPPRESS;
check(100, 100,
"int main()\n"
"{\n"
" int i = *((int*)0);\n"
" return 0;\n"
"}", dinit(CheckOptions, $.showtime = SHOWTIME_MODES::SHOWTIME_SUMMARY));
// we are not interested in the results - so just consume them
ignore_errout();
}
void many_files_plist() {
const std::string plistOutput = "plist_" + fprefix() + "/";
ScopedFile plistFile("dummy", "", plistOutput);
check(100, 100,
"int main()\n"
"{\n"
" int i = *((int*)0);\n"
" return 0;\n"
"}", dinit(CheckOptions, $.plistOutput = plistOutput.c_str()));
// we are not interested in the results - so just consume them
ignore_errout();
}
void no_errors_more_files() {
check(3, 0,
"int main()\n"
"{\n"
" return 0;\n"
"}");
}
void no_errors_less_files() {
check(1, 0,
"int main()\n"
"{\n"
" return 0;\n"
"}");
}
void no_errors_equal_amount_files() {
check(2, 0,
"int main()\n"
"{\n"
" return 0;\n"
"}");
}
void one_error_less_files() {
check(1, 1,
"int main()\n"
"{\n"
" {int i = *((int*)0);}\n"
" return 0;\n"
"}");
ASSERT_EQUALS("[" + fprefix() + "_" + zpad3(1) + ".cpp:3]: (error) Null pointer dereference: (int*)0\n", errout_str());
}
void one_error_several_files() {
const int num_files = 20;
check(num_files, num_files,
"int main()\n"
"{\n"
" {int i = *((int*)0);}\n"
" return 0;\n"
"}");
{
std::string expected;
for (int i = 1; i <= num_files; ++i) {
expected += "[" + fprefix() + "_" + zpad3(i) + ".cpp:3]: (error) Null pointer dereference: (int*)0\n";
}
ASSERT_EQUALS(expected, errout_str());
}
}
void clangTidy() {
// TODO: we currently only invoke it with ImportProject::FileSettings
if (!useFS)
return;
#ifdef _WIN32
constexpr char exe[] = "clang-tidy.exe";
#else
constexpr char exe[] = "clang-tidy";
#endif
const std::string file = fprefix() + "_001.cpp";
check(1, 0,
"int main()\n"
"{\n"
" return 0;\n"
"}",
dinit(CheckOptions,
$.quiet = false,
$.clangTidy = true,
$.executeCommandCalled = true,
$.exe = exe,
$.args = {"-quiet", "-checks=*,-clang-analyzer-*,-llvm*", file, "--"}));
ASSERT_EQUALS("Checking " + file + " ...\n", output_str());
}
// TODO: provide data which actually shows values above 0
void showtime_top5_file() {
REDIRECT;
check(2, 0,
"int main() {}",
dinit(CheckOptions,
$.showtime = SHOWTIME_MODES::SHOWTIME_TOP5_FILE));
const std::string output_s = GET_REDIRECT_OUTPUT;
// for each file: top5 results + overall + empty line
ASSERT_EQUALS((5 + 1 + 1) * 2LL, cppcheck::count_all_of(output_s, '\n'));
}
void showtime_top5_summary() {
REDIRECT;
check(2, 0,
"int main() {}",
dinit(CheckOptions,
$.showtime = SHOWTIME_MODES::SHOWTIME_TOP5_SUMMARY));
const std::string output_s = GET_REDIRECT_OUTPUT;
// once: top5 results + overall + empty line
ASSERT_EQUALS(5 + 1 + 1, cppcheck::count_all_of(output_s, '\n'));
// should only report the top5 once
ASSERT(output_s.find("1 result(s)") == std::string::npos);
ASSERT(output_s.find("2 result(s)") != std::string::npos);
}
void showtime_file() {
REDIRECT;
check(2, 0,
"int main() {}",
dinit(CheckOptions,
$.showtime = SHOWTIME_MODES::SHOWTIME_FILE));
const std::string output_s = GET_REDIRECT_OUTPUT;
ASSERT_EQUALS(2, cppcheck::count_all_of(output_s, "Overall time:"));
}
void showtime_summary() {
REDIRECT;
check(2, 0,
"int main() {}",
dinit(CheckOptions,
$.showtime = SHOWTIME_MODES::SHOWTIME_SUMMARY));
const std::string output_s = GET_REDIRECT_OUTPUT;
// should only report the actual summary once
ASSERT(output_s.find("1 result(s)") == std::string::npos);
ASSERT(output_s.find("2 result(s)") != std::string::npos);
}
void showtime_file_total() {
REDIRECT;
check(2, 0,
"int main() {}",
dinit(CheckOptions,
$.showtime = SHOWTIME_MODES::SHOWTIME_FILE_TOTAL));
const std::string output_s = GET_REDIRECT_OUTPUT;
ASSERT(output_s.find("Check time: " + fprefix() + "_" + zpad3(1) + ".cpp: ") != std::string::npos);
ASSERT(output_s.find("Check time: " + fprefix() + "_" + zpad3(2) + ".cpp: ") != std::string::npos);
}
void suppress_error_library() {
SUPPRESS;
const Settings settingsOld = settings;
const char xmldata[] = R"(<def format="2"><markup ext=".cpp" reporterrors="false"/></def>)";
settings = settingsBuilder().libraryxml(xmldata, sizeof(xmldata)).build();
check(1, 0,
"int main()\n"
"{\n"
" int i = *((int*)0);\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
settings = settingsOld;
}
void unique_errors() {
SUPPRESS;
ScopedFile inc_h(fprefix() + ".h",
"inline void f()\n"
"{\n"
" (void)*((int*)0);\n"
"}");
check(2, 2,
"#include \"" + inc_h.name() + "\"");
// these are not actually made unique by the implementation. That needs to be done by the given ErrorLogger
ASSERT_EQUALS(
"[" + inc_h.name() + ":3]: (error) Null pointer dereference: (int*)0\n"
"[" + inc_h.name() + ":3]: (error) Null pointer dereference: (int*)0\n",
errout_str());
}
// TODO: test whole program analysis
// TODO: test unique errors
};
class TestSingleExecutorFiles : public TestSingleExecutorBase {
public:
TestSingleExecutorFiles() : TestSingleExecutorBase("TestSingleExecutorFiles", false) {}
};
class TestSingleExecutorFS : public TestSingleExecutorBase {
public:
TestSingleExecutorFS() : TestSingleExecutorBase("TestSingleExecutorFS", true) {}
};
REGISTER_TEST(TestSingleExecutorFiles)
REGISTER_TEST(TestSingleExecutorFS)
| null |
971 | cpp | cppcheck | testsimplifytemplate.cpp | test/testsimplifytemplate.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "errortypes.h"
#include "fixture.h"
#include "helpers.h"
#include "platform.h"
#include "settings.h"
#include "templatesimplifier.h"
#include "token.h"
#include "tokenize.h"
#include "tokenlist.h"
#include <cstring>
#include <sstream>
#include <string>
#include <vector>
class TestSimplifyTemplate : public TestFixture {
public:
TestSimplifyTemplate() : TestFixture("TestSimplifyTemplate") {}
private:
// If there are unused templates, keep those
const Settings settings = settingsBuilder().severity(Severity::portability).build();
void run() override {
TEST_CASE(template1);
TEST_CASE(template2);
TEST_CASE(template3);
TEST_CASE(template4);
TEST_CASE(template5);
TEST_CASE(template6);
TEST_CASE(template7);
TEST_CASE(template8);
TEST_CASE(template9);
TEST_CASE(template10);
TEST_CASE(template11);
TEST_CASE(template12);
TEST_CASE(template13);
TEST_CASE(template14);
TEST_CASE(template15); // recursive templates
TEST_CASE(template16);
TEST_CASE(template17);
TEST_CASE(template18);
TEST_CASE(template19);
TEST_CASE(template20);
TEST_CASE(template21);
TEST_CASE(template22);
TEST_CASE(template23);
TEST_CASE(template24); // #2648 - using sizeof in template parameter
TEST_CASE(template25); // #2648 - another test for sizeof template parameter
TEST_CASE(template26); // #2721 - passing 'char[2]' as template parameter
TEST_CASE(template27); // #3350 - removing unused template in macro call
TEST_CASE(template28);
TEST_CASE(template30); // #3529 - template < template < ..
TEST_CASE(template31); // #4010 - reference type
TEST_CASE(template32); // #3818 - mismatching template not handled well
TEST_CASE(template33); // #3818,#4544 - inner templates in template instantiation not handled well
TEST_CASE(template34); // #3706 - namespace => hang
TEST_CASE(template35); // #4074 - A<'x'> a;
TEST_CASE(template36); // #4310 - passing unknown template instantiation as template argument
TEST_CASE(template37); // #4544 - A<class B> a;
TEST_CASE(template38); // #4832 - crash on C++11 right angle brackets
TEST_CASE(template39); // #4742 - freeze
TEST_CASE(template40); // #5055 - template specialization outside struct
TEST_CASE(template41); // #4710 - const in instantiation not handled perfectly
TEST_CASE(template42); // #4878 - variadic templates
TEST_CASE(template43); // #5097 - assert due to '>>' not treated as end of template instantiation
TEST_CASE(template44); // #5297 - TemplateSimplifier::simplifyCalculations not eager enough
TEST_CASE(template45); // #5814 - syntax error reported for valid code
TEST_CASE(template46); // #5816 - syntax error reported for valid code
TEST_CASE(template47); // #6023 - syntax error reported for valid code
TEST_CASE(template48); // #6134 - 100% CPU upon invalid code
TEST_CASE(template49); // #6237 - template instantiation
TEST_CASE(template50); // #4272 - simple partial specialization
TEST_CASE(template52); // #6437 - crash upon valid code
TEST_CASE(template53); // #4335 - bail out for valid code
TEST_CASE(template54); // #6587 - memory corruption upon valid code
TEST_CASE(template55); // #6604 - simplify "const const" to "const" in template instantiations
TEST_CASE(template56); // #7117 - const ternary operator simplification as template parameter
TEST_CASE(template57); // #7891
TEST_CASE(template58); // #6021 - use after free (deleted tokens in simplifyCalculations)
TEST_CASE(template59); // #8051 - TemplateSimplifier::simplifyTemplateInstantiation failure
TEST_CASE(template60); // handling of methods outside template definition
TEST_CASE(template61); // daca2, kodi
TEST_CASE(template62); // #8314 - inner template instantiation
TEST_CASE(template63); // #8576 - qualified type
TEST_CASE(template64); // #8683
TEST_CASE(template65); // #8321
TEST_CASE(template66); // #8725
TEST_CASE(template67); // #8122
TEST_CASE(template68); // union
TEST_CASE(template69); // #8791
TEST_CASE(template70); // #5289
TEST_CASE(template71); // #8821
TEST_CASE(template72);
TEST_CASE(template73);
TEST_CASE(template74);
TEST_CASE(template75);
TEST_CASE(template76);
TEST_CASE(template77);
TEST_CASE(template78);
TEST_CASE(template79); // #5133
TEST_CASE(template80);
TEST_CASE(template81);
TEST_CASE(template82); // #8603
TEST_CASE(template83); // #8867
TEST_CASE(template84); // #8880
TEST_CASE(template85); // #8902 crash
TEST_CASE(template86); // crash
TEST_CASE(template87);
TEST_CASE(template88); // #6183
TEST_CASE(template89); // #8917
TEST_CASE(template90); // crash
TEST_CASE(template91);
TEST_CASE(template92);
TEST_CASE(template93); // crash
TEST_CASE(template94); // #8927 crash
TEST_CASE(template95); // #7417
TEST_CASE(template96); // #7854
TEST_CASE(template97);
TEST_CASE(template98); // #8959
TEST_CASE(template99); // #8960
TEST_CASE(template100); // #8967
TEST_CASE(template101); // #8968
TEST_CASE(template102); // #9005
TEST_CASE(template103);
TEST_CASE(template104); // #9021
TEST_CASE(template105); // #9076
TEST_CASE(template106);
TEST_CASE(template107); // #8663
TEST_CASE(template108); // #9109
TEST_CASE(template109); // #9144
TEST_CASE(template110);
TEST_CASE(template111); // crash
TEST_CASE(template112); // #9146 syntax error
TEST_CASE(template113);
TEST_CASE(template114); // #9155
TEST_CASE(template115); // #9153
TEST_CASE(template116); // #9178
TEST_CASE(template117);
TEST_CASE(template118);
TEST_CASE(template119); // #9186
TEST_CASE(template120);
TEST_CASE(template121); // #9193
TEST_CASE(template122); // #9147
TEST_CASE(template123); // #9183
TEST_CASE(template124); // #9197
TEST_CASE(template125);
TEST_CASE(template126); // #9217
TEST_CASE(template127); // #9225
TEST_CASE(template128); // #9224
TEST_CASE(template129);
TEST_CASE(template130); // #9246
TEST_CASE(template131); // #9249
TEST_CASE(template132); // #9250
TEST_CASE(template133);
TEST_CASE(template134);
TEST_CASE(template135);
TEST_CASE(template136); // #9287
TEST_CASE(template137); // #9288
TEST_CASE(template138);
TEST_CASE(template139);
TEST_CASE(template140);
TEST_CASE(template141); // #9337
TEST_CASE(template142); // #9338
TEST_CASE(template143);
TEST_CASE(template144); // #9046
TEST_CASE(template145); // syntax error
TEST_CASE(template146); // syntax error
TEST_CASE(template147); // syntax error
TEST_CASE(template148); // syntax error
TEST_CASE(template149); // unknown macro
TEST_CASE(template150); // syntax error
TEST_CASE(template151); // crash
TEST_CASE(template152); // #9467
TEST_CASE(template153); // #9483
TEST_CASE(template154); // #9495
TEST_CASE(template155); // #9539
TEST_CASE(template156);
TEST_CASE(template157); // #9854
TEST_CASE(template158); // daca crash
TEST_CASE(template159); // #9886
TEST_CASE(template160);
TEST_CASE(template161);
TEST_CASE(template162);
TEST_CASE(template163); // #9685 syntax error
TEST_CASE(template164); // #9394
TEST_CASE(template165); // #10032 syntax error
TEST_CASE(template166); // #10081 hang
TEST_CASE(template167);
TEST_CASE(template168);
TEST_CASE(template169);
TEST_CASE(template170); // crash
TEST_CASE(template171); // crash
TEST_CASE(template172); // #10258 crash
TEST_CASE(template173); // #10332 crash
TEST_CASE(template174); // #10506 hang
TEST_CASE(template175); // #10908
TEST_CASE(template176); // #11146
TEST_CASE(template177);
TEST_CASE(template178);
TEST_CASE(template_specialization_1); // #7868 - template specialization template <typename T> struct S<C<T>> {..};
TEST_CASE(template_specialization_2); // #7868 - template specialization template <typename T> struct S<C<T>> {..};
TEST_CASE(template_specialization_3);
TEST_CASE(template_enum); // #6299 Syntax error in complex enum declaration (including template)
TEST_CASE(template_unhandled);
TEST_CASE(template_default_parameter);
TEST_CASE(template_forward_declared_default_parameter);
TEST_CASE(template_default_type);
TEST_CASE(template_typename);
TEST_CASE(template_constructor); // #3152 - template constructor is removed
TEST_CASE(syntax_error_templates_1);
TEST_CASE(template_member_ptr); // Ticket #5786 - crash upon valid code
TEST_CASE(template_namespace_1);
TEST_CASE(template_namespace_2);
TEST_CASE(template_namespace_3);
TEST_CASE(template_namespace_4);
TEST_CASE(template_namespace_5);
TEST_CASE(template_namespace_6);
TEST_CASE(template_namespace_7); // #8768
TEST_CASE(template_namespace_8);
TEST_CASE(template_namespace_9);
TEST_CASE(template_namespace_10);
TEST_CASE(template_namespace_11); // #7145
TEST_CASE(template_namespace_12);
TEST_CASE(template_pointer_type);
TEST_CASE(template_array_type);
// Test TemplateSimplifier::templateParameters
TEST_CASE(templateParameters);
TEST_CASE(templateNamePosition);
TEST_CASE(findTemplateDeclarationEnd);
TEST_CASE(getTemplateParametersInDeclaration);
TEST_CASE(expandSpecialized1);
TEST_CASE(expandSpecialized2);
TEST_CASE(expandSpecialized3); // #8671
TEST_CASE(expandSpecialized4);
TEST_CASE(expandSpecialized5); // #10494
TEST_CASE(templateAlias1);
TEST_CASE(templateAlias2);
TEST_CASE(templateAlias3); // #8315
TEST_CASE(templateAlias4); // #9070
TEST_CASE(templateAlias5);
// Test TemplateSimplifier::instantiateMatch
TEST_CASE(instantiateMatchTest);
TEST_CASE(templateParameterWithoutName); // #8602 Template default parameter without name yields syntax error
TEST_CASE(templateTypeDeduction1); // #8962
TEST_CASE(templateTypeDeduction2);
TEST_CASE(templateTypeDeduction3);
TEST_CASE(templateTypeDeduction4); // #9983
TEST_CASE(templateTypeDeduction5);
TEST_CASE(simplifyTemplateArgs1);
TEST_CASE(simplifyTemplateArgs2);
TEST_CASE(simplifyTemplateArgs3);
TEST_CASE(template_variadic_1); // #9144
TEST_CASE(template_variadic_2); // #4349
TEST_CASE(template_variadic_3); // #6172
TEST_CASE(template_variadic_4);
TEST_CASE(template_variable_1);
TEST_CASE(template_variable_2);
TEST_CASE(template_variable_3);
TEST_CASE(template_variable_4);
TEST_CASE(simplifyDecltype);
TEST_CASE(castInExpansion);
TEST_CASE(fold_expression_1);
TEST_CASE(fold_expression_2);
TEST_CASE(fold_expression_3);
TEST_CASE(fold_expression_4);
TEST_CASE(concepts1);
TEST_CASE(requires1);
TEST_CASE(requires2);
TEST_CASE(requires3);
TEST_CASE(requires4);
TEST_CASE(requires5);
TEST_CASE(explicitBool1);
TEST_CASE(explicitBool2);
}
#define tok(...) tok_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
std::string tok_(const char* file, int line, const char (&code)[size], bool debugwarnings = false, Platform::Type type = Platform::Type::Native) {
const Settings settings1 = settingsBuilder(settings).library("std.cfg").debugwarnings(debugwarnings).platform(type).build();
SimpleTokenizer tokenizer(settings1, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
return tokenizer.tokens()->stringifyList(nullptr, true);
}
void template1() {
const char code[] = "template <class T> T f(T val) { T a; }\n"
"f<int>(10);";
const char expected[] = "int f<int> ( int val ) ; "
"f<int> ( 10 ) ; "
"int f<int> ( int val ) { int a ; }";
ASSERT_EQUALS(expected, tok(code));
}
void template2() {
const char code[] = "template <class T> class Fred { T a; };\n"
"Fred<int> fred;";
const char expected[] = "class Fred<int> ; "
"Fred<int> fred ; "
"class Fred<int> { int a ; } ;";
ASSERT_EQUALS(expected, tok(code));
}
void template3() {
const char code[] = "template <class T, int sz> class Fred { T data[sz]; };\n"
"Fred<float,4> fred;";
const char expected[] = "class Fred<float,4> ; "
"Fred<float,4> fred ; "
"class Fred<float,4> { float data [ 4 ] ; } ;";
ASSERT_EQUALS(expected, tok(code));
}
void template4() {
const char code[] = "template <class T> class Fred { Fred(); };\n"
"Fred<float> fred;";
const char expected[] = "class Fred<float> ; "
"Fred<float> fred ; "
"class Fred<float> { Fred<float> ( ) ; } ;";
ASSERT_EQUALS(expected, tok(code));
}
void template5() {
const char code[] = "template <class T> class Fred { };\n"
"template <class T> Fred<T>::Fred() { }\n"
"Fred<float> fred;";
const char expected[] = "class Fred<float> ; "
"Fred<float> fred ; "
"class Fred<float> { } ; "
"Fred<float> :: Fred<float> ( ) { }";
ASSERT_EQUALS(expected, tok(code));
}
void template6() {
const char code[] = "template <class T> class Fred { };\n"
"Fred<float> fred1;\n"
"Fred<float> fred2;";
const char expected[] = "class Fred<float> ; "
"Fred<float> fred1 ; "
"Fred<float> fred2 ; "
"class Fred<float> { } ;";
ASSERT_EQUALS(expected, tok(code));
}
void template7() {
// A template class that is not used => no simplification
{
const char code[] = "template <class T>\n"
"class ABC\n"
"{\n"
"public:\n"
" typedef ABC<T> m;\n"
"};\n";
const char expected[] = "template < class T > class ABC { public: } ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "template <typename T> class ABC {\n"
"public:\n"
" typedef std::vector<T> type;\n"
"};\n"
"int main() {\n"
" ABC<int>::type v;\n"
" v.push_back(4);\n"
" return 0;\n"
"}\n";
const char wanted[] = "class ABC<int> ; "
"int main ( ) { "
"std :: vector < int > v ; "
"v . push_back ( 4 ) ; "
"return 0 ; "
"} "
"class ABC<int> { public: } ;";
const char current[] = "class ABC<int> ; "
"int main ( ) { "
"ABC<int> :: type v ; "
"v . push_back ( 4 ) ; "
"return 0 ; "
"} "
"class ABC<int> { public: } ;";
TODO_ASSERT_EQUALS(wanted, current, tok(code));
}
{
const char code[] = "template <typename T> class ABC {\n"
"public:\n"
" typedef std::vector<T> type;\n"
" void f()\n"
" {\n"
" ABC<int>::type v;\n"
" v.push_back(4);\n"
" }\n"
"};\n";
const char expected[] = "template < typename T > class ABC { "
"public: void f ( ) { "
"ABC < int > :: type v ; "
"v . push_back ( 4 ) ; "
"} "
"} ;";
ASSERT_EQUALS(expected, tok(code));
}
}
// Template definitions but no usage => no expansion
void template8() {
const char code[] = "template<typename T> class A;\n"
"template<typename T> class B;\n"
"\n"
"typedef A<int> x;\n"
"typedef B<int> y;\n"
"\n"
"template<typename T> class A {\n"
" void f() {\n"
" B<T> a = B<T>::g();\n"
" T b = 0;\n"
" if (b)\n"
" b = 0;\n"
" }\n"
"};\n"
"\n"
"template<typename T> inline B<T> h() { return B<T>(); }\n";
ASSERT_EQUALS("template < typename T > class A ; "
"template < typename T > class B ; "
"template < typename T > class A { void f ( ) { B < T > a ; a = B < T > :: g ( ) ; T b ; b = 0 ; if ( b ) { b = 0 ; } } } ; "
"template < typename T > B < T > h ( ) { return B < T > ( ) ; }", tok(code));
ASSERT_EQUALS("class A { template < typename T > int foo ( T d ) ; } ;", tok("class A{ template<typename T> int foo(T d);};"));
}
void template9() {
const char code[] = "template < typename T > class A { } ;\n"
"\n"
"void f ( ) {\n"
" A < int > a ;\n"
"}\n"
"\n"
"template < typename T >\n"
"class B {\n"
" void g ( ) {\n"
" A < T > b = A < T > :: h ( ) ;\n"
" }\n"
"} ;\n";
// The expected result..
const char expected[] = "class A<int> ; "
"void f ( ) { A<int> a ; } "
"template < typename T > class B { void g ( ) { A < T > b ; b = A < T > :: h ( ) ; } } ; "
"class A<int> { } ;";
ASSERT_EQUALS(expected, tok(code));
}
void template10() {
const char code[] = "template <int ui, typename T> T * foo()\n"
"{ return new T[ui]; }\n"
"\n"
"void f ( )\n"
"{\n"
" foo<3,int>();\n"
"}\n";
// The expected result..
const char expected[] = "int * foo<3,int> ( ) ; "
"void f ( ) "
"{"
" foo<3,int> ( ) ; "
"} "
"int * foo<3,int> ( ) { return new int [ 3 ] ; }";
ASSERT_EQUALS(expected, tok(code));
}
void template11() {
const char code[] = "template <int ui, typename T> T * foo()\n"
"{ return new T[ui]; }\n"
"\n"
"void f ( )\n"
"{\n"
" char * p = foo<3,char>();\n"
"}\n";
// The expected result..
const char expected[] = "char * foo<3,char> ( ) ; "
"void f ( ) "
"{"
" char * p ; p = foo<3,char> ( ) ; "
"} "
"char * foo<3,char> ( ) { return new char [ 3 ] ; }";
ASSERT_EQUALS(expected, tok(code));
}
void template12() {
const char code[] = "template <int x, int y, int z>\n"
"class A : public B<x, y, (x - y) ? ((y < z) ? 1 : -1) : 0>\n"
"{ };\n"
"\n"
"void f()\n"
"{\n"
" A<12,12,11> a;\n"
"}\n";
const char expected[] = "class A<12,12,11> ; "
"void f ( ) "
"{"
" A<12,12,11> a ; "
"} "
"class A<12,12,11> : public B < 12 , 12 , 0 > "
"{ } ;";
ASSERT_EQUALS(expected, tok(code));
}
void template13() {
const char code[] = "class BB {};\n"
"\n"
"template <class T>\n"
"class AA {\n"
"public:\n"
" static AA<T> create(T* newObject);\n"
" static int size();\n"
"};\n"
"\n"
"class CC { public: CC(AA<BB>, int) {} };\n"
"\n"
"class XX {\n"
" AA<CC> y;\n"
"public:\n"
" XX();\n"
"};\n"
"\n"
"XX::XX():\n"
" y(AA<CC>::create(new CC(AA<BB>(), 0)))\n"
" {}\n"
"\n"
"int yy[AA<CC>::size()];";
const char expected[] = "class BB { } ; "
"class AA<BB> ; "
"class AA<CC> ; "
"class CC { public: CC ( AA<BB> , int ) { } } ; "
"class XX { "
"AA<CC> y ; "
"public: "
"XX ( ) ; "
"} ; "
"XX :: XX ( ) : "
"y ( AA<CC> :: create ( new CC ( AA<BB> ( ) , 0 ) ) ) "
"{ } "
"int yy [ AA<CC> :: size ( ) ] ; "
"class AA<BB> { "
"public: "
"static AA<BB> create ( BB * newObject ) ; "
"static int size ( ) ; "
"} ; "
"class AA<CC> { "
"public: "
"static AA<CC> create ( CC * newObject ) ; "
"static int size ( ) ; "
"} ;";
ASSERT_EQUALS(expected, tok(code));
}
void template14() {
const char code[] = "template <> void foo<int *>()\n"
"{ x(); }\n"
"\n"
"int main()\n"
"{\n"
"foo<int*>();\n"
"}\n";
const char expected[] = "void foo<int*> ( ) ; "
"void foo<int*> ( ) "
"{ x ( ) ; } "
"int main ( ) "
"{ foo<int*> ( ) ; }";
ASSERT_EQUALS(expected, tok(code));
}
void template15() { // recursive templates #3130 etc
const char code[] = "template <unsigned int i> void a()\n"
"{\n"
" a<i-1>();\n"
"}\n"
"\n"
"template <> void a<0>()\n"
"{ }\n"
"\n"
"int main()\n"
"{\n"
" a<2>();\n"
" return 0;\n"
"}\n";
// The expected result..
const char expected[] = "void a<0> ( ) ; "
"void a<2> ( ) ; "
"void a<1> ( ) ; "
"void a<0> ( ) { } "
"int main ( ) "
"{ a<2> ( ) ; return 0 ; } "
"void a<2> ( ) { a<1> ( ) ; } "
"void a<1> ( ) { a<0> ( ) ; }";
ASSERT_EQUALS(expected, tok(code));
// #3130
const char code2[] = "template <int n> struct vec {\n"
" vec() {}\n"
" vec(const vec<n-1>& v) {}\n" // <- never used don't instantiate
"};\n"
"\n"
"vec<4> v;";
const char expected2[] = "struct vec<4> ; "
"vec<4> v ; "
"struct vec<4> { "
"vec<4> ( ) { } "
"vec<4> ( const vec < 4 - 1 > & v ) { } "
"} ;";
ASSERT_EQUALS(expected2, tok(code2));
}
void template16() {
const char code[] = "template <unsigned int i> void a()\n"
"{ }\n"
"\n"
"template <unsigned int i> void b()\n"
"{ a<i>(); }\n"
"\n"
"int main()\n"
"{\n"
" b<2>();\n"
" return 0;\n"
"}\n";
const char expected[] = "void a<2> ( ) ; "
"void b<2> ( ) ; "
"int main ( ) { b<2> ( ) ; return 0 ; } "
"void b<2> ( ) { a<2> ( ) ; } "
"void a<2> ( ) { }";
ASSERT_EQUALS(expected, tok(code));
}
void template17() {
const char code[] = "template<class T>\n"
"class Fred\n"
"{\n"
" template<class T>\n"
" static shared_ptr< Fred<T> > CreateFred()\n"
" {\n"
" }\n"
"};\n"
"\n"
"shared_ptr<int> i;\n";
const char expected[] = "template < class T > "
"class Fred "
"{ "
"template < class T > "
"static shared_ptr < Fred < T > > CreateFred ( ) "
"{ "
"} "
"} ; "
"shared_ptr < int > i ;";
ASSERT_EQUALS(expected, tok(code));
}
void template18() {
const char code[] = "template <class T> class foo { T a; };\n"
"foo<int> *f;";
const char expected[] = "class foo<int> ; "
"foo<int> * f ; "
"class foo<int> { int a ; } ;";
ASSERT_EQUALS(expected, tok(code));
}
void template19() {
const char code[] = "template <typename T> T & foo()\n"
"{ static T temp; return temp; }\n"
"\n"
"void f ( )\n"
"{\n"
" char p = foo<char>();\n"
"}\n";
// The expected result..
const char expected[] = "char & foo<char> ( ) ; "
"void f ( ) "
"{"
" char p ; p = foo<char> ( ) ; "
"} "
"char & foo<char> ( ) { static char temp ; return temp ; }";
ASSERT_EQUALS(expected, tok(code));
}
void template20() {
// Ticket #1788 - the destructor implementation is lost
const char code[] = "template <class T> class A { public: ~A(); };\n"
"template <class T> A<T>::~A() {}\n"
"A<int> a;\n";
// The expected result..
const char expected[] = "class A<int> ; "
"A<int> a ; "
"class A<int> { public: ~ A<int> ( ) ; } ; "
"A<int> :: ~ A<int> ( ) { }";
ASSERT_EQUALS(expected, tok(code));
}
void template21() {
{
const char code[] = "template <class T> struct Fred { T a; };\n"
"Fred<int> fred;";
const char expected[] = "struct Fred<int> ; "
"Fred<int> fred ; "
"struct Fred<int> { int a ; } ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "template <class T, int sz> struct Fred { T data[sz]; };\n"
"Fred<float,4> fred;";
const char expected[] = "struct Fred<float,4> ; "
"Fred<float,4> fred ; "
"struct Fred<float,4> { float data [ 4 ] ; } ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "template <class T> struct Fred { Fred(); };\n"
"Fred<float> fred;";
const char expected[] = "struct Fred<float> ; "
"Fred<float> fred ; "
"struct Fred<float> { Fred<float> ( ) ; } ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "template <class T> struct Fred { };\n"
"Fred<float> fred1;\n"
"Fred<float> fred2;";
const char expected[] = "struct Fred<float> ; "
"Fred<float> fred1 ; "
"Fred<float> fred2 ; "
"struct Fred<float> { } ;";
ASSERT_EQUALS(expected, tok(code));
}
}
void template22() {
const char code[] = "template <class T> struct Fred { T a; };\n"
"Fred<std::string> fred;";
const char expected[] = "struct Fred<std::string> ; "
"Fred<std::string> fred ; "
"struct Fred<std::string> { std :: string a ; } ;";
ASSERT_EQUALS(expected, tok(code));
}
void template23() {
const char code[] = "template <class T> void foo() { }\n"
"void bar() {\n"
" std::cout << (foo<double>());\n"
"}";
const char expected[] = "void foo<double> ( ) ; "
"void bar ( ) {"
" std :: cout << ( foo<double> ( ) ) ; "
"} "
"void foo<double> ( ) { }";
ASSERT_EQUALS(expected, tok(code));
}
void template24() {
// #2648
const char code[] = "template<int n> struct B\n"
"{\n"
" int a[n];\n"
"};\n"
"\n"
"template<int x> class bitset: B<sizeof(int)>\n"
"{};\n"
"\n"
"bitset<1> z;";
const char expected[] = "struct B<4> ; "
"class bitset<1> ; "
"bitset<1> z ; "
"class bitset<1> : B<4> { } ; "
"struct B<4> { int a [ 4 ] ; } ;";
ASSERT_EQUALS(expected, tok(code));
}
void template25() {
const char code[] = "template<int n> struct B\n"
"{\n"
" int a[n];\n"
"};\n"
"\n"
"template<int x> class bitset: B<((sizeof(int)) ? : 1)>\n"
"{};\n"
"\n"
"bitset<1> z;";
const char expected[] = "struct B<4> ; "
"class bitset<1> ; "
"bitset<1> z ; "
"class bitset<1> : B<4> { } ; "
"struct B<4> { int a [ 4 ] ; } ;";
ASSERT_EQUALS(expected, tok(code));
}
void template26() {
// #2721
const char code[] = "template<class T>\n"
"class A { public: T x; };\n"
"\n"
"template<class M>\n"
"class C: public A<char[M]> {};\n"
"\n"
"C<2> a;\n";
ASSERT_EQUALS("class A<char[2]> ; class C<2> ; C<2> a ; class C<2> : public A<char[2]> { } ; class A<char[2]> { public: char [ 2 ] x ; } ;", tok(code));
}
void template27() {
// #3350 - template inside macro call
const char code[] = "X(template<class T> class Fred);";
ASSERT_THROW_INTERNAL(tok(code), SYNTAX);
}
void template28() {
// #3226 - inner template
const char code[] = "template<class A, class B> class Fred {};\n"
"Fred<int,Fred<int,int> > x;\n";
ASSERT_EQUALS("class Fred<int,int> ; "
"class Fred<int,Fred<int,int>> ; "
"Fred<int,Fred<int,int>> x ; "
"class Fred<int,int> { } ; "
"class Fred<int,Fred<int,int>> { } ;", tok(code));
}
void template30() {
// #3529 - template < template < ..
const char code[] = "template<template<class> class A, class B> void f(){}";
ASSERT_EQUALS("template < template < class > class A , class B > void f ( ) { }", tok(code));
}
void template31() {
// #4010 - template reference type
const char code[] = "template<class T> struct A{}; A<int&> a;";
ASSERT_EQUALS("struct A<int&> ; "
"A<int&> a ; "
"struct A<int&> { } ;", tok(code));
// #7409 - rvalue
const char code2[] = "template<class T> struct A{}; A<int&&> a;";
ASSERT_EQUALS("struct A<int&&> ; "
"A<int&&> a ; "
"struct A<int&&> { } ;", tok(code2));
}
void template32() {
// #3818 - mismatching template not handled well
const char code[] = "template <class T1, class T2, class T3, class T4 > struct A { };\n"
"\n"
"template <class T>\n"
"struct B\n"
"{\n"
" public:\n"
" A < int, Pair<T, int>, int > a;\n" // mismatching parameters => don't instantiate
"};\n"
"\n"
"B<int> b;\n";
ASSERT_EQUALS("template < class T1 , class T2 , class T3 , class T4 > struct A { } ; "
"struct B<int> ; "
"B<int> b ; "
"struct B<int> { public: A < int , Pair < int , int > , int > a ; } ;", tok(code));
}
void template33() {
{
// #3818 - inner templates in template instantiation not handled well
const char code[] = "template<class T> struct A { };\n"
"template<class T> struct B { };\n"
"template<class T> struct C { A<B<X<T> > > ab; };\n"
"C<int> c;";
ASSERT_EQUALS("struct A<B<X<int>>> ; "
"struct B<X<int>> ; "
"struct C<int> ; "
"C<int> c ; "
"struct C<int> { A<B<X<int>>> ab ; } ; "
"struct B<X<int>> { } ; " // <- redundant.. but nevermind
"struct A<B<X<int>>> { } ;", tok(code));
}
{
// #4544
const char code[] = "struct A { };\n"
"template<class T> struct B { };\n"
"template<class T> struct C { };\n"
"C< B<A> > c;";
ASSERT_EQUALS("struct A { } ; "
"template < class T > struct B { } ; " // <- redundant.. but nevermind
"struct C<B<A>> ; "
"C<B<A>> c ; "
"struct C<B<A>> { } ;",
tok(code));
}
}
void template34() {
// #3706 - namespace => hang
const char code[] = "namespace abc {\n"
"template <typename T> struct X { void f(X<T> &x) {} };\n"
"}\n"
"template <> int X<int>::Y(0);";
(void)tok(code);
}
void template35() { // #4074 - "A<'x'> a;" is not recognized as template instantiation
const char code[] = "template <char c> class A {};\n"
"A <'x'> a;";
ASSERT_EQUALS("class A<'x'> ; "
"A<'x'> a ; "
"class A<'x'> { } ;", tok(code));
}
void template36() { // #4310 - Passing unknown template instantiation as template argument
const char code[] = "template <class T> struct X { T t; };\n"
"template <class C> struct Y { Foo < X< Bar<C> > > _foo; };\n" // <- Bar is unknown
"Y<int> bar;";
ASSERT_EQUALS("struct X<Bar<int>> ; "
"struct Y<int> ; "
"Y<int> bar ; "
"struct Y<int> { Foo < X<Bar<int>> > _foo ; } ; "
"struct X<Bar<int>> { Bar < int > t ; } ;",
tok(code));
}
void template37() { // #4544 - A<class B> a;
{
const char code[] = "class A { };\n"
"template<class T> class B {};\n"
"B<class A> b1;\n"
"B<A> b2;";
ASSERT_EQUALS("class A { } ; class B<A> ; B<A> b1 ; B<A> b2 ; class B<A> { } ;",
tok(code));
}
{
const char code[] = "struct A { };\n"
"template<class T> class B {};\n"
"B<struct A> b1;\n"
"B<A> b2;";
ASSERT_EQUALS("struct A { } ; class B<A> ; B<A> b1 ; B<A> b2 ; class B<A> { } ;",
tok(code));
}
{
const char code[] = "enum A { };\n"
"template<class T> class B {};\n"
"B<enum A> b1;\n"
"B<A> b2;";
ASSERT_EQUALS("enum A { } ; class B<A> ; B<A> b1 ; B<A> b2 ; class B<A> { } ;",
tok(code));
}
}
void template_unhandled() {
// An unhandled template usage should not be simplified..
ASSERT_EQUALS("x < int > ( ) ;", tok("x<int>();"));
}
void template38() { // #4832 - Crash on C++11 right angle brackets
const char code[] = "template <class T> class A {\n"
" T mT;\n"
"public:\n"
" void foo() {}\n"
"};\n"
"\n"
"int main() {\n"
" A<A<BLA>> gna1;\n"
" A<BLA> gna2;\n"
"}\n";
const char expected[] = "class A<BLA> ; "
"class A<A<BLA>> ; "
"int main ( ) { "
"A<A<BLA>> gna1 ; "
"A<BLA> gna2 ; "
"} "
"class A<BLA> { "
"BLA mT ; "
"public: "
"void foo ( ) { } "
"} ; "
"class A<A<BLA>> { "
"A<BLA> mT ; "
"public: "
"void foo ( ) { } "
"} ;";
ASSERT_EQUALS(expected, tok(code));
}
void template39() { // #4742 - Used to freeze in 1.60
const char code[] = "template<typename T> struct vector {"
" operator T() const;"
"};"
"void f() {"
" vector<vector<int>> v;"
" const vector<int> vi = static_cast<vector<int>>(v);"
"}";
(void)tok(code);
}
void template40() { // #5055 - false negatives when there is template specialization outside struct
const char code[] = "struct A {"
" template<typename T> struct X { T t; };"
"};"
"template<> struct A::X<int> { int *t; };";
const char expected[] = "struct A { "
"struct X<int> ; "
"template < typename T > struct X { T t ; } ; "
"} ; "
"struct A :: X<int> { int * t ; } ;";
ASSERT_EQUALS(expected, tok(code));
}
void template41() { // #4710 - const in template instantiation not handled perfectly
const char code1[] = "template<class T> struct X { };\n"
"void f(const X<int> x) { }";
ASSERT_EQUALS("struct X<int> ; "
"void f ( const X<int> x ) { } "
"struct X<int> { } ;", tok(code1));
const char code2[] = "template<class T> T f(T t) { return t; }\n"
"int x() { return f<int>(123); }";
ASSERT_EQUALS("int f<int> ( int t ) ; "
"int x ( ) { return f<int> ( 123 ) ; } "
"int f<int> ( int t ) { return t ; }", tok(code2));
}
void template42() { // #4878 cppcheck aborts in ext-blocks.cpp (clang testcode)
const char code[] = "template<typename ...Args>\n"
"int f0(Args ...args) {\n"
" return ^ {\n"
" return sizeof...(Args);\n"
" }() + ^ {\n"
" return sizeof...(args);\n"
" }();\n"
"}";
ASSERT_THROW_INTERNAL(tok(code), SYNTAX);
}
void template43() { // #5097 - Assert due to '>>' in 'B<A<C>>' not being treated as end of template instantiation
const char code[] = "template <typename T> struct E { typedef int Int; };\n"
"template <typename T> struct C { };\n"
"template <typename T> struct D { static int f() { return C<T>::f(); } };\n"
"template <typename T> inline int f2() { return D<T>::f(); }\n"
"template <typename T> int f1 (int x, T *) { int id = f2<T>(); return id; }\n"
"template <typename T> struct B { void f3(B<T> & other) { } };\n"
"struct A { };\n"
"template <> struct C<B<A>> {\n"
" static int f() { return f1<B<A>>(0, reinterpret_cast<B<A>*>(E<void*>::Int(-1))); }\n"
"};\n"
"int main(void) {\n"
" C<A> ca;\n"
" return 0;\n"
"}";
const char expected[] = "struct E<void*> ; "
"struct C<B<A>> ; "
"struct C<A> ; "
"struct D<B<A>> ; "
"int f2<B<A>> ( ) ; "
"int f1<B<A>> ( int x , B<A> * ) ; "
"struct B<A> ; "
"struct A { } ; "
"struct C<B<A>> { "
"static int f ( ) { "
"return f1<B<A>> ( 0 , reinterpret_cast < B<A> * > ( E<void*> :: Int ( -1 ) ) ) ; "
"} "
"} ; "
"int main ( ) { "
"C<A> ca ; "
"return 0 ; "
"} "
"struct B<A> { "
"void f3 ( B<A> & other ) { } "
"} ; "
"int f1<B<A>> ( int x , B<A> * ) { "
"int id ; id = f2<B<A>> ( ) ; "
"return id ; "
"} "
"int f2<B<A>> ( ) { "
"return D<B<A>> :: f ( ) ; "
"} "
"struct D<B<A>> { "
"static int f ( ) { "
"return C<B<A>> :: f ( ) ; "
"} "
"} ; "
"struct C<A> { } ; struct E<void*> { "
"} ;";
ASSERT_EQUALS(expected, tok(code));
}
void template44() { // #5297
const char code[] = "template<class T> struct StackContainer {"
" void foo(int i) {"
" if (0 >= 1 && i<0) {}"
" }"
"};"
"template<class T> class ZContainer : public StackContainer<T> {};"
"struct FGSTensor {};"
"class FoldedZContainer : public ZContainer<FGSTensor> {};";
const char expected[] = "struct StackContainer<FGSTensor> ; "
"class ZContainer<FGSTensor> ; "
"struct FGSTensor { } ; "
"class FoldedZContainer : public ZContainer<FGSTensor> { } ; "
"class ZContainer<FGSTensor> : public StackContainer<FGSTensor> { } ; "
"struct StackContainer<FGSTensor> { "
"void foo ( int i ) { "
"if ( 0 >= 1 && i < 0 ) { } "
"} "
"} ;";
ASSERT_EQUALS(expected, tok(code));
}
void template45() { // #5814
const char code[] = "namespace Constants { const int fourtytwo = 42; } "
"template <class T, int U> struct TypeMath { "
" static const int mult = sizeof(T) * U; "
"}; "
"template <class T> struct FOO { "
" enum { value = TypeMath<T, Constants::fourtytwo>::mult }; "
"}; "
"FOO<int> foo;";
const char expected[] = "namespace Constants { const int fourtytwo = 42 ; } "
"struct TypeMath<int,Constants::fourtytwo> ; "
"struct FOO<int> ; "
"FOO<int> foo ; "
"struct FOO<int> { "
"enum Anonymous0 { value = TypeMath<int,Constants::fourtytwo> :: mult } ; "
"} ; "
"struct TypeMath<int,Constants::fourtytwo> { "
"static const int mult = sizeof ( int ) * Constants :: fourtytwo ; "
"} ;";
ASSERT_EQUALS(expected, tok(code, true));
ASSERT_EQUALS("", errout_str());
}
void template46() { // #5816
ASSERT_NO_THROW(tok("template<class T, class U> struct A { static const int value = 0; }; "
"template <class T> struct B { "
" enum { value = A<typename T::type, int>::value }; "
"};"));
ASSERT_EQUALS("", errout_str());
ASSERT_NO_THROW(tok("template <class T, class U> struct A {}; "
"enum { e = sizeof(A<int, int>) }; "
"template <class T, class U> struct B {};"));
ASSERT_EQUALS("", errout_str());
ASSERT_NO_THROW(tok("template<class T, class U> struct A { static const int value = 0; }; "
"template<class T> struct B { typedef int type; }; "
"template <class T> struct C { "
" enum { value = A<typename B<T>::type, int>::value }; "
"};"));
ASSERT_EQUALS("", errout_str());
}
void template47() { // #6023
ASSERT_NO_THROW(tok("template <typename T1, typename T2 = T3<T1> > class C1 {}; "
"class C2 : public C1<C2> {};"));
ASSERT_EQUALS("", errout_str());
}
void template48() { // #6134 (hang)
(void)tok("template <int> int f( { } ); "
"int foo = f<1>(0);");
ASSERT_EQUALS("", errout_str());
}
void template49() { // #6237
const char code[] = "template <class T> class Fred { void f(); void g(); };\n"
"template <class T> void Fred<T>::f() { }\n"
"template <class T> void Fred<T>::g() { }\n"
"template void Fred<float>::f();\n"
"template void Fred<int>::g();\n";
const char expected[] = "class Fred<float> ; "
"class Fred<int> ; "
"class Fred<float> { void f ( ) ; void g ( ) ; } ; "
"void Fred<float> :: f ( ) { } "
"void Fred<float> :: g ( ) { } "
"class Fred<int> { void f ( ) ; void g ( ) ; } ; "
"void Fred<int> :: f ( ) { } "
"void Fred<int> :: g ( ) { }";
ASSERT_EQUALS(expected, tok(code));
}
void template50() { // #4272
const char code[] = "template <class T> class Fred { void f(); };\n"
"template <class T> void Fred<T>::f() { }\n"
"template<> void Fred<float>::f() { }\n"
"template<> void Fred<int>::f() { }\n";
const char expected[] = "class Fred<float> ; "
"class Fred<int> ; "
"template < > void Fred<float> :: f ( ) { } "
"template < > void Fred<int> :: f ( ) { } "
"class Fred<float> { void f ( ) ; } ; "
"void Fred<float> :: f ( ) { } "
"class Fred<int> { void f ( ) ; } ; "
"void Fred<int> :: f ( ) { }";
ASSERT_EQUALS(expected, tok(code));
}
void template52() { // #6437
const char code[] = "template <int value> int sum() { "
" return value + sum<value/2>(); "
"} "
"template<int x, int y> int calculate_value() { "
" if (x != y) { "
" return sum<x - y>(); "
" } else { "
" return 0; "
" } "
"} "
"int value = calculate_value<1,1>();";
const char expected[] = "int sum<0> ( ) ; "
"int calculate_value<1,1> ( ) ; "
"int value ; value = calculate_value<1,1> ( ) ; "
"int calculate_value<1,1> ( ) { "
"if ( 1 != 1 ) { "
"return sum<0> ( ) ; "
"} else { "
"return 0 ; "
"} "
"} "
"int sum<0> ( ) { "
"return 0 + sum<0> ( ) ; "
"}";
ASSERT_EQUALS(expected, tok(code));
}
void template53() { // #4335
const char code[] = "template<int N> struct Factorial { "
" enum { value = N * Factorial<N - 1>::value }; "
"};"
"template <> struct Factorial<0> { "
" enum { value = 1 }; "
"};"
"const int x = Factorial<4>::value;";
const char expected[] = "struct Factorial<0> ; "
"struct Factorial<4> ; "
"struct Factorial<3> ; "
"struct Factorial<2> ; "
"struct Factorial<1> ; "
"struct Factorial<0> { "
"enum Anonymous1 { value = 1 } ; "
"} ; "
"const int x = Factorial<4> :: value ; "
"struct Factorial<4> { "
"enum Anonymous0 { value = 4 * Factorial<3> :: value } ; "
"} ; "
"struct Factorial<3> { "
"enum Anonymous0 { value = 3 * Factorial<2> :: value } ; "
"} ; "
"struct Factorial<2> { "
"enum Anonymous0 { value = 2 * Factorial<1> :: value } ; "
"} ; "
"struct Factorial<1> { "
"enum Anonymous0 { value = 1 * Factorial<0> :: value } ; "
"} ;";
ASSERT_EQUALS(expected, tok(code, true));
ASSERT_EQUALS("", errout_str());
}
void template54() { // #6587 (use-after-free)
(void)tok("template<typename _Tp> _Tp* fn(); "
"template <class T> struct A { "
" template <class U, class S = decltype(fn<T>())> "
" struct B { }; "
"}; "
"A<int> a;");
}
void template55() { // #6604
// Avoid constconstconst in macro instantiations
ASSERT_EQUALS(
"template < class T > class AtSmartPtr : public ConstCastHelper < AtSmartPtr < const T > , T > { "
"friend struct ConstCastHelper < AtSmartPtr < const T > , T > ; "
"AtSmartPtr ( const AtSmartPtr < T > & r ) ; "
"} ;",
tok("template<class T> class AtSmartPtr : public ConstCastHelper<AtSmartPtr<const T>, T>\n"
"{\n"
" friend struct ConstCastHelper<AtSmartPtr<const T>, T>;\n"
" AtSmartPtr(const AtSmartPtr<T>& r);\n"
"};"));
// Similar problem can also happen with ...
ASSERT_EQUALS(
"struct A<int> ; "
"struct A<int...> ; "
"A<int> a ( 0 ) ; "
"struct A<int> { "
"A<int> ( int * p ) { ( A<int...> * ) ( p ) ; } "
"} ; "
"struct A<int...> { "
"A<int...> ( int * p ) { "
"( A<int...> * ) ( p ) ; "
"} } ;",
tok("template <typename... T> struct A\n"
"{\n"
" A(T* p) {\n"
" (A<T...>*)(p);\n"
" }\n"
"};\n"
"A<int> a(0);"));
}
void template56() { // #7117
const char code[] = "template<bool B> struct Foo { "
" std::array<int, B ? 1 : 2> mfoo; "
"}; "
"void foo() { "
" Foo<true> myFoo; "
"}";
const char expected[] = "struct Foo<true> ; "
"void foo ( ) { "
"Foo<true> myFoo ; "
"} struct Foo<true> { "
"std :: array < int , 1 > mfoo ; "
"} ;";
ASSERT_EQUALS(expected, tok(code, true));
ASSERT_EQUALS("", errout_str());
}
void template57() { // #7891
const char code[] = "template<class T> struct Test { Test(T); };\n"
"Test<unsigned long> test( 0 );";
const char exp[] = "struct Test<unsignedlong> ; "
"Test<unsignedlong> test ( 0 ) ; "
"struct Test<unsignedlong> { Test<unsignedlong> ( unsigned long ) ; } ;";
ASSERT_EQUALS(exp, tok(code));
}
void template58() { // #6021
const char code[] = "template <typename A>\n"
"void TestArithmetic() {\n"
" x(1 * CheckedNumeric<A>());\n"
"}\n"
"void foo() {\n"
" TestArithmetic<int>();\n"
"}";
const char exp[] = "void TestArithmetic<int> ( ) ; "
"void foo ( ) {"
" TestArithmetic<int> ( ) ; "
"} "
"void TestArithmetic<int> ( ) {"
" x ( 1 * CheckedNumeric < int > ( ) ) ; "
"}";
ASSERT_EQUALS(exp, tok(code));
}
void template59() { // #8051
const char code[] = "template<int N>\n"
"struct Factorial {\n"
" enum FacHelper { value = N * Factorial<N - 1>::value };\n"
"};\n"
"template <>\n"
"struct Factorial<0> {\n"
" enum FacHelper { value = 1 };\n"
"};\n"
"template<int DiagonalDegree>\n"
"int diagonalGroupTest() {\n"
" return Factorial<DiagonalDegree>::value;\n"
"}\n"
"int main () {\n"
" return diagonalGroupTest<4>();\n"
"}";
const char exp[] = "struct Factorial<0> ; "
"struct Factorial<4> ; "
"struct Factorial<3> ; "
"struct Factorial<2> ; "
"struct Factorial<1> ; "
"struct Factorial<0> { enum FacHelper { value = 1 } ; } ; "
"int diagonalGroupTest<4> ( ) ; "
"int main ( ) { return diagonalGroupTest<4> ( ) ; } "
"int diagonalGroupTest<4> ( ) { return Factorial<4> :: value ; } "
"struct Factorial<4> { enum FacHelper { value = 4 * Factorial<3> :: value } ; } ; "
"struct Factorial<3> { enum FacHelper { value = 3 * Factorial<2> :: value } ; } ; "
"struct Factorial<2> { enum FacHelper { value = 2 * Factorial<1> :: value } ; } ; "
"struct Factorial<1> { enum FacHelper { value = 1 * Factorial<0> :: value } ; } ;";
ASSERT_EQUALS(exp, tok(code));
}
void template60() { // Extracted from Clang testfile
const char code[] = "template <typename T> struct S { typedef int type; };\n"
"template <typename T> void f() {}\n"
"template <typename T> void h() { f<typename S<T>::type(0)>(); }\n"
"\n"
"void j() { h<int>(); }";
const char exp[] = "struct S<int> ; "
"void f<S<int>::type(0)> ( ) ; "
"void h<int> ( ) ; "
"void j ( ) { h<int> ( ) ; } "
"void h<int> ( ) { f<S<int>::type(0)> ( ) ; } "
"struct S<int> { } ; "
"void f<S<int>::type(0)> ( ) { }";
const char act[] = "template < typename T > struct S { } ; "
"void f<S<int>::type(0)> ( ) ; "
"void h<int> ( ) ; "
"void j ( ) { h<int> ( ) ; } "
"void h<int> ( ) { f<S<int>::type(0)> ( ) ; } "
"void f<S<int>::type(0)> ( ) { }";
TODO_ASSERT_EQUALS(exp, act, tok(code));
}
void template61() { // hang in daca, code extracted from kodi
const char code[] = "template <typename T> struct Foo {};\n"
"template <typename T> struct Bar {\n"
" void f1(Bar<T> x) {}\n"
" Foo<Bar<T>> f2() { }\n"
"};\n"
"Bar<int> c;";
const char exp[] = "struct Foo<Bar<int>> ; "
"struct Bar<int> ; "
"Bar<int> c ; "
"struct Bar<int> {"
" void f1 ( Bar<int> x ) { }"
" Foo<Bar<int>> f2 ( ) { } "
"} ; "
"struct Foo<Bar<int>> { } ;";
ASSERT_EQUALS(exp, tok(code));
}
void template62() { // #8314
const char code[] = "template <class T> struct C1 {};\n"
"template <class T> void f() { x = y ? C1<int>::allocate(1) : 0; }\n"
"template <class T, unsigned S> class C3 {};\n"
"template <class T, unsigned S> C3<T, S>::C3(const C3<T, S> &v) { C1<T *> c1; }\n"
"C3<int,6> c3;";
const char exp[] = "struct C1<int*> ; "
"template < class T > void f ( ) { x = y ? ( C1 < int > :: allocate ( 1 ) ) : 0 ; } "
"class C3<int,6> ; "
"C3<int,6> c3 ; "
"class C3<int,6> { } ; "
"C3<int,6> :: C3<int,6> ( const C3<int,6> & v ) { C1<int*> c1 ; } "
"struct C1<int*> { } ;";
ASSERT_EQUALS(exp, tok(code));
}
void template63() { // #8576
const char code[] = "template<class T> struct TestClass { T m_hi; };"
"TestClass<std::auto_ptr<v>> objTest3;";
const char exp[] = "struct TestClass<std::auto_ptr<v>> ; "
"TestClass<std::auto_ptr<v>> objTest3 ; "
"struct TestClass<std::auto_ptr<v>> { std :: auto_ptr < v > m_hi ; } ;";
ASSERT_EQUALS(exp, tok(code));
}
void template64() { // #8683
const char code[] = "template <typename T>\n"
"bool foo(){return true;}\n"
"struct A {\n"
"template<int n>\n"
"void t_func()\n"
"{\n"
" if( n != 0 || foo<int>());\n"
"}\n"
"void t_caller()\n"
"{\n"
" t_func<0>();\n"
" t_func<1>();\n"
"}\n"
"};";
const char exp[] = "bool foo<int> ( ) ; "
"struct A { "
"void t_func<0> ( ) ; "
"void t_func<1> ( ) ; "
"void t_caller ( ) "
"{ "
"t_func<0> ( ) ; "
"t_func<1> ( ) ; "
"} "
"} ; "
"void A :: t_func<0> ( ) "
"{ "
"if ( 0 != 0 || foo<int> ( ) ) { ; } "
"} "
"void A :: t_func<1> ( ) "
"{ "
"if ( 1 != 0 || foo<int> ( ) ) { ; } "
"} "
"bool foo<int> ( ) { return true ; }";
ASSERT_EQUALS(exp, tok(code));
}
void template65() { // #8321 (crash)
const char code[] = "namespace bpp\n"
"{\n"
"template<class N, class E, class DAGraphImpl>\n"
"class AssociationDAGraphImplObserver :\n"
" public AssociationGraphImplObserver<N, E, DAGraphImpl>\n"
"{};\n"
"template<class N, class E>\n"
"using AssociationDAGlobalGraphObserver = AssociationDAGraphImplObserver<N, E, DAGlobalGraph>;\n"
"}\n"
"using namespace bpp;\n"
"using namespace std;\n"
"int main() {\n"
" AssociationDAGlobalGraphObserver<string,unsigned int> grObs;\n"
" return 1;\n"
"}";
const char exp[] = "namespace bpp "
"{ "
"class AssociationDAGraphImplObserver<string,unsignedint,DAGlobalGraph> ; "
"} "
"using namespace bpp ; "
"int main ( ) { "
"bpp :: AssociationDAGraphImplObserver<string,unsignedint,DAGlobalGraph> grObs ; "
"return 1 ; "
"} class bpp :: AssociationDAGraphImplObserver<string,unsignedint,DAGlobalGraph> : "
"public AssociationGraphImplObserver < std :: string , unsigned int , DAGlobalGraph > "
"{ } ;";
ASSERT_EQUALS(exp, tok(code));
}
void template66() { // #8725
const char code[] = "template <class T> struct Fred {\n"
" const int ** foo();\n"
"};\n"
"template <class T> const int ** Fred<T>::foo() { return nullptr; }\n"
"Fred<int> fred;";
const char exp[] = "struct Fred<int> ; "
"Fred<int> fred ; "
"struct Fred<int> { "
"const int * * foo ( ) ; "
"} ; "
"const int * * Fred<int> :: foo ( ) { return nullptr ; }";
ASSERT_EQUALS(exp, tok(code));
}
void template67() { // ticket #8122
const char code[] = "template <class T> struct Container {\n"
" Container();\n"
" Container(const Container &);\n"
" Container & operator = (const Container &);\n"
" ~Container();\n"
" T* mElements;\n"
" const Container * c;\n"
"};\n"
"template <class T> Container<T>::Container() : mElements(nullptr), c(nullptr) {}\n"
"template <class T> Container<T>::Container(const Container & x) { nElements = x.nElements; c = x.c; }\n"
"template <class T> Container<T> & Container<T>::operator = (const Container & x) { mElements = x.mElements; c = x.c; return *this; }\n"
"template <class T> Container<T>::~Container() {}\n"
"Container<int> intContainer;";
const char expected[] = "struct Container<int> ; "
"Container<int> intContainer ; "
"struct Container<int> { "
"Container<int> ( ) ; "
"Container<int> ( const Container<int> & ) ; "
"Container<int> & operator= ( const Container<int> & ) ; "
"~ Container<int> ( ) ; "
"int * mElements ; "
"const Container<int> * c ; "
"} ; "
"Container<int> :: Container<int> ( ) : mElements ( nullptr ) , c ( nullptr ) { } "
"Container<int> :: Container<int> ( const Container<int> & x ) { nElements = x . nElements ; c = x . c ; } "
"Container<int> & Container<int> :: operator= ( const Container<int> & x ) { mElements = x . mElements ; c = x . c ; return * this ; } "
"Container<int> :: ~ Container<int> ( ) { }";
ASSERT_EQUALS(expected, tok(code));
}
void template68() {
const char code[] = "template <class T> union Fred {\n"
" char dummy[sizeof(T)];\n"
" T value;\n"
"};\n"
"Fred<int> fred;";
const char exp[] = "union Fred<int> ; "
"Fred<int> fred ; "
"union Fred<int> { "
"char dummy [ sizeof ( int ) ] ; "
"int value ; "
"} ;";
ASSERT_EQUALS(exp, tok(code));
}
void template69() { // #8791
const char code[] = "class Test {\n"
" int test;\n"
" template <class T> T lookup() { return test; }\n"
" int Fun() { return lookup<int>(); }\n"
"};";
const char exp[] = "class Test { "
"int test ; "
"int lookup<int> ( ) ; "
"int Fun ( ) { return lookup<int> ( ) ; } "
"} ; "
"int Test :: lookup<int> ( ) { return test ; }";
ASSERT_EQUALS(exp, tok(code));
}
void template70() { // #5289
const char code[] = "template<typename T, typename V, int KeySize = 0> class Bar;\n"
"template<>\n"
"class Bar<void, void> {\n"
"};\n"
"template<typename K, typename V, int KeySize>\n"
"class Bar : private Bar<void, void> {\n"
" void foo() { }\n"
"};";
const char exp[] = "template < typename T , typename V , int KeySize = 0 > class Bar ; "
"class Bar<void,void> ; "
"class Bar<void,void> { "
"} ; "
"template < typename K , typename V , int KeySize = 0 > "
"class Bar : private Bar<void,void> { "
"void foo ( ) { } "
"} ;";
const char act[] = "template < typename T , typename V , int KeySize = 0 > class Bar ; "
"class Bar<void,void> { "
"} ; "
"class Bar<void,void> ; "
"template < typename K , typename V , int KeySize = 0 > "
"class Bar : private Bar<void,void> { "
"void foo ( ) { } "
"} ;";
TODO_ASSERT_EQUALS(exp, act, tok(code));
}
void template71() { // #8821
const char code[] = "int f1(int * pInterface, int x) { return 0; }\n"
"\n"
"template< class interface_type > class Reference {\n"
" template< class interface_type > int i();\n"
" int *pInterface;\n"
"};\n"
"\n"
"template< class interface_type > int Reference< interface_type >::i() {\n"
" return f1(pInterface, interface_type::static_type());\n"
"}\n"
"\n"
"Reference< class XPropertyList > dostuff();";
const char exp[] = "int f1 ( int * pInterface , int x ) { return 0 ; } "
"class Reference<XPropertyList> ; "
"Reference<XPropertyList> dostuff ( ) ; "
"class Reference<XPropertyList> { template < class XPropertyList > int i ( ) ; int * pInterface ; } ; "
"int Reference<XPropertyList> :: i ( ) { return f1 ( pInterface , XPropertyList :: static_type ( ) ) ; }";
ASSERT_EQUALS(exp, tok(code));
}
void template72() {
const char code[] = "template <typename N, typename P> class Tokenizer;\n"
"const Tokenizer<Node, Path> *tokenizer() const;\n"
"template <typename N, typename P>\n"
"Tokenizer<N, P>::Tokenizer() { }";
const char exp[] = "template < typename N , typename P > class Tokenizer ; "
"const Tokenizer < Node , Path > * tokenizer ( ) const ; "
"template < typename N , typename P > "
"Tokenizer < N , P > :: Tokenizer ( ) { }";
ASSERT_EQUALS(exp, tok(code));
}
void template73() {
const char code[] = "template<typename T>\n"
"void keep_range(T& value, const T mini, const T maxi){}\n"
"template void keep_range<float>(float& v, const float l, const float u);\n"
"template void keep_range<int>(int& v, const int l, const int u);";
const char exp[] = "void keep_range<float> ( float & value , const float mini , const float maxi ) ; "
"void keep_range<int> ( int & value , const int mini , const int maxi ) ; "
"void keep_range<float> ( float & value , const float mini , const float maxi ) { } "
"void keep_range<int> ( int & value , const int mini , const int maxi ) { }";
ASSERT_EQUALS(exp, tok(code));
}
void template74() {
const char code[] = "template <class T> class BTlist { };\n"
"class PushBackStreamBuf {\n"
"public:\n"
" void pushBack(const BTlist<int> &vec);\n"
"};";
const char exp[] = "class BTlist<int> ; "
"class PushBackStreamBuf { "
"public: "
"void pushBack ( const BTlist<int> & vec ) ; "
"} ; "
"class BTlist<int> { } ;";
ASSERT_EQUALS(exp, tok(code));
}
void template75() {
const char code[] = "template<typename T>\n"
"T foo(T& value){ return value; }\n"
"template std::vector<std::vector<int>> foo<std::vector<std::vector<int>>>(std::vector<std::vector<int>>& v);";
const char exp[] = "std :: vector < std :: vector < int > > foo<std::vector<std::vector<int>>> ( std :: vector < std :: vector < int > > & value ) ; "
"std :: vector < std :: vector < int > > foo<std::vector<std::vector<int>>> ( std :: vector < std :: vector < int > > & value ) { return value ; }";
ASSERT_EQUALS(exp, tok(code));
}
void template76() {
const char code[] = "namespace NS {\n"
" template<typename T> T foo(T& value) { return value; }\n"
" template std::vector<std::vector<int>> foo<std::vector<std::vector<int>>>(std::vector<std::vector<int>>& v);\n"
"}\n"
"std::vector<std::vector<int>> v;\n"
"v = foo<std::vector<std::vector<int>>>(v);\n";
const char exp[] = "namespace NS { "
"std :: vector < std :: vector < int > > foo<std::vector<std::vector<int>>> ( std :: vector < std :: vector < int > > & value ) ; "
"} "
"std :: vector < std :: vector < int > > v ; "
"v = foo<std::vector<std::vector<int>>> ( v ) ; "
"std :: vector < std :: vector < int > > NS :: foo<std::vector<std::vector<int>>> ( std :: vector < std :: vector < int > > & value ) { return value ; }";
ASSERT_EQUALS(exp, tok(code));
}
void template77() {
const char code[] = "template<typename T>\n"
"struct is_void : std::false_type { };\n"
"template<>\n"
"struct is_void<void> : std::true_type { };\n"
"int main() {\n"
" std::cout << is_void<char>::value << std::endl;\n"
" std::cout << is_void<void>::value << std::endl;\n"
"}";
const char exp[] = "struct is_void<void> ; "
"struct is_void<char> ; "
"struct is_void<void> : std :: true_type { } ; "
"int main ( ) { "
"std :: cout << is_void<char> :: value << std :: endl ; "
"std :: cout << is_void<void> :: value << std :: endl ; "
"} "
"struct is_void<char> : std :: false_type { } ;";
ASSERT_EQUALS(exp, tok(code));
}
void template78() {
const char code[] = "template <typename>\n"
"struct Base { };\n"
"struct S : Base <void>::Type { };";
const char exp[] = "struct Base<void> ; "
"struct S : Base<void> :: Type { } ; "
"struct Base<void> { } ;";
ASSERT_EQUALS(exp, tok(code));
}
void template79() { // #5133
const char code[] = "class Foo {\n"
"public:\n"
" template<typename T> void foo() { bar<T>(); }\n"
"private:\n"
" template<typename T> void bar() { bazz(); }\n"
" void bazz() { }\n"
"};\n"
"void some_func() {\n"
" Foo x;\n"
" x.foo<int>();\n"
"}";
const char exp[] = "class Foo { "
"public: "
"void foo<int> ( ) ; "
"private: "
"void bar<int> ( ) ; "
"void bazz ( ) { } "
"} ; "
"void some_func ( ) { "
"Foo x ; "
"x . foo<int> ( ) ; "
"} "
"void Foo :: foo<int> ( ) { bar<int> ( ) ; } "
"void Foo :: bar<int> ( ) { bazz ( ) ; }";
ASSERT_EQUALS(exp, tok(code));
}
void template80() {
const char code[] = "class Fred {\n"
" template <typename T> T foo(T t) const { return t; }\n"
"};\n"
"const void * p = Fred::foo<const void *>(nullptr);";
const char exp[] = "class Fred { "
"const void * foo<constvoid*> ( const void * t ) const ; "
"} ; "
"const void * p ; p = Fred :: foo<constvoid*> ( nullptr ) ; "
"const void * Fred :: foo<constvoid*> ( const void * t ) const { return t ; }";
ASSERT_EQUALS(exp, tok(code));
}
void template81() {
const char code[] = "template <typename Type>\n"
"struct SortWith {\n"
" SortWith(Type);\n"
"};\n"
"template <typename Type>\n"
"SortWith<Type>::SortWith(Type) {}\n"
"int main() {\n"
" SortWith<int>(0);\n"
"}";
const char exp[] = "template < typename Type > "
"struct SortWith { "
"SortWith ( Type ) ; "
"} ; "
"SortWith<int> :: SortWith<int> ( int ) ; "
"int main ( ) { "
"SortWith<int> ( 0 ) ; "
"} "
"SortWith<int> :: SortWith<int> ( int ) { }";
ASSERT_EQUALS(exp, tok(code));
}
void template82() { // 8603
const char code[] = "typedef int comp;\n"
"const int f16=16;\n"
"template<int x>\n"
"class tvec2 {};\n"
"template<int x>\n"
"class tvec3 {};\n"
"namespace swizzle {\n"
"template <comp> void swizzle(tvec2<f16> v) { }\n"
"template <comp x, comp y> void swizzle(tvec3<f16> v) { }\n"
"}\n"
"void foo() {\n"
" using namespace swizzle;\n"
" tvec2<f16> tt2;\n"
" swizzle<1>(tt2);\n"
" tvec3<f16> tt3;\n"
" swizzle<2,3>(tt3);\n"
"}";
const char exp[] = "const int f16 = 16 ; "
"class tvec2<f16> ; "
"class tvec3<f16> ; "
"namespace swizzle { "
"void swizzle<1> ( tvec2<f16> v ) ; "
"void swizzle<2,3> ( tvec3<f16> v ) ; "
"} "
"void foo ( ) { "
"using namespace swizzle ; "
"tvec2<f16> tt2 ; "
"swizzle :: swizzle<1> ( tt2 ) ; "
"tvec3<f16> tt3 ; "
"swizzle :: swizzle<2,3> ( tt3 ) ; "
"} "
"void swizzle :: swizzle<2,3> ( tvec3<f16> v ) { } "
"void swizzle :: swizzle<1> ( tvec2<f16> v ) { } "
"class tvec3<f16> { } ; "
"class tvec2<f16> { } ;";
ASSERT_EQUALS(exp, tok(code));
}
void template83() { // #8867
const char code[] = "template<typename Task>\n"
"class MultiConsumer {\n"
" MultiConsumer();\n"
"};\n"
"template<typename Task>\n"
"MultiConsumer<Task>::MultiConsumer() : sizeBuffer(0) {}\n"
"MultiReads::MultiReads() {\n"
" mc = new MultiConsumer<reads_packet>();\n"
"}";
const char exp[] = "template < typename Task > " // TODO: this should be expanded
"class MultiConsumer { "
"MultiConsumer ( ) ; "
"} ; "
"MultiConsumer<reads_packet> :: MultiConsumer<reads_packet> ( ) ; "
"MultiReads :: MultiReads ( ) { "
"mc = new MultiConsumer<reads_packet> ( ) ; "
"} "
"MultiConsumer<reads_packet> :: MultiConsumer<reads_packet> ( ) : sizeBuffer ( 0 ) { }";
ASSERT_EQUALS(exp, tok(code));
}
void template84() { // #8880
{
const char code[] = "template <class b, int c, class>\n"
"auto d() -> typename a<decltype(b{})>::e {\n"
" d<int, c, int>();\n"
"}";
const char exp[] = "template < class b , int c , class > "
"auto d ( ) . a < decltype ( b { } ) > :: e { "
"d < int , c , int > ( ) ; "
"}";
ASSERT_EQUALS(exp, tok(code));
}
{
const char code[] = "template <class b, int c, class>\n"
"auto d() -> typename a<decltype(b{})>::e {\n"
" d<int, c, int>();\n"
"}"
"void foo() { d<char, 1, int>(); }";
const char exp[] = "auto d<char,1,int> ( ) . a < char > :: e ; "
"auto d<int,1,int> ( ) . a < int > :: e ; "
"void foo ( ) { d<char,1,int> ( ) ; } "
"auto d<char,1,int> ( ) . a < char > :: e { "
"d<int,1,int> ( ) ; "
"} "
"auto d<int,1,int> ( ) . a < int > :: e { "
"d<int,1,int> ( ) ; "
"}";
ASSERT_EQUALS(exp, tok(code));
}
}
void template85() { // #8902 - crash
const char code[] = "template<typename T>\n"
"struct C\n"
"{\n"
" template<typename U, typename std::enable_if<(!std::is_fundamental<U>::value)>::type* = nullptr>\n"
" void foo();\n"
"};\n"
"extern template void C<int>::foo<int, nullptr>();\n"
"template<typename T>\n"
"template<typename U, typename std::enable_if<(!std::is_fundamental<U>::value)>::type>\n"
"void C<T>::foo() {}";
// @todo the output is very wrong but we are only worried about the crash for now
(void)tok(code);
}
void template86() { // crash
const char code[] = "struct S {\n"
" S();\n"
"};\n"
"template <typename T>\n"
"struct U {\n"
" static S<T> u;\n"
"};\n"
"template <typename T>\n"
"S<T> U<T>::u;\n"
"template S<int> U<int>::u;\n"
"S<int> &i = U<int>::u;";
(void)tok(code);
}
void template87() {
const char code[] = "template<typename T>\n"
"T f1(T t) { return t; }\n"
"template const char * f1<const char *>(const char *);\n"
"template const char & f1<const char &>(const char &);";
const char exp[] = "const char * f1<constchar*> ( const char * t ) ; "
"const char & f1<constchar&> ( const char & t ) ; "
"const char * f1<constchar*> ( const char * t ) { return t ; } "
"const char & f1<constchar&> ( const char & t ) { return t ; }";
ASSERT_EQUALS(exp, tok(code));
}
void template88() { // #6183.cpp
const char code[] = "class CTest {\n"
"public:\n"
" template <typename T>\n"
" static void Greeting(T val) {\n"
" std::cout << val << std::endl;\n"
" }\n"
"private:\n"
" static void SayHello() {\n"
" std::cout << \"Hello World!\" << std::endl;\n"
" }\n"
"};\n"
"template<>\n"
"void CTest::Greeting(bool) {\n"
" CTest::SayHello();\n"
"}\n"
"int main() {\n"
" CTest::Greeting<bool>(true);\n"
" return 0;\n"
"}";
const char exp[] = "class CTest { "
"public: "
"static void Greeting<bool> ( bool ) ; "
"template < typename T > "
"static void Greeting ( T val ) { "
"std :: cout << val << std :: endl ; "
"} "
"private: "
"static void SayHello ( ) { "
"std :: cout << \"Hello World!\" << std :: endl ; "
"} "
"} ; "
"void CTest :: Greeting<bool> ( bool ) { "
"CTest :: SayHello ( ) ; "
"} "
"int main ( ) { "
"CTest :: Greeting<bool> ( true ) ; "
"return 0 ; "
"}";
ASSERT_EQUALS(exp, tok(code));
}
void template89() { // #8917
const char code[] = "struct Fred {\n"
" template <typename T> static void foo() { }\n"
"};\n"
"template void Fred::foo<char>();\n"
"template void Fred::foo<float>();\n"
"template <> void Fred::foo<bool>() { }\n"
"template <> void Fred::foo<int>() { }";
const char exp[] = "struct Fred { "
"static void foo<int> ( ) ; "
"static void foo<bool> ( ) ; "
"static void foo<char> ( ) ; "
"static void foo<float> ( ) ; "
"} ; "
"void Fred :: foo<bool> ( ) { } "
"void Fred :: foo<int> ( ) { } "
"void Fred :: foo<char> ( ) { } "
"void Fred :: foo<float> ( ) { }";
ASSERT_EQUALS(exp, tok(code));
}
void template90() { // crash
const char code[] = "template <typename T> struct S1 {};\n"
"void f(S1<double>) {}\n"
"template <typename T>\n"
"decltype(S1<T>().~S1<T>()) fun1() {};";
const char exp[] = "struct S1<double> ; "
"void f ( S1<double> ) { } "
"template < typename T > "
"decltype ( S1 < T > ( ) . ~ S1 < T > ( ) ) fun1 ( ) { } ; "
"struct S1<double> { } ;";
ASSERT_EQUALS(exp, tok(code));
}
void template91() {
{
const char code[] = "template<typename T> T foo(T t) { return t; }\n"
"template<> char foo<char>(char a) { return a; }\n"
"template<> int foo<int>(int a) { return a; }\n"
"template float foo<float>(float);\n"
"template double foo<double>(double);";
const char exp[] = "int foo<int> ( int a ) ; "
"char foo<char> ( char a ) ; "
"float foo<float> ( float t ) ; "
"double foo<double> ( double t ) ; "
"char foo<char> ( char a ) { return a ; } "
"int foo<int> ( int a ) { return a ; } "
"float foo<float> ( float t ) { return t ; } "
"double foo<double> ( double t ) { return t ; }";
ASSERT_EQUALS(exp, tok(code));
}
{
const char code[] = "struct Fred {\n"
" template<typename T> T foo(T t) { return t; }\n"
" template<> char foo<char>(char a) { return a; }\n"
" template<> int foo<int>(int a) { return a; }\n"
"};\n"
"template float Fred::foo<float>(float);\n"
"template double Fred::foo<double>(double);";
const char exp[] = "struct Fred { "
"int foo<int> ( int a ) ; "
"char foo<char> ( char a ) ; "
"float foo<float> ( float t ) ; "
"double foo<double> ( double t ) ; "
"char foo<char> ( char a ) { return a ; } "
"int foo<int> ( int a ) { return a ; } "
"} ; "
"float Fred :: foo<float> ( float t ) { return t ; } "
"double Fred :: foo<double> ( double t ) { return t ; }";
ASSERT_EQUALS(exp, tok(code));
}
{
const char code[] = "namespace NS1 {\n"
" namespace NS2 {\n"
" template<typename T> T foo(T t) { return t; }\n"
" template<> char foo<char>(char a) { return a; }\n"
" template<> int foo<int>(int a) { return a; }\n"
" template short NS2::foo<short>(short);\n"
" template long NS1::NS2::foo<long>(long);\n"
" }\n"
" template float NS2::foo<float>(float);\n"
" template bool NS1::NS2::foo<bool>(bool);\n"
"}\n"
"template double NS1::NS2::foo<double>(double);";
const char exp[] = "namespace NS1 { "
"namespace NS2 { "
"int foo<int> ( int a ) ; "
"char foo<char> ( char a ) ; "
"short foo<short> ( short t ) ; "
"long foo<long> ( long t ) ; "
"float foo<float> ( float t ) ; "
"bool foo<bool> ( bool t ) ; "
"double foo<double> ( double t ) ; "
"char foo<char> ( char a ) { return a ; } "
"int foo<int> ( int a ) { return a ; } "
"} "
"} "
"short NS1 :: NS2 :: foo<short> ( short t ) { return t ; } "
"long NS1 :: NS2 :: foo<long> ( long t ) { return t ; } "
"float NS1 :: NS2 :: foo<float> ( float t ) { return t ; } "
"bool NS1 :: NS2 :: foo<bool> ( bool t ) { return t ; } "
"double NS1 :: NS2 :: foo<double> ( double t ) { return t ; }";
ASSERT_EQUALS(exp, tok(code));
}
{
const char code[] = "namespace NS1 {\n"
" namespace NS {\n"
" template<typename T> T foo(T t) { return t; }\n"
" template<> char foo<char>(char a) { return a; }\n"
" template<> int foo<int>(int a) { return a; }\n"
" template short NS::foo<short>(short);\n"
" template long NS1::NS::foo<long>(long);\n"
" }\n"
" template float NS::foo<float>(float);\n"
" template bool NS1::NS::foo<bool>(bool);\n"
"}\n"
"template double NS1::NS::foo<double>(double);";
const char exp[] = "namespace NS1 { "
"namespace NS { "
"int foo<int> ( int a ) ; "
"char foo<char> ( char a ) ; "
"short foo<short> ( short t ) ; "
"long foo<long> ( long t ) ; "
"float foo<float> ( float t ) ; "
"bool foo<bool> ( bool t ) ; "
"double foo<double> ( double t ) ; "
"char foo<char> ( char a ) { return a ; } "
"int foo<int> ( int a ) { return a ; } "
"} "
"} "
"short NS1 :: NS :: foo<short> ( short t ) { return t ; } "
"long NS1 :: NS :: foo<long> ( long t ) { return t ; } "
"float NS1 :: NS :: foo<float> ( float t ) { return t ; } "
"bool NS1 :: NS :: foo<bool> ( bool t ) { return t ; } "
"double NS1 :: NS :: foo<double> ( double t ) { return t ; }";
ASSERT_EQUALS(exp, tok(code));
}
}
void template92() {
const char code[] = "template<class T> void foo(T const& t) { }\n"
"template<> void foo<double>(double const& d) { }\n"
"template void foo<float>(float const& f);\n"
"int main() {\n"
" foo<int>(2);\n"
" foo<double>(3.14);\n"
" foo<float>(3.14f);\n"
"}";
const char exp[] = "void foo<double> ( const double & d ) ; "
"void foo<float> ( const float & t ) ; "
"void foo<int> ( const int & t ) ; "
"void foo<double> ( const double & d ) { } "
"int main ( ) { "
"foo<int> ( 2 ) ; "
"foo<double> ( 3.14 ) ; "
"foo<float> ( 3.14f ) ; "
"} "
"void foo<float> ( const float & t ) { } "
"void foo<int> ( const int & t ) { }";
ASSERT_EQUALS(exp, tok(code));
}
void template93() { // crash
const char code[] = "template <typename Iterator>\n"
"void ForEach() { }\n"
"template <typename Type>\n"
"class Vector2 : public Vector {\n"
" template <typename Iterator>\n"
" void ForEach();\n"
"public:\n"
" void process();\n"
"};\n"
"template <typename Type>\n"
"void Vector2<Type>::process() {\n"
" ForEach<iterator>();\n"
"}\n"
"Vector2<string> c;";
const char exp[] = "void ForEach<iterator> ( ) ; "
"class Vector2<string> ; "
"Vector2<string> c ; "
"class Vector2<string> : public Vector { "
"template < typename Iterator > "
"void ForEach ( ) ; "
"public: "
"void process ( ) ; "
"} ; "
"void Vector2<string> :: process ( ) { "
"ForEach<iterator> ( ) ; "
"} "
"void ForEach<iterator> ( ) { "
"}";
ASSERT_EQUALS(exp, tok(code));
}
void template94() { // #8927 crash
const char code[] = "template <typename T>\n"
"class Array { };\n"
"template<typename T>\n"
"Array<T> foo() {};\n"
"template <> Array<double> foo<double>() { }\n"
"template <> Array<std::complex<float>> foo<std::complex<float>>() { }\n"
"template <> Array<float> foo<float>() { }\n"
"template < typename T >\n"
"Array<T> matmul() {\n"
" return foo<T>( );\n"
"}\n"
"template Array<std::complex<float>> matmul<std::complex<float>>();";
const char exp[] = "class Array<double> ; "
"class Array<std::complex<float>> ; "
"class Array<float> ; "
"Array<float> foo<float> ( ) ; "
"Array<std::complex<float>> foo<std::complex<float>> ( ) ; "
"Array<double> foo<double> ( ) ; "
"template < typename T > "
"Array < T > foo ( ) { } ; "
"Array<double> foo<double> ( ) { } "
"Array<std::complex<float>> foo<std::complex<float>> ( ) { } "
"Array<float> foo<float> ( ) { } "
"Array<std::complex<float>> matmul<std::complex<float>> ( ) ; "
"Array<std::complex<float>> matmul<std::complex<float>> ( ) { "
"return foo<std::complex<float>> ( ) ; "
"} "
"class Array<double> { } ; "
"class Array<std::complex<float>> { } ; "
"class Array<float> { } ;";
ASSERT_EQUALS(exp, tok(code));
}
void template95() { // #7417
const char code[] = "template <typename T>\n"
"T Value = 123;\n"
"template<>\n"
"int Value<int> = 456;\n"
"float f = Value<float>;\n"
"int i = Value<int>;";
const char exp[] = "float Value<float> ; Value<float> = 123 ; "
"int Value<int> ; Value<int> = 456 ; "
"float f ; f = Value<float> ; "
"int i ; i = Value<int> ;";
ASSERT_EQUALS(exp, tok(code));
}
void template96() { // #7854
{
const char code[] = "template<unsigned int n>\n"
" constexpr long fib = fib<n-1> + fib<n-2>;\n"
"template<>\n"
" constexpr long fib<0> = 0;\n"
"template<>\n"
" constexpr long fib<1> = 1;\n"
"long f0 = fib<0>;\n"
"long f1 = fib<1>;\n"
"long f2 = fib<2>;\n"
"long f3 = fib<3>;";
const char exp[] = "constexpr long fib<2> = fib<1> + fib<0> ; "
"constexpr long fib<3> = fib<2> + fib<1> ; "
"constexpr long fib<0> = 0 ; "
"constexpr long fib<1> = 1 ; "
"long f0 ; f0 = fib<0> ; "
"long f1 ; f1 = fib<1> ; "
"long f2 ; f2 = fib<2> ; "
"long f3 ; f3 = fib<3> ;";
ASSERT_EQUALS(exp, tok(code));
}
{
const char code[] = "template<unsigned int n>\n"
" constexpr long fib = fib<n-1> + fib<n-2>;\n"
"template<>\n"
" constexpr long fib<0> = 0;\n"
"template<>\n"
" constexpr long fib<1> = 1;\n"
"long f5 = fib<5>;\n";
const char exp[] = "constexpr long fib<5> = fib<4> + fib<3> ; "
"constexpr long fib<4> = fib<3> + fib<2> ; "
"constexpr long fib<3> = fib<2> + fib<1> ; "
"constexpr long fib<2> = fib<1> + fib<0> ; "
"constexpr long fib<0> = 0 ; "
"constexpr long fib<1> = 1 ; "
"long f5 ; f5 = fib<5> ;";
ASSERT_EQUALS(exp, tok(code));
}
}
void template97() {
const char code[] ="namespace NS1 {\n"
" namespace NS2 {\n"
" namespace NS3 {\n"
" namespace NS4 {\n"
" template<class T>\n"
" class Fred {\n"
" T * t;\n"
" public:\n"
" Fred<T>() : t(nullptr) {}\n"
" };\n"
" }\n"
" using namespace NS4;\n"
" Fred<bool> fred_bool;\n"
" NS4::Fred<char> fred_char;\n"
" }\n"
" using namespace NS3;\n"
" NS4::Fred<short> fred_short;\n"
" using namespace NS3::NS4;\n"
" Fred<int> fred_int;\n"
" NS3::NS4::Fred<long> fred_long;\n"
" NS2::NS3::NS4::Fred<float> fred_float;\n"
" NS1::NS2::NS3::NS4::Fred<double> fred_double;\n"
" }\n"
" using namespace NS2;\n"
" NS3::NS4::Fred<float> fred_float1;\n"
" NS2::NS3::NS4::Fred<double> fred_double1;\n"
"}\n"
"using namespace NS1::NS2::NS3::NS4;\n"
"Fred<bool> fred_bool1;\n"
"NS1::NS2::NS3::NS4::Fred<int> fred_int1;";
const char exp[] = "namespace NS1 { "
"namespace NS2 { "
"namespace NS3 { "
"namespace NS4 { "
"class Fred<bool> ; "
"class Fred<char> ; "
"class Fred<short> ; "
"class Fred<int> ; "
"class Fred<long> ; "
"class Fred<float> ; "
"class Fred<double> ; "
"} "
"using namespace NS4 ; "
"NS4 :: Fred<bool> fred_bool ; "
"NS4 :: Fred<char> fred_char ; "
"} "
"using namespace NS3 ; "
"NS3 :: NS4 :: Fred<short> fred_short ; "
"using namespace NS3 :: NS4 ; "
"NS3 :: NS4 :: Fred<int> fred_int ; "
"NS3 :: NS4 :: Fred<long> fred_long ; "
"NS2 :: NS3 :: NS4 :: Fred<float> fred_float ; "
"NS1 :: NS2 :: NS3 :: NS4 :: Fred<double> fred_double ; "
"} "
"using namespace NS2 ; "
"NS2 :: NS3 :: NS4 :: Fred<float> fred_float1 ; "
"NS2 :: NS3 :: NS4 :: Fred<double> fred_double1 ; "
"} "
"using namespace NS1 :: NS2 :: NS3 :: NS4 ; "
"NS1 :: NS2 :: NS3 :: NS4 :: Fred<bool> fred_bool1 ; "
"NS1 :: NS2 :: NS3 :: NS4 :: Fred<int> fred_int1 ; "
"class NS1 :: NS2 :: NS3 :: NS4 :: Fred<bool> { "
"bool * t ; "
"public: "
"Fred<bool> ( ) : t ( nullptr ) { } "
"} ; "
"class NS1 :: NS2 :: NS3 :: NS4 :: Fred<char> { "
"char * t ; "
"public: "
"Fred<char> ( ) : t ( nullptr ) { } "
"} ; "
"class NS1 :: NS2 :: NS3 :: NS4 :: Fred<short> { "
"short * t ; "
"public: "
"Fred<short> ( ) : t ( nullptr ) { } "
"} ; "
"class NS1 :: NS2 :: NS3 :: NS4 :: Fred<int> { "
"int * t ; "
"public: "
"Fred<int> ( ) : t ( nullptr ) { } "
"} ; "
"class NS1 :: NS2 :: NS3 :: NS4 :: Fred<long> { "
"long * t ; "
"public: "
"Fred<long> ( ) : t ( nullptr ) { } "
"} ; "
"class NS1 :: NS2 :: NS3 :: NS4 :: Fred<float> { "
"float * t ; "
"public: "
"Fred<float> ( ) : t ( nullptr ) { } "
"} ; "
"class NS1 :: NS2 :: NS3 :: NS4 :: Fred<double> { "
"double * t ; "
"public: "
"Fred<double> ( ) : t ( nullptr ) { } "
"} ;";
ASSERT_EQUALS(exp, tok(code));
}
void template98() { // #8959
const char code[] = "template <typename T>\n"
"using unique_ptr_with_deleter = std::unique_ptr<T, std::function<void(T*)>>;\n"
"class A {};\n"
"static void func() {\n"
" unique_ptr_with_deleter<A> tmp(new A(), [](A* a) {\n"
" delete a;\n"
" });\n"
"}";
const char exp[] = "class A { } ; "
"static void func ( ) { "
"std :: unique_ptr < A , std :: function < void ( A * ) > > tmp ( new A ( ) , [ ] ( A * a ) { "
"delete a ; "
"} ) ; "
"}";
ASSERT_EQUALS(exp, tok(code));
}
void template99() { // #8960
const char code[] = "template <typename T>\n"
"class Base {\n"
"public:\n"
" using ArrayType = std::vector<Base<T>>;\n"
"};\n"
"using A = Base<int>;\n"
"static A::ArrayType array;\n";
const char exp[] = "class Base<int> ; "
"static std :: vector < Base<int> > array ; "
"class Base<int> { "
"public: "
"} ;";
ASSERT_EQUALS(exp, tok(code));
}
void template100() { // #8967
const char code[] = "enum class Device { I2C0, I2C1 };\n"
"template <Device D>\n"
"const char* deviceFile;\n"
"template <>\n"
"const char* deviceFile<Device::I2C0> = \"/tmp/i2c-0\";\n";
const char exp[] = "enum class Device { I2C0 , I2C1 } ; "
"template < Device D > "
"const char * deviceFile ; "
"const char * deviceFile<Device::I2C0> ; deviceFile<Device::I2C0> = \"/tmp/i2c-0\" ;";
ASSERT_EQUALS(exp, tok(code));
}
void template101() { // #8968
const char code[] = "class A {\n"
"public:\n"
" using ArrayType = std::vector<int>;\n"
" void func(typename ArrayType::size_type i) {\n"
" }\n"
"};";
const char exp[] = "class A { "
"public: "
"void func ( std :: vector < int > :: size_type i ) { "
"} "
"} ;";
ASSERT_EQUALS(exp, tok(code));
ASSERT_EQUALS("", errout_str());
}
void template102() { // #9005
const char code[] = "namespace ns {\n"
"template <class T>\n"
"struct is_floating_point\n"
": std::integral_constant<bool, std::is_floating_point<T>::value || true>\n"
"{};\n"
"}\n"
"void f() {\n"
" if(std::is_floating_point<float>::value) {}\n"
"}";
const char exp[] = "namespace ns { "
"template < class T > "
"struct is_floating_point "
": std :: integral_constant < bool , std :: is_floating_point < T > :: value || true > "
"{ } ; "
"} "
"void f ( ) { "
"if ( std :: is_floating_point < float > :: value ) { } "
"}";
ASSERT_EQUALS(exp, tok(code));
}
void template103() {
const char code[] = "namespace sample {\n"
" template <typename T>\n"
" class Sample {\n"
" public:\n"
" T function(T t);\n"
" };\n"
" template <typename T>\n"
" T Sample<T>::function(T t) {\n"
" return t;\n"
" }\n"
"}\n"
"sample::Sample<int> s1;";
const char exp[] = "namespace sample { "
"class Sample<int> ; "
"} "
"sample :: Sample<int> s1 ; "
"class sample :: Sample<int> { "
"public: "
"int function ( int t ) ; "
"} ; "
"int sample :: Sample<int> :: function ( int t ) { "
"return t ; "
"}";
ASSERT_EQUALS(exp, tok(code));
}
void template104() { // #9021
const char code[] = "template < int i >\n"
"auto key ( ) { return hana :: test :: ct_eq < i > { } ; }\n"
"template < int i >\n"
"auto val ( ) { return hana :: test :: ct_eq < - i > { } ; }\n"
"template < int i , int j >\n"
"auto p ( ) { return :: minimal_product ( key < i > ( ) , val < j > ( ) ) ; }\n"
"int main ( ) {\n"
" BOOST_HANA_CONSTANT_CHECK ( hana :: equal (\n"
" hana :: at_key ( hana :: make_map ( p < 0 , 0 > ( ) ) , key < 0 > ( ) ) ,\n"
" val < 0 > ( ) ) ) ;\n"
"}";
const char exp[] = "auto key<0> ( ) ; "
"auto val<0> ( ) ; "
"auto p<0,0> ( ) ; "
"int main ( ) { "
"BOOST_HANA_CONSTANT_CHECK ( hana :: equal ( "
"hana :: at_key ( hana :: make_map ( p<0,0> ( ) ) , key<0> ( ) ) , "
"val<0> ( ) ) ) ; "
"} "
"auto p<0,0> ( ) { return :: minimal_product ( key<0> ( ) , val<0> ( ) ) ; } "
"auto val<0> ( ) { return hana :: test :: ct_eq < - 0 > { } ; } "
"auto key<0> ( ) { return hana :: test :: ct_eq < 0 > { } ; }";
ASSERT_EQUALS(exp, tok(code));
}
void template105() { // #9076
const char code[] = "template <template <typename> class TOUT> class ObjectCache;\n"
"template <template <typename> class TOUT>\n"
"class ObjectCache { };\n"
"template <typename T> class Fred {};\n"
"ObjectCache<Fred> _cache;";
const char exp[] = "class ObjectCache<Fred> ; "
"template < typename T > class Fred { } ; "
"ObjectCache<Fred> _cache ; class ObjectCache<Fred> { } ;";
ASSERT_EQUALS(exp, tok(code));
}
void template106() {
const char code[] = "template<class T, class U> class A {\n"
"public:\n"
" int x;\n"
"};\n"
"template<template<class T, class U> class V> class B {\n"
" V<char, char> i;\n"
"};\n"
"B<A> c;";
const char exp[] = "class A<char,char> ; "
"class B<A> ; "
"B<A> c ; "
"class B<A> { "
"A<char,char> i ; "
"} ; class A<char,char> { "
"public: "
"int x ; "
"} ;";
ASSERT_EQUALS(exp, tok(code));
}
void template107() { // #8663
const char code[] = "template <class T1, class T2>\n"
"void f() {\n"
" using T3 = typename T1::template T3<T2>;\n"
" T3 t;\n"
"}\n"
"struct C3 {\n"
" template <typename T>\n"
" class T3\n"
" {};\n"
"};\n"
"void foo() {\n"
" f<C3, long>();\n"
"}";
const char exp[] = "void f<C3,long> ( ) ; "
"struct C3 { "
"class T3<long> ; "
"} ; "
"void foo ( ) { "
"f<C3,long> ( ) ; "
"} "
"void f<C3,long> ( ) { "
"C3 :: T3<long> t ; "
"} "
"class C3 :: T3<long> { } ;";
ASSERT_EQUALS(exp, tok(code));
}
void template108() { // #9109
{
const char code[] = "template <typename> struct a;\n"
"template <typename> struct b {};\n"
"template <typename> struct c;\n"
"template <typename d> struct e {\n"
" using f = a<b<typename c<d>::g>>;\n"
" bool h = f::h;\n"
"};\n"
"struct i {\n"
" e<int> j();\n"
"};\n";
const char exp[] = "template < typename > struct a ; "
"struct b<c<int>::g> ; "
"template < typename > struct c ; "
"struct e<int> ; "
"struct i { e<int> j ( ) ; "
"} ; "
"struct e<int> { bool h ; "
"h = a < b<c<int>::g> > :: h ; "
"} ; "
"struct b<c<int>::g> { } ;";
ASSERT_EQUALS(exp, tok(code));
}
{
const char code[] = "namespace {\n"
"template <typename> struct a;\n"
"template <typename> struct b {};\n"
"}\n"
"namespace {\n"
"template <typename> struct c;\n"
"template <typename d> struct e {\n"
" using f = a<b<typename c<d>::g>>;\n"
" bool h = f::h;\n"
"};\n"
"template <typename i> using j = typename e<i>::g;\n"
"}";
const char exp[] = "namespace { "
"template < typename > struct a ; "
"template < typename > struct b { } ; "
"} "
"namespace { "
"template < typename > struct c ; "
"template < typename d > struct e { "
"using f = a < b < c < d > :: g > > ; "
"bool h ; h = f :: h ; "
"} ; "
"template < typename i > using j = typename e < i > :: g ; "
"}";
ASSERT_EQUALS(exp, tok(code));
}
{
const char code[] = "namespace {\n"
"template <typename> struct a;\n"
"template <typename> struct b {};\n"
"}\n"
"namespace {\n"
"template <typename> struct c;\n"
"template <typename d> struct e {\n"
" using f = a<b<typename c<d>::g>>;\n"
" bool h = f::h;\n"
"};\n"
"template <typename i> using j = typename e<i>::g;\n"
"}\n"
"j<int> foo;";
const char exp[] = "namespace { "
"template < typename > struct a ; "
"struct b<c<int>::g> ; "
"} "
"namespace { "
"template < typename > struct c ; "
"struct e<int> ; "
"} "
"e<int> :: g foo ; "
"struct e<int> { "
"bool h ; h = a < b<c<int>::g> > :: h ; "
"} ; "
"struct b<c<int>::g> { } ;";
ASSERT_EQUALS(exp, tok(code));
}
}
void template109() { // #9144
{
const char code[] = "namespace a {\n"
"template <typename b, bool = __is_empty(b) && __is_final(b)> struct c;\n"
"}\n"
"template <typename...> struct e {};\n"
"static_assert(sizeof(e<>) == sizeof(e<c<int>, c<int>, int>), \"\");\n";
const char exp[] = "namespace a { "
"template < typename b , bool > struct c ; "
"} "
"struct e<> ; "
"struct e<c<int>,c<int>,int> ; "
"static_assert ( sizeof ( e<> ) == sizeof ( e<c<int>,c<int>,int> ) , \"\" ) ; "
"struct e<> { } ; "
"struct e<c<int>,c<int>,int> { } ;";
ASSERT_EQUALS(exp, tok(code));
}
{
const char code[] = "namespace a {\n"
"template <typename b, bool = __is_empty(b) && __is_final(b)> struct c;\n"
"}\n"
"template <typename...> struct e {};\n"
"static_assert(sizeof(e<>) == sizeof(e<a::c<int>, a::c<int>, int>), \"\");\n";
const char exp[] = "namespace a { "
"template < typename b , bool > struct c ; "
"} "
"struct e<> ; "
"struct e<a::c<int,std::is_empty<int>{}&&std::is_final<int>{}>,a::c<int,std::is_empty<int>{}&&std::is_final<int>{}>,int> ; "
"static_assert ( sizeof ( e<> ) == sizeof ( e<a::c<int,std::is_empty<int>{}&&std::is_final<int>{}>,a::c<int,std::is_empty<int>{}&&std::is_final<int>{}>,int> ) , \"\" ) ; "
"struct e<> { } ; "
"struct e<a::c<int,std::is_empty<int>{}&&std::is_final<int>{}>,a::c<int,std::is_empty<int>{}&&std::is_final<int>{}>,int> { } ;";
ASSERT_EQUALS(exp, tok(code));
}
{
const char code[] = "template <typename b, bool = __is_empty(b) && __is_final(b)> struct c;\n"
"template <typename...> struct e {};\n"
"static_assert(sizeof(e<>) == sizeof(e<c<int>, c<int>, int>), \"\");\n";
const char exp[] = "template < typename b , bool > struct c ; "
"struct e<> ; "
"struct e<c<int,std::is_empty<int>{}&&std::is_final<int>{}>,c<int,std::is_empty<int>{}&&std::is_final<int>{}>,int> ; "
"static_assert ( sizeof ( e<> ) == sizeof ( e<c<int,std::is_empty<int>{}&&std::is_final<int>{}>,c<int,std::is_empty<int>{}&&std::is_final<int>{}>,int> ) , \"\" ) ; "
"struct e<> { } ; "
"struct e<c<int,std::is_empty<int>{}&&std::is_final<int>{}>,c<int,std::is_empty<int>{}&&std::is_final<int>{}>,int> { } ;";
ASSERT_EQUALS(exp, tok(code));
}
{
const char code[] = "template <typename b, bool = __is_empty(b) && __is_final(b)> struct c{};\n"
"c<int> cc;\n";
const char exp[] = "struct c<int,std::is_empty<int>{}&&std::is_final<int>{}> ; "
"c<int,std::is_empty<int>{}&&std::is_final<int>{}> cc ; "
"struct c<int,std::is_empty<int>{}&&std::is_final<int>{}> { } ;";
ASSERT_EQUALS(exp, tok(code));
}
{
const char code[] = "template <typename b, bool = unknown1(b) && unknown2(b)> struct c{};\n"
"c<int> cc;\n";
const char exp[] = "struct c<int,unknown1(int)&&unknown2(int)> ; "
"c<int,unknown1(int)&&unknown2(int)> cc ; "
"struct c<int,unknown1(int)&&unknown2(int)> { } ;";
ASSERT_EQUALS(exp, tok(code));
}
}
void template110() {
const char code[] = "template<typename T> using A = int;\n"
"template<typename T> using A<T*> = char;\n"
"template<> using A<char> = char;\n"
"template using A<char> = char;\n"
"using A<char> = char;";
const char exp[] = "template < typename T > using A = int ; "
"template < typename T > using A < T * > = char ; "
"template < > using A < char > = char ; "
"template using A < char > = char ; "
"using A < char > = char ;";
ASSERT_EQUALS(exp, tok(code));
}
void template111() { // crash
const char code[] = "template<typename T, typename U> struct pair;\n"
"template<typename T> using cell = pair<T*, cell<T>*>;";
const char exp[] = "template < typename T , typename U > struct pair ; "
"template < typename T > using cell = pair < T * , cell < T > * > ;";
ASSERT_EQUALS(exp, tok(code));
}
void template112() { // #9146 syntax error
const char code[] = "template <int> struct a;\n"
"template <class, class b> using c = typename a<int{b::d}>::e;\n"
"template <class> struct f;\n"
"template <class b> using g = typename f<c<int, b>>::e;";
const char exp[] = "template < int > struct a ; "
"template < class , class b > using c = typename a < int { b :: d } > :: e ; "
"template < class > struct f ; "
"template < class b > using g = typename f < c < int , b > > :: e ;";
ASSERT_EQUALS(exp, tok(code));
}
void template113() {
{
const char code[] = "template <class> class A { void f(); };\n"
"A<int> a;";
const char exp[] = "class A<int> ; "
"A<int> a ; "
"class A<int> { void f ( ) ; } ;";
ASSERT_EQUALS(exp, tok(code));
}
{
const char code[] = "template <struct> struct A { void f(); };\n"
"A<int> a;";
const char exp[] = "struct A<int> ; "
"A<int> a ; "
"struct A<int> { void f ( ) ; } ;";
ASSERT_EQUALS(exp, tok(code));
}
}
void template114() { // #9155
{
const char code[] = "template <typename a, a> struct b {};\n"
"template <typename> struct c;\n"
"template <typename> struct d : b<bool, std::is_polymorphic<int>{}> {};\n"
"template <bool> struct e;\n"
"template <typename a> using f = typename e<c<d<a>>::g>::h;";
const char exp[] = "template < typename a , a > struct b { } ; "
"template < typename > struct c ; "
"template < typename > struct d : b < bool , std :: is_polymorphic < int > { } > { } ; "
"template < bool > struct e ; "
"template < typename a > using f = typename e < c < d < a > > :: g > :: h ;";
ASSERT_EQUALS(exp, tok(code));
}
{
const char code[] = "template <typename a, a> struct b;\n"
"template <bool, typename> struct c;\n"
"template <typename a> struct d : b<bool, std::is_empty<a>{}> {};\n"
"template <typename a> using e = typename c<std::is_final<a>{}, d<a>>::f;\n";
const char exp[] = "template < typename a , a > struct b ; "
"template < bool , typename > struct c ; "
"template < typename a > struct d : b < bool , std :: is_empty < a > { } > { } ; "
"template < typename a > using e = typename c < std :: is_final < a > { } , d < a > > :: f ;";
ASSERT_EQUALS(exp, tok(code));
}
}
void template115() { // #9153
const char code[] = "namespace {\n"
" namespace b {\n"
" template <int c> struct B { using B<c / 2>::d; };\n"
" }\n"
" template <class, class> using e = typename b::B<int{}>;\n"
" namespace b {\n"
" template <class> struct f {};\n"
" }\n"
" template <class c> using g = b::f<e<int, c>>;\n"
"}\n"
"g<int> g1;";
const char exp[] = "namespace { "
"namespace b { "
"struct B<0> ; "
"} "
"namespace b { "
"struct f<b::B<0>> ; "
"} "
"} "
"b :: f<b::B<0>> g1 ; struct b :: B<0> { using d = B<0> :: d ; } ; "
"struct b :: f<b::B<0>> { } ;";
ASSERT_EQUALS(exp, tok(code));
}
void template116() { // #9178
{
const char code[] = "template <class, class a> auto b() -> decltype(a{}.template b<void(int, int)>);\n"
"template <class, class a> auto b() -> decltype(a{}.template b<void(int, int)>){}";
const char exp[] = "template < class , class a > auto b ( ) . decltype ( a { } . template b < void ( int , int ) > ) ; "
"template < class , class a > auto b ( ) . decltype ( a { } . template b < void ( int , int ) > ) { }";
ASSERT_EQUALS(exp, tok(code));
}
{
const char code[] = "template <class, class a>\n"
"auto b() -> decltype(a{}.template b<void(int, int)>()) {}\n"
"struct c {\n"
" template <class> void b();\n"
"};\n"
"void d() { b<c, c>(); }";
const char exp[] = "auto b<c,c> ( ) . decltype ( c { } . template b < void ( int , int ) > ( ) ) ; "
"struct c { "
"template < class > void b ( ) ; "
"} ; "
"void d ( ) { b<c,c> ( ) ; } "
"auto b<c,c> ( ) . decltype ( c { } . template b < void ( int , int ) > ( ) ) { }";
ASSERT_EQUALS(exp, tok(code));
}
}
void template117() {
const char code[] = "template<typename T = void> struct X {};\n"
"X<X<>> x;";
const char exp[] = "struct X<void> ; "
"struct X<X<void>> ; "
"X<X<void>> x ; "
"struct X<void> { } ; "
"struct X<X<void>> { } ;";
ASSERT_EQUALS(exp, tok(code));
}
void template118() {
const char code[] = "template<int> struct S { void f(int i); };\n"
"S<1> s;";
const char exp[] = "struct S<1> ; "
"S<1> s ; struct S<1> { "
"void f ( int i ) ; "
"} ;";
ASSERT_EQUALS(exp, tok(code));
}
void template119() { // #9186
{
const char code[] = "template <typename T>\n"
"constexpr auto func = [](auto x){ return T(x);};\n"
"template <typename T>\n"
"constexpr auto funcBraced = [](auto x){ return T{x};};\n"
"double f(int x) { return func<double>(x); }\n"
"double fBraced(int x) { return funcBraced<int>(x); }";
const char exp[] = "constexpr auto func<double> = [ ] ( auto x ) { return double ( x ) ; } ; "
"constexpr auto funcBraced<int> = [ ] ( auto x ) { return int { x } ; } ; "
"double f ( int x ) { return func<double> ( x ) ; } "
"double fBraced ( int x ) { return funcBraced<int> ( x ) ; }";
ASSERT_EQUALS(exp, tok(code));
}
{
const char code[] = "template <typename T>\n"
"constexpr auto func = [](auto x){ return T(x);};\n"
"void foo() {\n"
" func<int>(x);\n"
" func<double>(x);\n"
"}";
const char exp[] = "constexpr auto func<int> = [ ] ( auto x ) { return int ( x ) ; } ; "
"constexpr auto func<double> = [ ] ( auto x ) { return double ( x ) ; } ; "
"void foo ( ) { "
"func<int> ( x ) ; "
"func<double> ( x ) ; "
"}";
ASSERT_EQUALS(exp, tok(code));
}
}
void template120() {
const char code[] = "template<typename Tuple>\n"
"struct lambda_context {\n"
" template<typename Sig> struct result;\n"
" template<typename This, typename I>\n"
" struct result<This(terminal, placeholder)> : at<Tuple, I> {};\n"
"};\n"
"template<typename T>\n"
"struct lambda {\n"
" template<typename Sig> struct result;\n"
" template<typename This>\n"
" struct result<This()> : lambda_context<tuple<> > {};\n"
"};\n"
"lambda<int> l;";
const char exp[] = "template < typename Tuple > "
"struct lambda_context { "
"template < typename Sig > struct result ; "
"template < typename This , typename I > "
"struct result < This ( terminal , placeholder ) > : at < Tuple , I > { } ; "
"} ; "
"struct lambda<int> ; "
"lambda<int> l ; struct lambda<int> { "
"template < typename Sig > struct result ; "
"template < typename This > "
"struct result < This ( ) > : lambda_context < tuple < > > { } ; "
"} ;";
ASSERT_EQUALS(exp, tok(code));
}
void template121() { // #9193
const char code[] = "template <class VALUE_T, class LIST_T = std::list<VALUE_T>>\n"
"class TestList { };\n"
"TestList<std::shared_ptr<int>> m_test;";
const char exp[] = "class TestList<std::shared_ptr<int>,std::list<std::shared_ptr<int>>> ; "
"TestList<std::shared_ptr<int>,std::list<std::shared_ptr<int>>> m_test ; "
"class TestList<std::shared_ptr<int>,std::list<std::shared_ptr<int>>> { } ;";
ASSERT_EQUALS(exp, tok(code));
}
void template122() { // #9147
const char code[] = "template <class...> struct a;\n"
"namespace {\n"
"template <class, class> struct b;\n"
"template <template <class> class c, class... f, template <class...> class d>\n"
"struct b<c<f...>, d<>>;\n"
"}\n"
"void e() { using c = a<>; }";
const char exp[] = "template < class ... > struct a ; "
"namespace { "
"template < class , class > struct b ; "
"template < template < class > class c , class ... f , template < class ... > class d > "
"struct b < c < f ... > , d < > > ; "
"} "
"void e ( ) { }";
ASSERT_EQUALS(exp, tok(code));
}
void template123() { // #9183
const char code[] = "template <class...> struct a;\n"
"namespace {\n"
"template <class, class, class, class>\n"
"struct b;\n"
"template <template <class> class c, class... d, template <class> class e, class... f>\n"
"struct b<c<d...>, e<f...>>;\n"
"}\n"
"void fn1() {\n"
" using c = a<>;\n"
" using e = a<>;\n"
"}";
const char exp[] = "template < class ... > struct a ; "
"namespace { "
"template < class , class , class , class > "
"struct b ; "
"template < template < class > class c , class ... d , template < class > class e , class ... f > "
"struct b < c < d ... > , e < f ... > > ; "
"} "
"void fn1 ( ) { "
"}";
ASSERT_EQUALS(exp, tok(code));
}
void template124() { // #9197
const char code[] = "template <bool> struct a;\n"
"template <bool b> using c = typename a<b>::d;\n"
"template <typename> struct e;\n"
"template <typename> struct h {\n"
" template <typename... f, c<h<e<typename f::d...>>::g>> void i();\n"
"};";
const char exp[] = "template < bool > struct a ; "
"template < bool b > using c = typename a < b > :: d ; "
"template < typename > struct e ; "
"template < typename > struct h { "
"template < typename ... f , c < h < e < typename f :: d ... > > :: g > > void i ( ) ; "
"} ;";
ASSERT_EQUALS(exp, tok(code));
}
void template125() {
ASSERT_THROW_INTERNAL(tok("template<int M, int N>\n"
"class GCD {\n"
"public:\n"
" enum { val = (N == 0) ? M : GCD<N, M % N>::val };\n"
"};\n"
"int main() {\n"
" GCD< 1, 0 >::val;\n"
"}"), INSTANTIATION);
}
void template126() { // #9217
const char code[] = "template <typename b> using d = a<b>;\n"
"static_assert(i<d<l<b>>>{}, \"\");";
const char exp[] = "static_assert ( i < a < l < b > > > { } , \"\" ) ;";
ASSERT_EQUALS(exp, tok(code));
}
void template127() { // #9225
{
const char code[] = "template <typename> struct a {\n"
" template <typename b> constexpr decltype(auto) operator()(b &&) const;\n"
"};\n"
"a<int> c;\n"
"template <typename d>\n"
"template <typename b>\n"
"constexpr decltype(auto) a<d>::operator()(b &&) const {}";
const char exp[] = "struct a<int> ; "
"a<int> c ; "
"template < typename d > "
"template < typename b > "
"constexpr decltype ( auto ) a < d > :: operator() ( b && ) const { } "
"struct a<int> { "
"template < typename b > constexpr decltype ( auto ) operator() ( b && ) const ; "
"} ;";
const char act[] = "struct a<int> ; "
"a<int> c ; "
"template < typename d > "
"template < typename b > "
"constexpr decltype ( auto ) a < d > :: operator() ( b && ) const { } "
"struct a<int> { "
"template < typename b > constexpr decltype ( auto ) operator() ( b && ) const ; "
"} ; "
"constexpr decltype ( auto ) a<int> :: operator() ( b && ) const { }";
TODO_ASSERT_EQUALS(exp, act, tok(code));
}
{
const char code[] = "template <typename> struct a {\n"
" template <typename b> static void foo();\n"
"};\n"
"a<int> c;\n"
"template <typename d>\n"
"template <typename b>\n"
"void a<d>::foo() {}\n"
"void bar() { a<int>::foo<char>(); }";
const char exp[] = "struct a<int> ; "
"a<int> c ; "
"template < typename d > "
"template < typename b > "
"void a < d > :: foo ( ) { } "
"void bar ( ) { a<int> :: foo < char > ( ) ; } "
"struct a<int> { "
"template < typename b > static void foo ( ) ; "
"static void foo<char> ( ) ; "
"} ; "
"void a<int> :: foo<char> ( ) { }";
const char act[] = "struct a<int> ; "
"a<int> c ; "
"template < typename d > "
"template < typename b > "
"void a < d > :: foo ( ) { } "
"void bar ( ) { a<int> :: foo < char > ( ) ; } "
"struct a<int> { "
"template < typename b > static void foo ( ) ; "
"} ; "
"void a<int> :: foo ( ) { }";
TODO_ASSERT_EQUALS(exp, act, tok(code));
}
{
const char code[] = "template <typename> struct a {\n"
" template <typename b> static void foo();\n"
"};\n"
"template <typename d>\n"
"template <typename b>\n"
"void a<d>::foo() {}\n"
"void bar() { a<int>::foo<char>(); }";
const char exp[] = "struct a<int> ; "
"template < typename d > "
"template < typename b > "
"void a < d > :: foo ( ) { } "
"void bar ( ) { a<int> :: foo < char > ( ) ; } "
"struct a<int> { "
"static void foo<char> ( ) ; "
"} ; "
"void a<int> :: foo<char> ( ) { }";
const char act[] = "struct a<int> ; "
"template < typename d > "
"template < typename b > "
"void a < d > :: foo ( ) { } "
"void bar ( ) { a<int> :: foo < char > ( ) ; } "
"struct a<int> { "
"template < typename b > static void foo ( ) ; "
"} ; "
"void a<int> :: foo ( ) { }";
TODO_ASSERT_EQUALS(exp, act, tok(code));
}
}
void template128() { // #9224
const char code[] = "template <typename> struct a { };\n"
"template <typename j> void h() { k.h<a<j>>; }\n"
"void foo() { h<int>(); }";
const char exp[] = "struct a<int> ; "
"void h<int> ( ) ; "
"void foo ( ) { h<int> ( ) ; } "
"void h<int> ( ) { k . h < a<int> > ; } "
"struct a<int> { } ;";
ASSERT_EQUALS(exp, tok(code));
}
void template129() {
const char code[] = "class LuaContext {\n"
"public:\n"
" template <typename TFunctionType, typename TType>\n"
" void registerFunction(TType fn) { }\n"
"};\n"
"void setupLuaBindingsDNSQuestion() {\n"
" g_lua.registerFunction<void (DNSQuestion ::*)(std ::string, std ::string)>();\n"
"}";
const char exp[] = "class LuaContext { "
"public: "
"template < typename TFunctionType , typename TType > "
"void registerFunction ( TType fn ) { } "
"} ; "
"void setupLuaBindingsDNSQuestion ( ) { "
"g_lua . registerFunction < void ( DNSQuestion :: * ) ( std :: string , std :: string ) > ( ) ; "
"}";
ASSERT_EQUALS(exp, tok(code));
}
void template130() { // #9246
const char code[] = "template <typename...> using a = int;\n"
"template <typename, typename> using b = a<>;\n"
"template <typename, typename> void c();\n"
"template <typename d, typename> void e() { c<b<d, int>, int>; }\n"
"void f() { e<int(int, ...), int>(); }";
const char exp[] = "template < typename , typename > void c ( ) ; "
"void e<int(int,...),int> ( ) ; "
"void f ( ) { e<int(int,...),int> ( ) ; } "
"void e<int(int,...),int> ( ) { c < int , int > ; }";
ASSERT_EQUALS(exp, tok(code));
}
void template131() { // #9249
{
const char code[] = "template <long a, bool = 0 == a> struct b {};\n"
"b<1> b1;";
const char exp[] = "struct b<1,false> ; "
"b<1,false> b1 ; "
"struct b<1,false> { } ;";
ASSERT_EQUALS(exp, tok(code));
}
{
const char code[] = "template <long a, bool = 0 != a> struct b {};\n"
"b<1> b1;";
const char exp[] = "struct b<1,true> ; "
"b<1,true> b1 ; "
"struct b<1,true> { } ;";
ASSERT_EQUALS(exp, tok(code));
}
{
const char code[] = "template <long a, bool = a < 0> struct b {};\n"
"b<1> b1;";
const char exp[] = "struct b<1,false> ; "
"b<1,false> b1 ; "
"struct b<1,false> { } ;";
ASSERT_EQUALS(exp, tok(code));
}
{
const char code[] = "template <long a, bool = 0 < a> struct b {};\n"
"b<1> b1;";
const char exp[] = "struct b<1,true> ; "
"b<1,true> b1 ; "
"struct b<1,true> { } ;";
ASSERT_EQUALS(exp, tok(code));
}
{
const char code[] = "template <long a, bool = 0 <= a> struct b {};\n"
"b<1> b1;";
const char exp[] = "struct b<1,true> ; "
"b<1,true> b1 ; "
"struct b<1,true> { } ;";
ASSERT_EQUALS(exp, tok(code));
}
{
const char code[] = "template <long a, bool = a >= 0> struct b {};\n"
"b<1> b1;";
const char exp[] = "struct b<1,true> ; "
"b<1,true> b1 ; "
"struct b<1,true> { } ;";
ASSERT_EQUALS(exp, tok(code));
}
}
void template132() { // #9250
const char code[] = "struct TrueFalse {\n"
" static constexpr bool v() { return true; }\n"
"};\n"
"int global;\n"
"template<typename T> int foo() {\n"
" __transaction_atomic noexcept(T::v()) { global += 1; }\n"
" return __transaction_atomic noexcept(T::v()) (global + 2);\n"
"}\n"
"int f1() {\n"
" return foo<TrueFalse>();\n"
"}";
const char exp[] = "struct TrueFalse { "
"static constexpr bool v ( ) { return true ; } "
"} ; "
"int global ; "
"int foo<TrueFalse> ( ) ; "
"int f1 ( ) { "
"return foo<TrueFalse> ( ) ; "
"} "
"int foo<TrueFalse> ( ) { "
"__transaction_atomic noexcept ( TrueFalse :: v ( ) ) { global += 1 ; } "
"return __transaction_atomic noexcept ( TrueFalse :: v ( ) ) ( global + 2 ) ; "
"}";
ASSERT_EQUALS(exp, tok(code));
}
void template133() {
const char code[] = "template <typename a> struct bar {\n"
" template <typename b> static bar foo(const bar<b> &c) {\n"
" return bar();\n"
" }\n"
"};\n"
"bar<short> bs;\n"
"bar<std::array<int,4>> ba;\n"
"bar<short> b1 = bar<short>::foo<std::array<int,4>>(ba);\n"
"bar<std::array<int,4>> b2 = bar<std::array<int,4>>::foo<short>(bs);";
const char act[] = "struct bar<short> ; struct bar<std::array<int,4>> ; "
"bar<short> bs ; "
"bar<std::array<int,4>> ba ; "
"bar<short> b1 ; b1 = bar<short> :: foo<std::array<int,4>> ( ba ) ; "
"bar<std::array<int,4>> b2 ; b2 = bar<std::array<int,4>> :: foo<short> ( bs ) ; "
"struct bar<short> { "
"static bar<short> foo<std::array<int,4>> ( const bar < std :: array < int , 4 > > & c ) ; "
"} ; "
"struct bar<std::array<int,4>> { "
"static bar<std::array<int,4>> foo<short> ( const bar < short > & c ) ; "
"} ; "
"bar<std::array<int,4>> bar<std::array<int,4>> :: foo<short> ( const bar < short > & c ) { "
"return bar<std::array<int,4>> ( ) ; "
"} "
"bar<short> bar<short> :: foo<std::array<int,4>> ( const bar < std :: array < int , 4 > > & c ) { "
"return bar<short> ( ) ; "
"}";
const char exp[] = "struct bar<short> ; struct bar<std::array<int,4>> ; "
"bar<short> bs ; "
"bar<std::array<int,4>> ba ; "
"bar<short> b1 ; b1 = bar<short> :: foo<std::array<int,4>> ( ba ) ; "
"bar<std::array<int,4>> b2 ; b2 = bar<std::array<int,4>> :: foo<short> ( bs ) ; "
"struct bar<short> { "
"static bar<short> foo<std::array<int,4>> ( const bar<std::array<int,4>> & c ) ; "
"} ; "
"struct bar<std::array<int,4>> { "
"static bar<std::array<int,4>> foo<short> ( const bar<short> & c ) ; "
"} ; "
"bar<std::array<int,4>> bar<std::array<int,4>> :: foo<short> ( const bar<short> & c ) { "
"return bar<std::array<int,4>> ( ) ; "
"} "
"bar<short> bar<short> :: foo<std::array<int,4>> ( const bar<std::array<int,4>> & c ) { "
"return bar<short> ( ) ; "
"}";
TODO_ASSERT_EQUALS(exp, act, tok(code));
}
void template134() {
const char code[] = "template <int a> class e { };\n"
"template <int a> class b { e<(c > a ? 1 : 0)> d; };\n"
"b<0> b0;\n"
"b<1> b1;";
const char exp[] = "class e<(c>0)> ; class e<(c>1)> ; "
"class b<0> ; class b<1> ; "
"b<0> b0 ; "
"b<1> b1 ; "
"class b<0> { e<(c>0)> d ; } ; class b<1> { e<(c>1)> d ; } ; "
"class e<(c>0)> { } ; class e<(c>1)> { } ;";
ASSERT_EQUALS(exp, tok(code));
}
void template135() {
const char code[] = "template <int> struct a { template <int b> void c(a<b>); };\n"
"a<2> d;";
const char exp[] = "struct a<2> ; "
"a<2> d ; "
"struct a<2> { template < int b > void c ( a < b > ) ; } ;";
ASSERT_EQUALS(exp, tok(code));
}
void template136() { // #9287
const char code[] = "namespace a {\n"
"template <typename> struct b;\n"
"template <int> struct c;\n"
"template <typename> struct d;\n"
"template <typename> struct f;\n"
"template <typename> struct g;\n"
"template <typename h>\n"
"struct i : c<b<f<typename h ::j>>::k && b<g<typename h ::j>>::k> {};\n"
"}\n"
"namespace hana = a;\n"
"using e = int;\n"
"void l(hana::d<hana::i<e>>);";
const char exp[] = "namespace a { "
"template < typename > struct b ; "
"template < int > struct c ; "
"template < typename > struct d ; "
"template < typename > struct f ; "
"template < typename > struct g ; "
"struct i<int> ; "
"} "
"void l ( a :: d < a :: i<int> > ) ; "
"struct a :: i<int> : c < b < f < int :: j > > :: k && b < g < int :: j > > :: k > { } ;";
ASSERT_EQUALS(exp, tok(code));
}
void template137() { // #9288
const char code[] = "template <bool> struct a;\n"
"template <bool b, class> using c = typename a<b>::d;\n"
"template <class, template <class> class, class> struct e;\n"
"template <class f, class g, class... h>\n"
"using i = typename e<f, g::template fn, h...>::d;\n"
"template <class... j> struct k : c<sizeof...(j), int>::template fn<j...> {};";
const char exp[] = "template < bool > struct a ; "
"template < bool b , class > using c = typename a < b > :: d ; "
"template < class , template < class > class , class > struct e ; "
"template < class f , class g , class ... h > "
"using i = typename e < f , g :: fn , h ... > :: d ; "
"template < class ... j > struct k : c < sizeof... ( j ) , int > :: fn < j ... > { } ;";
ASSERT_EQUALS(exp, tok(code));
}
void template138() {
{
const char code[] = "struct inferior {\n"
" using visitor = int;\n"
" template <typename T>\n"
" bool operator()(const T &a, const T &b) const {\n"
" return 1 < b;\n"
" }\n"
"};\n"
"int main() {\n"
" return 0;\n"
"}";
const char exp[] = "struct inferior { "
"template < typename T > "
"bool operator() ( const T & a , const T & b ) const { "
"return 1 < b ; "
"} "
"} ; "
"int main ( ) { "
"return 0 ; "
"}";
ASSERT_EQUALS(exp, tok(code));
}
{
const char code[] = "struct inferior {\n"
" template <typename T>\n"
" bool operator()(const T &a, const T &b) const {\n"
" return 1 < b;\n"
" }\n"
"};\n"
"int main() {\n"
" return 0;\n"
"}";
const char exp[] = "struct inferior { "
"template < typename T > "
"bool operator() ( const T & a , const T & b ) const { "
"return 1 < b ; "
"} "
"} ; "
"int main ( ) { "
"return 0 ; "
"}";
ASSERT_EQUALS(exp, tok(code));
}
{
const char code[] = "struct inferior {\n"
" using visitor = int;\n"
" template <typename T>\n"
" bool operator()(const T &a, const T &b) const {\n"
" return a < b;\n"
" }\n"
"};\n"
"int main() {\n"
" return 0;\n"
"}";
const char exp[] = "struct inferior { "
"template < typename T > "
"bool operator() ( const T & a , const T & b ) const { "
"return a < b ; "
"} "
"} ; "
"int main ( ) { "
"return 0 ; "
"}";
ASSERT_EQUALS(exp, tok(code));
}
{
const char code[] = "struct inferior {\n"
" template <typename T>\n"
" bool operator()(const T &a, const T &b) const {\n"
" return a < b;\n"
" }\n"
"};\n"
"int main() {\n"
" return 0;\n"
"}";
const char exp[] = "struct inferior { "
"template < typename T > "
"bool operator() ( const T & a , const T & b ) const { "
"return a < b ; "
"} "
"} ; "
"int main ( ) { "
"return 0 ; "
"}";
ASSERT_EQUALS(exp, tok(code));
}
}
void template139() {
{
const char code[] = "template<typename T>\n"
"struct Foo {\n"
" template<typename> friend struct Foo;\n"
"};";
const char exp[] = "template < typename T > "
"struct Foo { "
"template < typename > friend struct Foo ; "
"} ;";
ASSERT_EQUALS(exp, tok(code));
}
{
const char code[] = "template<typename T>\n"
"struct Foo {\n"
" template<typename> friend struct Foo;\n"
"} ;\n"
"Foo<int> foo;";
const char exp[] = "struct Foo<int> ; "
"Foo<int> foo ; "
"struct Foo<int> { "
"template < typename > friend struct Foo ; "
"} ;";
ASSERT_EQUALS(exp, tok(code));
}
}
void template140() {
{
const char code[] = "template <typename> struct a { };\n"
"template <typename b> struct d {\n"
" d();\n"
" d(d<a<b>> e);\n"
"};\n"
"void foo() { d<char> c; }";
const char exp[] = "struct a<char> ; "
"struct d<char> ; "
"void foo ( ) { d<char> c ; } "
"struct d<char> { "
"d<char> ( ) ; "
"d<char> ( d < a<char> > e ) ; "
"} ; "
"struct a<char> { } ;";
ASSERT_EQUALS(exp, tok(code));
}
{
const char code[] = "namespace a {\n"
"template <typename b> using c = typename b ::d;\n"
"template <typename> constexpr bool e() { return false; }\n"
"template <typename b> class f { f(f<c<b>>); };\n"
"static_assert(!e<f<char>>());\n"
"}";
const char exp[] = "namespace a { "
"constexpr bool e<f<char>> ( ) ; "
"class f<char> ; "
"static_assert ( ! e<f<char>> ( ) ) ; } "
"class a :: f<char> { f<char> ( a :: f < b :: d > ) ; } ; "
"constexpr bool a :: e<f<char>> ( ) { return false ; }";
ASSERT_EQUALS(exp, tok(code));
}
}
void template141() { // #9337
const char code[] = "struct a {\n"
" int c;\n"
" template <typename b> void d(b e) const { c < *e; }\n"
"};";
const char exp[] = "struct a { "
"int c ; "
"template < typename b > void d ( b e ) const { c < * e ; } "
"} ;";
ASSERT_EQUALS(exp, tok(code));
}
void template142() { // #9338
const char code[] = "template <typename...> struct a;\n"
"template <typename b, typename c, typename... d> struct a<b c::*, d...> {\n"
" using typename b ::e;\n"
" static_assert(e::f ? sizeof...(d) : sizeof...(d), \"\");\n"
"};";
const char exp[] = "template < typename ... > struct a ; "
"template < typename b , typename c , typename ... d > struct a < b c :: * , d ... > { "
"using e = b :: e ; "
"static_assert ( e :: f ? sizeof... ( d ) : sizeof... ( d ) , \"\" ) ; "
"} ;";
ASSERT_EQUALS(exp, tok(code));
}
void template143() {
const char code[] = "template<int N>\n"
"using A1 = struct B1 { static auto constexpr value = N; };\n"
"A1<0> a1;\n"
"template<class T>\n"
"using A2 = struct B2 { void f(T){} };\n"
"A2<bool> a2;\n"
"template<class T>\n"
"using A3 = enum B3 {b = 0};\n"
"A3<int> a3;";
const char exp[] = "template < int N > "
"using A1 = struct B1 { static auto constexpr value = N ; } ; "
"A1 < 0 > a1 ; "
"template < class T > "
"using A2 = struct B2 { void f ( T ) { } } ; "
"A2 < bool > a2 ; "
"template < class T > "
"using A3 = enum B3 { b = 0 } ; "
"A3 < int > a3 ;";
ASSERT_EQUALS(exp, tok(code));
}
void template144() { // #9046
const char code[] = "namespace a {\n"
"template <typename T, typename enable = void>\n"
"struct promote {\n"
" using type = T;\n"
"};\n"
"template <typename T>\n"
"struct promote <T, typename std::enable_if< std::is_integral<T>::value && sizeof(T) < sizeof(int) >::type>{\n"
"};\n"
"}";
const char exp[] = "namespace a { "
"template < typename T , typename enable = void > "
"struct promote { "
"using type = T ; "
"} ; "
"template < typename T > "
"struct promote < T , std :: enable_if < std :: is_integral < T > :: value && sizeof ( T ) < sizeof ( int ) > :: type > { "
"} ; "
"}";
ASSERT_EQUALS(exp, tok(code));
}
void template145() { // syntax error
const char code[] = "template<template<typename, Ts = 0> class ...Cs, Cs<Ts> ...Vs> struct B { };";
const char exp[] = "template < template < typename , Ts = 0 > class ... Cs , Cs < Ts > ... Vs > struct B { } ;";
ASSERT_EQUALS(exp, tok(code));
}
void template146() { // syntax error
const char code[] = "template<class T> struct C { };\n"
"template<class T, template<class TT_T0, template<class TT_T1> class TT_TT> class TT, class U = TT<int, C> >\n"
"struct S {\n"
" void foo(TT<T, C>);\n"
"};";
const char exp[] = "template < class T > struct C { } ; "
"template < class T , template < class TT_T0 , template < class TT_T1 > class TT_TT > class TT , class U = TT < int , C > > "
"struct S { "
"void foo ( TT < T , C > ) ; "
"} ;";
ASSERT_EQUALS(exp, tok(code));
}
void template147() { // syntax error
const char code[] = "template <template <typename> class C, typename X, C<X>*> struct b { };";
const char exp[] = "template < template < typename > class C , typename X , C < X > * > struct b { } ;";
ASSERT_EQUALS(exp, tok(code));
}
void template148() { // syntax error
const char code[] = "static_assert(var<S1<11, 100>> == var<S1<199, 23>> / 2\n"
" && var<S1<50, 120>> == var<S1<150, var<S1<10, 10>>>>\n"
" && var<S1<53, 23>> != 222, \"\");";
const char exp[] = "static_assert ( var < S1 < 11 , 100 > > == var < S1 < 199 , 23 > > / 2 "
"&& var < S1 < 50 , 120 > > == var < S1 < 150 , var < S1 < 10 , 10 > > > > "
"&& var < S1 < 53 , 23 > > != 222 , \"\" ) ;";
ASSERT_EQUALS(exp, tok(code));
}
void template149() { // unknown macro
const char code[] = "BEGIN_VERSIONED_NAMESPACE_DECL\n"
"template<typename T> class Fred { };\n"
"END_VERSIONED_NAMESPACE_DECL";
ASSERT_THROW_INTERNAL_EQUALS(tok(code), UNKNOWN_MACRO, "There is an unknown macro here somewhere. Configuration is required. If BEGIN_VERSIONED_NAMESPACE_DECL is a macro then please configure it.");
}
void template150() { // syntax error
const char code[] = "struct Test {\n"
" template <typename T>\n"
" T &operator[] (T) {}\n"
"};\n"
"void foo() {\n"
" Test test;\n"
" const string type = test.operator[]<string>(\"type\");\n"
"}";
const char exp[] = "struct Test { "
"string & operator[]<string> ( string ) ; "
"} ; "
"void foo ( ) { "
"Test test ; "
"const string type = test . operator[]<string> ( \"type\" ) ; "
"} string & Test :: operator[]<string> ( string ) { }";
ASSERT_EQUALS(exp, tok(code));
}
void template151() { // crash
{
const char code[] = "class SimulationComponentGroupGenerator {\n"
" std::list<int, std::allocator<int>> build() const;\n"
"};\n"
"template <\n"
" class obj_type,\n"
" template<class> class allocator = std::allocator,\n"
" template<class, class> class data_container = std::list>\n"
"class GenericConfigurationHandler {\n"
" data_container<int, std::allocator<int>> m_target_configurations;\n"
"};\n"
"class TargetConfigurationHandler : public GenericConfigurationHandler<int> { };";
const char exp[] = "class SimulationComponentGroupGenerator { "
"std :: list < int , std :: allocator < int > > build ( ) const ; "
"} ; "
"class GenericConfigurationHandler<int,std::allocator,std::list> ; "
"class TargetConfigurationHandler : public GenericConfigurationHandler<int,std::allocator,std::list> { } ; "
"class GenericConfigurationHandler<int,std::allocator,std::list> { "
"std :: list < int , std :: std :: allocator < int > > m_target_configurations ; "
"} ;";
ASSERT_EQUALS(exp, tok(code));
}
{
const char code[] = "std::list<std::allocator<int>> a;\n"
"template <class, template <class> class allocator = std::allocator> class b {};\n"
"class c : b<int> {};";
const char exp[] = "std :: list < std :: allocator < int > > a ; "
"class b<int,std::allocator> ; "
"class c : b<int,std::allocator> { } ; "
"class b<int,std::allocator> { } ;";
ASSERT_EQUALS(exp, tok(code));
}
{
const char code[] = "template <typename> class a {};\n"
"template class a<char>;\n"
"template <class, template <class> class a = a> class b {};\n"
"class c : b<int> {};";
const char exp[] = "class a<char> ; "
"class b<int,a> ; "
"class c : b<int,a> { } ; "
"class b<int,a> { } ; "
"class a<char> { } ;";
ASSERT_EQUALS(exp, tok(code));
}
}
void template152() { // #9467
const char code[] = "class Foo {\n"
" template <unsigned int i>\n"
" bool bar() {\n"
" return true;\n"
" }\n"
"};\n"
"template <>\n"
"bool Foo::bar<9>() {\n"
" return true;\n"
"}\n"
"int global() {\n"
" int bar = 1;\n"
" return bar;\n"
"}";
const char exp[] = "class Foo { "
"bool bar<9> ( ) ; "
"template < unsigned int i > "
"bool bar ( ) { "
"return true ; "
"} "
"} ; "
"bool Foo :: bar<9> ( ) { "
"return true ; "
"} "
"int global ( ) { "
"int bar ; bar = 1 ; "
"return bar ; "
"}";
ASSERT_EQUALS(exp, tok(code));
}
void template153() { // #9483
const char code[] = "template <class = b<decltype(a<h>())...>> void i();";
const char exp[] = "template < class = b < decltype ( a < h > ( ) ) ... > > void i ( ) ;";
ASSERT_EQUALS(exp, tok(code));
}
void template154() { // #9495
const char code[] = "template <typename S, enable_if_t<(is_compile_string<S>::value), int>> void i(S s);";
const char exp[] = "template < typename S , enable_if_t < ( is_compile_string < S > :: value ) , int > > void i ( S s ) ;";
ASSERT_EQUALS(exp, tok(code));
}
void template155() { // #9539
const char code[] = "template <int> int a = 0;\n"
"struct b {\n"
" void operator[](int);\n"
"};\n"
"void c() {\n"
" b d;\n"
" d[a<0>];\n"
"}";
const char exp[] = "int a<0> ; "
"a<0> = 0 ; "
"struct b { "
"void operator[] ( int ) ; "
"} ; "
"void c ( ) { "
"b d ; "
"d [ a<0> ] ; "
"}";
ASSERT_EQUALS(exp, tok(code));
}
void template156() {
const char code[] = "template <int a> struct c { static constexpr int d = a; };\n"
"template <bool b> using e = c<b>;\n"
"using f = e<false>;\n"
"template <typename> struct g : f {};\n"
"template <bool, class, class> using h = e<g<long>::d>;\n"
"template <typename> using i = e<g<double>::d>;\n"
"template <typename j> using k = e<i<j>::d>;\n"
"template <typename j> using l = h<k<j>::d, e<1 < (j)0>, f>;\n"
"template <typename> void m(int, int, int) { l<int> d; }\n"
"void n() { m<int>(0, 4, 5); }";
(void)tok(code); // don't crash
}
void template157() { // #9854
const char code[] = "template <int a, bool c = a == int()> struct b1 { bool d = c; };\n"
"template <int a, bool c = a != int()> struct b2 { bool d = c; };\n"
"template <int a, bool c = a < int()> struct b3 { bool d = c; };\n"
"template <int a, bool c = a <= int()> struct b4 { bool d = c; };\n"
"template <int a, bool c = (a > int())> struct b5 { bool d = c; };\n"
"template <int a, bool c = a >= int()> struct b6 { bool d = c; };\n"
"b1<0> var1;\n"
"b2<0> var2;\n"
"b3<0> var3;\n"
"b4<0> var4;\n"
"b5<0> var5;\n"
"b6<0> var6;";
const char exp[] = "struct b1<0,true> ; "
"struct b2<0,false> ; "
"struct b3<0,false> ; "
"struct b4<0,true> ; "
"struct b5<0,false> ; "
"struct b6<0,true> ; "
"b1<0,true> var1 ; "
"b2<0,false> var2 ; "
"b3<0,false> var3 ; "
"b4<0,true> var4 ; "
"b5<0,false> var5 ; "
"b6<0,true> var6 ; "
"struct b6<0,true> { bool d ; d = true ; } ; "
"struct b5<0,false> { bool d ; d = false ; } ; "
"struct b4<0,true> { bool d ; d = true ; } ; "
"struct b3<0,false> { bool d ; d = false ; } ; "
"struct b2<0,false> { bool d ; d = false ; } ; "
"struct b1<0,true> { bool d ; d = true ; } ;";
ASSERT_EQUALS(exp, tok(code));
}
void template158() { // daca crash
const char code[] = "template <typename> class a0{};\n"
"template <typename> class a1{};\n"
"template <typename> class a2{};\n"
"template <typename> class a3{};\n"
"template <typename> class a4{};\n"
"template <typename> class a5{};\n"
"template <typename> class a6{};\n"
"template <typename> class a7{};\n"
"template <typename> class a8{};\n"
"template <typename> class a9{};\n"
"template <typename> class a10{};\n"
"template <typename> class a11{};\n"
"template <typename> class a12{};\n"
"template <typename> class a13{};\n"
"template <typename> class a14{};\n"
"template <typename> class a15{};\n"
"template <typename> class a16{};\n"
"template <typename> class a17{};\n"
"template <typename> class a18{};\n"
"template <typename> class a19{};\n"
"template <typename> class a20{};\n"
"template <typename> class a21{};\n"
"template <typename> class a22{};\n"
"template <typename> class a23{};\n"
"template <typename> class a24{};\n"
"template <typename> class a25{};\n"
"template <typename> class a26{};\n"
"template <typename> class a27{};\n"
"template <typename> class a28{};\n"
"template <typename> class a29{};\n"
"template <typename> class a30{};\n"
"template <typename> class a31{};\n"
"template <typename> class a32{};\n"
"template <typename> class a33{};\n"
"template <typename> class a34{};\n"
"template <typename> class a35{};\n"
"template <typename> class a36{};\n"
"template <typename> class a37{};\n"
"template <typename> class a38{};\n"
"template <typename> class a39{};\n"
"template <typename> class a40{};\n"
"template <typename> class a41{};\n"
"template <typename> class a42{};\n"
"template <typename> class a43{};\n"
"template <typename> class a44{};\n"
"template <typename> class a45{};\n"
"template <typename> class a46{};\n"
"template <typename> class a47{};\n"
"template <typename> class a48{};\n"
"template <typename> class a49{};\n"
"template <typename> class a50{};\n"
"template <typename> class a51{};\n"
"template <typename> class a52{};\n"
"template <typename> class a53{};\n"
"template <typename> class a54{};\n"
"template <typename> class a55{};\n"
"template <typename> class a56{};\n"
"template <typename> class a57{};\n"
"template <typename> class a58{};\n"
"template <typename> class a59{};\n"
"template <typename> class a60{};\n"
"template <typename> class a61{};\n"
"template <typename> class a62{};\n"
"template <typename> class a63{};\n"
"template <typename> class a64{};\n"
"template <typename> class a65{};\n"
"template <typename> class a66{};\n"
"template <typename> class a67{};\n"
"template <typename> class a68{};\n"
"template <typename> class a69{};\n"
"template <typename> class a70{};\n"
"template <typename> class a71{};\n"
"template <typename> class a72{};\n"
"template <typename> class a73{};\n"
"template <typename> class a74{};\n"
"template <typename> class a75{};\n"
"template <typename> class a76{};\n"
"template <typename> class a77{};\n"
"template <typename> class a78{};\n"
"template <typename> class a79{};\n"
"template <typename> class a80{};\n"
"template <typename> class a81{};\n"
"template <typename> class a82{};\n"
"template <typename> class a83{};\n"
"template <typename> class a84{};\n"
"template <typename> class a85{};\n"
"template <typename> class a86{};\n"
"template <typename> class a87{};\n"
"template <typename> class a88{};\n"
"template <typename> class a89{};\n"
"template <typename> class a90{};\n"
"template <typename> class a91{};\n"
"template <typename> class a92{};\n"
"template <typename> class a93{};\n"
"template <typename> class a94{};\n"
"template <typename> class a95{};\n"
"template <typename> class a96{};\n"
"template <typename> class a97{};\n"
"template <typename> class a98{};\n"
"template <typename> class a99{};\n"
"template <typename> class a100{};\n"
"template <typename> class b {};\n"
"b<a0<int>> d0;\n"
"b<a1<int>> d1;\n"
"b<a2<int>> d2;\n"
"b<a3<int>> d3;\n"
"b<a4<int>> d4;\n"
"b<a5<int>> d5;\n"
"b<a6<int>> d6;\n"
"b<a7<int>> d7;\n"
"b<a8<int>> d8;\n"
"b<a9<int>> d9;\n"
"b<a10<int>> d10;\n"
"b<a11<int>> d11;\n"
"b<a12<int>> d12;\n"
"b<a13<int>> d13;\n"
"b<a14<int>> d14;\n"
"b<a15<int>> d15;\n"
"b<a16<int>> d16;\n"
"b<a17<int>> d17;\n"
"b<a18<int>> d18;\n"
"b<a19<int>> d19;\n"
"b<a20<int>> d20;\n"
"b<a21<int>> d21;\n"
"b<a22<int>> d22;\n"
"b<a23<int>> d23;\n"
"b<a24<int>> d24;\n"
"b<a25<int>> d25;\n"
"b<a26<int>> d26;\n"
"b<a27<int>> d27;\n"
"b<a28<int>> d28;\n"
"b<a29<int>> d29;\n"
"b<a30<int>> d30;\n"
"b<a31<int>> d31;\n"
"b<a32<int>> d32;\n"
"b<a33<int>> d33;\n"
"b<a34<int>> d34;\n"
"b<a35<int>> d35;\n"
"b<a36<int>> d36;\n"
"b<a37<int>> d37;\n"
"b<a38<int>> d38;\n"
"b<a39<int>> d39;\n"
"b<a40<int>> d40;\n"
"b<a41<int>> d41;\n"
"b<a42<int>> d42;\n"
"b<a43<int>> d43;\n"
"b<a44<int>> d44;\n"
"b<a45<int>> d45;\n"
"b<a46<int>> d46;\n"
"b<a47<int>> d47;\n"
"b<a48<int>> d48;\n"
"b<a49<int>> d49;\n"
"b<a50<int>> d50;\n"
"b<a51<int>> d51;\n"
"b<a52<int>> d52;\n"
"b<a53<int>> d53;\n"
"b<a54<int>> d54;\n"
"b<a55<int>> d55;\n"
"b<a56<int>> d56;\n"
"b<a57<int>> d57;\n"
"b<a58<int>> d58;\n"
"b<a59<int>> d59;\n"
"b<a60<int>> d60;\n"
"b<a61<int>> d61;\n"
"b<a62<int>> d62;\n"
"b<a63<int>> d63;\n"
"b<a64<int>> d64;\n"
"b<a65<int>> d65;\n"
"b<a66<int>> d66;\n"
"b<a67<int>> d67;\n"
"b<a68<int>> d68;\n"
"b<a69<int>> d69;\n"
"b<a70<int>> d70;\n"
"b<a71<int>> d71;\n"
"b<a72<int>> d72;\n"
"b<a73<int>> d73;\n"
"b<a74<int>> d74;\n"
"b<a75<int>> d75;\n"
"b<a76<int>> d76;\n"
"b<a77<int>> d77;\n"
"b<a78<int>> d78;\n"
"b<a79<int>> d79;\n"
"b<a80<int>> d80;\n"
"b<a81<int>> d81;\n"
"b<a82<int>> d82;\n"
"b<a83<int>> d83;\n"
"b<a84<int>> d84;\n"
"b<a85<int>> d85;\n"
"b<a86<int>> d86;\n"
"b<a87<int>> d87;\n"
"b<a88<int>> d88;\n"
"b<a89<int>> d89;\n"
"b<a90<int>> d90;\n"
"b<a91<int>> d91;\n"
"b<a92<int>> d92;\n"
"b<a93<int>> d93;\n"
"b<a94<int>> d94;\n"
"b<a95<int>> d95;\n"
"b<a96<int>> d96;\n"
"b<a97<int>> d97;\n"
"b<a98<int>> d98;\n"
"b<a99<int>> d99;\n"
"b<a100<int>> d100;";
// don't bother checking the output because this is not instantiated properly
(void)tok(code); // don't crash
const char code2[] = "template<typename T> void f();\n" // #11489
"template<typename T> void f(int);\n"
"void g() {\n"
" f<int>();\n"
" f<char>(1);\n"
"}\n"
"template<typename T>\n"
"void f(int) {}\n"
"template<typename T>\n"
"void f() {\n"
" f<T>(0);\n"
"}\n";
const char exp2[] = "template < typename T > void f ( ) ; "
"void f<char> ( int ) ; "
"void f<int> ( int ) ; "
"void g ( ) { f<int> ( ) ; f<char> ( 1 ) ; } "
"void f<char> ( int ) { } "
"void f<int> ( ) { f<int> ( 0 ) ; }";
ASSERT_EQUALS(exp2, tok(code2));
}
void template159() { // #9886
const char code[] = "struct impl { template <class T> static T create(); };\n"
"template<class T, class U, class = decltype(impl::create<T>()->impl::create<U>())>\n"
"struct tester{};\n"
"tester<impl*, int> ti;\n"
"template<class T, class U, class = decltype(impl::create<T>()->impl::create<U>())>\n"
"int test() { return 0; }\n"
"int i = test<impl*, int>();";
const char exp[] = "struct impl { template < class T > static T create ( ) ; } ; "
"struct tester<impl*,int,decltype(impl::create<impl*>().impl::create<int>())> ; "
"tester<impl*,int,decltype(impl::create<impl*>().impl::create<int>())> ti ; "
"int test<impl*,int,decltype(impl::create<impl*>().impl::create<int>())> ( ) ; "
"int i ; i = test<impl*,int,decltype(impl::create<impl*>().impl::create<int>())> ( ) ; "
"int test<impl*,int,decltype(impl::create<impl*>().impl::create<int>())> ( ) { return 0 ; } "
"struct tester<impl*,int,decltype(impl::create<impl*>().impl::create<int>())> { } ;";
ASSERT_EQUALS(exp, tok(code));
}
void template160() {
const char code[] = "struct Fred {\n"
" template <typename T> static void foo() { }\n"
" template <typename T> static void foo(T) { }\n"
"};\n"
"template void Fred::foo<char>();\n"
"template <> void Fred::foo<bool>() { }\n"
"template void Fred::foo<float>(float);\n"
"template <> void Fred::foo<int>(int) { }";
const char exp[] = "struct Fred { "
"static void foo<bool> ( ) ; "
"static void foo<char> ( ) ; "
"static void foo<int> ( int ) ; "
"static void foo<float> ( float ) ; "
"} ; "
"void Fred :: foo<bool> ( ) { } "
"void Fred :: foo<int> ( int ) { } "
"void Fred :: foo<float> ( float ) { } "
"void Fred :: foo<char> ( ) { }";
ASSERT_EQUALS(exp, tok(code));
}
void template161() {
const char code[] = "struct JobEntry { };\n"
"template<class T>\n"
"struct adapter : public T {\n"
" template<class... Args>\n"
" adapter(Args&&... args) : T{ std::forward<Args>(args)... } {}\n"
"};\n"
"void foo() {\n"
" auto notifyJob = std::make_shared<adapter<JobEntry>> ();\n"
"}";
const char exp[] = "???";
const char act[] = "struct JobEntry { } ; "
"struct adapter<JobEntry> ; "
"void foo ( ) { "
"auto notifyJob ; notifyJob = std :: make_shared < adapter<JobEntry> > ( ) ; "
"} "
"struct adapter<JobEntry> : public JobEntry { "
"template < class ... Args > "
"adapter<JobEntry> ( Args && ... args ) : JobEntry { std :: forward < Args > ( args ) ... } { } "
"} ;";
TODO_ASSERT_EQUALS(exp, act, tok(code));
}
void template162() {
const char code[] = "template <std::size_t N>\n"
"struct CountryCode {\n"
" CountryCode(std::string cc);\n"
"};"
"template <std::size_t N>\n"
"CountryCode<N>::CountryCode(std::string cc) : m_String{std::move(cc)} {\n"
"}\n"
"template class CountryCode<2>;\n"
"template class CountryCode<3>;";
const char exp[] = "struct CountryCode<2> ; "
"struct CountryCode<3> ; "
"struct CountryCode<2> { "
"CountryCode<2> ( std :: string cc ) ; "
"} ; "
"CountryCode<2> :: CountryCode<2> ( std :: string cc ) : m_String { std :: move ( cc ) } { "
"} "
"struct CountryCode<3> { "
"CountryCode<3> ( std :: string cc ) ; "
"} ; "
"CountryCode<3> :: CountryCode<3> ( std :: string cc ) : m_String { std :: move ( cc ) } { "
"}";
ASSERT_EQUALS(exp, tok(code));
}
void template163() { // #9685 syntax error
const char code[] = "extern \"C++\" template < typename T > T * test ( ) { return nullptr ; }";
const char expected[] = "template < typename T > T * test ( ) { return nullptr ; }";
ASSERT_EQUALS(expected, tok(code));
}
void template164() { // #9394
const char code[] = "template <class TYPE>\n"
"struct A {\n"
" A();\n"
" ~A();\n"
" static void f();\n"
"};\n"
"template <class TYPE>\n"
"A<TYPE>::A() { }\n"
"template <class TYPE>\n"
"A<TYPE>::~A() { }\n"
"template <class TYPE>\n"
"void A<TYPE>::f() { }\n"
"template class A<int>;\n"
"template class A<float>;";
const char exp[] = "struct A<int> ; "
"struct A<float> ; "
"struct A<int> { "
"A<int> ( ) ; "
"~ A<int> ( ) ; "
"static void f ( ) ; "
"} ; "
"A<int> :: A<int> ( ) { } "
"A<int> :: ~ A<int> ( ) { } "
"void A<int> :: f ( ) { } "
"struct A<float> { "
"A<float> ( ) ; "
"~ A<float> ( ) ; "
"static void f ( ) ; "
"} ; "
"A<float> :: A<float> ( ) { } "
"A<float> :: ~ A<float> ( ) { } "
"void A<float> :: f ( ) { }";
ASSERT_EQUALS(exp, tok(code));
}
void template165() { // #10032 syntax error
const char code[] = "struct MyStruct {\n"
" template<class T>\n"
" bool operator()(const T& l, const T& r) const {\n"
" return l.first < r.first;\n"
" }\n"
"};";
const char exp[] = "struct MyStruct { "
"template < class T > "
"bool operator() ( const T & l , const T & r ) const { "
"return l . first < r . first ; "
"} "
"} ;";
ASSERT_EQUALS(exp, tok(code));
}
void template166() { // #10081 hang
const char code[] = "template <typename T, size_t k = (T::s < 3) ? 0 : 3>\n"
"void foo() {}\n"
"foo<T>();";
const char exp[] = "void foo<T,(T::s<3)?0:3> ( ) ; "
"foo<T,(T::s<3)?0:3> ( ) ; "
"void foo<T,(T::s<3)?0:3> ( ) { }";
ASSERT_EQUALS(exp, tok(code));
}
void template167() {
const char code[] = "struct MathLib {\n"
" template<class T> static std::string toString(T value) {\n"
" return std::string{};\n"
" }\n"
"};\n"
"template<> std::string MathLib::toString(double value);\n"
"template<> std::string MathLib::toString(double value) {\n"
" return std::string{std::to_string(value)};\n"
"}\n"
"void foo() {\n"
" std::string str = MathLib::toString(1.0);\n"
"}";
const char exp[] = "struct MathLib { "
"static std :: string toString<double> ( double value ) ; "
"template < class T > static std :: string toString ( T value ) { "
"return std :: string { } ; "
"} "
"} ; "
"std :: string MathLib :: toString<double> ( double value ) { "
"return std :: string { std :: to_string ( value ) } ; "
"} "
"void foo ( ) { "
"std :: string str ; str = MathLib :: toString<double> ( 1.0 ) ; "
"}";
ASSERT_EQUALS(exp, tok(code));
}
void template168() {
const char code[] = "template < typename T, typename U > struct type { };\n"
"template < > struct type < bool, bool > {};\n"
"template < > struct type < unsigned char, unsigned char > {};\n"
"template < > struct type < char, char > {};\n"
"template < > struct type < signed char, signed char > {};\n"
"template < > struct type < unsigned short, unsigned short > {};\n"
"template < > struct type < short, short > {};\n"
"template < > struct type < unsigned int, unsigned int > {};\n"
"template < > struct type < int, int > {};\n"
"template < > struct type < unsigned long long, unsigned long long > {};\n"
"template < > struct type < long long, long long > {};\n"
"template < > struct type < double, double > {};\n"
"template < > struct type < float, float > {};\n"
"template < > struct type < long double, long double > {};";
const char exp[] = "struct type<longdouble,longdouble> ; "
"struct type<float,float> ; "
"struct type<double,double> ; "
"struct type<longlong,longlong> ; "
"struct type<unsignedlonglong,unsignedlonglong> ; "
"struct type<int,int> ; "
"struct type<unsignedint,unsignedint> ; "
"struct type<short,short> ; "
"struct type<unsignedshort,unsignedshort> ; "
"struct type<signedchar,signedchar> ; "
"struct type<char,char> ; "
"struct type<unsignedchar,unsignedchar> ; "
"struct type<bool,bool> ; "
"template < typename T , typename U > struct type { } ; "
"struct type<bool,bool> { } ; "
"struct type<unsignedchar,unsignedchar> { } ; "
"struct type<char,char> { } ; "
"struct type<signedchar,signedchar> { } ; "
"struct type<unsignedshort,unsignedshort> { } ; "
"struct type<short,short> { } ; "
"struct type<unsignedint,unsignedint> { } ; "
"struct type<int,int> { } ; "
"struct type<unsignedlonglong,unsignedlonglong> { } ; "
"struct type<longlong,longlong> { } ; "
"struct type<double,double> { } ; "
"struct type<float,float> { } ; "
"struct type<longdouble,longdouble> { } ;";
ASSERT_EQUALS(exp, tok(code));
}
void template169() {
const char code[] = "template < typename T> struct last { T t; };\n"
"template < typename T > struct CImgList { T t; };\n"
"CImgList < last < bool > > c1;\n"
"CImgList < last < signed char > > c2;\n"
"CImgList < last < unsigned char > > c3;\n"
"CImgList < last < char > > c4;\n"
"CImgList < last < unsigned short > > c5;\n"
"CImgList < last < short > > c6;\n"
"CImgList < last < unsigned int > > c7;\n"
"CImgList < last < int > > c8;\n"
"CImgList < last < unsigned long > > c9;\n"
"CImgList < last < long > > c10;\n"
"CImgList < last < unsigned long long > > c11;\n"
"CImgList < last < long long > > c12;\n"
"CImgList < last < float > > c13;\n"
"CImgList < last < double > > c14;\n"
"CImgList < last < long double > > c15;";
const char exp[] = "struct last<bool> ; "
"struct last<signedchar> ; "
"struct last<unsignedchar> ; "
"struct last<char> ; "
"struct last<unsignedshort> ; "
"struct last<short> ; "
"struct last<unsignedint> ; "
"struct last<int> ; "
"struct last<unsignedlong> ; "
"struct last<long> ; "
"struct last<unsignedlonglong> ; "
"struct last<longlong> ; "
"struct last<float> ; "
"struct last<double> ; "
"struct last<longdouble> ; "
"struct CImgList<last<bool>> ; "
"struct CImgList<last<signedchar>> ; "
"struct CImgList<last<unsignedchar>> ; "
"struct CImgList<last<char>> ; "
"struct CImgList<last<unsignedshort>> ; "
"struct CImgList<last<short>> ; "
"struct CImgList<last<unsignedint>> ; "
"struct CImgList<last<int>> ; "
"struct CImgList<last<unsignedlong>> ; "
"struct CImgList<last<long>> ; "
"struct CImgList<last<unsignedlonglong>> ; "
"struct CImgList<last<longlong>> ; "
"struct CImgList<last<float>> ; "
"struct CImgList<last<double>> ; "
"struct CImgList<last<longdouble>> ; "
"CImgList<last<bool>> c1 ; "
"CImgList<last<signedchar>> c2 ; "
"CImgList<last<unsignedchar>> c3 ; "
"CImgList<last<char>> c4 ; "
"CImgList<last<unsignedshort>> c5 ; "
"CImgList<last<short>> c6 ; "
"CImgList<last<unsignedint>> c7 ; "
"CImgList<last<int>> c8 ; "
"CImgList<last<unsignedlong>> c9 ; "
"CImgList<last<long>> c10 ; "
"CImgList<last<unsignedlonglong>> c11 ; "
"CImgList<last<longlong>> c12 ; "
"CImgList<last<float>> c13 ; "
"CImgList<last<double>> c14 ; "
"CImgList<last<longdouble>> c15 ; "
"struct CImgList<last<bool>> { last<bool> t ; } ; "
"struct CImgList<last<signedchar>> { last<signedchar> t ; } ; "
"struct CImgList<last<unsignedchar>> { last<unsignedchar> t ; } ; "
"struct CImgList<last<char>> { last<char> t ; } ; "
"struct CImgList<last<unsignedshort>> { last<unsignedshort> t ; } ; "
"struct CImgList<last<short>> { last<short> t ; } ; "
"struct CImgList<last<unsignedint>> { last<unsignedint> t ; } ; "
"struct CImgList<last<int>> { last<int> t ; } ; "
"struct CImgList<last<unsignedlong>> { last<unsignedlong> t ; } ; "
"struct CImgList<last<long>> { last<long> t ; } ; "
"struct CImgList<last<unsignedlonglong>> { last<unsignedlonglong> t ; } ; "
"struct CImgList<last<longlong>> { last<longlong> t ; } ; "
"struct CImgList<last<float>> { last<float> t ; } ; "
"struct CImgList<last<double>> { last<double> t ; } ; "
"struct CImgList<last<longdouble>> { last<longdouble> t ; } ; "
"struct last<bool> { bool t ; } ; "
"struct last<signedchar> { signed char t ; } ; "
"struct last<unsignedchar> { unsigned char t ; } ; "
"struct last<char> { char t ; } ; "
"struct last<unsignedshort> { unsigned short t ; } ; "
"struct last<short> { short t ; } ; "
"struct last<unsignedint> { unsigned int t ; } ; "
"struct last<int> { int t ; } ; "
"struct last<unsignedlong> { unsigned long t ; } ; "
"struct last<long> { long t ; } ; "
"struct last<unsignedlonglong> { unsigned long long t ; } ; "
"struct last<longlong> { long long t ; } ; "
"struct last<float> { float t ; } ; "
"struct last<double> { double t ; } ; "
"struct last<longdouble> { long double t ; } ;";
ASSERT_EQUALS(exp, tok(code));
}
void template170() { // crash
const char code[] = "template <int b> int a = 0;\n"
"void c() {\n"
" a<1>;\n"
" [](auto b) {};\n"
"}";
const char exp[] = "int a<1> ; a<1> = 0 ; "
"void c ( ) { "
"a<1> ; "
"[ ] ( auto b ) { } ; "
"}";
ASSERT_EQUALS(exp, tok(code));
}
void template171() { // crash
const char code[] = "template <int> struct c { enum { b }; };\n"
"template <int> struct h { enum { d }; enum { e }; };\n"
"template <int f, long = h<f>::d, int g = h<f>::e> class i { enum { e = c<g>::b }; };\n"
"void j() { i<2> a; }";
const char exp[] = "struct c<h<2>::e> ; "
"struct h<2> ; "
"class i<2,h<2>::d,h<2>::e> ; "
"void j ( ) { i<2,h<2>::d,h<2>::e> a ; } "
"class i<2,h<2>::d,h<2>::e> { enum Anonymous3 { e = c<h<2>::e> :: b } ; } ; "
"struct h<2> { enum Anonymous1 { d } ; enum Anonymous2 { e } ; } ; "
"struct c<h<2>::e> { enum Anonymous0 { b } ; } ;";
const char act[] = "struct c<h<2>::e> ; "
"template < int > struct h { enum Anonymous1 { d } ; enum Anonymous2 { e } ; } ; "
"class i<2,h<2>::d,h<2>::e> ; "
"void j ( ) { i<2,h<2>::d,h<2>::e> a ; } "
"class i<2,h<2>::d,h<2>::e> { enum Anonymous3 { e = c<h<2>::e> :: b } ; } ; "
"struct c<h<2>::e> { enum Anonymous0 { b } ; } ;";
TODO_ASSERT_EQUALS(exp, act, tok(code));
}
void template172() { // #10258 crash
const char code[] = "template<typename T, typename... Args>\n"
"void bar(T t, Args&&... args) { }\n"
"void foo() { bar<int>(0, 1); }";
const char exp[] = "void bar<int> ( int t , Args && ... args ) ; "
"void foo ( ) { bar<int> ( 0 , 1 ) ; } "
"void bar<int> ( int t , Args && ... args ) { }";
ASSERT_EQUALS(exp, tok(code));
}
void template173() { // #10332 crash
const char code[] = "namespace a {\n"
"template <typename, typename> struct b;\n"
"template <template <typename, typename> class = b> class c;\n"
"using d = c<>;\n"
"template <template <typename, typename = void> class> class c {};\n"
"}\n"
"namespace std {\n"
"template <> void swap<a::d>(a::d &, a::d &) {}\n"
"}";
const char exp[] = "namespace a { "
"template < typename , typename > struct b ; "
"template < template < typename , typename > class > class c ; "
"class c<b> ; "
"} "
"namespace std { "
"void swap<a::c<b>> ( a :: c<b> & , a :: c<b> & ) ; "
"void swap<a::c<b>> ( a :: c<b> & , a :: c<b> & ) { } "
"} "
"class a :: c<b> { } ;";
ASSERT_EQUALS(exp, tok(code));
}
void template174()
{ // #10506 hang
const char code[] = "namespace a {\n"
"template <typename> using b = int;\n"
"template <typename c> c d() { return d<b<c>>(); }\n"
"}\n"
"void e() { a::d<int>(); }\n";
const char exp[] = "namespace a { int d<int> ( ) ; } "
"void e ( ) { a :: d<int> ( ) ; } "
"int a :: d<int> ( ) { return d < int > ( ) ; }";
ASSERT_EQUALS(exp, tok(code));
}
void template175() // #10908
{
const char code[] = "template <typename T, int value> T Get() {return value;}\n"
"char f() { Get<int,10>(); }\n";
const char exp[] = "int Get<int,10> ( ) ; "
"char f ( ) { Get<int,10> ( ) ; } "
"int Get<int,10> ( ) { return 10 ; }";
ASSERT_EQUALS(exp, tok(code));
}
void template176() // #11146 don't crash
{
const char code[] = "struct a {\n"
" template <typename> class b {};\n"
"};\n"
"struct c {\n"
" template <typename> a::b<int> d();\n"
" ;\n"
"};\n"
"template <typename> a::b<int> c::d() {}\n"
"template <> class a::b<int> c::d<int>() { return {}; };\n";
const char exp[] = "struct a { "
"class b<int> c :: d<int> ( ) ; "
"template < typename > class b { } ; "
"} ; "
"struct c { a :: b<int> d<int> ( ) ; } ; "
"class a :: b<int> c :: d<int> ( ) { return { } ; } ; "
"a :: b<int> c :: d<int> ( ) { }";
ASSERT_EQUALS(exp, tok(code));
}
void template177() {
const char code[] = "template <typename Encoding, typename Allocator>\n"
"class C { xyz<Encoding, Allocator> x; };\n"
"C<UTF8<>, MemoryPoolAllocator<>> c;";
const char exp[] = "class C<UTF8<>,MemoryPoolAllocator<>> ; "
"C<UTF8<>,MemoryPoolAllocator<>> c ; "
"class C<UTF8<>,MemoryPoolAllocator<>> { xyz < UTF8 < > , MemoryPoolAllocator < > > x ; } ;";
ASSERT_EQUALS(exp, tok(code));
}
void template178() {
const char code[] = "template<typename T>\n" // #11893
"void g() {\n"
" for (T i = 0; i < T{ 3 }; ++i) {}\n"
"}\n"
"void f() {\n"
" g<int>();\n"
"}";
const char exp[] = "void g<int> ( ) ; void f ( ) { g<int> ( ) ; } void g<int> ( ) { for ( int i = 0 ; i < int { 3 } ; ++ i ) { } }";
ASSERT_EQUALS(exp, tok(code));
const char code2[] = "template<typename T>\n"
"struct S {\n"
" T c;\n"
" template<typename U>\n"
" void g() {\n"
" for (U i = 0; i < U{ 3 }; ++i) {}\n"
" }\n"
"};\n"
"void f() {\n"
" S<char> s{};\n"
" s.g<int>();\n"
"}";
const char exp2[] = "struct S<char> ; void f ( ) { S<char> s { } ; s . g<int> ( ) ; } struct S<char> { char c ; void g<int> ( ) ; } ; "
"void S<char> :: g<int> ( ) { for ( int i = 0 ; i < int { 3 } ; ++ i ) { } }";
ASSERT_EQUALS(exp2, tok(code2));
}
void template_specialization_1() { // #7868 - template specialization template <typename T> struct S<C<T>> {..};
const char code[] = "template <typename T> struct C {};\n"
"template <typename T> struct S {a};\n"
"template <typename T> struct S<C<T>> {b};\n"
"S<int> s;";
const char exp[] = "template < typename T > struct C { } ; struct S<int> ; template < typename T > struct S < C < T > > { b } ; S<int> s ; struct S<int> { a } ;";
ASSERT_EQUALS(exp, tok(code));
}
void template_specialization_2() { // #7868 - template specialization template <typename T> struct S<C<T>> {..};
const char code[] = "template <typename T> struct C {};\n"
"template <typename T> struct S {a};\n"
"template <typename T> struct S<C<T>> {b};\n"
"S<C<int>> s;";
const char exp[] = "template < typename T > struct C { } ; template < typename T > struct S { a } ; struct S<C<int>> ; S<C<int>> s ; struct S<C<int>> { b } ;";
ASSERT_EQUALS(exp, tok(code));
}
void template_specialization_3() {
const char code[] = "namespace N {\n" // #12312
" template <typename T>\n"
" bool equal(const T&);\n"
" template <>\n"
" bool equal<int>(const int&) { return false; }\n"
"}\n"
"void f(bool equal, int i) { if (equal) {} }\n";
const char exp[] = "namespace N { "
"bool equal<int> ( const int & ) ; "
"template < typename T > "
"bool equal ( const T & ) ; "
"bool equal<int> ( const int & ) { return false ; } "
"} "
"void f ( bool equal , int i ) { if ( equal ) { } }";
ASSERT_EQUALS(exp, tok(code));
}
void template_enum() {
const char code1[] = "template <class T>\n"
"struct Unconst {\n"
" typedef T type;\n"
"};\n"
"template <class T>\n"
"struct Unconst<const T> {\n"
" typedef T type;\n"
"};\n"
"template <class T>\n"
"struct Unconst<const T&> {\n"
" typedef T& type;\n"
"};\n"
"template <class T>\n"
"struct Unconst<T* const> {\n"
" typedef T* type;\n"
"};\n"
"template <class T1, class T2>\n"
"struct type_equal {\n"
" enum { value = 0 };\n"
"};\n"
"template <class T>\n"
"struct type_equal<T, T> {\n"
" enum { value = 1 };\n"
"};\n"
"template<class T>\n"
"struct template_is_const\n"
"{\n"
" enum {value = !type_equal<T, typename Unconst<T>::type>::value };\n"
"};";
const char exp1[] = "template < class T > struct Unconst { } ; "
"template < class T > struct Unconst < const T > { } ; "
"template < class T > struct Unconst < const T & > { } ; "
"template < class T > struct Unconst < T * const > { } ; "
"template < class T1 , class T2 > struct type_equal { enum Anonymous0 { value = 0 } ; } ; "
"template < class T > struct type_equal < T , T > { enum Anonymous1 { value = 1 } ; } ; "
"template < class T > struct template_is_const { enum Anonymous2 { value = ! type_equal < T , Unconst < T > :: type > :: value } ; } ;";
ASSERT_EQUALS(exp1, tok(code1));
}
void template_default_parameter() {
{
const char code[] = "template <class T, int n=3>\n"
"class A\n"
"{ T ar[n]; };\n"
"\n"
"void f()\n"
"{\n"
" A<int,2> a1;\n"
" A<int> a2;\n"
"}\n";
const char expected[] = "class A<int,2> ; "
"class A<int,3> ; "
"void f ( ) "
"{"
" A<int,2> a1 ;"
" A<int,3> a2 ; "
"} "
"class A<int,2> "
"{ int ar [ 2 ] ; } ; "
"class A<int,3> "
"{ int ar [ 3 ] ; } ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "template <class T, int n1=3, int n2=2>\n"
"class A\n"
"{ T ar[n1+n2]; };\n"
"\n"
"void f()\n"
"{\n"
" A<int> a1;\n"
" A<int,3> a2;\n"
"}\n";
const char expected[] = "class A<int,3,2> ; "
"void f ( ) "
"{"
" A<int,3,2> a1 ;"
" A<int,3,2> a2 ; "
"} "
"class A<int,3,2> "
"{ int ar [ 3 + 2 ] ; } ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "template <class T, int n=3>\n"
"class A\n"
"{ T ar[n]; };\n"
"\n"
"void f()\n"
"{\n"
" A<int,(int)2> a1;\n"
" A<int> a2;\n"
"}\n";
const char expected[] = "class A<int,(int)2> ; "
"class A<int,3> ; "
"void f ( ) "
"{ "
"A<int,(int)2> a1 ; "
"A<int,3> a2 ; "
"} "
"class A<int,(int)2> "
"{ int ar [ ( int ) 2 ] ; } ; "
"class A<int,3> "
"{ int ar [ 3 ] ; } ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "class A { }; "
"template<class T> class B { }; "
"template<class T1, class T2 = B<T1>> class C { }; "
"template<class T1 = A, typename T2 = B<A>> class D { };";
ASSERT_EQUALS("class A { } ; "
"template < class T > class B { } ; "
"template < class T1 , class T2 = B < T1 > > class C { } ; "
"template < class T1 = A , typename T2 = B < A > > class D { } ;", tok(code));
}
{
// #7548
const char code[] = "template<class T, class U> class DefaultMemory {}; "
"template<class Key, class Val, class Mem=DefaultMemory<Key,Val> > class thv_table_c {}; "
"thv_table_c<void *,void *> id_table_m;";
const char exp[] = "template < class T , class U > class DefaultMemory { } ; "
"class thv_table_c<void*,void*,DefaultMemory<void*,void*>> ; "
"thv_table_c<void*,void*,DefaultMemory<void*,void*>> id_table_m ; "
"class thv_table_c<void*,void*,DefaultMemory<void*,void*>> { } ;";
ASSERT_EQUALS(exp, tok(code));
}
{
// #8890
const char code[] = "template <typename = void> struct a {\n"
" void c();\n"
"};\n"
"void f() {\n"
" a<> b;\n"
" b.a<>::c();\n"
"}";
ASSERT_EQUALS("struct a<void> ; "
"void f ( ) { "
"a<void> b ; "
"b . a<void> :: c ( ) ; "
"} "
"struct a<void> { "
"void c ( ) ; "
"} ;", tok(code));
}
{
// #8890
const char code[] = "template< typename T0 = void > class A;\n"
"template<>\n"
"class A< void > {\n"
" public:\n"
" A() { }\n"
" ~A() { }\n"
" void Print() { std::cout << \"A\" << std::endl; }\n"
"};\n"
"class B : public A<> {\n"
" public:\n"
" B() { }\n"
" ~B() { }\n"
"};\n"
"int main( int argc, char* argv[] ) {\n"
" B b;\n"
" b.A<>::Print();\n"
" return 0;\n"
"}";
ASSERT_EQUALS("class A<void> ; "
"template < typename T0 > class A ; "
"class A<void> { "
"public: "
"A<void> ( ) { } "
"~ A<void> ( ) { } "
"void Print ( ) { std :: cout << \"A\" << std :: endl ; } "
"} ; "
"class B : public A<void> { "
"public: "
"B ( ) { } "
"~ B ( ) { } "
"} ; "
"int main ( int argc , char * argv [ ] ) { "
"B b ; "
"b . A<void> :: Print ( ) ; "
"return 0 ; "
"}", tok(code));
}
}
void template_forward_declared_default_parameter() {
{
const char code[] = "template <class T, int n=3> class A;\n"
"template <class T, int n>\n"
"class A\n"
"{ T ar[n]; };\n"
"\n"
"void f()\n"
"{\n"
" A<int,2> a1;\n"
" A<int> a2;\n"
"}\n";
const char exp[] = "class A<int,2> ; "
"class A<int,3> ; "
"void f ( ) "
"{"
" A<int,2> a1 ;"
" A<int,3> a2 ; "
"} "
"class A<int,2> "
"{ int ar [ 2 ] ; } ; "
"class A<int,3> "
"{ int ar [ 3 ] ; } ;";
ASSERT_EQUALS(exp, tok(code));
}
{
const char code[] = "template <class, int = 3> class A;\n"
"template <class T, int n>\n"
"class A\n"
"{ T ar[n]; };\n"
"\n"
"void f()\n"
"{\n"
" A<int,2> a1;\n"
" A<int> a2;\n"
"}\n";
const char exp[] = "class A<int,2> ; "
"class A<int,3> ; "
"void f ( ) "
"{"
" A<int,2> a1 ;"
" A<int,3> a2 ; "
"} "
"class A<int,2> "
"{ int ar [ 2 ] ; } ; "
"class A<int,3> "
"{ int ar [ 3 ] ; } ;";
ASSERT_EQUALS(exp, tok(code));
}
{
const char code[] = "template<typename Lhs, int TriangularPart = (int(Lhs::Flags) & LowerTriangularBit)>\n"
"struct ei_solve_triangular_selector;\n"
"template<typename Lhs, int UpLo>\n"
"struct ei_solve_triangular_selector<Lhs,UpLo> {\n"
"};\n"
"template<typename Lhs, int TriangularPart>\n"
"struct ei_solve_triangular_selector { };";
const char exp[] = "template < typename Lhs , int TriangularPart = ( int ( Lhs :: Flags ) & LowerTriangularBit ) > "
"struct ei_solve_triangular_selector ; "
"template < typename Lhs , int UpLo > "
"struct ei_solve_triangular_selector < Lhs , UpLo > { "
"} ; "
"template < typename Lhs , int TriangularPart = ( int ( Lhs :: Flags ) & LowerTriangularBit ) > "
"struct ei_solve_triangular_selector { } ;";
ASSERT_EQUALS(exp, tok(code));
}
{ // #10432
const char code[] = "template<int A = 128, class T = wchar_t>\n"
"class Foo;\n"
"template<int A, class T>\n"
"class Foo\n"
"{\n"
"public:\n"
" T operator[](int Index) const;\n"
"};\n"
"template<int A, class T>\n"
"T Foo<A, T>::operator[](int Index) const\n"
"{\n"
" return T{};\n"
"}\n"
"Foo<> f;";
const char exp[] = "class Foo<128,wchar_t> ; Foo<128,wchar_t> f ; "
"class Foo<128,wchar_t> { public: wchar_t operator[] ( int Index ) const ; } ; "
"wchar_t Foo<128,wchar_t> :: operator[] ( int Index ) const { return wchar_t { } ; }";
ASSERT_EQUALS(exp, tok(code));
}
}
void template_default_type() {
const char code[] = "template <typename T, typename U=T>\n"
"class A\n"
"{\n"
"public:\n"
" void foo() {\n"
" int a;\n"
" a = static_cast<U>(a);\n"
" }\n"
"};\n"
"\n"
"template <typename T>\n"
"class B\n"
"{\n"
"protected:\n"
" A<int> a;\n"
"};\n"
"\n"
"class C\n"
" : public B<int>\n"
"{\n"
"};\n";
(void)tok(code);
//ASSERT_EQUALS("[file1.cpp:15]: (error) Internal error: failed to instantiate template. The checking continues anyway.\n", errout_str());
ASSERT_EQUALS("", errout_str());
}
void template_typename() {
{
const char code[] = "template <class T>\n"
"void foo(typename T::t *)\n"
"{ }";
// The expected result..
const char expected[] = "template < class T > void foo ( T :: t * ) { }";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "void f() {\n"
" x(sizeof typename);\n"
" type = 0;\n"
"}";
ASSERT_EQUALS("void f ( ) { x ( sizeof ( typename ) ) ; type = 0 ; }", tok(code));
}
}
void template_constructor() {
// #3152 - if template constructor is removed then there might be
// "no constructor" false positives
const char code[] = "class Fred {\n"
" template<class T> explicit Fred(T t) { }\n"
"};";
ASSERT_EQUALS("class Fred { template < class T > explicit Fred ( T t ) { } } ;", tok(code));
// #3532
const char code2[] = "class Fred {\n"
" template<class T> Fred(T t) { }\n"
"};";
ASSERT_EQUALS("class Fred { template < class T > Fred ( T t ) { } } ;", tok(code2));
}
void syntax_error_templates_1() {
// ok code.. using ">" for a comparison
ASSERT_NO_THROW(tok("x<y>z> xyz;"));
ASSERT_EQUALS("", errout_str());
// ok code
ASSERT_NO_THROW(tok("template<class T> operator<(T a, T b) { }"));
ASSERT_EQUALS("", errout_str());
// ok code (ticket #1984)
ASSERT_NO_THROW(tok("void f(a) int a;\n"
"{ ;x<y; }"));
ASSERT_EQUALS("", errout_str());
// ok code (ticket #1985)
ASSERT_NO_THROW(tok("void f()\n"
"{ try { ;x<y; } }"));
ASSERT_EQUALS("", errout_str());
// ok code (ticket #3183)
ASSERT_NO_THROW(tok("MACRO(({ i < x }))"));
ASSERT_EQUALS("", errout_str());
// bad code.. missing ">"
ASSERT_THROW_INTERNAL(tok("x<y<int> xyz;\n"), SYNTAX);
// bad code
ASSERT_THROW_INTERNAL(tok("typedef\n"
" typename boost::mpl::if_c<\n"
" _visitableIndex < boost::mpl::size< typename _Visitables::ConcreteVisitables >::value\n"
" , ConcreteVisitable\n"
" , Dummy< _visitableIndex >\n"
" >::type ConcreteVisitableOrDummy;\n"), SYNTAX);
// code is ok, don't show syntax error
ASSERT_NO_THROW(tok("struct A {int a;int b};\n"
"class Fred {"
"public:\n"
" Fred() : a({1,2}) {\n"
" for (int i=0;i<6;i++);\n" // <- no syntax error
" }\n"
"private:\n"
" A a;\n"
"};"));
ASSERT_EQUALS("", errout_str());
//both of these should work but in cppcheck 2.1 only the first option will work (ticket #9843)
{
const std::string expected = "template < long Num > constexpr bool foo < bar < Num > > = true ;";
ASSERT_EQUALS(expected,
tok("template <long Num>\n"
"constexpr bool foo<bar<Num> > = true;\n"));
ASSERT_EQUALS("", errout_str());
ASSERT_EQUALS(expected,
tok("template <long Num>\n"
"constexpr bool foo<bar<Num>> = true;\n"));
ASSERT_EQUALS("", errout_str());
}
}
void template_member_ptr() { // Ticket #5786 (segmentation fault)
(void)tok("struct A {}; "
"struct B { "
"template <void (A::*)() const> struct BB {}; "
"template <bool BT> static bool foo(int) { return true; } "
"void bar() { bool b = foo<true>(0); }"
"};");
(void)tok("struct A {}; "
"struct B { "
"template <void (A::*)() volatile> struct BB {}; "
"template <bool BT> static bool foo(int) { return true; } "
"void bar() { bool b = foo<true>(0); }"
"};");
(void)tok("struct A {}; "
"struct B { "
"template <void (A::*)() const volatile> struct BB {}; "
"template <bool BT> static bool foo(int) { return true; } "
"void bar() { bool b = foo<true>(0); }"
"};");
(void)tok("struct A {}; "
"struct B { "
"template <void (A::*)() volatile const> struct BB {}; "
"template <bool BT> static bool foo(int) { return true; } "
"void bar() { bool b = foo<true>(0); }"
"};");
}
void template_namespace_1() {
// #6570
const char code[] = "namespace {\n"
" template<class T> void Fred(T value) { }\n"
"}\n"
"Fred<int>(123);";
ASSERT_EQUALS("namespace { "
"void Fred<int> ( int value ) ; "
"} "
"Fred<int> ( 123 ) ; "
"void Fred<int> ( int value ) { }", tok(code));
}
void template_namespace_2() {
// #8283
const char code[] = "namespace X {\n"
" template<class T> struct S { };\n"
"}\n"
"X::S<int> s;";
ASSERT_EQUALS("namespace X { "
"struct S<int> ; "
"} "
"X :: S<int> s ; "
"struct X :: S<int> { } ;", tok(code));
}
void template_namespace_3() {
const char code[] = "namespace test16 {\n"
" template <class T> struct foo {\n"
" static void *bar();\n"
" };\n"
" void *test() { return foo<int>::bar(); }\n"
"}";
ASSERT_EQUALS("namespace test16 {"
" struct foo<int> ;"
" void * test ( ) {"
" return foo<int> :: bar ( ) ;"
" } "
"} "
"struct test16 :: foo<int> {"
" static void * bar ( ) ; "
"} ;", tok(code));
}
void template_namespace_4() {
const char code[] = "namespace foo {\n"
" template<class T> class A { void dostuff() {} };\n"
" struct S : public A<int> {\n"
" void f() {\n"
" A<int>::dostuff();\n"
" }\n"
" };\n"
"}";
ASSERT_EQUALS("namespace foo {"
" class A<int> ;"
" struct S : public A<int> {"
" void f ( ) {"
" A<int> :: dostuff ( ) ;"
" }"
" } ; "
"} "
"class foo :: A<int> { void dostuff ( ) { } } ;", tok(code));
}
void template_namespace_5() {
const char code[] = "template<class C> struct S {};\n"
"namespace X { S<int> s; }";
ASSERT_EQUALS("struct S<int> ; "
"namespace X { S<int> s ; } "
"struct S<int> { } ;", tok(code));
}
void template_namespace_6() {
const char code[] = "namespace NS {\n"
"template <typename T> union C {\n"
" char dummy[sizeof(T)];\n"
" T value;\n"
" C();\n"
" ~C();\n"
" C(const C &);\n"
" C & operator = (const C &);\n"
"};\n"
"}\n"
"NS::C<int> intC;\n"
"template <typename T> NS::C<T>::C() {}\n"
"template <typename T> NS::C<T>::~C() {}\n"
"template <typename T> NS::C<T>::C(const NS::C<T> &) {}\n"
"template <typename T> NS::C<T> & NS::C<T>::operator=(const NS::C<T> &) {}";
ASSERT_EQUALS("namespace NS { "
"union C<int> ; "
"} "
"NS :: C<int> intC ; union NS :: C<int> { "
"char dummy [ sizeof ( int ) ] ; "
"int value ; "
"C<int> ( ) ; "
"~ C<int> ( ) ; "
"C<int> ( const NS :: C<int> & ) ; "
"NS :: C<int> & operator= ( const NS :: C<int> & ) ; "
"} ; "
"NS :: C<int> :: C<int> ( ) { } "
"NS :: C<int> :: ~ C<int> ( ) { } "
"NS :: C<int> :: C<int> ( const NS :: C<int> & ) { } "
"NS :: C<int> & NS :: C<int> :: operator= ( const NS :: C<int> & ) { }", tok(code));
}
void template_namespace_7() { // #8768
const char code[] = "namespace N1 {\n"
"namespace N2 {\n"
" struct C { };\n"
" template <class T> struct CT { };\n"
" C c1;\n"
" CT<int> ct1;\n"
"}\n"
"N2::C c2;\n"
"N2::CT<int> ct2;\n"
"}\n"
"N1::N2::C c3;\n"
"N1::N2::CT<int> ct3;";
ASSERT_EQUALS("namespace N1 { "
"namespace N2 { "
"struct C { } ; "
"struct CT<int> ; "
"C c1 ; "
"CT<int> ct1 ; "
"} "
"N2 :: C c2 ; "
"N2 :: CT<int> ct2 ; "
"} "
"N1 :: N2 :: C c3 ; "
"N1 :: N2 :: CT<int> ct3 ; struct N1 :: N2 :: CT<int> { } ;", tok(code));
}
void template_namespace_8() { // #8768
const char code[] = "namespace NS1 {\n"
"namespace NS2 {\n"
" template <typename T>\n"
" struct Fred {\n"
" Fred();\n"
" Fred(const Fred &);\n"
" Fred & operator = (const Fred &);\n"
" ~Fred();\n"
" };\n"
" template <typename T>\n"
" Fred<T>::Fred() { }\n"
" template <typename T>\n"
" Fred<T>::Fred(const Fred<T> & f) { }\n"
" template <typename T>\n"
" Fred<T> & Fred<T>::operator = (const Fred<T> & f) { }\n"
" template <typename T>\n"
" Fred<T>::~Fred() { }\n"
"}\n"
"}\n"
"NS1::NS2::Fred<int> fred;";
ASSERT_EQUALS("namespace NS1 { "
"namespace NS2 { "
"struct Fred<int> ; "
"} "
"} "
"NS1 :: NS2 :: Fred<int> fred ; struct NS1 :: NS2 :: Fred<int> { "
"Fred<int> ( ) ; "
"Fred<int> ( const NS1 :: NS2 :: Fred<int> & ) ; "
"NS1 :: NS2 :: Fred<int> & operator= ( const NS1 :: NS2 :: Fred<int> & ) ; "
"~ Fred<int> ( ) ; "
"} ; "
"NS1 :: NS2 :: Fred<int> :: Fred<int> ( ) { } "
"NS1 :: NS2 :: Fred<int> :: Fred<int> ( const NS1 :: NS2 :: Fred<int> & f ) { } "
"NS1 :: NS2 :: Fred<int> & NS1 :: NS2 :: Fred<int> :: operator= ( const NS1 :: NS2 :: Fred<int> & f ) { } "
"NS1 :: NS2 :: Fred<int> :: ~ Fred<int> ( ) { }", tok(code));
}
void template_namespace_9() {
const char code[] = "namespace NS {\n"
"template<int type> struct Barney;\n"
"template<> struct Barney<1> { };\n"
"template<int type>\n"
"class Fred {\n"
"public:\n"
" Fred();\n"
"private:\n"
" Barney<type> m_data;\n"
"};\n"
"template class Fred<1>;\n"
"}\n";
ASSERT_EQUALS("namespace NS { "
"struct Barney<1> ; "
"template < int type > struct Barney ; "
"struct Barney<1> { } ; "
"class Fred<1> ; "
"} "
"class NS :: Fred<1> { "
"public: "
"Fred<1> ( ) ; "
"private: "
"Barney<1> m_data ; "
"} ;", tok(code));
}
void template_namespace_10() {
const char code[] = "namespace NS1 {\n"
"namespace NS2 {\n"
"template<class T>\n"
"class Fred {\n"
" T * t;\n"
"public:\n"
" Fred<T>() : t(nullptr) {}\n"
"};\n"
"}\n"
"}\n"
"NS1::NS2::Fred<int> fred;";
ASSERT_EQUALS("namespace NS1 { "
"namespace NS2 { "
"class Fred<int> ; "
"} "
"} "
"NS1 :: NS2 :: Fred<int> fred ; class NS1 :: NS2 :: Fred<int> "
"{ "
"int * t ; "
"public: "
"Fred<int> ( ) : t ( nullptr ) { } "
"} ;", tok(code));
}
void template_namespace_11() {// #7145
const char code[] = "namespace MyNamespace {\n"
"class TestClass {\n"
"public:\n"
" TestClass() {\n"
" SomeFunction();\n"
" TemplatedMethod< int >( 0 );\n"
" }\n"
" void SomeFunction() { }\n"
"private:\n"
" template< typename T > T TemplatedMethod(T);\n"
"};\n"
"template< typename T > T TestClass::TemplatedMethod(T t) { return t; }\n"
"}";
ASSERT_EQUALS("namespace MyNamespace { "
"class TestClass { "
"public: "
"TestClass ( ) { "
"SomeFunction ( ) ; "
"TemplatedMethod<int> ( 0 ) ; "
"} "
"void SomeFunction ( ) { } "
"private: "
"int TemplatedMethod<int> ( int ) ; "
"} ; "
"} int MyNamespace :: TestClass :: TemplatedMethod<int> ( int t ) { return t ; }", tok(code));
}
void template_namespace_12() {
const char code[] = "struct S {};\n" // #13444
"namespace N {\n"
" template<>\n"
" struct hash<S> {};\n"
"}\n"
"struct T {\n"
" T(int i) : hash(i) {}\n"
" int hash;\n"
"};\n";
ASSERT_EQUALS("struct S { } ; "
"namespace N { "
"struct hash<S> { } ; "
"} "
"struct T { "
"T ( int i ) : hash ( i ) { } "
"int hash ; "
"} ;",
tok(code));
}
void template_pointer_type() {
const char code[] = "template<class T> void foo(const T x) {}\n"
"void bar() { foo<int*>(0); }";
ASSERT_EQUALS("void foo<int*> ( int * const x ) ; "
"void bar ( ) { foo<int*> ( 0 ) ; } "
"void foo<int*> ( int * const x ) { }", tok(code));
}
void template_array_type() {
ASSERT_EQUALS("void foo<int[]> ( int [ ] x ) ; "
"void bar ( ) { int y [ 3 ] ; foo<int[]> ( y ) ; } "
"void foo<int[]> ( int [ ] x ) { }",
tok("template <class T> void foo(T x) {};\n"
"void bar() {\n"
" int y[3];\n"
" foo<int[]>(y);\n"
"}"));
ASSERT_EQUALS("struct A<int[2]> ; "
"A<int[2]> y ; "
"struct A<int[2]> { int [ 2 ] x ; } ;",
tok("template <class T> struct A { T x; };\n"
"A<int[2]> y;"));
// Previously resulted in:
// test.cpp:2:33: error: Syntax Error: AST broken, binary operator '>' doesn't have two operands. [internalAstError]
ASSERT_EQUALS("struct A<B<int>[]> ; "
"struct B<B<int>> ; "
"struct C<B<int>> ; "
"C<B<int>> y ; "
"struct C<B<int>> : B<B<int>> { } ; "
"struct B<B<int>> { A<B<int>[]> x ; } ; "
"struct A<B<int>[]> { } ;",
tok("template <class > struct A {};\n"
"template <class T> struct B { A<T[]> x; };\n"
"template <class T> struct C : B<T> {};\n"
"C<B<int>> y;"));
}
unsigned int templateParameters(const char code[]) {
Tokenizer tokenizer(settings, *this);
std::istringstream istr(code);
if (!tokenizer.list.createTokens(istr, "test.cpp"))
return false;
tokenizer.createLinks();
tokenizer.splitTemplateRightAngleBrackets(false);
for (const Token *tok1 = tokenizer.tokens(); tok1; tok1 = tok1->next()) {
if (tok1->str() == "var1")
(const_cast<Token *>(tok1))->varId(1);
}
return TemplateSimplifier::templateParameters(tokenizer.tokens()->next());
}
void templateParameters() {
// Test that the function TemplateSimplifier::templateParameters works
ASSERT_EQUALS(1U, templateParameters("X<struct C> x;"));
ASSERT_EQUALS(1U, templateParameters("X<union C> x;"));
ASSERT_EQUALS(1U, templateParameters("X<const int> x;"));
ASSERT_EQUALS(1U, templateParameters("X<int const *> x;"));
ASSERT_EQUALS(1U, templateParameters("X<const struct C> x;"));
ASSERT_EQUALS(0U, templateParameters("X<len>>x;"));
ASSERT_EQUALS(1U, templateParameters("X<typename> x;"));
ASSERT_EQUALS(0U, templateParameters("X<...> x;"));
ASSERT_EQUALS(0U, templateParameters("X<class T...> x;")); // Invalid syntax
ASSERT_EQUALS(1U, templateParameters("X<class... T> x;"));
ASSERT_EQUALS(0U, templateParameters("X<class, typename T...> x;")); // Invalid syntax
ASSERT_EQUALS(2U, templateParameters("X<class, typename... T> x;"));
ASSERT_EQUALS(2U, templateParameters("X<int(&)(), class> x;"));
ASSERT_EQUALS(3U, templateParameters("X<char, int(*)(), bool> x;"));
ASSERT_EQUALS(1U, templateParameters("X<int...> x;"));
ASSERT_EQUALS(2U, templateParameters("X<class, typename...> x;"));
ASSERT_EQUALS(2U, templateParameters("X<1, T> x;"));
ASSERT_EQUALS(1U, templateParameters("X<T[]> x;"));
ASSERT_EQUALS(1U, templateParameters("X<T[2]> x;"));
ASSERT_EQUALS(1U, templateParameters("X<i == 0> x;"));
ASSERT_EQUALS(2U, templateParameters("X<int, i>=0> x;"));
ASSERT_EQUALS(3U, templateParameters("X<int, i>=0, i - 2> x;"));
ASSERT_EQUALS(0U, templateParameters("var1<1> x;"));
ASSERT_EQUALS(0U, templateParameters("X<1>2;"));
ASSERT_EQUALS(2U, templateParameters("template<typename...B,typename=SameSize<B...>> x;"));
ASSERT_EQUALS(2U, templateParameters("template<typename...B,typename=SameSize<B...> > x;"));
ASSERT_EQUALS(1U, templateParameters("template<template<typename>...Foo> x;"));
ASSERT_EQUALS(1U, templateParameters("template<template<typename>> x;"));
ASSERT_EQUALS(1U, templateParameters("template<template<template<typename>>> x;"));
ASSERT_EQUALS(1U, templateParameters("template<template<template<template<typename>>>> x;"));
ASSERT_EQUALS(1U, templateParameters("template<template<template<template<template<typename>>>>> x;"));
ASSERT_EQUALS(2U, templateParameters("template<template<typename>,int> x;"));
ASSERT_EQUALS(2U, templateParameters("template<template<template<typename>>,int> x;"));
ASSERT_EQUALS(2U, templateParameters("template<template<template<template<typename>>>,int> x;"));
ASSERT_EQUALS(2U, templateParameters("template<template<template<template<template<typename>>>>,int> x;"));
ASSERT_EQUALS(2U, templateParameters("template<template<typename>...Foo,template<template<template<typename>>>> x;"));
ASSERT_EQUALS(3U, templateParameters("template<template<typename>...Foo,int,template<template<template<typename>>>> x;"));
ASSERT_EQUALS(4U, templateParameters("template<template<typename>...Foo,int,template<template<template<typename>>>,int> x;"));
ASSERT_EQUALS(2U, templateParameters("template<typename S, enable_if_t<(is_compile_string<S>::value), int>> void i(S s);"));
ASSERT_EQUALS(2U, templateParameters("template<typename c, b<(c::d), int>> void e();"));
ASSERT_EQUALS(3U, templateParameters("template <class T, class... Args, class Tup = std::tuple<Args&...>> constexpr void f() {}")); // #11351
ASSERT_EQUALS(3U, templateParameters("template <class T, class... Args, class Tup = std::tuple<Args&&...>> void f() {}"));
ASSERT_EQUALS(3U, templateParameters("template <class T, class... Args, class Tup = std::tuple<Args*...>> void f() {}"));
ASSERT_EQUALS(1U, templateParameters("S<4 < sizeof(uintptr_t)> x;"));
ASSERT_EQUALS(2U, templateParameters("template <typename... Ts, typename = std::enable_if_t<std::is_same<Ts..., int>::value>> void g() {}")); // #11915
ASSERT_EQUALS(1U, templateParameters("S<N::M<O<\"A\"_I>>> s;")); // #10837
}
// Helper function to unit test TemplateSimplifier::getTemplateNamePosition
int templateNamePositionHelper(const char code[], unsigned offset = 0) {
Tokenizer tokenizer(settings, *this);
std::istringstream istr(code);
if (!tokenizer.list.createTokens(istr, "test.cpp"))
return false;
tokenizer.createLinks();
tokenizer.splitTemplateRightAngleBrackets(false);
const Token *_tok = tokenizer.tokens();
for (unsigned i = 0; i < offset; ++i)
_tok = _tok->next();
return tokenizer.mTemplateSimplifier->getTemplateNamePosition(_tok);
}
void templateNamePosition() {
// Template class
ASSERT_EQUALS(2, templateNamePositionHelper("template<class T> class A {};", 4));
ASSERT_EQUALS(2, templateNamePositionHelper("template<class T> struct A {};", 4));
ASSERT_EQUALS(2, templateNamePositionHelper("template<class T> class A : B {};", 4));
ASSERT_EQUALS(2, templateNamePositionHelper("template<class T> struct A : B {};", 4));
// Template function definitions
ASSERT_EQUALS(2, templateNamePositionHelper("template<class T> unsigned foo() { return 0; }", 4));
ASSERT_EQUALS(3, templateNamePositionHelper("template<class T> unsigned* foo() { return 0; }", 4));
ASSERT_EQUALS(4, templateNamePositionHelper("template<class T> unsigned** foo() { return 0; }", 4));
ASSERT_EQUALS(3, templateNamePositionHelper("template<class T> const unsigned foo() { return 0; }", 4));
ASSERT_EQUALS(4, templateNamePositionHelper("template<class T> const unsigned& foo() { return 0; }", 4));
ASSERT_EQUALS(5, templateNamePositionHelper("template<class T> const unsigned** foo() { return 0; }", 4));
ASSERT_EQUALS(4, templateNamePositionHelper("template<class T> std::string foo() { static str::string str; return str; }", 4));
ASSERT_EQUALS(5, templateNamePositionHelper("template<class T> std::string & foo() { static str::string str; return str; }", 4));
ASSERT_EQUALS(6, templateNamePositionHelper("template<class T> const std::string & foo() { static str::string str; return str; }", 4));
ASSERT_EQUALS(9, templateNamePositionHelper("template<class T> std::map<int, int> foo() { static std::map<int, int> m; return m; }", 4));
ASSERT_EQUALS(10, templateNamePositionHelper("template<class T> std::map<int, int> & foo() { static std::map<int, int> m; return m; }", 4));
ASSERT_EQUALS(11, templateNamePositionHelper("template<class T> const std::map<int, int> & foo() { static std::map<int, int> m; return m; }", 4));
// Class template members
ASSERT_EQUALS(4, templateNamePositionHelper(
"class A { template<class T> unsigned foo(); }; "
"template<class T> unsigned A::foo() { return 0; }", 19));
ASSERT_EQUALS(5, templateNamePositionHelper(
"class A { template<class T> const unsigned foo(); }; "
"template<class T> const unsigned A::foo() { return 0; }", 20));
ASSERT_EQUALS(7, templateNamePositionHelper(
"class A { class B { template<class T> const unsigned foo(); }; } ; "
"template<class T> const unsigned A::B::foo() { return 0; }", 25));
ASSERT_EQUALS(8, templateNamePositionHelper(
"class A { class B { template<class T> const unsigned * foo(); }; } ; "
"template<class T> const unsigned * A::B::foo() { return 0; }", 26));
ASSERT_EQUALS(9, templateNamePositionHelper(
"class A { class B { template<class T> const unsigned ** foo(); }; } ; "
"template<class T> const unsigned ** A::B::foo() { return 0; }", 27));
// Template class member
ASSERT_EQUALS(6, templateNamePositionHelper(
"template<class T> class A { A(); }; "
"template<class T> A<T>::A() {}", 18));
ASSERT_EQUALS(8, templateNamePositionHelper(
"template<class T, class U> class A { A(); }; "
"template<class T, class U> A<T, U>::A() {}", 24));
ASSERT_EQUALS(7, templateNamePositionHelper(
"template<class T> class A { unsigned foo(); }; "
"template<class T> unsigned A<T>::foo() { return 0; }", 19));
ASSERT_EQUALS(9, templateNamePositionHelper(
"template<class T, class U> class A { unsigned foo(); }; "
"template<class T, class U> unsigned A<T, U>::foo() { return 0; }", 25));
ASSERT_EQUALS(12, templateNamePositionHelper(
"template<> unsigned A<int, v<char> >::foo() { return 0; }", 2));
}
// Helper function to unit test TemplateSimplifier::findTemplateDeclarationEnd
bool findTemplateDeclarationEndHelper(const char code[], const char pattern[], unsigned offset = 0) {
Tokenizer tokenizer(settings, *this);
std::istringstream istr(code);
if (!tokenizer.list.createTokens(istr, "test.cpp"))
return false;
tokenizer.createLinks();
tokenizer.splitTemplateRightAngleBrackets(false);
const Token *_tok = tokenizer.tokens();
for (unsigned i = 0; i < offset; ++i)
_tok = _tok->next();
const Token *tok1 = TemplateSimplifier::findTemplateDeclarationEnd(_tok);
return (tok1 == Token::findsimplematch(tokenizer.list.front(), pattern, strlen(pattern)));
}
void findTemplateDeclarationEnd() {
ASSERT(findTemplateDeclarationEndHelper("template <typename T> class Fred { }; int x;", "; int x ;"));
ASSERT(findTemplateDeclarationEndHelper("template <typename T> void Fred() { } int x;", "} int x ;"));
ASSERT(findTemplateDeclarationEndHelper("template <typename T> int Fred = 0; int x;", "; int x ;"));
ASSERT(findTemplateDeclarationEndHelper("template <typename T> constexpr auto func = [](auto x){ return T(x);}; int x;", "; int x ;"));
ASSERT(findTemplateDeclarationEndHelper("template <class, class a> auto b() -> decltype(a{}.template b<void(int, int)>); int x;", "; int x ;"));
ASSERT(findTemplateDeclarationEndHelper("template <class, class a> auto b() -> decltype(a{}.template b<void(int, int)>){} int x;", "} int x ;"));
ASSERT(findTemplateDeclarationEndHelper("template <typename... f, c<h<e<typename f::d...>>::g>> void i(); int x;", "; int x ;"));
ASSERT(findTemplateDeclarationEndHelper("template <typename... f, c<h<e<typename f::d...>>::g>> void i(){} int x;", "} int x ;"));
}
// Helper function to unit test TemplateSimplifier::getTemplateParametersInDeclaration
bool getTemplateParametersInDeclarationHelper(const char code[], const std::vector<std::string> & params) {
Tokenizer tokenizer(settings, *this);
std::istringstream istr(code);
if (!tokenizer.list.createTokens(istr, "test.cpp"))
return false;
tokenizer.createLinks();
tokenizer.splitTemplateRightAngleBrackets(false);
std::vector<const Token *> typeParametersInDeclaration;
TemplateSimplifier::getTemplateParametersInDeclaration(tokenizer.tokens()->tokAt(2), typeParametersInDeclaration);
if (params.size() != typeParametersInDeclaration.size())
return false;
for (size_t i = 0; i < typeParametersInDeclaration.size(); ++i) {
if (typeParametersInDeclaration[i]->str() != params[i])
return false;
}
return true;
}
void getTemplateParametersInDeclaration() {
ASSERT(getTemplateParametersInDeclarationHelper("template<typename T> class Fred {};", std::vector<std::string> {"T"}));
ASSERT(getTemplateParametersInDeclarationHelper("template<typename T=int> class Fred {};", std::vector<std::string> {"T"}));
ASSERT(getTemplateParametersInDeclarationHelper("template<typename T,typename U> class Fred {};", std::vector<std::string> {"T","U"}));
ASSERT(getTemplateParametersInDeclarationHelper("template<typename T,typename U=int> class Fred {};", std::vector<std::string> {"T","U"}));
ASSERT(getTemplateParametersInDeclarationHelper("template<typename T=int,typename U=int> class Fred {};", std::vector<std::string> {"T","U"}));
}
void expandSpecialized1() {
ASSERT_EQUALS("class A<int> { } ;", tok("template<> class A<int> {};"));
ASSERT_EQUALS("class A<int> : public B { } ;", tok("template<> class A<int> : public B {};"));
ASSERT_EQUALS("class A<int> { A<int> ( ) ; ~ A<int> ( ) ; } ;", tok("template<> class A<int> { A(); ~A(); };"));
ASSERT_EQUALS("class A<int> { A<int> ( ) { } ~ A<int> ( ) { } } ;", tok("template<> class A<int> { A() {} ~A() {} };"));
ASSERT_EQUALS("class A<int> { A<int> ( ) ; ~ A<int> ( ) ; } ; A<int> :: A<int> ( ) { } ~ A<int> :: A<int> ( ) { }",
tok("template<> class A<int> { A(); ~A(); }; A<int>::A() { } ~A<int>::A() {}"));
ASSERT_EQUALS("class A<int> { A<int> ( ) ; A<int> ( const A<int> & ) ; A<int> foo ( ) ; } ; A<int> :: A<int> ( ) { } A<int> :: A<int> ( const A<int> & ) { } A<int> A<int> :: foo ( ) { A<int> a ; return a ; }",
tok("template<> class A<int> { A(); A(const A &) ; A foo(); }; A<int>::A() { } A<int>::A(const A &) { } A<int> A<int>::foo() { A a; return a; }"));
}
void expandSpecialized2() {
{
const char code[] = "template <>\n"
"class C<float> {\n"
"public:\n"
" C() { }\n"
" C(const C &) { }\n"
" ~C() { }\n"
" C & operator=(const C &) { return *this; }\n"
"};\n"
"C<float> b;\n";
const char expected[] = "class C<float> { "
"public: "
"C<float> ( ) { } "
"C<float> ( const C<float> & ) { } "
"~ C<float> ( ) { } "
"C<float> & operator= ( const C<float> & ) { return * this ; } "
"} ; "
"C<float> b ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "template <>\n"
"class C<float> {\n"
"public:\n"
" C() { }\n"
" C(const C &) { }\n"
" ~C() { }\n"
" C & operator=(const C &) { return *this; }\n"
"};";
const char expected[] = "class C<float> { "
"public: "
"C<float> ( ) { } "
"C<float> ( const C<float> & ) { } "
"~ C<float> ( ) { } "
"C<float> & operator= ( const C<float> & ) { return * this ; } "
"} ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "template <>\n"
"class C<float> {\n"
"public:\n"
" C();\n"
" C(const C &);\n"
" ~C();\n"
" C & operator=(const C &);\n"
"};\n"
"C::C() { }\n"
"C::C(const C &) { }\n"
"C::~C() { }\n"
"C & C::operator=(const C &) { return *this; }\n"
"C<float> b;\n";
const char expected[] = "class C<float> { "
"public: "
"C<float> ( ) ; "
"C<float> ( const C<float> & ) ; "
"~ C<float> ( ) ; "
"C<float> & operator= ( const C<float> & ) ; "
"} ; "
"C<float> :: C<float> ( ) { } "
"C<float> :: C<float> ( const C<float> & ) { } "
"C<float> :: ~ C<float> ( ) { } "
"C<float> & C<float> :: operator= ( const C<float> & ) { return * this ; } "
"C<float> b ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "template <>\n"
"class C<float> {\n"
"public:\n"
" C();\n"
" C(const C &);\n"
" ~C();\n"
" C & operator=(const C &);\n"
"};\n"
"C::C() { }\n"
"C::C(const C &) { }\n"
"C::~C() { }\n"
"C & C::operator=(const C &) { return *this; }";
const char expected[] = "class C<float> { "
"public: "
"C<float> ( ) ; "
"C<float> ( const C<float> & ) ; "
"~ C<float> ( ) ; "
"C<float> & operator= ( const C<float> & ) ; "
"} ; "
"C<float> :: C<float> ( ) { } "
"C<float> :: C<float> ( const C<float> & ) { } "
"C<float> :: ~ C<float> ( ) { } "
"C<float> & C<float> :: operator= ( const C<float> & ) { return * this ; }";
ASSERT_EQUALS(expected, tok(code));
}
}
void expandSpecialized3() { // #8671
const char code[] = "template <> struct OutputU16<unsigned char> final {\n"
" explicit OutputU16(std::basic_ostream<unsigned char> &t) : outputStream_(t) {}\n"
" void operator()(unsigned short) const;\n"
"private:\n"
" std::basic_ostream<unsigned char> &outputStream_;\n"
"};";
const char expected[] = "struct OutputU16<unsignedchar> { "
"explicit OutputU16<unsignedchar> ( std :: basic_ostream < unsigned char > & t ) : outputStream_ ( t ) { } "
"void operator() ( unsigned short ) const ; "
"private: "
"std :: basic_ostream < unsigned char > & outputStream_ ; "
"} ;";
ASSERT_EQUALS(expected, tok(code));
}
void expandSpecialized4() {
{
const char code[] = "template<> class C<char> { };\n"
"map<int> m;";
const char expected[] = "class C<char> { } ; "
"map < int > m ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "template<> class C<char> { };\n"
"map<int> m;\n"
"C<char> c;";
const char expected[] = "class C<char> { } ; "
"map < int > m ; "
"C<char> c ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "template<typename T> class C { };\n"
"template<> class C<char> { };\n"
"map<int> m;\n";
const char expected[] = "class C<char> ; "
"template < typename T > class C { } ; "
"class C<char> { } ; "
"map < int > m ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "template<typename T> class C { };\n"
"template<> class C<char> { };\n"
"map<int> m;\n"
"C<int> i;";
const char expected[] = "class C<char> ; "
"class C<int> ; "
"class C<char> { } ; "
"map < int > m ; "
"C<int> i ; "
"class C<int> { } ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "template<typename T> class C { };\n"
"template<> class C<char> { };\n"
"map<int> m;\n"
"C<int> i;\n"
"C<char> c;";
const char expected[] = "class C<char> ; "
"class C<int> ; "
"class C<char> { } ; "
"map < int > m ; "
"C<int> i ; "
"C<char> c ; "
"class C<int> { } ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "class A {};\n"
"template<typename T> struct B;\n"
"template<> struct B<A> {};\n"
"int f() {\n"
" int B[1] = {};\n"
" return B[0];\n"
"}\n";
const char expected[] = "class A { } ; "
"struct B<A> ; "
"template < typename T > struct B ; "
"struct B<A> { } ; "
"int f ( ) { "
"int B [ 1 ] = { } ; "
"return B [ 0 ] ; "
"}";
ASSERT_EQUALS(expected, tok(code));
}
}
void expandSpecialized5() {
const char code[] = "template<typename T> class hash;\n" // #10494
"template<> class hash<int> {};\n"
"int f(int i) {\n"
" int hash = i;\n"
" const int a[2]{};\n"
" return a[hash];\n"
"}\n";
const char expected[] = "class hash<int> ; "
"template < typename T > class hash ; "
"class hash<int> { } ; "
"int f ( int i ) { "
"int hash ; hash = i ; "
"const int a [ 2 ] { } ; "
"return a [ hash ] ; "
"}";
ASSERT_EQUALS(expected, tok(code));
}
void templateAlias1() {
const char code[] = "template<class T, int N> struct Foo {};\n"
"template<class T> using Bar = Foo<T,3>;\n"
"Bar<int> b;\n";
const char expected[] = "struct Foo<int,3> ; "
"Foo<int,3> b ; "
"struct Foo<int,3> { } ;";
ASSERT_EQUALS(expected, tok(code));
}
void templateAlias2() {
const char code[] = "namespace A { template<class T, int N> struct Foo {}; }\n"
"template<class T> using Bar = A::Foo<T,3>;\n"
"Bar<int> b;\n";
const char expected[] = "namespace A { struct Foo<int,3> ; } "
"A :: Foo<int,3> b ; "
"struct A :: Foo<int,3> { } ;";
ASSERT_EQUALS(expected, tok(code));
}
void templateAlias3() { // #8315
const char code[] = "template <int> struct Tag {};\n"
"template <int ID> using SPtr = std::shared_ptr<void(Tag<ID>)>;\n"
"SPtr<0> s;";
const char expected[] = "struct Tag<0> ; "
"std :: shared_ptr < void ( Tag<0> ) > s ; "
"struct Tag<0> { } ;";
ASSERT_EQUALS(expected, tok(code));
}
void templateAlias4() { // #9070
const char code[] = "template <class T>\n"
"using IntrusivePtr = boost::intrusive_ptr<T>;\n"
"template <class T> class Vertex { };\n"
"IntrusivePtr<Vertex<int>> p;";
const char expected[] = "class Vertex<int> ; "
"boost :: intrusive_ptr < Vertex<int> > p ; "
"class Vertex<int> { } ;";
ASSERT_EQUALS(expected, tok(code));
}
void templateAlias5() {
const char code[] = "template<typename T> using A = int;\n"
"template<typename T> using B = T;\n"
"A<char> a;\n"
"B<char> b;";
const char expected[] = "int a ; "
"char b ;";
ASSERT_EQUALS(expected, tok(code));
}
#define instantiateMatch(code, numberOfArguments, patternAfter) instantiateMatch_(code, numberOfArguments, patternAfter, __FILE__, __LINE__)
template<size_t size>
bool instantiateMatch_(const char (&code)[size], const std::size_t numberOfArguments, const char patternAfter[], const char* file, int line) {
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
return (TemplateSimplifier::instantiateMatch)(tokenizer.tokens(), numberOfArguments, false, patternAfter);
}
void instantiateMatchTest() {
// Ticket #8175
ASSERT_EQUALS(false,
instantiateMatch("ConvertHelper < From, To > c ;",
2, ":: %name% ("));
ASSERT_EQUALS(true,
instantiateMatch("ConvertHelper < From, To > :: Create ( ) ;",
2, ":: %name% ("));
ASSERT_EQUALS(false,
instantiateMatch("integral_constant < bool, sizeof ( ConvertHelper < From, To > :: Create ( ) ) > ;",
2, ":: %name% ("));
ASSERT_EQUALS(false,
instantiateMatch("integral_constant < bool, sizeof ( ns :: ConvertHelper < From, To > :: Create ( ) ) > ;",
2, ":: %name% ("));
}
void templateParameterWithoutName() {
ASSERT_EQUALS(1U, templateParameters("template<typename = void> struct s;"));
ASSERT_EQUALS(1U, templateParameters("template<template<typename = float> typename T> struct A {\n"
" void f();\n"
" void g();\n"
"};n"));
}
void templateTypeDeduction1() { // #8962
const char code[] = "template<typename T>\n"
"void f(T n) { (void)n; }\n"
"static void func() {\n"
" f(0);\n"
" f(0u);\n"
" f(0U);\n"
" f(0l);\n"
" f(0L);\n"
" f(0ul);\n"
" f(0UL);\n"
" f(0ll);\n"
" f(0LL);\n"
" f(0ull);\n"
" f(0ULL);\n"
" f(0.0);\n"
" f(0.0f);\n"
" f(0.0F);\n"
" f(0.0l);\n"
" f(0.0L);\n"
" f('c');\n"
" f(L'c');\n"
" f(\"string\");\n"
" f(L\"string\");\n"
" f(true);\n"
" f(false);\n"
"}";
const char expected[] = "void f<int> ( int n ) ; "
"void f<unsignedint> ( unsigned int n ) ; "
"void f<long> ( long n ) ; "
"void f<unsignedlong> ( unsigned long n ) ; "
"void f<longlong> ( long long n ) ; "
"void f<unsignedlonglong> ( unsigned long long n ) ; "
"void f<double> ( double n ) ; "
"void f<float> ( float n ) ; "
"void f<longdouble> ( long double n ) ; "
"void f<char> ( char n ) ; "
"void f<wchar_t> ( wchar_t n ) ; "
"void f<constchar*> ( const char * n ) ; "
"void f<constwchar_t*> ( const wchar_t * n ) ; "
"void f<bool> ( bool n ) ; "
"static void func ( ) { "
"f<int> ( 0 ) ; "
"f<unsignedint> ( 0u ) ; "
"f<unsignedint> ( 0U ) ; "
"f<long> ( 0l ) ; "
"f<long> ( 0L ) ; "
"f<unsignedlong> ( 0ul ) ; "
"f<unsignedlong> ( 0UL ) ; "
"f<longlong> ( 0ll ) ; "
"f<longlong> ( 0LL ) ; "
"f<unsignedlonglong> ( 0ull ) ; "
"f<unsignedlonglong> ( 0ULL ) ; "
"f<double> ( 0.0 ) ; "
"f<float> ( 0.0f ) ; "
"f<float> ( 0.0F ) ; "
"f<longdouble> ( 0.0l ) ; "
"f<longdouble> ( 0.0L ) ; "
"f<char> ( 'c' ) ; "
"f<wchar_t> ( L'c' ) ; "
"f<constchar*> ( \"string\" ) ; "
"f<constwchar_t*> ( L\"string\" ) ; "
"f<bool> ( true ) ; "
"f<bool> ( false ) ; "
"} "
"void f<int> ( int n ) { ( void ) n ; } "
"void f<unsignedint> ( unsigned int n ) { ( void ) n ; } "
"void f<long> ( long n ) { ( void ) n ; } "
"void f<unsignedlong> ( unsigned long n ) { ( void ) n ; } "
"void f<longlong> ( long long n ) { ( void ) n ; } "
"void f<unsignedlonglong> ( unsigned long long n ) { ( void ) n ; } "
"void f<double> ( double n ) { ( void ) n ; } "
"void f<float> ( float n ) { ( void ) n ; } "
"void f<longdouble> ( long double n ) { ( void ) n ; } "
"void f<char> ( char n ) { ( void ) n ; } "
"void f<wchar_t> ( wchar_t n ) { ( void ) n ; } "
"void f<constchar*> ( const char * n ) { ( void ) n ; } "
"void f<constwchar_t*> ( const wchar_t * n ) { ( void ) n ; } "
"void f<bool> ( bool n ) { ( void ) n ; }";
ASSERT_EQUALS(expected, tok(code));
ASSERT_EQUALS("", errout_str());
}
void templateTypeDeduction2() {
const char code[] = "template<typename T, typename U>\n"
"void f(T t, U u) { }\n"
"static void func() {\n"
" f(0, 0.0);\n"
" f(0.0, 0);\n"
"}";
const char expected[] = "void f<int,double> ( int t , double u ) ; "
"void f<double,int> ( double t , int u ) ; "
"static void func ( ) { "
"f<int,double> ( 0 , 0.0 ) ; "
"f<double,int> ( 0.0, 0 ) ; "
"void f<int,double> ( int t , double u ) { } "
"void f<double,int> ( double t , int u ) { } ";
const char actual[] = "template < typename T , typename U > "
"void f ( T t , U u ) { } "
"static void func ( ) { "
"f ( 0 , 0.0 ) ; "
"f ( 0.0 , 0 ) ; "
"}";
TODO_ASSERT_EQUALS(expected, actual, tok(code));
}
void templateTypeDeduction3() { // #9975
const char code[] = "struct A {\n"
" int a = 1;\n"
" void f() { g(1); }\n"
" template <typename T> void g(T x) { a = 2; }\n"
"};\n"
"int main() {\n"
" A a;\n"
" a.f();\n"
"}";
const char exp[] = "struct A { "
"int a ; a = 1 ; "
"void f ( ) { g<int> ( 1 ) ; } "
"void g<int> ( int x ) ; "
"} ; "
"int main ( ) { "
"A a ; "
"a . f ( ) ; "
"} void A :: g<int> ( int x ) { a = 2 ; }";
ASSERT_EQUALS(exp, tok(code));
}
void templateTypeDeduction4() { // #9983
{
const char code[] = "int a = 1;\n"
"template <typename T> void f(T x, T y) { a = x + y; }\n"
"void test() { f(0, 0); }";
const char exp[] = "int a ; a = 1 ; "
"void f<int> ( int x , int y ) ; "
"void test ( ) { f<int> ( 0 , 0 ) ; } "
"void f<int> ( int x , int y ) { a = x + y ; }";
ASSERT_EQUALS(exp, tok(code));
}
{
const char code[] = "int a = 1;\n"
"template <typename T> void f(T x, double y) { a = x + y; }\n"
"void test() { f(0, 0.0); }";
const char exp[] = "int a ; a = 1 ; "
"void f<int> ( int x , double y ) ; "
"void test ( ) { f<int> ( 0 , 0.0 ) ; } "
"void f<int> ( int x , double y ) { a = x + y ; }";
ASSERT_EQUALS(exp, tok(code));
}
{
const char code[] = "int a = 1;\n"
"template <typename T> void f(double x, T y) { a = x + y; }\n"
"void test() { f(0.0, 0); }";
const char exp[] = "int a ; a = 1 ; "
"void f<int> ( double x , int y ) ; "
"void test ( ) { f<int> ( 0.0 , 0 ) ; } "
"void f<int> ( double x , int y ) { a = x + y ; }";
ASSERT_EQUALS(exp, tok(code));
}
{
const char code[] = "int a = 1;\n"
"template <typename T> void f(double x, T y) { a = x + y; }\n"
"template <typename T> void f(int x, T y) { a = x + y; }\n"
"void test() {\n"
" f(0, 0);\n"
" f(0.0, 0);\n"
" f(0, 0.0);\n"
" f(0.0, 0.0);\n"
"}";
const char exp[] = "int a ; a = 1 ; "
"void f<int> ( int x , int y ) ; "
"void f<int> ( double x , int y ) ; "
"void f<double> ( int x , double y ) ; "
"void f<double> ( double x , double y ) ; "
"void test ( ) { "
"f<int> ( 0 , 0 ) ; "
"f<int> ( 0.0 , 0 ) ; "
"f<double> ( 0 , 0.0 ) ; "
"f<double> ( 0.0 , 0.0 ) ; "
"} "
"void f<int> ( int x , int y ) { a = x + y ; } "
"void f<int> ( double x , int y ) { a = x + y ; } "
"void f<double> ( int x , double y ) { a = x + y ; } "
"void f<double> ( double x , double y ) { a = x + y ; }";
const char act[] = "int a ; a = 1 ; "
"template < typename T > void f ( double x , T y ) { a = x + y ; } "
"void f<int> ( int x , int y ) ; void f<double> ( int x , double y ) ; "
"void test ( ) { "
"f<int> ( 0 , 0 ) ; "
"f<int> ( 0.0 , 0 ) ; "
"f<double> ( 0 , 0.0 ) ; "
"f<double> ( 0.0 , 0.0 ) ; "
"} "
"void f<int> ( int x , int y ) { a = x + y ; } "
"void f<double> ( int x , double y ) { a = x + y ; }";
TODO_ASSERT_EQUALS(exp, act, tok(code));
}
{
const char code[] = "int a = 1;\n"
"template <typename T, typename U> void f(T x, U y) { a = x + y; }\n"
"void test() { f(0, 0.0); }";
const char exp[] = "int a ; a = 1 ; "
"void f<int,double> ( int x , double y ) ; "
"void test ( ) { f<int,double> ( 0 , 0.0 ) ; } "
"void f<int,double> ( int x , double y ) { a = x + y ; }";
const char act[] = "int a ; a = 1 ; "
"template < typename T , typename U > void f ( T x , U y ) { a = x + y ; } "
"void test ( ) { f ( 0 , 0.0 ) ; }";
TODO_ASSERT_EQUALS(exp, act, tok(code));
}
}
void templateTypeDeduction5() {
{
const char code[] = "class Fred {\n"
"public:\n"
" template <class T> Fred(T t) { }\n"
"};\n"
"Fred fred1 = Fred(0);\n"
"Fred fred2 = Fred(0.0);\n"
"Fred fred3 = Fred(\"zero\");\n"
"Fred fred4 = Fred(false);";
const char exp[] = "class Fred { "
"public: "
"Fred<int> ( int t ) ; "
"Fred<double> ( double t ) ; "
"Fred<constchar*> ( const char * t ) ; "
"Fred<bool> ( bool t ) ; "
"} ; "
"Fred fred1 ; fred1 = Fred<int> ( 0 ) ; "
"Fred fred2 ; fred2 = Fred<double> ( 0.0 ) ; "
"Fred fred3 ; fred3 = Fred<constchar*> ( \"zero\" ) ; "
"Fred fred4 ; fred4 = Fred<bool> ( false ) ; "
"Fred :: Fred<int> ( int t ) { } "
"Fred :: Fred<double> ( double t ) { } "
"Fred :: Fred<constchar*> ( const char * t ) { } "
"Fred :: Fred<bool> ( bool t ) { }";
ASSERT_EQUALS(exp, tok(code));
}
{
const char code[] = "namespace NS {\n"
"class Fred {\n"
"public:\n"
" template <class T> Fred(T t) { }\n"
"};\n"
"Fred fred1 = Fred(0);\n"
"Fred fred2 = Fred(0.0);\n"
"Fred fred3 = Fred(\"zero\");\n"
"Fred fred4 = Fred(false);\n"
"}\n"
"NS::Fred fred1 = NS::Fred(0);\n"
"NS::Fred fred2 = NS::Fred(0.0);\n"
"NS::Fred fred3 = NS::Fred(\"zero\");\n"
"NS::Fred fred4 = NS::Fred(false);\n";
const char exp[] = "namespace NS { "
"class Fred { "
"public: "
"Fred<int> ( int t ) ; "
"Fred<double> ( double t ) ; "
"Fred<constchar*> ( const char * t ) ; "
"Fred<bool> ( bool t ) ; "
"} ; "
"Fred fred1 ; fred1 = Fred<int> ( 0 ) ; "
"Fred fred2 ; fred2 = Fred<double> ( 0.0 ) ; "
"Fred fred3 ; fred3 = Fred<constchar*> ( \"zero\" ) ; "
"Fred fred4 ; fred4 = Fred<bool> ( false ) ; "
"} "
"NS :: Fred fred1 ; fred1 = NS :: Fred<int> ( 0 ) ; "
"NS :: Fred fred2 ; fred2 = NS :: Fred<double> ( 0.0 ) ; "
"NS :: Fred fred3 ; fred3 = NS :: Fred<constchar*> ( \"zero\" ) ; "
"NS :: Fred fred4 ; fred4 = NS :: Fred<bool> ( false ) ; "
"NS :: Fred :: Fred<int> ( int t ) { } "
"NS :: Fred :: Fred<double> ( double t ) { } "
"NS :: Fred :: Fred<constchar*> ( const char * t ) { } "
"NS :: Fred :: Fred<bool> ( bool t ) { }";
ASSERT_EQUALS(exp, tok(code));
}
}
void simplifyTemplateArgs1() {
ASSERT_EQUALS("foo<2> = 2 ; foo<2> ;", tok("template<int N> foo = N; foo < ( 2 ) >;"));
ASSERT_EQUALS("foo<2> = 2 ; foo<2> ;", tok("template<int N> foo = N; foo < 1 + 1 >;"));
ASSERT_EQUALS("foo<2> = 2 ; foo<2> ;", tok("template<int N> foo = N; foo < ( 1 + 1 ) >;"));
ASSERT_EQUALS("foo<2,2> = 4 ; foo<2,2> ;", tok("template<int N, int M> foo = N * M; foo < ( 2 ), ( 2 ) >;"));
ASSERT_EQUALS("foo<2,2> = 4 ; foo<2,2> ;", tok("template<int N, int M> foo = N * M; foo < 1 + 1, 1 + 1 >;"));
ASSERT_EQUALS("foo<2,2> = 4 ; foo<2,2> ;", tok("template<int N, int M> foo = N * M; foo < ( 1 + 1 ), ( 1 + 1 ) >;"));
ASSERT_EQUALS("foo<true> = true ; foo<true> ;", tok("template<bool N> foo = N; foo < true ? true : false >;"));
ASSERT_EQUALS("foo<false> = false ; foo<false> ;", tok("template<bool N> foo = N; foo < false ? true : false >;"));
ASSERT_EQUALS("foo<true> = true ; foo<true> ;", tok("template<bool N> foo = N; foo < 1 ? true : false >;"));
ASSERT_EQUALS("foo<false> = false ; foo<false> ;", tok("template<bool N> foo = N; foo < 0 ? true : false >;"));
ASSERT_EQUALS("foo<true> = true ; foo<true> ;", tok("template<bool N> foo = N; foo < (1 + 1 ) ? true : false >;"));
ASSERT_EQUALS("foo<false> = false ; foo<false> ;", tok("template<bool N> foo = N; foo < ( 1 - 1) ? true : false >;"));
}
void simplifyTemplateArgs2() {
const char code[] = "template<bool T> struct a_t { static const bool t = T; };\n"
"typedef a_t<sizeof(void*) == sizeof(char)> a;\n"
"void foo() { bool b = a::t; }";
const char expected[] = "struct a_t<false> ; "
"void foo ( ) { bool b ; b = a_t<false> :: t ; } "
"struct a_t<false> { static const bool t = false ; } ;";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyTemplateArgs3() { // #11418
const char code[] = "template <class T> struct S {};\n"
"template<typename T>\n"
"T f() {}\n"
"template<typename T, typename U>\n"
"void g() {\n"
" S<decltype(true ? f<T>() : f<U>())> s1;\n"
" S<decltype(false ? f<T>() : f<U>())> s2;\n"
"}\n"
"void h() {\n"
" g<int, char>();\n"
"}\n";
const char expected[] = "struct S<decltype((f<int>()))> ; "
"struct S<decltype(f<char>())> ; "
"int f<int> ( ) ; "
"char f<char> ( ) ; "
"void g<int,char> ( ) ; "
"void h ( ) { g<int,char> ( ) ; } "
"void g<int,char> ( ) { "
"S<decltype((f<int>()))> s1 ; "
"S<decltype(f<char>())> s2 ; "
"} "
"int f<int> ( ) { } "
"char f<char> ( ) { } "
"struct S<decltype((f<int>()))> { } ; "
"struct S<decltype(f<char>())> { } ;";
ASSERT_EQUALS(expected, tok(code));
}
void template_variadic_1() { // #9144
const char code[] = "template <typename...> struct e {};\n"
"static_assert(sizeof(e<>) == sizeof(e<int,int>), \"\");";
const char expected[] = "struct e<> ; struct e<int,int> ; "
"static_assert ( sizeof ( e<> ) == sizeof ( e<int,int> ) , \"\" ) ; "
"struct e<> { } ; struct e<int,int> { } ;";
ASSERT_EQUALS(expected, tok(code));
}
void template_variadic_2() { // #4349
const char code[] = "template<typename T, typename... Args>\n"
"void printf(const char *s, T value, Args... args) {}\n"
"\n"
"int main() {\n"
" printf<int, float>(\"\", foo, bar);\n"
"}";
const char expected[] = "void printf<int,float> ( const char * s , int value , float ) ; "
"int main ( ) { printf<int,float> ( \"\" , foo , bar ) ; } "
"void printf<int,float> ( const char * s , int value , float ) { }";
ASSERT_EQUALS(expected, tok(code));
}
void template_variadic_3() { // #6172
const char code[] = "template<int N, int ... M> struct A { "
" static void foo() { "
" int i = N; "
" } "
"}; "
"void bar() { "
" A<0>::foo(); "
"}";
const char expected[] = "struct A<0> ; "
"void bar ( ) { A<0> :: foo ( ) ; } "
"struct A<0> { static void foo ( ) { int i ; i = 0 ; } } ;";
ASSERT_EQUALS(expected, tok(code));
}
void template_variadic_4() { // #11763
const char code[] = "template <int... N>\n"
"class E {\n"
" template <int... I>\n"
" int f(int n, std::integer_sequence<int, I...>) {\n"
" return (((I == n) ? N : 0) + ...);\n"
" }\n"
"};\n"
"E<1, 3> e;\n";
const char expected[] = "class E<1,3> ; E<1,3> e ; "
"class E<1,3> { "
"template < int ... I > "
"int f ( int n , std :: integer_sequence < int , I ... > ) { "
"return ( ( ( I == n ) ? : 0 ) + ... ) ; "
"} "
"} ;";
ASSERT_EQUALS(expected, tok(code));
}
void template_variable_1() {
{
const char code[] = "template <int N> const int foo = N*N;\n"
"int x = foo<7>;";
const char expected[] = "const int foo<7> = 49 ; "
"int x ; x = foo<7> ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "template <int> const int foo = 7;\n"
"int x = foo<7>;";
const char expected[] = "const int foo<7> = 7 ; "
"int x ; x = foo<7> ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "template <int N = 7> const int foo = N*N;\n"
"int x = foo<7>;";
const char expected[] = "const int foo<7> = 49 ; "
"int x ; x = foo<7> ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "template <int N = 7> const int foo = N*N;\n"
"int x = foo<>;";
const char expected[] = "const int foo<7> = 49 ; "
"int x ; x = foo<7> ;";
ASSERT_EQUALS(expected, tok(code));
}
}
void template_variable_2() {
{
const char code[] = "template<class T> constexpr T pi = T(3.1415926535897932385L);\n"
"float x = pi<float>;";
const char expected[] = "constexpr float pi<float> = float ( 3.1415926535897932385L ) ; "
"float x ; x = pi<float> ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "template<class> constexpr float pi = float(3.1415926535897932385L);\n"
"float x = pi<float>;";
const char expected[] = "constexpr float pi<float> = float ( 3.1415926535897932385L ) ; "
"float x ; x = pi<float> ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "template<class T = float> constexpr T pi = T(3.1415926535897932385L);\n"
"float x = pi<float>;";
const char expected[] = "constexpr float pi<float> = float ( 3.1415926535897932385L ) ; "
"float x ; x = pi<float> ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "template<class T = float> constexpr T pi = T(3.1415926535897932385L);\n"
"float x = pi<>;";
const char expected[] = "constexpr float pi<float> = float ( 3.1415926535897932385L ) ; "
"float x ; x = pi<float> ;";
ASSERT_EQUALS(expected, tok(code));
}
}
void template_variable_3() {
{
const char code[] = "template<class T, int N> constexpr T foo = T(N*N);\n"
"float x = foo<float,7>;";
const char expected[] = "constexpr float foo<float,7> = float ( 49 ) ; "
"float x ; x = foo<float,7> ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "template<class,int> constexpr float foo = float(7);\n"
"float x = foo<float,7>;";
const char expected[] = "constexpr float foo<float,7> = float ( 7 ) ; "
"float x ; x = foo<float,7> ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "template<class T = float, int N = 7> constexpr T foo = T(7);\n"
"double x = foo<double, 14>;";
const char expected[] = "constexpr double foo<double,14> = double ( 7 ) ; "
"double x ; x = foo<double,14> ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "template<class T = float, int N = 7> constexpr T foo = T(7);\n"
"float x = foo<>;";
const char expected[] = "constexpr float foo<float,7> = float ( 7 ) ; "
"float x ; x = foo<float,7> ;";
ASSERT_EQUALS(expected, tok(code));
}
{
const char code[] = "template<class T = float, int N = 7> constexpr T foo = T(7);\n"
"double x = foo<double>;";
const char expected[] = "constexpr double foo<double,7> = double ( 7 ) ; "
"double x ; x = foo<double,7> ;";
ASSERT_EQUALS(expected, tok(code));
}
}
void template_variable_4() {
const char code[] = "template<typename T> void test() { }\n"
"template<typename T> decltype(test<T>)* foo = &(test<T>);\n"
"void bar() { foo<int>(); }";
const char expected[] = "void test<int> ( ) ; "
"decltype ( test<int> ) * foo<int> = & ( test<int> ) ; "
"void bar ( ) { foo<int> ( ) ; } "
"void test<int> ( ) { }";
ASSERT_EQUALS(expected, tok(code));
}
void simplifyDecltype() {
const char code[] = "template<typename T> class type { };\n"
"type<decltype(true)> b;\n"
"type<decltype(0)> i;\n"
"type<decltype(0U)> ui;\n"
"type<decltype(0L)> l;\n"
"type<decltype(0UL)> ul;\n"
"type<decltype(0LL)> ll;\n"
"type<decltype(0ULL)> ull;\n"
"type<decltype(0.0)> d;\n"
"type<decltype(0.0F)> f;\n"
"type<decltype(0.0L)> ld;";
const char expected[] = "class type<bool> ; "
"class type<int> ; "
"class type<unsignedint> ; "
"class type<long> ; "
"class type<unsignedlong> ; "
"class type<longlong> ; "
"class type<unsignedlonglong> ; "
"class type<double> ; "
"class type<float> ; "
"class type<longdouble> ; "
"type<bool> b ; "
"type<int> i ; "
"type<unsignedint> ui ; "
"type<long> l ; "
"type<unsignedlong> ul ; "
"type<longlong> ll ; "
"type<unsignedlonglong> ull ; "
"type<double> d ; "
"type<float> f ; "
"type<longdouble> ld ; "
"class type<bool> { } ; "
"class type<int> { } ; "
"class type<unsignedint> { } ; "
"class type<long> { } ; "
"class type<unsignedlong> { } ; "
"class type<longlong> { } ; "
"class type<unsignedlonglong> { } ; "
"class type<double> { } ; "
"class type<float> { } ; "
"class type<longdouble> { } ;";
ASSERT_EQUALS(expected, tok(code));
}
void castInExpansion() {
const char code[] = "template <int N> class C { };\n"
"template <typename TC> class Base {};\n"
"template <typename TC> class Derived : private Base<TC> {};\n"
"typedef Derived<C<static_cast<int>(-1)> > C_;\n"
"class C3 { C_ c; };";
const char expected[] = "template < int N > class C { } ; "
"class Base<C<static_cast<int>-1>> ; "
"class Derived<C<static_cast<int>-1>> ; "
"class C3 { Derived<C<static_cast<int>-1>> c ; } ; "
"class Derived<C<static_cast<int>-1>> : private Base<C<static_cast<int>-1>> { } ; "
"class Base<C<static_cast<int>-1>> { } ;";
ASSERT_EQUALS(expected, tok(code));
}
void fold_expression_1() {
const char code[] = "template<typename... Args> bool all(Args... args) { return (... && args); }\n"
"x=all(true,false,true,true);";
const char expected[] = "template < typename ... Args > bool all ( Args ... args ) { return ( __cppcheck_fold_&&__ ( args ... ) ) ; } x = all ( true , false , true , true ) ;";
ASSERT_EQUALS(expected, tok(code));
}
void fold_expression_2() {
const char code[] = "template<typename... Args> bool all(Args... args) { return (args && ...); }\n"
"x=all(true,false,true,true);";
const char expected[] = "template < typename ... Args > bool all ( Args ... args ) { return ( __cppcheck_fold_&&__ ( args ... ) ) ; } x = all ( true , false , true , true ) ;";
ASSERT_EQUALS(expected, tok(code));
}
void fold_expression_3() {
const char code[] = "template<typename... Args> int foo(Args... args) { return (12 * ... * args); }\n"
"x=foo(1,2);";
const char expected[] = "template < typename ... Args > int foo ( Args ... args ) { return ( __cppcheck_fold_*__ ( args ... ) ) ; } x = foo ( 1 , 2 ) ;";
ASSERT_EQUALS(expected, tok(code));
}
void fold_expression_4() {
const char code[] = "template<typename... Args> int foo(Args... args) { return (args * ... * 123); }\n"
"x=foo(1,2);";
const char expected[] = "template < typename ... Args > int foo ( Args ... args ) { return ( __cppcheck_fold_*__ ( args ... ) ) ; } x = foo ( 1 , 2 ) ;";
ASSERT_EQUALS(expected, tok(code));
}
void concepts1() {
const char code[] = "template <my_concept T> void f(T v) {}\n"
"f<int>(123);";
const char expected[] = "void f<int> ( int v ) ; f<int> ( 123 ) ; void f<int> ( int v ) { }";
ASSERT_EQUALS(expected, tok(code));
}
void requires1() {
const char code[] = "template <class T> requires my_concept<T> void f(T v) {}\n"
"f<int>(123);";
const char expected[] = "void f<int> ( int v ) ; f<int> ( 123 ) ; void f<int> ( int v ) { }";
ASSERT_EQUALS(expected, tok(code));
}
void requires2() {
const char code[] = "template<class T> requires (sizeof(T) > 1 && get_value<T>()) void f(T v){}\n"
"f<int>(123);";
const char expected[] = "void f<int> ( int v ) ; f<int> ( 123 ) ; void f<int> ( int v ) { }";
ASSERT_EQUALS(expected, tok(code));
}
void requires3() {
const char code[] = "template<class T> requires c1<T> && c2<T> void f(T v){}\n"
"f<int>(123);";
const char expected[] = "void f<int> ( int v ) ; f<int> ( 123 ) ; void f<int> ( int v ) { }";
ASSERT_EQUALS(expected, tok(code));
}
void requires4() {
const char code[] = "template <class T> void f(T v) requires my_concept<T> {}\n"
"f<int>(123);";
const char expected[] = "void f<int> ( int v ) ; f<int> ( 123 ) ; void f<int> ( int v ) { }";
ASSERT_EQUALS(expected, tok(code));
}
void requires5() {
const char code[] = "template <class T>\n"
" requires requires (T x) { x + x; }\n"
" T add(T a, T b) { return a + b; }\n"
"add<int>(123,456);";
const char expected[] = "int add<int> ( int a , int b ) ; add<int> ( 123 , 456 ) ; int add<int> ( int a , int b ) { return a + b ; }";
ASSERT_EQUALS(expected, tok(code));
}
void explicitBool1() {
const char code[] = "class Fred { explicit(true) Fred(int); };";
ASSERT_EQUALS("class Fred { explicit Fred ( int ) ; } ;", tok(code));
}
void explicitBool2() {
const char code[] = "class Fred { explicit(false) Fred(int); };";
ASSERT_EQUALS("class Fred { Fred ( int ) ; } ;", tok(code));
}
};
REGISTER_TEST(TestSimplifyTemplate)
| null |
972 | cpp | cppcheck | testpreprocessor.cpp | test/testpreprocessor.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// The preprocessor that Cppcheck uses is a bit special. Instead of generating
// the code for a known configuration, it generates the code for each configuration.
#include "errortypes.h"
#include "path.h"
#include "platform.h"
#include "preprocessor.h"
#include "settings.h"
#include "suppressions.h"
#include "tokenize.h"
#include "tokenlist.h"
#include "fixture.h"
#include "helpers.h"
#include <cstring>
#include <list>
#include <map>
#include <set>
#include <sstream>
#include <string>
#include <vector>
#include <simplecpp.h>
class ErrorLogger;
class TestPreprocessor : public TestFixture {
public:
TestPreprocessor() : TestFixture("TestPreprocessor") {}
private:
static std::string expandMacros(const char code[], ErrorLogger &errorLogger) {
std::istringstream istr(code);
simplecpp::OutputList outputList;
std::vector<std::string> files;
const simplecpp::TokenList tokens1 = simplecpp::TokenList(istr, files, "file.cpp", &outputList);
const Settings settings;
Preprocessor p(settings, errorLogger);
simplecpp::TokenList tokens2 = p.preprocess(tokens1, "", files, true);
p.reportOutput(outputList, true);
return tokens2.stringify();
}
const Settings settings0 = settingsBuilder().severity(Severity::information).build();
void run() override {
// The bug that started the whole work with the new preprocessor
TEST_CASE(Bug2190219);
TEST_CASE(error1); // #error => don't extract any code
TEST_CASE(error2); // #error if symbol is not defined
TEST_CASE(error3);
TEST_CASE(error4); // #2919 - wrong filename is reported
TEST_CASE(error5);
TEST_CASE(error6);
TEST_CASE(error7);
TEST_CASE(error8); // #10170 -> previous #if configurations
TEST_CASE(setPlatformInfo);
// Handling include guards (don't create extra configuration for it)
TEST_CASE(includeguard1);
TEST_CASE(includeguard2);
TEST_CASE(if0);
TEST_CASE(if1);
TEST_CASE(elif);
TEST_CASE(if_cond1);
TEST_CASE(if_cond2);
TEST_CASE(if_cond3);
TEST_CASE(if_cond4);
TEST_CASE(if_cond5);
TEST_CASE(if_cond6);
TEST_CASE(if_cond8);
TEST_CASE(if_cond9);
TEST_CASE(if_cond10);
TEST_CASE(if_cond11);
TEST_CASE(if_cond12);
TEST_CASE(if_cond13);
TEST_CASE(if_cond14);
TEST_CASE(if_or_1);
TEST_CASE(if_or_2);
TEST_CASE(if_macro_eq_macro); // #3536
TEST_CASE(ticket_3675);
TEST_CASE(ticket_3699);
TEST_CASE(ticket_4922); // #4922
// Macros..
TEST_CASE(macro_simple1);
TEST_CASE(macro_simple2);
TEST_CASE(macro_simple3);
TEST_CASE(macro_simple4);
TEST_CASE(macro_simple5);
TEST_CASE(macro_simple6);
TEST_CASE(macro_simple7);
TEST_CASE(macro_simple8);
TEST_CASE(macro_simple9);
TEST_CASE(macro_simple10);
TEST_CASE(macro_simple11);
TEST_CASE(macro_simple12);
TEST_CASE(macro_simple13);
TEST_CASE(macro_simple14);
TEST_CASE(macro_simple15);
TEST_CASE(macro_simple16); // #4703: Macro parameters not trimmed
TEST_CASE(macro_simple17); // #5074: isExpandedMacro not set
TEST_CASE(macro_simple18); // (1e-7)
TEST_CASE(macroInMacro1);
TEST_CASE(macroInMacro2);
TEST_CASE(macro_linenumbers);
TEST_CASE(macro_nopar);
TEST_CASE(macro_incdec); // separate ++ and -- with space when expanding such macro: '#define M(X) A-X'
TEST_CASE(macro_switchCase);
TEST_CASE(macro_NULL); // skip #define NULL .. it is replaced in the tokenizer
TEST_CASE(string1);
TEST_CASE(string2);
TEST_CASE(string3);
TEST_CASE(preprocessor_undef);
TEST_CASE(defdef); // Defined multiple times
TEST_CASE(preprocessor_doublesharp);
TEST_CASE(preprocessor_include_in_str);
TEST_CASE(va_args_1);
//TEST_CASE(va_args_2); invalid code
TEST_CASE(va_args_3);
TEST_CASE(va_args_4);
TEST_CASE(va_args_5);
TEST_CASE(multi_character_character);
TEST_CASE(stringify);
TEST_CASE(stringify2);
TEST_CASE(stringify3);
TEST_CASE(stringify4);
TEST_CASE(stringify5);
TEST_CASE(ifdefwithfile);
TEST_CASE(pragma);
TEST_CASE(pragma_asm_1);
TEST_CASE(pragma_asm_2);
TEST_CASE(endifsemicolon);
TEST_CASE(missing_doublequote);
TEST_CASE(handle_error);
TEST_CASE(dup_defines);
TEST_CASE(define_part_of_func);
TEST_CASE(conditionalDefine);
TEST_CASE(macro_parameters);
TEST_CASE(newline_in_macro);
TEST_CASE(ifdef_ifdefined);
// define and then ifdef
TEST_CASE(define_if1);
TEST_CASE(define_if2);
TEST_CASE(define_if3);
TEST_CASE(define_if4); // #4079 - #define X +123
TEST_CASE(define_if5); // #4516 - #define B (A & 0x00f0)
TEST_CASE(define_if6); // #4863 - #define B (A?-1:1)
TEST_CASE(define_ifdef);
TEST_CASE(define_ifndef1);
TEST_CASE(define_ifndef2);
TEST_CASE(ifndef_define);
TEST_CASE(undef_ifdef);
TEST_CASE(endfile);
TEST_CASE(redundant_config);
TEST_CASE(invalid_define_1); // #2605 - hang for: '#define ='
TEST_CASE(invalid_define_2); // #4036 - hang for: '#define () {(int f(x) }'
// inline suppression, missingInclude/missingIncludeSystem
TEST_CASE(inline_suppressions);
// remark comment
TEST_CASE(remarkComment1);
TEST_CASE(remarkComment2);
TEST_CASE(remarkComment3);
// Using -D to predefine symbols
TEST_CASE(predefine1);
TEST_CASE(predefine2);
TEST_CASE(predefine3);
TEST_CASE(predefine4);
TEST_CASE(predefine5); // automatically define __cplusplus
TEST_CASE(predefine6); // automatically define __STDC_VERSION__
TEST_CASE(invalidElIf); // #2942 segfault
// Preprocessor::getConfigs
TEST_CASE(getConfigs1);
TEST_CASE(getConfigs2);
TEST_CASE(getConfigs3);
TEST_CASE(getConfigs4);
TEST_CASE(getConfigs5);
TEST_CASE(getConfigs7);
TEST_CASE(getConfigs7a);
TEST_CASE(getConfigs7b);
TEST_CASE(getConfigs7c);
TEST_CASE(getConfigs7d);
TEST_CASE(getConfigs7e);
TEST_CASE(getConfigs8); // #if A==1 => cfg: A=1
TEST_CASE(getConfigs10); // #5139
TEST_CASE(getConfigs11); // #9832 - include guards
TEST_CASE(getConfigsError);
TEST_CASE(getConfigsD1);
TEST_CASE(getConfigsU1);
TEST_CASE(getConfigsU2);
TEST_CASE(getConfigsU3);
TEST_CASE(getConfigsU4);
TEST_CASE(getConfigsU5);
TEST_CASE(getConfigsU6);
TEST_CASE(getConfigsU7);
TEST_CASE(if_sizeof);
TEST_CASE(invalid_ifs); // #5909
TEST_CASE(garbage);
TEST_CASE(wrongPathOnErrorDirective);
TEST_CASE(testMissingInclude);
TEST_CASE(testMissingInclude2);
TEST_CASE(testMissingInclude3);
TEST_CASE(testMissingInclude4);
TEST_CASE(testMissingInclude5);
TEST_CASE(testMissingInclude6);
TEST_CASE(testMissingSystemInclude);
TEST_CASE(testMissingSystemInclude2);
TEST_CASE(testMissingSystemInclude3);
TEST_CASE(testMissingSystemInclude4);
TEST_CASE(testMissingSystemInclude5);
TEST_CASE(testMissingIncludeMixed);
TEST_CASE(testMissingIncludeCheckConfig);
TEST_CASE(limitsDefines);
TEST_CASE(hashCalculation);
TEST_CASE(standard);
}
std::string getConfigsStr(const char filedata[], const char *arg = nullptr) {
Settings settings;
if (arg && std::strncmp(arg,"-D",2)==0)
settings.userDefines = arg + 2;
if (arg && std::strncmp(arg,"-U",2)==0)
settings.userUndefs.insert(arg+2);
Preprocessor preprocessor(settings, *this);
std::vector<std::string> files;
std::istringstream istr(filedata);
simplecpp::TokenList tokens(istr,files);
tokens.removeComments();
const std::set<std::string> configs = preprocessor.getConfigs(tokens);
std::string ret;
for (const std::string & config : configs)
ret += config + '\n';
return ret;
}
std::size_t getHash(const char filedata[]) {
Settings settings;
Preprocessor preprocessor(settings, *this);
std::vector<std::string> files;
std::istringstream istr(filedata);
simplecpp::TokenList tokens(istr,files);
tokens.removeComments();
return preprocessor.calculateHash(tokens, "");
}
void Bug2190219() {
const char filedata[] = "#ifdef __cplusplus\n"
"cpp\n"
"#else\n"
"c\n"
"#endif";
{
// Preprocess => actual result..
const std::map<std::string, std::string> actual = PreprocessorHelper::getcode(settings0, *this, filedata, "file.cpp");
// Compare results..
ASSERT_EQUALS(1U, actual.size());
ASSERT_EQUALS("\ncpp", actual.at(""));
}
{
// Ticket #7102 - skip __cplusplus in C code
// Preprocess => actual result..
const std::map<std::string, std::string> actual = PreprocessorHelper::getcode(settings0, *this, filedata, "file.c");
// Compare results..
ASSERT_EQUALS(1U, actual.size());
ASSERT_EQUALS("\n\n\nc", actual.at(""));
}
}
void error1() {
const char filedata[] = "#ifdef A\n"
";\n"
"#else\n"
"#error abcd\n"
"#endif\n";
ASSERT_EQUALS("\nA\n", getConfigsStr(filedata));
}
void error2() {
const char filedata1[] = "#ifndef A\n"
"#error\n"
"#endif\n";
ASSERT_EQUALS("A\n", getConfigsStr(filedata1));
const char filedata2[] = "#if !A\n"
"#error\n"
"#endif\n";
ASSERT_EQUALS("A\n", getConfigsStr(filedata2));
}
void error3() {
const auto settings = dinit(Settings, $.userDefines = "__cplusplus");
const std::string code("#error hello world!\n");
(void)PreprocessorHelper::getcode(settings, *this, code, "X", "test.c");
ASSERT_EQUALS("[test.c:1]: (error) #error hello world!\n", errout_str());
}
// Ticket #2919 - wrong filename reported for #error
void error4() {
// In included file
{
const auto settings = dinit(Settings, $.userDefines = "TEST");
const std::string code("#file \"ab.h\"\n#error hello world!\n#endfile");
(void)PreprocessorHelper::getcode(settings, *this, code, "TEST", "test.c");
ASSERT_EQUALS("[ab.h:1]: (error) #error hello world!\n", errout_str());
}
// After including a file
{
const auto settings = dinit(Settings, $.userDefines = "TEST");
const std::string code("#file \"ab.h\"\n\n#endfile\n#error aaa");
(void)PreprocessorHelper::getcode(settings, *this, code, "TEST", "test.c");
ASSERT_EQUALS("[test.c:2]: (error) #error aaa\n", errout_str());
}
}
void error5() {
// No message if --force is given
const auto settings = dinit(Settings,
$.userDefines = "TEST",
$.force = true);
const std::string code("#error hello world!\n");
(void)PreprocessorHelper::getcode(settings, *this, code, "X", "test.c");
ASSERT_EQUALS("", errout_str());
}
void error6() {
const char filedata1[] = "#ifdef A\n"
"#else\n"
"#error 1\n"
"#endif\n"
"#ifdef B\n"
"#else\n"
"#error 2\n"
"#endif\n";
ASSERT_EQUALS("\nA\nA;B\nB\n", getConfigsStr(filedata1));
const char filedata2[] = "#ifndef A\n"
"#error 1\n"
"#endif\n"
"#ifndef B\n"
"#error 2\n"
"#endif\n";
ASSERT_EQUALS("A;B\n", getConfigsStr(filedata2));
const char filedata3[] = "#if !A\n"
"#error 1\n"
"#endif\n"
"#if !B\n"
"#error 2\n"
"#endif\n";
ASSERT_EQUALS("A;B\n", getConfigsStr(filedata3));
}
void error7() { // #8074
const char filedata[] = "#define A\n"
"\n"
"#if defined(B)\n"
"#else\n"
"#error \"1\"\n"
"#endif\n"
"\n"
"#if defined(A)\n"
"#else\n"
"#error \"2\"\n"
"#endif\n";
ASSERT_EQUALS("\nB\n", getConfigsStr(filedata));
}
void error8() {
const char filedata[] = "#ifdef A\n"
"#ifdef B\n"
"#endif\n"
"#else\n"
"#endif\n"
"\n"
"#ifndef C\n"
"#error aa\n"
"#endif";
ASSERT_EQUALS("A;B;C\nA;C\nC\n", getConfigsStr(filedata));
}
void setPlatformInfo() {
// read code with simplecpp..
const char filedata[] = "#if sizeof(long) == 4\n"
"1\n"
"#else\n"
"2\n"
"#endif\n";
std::istringstream istr(filedata);
std::vector<std::string> files;
simplecpp::TokenList tokens(istr, files, "test.c");
// preprocess code with unix32 platform..
{
const Settings settings = settingsBuilder().platform(Platform::Type::Unix32).build();
Preprocessor::setPlatformInfo(tokens, settings);
Preprocessor preprocessor(settings, *this);
ASSERT_EQUALS("\n1", preprocessor.getcode(tokens, "", files, false));
}
// preprocess code with unix64 platform..
{
const Settings settings = settingsBuilder().platform(Platform::Type::Unix64).build();
Preprocessor::setPlatformInfo(tokens, settings);
Preprocessor preprocessor(settings, *this);
ASSERT_EQUALS("\n\n\n2", preprocessor.getcode(tokens, "", files, false));
}
}
void includeguard1() {
// Handling include guards..
const char filedata[] = "#file \"abc.h\"\n"
"#ifndef abcH\n"
"#define abcH\n"
"#endif\n"
"#endfile\n"
"#ifdef ABC\n"
"#endif";
ASSERT_EQUALS("\nABC\n", getConfigsStr(filedata));
}
void includeguard2() {
// Handling include guards..
const char filedata[] = "#file \"abc.h\"\n"
"foo\n"
"#ifdef ABC\n"
"\n"
"#endif\n"
"#endfile\n";
ASSERT_EQUALS("\nABC\n", getConfigsStr(filedata));
}
void ifdefwithfile() {
// Handling include guards..
const char filedata[] = "#ifdef ABC\n"
"#file \"abc.h\"\n"
"class A{};/*\n\n\n\n\n\n\n*/\n"
"#endfile\n"
"#endif\n"
"int main() {}\n";
// Preprocess => actual result..
const std::map<std::string, std::string> actual = PreprocessorHelper::getcode(settings0, *this, filedata);
// Expected configurations: "" and "ABC"
ASSERT_EQUALS(2, actual.size());
ASSERT_EQUALS("\n\n\nint main ( ) { }", actual.at(""));
ASSERT_EQUALS("\n#line 1 \"abc.h\"\nclass A { } ;\n#line 4 \"file.c\"\n int main ( ) { }", actual.at("ABC"));
}
void if0() {
const char filedata[] = " # if /* comment */ 0 // comment\n"
"#ifdef WIN32\n"
"#endif\n"
"#endif\n";
ASSERT_EQUALS("\n", getConfigsStr(filedata));
}
void if1() {
const char filedata[] = " # if /* comment */ 1 // comment\n"
"ABC\n"
" # endif \n";
ASSERT_EQUALS("\n", getConfigsStr(filedata));
}
void elif() {
{
const char filedata[] = "#if DEF1\n"
"ABC\n"
"#elif DEF2\n"
"DEF\n"
"#endif\n";
ASSERT_EQUALS("\nDEF1\nDEF2\n", getConfigsStr(filedata));
}
{
const char filedata[] = "#if(defined DEF1)\n"
"ABC\n"
"#elif(defined DEF2)\n"
"DEF\n"
"#else\n"
"GHI\n"
"#endif\n";
ASSERT_EQUALS("\nDEF1\nDEF2\n", getConfigsStr(filedata));
}
}
void if_cond1() {
const char filedata[] = "#if LIBVER>100\n"
" A\n"
"#else\n"
" B\n"
"#endif\n";
TODO_ASSERT_EQUALS("\nLIBVER=101\n", "\n", getConfigsStr(filedata));
}
void if_cond2() {
const char filedata[] = "#ifdef A\n"
"a\n"
"#endif\n"
"#if defined(A) && defined(B)\n"
"ab\n"
"#endif\n";
ASSERT_EQUALS("\nA\nA;B\n", getConfigsStr(filedata));
if_cond2b();
if_cond2c();
if_cond2d();
if_cond2e();
}
void if_cond2b() {
const char filedata[] = "#ifndef A\n"
"!a\n"
"#ifdef B\n"
"b\n"
"#endif\n"
"#else\n"
"a\n"
"#endif\n";
TODO_ASSERT_EQUALS("\nA;B\n", "\nA\nB\n", getConfigsStr(filedata));
}
void if_cond2c() {
const char filedata[] = "#ifndef A\n"
"!a\n"
"#ifdef B\n"
"b\n"
"#else\n"
"!b\n"
"#endif\n"
"#else\n"
"a\n"
"#endif\n";
TODO_ASSERT_EQUALS("\nA\nA;B\n", "\nA\nB\n", getConfigsStr(filedata));
}
void if_cond2d() {
const char filedata[] = "#ifndef A\n"
"!a\n"
"#ifdef B\n"
"b\n"
"#else\n"
"!b\n"
"#endif\n"
"#else\n"
"a\n"
"#ifdef B\n"
"b\n"
"#else\n"
"!b\n"
"#endif\n"
"#endif\n";
ASSERT_EQUALS("\nA\nA;B\nB\n", getConfigsStr(filedata));
}
void if_cond2e() {
const char filedata[] = "#if !defined(A)\n"
"!a\n"
"#elif !defined(B)\n"
"!b\n"
"#endif\n";
ASSERT_EQUALS("\nA\nB\n", getConfigsStr(filedata));
}
void if_cond3() {
const char filedata[] = "#ifdef A\n"
"a\n"
"#if defined(B) && defined(C)\n"
"abc\n"
"#endif\n"
"#endif\n";
ASSERT_EQUALS("\nA\nA;B;C\n", getConfigsStr(filedata));
}
void if_cond4() {
{
const char filedata[] = "#define A\n"
"#define B\n"
"#if defined A || defined B\n"
"ab\n"
"#endif\n";
ASSERT_EQUALS("\n", getConfigsStr(filedata));
}
{
const char filedata[] = "#if A\n"
"{\n"
"#if (defined(B))\n"
"foo();\n"
"#endif\n"
"}\n"
"#endif\n";
ASSERT_EQUALS("\nA\nA;B\n", getConfigsStr(filedata));
}
{
const char filedata[] = "#define A\n"
"#define B\n"
"#if (defined A) || defined (B)\n"
"ab\n"
"#endif\n";
ASSERT_EQUALS("\n", getConfigsStr(filedata));
}
{
const char filedata[] = "#if (A)\n"
"foo();\n"
"#endif\n";
ASSERT_EQUALS("\nA\n", getConfigsStr(filedata));
}
{
const char filedata[] = "#if! A\n"
"foo();\n"
"#endif\n";
ASSERT_EQUALS("\nA=0\n", getConfigsStr(filedata));
}
}
void if_cond5() {
const char filedata[] = "#if defined(A) && defined(B)\n"
"ab\n"
"#endif\n"
"cd\n"
"#if defined(B) && defined(A)\n"
"ef\n"
"#endif\n";
ASSERT_EQUALS("\nA;B\n", getConfigsStr(filedata));
}
void if_cond6() {
const char filedata[] = "\n"
"#if defined(A) && defined(B))\n"
"#endif\n";
ASSERT_EQUALS("\nA;B\n", getConfigsStr(filedata));
}
void if_cond8() {
const char filedata[] = "#if defined(A) + defined(B) + defined(C) != 1\n"
"#endif\n";
TODO_ASSERT_EQUALS("\nA\n", "\nA;B;C\n", getConfigsStr(filedata));
}
void if_cond9() {
const char filedata[] = "#if !defined _A\n"
"abc\n"
"#endif\n";
ASSERT_EQUALS("\n_A\n", getConfigsStr(filedata));
}
void if_cond10() {
const char filedata[] = "#if !defined(a) && !defined(b)\n"
"#if defined(and)\n"
"#endif\n"
"#endif\n";
// Preprocess => don't crash..
(void)PreprocessorHelper::getcode(settings0, *this, filedata);
}
void if_cond11() {
const char filedata[] = "#if defined(L_fixunssfdi) && LIBGCC2_HAS_SF_MODE\n"
"#if LIBGCC2_HAS_DF_MODE\n"
"#elif FLT_MANT_DIG < W_TYPE_SIZE\n"
"#endif\n"
"#endif\n";
(void)PreprocessorHelper::getcode(settings0, *this, filedata);
ASSERT_EQUALS("", errout_str());
}
void if_cond12() {
const char filedata[] = "#define A (1)\n"
"#if A == 1\n"
";\n"
"#endif\n";
ASSERT_EQUALS("\n", getConfigsStr(filedata));
}
void if_cond13() {
const char filedata[] = "#if ('A' == 0x41)\n"
"123\n"
"#endif\n";
ASSERT_EQUALS("\n", getConfigsStr(filedata));
}
void if_cond14() {
const char filedata[] = "#if !(A)\n"
"123\n"
"#endif\n";
ASSERT_EQUALS("\n", getConfigsStr(filedata));
}
void if_or_1() {
const char filedata[] = "#if defined(DEF_10) || defined(DEF_11)\n"
"a1;\n"
"#endif\n";
ASSERT_EQUALS("\nDEF_10;DEF_11\n", getConfigsStr(filedata));
}
void if_or_2() {
const char filedata[] = "#if X || Y\n"
"a1;\n"
"#endif\n";
TODO_ASSERT_EQUALS("\nX;Y\n", "\n", getConfigsStr(filedata));
}
void if_macro_eq_macro() {
const char *code = "#define A B\n"
"#define B 1\n"
"#define C 1\n"
"#if A == C\n"
"Wilma\n"
"#else\n"
"Betty\n"
"#endif\n";
ASSERT_EQUALS("\n", getConfigsStr(code));
}
void ticket_3675() {
const char* code = "#ifdef YYSTACKSIZE\n"
"#define YYMAXDEPTH YYSTACKSIZE\n"
"#else\n"
"#define YYSTACKSIZE YYMAXDEPTH\n"
"#endif\n"
"#if YYDEBUG\n"
"#endif\n";
(void)PreprocessorHelper::getcode(settings0, *this, code);
// There's nothing to assert. It just needs to not hang.
}
void ticket_3699() {
const char* code = "#define INLINE __forceinline\n"
"#define inline __forceinline\n"
"#define __forceinline inline\n"
"#if !defined(_WIN32)\n"
"#endif\n"
"INLINE inline __forceinline\n";
const std::map<std::string, std::string> actual = PreprocessorHelper::getcode(settings0, *this, code);
// First, it must not hang. Second, inline must becomes inline, and __forceinline must become __forceinline.
ASSERT_EQUALS("\n\n\n\n\n$__forceinline $inline $__forceinline", actual.at(""));
}
void ticket_4922() { // #4922
const char* code = "__asm__ \n"
"{ int extern __value) 0; (double return (\"\" } extern\n"
"__typeof __finite (__finite) __finite __inline \"__GI___finite\");";
(void)PreprocessorHelper::getcode(settings0, *this, code);
}
void macro_simple1() {
{
const char filedata[] = "#define AAA(aa) f(aa)\n"
"AAA(5);\n";
ASSERT_EQUALS("\nf ( 5 ) ;", expandMacros(filedata, *this));
}
{
const char filedata[] = "#define AAA(aa) f(aa)\n"
"AAA (5);\n";
ASSERT_EQUALS("\nf ( 5 ) ;", expandMacros(filedata, *this));
}
}
void macro_simple2() {
const char filedata[] = "#define min(x,y) x<y?x:y\n"
"min(a(),b());\n";
ASSERT_EQUALS("\na ( ) < b ( ) ? a ( ) : b ( ) ;", expandMacros(filedata, *this));
}
void macro_simple3() {
const char filedata[] = "#define A 4\n"
"A AA\n";
ASSERT_EQUALS("\n4 AA", expandMacros(filedata, *this));
}
void macro_simple4() {
const char filedata[] = "#define TEMP_1 if( temp > 0 ) return 1;\n"
"TEMP_1\n";
ASSERT_EQUALS("\nif ( temp > 0 ) return 1 ;", expandMacros(filedata, *this));
}
void macro_simple5() {
const char filedata[] = "#define ABC if( temp > 0 ) return 1;\n"
"\n"
"void foo()\n"
"{\n"
" int temp = 0;\n"
" ABC\n"
"}\n";
ASSERT_EQUALS("\n\nvoid foo ( )\n{\nint temp = 0 ;\nif ( temp > 0 ) return 1 ;\n}", expandMacros(filedata, *this));
}
void macro_simple6() {
const char filedata[] = "#define ABC (a+b+c)\n"
"ABC\n";
ASSERT_EQUALS("\n( a + b + c )", expandMacros(filedata, *this));
}
void macro_simple7() {
const char filedata[] = "#define ABC(str) str\n"
"ABC(\"(\")\n";
ASSERT_EQUALS("\n\"(\"", expandMacros(filedata, *this));
}
void macro_simple8() {
const char filedata[] = "#define ABC 123\n"
"#define ABCD 1234\n"
"ABC ABCD\n";
ASSERT_EQUALS("\n\n123 1234", expandMacros(filedata, *this));
}
void macro_simple9() {
const char filedata[] = "#define ABC(a) f(a)\n"
"ABC( \"\\\"\" );\n"
"ABC( \"g\" );\n";
ASSERT_EQUALS("\nf ( \"\\\"\" ) ;\nf ( \"g\" ) ;", expandMacros(filedata, *this));
}
void macro_simple10() {
const char filedata[] = "#define ABC(t) t x\n"
"ABC(unsigned long);\n";
ASSERT_EQUALS("\nunsigned long x ;", expandMacros(filedata, *this));
}
void macro_simple11() {
const char filedata[] = "#define ABC(x) delete x\n"
"ABC(a);\n";
ASSERT_EQUALS("\ndelete a ;", expandMacros(filedata, *this));
}
void macro_simple12() {
const char filedata[] = "#define AB ab.AB\n"
"AB.CD\n";
ASSERT_EQUALS("\nab . AB . CD", expandMacros(filedata, *this));
}
void macro_simple13() {
const char filedata[] = "#define TRACE(x)\n"
"TRACE(;if(a))\n";
ASSERT_EQUALS("", expandMacros(filedata, *this));
}
void macro_simple14() {
const char filedata[] = "#define A \" a \"\n"
"printf(A);\n";
ASSERT_EQUALS("\nprintf ( \" a \" ) ;", expandMacros(filedata, *this));
}
void macro_simple15() {
const char filedata[] = "#define FOO\"foo\"\n"
"FOO\n";
ASSERT_EQUALS("\n\"foo\"", expandMacros(filedata, *this));
}
void macro_simple16() { // # 4703
const char filedata[] = "#define MACRO( A, B, C ) class A##B##C##Creator {};\n"
"MACRO( B\t, U , G )";
ASSERT_EQUALS("\nclass BUGCreator { } ;", expandMacros(filedata, *this));
}
void macro_simple17() { // # 5074 - the Token::isExpandedMacro() doesn't always indicate properly if token comes from macro
// It would probably be OK if the generated code was
// "\n123+$123" since the first 123 comes from the source code
const char filedata[] = "#define MACRO(A) A+123\n"
"MACRO(123)";
ASSERT_EQUALS("\n123 + 123", expandMacros(filedata, *this));
}
void macro_simple18() { // (1e-7)
const char filedata1[] = "#define A (1e-7)\n"
"a=A;";
ASSERT_EQUALS("\na = ( 1e-7 ) ;", expandMacros(filedata1, *this));
const char filedata2[] = "#define A (1E-7)\n"
"a=A;";
ASSERT_EQUALS("\na = ( 1E-7 ) ;", expandMacros(filedata2, *this));
const char filedata3[] = "#define A (1e+7)\n"
"a=A;";
ASSERT_EQUALS("\na = ( 1e+7 ) ;", expandMacros(filedata3, *this));
const char filedata4[] = "#define A (1.e+7)\n"
"a=A;";
ASSERT_EQUALS("\na = ( 1.e+7 ) ;", expandMacros(filedata4, *this));
const char filedata5[] = "#define A (1.7f)\n"
"a=A;";
ASSERT_EQUALS("\na = ( 1.7f ) ;", expandMacros(filedata5, *this));
const char filedata6[] = "#define A (.1)\n"
"a=A;";
ASSERT_EQUALS("\na = ( .1 ) ;", expandMacros(filedata6, *this));
const char filedata7[] = "#define A (1.)\n"
"a=A;";
ASSERT_EQUALS("\na = ( 1. ) ;", expandMacros(filedata7, *this));
const char filedata8[] = "#define A (8.0E+007)\n"
"a=A;";
ASSERT_EQUALS("\na = ( 8.0E+007 ) ;", expandMacros(filedata8, *this));
}
void macroInMacro1() {
{
const char filedata[] = "#define A(m) long n = m; n++;\n"
"#define B(n) A(n)\n"
"B(0)\n";
ASSERT_EQUALS("\n\nlong n = 0 ; n ++ ;", expandMacros(filedata, *this));
}
{
const char filedata[] = "#define A B\n"
"#define B 3\n"
"A\n";
ASSERT_EQUALS("\n\n3", expandMacros(filedata, *this));
}
{
const char filedata[] = "#define BC(b, c...) 0##b * 0##c\n"
"#define ABC(a, b...) a + BC(b)\n"
"\n"
"ABC(1);\n" // <- too few parameters
"ABC(2,3);\n"
"ABC(4,5,6);\n";
ASSERT_EQUALS("\n\n\n1 + 0 * 0 ;\n2 + 03 * 0 ;\n4 + 05 * 06 ;", expandMacros(filedata, *this));
}
{
const char filedata[] = "#define A 4\n"
"#define B(a) a,A\n"
"B(2);\n";
ASSERT_EQUALS("\n\n2 , 4 ;", expandMacros(filedata, *this));
}
{
const char filedata[] = "#define A(x) (x)\n"
"#define B )A(\n"
"#define C )A(\n";
ASSERT_EQUALS("", expandMacros(filedata, *this));
}
{
const char filedata[] = "#define A(x) (x*2)\n"
"#define B A(\n"
"foo B(i));\n";
ASSERT_EQUALS("\n\nfoo ( ( i ) * 2 ) ;", expandMacros(filedata, *this));
}
{
const char filedata[] = "#define foo foo\n"
"foo\n";
ASSERT_EQUALS("\nfoo", expandMacros(filedata, *this));
}
{
const char filedata[] =
"#define B(A1, A2) } while (0)\n"
"#define A(name) void foo##name() { do { B(1, 2); }\n"
"A(0)\n"
"A(1)\n";
ASSERT_EQUALS("\n\nvoid foo0 ( ) { do { } while ( 0 ) ; }\nvoid foo1 ( ) { do { } while ( 0 ) ; }", expandMacros(filedata, *this));
}
{
const char filedata[] =
"#define B(x) (\n"
"#define A() B(xx)\n"
"B(1) A() ) )\n";
ASSERT_EQUALS("\n\n( ( ) )", expandMacros(filedata, *this));
}
{
const char filedata[] =
"#define PTR1 (\n"
"#define PTR2 PTR1 PTR1\n"
"int PTR2 PTR2 foo )))) = 0;\n";
ASSERT_EQUALS("\n\nint ( ( ( ( foo ) ) ) ) = 0 ;", expandMacros(filedata, *this));
}
{
const char filedata[] =
"#define PTR1 (\n"
"PTR1 PTR1\n";
ASSERT_EQUALS("\n( (", expandMacros(filedata, *this));
}
}
void macroInMacro2() {
const char filedata[] = "#define A(x) a##x\n"
"#define B 0\n"
"A(B)\n";
ASSERT_EQUALS("\n\naB", expandMacros(filedata, *this));
}
void macro_linenumbers() {
const char filedata[] = "#define AAA(a)\n"
"AAA(5\n"
"\n"
")\n"
"int a;\n";
ASSERT_EQUALS("\n"
"\n"
"\n"
"\n"
"int a ;",
expandMacros(filedata, *this));
}
void macro_nopar() {
const char filedata[] = "#define AAA( ) { NULL }\n"
"AAA()\n";
ASSERT_EQUALS("\n{ NULL }", expandMacros(filedata, *this));
}
void macro_incdec() {
const char filedata[] = "#define M1(X) 1+X\n"
"#define M2(X) 2-X\n"
"M1(+1) M2(-1)\n";
ASSERT_EQUALS("\n\n1 + + 1 2 - - 1", expandMacros(filedata, *this));
}
void macro_switchCase() {
{
// Make sure "case 2" doesn't become "case2"
const char filedata[] = "#define A( b ) "
"switch( a ){ "
"case 2: "
" break; "
"}\n"
"A( 5 );\n";
ASSERT_EQUALS("\nswitch ( a ) { case 2 : break ; } ;", expandMacros(filedata, *this));
}
{
// Make sure "2 BB" doesn't become "2BB"
const char filedata[] = "#define A() AA : 2 BB\n"
"A();\n";
ASSERT_EQUALS("\nAA : 2 BB ;", expandMacros(filedata, *this));
}
{
const char filedata[] = "#define A }\n"
"#define B() A\n"
"#define C( a ) B() break;\n"
"{C( 2 );\n";
ASSERT_EQUALS("\n\n\n{ } break ; ;", expandMacros(filedata, *this));
}
{
const char filedata[] = "#define A }\n"
"#define B() A\n"
"#define C( a ) B() _break;\n"
"{C( 2 );\n";
ASSERT_EQUALS("\n\n\n{ } _break ; ;", expandMacros(filedata, *this));
}
{
const char filedata[] = "#define A }\n"
"#define B() A\n"
"#define C( a ) B() 5;\n"
"{C( 2 );\n";
ASSERT_EQUALS("\n\n\n{ } 5 ; ;", expandMacros(filedata, *this));
}
}
void macro_NULL() {
// See ticket #4482 - UB when passing NULL to variadic function
ASSERT_EQUALS("\n0", expandMacros("#define null 0\nnull", *this));
TODO_ASSERT_EQUALS("\nNULL", "\n0", expandMacros("#define NULL 0\nNULL", *this)); // TODO: Let the tokenizer handle NULL?
}
void string1() {
const char filedata[] = "int main()"
"{"
" const char *a = \"#define A\";"
"}\n";
// Preprocess => actual result..
const std::map<std::string, std::string> actual = PreprocessorHelper::getcode(settings0, *this, filedata);
// Compare results..
ASSERT_EQUALS(1, actual.size());
ASSERT_EQUALS("int main ( ) { const char * a = \"#define A\" ; }", actual.at(""));
}
void string2() {
const char filedata[] = "#define AAA 123\n"
"str = \"AAA\"\n";
// Compare results..
ASSERT_EQUALS("\nstr = \"AAA\"", expandMacros(filedata, *this));
}
void string3() {
const char filedata[] = "str(\";\");\n";
// Compare results..
ASSERT_EQUALS("str ( \";\" ) ;", expandMacros(filedata, *this));
}
void preprocessor_undef() {
{
const char filedata[] = "#define AAA int a;\n"
"#undef AAA\n"
"#define AAA char b=0;\n"
"AAA\n";
// Compare results..
ASSERT_EQUALS("\n\n\nchar b = 0 ;", expandMacros(filedata, *this));
}
{
// ticket #403
const char filedata[] = "#define z p[2]\n"
"#undef z\n"
"int z;\n"
"z = 0;\n";
ASSERT_EQUALS("\n\nint z ;\nz = 0 ;", PreprocessorHelper::getcode(settings0, *this, filedata, "", ""));
}
}
void defdef() {
const char filedata[] = "#define AAA 123\n"
"#define AAA 456\n"
"#define AAA 789\n"
"AAA\n";
// Compare results..
ASSERT_EQUALS("\n\n\n789", expandMacros(filedata, *this));
}
void preprocessor_doublesharp() {
// simple testcase without ##
const char filedata1[] = "#define TEST(var,val) var = val\n"
"TEST(foo,20);\n";
ASSERT_EQUALS("\nfoo = 20 ;", expandMacros(filedata1, *this));
// simple testcase with ##
const char filedata2[] = "#define TEST(var,val) var##_##val = val\n"
"TEST(foo,20);\n";
ASSERT_EQUALS("\nfoo_20 = 20 ;", expandMacros(filedata2, *this));
// concat macroname
const char filedata3[] = "#define ABCD 123\n"
"#define A(B) A##B\n"
"A(BCD)\n";
ASSERT_EQUALS("\n\n123", expandMacros(filedata3, *this));
// Ticket #1802 - inner ## must be expanded before outer macro
const char filedata4[] = "#define A(B) A##B\n"
"#define a(B) A(B)\n"
"a(A(B))\n";
ASSERT_EQUALS("\n\nAAB", expandMacros(filedata4, *this));
// Ticket #1802 - inner ## must be expanded before outer macro
const char filedata5[] = "#define AB(A,B) A##B\n"
"#define ab(A,B) AB(A,B)\n"
"ab(a,AB(b,c))\n";
ASSERT_EQUALS("\n\nabc", expandMacros(filedata5, *this));
// Ticket #1802
const char filedata6[] = "#define AB_(A,B) A ## B\n"
"#define AB(A,B) AB_(A,B)\n"
"#define ab(suf) AB(X, AB_(_, suf))\n"
"#define X x\n"
"ab(y)\n";
ASSERT_EQUALS("\n\n\n\nx_y", expandMacros(filedata6, *this));
}
void preprocessor_include_in_str() {
const char filedata[] = "int main()\n"
"{\n"
"const char *a = \"#include <string>\";\n"
"return 0;\n"
"}\n";
// Preprocess => actual result..
const std::map<std::string, std::string> actual = PreprocessorHelper::getcode(settings0, *this, filedata);
// Compare results..
ASSERT_EQUALS(1, actual.size());
ASSERT_EQUALS("int main ( )\n{\nconst char * a = \"#include <string>\" ;\nreturn 0 ;\n}", actual.at(""));
}
void va_args_1() {
const char filedata[] = "#define DBG(fmt...) printf(fmt)\n"
"DBG(\"[0x%lx-0x%lx)\", pstart, pend);\n";
// Preprocess..
std::string actual = expandMacros(filedata, *this);
ASSERT_EQUALS("\nprintf ( \"[0x%lx-0x%lx)\" , pstart , pend ) ;", actual);
}
/*
void va_args_2() {
const char filedata[] = "#define DBG(fmt, args...) printf(fmt, ## args)\n"
"DBG(\"hello\");\n";
// Preprocess..
std::string actual = expandMacros(filedata, *this);
// invalid code ASSERT_EQUALS("\nprintf ( \"hello\" ) ;", actual);
}
*/
void va_args_3() {
const char filedata[] = "#define FRED(...) { fred(__VA_ARGS__); }\n"
"FRED(123)\n";
ASSERT_EQUALS("\n{ fred ( 123 ) ; }", expandMacros(filedata, *this));
}
void va_args_4() {
const char filedata[] = "#define FRED(name, ...) name (__VA_ARGS__)\n"
"FRED(abc, 123)\n";
ASSERT_EQUALS("\nabc ( 123 )", expandMacros(filedata, *this));
}
void va_args_5() {
const char filedata1[] = "#define A(...) #__VA_ARGS__\n"
"A(123)\n";
ASSERT_EQUALS("\n\"123\"", expandMacros(filedata1, *this));
const char filedata2[] = "#define A(X,...) X(#__VA_ARGS__)\n"
"A(f,123)\n";
ASSERT_EQUALS("\nf ( \"123\" )", expandMacros(filedata2, *this));
}
void multi_character_character() {
const char filedata[] = "#define FOO 'ABCD'\n"
"int main()\n"
"{\n"
"if( FOO == 0 );\n"
"return 0;\n"
"}\n";
// Preprocess => actual result..
const std::map<std::string, std::string> actual = PreprocessorHelper::getcode(settings0, *this, filedata);
// Compare results..
ASSERT_EQUALS(1, actual.size());
ASSERT_EQUALS("\nint main ( )\n{\nif ( $'ABCD' == 0 ) ;\nreturn 0 ;\n}", actual.at(""));
}
void stringify() {
const char filedata[] = "#define STRINGIFY(x) #x\n"
"STRINGIFY(abc)\n";
// expand macros..
std::string actual = expandMacros(filedata, *this);
ASSERT_EQUALS("\n\"abc\"", actual);
}
void stringify2() {
const char filedata[] = "#define A(x) g(#x)\n"
"A(abc);\n";
// expand macros..
std::string actual = expandMacros(filedata, *this);
ASSERT_EQUALS("\ng ( \"abc\" ) ;", actual);
}
void stringify3() {
const char filedata[] = "#define A(x) g(#x)\n"
"A( abc);\n";
// expand macros..
std::string actual = expandMacros(filedata, *this);
ASSERT_EQUALS("\ng ( \"abc\" ) ;", actual);
}
void stringify4() {
const char filedata[] = "#define A(x) #x\n"
"1 A(\n"
"abc\n"
") 2\n";
// expand macros..
std::string actual = expandMacros(filedata, *this);
ASSERT_EQUALS("\n1 \"abc\"\n\n2", actual);
}
void stringify5() {
const char filedata[] = "#define A(x) a(#x,x)\n"
"A(foo(\"\\\"\"))\n";
ASSERT_EQUALS("\na ( \"foo(\\\"\\\\\\\"\\\")\" , foo ( \"\\\"\" ) )", expandMacros(filedata, *this));
}
void pragma() {
const char filedata[] = "#pragma once\n"
"void f()\n"
"{\n"
"}\n";
// Preprocess => actual result..
const std::map<std::string, std::string> actual = PreprocessorHelper::getcode(settings0, *this, filedata);
// Compare results..
ASSERT_EQUALS(1, actual.size());
ASSERT_EQUALS("\nvoid f ( )\n{\n}", actual.at(""));
}
void pragma_asm_1() {
const char filedata[] = "#pragma asm\n"
" mov r1, 11\n"
"#pragma endasm\n"
"aaa\n"
"#pragma asm foo\n"
" mov r1, 11\n"
"#pragma endasm bar\n"
"bbb";
// Preprocess => actual result..
const std::map<std::string, std::string> actual = PreprocessorHelper::getcode(settings0, *this, filedata);
// Compare results..
ASSERT_EQUALS(1, actual.size());
ASSERT_EQUALS("asm ( )\n;\n\naaa\nasm ( ) ;\n\n\nbbb", actual.at(""));
}
void pragma_asm_2() {
const char filedata[] = "#pragma asm\n"
" mov @w1, 11\n"
"#pragma endasm ( temp=@w1 )\n"
"bbb";
// Preprocess => actual result..
const std::map<std::string, std::string> actual = PreprocessorHelper::getcode(settings0, *this, filedata);
// Compare results..
ASSERT_EQUALS(1, actual.size());
ASSERT_EQUALS("asm ( )\n;\n\nbbb", actual.at(""));
}
void endifsemicolon() {
const char filedata[] = "void f() {\n"
"#ifdef A\n"
"#endif;\n"
"}\n";
// Preprocess => actual result..
const std::map<std::string, std::string> actual = PreprocessorHelper::getcode(settings0, *this, filedata);
// Compare results..
ASSERT_EQUALS(2, actual.size());
const std::string expected("void f ( ) {\n\n\n}");
ASSERT_EQUALS(expected, actual.at(""));
ASSERT_EQUALS(expected, actual.at("A"));
}
void handle_error() {
{
const char filedata[] = "#define A \n"
"#define B don't want to \\\n"
"more text\n"
"void f()\n"
"{\n"
" char a = 'a'; // '\n"
"}\n";
// Preprocess => actual result..
const std::map<std::string, std::string> actual = PreprocessorHelper::getcode(settings0, *this, filedata);
ASSERT_EQUALS(0, actual.size());
ASSERT_EQUALS("[file.c:2]: (error) No pair for character ('). Can't process file. File is either invalid or unicode, which is currently not supported.\n", errout_str());
}
}
void missing_doublequote() {
{
const char filedata[] = "#define a\n"
"#ifdef 1\n"
"\"\n"
"#endif\n";
// expand macros..
const std::string actual(expandMacros(filedata, *this));
ASSERT_EQUALS("", actual);
ASSERT_EQUALS("[file.cpp:3]: (error) No pair for character (\"). Can't process file. File is either invalid or unicode, which is currently not supported.\n", errout_str());
}
{
const char filedata[] = "#file \"abc.h\"\n"
"#define a\n"
"\"\n"
"#endfile\n";
// expand macros..
const std::string actual(expandMacros(filedata, *this));
ASSERT_EQUALS("", actual);
ASSERT_EQUALS("[abc.h:2]: (error) No pair for character (\"). Can't process file. File is either invalid or unicode, which is currently not supported.\n", errout_str());
}
{
const char filedata[] = "#file \"abc.h\"\n"
"#define a\n"
"#endfile\n"
"\"\n";
// expand macros..
const std::string actual(expandMacros(filedata, *this));
ASSERT_EQUALS("", actual);
ASSERT_EQUALS("[file.cpp:2]: (error) No pair for character (\"). Can't process file. File is either invalid or unicode, which is currently not supported.\n", errout_str());
}
{
const char filedata[] = "#define A 1\n"
"#define B \"\n"
"int a = A;\n";
// expand macros..
const std::string actual(expandMacros(filedata, *this));
ASSERT_EQUALS("", actual);
ASSERT_EQUALS("[file.cpp:2]: (error) No pair for character (\"). Can't process file. File is either invalid or unicode, which is currently not supported.\n", errout_str());
}
{
const char filedata[] = "void foo()\n"
"{\n"
"\n"
"\n"
"\n"
"int a = 0;\n"
"printf(Text\");\n"
"}\n";
// expand macros..
(void)expandMacros(filedata, *this);
ASSERT_EQUALS("[file.cpp:7]: (error) No pair for character (\"). Can't process file. File is either invalid or unicode, which is currently not supported.\n", errout_str());
}
}
void define_part_of_func() {
const char filedata[] = "#define A g(\n"
"void f() {\n"
" A );\n"
" }\n";
// Preprocess => actual result..
const std::map<std::string, std::string> actual = PreprocessorHelper::getcode(settings0, *this, filedata);
// Compare results..
ASSERT_EQUALS(1, actual.size());
ASSERT_EQUALS("\nvoid f ( ) {\n$g $( ) ;\n}", actual.at(""));
ASSERT_EQUALS("", errout_str());
}
void conditionalDefine() {
const char filedata[] = "#ifdef A\n"
"#define N 10\n"
"#else\n"
"#define N 20\n"
"#endif\n"
"N";
// Preprocess => actual result..
const std::map<std::string, std::string> actual = PreprocessorHelper::getcode(settings0, *this, filedata);
// Compare results..
ASSERT_EQUALS(2, actual.size());
ASSERT_EQUALS("\n\n\n\n\n$20", actual.at(""));
ASSERT_EQUALS("\n\n\n\n\n$10", actual.at("A"));
ASSERT_EQUALS("", errout_str());
}
void macro_parameters() {
const char filedata[] = "#define BC(a, b, c, arg...) \\\n"
"AB(a, b, c, ## arg)\n"
"\n"
"void f()\n"
"{\n"
" BC(3);\n"
"}\n";
// Preprocess => actual result..
const std::map<std::string, std::string> actual = PreprocessorHelper::getcode(settings0, *this, filedata);
// Compare results..
ASSERT_EQUALS(1, actual.size());
ASSERT_EQUALS("", actual.at(""));
ASSERT_EQUALS("[file.c:6]: (error) failed to expand 'BC', Wrong number of parameters for macro 'BC'.\n", errout_str());
}
void newline_in_macro() {
const char filedata[] = "#define ABC(str) printf( str )\n"
"void f()\n"
"{\n"
" ABC(\"\\n\");\n"
"}\n";
// Preprocess => actual result..
const std::map<std::string, std::string> actual = PreprocessorHelper::getcode(settings0, *this, filedata);
// Compare results..
ASSERT_EQUALS(1, actual.size());
ASSERT_EQUALS("\nvoid f ( )\n{\n$printf $( \"\\n\" $) ;\n}", actual.at(""));
ASSERT_EQUALS("", errout_str());
}
void ifdef_ifdefined() {
const char filedata[] = "#ifdef ABC\n"
"A\n"
"#endif\t\n"
"#if defined ABC\n"
"A\n"
"#endif\n";
// Preprocess => actual result..
const std::map<std::string, std::string> actual = PreprocessorHelper::getcode(settings0, *this, filedata);
// Compare results..
ASSERT_EQUALS(2, actual.size());
ASSERT_EQUALS("", actual.at(""));
ASSERT_EQUALS("\nA\n\n\nA", actual.at("ABC"));
}
void define_if1() {
{
const char filedata[] = "#define A 0\n"
"#if A\n"
"FOO\n"
"#endif";
ASSERT_EQUALS("", PreprocessorHelper::getcode(settings0, *this, filedata,"",""));
}
{
const char filedata[] = "#define A 1\n"
"#if A==1\n"
"FOO\n"
"#endif";
ASSERT_EQUALS("\n\nFOO", PreprocessorHelper::getcode(settings0, *this, filedata,"",""));
}
}
void define_if2() {
const char filedata[] = "#define A 22\n"
"#define B A\n"
"#if (B==A) || (B==C)\n"
"FOO\n"
"#endif";
ASSERT_EQUALS("\n\n\nFOO", PreprocessorHelper::getcode(settings0, *this, filedata,"",""));
}
void define_if3() {
const char filedata[] = "#define A 0\n"
"#if (A==0)\n"
"FOO\n"
"#endif";
ASSERT_EQUALS("\n\nFOO", PreprocessorHelper::getcode(settings0, *this, filedata,"",""));
}
void define_if4() {
const char filedata[] = "#define X +123\n"
"#if X==123\n"
"FOO\n"
"#endif";
ASSERT_EQUALS("\n\nFOO", PreprocessorHelper::getcode(settings0, *this, filedata,"",""));
}
void define_if5() { // #4516 - #define B (A & 0x00f0)
{
const char filedata[] = "#define A 0x0010\n"
"#define B (A & 0x00f0)\n"
"#if B==0x0010\n"
"FOO\n"
"#endif";
ASSERT_EQUALS("\n\n\nFOO", PreprocessorHelper::getcode(settings0, *this, filedata,"",""));
}
{
const char filedata[] = "#define A 0x00f0\n"
"#define B (16)\n"
"#define C (B & A)\n"
"#if C==0x0010\n"
"FOO\n"
"#endif";
ASSERT_EQUALS("\n\n\n\nFOO", PreprocessorHelper::getcode(settings0, *this, filedata,"",""));
}
{
const char filedata[] = "#define A (1+A)\n" // don't hang for recursive macros
"#if A==1\n"
"FOO\n"
"#endif";
ASSERT_EQUALS("\n\nFOO", PreprocessorHelper::getcode(settings0, *this, filedata,"",""));
}
}
void define_if6() { // #4516 - #define B (A?1:-1)
const char filedata[] = "#ifdef A\n"
"#define B (A?1:-1)\n"
"#endif\n"
"\n"
"#if B < 0\n"
"123\n"
"#endif\n"
"\n"
"#if B >= 0\n"
"456\n"
"#endif\n";
const std::string actualA0 = PreprocessorHelper::getcode(settings0, *this, filedata, "A=0", "test.c");
ASSERT_EQUALS(true, actualA0.find("123") != std::string::npos);
ASSERT_EQUALS(false, actualA0.find("456") != std::string::npos);
const std::string actualA1 = PreprocessorHelper::getcode(settings0, *this, filedata, "A=1", "test.c");
ASSERT_EQUALS(false, actualA1.find("123") != std::string::npos);
ASSERT_EQUALS(true, actualA1.find("456") != std::string::npos);
}
void define_ifdef() {
{
const char filedata[] = "#define ABC\n"
"#ifndef ABC\n"
"A\n"
"#else\n"
"B\n"
"#endif\n";
// Preprocess => actual result..
const std::map<std::string, std::string> actual = PreprocessorHelper::getcode(settings0, *this, filedata);
// Compare results..
ASSERT_EQUALS(1, (int)actual.size());
ASSERT_EQUALS("\n\n\n\nB", actual.at(""));
}
{
const char filedata[] = "#define A 1\n"
"#ifdef A\n"
"A\n"
"#endif\n";
// Preprocess => actual result..
const std::map<std::string, std::string> actual = PreprocessorHelper::getcode(settings0, *this, filedata);
// Compare results..
ASSERT_EQUALS(1, (int)actual.size());
ASSERT_EQUALS("\n\n$1", actual.at(""));
}
{
const char filedata[] = "#define A 1\n"
"#if A==1\n"
"A\n"
"#endif\n";
// Preprocess => actual result..
const std::map<std::string, std::string> actual = PreprocessorHelper::getcode(settings0, *this, filedata);
// Compare results..
ASSERT_EQUALS(1, (int)actual.size());
ASSERT_EQUALS("\n\n$1", actual.at(""));
}
{
const char filedata[] = "#define A 1\n"
"#if A>0\n"
"A\n"
"#endif\n";
// Preprocess => actual result..
const std::map<std::string, std::string> actual = PreprocessorHelper::getcode(settings0, *this, filedata);
// Compare results..
ASSERT_EQUALS(1, (int)actual.size());
ASSERT_EQUALS("\n\n$1", actual.at(""));
}
{
const char filedata[] = "#define A 1\n"
"#if 0\n"
"#undef A\n"
"#endif\n"
"A\n";
// Preprocess => actual result..
const std::map<std::string, std::string> actual = PreprocessorHelper::getcode(settings0, *this, filedata);
// Compare results..
ASSERT_EQUALS(1, (int)actual.size());
ASSERT_EQUALS("\n\n\n\n$1", actual.at(""));
}
}
void define_ifndef1() {
const char filedata[] = "#define A(x) (x)\n"
"#ifndef A\n"
";\n"
"#endif\n";
// Preprocess => actual result..
const std::map<std::string, std::string> actual = PreprocessorHelper::getcode(settings0, *this, filedata);
// Compare results..
ASSERT_EQUALS(1U, actual.size());
ASSERT_EQUALS("", actual.at(""));
}
void define_ifndef2() {
const char filedata[] = "#ifdef A\n"
"#define B char\n"
"#endif\n"
"#ifndef B\n"
"#define B int\n"
"#endif\n"
"B me;\n";
// Preprocess => actual result..
ASSERT_EQUALS("\n\n\n\n\n\n$int me ;", PreprocessorHelper::getcode(settings0, *this, filedata, "", "a.cpp"));
ASSERT_EQUALS("\n\n\n\n\n\n$char me ;", PreprocessorHelper::getcode(settings0, *this, filedata, "A", "a.cpp"));
}
void ifndef_define() {
const char filedata[] = "#ifndef A\n"
"#define A(x) x\n"
"#endif\n"
"A(123);";
// Preprocess => actual result..
const std::map<std::string, std::string> actual = PreprocessorHelper::getcode(settings0, *this, filedata);
ASSERT_EQUALS(1U, actual.size());
ASSERT_EQUALS("\n\n\n123 ;", actual.at(""));
}
void undef_ifdef() {
const char filedata[] = "#undef A\n"
"#ifdef A\n"
"123\n"
"#endif\n";
// Preprocess => actual result..
ASSERT_EQUALS("", PreprocessorHelper::getcode(settings0, *this, filedata, "", "a.cpp"));
ASSERT_EQUALS("", PreprocessorHelper::getcode(settings0, *this, filedata, "A", "a.cpp"));
}
void redundant_config() {
const char filedata[] = "int main() {\n"
"#ifdef FOO\n"
"#ifdef BAR\n"
" std::cout << 1;\n"
"#endif\n"
"#endif\n"
"\n"
"#ifdef BAR\n"
"#ifdef FOO\n"
" std::cout << 2;\n"
"#endif\n"
"#endif\n"
"}\n";
// Preprocess => actual result..
const std::map<std::string, std::string> actual = PreprocessorHelper::getcode(settings0, *this, filedata);
// Compare results..
ASSERT_EQUALS(4, (int)actual.size());
ASSERT(actual.find("") != actual.end());
ASSERT(actual.find("BAR") != actual.end());
ASSERT(actual.find("FOO") != actual.end());
ASSERT(actual.find("BAR;FOO") != actual.end());
}
void endfile() {
const char filedata[] = "char a[] = \"#endfile\";\n"
"char b[] = \"#endfile\";\n"
"#include \"notfound.h\"\n";
// Preprocess => actual result..
const std::map<std::string, std::string> actual = PreprocessorHelper::getcode(settings0, *this, filedata);
// Compare results..
ASSERT_EQUALS(1, (int)actual.size());
ASSERT_EQUALS("char a [ ] = \"#endfile\" ;\nchar b [ ] = \"#endfile\" ;", actual.at(""));
}
void dup_defines() {
const char filedata[] = "#ifdef A\n"
"#define B\n"
"#if defined(B) && defined(A)\n"
"a\n"
"#else\n"
"b\n"
"#endif\n"
"#endif\n";
// Preprocess => actual result..
const std::map<std::string, std::string> actual = PreprocessorHelper::getcode(settings0, *this, filedata);
// B will always be defined if A is defined; the following test
// cases should be fixed whenever this other bug is fixed
ASSERT_EQUALS(2U, actual.size());
ASSERT_EQUALS_MSG(true, (actual.find("A") != actual.end()), "A is expected to be checked but it was not checked");
ASSERT_EQUALS_MSG(true, (actual.find("A;A;B") == actual.end()), "A;A;B is expected to NOT be checked but it was checked");
}
void invalid_define_1() {
(void)PreprocessorHelper::getcode(settings0, *this, "#define =\n");
ASSERT_EQUALS("[file.c:1]: (error) Failed to parse #define\n", errout_str());
}
void invalid_define_2() { // #4036
(void)PreprocessorHelper::getcode(settings0, *this, "#define () {(int f(x) }\n");
ASSERT_EQUALS("[file.c:1]: (error) Failed to parse #define\n", errout_str());
}
void inline_suppressions() {
/*const*/ Settings settings;
settings.inlineSuppressions = true;
settings.checks.enable(Checks::missingInclude);
const std::string code("// cppcheck-suppress missingInclude\n"
"#include \"missing.h\"\n"
"// cppcheck-suppress missingIncludeSystem\n"
"#include <missing2.h>\n");
SuppressionList inlineSuppr;
(void)PreprocessorHelper::getcode(settings, *this, code, "", "test.c", &inlineSuppr);
auto suppressions = inlineSuppr.getSuppressions();
ASSERT_EQUALS(2, suppressions.size());
auto suppr = suppressions.front();
suppressions.pop_front();
ASSERT_EQUALS("missingInclude", suppr.errorId);
ASSERT_EQUALS("test.c", suppr.fileName);
ASSERT_EQUALS(2, suppr.lineNumber);
ASSERT_EQUALS(false, suppr.checked);
ASSERT_EQUALS(false, suppr.matched);
suppr = suppressions.front();
suppressions.pop_front();
ASSERT_EQUALS("missingIncludeSystem", suppr.errorId);
ASSERT_EQUALS("test.c", suppr.fileName);
ASSERT_EQUALS(4, suppr.lineNumber);
ASSERT_EQUALS(false, suppr.checked);
ASSERT_EQUALS(false, suppr.matched);
ignore_errout(); // we are not interested in the output
}
void remarkComment1() {
const char code[] = "// REMARK: assignment with 1\n"
"x=1;\n";
const auto remarkComments = PreprocessorHelper::getRemarkComments(code, *this);
ASSERT_EQUALS(1, remarkComments.size());
ASSERT_EQUALS(2, remarkComments[0].lineNumber);
ASSERT_EQUALS("assignment with 1", remarkComments[0].str);
}
void remarkComment2() {
const char code[] = "x=1; ///REMARK assignment with 1\n";
const auto remarkComments = PreprocessorHelper::getRemarkComments(code, *this);
ASSERT_EQUALS(1, remarkComments.size());
ASSERT_EQUALS(1, remarkComments[0].lineNumber);
ASSERT_EQUALS("assignment with 1", remarkComments[0].str);
}
void remarkComment3() {
const char code[] = "/** REMARK: assignment with 1 */\n"
"x=1;\n";
const auto remarkComments = PreprocessorHelper::getRemarkComments(code, *this);
ASSERT_EQUALS(1, remarkComments.size());
ASSERT_EQUALS(2, remarkComments[0].lineNumber);
ASSERT_EQUALS("assignment with 1 ", remarkComments[0].str);
}
void predefine1() {
const std::string src("#if defined X || Y\n"
"Fred & Wilma\n"
"#endif\n");
std::string actual = PreprocessorHelper::getcode(settings0, *this, src, "X=1", "test.c");
ASSERT_EQUALS("\nFred & Wilma", actual);
}
void predefine2() {
const std::string src("#if defined(X) && Y\n"
"Fred & Wilma\n"
"#endif\n");
{
std::string actual = PreprocessorHelper::getcode(settings0, *this, src, "X=1", "test.c");
ASSERT_EQUALS("", actual);
}
{
std::string actual = PreprocessorHelper::getcode(settings0, *this, src, "X=1;Y=2", "test.c");
ASSERT_EQUALS("\nFred & Wilma", actual);
}
}
void predefine3() {
// #2871 - define in source is not used if -D is used
const char code[] = "#define X 1\n"
"#define Y X\n"
"#if (X == Y)\n"
"Fred & Wilma\n"
"#endif\n";
const std::string actual = PreprocessorHelper::getcode(settings0, *this, code, "TEST", "test.c");
ASSERT_EQUALS("\n\n\nFred & Wilma", actual);
}
void predefine4() {
// #3577
const char code[] = "char buf[X];\n";
const std::string actual = PreprocessorHelper::getcode(settings0, *this, code, "X=123", "test.c");
ASSERT_EQUALS("char buf [ $123 ] ;", actual);
}
void predefine5() { // #3737, #5119 - automatically define __cplusplus
// #3737...
const char code[] = "#ifdef __cplusplus\n123\n#endif";
ASSERT_EQUALS("", PreprocessorHelper::getcode(settings0, *this, code, "", "test.c"));
ASSERT_EQUALS("\n123", PreprocessorHelper::getcode(settings0, *this, code, "", "test.cpp"));
}
void predefine6() { // automatically define __STDC_VERSION__
const char code[] = "#ifdef __STDC_VERSION__\n123\n#endif";
ASSERT_EQUALS("\n123", PreprocessorHelper::getcode(settings0, *this, code, "", "test.c"));
ASSERT_EQUALS("", PreprocessorHelper::getcode(settings0, *this, code, "", "test.cpp"));
}
void invalidElIf() {
// #2942 - segfault
const char code[] = "#elif (){\n";
const std::string actual = PreprocessorHelper::getcode(settings0, *this, code, "TEST", "test.c");
ASSERT_EQUALS("", actual);
ASSERT_EQUALS("[test.c:1]: (error) #elif without #if\n", errout_str());
}
void getConfigs1() {
const char filedata[] = "#ifdef WIN32 \n"
" abcdef\n"
"#else \n"
" qwerty\n"
"#endif \n";
ASSERT_EQUALS("\nWIN32\n", getConfigsStr(filedata));
}
void getConfigs2() {
const char filedata[] = "# ifndef WIN32\n"
" \" # ifdef WIN32\" // a comment\n"
" # else \n"
" qwerty\n"
" # endif \n";
ASSERT_EQUALS("\nWIN32\n", getConfigsStr(filedata));
}
void getConfigs3() {
const char filedata[] = "#ifdef ABC\n"
"a\n"
"#ifdef DEF\n"
"b\n"
"#endif\n"
"c\n"
"#endif\n";
ASSERT_EQUALS("\nABC\nABC;DEF\n", getConfigsStr(filedata));
}
void getConfigs4() {
const char filedata[] = "#ifdef ABC\n"
"A\n"
"#endif\t\n"
"#ifdef ABC\n"
"A\n"
"#endif\n";
ASSERT_EQUALS("\nABC\n", getConfigsStr(filedata));
}
void getConfigs5() {
const char filedata[] = "#ifdef ABC\n"
"A\n"
"#else\n"
"B\n"
"#ifdef DEF\n"
"C\n"
"#endif\n"
"#endif\n";
ASSERT_EQUALS("\nABC\nDEF\n", getConfigsStr(filedata));
}
void getConfigs7() {
const char filedata[] = "#ifdef ABC\n"
"A\n"
"#ifdef ABC\n"
"B\n"
"#endif\n"
"#endif\n";
ASSERT_EQUALS("\nABC\n", getConfigsStr(filedata));
}
void getConfigs7a() {
const char filedata[] = "#ifndef ABC\n"
"A\n"
"#ifndef ABC\n"
"B\n"
"#endif\n"
"#endif\n";
ASSERT_EQUALS("\n", getConfigsStr(filedata));
}
void getConfigs7b() {
const char filedata[] = "#ifndef ABC\n"
"A\n"
"#ifdef ABC\n"
"B\n"
"#endif\n"
"#endif\n";
ASSERT_EQUALS("\nABC\n", getConfigsStr(filedata));
}
void getConfigs7c() {
const char filedata[] = "#ifdef ABC\n"
"A\n"
"#ifndef ABC\n"
"B\n"
"#endif\n"
"#endif\n";
ASSERT_EQUALS("\nABC\n", getConfigsStr(filedata));
}
void getConfigs7d() {
const char filedata[] = "#if defined(ABC)\n"
"A\n"
"#if defined(ABC)\n"
"B\n"
"#endif\n"
"#endif\n";
ASSERT_EQUALS("\nABC\n", getConfigsStr(filedata));
}
void getConfigs7e() {
const char filedata[] = "#ifdef ABC\n"
"#file \"test.h\"\n"
"#ifndef test_h\n"
"#define test_h\n"
"#ifdef ABC\n"
"#endif\n"
"#endif\n"
"#endfile\n"
"#endif\n";
ASSERT_EQUALS("\nABC\n", getConfigsStr(filedata));
}
void getConfigs8() {
const char filedata[] = "#if A == 1\n"
"1\n"
"#endif\n";
ASSERT_EQUALS("\nA=1\n", getConfigsStr(filedata));
}
void getConfigs10() { // Ticket #5139
const char filedata[] = "#define foo a.foo\n"
"#define bar foo\n"
"#define baz bar+0\n"
"#if 0\n"
"#endif";
ASSERT_EQUALS("\n", getConfigsStr(filedata));
}
void getConfigs11() { // #9832 - include guards
const char filedata[] = "#file \"test.h\"\n"
"#if !defined(test_h)\n"
"#define test_h\n"
"123\n"
"#endif\n"
"#endfile\n";
ASSERT_EQUALS("\n", getConfigsStr(filedata));
}
void getConfigsError() {
const char filedata1[] = "#ifndef X\n"
"#error \"!X\"\n"
"#endif\n";
ASSERT_EQUALS("X\n", getConfigsStr(filedata1));
const char filedata2[] = "#ifdef X\n"
"#ifndef Y\n"
"#error \"!Y\"\n"
"#endif\n"
"#endif\n";
ASSERT_EQUALS("\nX;Y\nY\n", getConfigsStr(filedata2));
}
void getConfigsD1() {
const char filedata[] = "#ifdef X\n"
"#else\n"
"#ifdef Y\n"
"#endif\n"
"#endif\n";
ASSERT_EQUALS("\n", getConfigsStr(filedata, "-DX"));
ASSERT_EQUALS("\nX\nY\n", getConfigsStr(filedata));
}
void getConfigsU1() {
const char filedata[] = "#ifdef X\n"
"#endif\n";
ASSERT_EQUALS("\n", getConfigsStr(filedata, "-UX"));
ASSERT_EQUALS("\nX\n", getConfigsStr(filedata));
}
void getConfigsU2() {
const char filedata[] = "#ifndef X\n"
"#endif\n";
ASSERT_EQUALS("\n", getConfigsStr(filedata, "-UX"));
ASSERT_EQUALS("\n", getConfigsStr(filedata)); // no #else
}
void getConfigsU3() {
const char filedata[] = "#ifndef X\n"
"Fred & Wilma\n"
"#else\n"
"Barney & Betty\n"
"#endif\n";
ASSERT_EQUALS("\n", getConfigsStr(filedata, "-UX"));
ASSERT_EQUALS("\nX\n", getConfigsStr(filedata));
}
void getConfigsU4() {
const char filedata[] = "#if defined(X) || defined(Y) || defined(Z)\n"
"#else\n"
"#endif\n";
ASSERT_EQUALS("\nY;Z\n", getConfigsStr(filedata, "-UX"));
ASSERT_EQUALS("\nX;Y;Z\n", getConfigsStr(filedata));
}
void getConfigsU5() {
const char filedata[] = "#if X==1\n"
"#endif\n";
ASSERT_EQUALS("\n", getConfigsStr(filedata, "-UX"));
ASSERT_EQUALS("\nX=1\n", getConfigsStr(filedata));
}
void getConfigsU6() {
const char filedata[] = "#if X==0\n"
"#endif\n";
ASSERT_EQUALS("\nX=0\n", getConfigsStr(filedata, "-UX"));
ASSERT_EQUALS("\nX=0\n", getConfigsStr(filedata));
}
void getConfigsU7() {
const char code[] = "#ifndef Y\n"
"#else\n"
"#endif\n";
ASSERT_EQUALS("\nY\n", getConfigsStr(code, "-DX"));
}
void if_sizeof() { // #4071
static const char* code = "#if sizeof(unsigned short) == 2\n"
"Fred & Wilma\n"
"#elif sizeof(unsigned short) == 4\n"
"Fred & Wilma\n"
"#else\n"
"#endif";
const std::map<std::string, std::string> actual = PreprocessorHelper::getcode(settings0, *this, code);
ASSERT_EQUALS("\nFred & Wilma", actual.at(""));
}
void invalid_ifs() {
const char filedata[] = "#ifdef\n"
"#endif\n"
"#ifdef !\n"
"#endif\n"
"#if defined\n"
"#endif\n"
"#define f(x) x\n"
"#if f(2\n"
"#endif\n"
"int x;\n";
// Preprocess => don't crash..
(void)PreprocessorHelper::getcode(settings0, *this, filedata);
ASSERT_EQUALS(
"[file.c:1]: (error) Syntax error in #ifdef\n"
"[file.c:1]: (error) Syntax error in #ifdef\n", errout_str());
}
void garbage() {
const char filedata[] = "V\n"
"#define X b #endif #line 0 \"x\" ;\n"
"#if ! defined ( Y ) #endif";
// Preprocess => don't crash..
(void)PreprocessorHelper::getcode(settings0, *this, filedata);
}
void wrongPathOnErrorDirective() {
const auto settings = dinit(Settings, $.userDefines = "foo");
const std::string code("#error hello world!\n");
(void)PreprocessorHelper::getcode(settings, *this, code, "X", "./././test.c");
ASSERT_EQUALS("[test.c:1]: (error) #error hello world!\n", errout_str());
}
// test for existing local include
void testMissingInclude() {
/*const*/ Settings settings;
settings.clearIncludeCache = true;
settings.checks.enable(Checks::missingInclude);
settings.templateFormat = "simple"; // has no effect
setTemplateFormat("simple");
ScopedFile header("header.h", "");
std::string code("#include \"header.h\"");
(void)PreprocessorHelper::getcode(settings, *this, code, "", "test.c");
ASSERT_EQUALS("", errout_str());
}
// test for missing local include
void testMissingInclude2() {
/*const*/ Settings settings;
settings.clearIncludeCache = true;
settings.checks.enable(Checks::missingInclude);
settings.templateFormat = "simple"; // has no effect
setTemplateFormat("simple");
std::string code("#include \"header.h\"");
(void)PreprocessorHelper::getcode(settings, *this, code, "", "test.c");
ASSERT_EQUALS("test.c:1:0: information: Include file: \"header.h\" not found. [missingInclude]\n", errout_str());
}
// test for missing local include - no include path given
void testMissingInclude3() {
/*const*/ Settings settings;
settings.clearIncludeCache = true;
settings.checks.enable(Checks::missingInclude);
settings.templateFormat = "simple"; // has no effect
setTemplateFormat("simple");
ScopedFile header("header.h", "", "inc");
std::string code("#include \"header.h\"");
(void)PreprocessorHelper::getcode(settings, *this, code, "", "test.c");
ASSERT_EQUALS("test.c:1:0: information: Include file: \"header.h\" not found. [missingInclude]\n", errout_str());
}
// test for existing local include - include path provided
void testMissingInclude4() {
/*const*/ Settings settings;
settings.clearIncludeCache = true;
settings.checks.enable(Checks::missingInclude);
settings.includePaths.emplace_back("inc");
settings.templateFormat = "simple"; // has no effect
setTemplateFormat("simple");
ScopedFile header("header.h", "", "inc");
std::string code("#include \"inc/header.h\"");
(void)PreprocessorHelper::getcode(settings, *this, code, "", "test.c");
ASSERT_EQUALS("", errout_str());
}
// test for existing local include - absolute path
void testMissingInclude5() {
/*const*/ Settings settings;
settings.clearIncludeCache = true;
settings.checks.enable(Checks::missingInclude);
settings.includePaths.emplace_back("inc");
settings.templateFormat = "simple"; // has no effect
setTemplateFormat("simple");
ScopedFile header("header.h", "", Path::getCurrentPath());
std::string code("#include \"" + header.path() + "\"");
(void)PreprocessorHelper::getcode(settings, *this, code, "", "test.c");
ASSERT_EQUALS("", errout_str());
}
// test for missing local include - absolute path
void testMissingInclude6() {
/*const*/ Settings settings;
settings.clearIncludeCache = true;
settings.checks.enable(Checks::missingInclude);
settings.templateFormat = "simple"; // has no effect
setTemplateFormat("simple");
const std::string header = Path::join(Path::getCurrentPath(), "header.h");
std::string code("#include \"" + header + "\"");
(void)PreprocessorHelper::getcode(settings, *this, code, "", "test.c");
ASSERT_EQUALS("test.c:1:0: information: Include file: \"" + header + "\" not found. [missingInclude]\n", errout_str());
}
// test for missing system include - system includes are not searched for in relative path
void testMissingSystemInclude() {
/*const*/ Settings settings;
settings.clearIncludeCache = true;
settings.checks.enable(Checks::missingInclude);
settings.templateFormat = "simple"; // has no effect
setTemplateFormat("simple");
ScopedFile header("header.h", "");
std::string code("#include <header.h>");
(void)PreprocessorHelper::getcode(settings, *this, code, "", "test.c");
ASSERT_EQUALS("test.c:1:0: information: Include file: <header.h> not found. Please note: Cppcheck does not need standard library headers to get proper results. [missingIncludeSystem]\n", errout_str());
}
// test for missing system include
void testMissingSystemInclude2() {
/*const*/ Settings settings;
settings.clearIncludeCache = true;
settings.checks.enable(Checks::missingInclude);
settings.templateFormat = "simple"; // has no effect
setTemplateFormat("simple");
std::string code("#include <header.h>");
(void)PreprocessorHelper::getcode(settings, *this, code, "", "test.c");
ASSERT_EQUALS("test.c:1:0: information: Include file: <header.h> not found. Please note: Cppcheck does not need standard library headers to get proper results. [missingIncludeSystem]\n", errout_str());
}
// test for existing system include in system include path
void testMissingSystemInclude3() {
/*const*/ Settings settings;
settings.clearIncludeCache = true;
settings.checks.enable(Checks::missingInclude);
settings.templateFormat = "simple"; // has no effect
setTemplateFormat("simple");
settings.includePaths.emplace_back("system");
ScopedFile header("header.h", "", "system");
std::string code("#include <header.h>");
(void)PreprocessorHelper::getcode(settings0, *this, code, "", "test.c");
ASSERT_EQUALS("", errout_str());
}
// test for existing system include - absolute path
void testMissingSystemInclude4() {
/*const*/ Settings settings;
settings.clearIncludeCache = true;
settings.checks.enable(Checks::missingInclude);
settings.includePaths.emplace_back("inc");
settings.templateFormat = "simple"; // has no effect
setTemplateFormat("simple");
ScopedFile header("header.h", "", Path::getCurrentPath());
std::string code("#include <" + header.path() + ">");
(void)PreprocessorHelper::getcode(settings, *this, code, "", "test.c");
ASSERT_EQUALS("", errout_str());
}
// test for missing system include - absolute path
void testMissingSystemInclude5() {
/*const*/ Settings settings;
settings.clearIncludeCache = true;
settings.checks.enable(Checks::missingInclude);
settings.templateFormat = "simple"; // has no effect
setTemplateFormat("simple");
const std::string header = Path::join(Path::getCurrentPath(), "header.h");
std::string code("#include <" + header + ">");
(void)PreprocessorHelper::getcode(settings, *this, code, "", "test.c");
ASSERT_EQUALS("test.c:1:0: information: Include file: <" + header + "> not found. Please note: Cppcheck does not need standard library headers to get proper results. [missingIncludeSystem]\n", errout_str());
}
// test for missing local and system include
void testMissingIncludeMixed() {
/*const*/ Settings settings;
settings.clearIncludeCache = true;
settings.checks.enable(Checks::missingInclude);
settings.templateFormat = "simple"; // has no effect
setTemplateFormat("simple");
ScopedFile header("header.h", "");
ScopedFile header2("header2.h", "");
std::string code("#include \"missing.h\"\n"
"#include <header.h>\n"
"#include <missing2.h>\n"
"#include \"header2.h\"");
(void)PreprocessorHelper::getcode(settings, *this, code, "", "test.c");
ASSERT_EQUALS("test.c:1:0: information: Include file: \"missing.h\" not found. [missingInclude]\n"
"test.c:2:0: information: Include file: <header.h> not found. Please note: Cppcheck does not need standard library headers to get proper results. [missingIncludeSystem]\n"
"test.c:3:0: information: Include file: <missing2.h> not found. Please note: Cppcheck does not need standard library headers to get proper results. [missingIncludeSystem]\n", errout_str());
}
void testMissingIncludeCheckConfig() {
/*const*/ Settings settings;
settings.clearIncludeCache = true;
settings.checks.enable(Checks::missingInclude);
settings.includePaths.emplace_back("system");
settings.templateFormat = "simple"; // has no effect
setTemplateFormat("simple");
ScopedFile header("header.h", "");
ScopedFile header2("header2.h", "");
ScopedFile header3("header3.h", "", "system");
ScopedFile header4("header4.h", "", "inc");
ScopedFile header5("header5.h", "", Path::getCurrentPath());
ScopedFile header6("header6.h", "", Path::getCurrentPath());
const std::string missing3 = Path::join(Path::getCurrentPath(), "missing3.h");
const std::string missing4 = Path::join(Path::getCurrentPath(), "missing4.h");
std::string code("#include \"missing.h\"\n"
"#include <header.h>\n"
"#include <missing2.h>\n"
"#include \"header2.h\"\n"
"#include <header3.h>\n"
"#include \"header4.h\"\n"
"#include \"inc/header4.h\"\n"
"#include \"" + header5.path() + "\"\n"
"#include \"" + missing3 + "\"\n"
"#include <" + header6.path() + ">\n"
"#include <" + missing4 + ">\n");
(void)PreprocessorHelper::getcode(settings, *this, code, "", "test.c");
ASSERT_EQUALS("test.c:1:0: information: Include file: \"missing.h\" not found. [missingInclude]\n"
"test.c:2:0: information: Include file: <header.h> not found. Please note: Cppcheck does not need standard library headers to get proper results. [missingIncludeSystem]\n"
"test.c:3:0: information: Include file: <missing2.h> not found. Please note: Cppcheck does not need standard library headers to get proper results. [missingIncludeSystem]\n"
"test.c:6:0: information: Include file: \"header4.h\" not found. [missingInclude]\n"
"test.c:9:0: information: Include file: \"" + missing3 + "\" not found. [missingInclude]\n"
"test.c:11:0: information: Include file: <" + missing4 + "> not found. Please note: Cppcheck does not need standard library headers to get proper results. [missingIncludeSystem]\n", errout_str());
}
void limitsDefines() {
// #11928 / #10045
const char code[] = "void f(long l) {\n"
" if (l > INT_MAX) {}\n"
"}";
const std::string actual = PreprocessorHelper::getcode(settings0, *this, code, "", "test.c");
ASSERT_EQUALS("void f ( long l ) {\n"
"if ( l > $2147483647 ) { }\n"
"}", actual);
}
void hashCalculation() {
// #12383
const char code[] = "int a;";
const char code2[] = "int a;"; // extra space
const char code3[] = "\n\nint a;"; // extra new line
ASSERT_EQUALS(getHash(code), getHash(code));
ASSERT_EQUALS(getHash(code2), getHash(code2));
ASSERT_EQUALS(getHash(code3), getHash(code3));
ASSERT(getHash(code) != getHash(code2));
ASSERT(getHash(code) != getHash(code3));
ASSERT(getHash(code2) != getHash(code3));
}
void standard() {
std::vector<std::string> files = {"test.cpp"};
const char code[] = "int a;";
// TODO: this bypasses the standard determined from the settings - the parameter should not be exposed
simplecpp::DUI dui;
{
Tokenizer tokenizer(settingsDefault, *this);
dui.std = "c89";
PreprocessorHelper::preprocess(code, files, tokenizer, *this, dui);
ASSERT(tokenizer.list.front());
}
{
Tokenizer tokenizer(settingsDefault, *this);
dui.std = "gnu23";
PreprocessorHelper::preprocess(code, files, tokenizer, *this, dui);
ASSERT(tokenizer.list.front());
}
{
Tokenizer tokenizer(settingsDefault, *this);
dui.std = "c++98";
PreprocessorHelper::preprocess(code, files, tokenizer, *this, dui);
ASSERT(tokenizer.list.front());
}
{
Tokenizer tokenizer(settingsDefault, *this);
dui.std = "gnu++26";
PreprocessorHelper::preprocess(code, files, tokenizer, *this, dui);
ASSERT(tokenizer.list.front());
}
{
Tokenizer tokenizer(settingsDefault, *this);
dui.std = "gnu77";
PreprocessorHelper::preprocess(code, files, tokenizer, *this, dui);
ASSERT(!tokenizer.list.front()); // nothing is tokenized when an unknown standard is provided
}
}
};
REGISTER_TEST(TestPreprocessor)
| null |
973 | cpp | cppcheck | testboost.cpp | test/testboost.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "checkboost.h"
#include "errortypes.h"
#include "fixture.h"
#include "helpers.h"
#include "settings.h"
#include <cstddef>
class TestBoost : public TestFixture {
public:
TestBoost() : TestFixture("TestBoost") {}
private:
const Settings settings = settingsBuilder().severity(Severity::style).severity(Severity::performance).build();
void run() override {
TEST_CASE(BoostForeachContainerModification);
}
#define check(code) check_(code, __FILE__, __LINE__)
template<size_t size>
void check_(const char (&code)[size], const char* file, int line) {
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
// Check..
runChecks<CheckBoost>(tokenizer, this);
}
void BoostForeachContainerModification() {
check("void f() {\n"
" vector<int> data;\n"
" BOOST_FOREACH(int i, data) {\n"
" data.push_back(123);\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) BOOST_FOREACH caches the end() iterator. It's undefined behavior if you modify the container inside.\n", errout_str());
check("void f() {\n"
" set<int> data;\n"
" BOOST_FOREACH(int i, data) {\n"
" data.insert(123);\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) BOOST_FOREACH caches the end() iterator. It's undefined behavior if you modify the container inside.\n", errout_str());
check("void f() {\n"
" set<int> data;\n"
" BOOST_FOREACH(const int &i, data) {\n"
" data.erase(123);\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) BOOST_FOREACH caches the end() iterator. It's undefined behavior if you modify the container inside.\n", errout_str());
// Check single line usage
check("void f() {\n"
" set<int> data;\n"
" BOOST_FOREACH(const int &i, data)\n"
" data.clear();\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) BOOST_FOREACH caches the end() iterator. It's undefined behavior if you modify the container inside.\n", errout_str());
// Container returned as result of a function -> Be quiet
check("void f() {\n"
" BOOST_FOREACH(const int &i, get_data())\n"
" data.insert(i);\n"
"}");
ASSERT_EQUALS("", errout_str());
// Break after modification (#4788)
check("void f() {\n"
" vector<int> data;\n"
" BOOST_FOREACH(int i, data) {\n"
" data.push_back(123);\n"
" break;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
};
REGISTER_TEST(TestBoost)
| null |
974 | cpp | cppcheck | testpathmatch.cpp | test/testpathmatch.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "pathmatch.h"
#include "fixture.h"
#include <string>
#include <utility>
#include <vector>
class TestPathMatch : public TestFixture {
public:
TestPathMatch() : TestFixture("TestPathMatch") {}
private:
const PathMatch emptyMatcher{std::vector<std::string>()};
const PathMatch srcMatcher{std::vector<std::string>(1, "src/")};
const PathMatch fooCppMatcher{std::vector<std::string>(1, "foo.cpp")};
const PathMatch srcFooCppMatcher{std::vector<std::string>(1, "src/foo.cpp")};
void run() override {
TEST_CASE(emptymaskemptyfile);
TEST_CASE(emptymaskpath1);
TEST_CASE(emptymaskpath2);
TEST_CASE(emptymaskpath3);
TEST_CASE(onemaskemptypath);
TEST_CASE(onemasksamepath);
TEST_CASE(onemasksamepathdifferentslash);
TEST_CASE(onemasksamepathdifferentcase);
TEST_CASE(onemasksamepathwithfile);
TEST_CASE(onemaskshorterpath);
TEST_CASE(onemaskdifferentdir1);
TEST_CASE(onemaskdifferentdir2);
TEST_CASE(onemaskdifferentdir3);
TEST_CASE(onemaskdifferentdir4);
TEST_CASE(onemasklongerpath1);
TEST_CASE(onemasklongerpath2);
TEST_CASE(onemasklongerpath3);
TEST_CASE(twomasklongerpath1);
TEST_CASE(twomasklongerpath2);
TEST_CASE(twomasklongerpath3);
TEST_CASE(twomasklongerpath4);
TEST_CASE(filemask1);
TEST_CASE(filemaskdifferentcase);
TEST_CASE(filemask2);
TEST_CASE(filemask3);
TEST_CASE(filemaskpath1);
TEST_CASE(filemaskpath2);
TEST_CASE(filemaskpath3);
TEST_CASE(filemaskpath4);
}
// Test empty PathMatch
void emptymaskemptyfile() const {
ASSERT(!emptyMatcher.match(""));
}
void emptymaskpath1() const {
ASSERT(!emptyMatcher.match("src/"));
}
void emptymaskpath2() const {
ASSERT(!emptyMatcher.match("../src/"));
}
void emptymaskpath3() const {
ASSERT(!emptyMatcher.match("/home/user/code/src/"));
ASSERT(!emptyMatcher.match("d:/home/user/code/src/"));
}
// Test PathMatch containing "src/"
void onemaskemptypath() const {
ASSERT(!srcMatcher.match(""));
}
void onemasksamepath() const {
ASSERT(srcMatcher.match("src/"));
}
void onemasksamepathdifferentslash() const {
const PathMatch srcMatcher2{std::vector<std::string>(1, "src\\")};
ASSERT(srcMatcher2.match("src/"));
}
void onemasksamepathdifferentcase() const {
std::vector<std::string> masks(1, "sRc/");
PathMatch match(std::move(masks), false);
ASSERT(match.match("srC/"));
}
void onemasksamepathwithfile() const {
ASSERT(srcMatcher.match("src/file.txt"));
}
void onemaskshorterpath() const {
const std::string longerExclude("longersrc/");
const std::string shorterToMatch("src/");
ASSERT(shorterToMatch.length() < longerExclude.length());
PathMatch match(std::vector<std::string>(1, longerExclude));
ASSERT(match.match(longerExclude));
ASSERT(!match.match(shorterToMatch));
}
void onemaskdifferentdir1() const {
ASSERT(!srcMatcher.match("srcfiles/file.txt"));
}
void onemaskdifferentdir2() const {
ASSERT(!srcMatcher.match("proj/srcfiles/file.txt"));
}
void onemaskdifferentdir3() const {
ASSERT(!srcMatcher.match("proj/mysrc/file.txt"));
}
void onemaskdifferentdir4() const {
ASSERT(!srcMatcher.match("proj/mysrcfiles/file.txt"));
}
void onemasklongerpath1() const {
ASSERT(srcMatcher.match("/tmp/src/"));
ASSERT(srcMatcher.match("d:/tmp/src/"));
}
void onemasklongerpath2() const {
ASSERT(srcMatcher.match("src/module/"));
}
void onemasklongerpath3() const {
ASSERT(srcMatcher.match("project/src/module/"));
}
void twomasklongerpath1() const {
std::vector<std::string> masks = { "src/", "module/" };
PathMatch match(std::move(masks));
ASSERT(!match.match("project/"));
}
void twomasklongerpath2() const {
std::vector<std::string> masks = { "src/", "module/" };
PathMatch match(std::move(masks));
ASSERT(match.match("project/src/"));
}
void twomasklongerpath3() const {
std::vector<std::string> masks = { "src/", "module/" };
PathMatch match(std::move(masks));
ASSERT(match.match("project/module/"));
}
void twomasklongerpath4() const {
std::vector<std::string> masks = { "src/", "module/" };
PathMatch match(std::move(masks));
ASSERT(match.match("project/src/module/"));
}
// Test PathMatch containing "foo.cpp"
void filemask1() const {
ASSERT(fooCppMatcher.match("foo.cpp"));
}
void filemaskdifferentcase() const {
std::vector<std::string> masks(1, "foo.cPp");
PathMatch match(std::move(masks), false);
ASSERT(match.match("fOo.cpp"));
}
void filemask2() const {
ASSERT(fooCppMatcher.match("../foo.cpp"));
}
void filemask3() const {
ASSERT(fooCppMatcher.match("src/foo.cpp"));
}
// Test PathMatch containing "src/foo.cpp"
void filemaskpath1() const {
ASSERT(srcFooCppMatcher.match("src/foo.cpp"));
}
void filemaskpath2() const {
ASSERT(srcFooCppMatcher.match("proj/src/foo.cpp"));
}
void filemaskpath3() const {
ASSERT(!srcFooCppMatcher.match("foo.cpp"));
}
void filemaskpath4() const {
ASSERT(!srcFooCppMatcher.match("bar/foo.cpp"));
}
};
REGISTER_TEST(TestPathMatch)
| null |
975 | cpp | cppcheck | testfilesettings.cpp | test/testfilesettings.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "filesettings.h"
#include "fixture.h"
class TestFileSettings : public TestFixture {
public:
TestFileSettings() : TestFixture("TestFileSettings") {}
private:
void run() override {
TEST_CASE(test);
}
void test() const {
{
const FileWithDetails p{"file.cpp"};
ASSERT_EQUALS("file.cpp", p.path());
ASSERT_EQUALS("file.cpp", p.spath());
ASSERT_EQUALS(0, p.size());
}
{
const FileWithDetails p{"file.cpp", 123};
ASSERT_EQUALS("file.cpp", p.path());
ASSERT_EQUALS("file.cpp", p.spath());
ASSERT_EQUALS(123, p.size());
}
{
const FileWithDetails p{"in/file.cpp"};
ASSERT_EQUALS("in/file.cpp", p.path());
ASSERT_EQUALS("in/file.cpp", p.spath());
ASSERT_EQUALS(0, p.size());
}
{
const FileWithDetails p{"in\\file.cpp"};
ASSERT_EQUALS("in\\file.cpp", p.path());
ASSERT_EQUALS("in/file.cpp", p.spath());
ASSERT_EQUALS(0, p.size());
}
{
const FileWithDetails p{"in/../file.cpp"};
ASSERT_EQUALS("in/../file.cpp", p.path());
ASSERT_EQUALS("file.cpp", p.spath());
ASSERT_EQUALS(0, p.size());
}
{
const FileWithDetails p{"in\\..\\file.cpp"};
ASSERT_EQUALS("in\\..\\file.cpp", p.path());
ASSERT_EQUALS("file.cpp", p.spath());
ASSERT_EQUALS(0, p.size());
}
}
};
REGISTER_TEST(TestFileSettings)
| null |
976 | cpp | cppcheck | testsuppressions.cpp | test/testsuppressions.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "config.h"
#include "cppcheck.h"
#include "cppcheckexecutor.h"
#include "errortypes.h"
#include "filesettings.h"
#include "processexecutor.h"
#include "settings.h"
#include "suppressions.h"
#include "fixture.h"
#include "helpers.h"
#include "threadexecutor.h"
#include "singleexecutor.h"
#include <cstring>
#include <list>
#include <map>
#include <memory>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
class TestSuppressions : public TestFixture {
public:
TestSuppressions() : TestFixture("TestSuppressions") {}
private:
void run() override {
TEST_CASE(suppressionsBadId1);
TEST_CASE(suppressionsDosFormat); // Ticket #1836
TEST_CASE(suppressionsFileNameWithColon); // Ticket #1919 - filename includes colon
TEST_CASE(suppressionsGlob);
TEST_CASE(suppressionsGlobId);
TEST_CASE(suppressionsFileNameWithExtraPath);
TEST_CASE(suppressionsSettingsFiles);
TEST_CASE(suppressionsSettingsFS);
TEST_CASE(suppressionsSettingsThreadsFiles);
TEST_CASE(suppressionsSettingsThreadsFS);
#if !defined(WIN32) && !defined(__MINGW32__) && !defined(__CYGWIN__)
TEST_CASE(suppressionsSettingsProcessesFiles);
TEST_CASE(suppressionsSettingsProcessesFS);
#endif
TEST_CASE(suppressionsMultiFileFiles);
TEST_CASE(suppressionsMultiFileFS);
TEST_CASE(suppressionsPathSeparator);
TEST_CASE(suppressionsLine0);
TEST_CASE(suppressionsFileComment);
TEST_CASE(inlinesuppress);
TEST_CASE(inlinesuppress_symbolname_Files);
TEST_CASE(inlinesuppress_symbolname_FS);
TEST_CASE(inlinesuppress_comment);
TEST_CASE(multi_inlinesuppress);
TEST_CASE(multi_inlinesuppress_comment);
TEST_CASE(globalSuppressions); // Testing that global suppressions work (#8515)
TEST_CASE(inlinesuppress_unusedFunction); // #4210 - unusedFunction
TEST_CASE(globalsuppress_unusedFunction); // #4946
TEST_CASE(suppressionWithRelativePaths); // #4733
TEST_CASE(suppressingSyntaxErrorsFiles); // #7076
TEST_CASE(suppressingSyntaxErrorsFS); // #7076
TEST_CASE(suppressingSyntaxErrorsInlineFiles); // #5917
TEST_CASE(suppressingSyntaxErrorsInlineFS); // #5917
TEST_CASE(suppressingSyntaxErrorsWhileFileReadFiles); // PR #1333
TEST_CASE(suppressingSyntaxErrorsWhileFileReadFS); // PR #1333
TEST_CASE(symbol);
TEST_CASE(unusedFunctionFiles);
TEST_CASE(unusedFunctionFS);
TEST_CASE(suppressingSyntaxErrorAndExitCodeFiles);
TEST_CASE(suppressingSyntaxErrorAndExitCodeFS);
TEST_CASE(suppressingSyntaxErrorAndExitCodeMultiFileFiles);
TEST_CASE(suppressingSyntaxErrorAndExitCodeMultiFileFS);
TEST_CASE(suppressLocal);
TEST_CASE(suppressUnmatchedSuppressions);
TEST_CASE(suppressionsParseXmlFile);
}
void suppressionsBadId1() const {
SuppressionList suppressions;
std::istringstream s1("123");
ASSERT_EQUALS("Failed to add suppression. Invalid id \"123\"", suppressions.parseFile(s1));
std::istringstream s2("obsoleteFunctionsrand_r");
ASSERT_EQUALS("", suppressions.parseFile(s2));
}
static SuppressionList::ErrorMessage errorMessage(const std::string &errorId) {
SuppressionList::ErrorMessage ret;
ret.errorId = errorId;
ret.hash = 0;
ret.lineNumber = 0;
ret.certainty = Certainty::normal;
return ret;
}
static SuppressionList::ErrorMessage errorMessage(const std::string &errorId, const std::string &file, int line) {
SuppressionList::ErrorMessage ret;
ret.errorId = errorId;
ret.setFileName(file);
ret.lineNumber = line;
return ret;
}
void suppressionsDosFormat() const {
SuppressionList suppressions;
std::istringstream s("abc\r\n"
"def\r\n");
ASSERT_EQUALS("", suppressions.parseFile(s));
ASSERT_EQUALS(true, suppressions.isSuppressed(errorMessage("abc")));
ASSERT_EQUALS(true, suppressions.isSuppressed(errorMessage("def")));
}
void suppressionsFileNameWithColon() const {
SuppressionList suppressions;
std::istringstream s("errorid:c:\\foo.cpp\n"
"errorid:c:\\bar.cpp:12");
ASSERT_EQUALS("", suppressions.parseFile(s));
ASSERT_EQUALS(true, suppressions.isSuppressed(errorMessage("errorid", "c:/foo.cpp", 1111)));
ASSERT_EQUALS(false, suppressions.isSuppressed(errorMessage("errorid", "c:/bar.cpp", 10)));
ASSERT_EQUALS(true, suppressions.isSuppressed(errorMessage("errorid", "c:/bar.cpp", 12)));
}
void suppressionsGlob() const {
// Check for syntax errors in glob
{
SuppressionList suppressions;
std::istringstream s("errorid:**.cpp\n");
ASSERT_EQUALS("Failed to add suppression. Invalid glob pattern '**.cpp'.", suppressions.parseFile(s));
}
// Check that globbing works
{
SuppressionList suppressions;
std::istringstream s("errorid:x*.cpp\n"
"errorid:y?.cpp\n"
"errorid:test.c*");
ASSERT_EQUALS("", suppressions.parseFile(s));
ASSERT_EQUALS(true, suppressions.isSuppressed(errorMessage("errorid", "xyz.cpp", 1)));
ASSERT_EQUALS(true, suppressions.isSuppressed(errorMessage("errorid", "xyz.cpp.cpp", 1)));
ASSERT_EQUALS(false, suppressions.isSuppressed(errorMessage("errorid", "abc.cpp", 1)));
ASSERT_EQUALS(true, suppressions.isSuppressed(errorMessage("errorid", "ya.cpp", 1)));
ASSERT_EQUALS(false, suppressions.isSuppressed(errorMessage("errorid", "y.cpp", 1)));
ASSERT_EQUALS(true, suppressions.isSuppressed(errorMessage("errorid", "test.c", 1)));
ASSERT_EQUALS(true, suppressions.isSuppressed(errorMessage("errorid", "test.cpp", 1)));
}
// Check that both a filename match and a glob match apply
{
SuppressionList suppressions;
std::istringstream s("errorid:x*.cpp\n"
"errorid:xyz.cpp:1\n"
"errorid:a*.cpp:1\n"
"errorid:abc.cpp:2");
ASSERT_EQUALS("", suppressions.parseFile(s));
ASSERT_EQUALS(true, suppressions.isSuppressed(errorMessage("errorid", "xyz.cpp", 1)));
ASSERT_EQUALS(true, suppressions.isSuppressed(errorMessage("errorid", "xyz.cpp", 2)));
ASSERT_EQUALS(true, suppressions.isSuppressed(errorMessage("errorid", "abc.cpp", 1)));
ASSERT_EQUALS(true, suppressions.isSuppressed(errorMessage("errorid", "abc.cpp", 2)));
}
}
void suppressionsGlobId() const {
SuppressionList suppressions;
std::istringstream s("a*\n");
ASSERT_EQUALS("", suppressions.parseFile(s));
ASSERT_EQUALS(true, suppressions.isSuppressed(errorMessage("abc", "xyz.cpp", 1)));
ASSERT_EQUALS(false, suppressions.isSuppressed(errorMessage("def", "xyz.cpp", 1)));
}
void suppressionsFileNameWithExtraPath() const {
// Ticket #2797
SuppressionList suppressions;
ASSERT_EQUALS("", suppressions.addSuppressionLine("errorid:./a.c:123"));
ASSERT_EQUALS(true, suppressions.isSuppressed(errorMessage("errorid", "a.c", 123)));
ASSERT_EQUALS(true, suppressions.isSuppressed(errorMessage("errorid", "x/../a.c", 123)));
}
unsigned int checkSuppressionFiles(const char code[], const std::string &suppression = emptyString) {
return _checkSuppression(code, false, suppression);
}
unsigned int checkSuppressionFS(const char code[], const std::string &suppression = emptyString) {
return _checkSuppression(code, true, suppression);
}
// Check the suppression
unsigned int _checkSuppression(const char code[], bool useFS, const std::string &suppression = emptyString) {
std::map<std::string, std::string> files;
files["test.cpp"] = code;
return _checkSuppression(files, useFS, suppression);
}
unsigned int checkSuppressionFiles(std::map<std::string, std::string> &f, const std::string &suppression = emptyString) {
return _checkSuppression(f, false, suppression);
}
unsigned int checkSuppressionFS(std::map<std::string, std::string> &f, const std::string &suppression = emptyString) {
return _checkSuppression(f, true, suppression);
}
// Check the suppression for multiple files
unsigned int _checkSuppression(std::map<std::string, std::string> &f, bool useFS, const std::string &suppression = emptyString) {
std::list<FileSettings> fileSettings;
std::list<FileWithDetails> filelist;
for (std::map<std::string, std::string>::const_iterator i = f.cbegin(); i != f.cend(); ++i) {
filelist.emplace_back(i->first, i->second.size());
if (useFS) {
fileSettings.emplace_back(i->first, i->second.size());
}
}
CppCheck cppCheck(*this, true, nullptr);
Settings& settings = cppCheck.settings();
settings.jobs = 1;
settings.quiet = true;
settings.inlineSuppressions = true;
settings.severity.enable(Severity::information);
if (suppression == "unusedFunction")
settings.checks.setEnabled(Checks::unusedFunction, true);
if (!suppression.empty()) {
ASSERT_EQUALS("", settings.supprs.nomsg.addSuppressionLine(suppression));
}
std::vector<std::unique_ptr<ScopedFile>> scopedfiles;
scopedfiles.reserve(filelist.size());
for (std::map<std::string, std::string>::const_iterator i = f.cbegin(); i != f.cend(); ++i)
scopedfiles.emplace_back(new ScopedFile(i->first, i->second));
// clear files list so only fileSettings are used
if (useFS)
filelist.clear();
SingleExecutor executor(cppCheck, filelist, fileSettings, settings, settings.supprs.nomsg, *this);
const unsigned int exitCode = executor.check();
CppCheckExecutor::reportSuppressions(settings, settings.supprs.nomsg, false, filelist, fileSettings, *this); // TODO: check result
return exitCode;
}
unsigned int checkSuppressionThreadsFiles(const char code[], const std::string &suppression = emptyString) {
return _checkSuppressionThreads(code, false, suppression);
}
unsigned int checkSuppressionThreadsFS(const char code[], const std::string &suppression = emptyString) {
return _checkSuppressionThreads(code, true, suppression);
}
unsigned int _checkSuppressionThreads(const char code[], bool useFS, const std::string &suppression = emptyString) {
std::list<FileSettings> fileSettings;
std::list<FileWithDetails> filelist;
filelist.emplace_back("test.cpp", strlen(code));
if (useFS) {
fileSettings.emplace_back("test.cpp", strlen(code));
}
/*const*/ auto settings = dinit(Settings,
$.jobs = 2,
$.quiet = true,
$.inlineSuppressions = true);
settings.severity.enable(Severity::information);
if (!suppression.empty()) {
ASSERT_EQUALS("", settings.supprs.nomsg.addSuppressionLine(suppression));
}
std::vector<std::unique_ptr<ScopedFile>> scopedfiles;
scopedfiles.reserve(filelist.size());
for (std::list<FileWithDetails>::const_iterator i = filelist.cbegin(); i != filelist.cend(); ++i)
scopedfiles.emplace_back(new ScopedFile(i->path(), code));
// clear files list so only fileSettings are used
if (useFS)
filelist.clear();
ThreadExecutor executor(filelist, fileSettings, settings, settings.supprs.nomsg, *this, CppCheckExecutor::executeCommand);
const unsigned int exitCode = executor.check();
CppCheckExecutor::reportSuppressions(settings, settings.supprs.nomsg, false, filelist, fileSettings, *this); // TODO: check result
return exitCode;
}
#if !defined(WIN32) && !defined(__MINGW32__) && !defined(__CYGWIN__)
unsigned int checkSuppressionProcessesFiles(const char code[], const std::string &suppression = emptyString) {
return _checkSuppressionProcesses(code, false, suppression);
}
unsigned int checkSuppressionProcessesFS(const char code[], const std::string &suppression = emptyString) {
return _checkSuppressionProcesses(code, true, suppression);
}
unsigned int _checkSuppressionProcesses(const char code[], bool useFS, const std::string &suppression = emptyString) {
std::list<FileSettings> fileSettings;
std::list<FileWithDetails> filelist;
filelist.emplace_back("test.cpp", strlen(code));
if (useFS) {
fileSettings.emplace_back("test.cpp", strlen(code));
}
/*const*/ auto settings = dinit(Settings,
$.jobs = 2,
$.quiet = true,
$.inlineSuppressions = true);
settings.severity.enable(Severity::information);
if (!suppression.empty()) {
ASSERT_EQUALS("", settings.supprs.nomsg.addSuppressionLine(suppression));
}
std::vector<std::unique_ptr<ScopedFile>> scopedfiles;
scopedfiles.reserve(filelist.size());
for (std::list<FileWithDetails>::const_iterator i = filelist.cbegin(); i != filelist.cend(); ++i)
scopedfiles.emplace_back(new ScopedFile(i->path(), code));
// clear files list so only fileSettings are used
if (useFS)
filelist.clear();
ProcessExecutor executor(filelist, fileSettings, settings, settings.supprs.nomsg, *this, CppCheckExecutor::executeCommand);
const unsigned int exitCode = executor.check();
CppCheckExecutor::reportSuppressions(settings, settings.supprs.nomsg, false, filelist, fileSettings, *this); // TODO: check result
return exitCode;
}
#endif
void runChecks(unsigned int (TestSuppressions::*check)(const char[], const std::string &)) {
// check to make sure the appropriate errors are present
ASSERT_EQUALS(1, (this->*check)("void f() {\n"
" int a;\n"
" a++;\n"
"}\n",
""));
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: a\n", errout_str());
ASSERT_EQUALS(1, (this->*check)("void f() {\n"
" int a;\n"
" a++;\n"
" int b;\n"
" b++;\n"
"}\n",
""));
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: a\n"
"[test.cpp:5]: (error) Uninitialized variable: b\n", errout_str());
// suppress uninitvar globally
ASSERT_EQUALS(0, (this->*check)("void f() {\n"
" int a;\n"
" a++;\n"
"}\n",
"uninitvar"));
ASSERT_EQUALS("", errout_str());
(this->*check)("void f() {\n"
" // cppcheck-suppress-file uninitvar\n"
" int a;\n"
" a++;\n"
"}\n",
"");
ASSERT_EQUALS("[test.cpp:2]: (error) File suppression should be at the top of the file\n"
"[test.cpp:4]: (error) Uninitialized variable: a\n", errout_str());
(this->*check)("void f() {\n"
" int a;\n"
" a++;\n"
"}\n"
"// cppcheck-suppress-file uninitvar\n",
"");
ASSERT_EQUALS("[test.cpp:5]: (error) File suppression should be at the top of the file\n"
"[test.cpp:3]: (error) Uninitialized variable: a\n", errout_str());
ASSERT_EQUALS(0, (this->*check)("// cppcheck-suppress-file uninitvar\n"
"void f() {\n"
" int a;\n"
" a++;\n"
" int b;\n"
" b++;\n"
"}\n",
""));
ASSERT_EQUALS("", errout_str());
ASSERT_EQUALS(0, (this->*check)("/* Fake file description\n"
" * End\n"
" */\n"
"\n"
"// cppcheck-suppress-file uninitvar\n"
"\n"
"void f() {\n"
" int a;\n"
" a++;\n"
" int b;\n"
" b++;\n"
"}\n",
""));
ASSERT_EQUALS("", errout_str());
(this->*check)("// cppcheck-suppress-file uninitvar\n"
"void f() {\n"
" int a;\n"
" a++;\n"
" int b;\n"
" b++;\n"
"}\n",
"");
ASSERT_EQUALS("", errout_str());
// suppress uninitvar globally, without error present
ASSERT_EQUALS(0, (this->*check)("void f() {\n"
" int a;\n"
" b++;\n"
"}\n",
"uninitvar"));
ASSERT_EQUALS("(information) Unmatched suppression: uninitvar\n", errout_str());
(this->*check)("// cppcheck-suppress-file uninitvar\n"
"void f() {\n"
" int a;\n"
" b++;\n"
"}\n",
"");
ASSERT_EQUALS("[test.cpp:1]: (information) Unmatched suppression: uninitvar\n", errout_str());
// suppress uninitvar for this file only
ASSERT_EQUALS(0, (this->*check)("void f() {\n"
" int a;\n"
" a++;\n"
"}\n",
"uninitvar:test.cpp"));
ASSERT_EQUALS("", errout_str());
// suppress uninitvar for this file only, without error present
(this->*check)("void f() {\n"
" int a;\n"
" b++;\n"
"}\n",
"uninitvar:test.cpp");
ASSERT_EQUALS("[test.cpp]: (information) Unmatched suppression: uninitvar\n", errout_str());
// suppress all for this file only
ASSERT_EQUALS(0, (this->*check)("void f() {\n"
" int a;\n"
" a++;\n"
"}\n",
"*:test.cpp"));
ASSERT_EQUALS("", errout_str());
// suppress all for this file only, without error present
(this->*check)("void f() {\n"
" int a;\n"
" b++;\n"
"}\n",
"*:test.cpp");
ASSERT_EQUALS("[test.cpp]: (information) Unmatched suppression: *\n", errout_str());
// suppress uninitvar for this file and line
ASSERT_EQUALS(0, (this->*check)("void f() {\n"
" int a;\n"
" a++;\n"
"}\n",
"uninitvar:test.cpp:3"));
ASSERT_EQUALS("", errout_str());
// suppress uninitvar for this file and line, without error present
(this->*check)("void f() {\n"
" int a;\n"
" b++;\n"
"}\n",
"uninitvar:test.cpp:3");
ASSERT_EQUALS("[test.cpp:3]: (information) Unmatched suppression: uninitvar\n", errout_str());
// suppress uninitvar inline
ASSERT_EQUALS(0, (this->*check)("void f() {\n"
" int a;\n"
" // cppcheck-suppress uninitvar\n"
" a++;\n"
"}\n",
""));
ASSERT_EQUALS("", errout_str());
// suppress uninitvar inline
ASSERT_EQUALS(0, (this->*check)("void f() {\n"
" int a;\n"
" // cppcheck-suppress uninitvar\n"
"\n"
" a++;\n"
"}\n",
""));
ASSERT_EQUALS("", errout_str());
// suppress uninitvar inline
ASSERT_EQUALS(0, (this->*check)("void f() {\n"
" int a;\n"
" a++;// cppcheck-suppress uninitvar\n"
"}\n",
""));
ASSERT_EQUALS("", errout_str());
// suppress uninitvar inline
ASSERT_EQUALS(0, (this->*check)("void f() {\n"
" int a;\n"
" /* cppcheck-suppress uninitvar */\n"
" a++;\n"
"}\n",
""));
ASSERT_EQUALS("", errout_str());
// suppress uninitvar inline
ASSERT_EQUALS(0, (this->*check)("void f() {\n"
" int a;\n"
" /* cppcheck-suppress uninitvar */\n"
"\n"
" a++;\n"
"}\n",
""));
ASSERT_EQUALS("", errout_str());
// suppress uninitvar inline
ASSERT_EQUALS(0, (this->*check)("void f() {\n"
" int a;\n"
" a++;/* cppcheck-suppress uninitvar */\n"
"}\n",
""));
ASSERT_EQUALS("", errout_str());
// suppress uninitvar inline
ASSERT_EQUALS(0, (this->*check)("void f() {\n"
" int a;\n"
" // cppcheck-suppress[uninitvar]\n"
" a++;\n"
"}\n",
""));
ASSERT_EQUALS("", errout_str());
// suppress uninitvar inline
ASSERT_EQUALS(0, (this->*check)("void f() {\n"
" int a;\n"
" // cppcheck-suppress[uninitvar]\n"
" a++;\n"
"\n"
" a++;\n"
"}\n",
""));
ASSERT_EQUALS("", errout_str());
// suppress uninitvar inline
ASSERT_EQUALS(0, (this->*check)("void f() {\n"
" int a;\n"
" a++;// cppcheck-suppress[uninitvar]\n"
"}\n",
""));
ASSERT_EQUALS("", errout_str());
// suppress uninitvar inline
ASSERT_EQUALS(0, (this->*check)("void f() {\n"
" int a;\n"
" /* cppcheck-suppress[uninitvar]*/\n"
" a++;\n"
"}\n",
""));
ASSERT_EQUALS("", errout_str());
// suppress uninitvar inline
ASSERT_EQUALS(0, (this->*check)("void f() {\n"
" int a;\n"
" /* cppcheck-suppress[uninitvar]*/\n"
"\n"
" a++;\n"
"}\n",
""));
ASSERT_EQUALS("", errout_str());
// suppress uninitvar inline
ASSERT_EQUALS(0, (this->*check)("void f() {\n"
" int a;\n"
" a++;/* cppcheck-suppress[uninitvar]*/\n"
"}\n",
""));
ASSERT_EQUALS("", errout_str());
// suppress uninitvar inline, with asm before (#6813)
ASSERT_EQUALS(0, (this->*check)("void f() {\n"
" __asm {\n"
" foo\n"
" }"
" int a;\n"
" // cppcheck-suppress uninitvar\n"
" a++;\n"
"}",
""));
ASSERT_EQUALS("", errout_str());
// suppress uninitvar inline, without error present
(this->*check)("void f() {\n"
" int a;\n"
" // cppcheck-suppress uninitvar\n"
" b++;\n"
"}\n",
"");
ASSERT_EQUALS("[test.cpp:4]: (information) Unmatched suppression: uninitvar\n", errout_str());
// suppress block inline checks
ASSERT_EQUALS(0, (this->*check)("void f() {\n"
" // cppcheck-suppress-begin uninitvar\n"
" int a;\n"
" a++;\n"
" int b;\n"
" b++;\n"
" // cppcheck-suppress-end uninitvar\n"
"}\n",
""));
ASSERT_EQUALS("", errout_str());
ASSERT_EQUALS(1, (this->*check)("void f() {\n"
" // cppcheck-suppress-begin uninitvar\n"
" int a;\n"
" a++;\n"
" int b;\n"
" b++;\n"
"}\n",
""));
ASSERT_EQUALS("[test.cpp:2]: (error) Suppress Begin: No matching end\n"
"[test.cpp:4]: (error) Uninitialized variable: a\n"
"[test.cpp:6]: (error) Uninitialized variable: b\n", errout_str());
ASSERT_EQUALS(1, (this->*check)("void f() {\n"
" int a;\n"
" a++;\n"
" int b;\n"
" b++;\n"
" // cppcheck-suppress-end uninitvar\n"
"}\n",
""));
ASSERT_EQUALS("[test.cpp:6]: (error) Suppress End: No matching begin\n"
"[test.cpp:3]: (error) Uninitialized variable: a\n"
"[test.cpp:5]: (error) Uninitialized variable: b\n", errout_str());
ASSERT_EQUALS(1, (this->*check)("void f() {\n"
" int a;\n"
" // cppcheck-suppress-begin uninitvar\n"
" a++;\n"
" // cppcheck-suppress-end uninitvar\n"
" int b;\n"
" b++;\n"
"}\n",
""));
ASSERT_EQUALS("[test.cpp:7]: (error) Uninitialized variable: b\n", errout_str());
ASSERT_EQUALS(1, (this->*check)("void f() {\n"
" int a;\n"
" // cppcheck-suppress-begin uninitvar\n"
" a++;\n"
" // cppcheck-suppress-end uninitvar\n"
" int b;\n"
" b++;\n"
"}\n",
""));
ASSERT_EQUALS("[test.cpp:7]: (error) Uninitialized variable: b\n", errout_str());
ASSERT_EQUALS(1, (this->*check)("void f() {\n"
" int a;\n"
" // cppcheck-suppress-begin[uninitvar]\n"
" a++;\n"
" // cppcheck-suppress-end[uninitvar]\n"
" int b;\n"
" b++;\n"
"}\n",
""));
ASSERT_EQUALS("[test.cpp:7]: (error) Uninitialized variable: b\n", errout_str());
ASSERT_EQUALS(1, (this->*check)("void f() {\n"
" int a;\n"
" // cppcheck-suppress-begin [uninitvar]\n"
" a++;\n"
" // cppcheck-suppress-end [uninitvar]\n"
" int b;\n"
" b++;\n"
"}\n",
""));
ASSERT_EQUALS("[test.cpp:7]: (error) Uninitialized variable: b\n", errout_str());
(this->*check)("void f() {\n"
" int a;\n"
" // cppcheck-suppress-begin uninitvar\n"
" a++;\n"
" // cppcheck-suppress-end uninitvar\n"
" int b;\n"
" // cppcheck-suppress-begin uninitvar\n"
" b++;\n"
" // cppcheck-suppress-end uninitvar\n"
"}\n",
"");
ASSERT_EQUALS("", errout_str());
(this->*check)("void f() {\n"
" int a;\n"
" // cppcheck-suppress-begin uninitvar\n"
" a++;\n"
" // cppcheck-suppress-end uninitvar\n"
" // cppcheck-suppress-begin uninitvar\n"
" int b;\n"
" b++;\n"
" // cppcheck-suppress-end uninitvar\n"
"}\n",
"");
ASSERT_EQUALS("", errout_str());
(this->*check)("void f() {\n"
" // cppcheck-suppress-begin [uninitvar]\n"
" int a;\n"
" // cppcheck-suppress-begin uninitvar\n"
" a++;\n"
" // cppcheck-suppress-end uninitvar\n"
" int b;\n"
" // cppcheck-suppress-begin uninitvar\n"
" b++;\n"
" // cppcheck-suppress-end uninitvar\n"
" // cppcheck-suppress-end [uninitvar]\n"
"}\n",
"");
ASSERT_EQUALS("", errout_str());
(this->*check)("void f() {\n"
" // cppcheck-suppress-begin [uninitvar, syntaxError]\n"
" int a;\n"
" // cppcheck-suppress-begin uninitvar\n"
" a++;\n"
" // cppcheck-suppress-end uninitvar\n"
" int b;\n"
" // cppcheck-suppress-begin uninitvar\n"
" b++;\n"
" // cppcheck-suppress-end uninitvar\n"
" // cppcheck-suppress-end [uninitvar, syntaxError]\n"
"}\n",
"");
ASSERT_EQUALS("[test.cpp:2]: (information) Unmatched suppression: syntaxError\n", errout_str());
(this->*check)("// cppcheck-suppress-begin [uninitvar, syntaxError]\n"
"void f() {\n"
" int a;\n"
" // cppcheck-suppress-begin uninitvar\n"
" a++;\n"
" // cppcheck-suppress-end uninitvar\n"
" int b;\n"
" // cppcheck-suppress-begin uninitvar\n"
" b++;\n"
" // cppcheck-suppress-end uninitvar\n"
"}\n"
"// cppcheck-suppress-end [uninitvar, syntaxError]\n",
"");
ASSERT_EQUALS("[test.cpp:1]: (information) Unmatched suppression: syntaxError\n", errout_str());
(this->*check)("// cppcheck-suppress-begin [uninitvar, syntaxError]\n"
"void f() {\n"
" int a;\n"
" // cppcheck-suppress-begin uninitvar\n"
" a++;\n"
" // cppcheck-suppress-end uninitvar\n"
" int b;\n"
" // cppcheck-suppress-begin uninitvar\n"
" b++;\n"
" // cppcheck-suppress-end uninitvar\n"
"}\n"
"// cppcheck-suppress-end [uninitvar, syntaxError]",
"");
ASSERT_EQUALS("[test.cpp:1]: (information) Unmatched suppression: syntaxError\n", errout_str());
// test of multiple suppression types
(this->*check)("// cppcheck-suppress-file uninitvar\n"
"void f() {\n"
" int a;\n"
" // cppcheck-suppress-begin uninitvar\n"
" // cppcheck-suppress uninitvar\n"
" a++;\n"
" // cppcheck-suppress-end uninitvar\n"
"}\n",
"");
ASSERT_EQUALS("", errout_str());
(this->*check)("void f() {\n"
" int a;\n"
" // cppcheck-suppress-begin uninitvar\n"
" // cppcheck-suppress uninitvar\n"
" a++;\n"
" // cppcheck-suppress-end uninitvar\n"
"}\n",
"");
ASSERT_EQUALS("", errout_str());
(this->*check)("// cppcheck-suppress-file uninitvar\n"
"void f() {\n"
" int a;\n"
" // cppcheck-suppress uninitvar\n"
" a++;\n"
"}\n",
"");
ASSERT_EQUALS("", errout_str());
(this->*check)("// cppcheck-suppress-file uninitvar\n"
"void f() {\n"
" int a;\n"
" // cppcheck-suppress-begin uninitvar\n"
" a++;\n"
" // cppcheck-suppress-end uninitvar\n"
"}\n",
"");
ASSERT_EQUALS("", errout_str());
(this->*check)("// cppcheck-suppress-file uninitvar\n"
"void f() {\n"
" // cppcheck-suppress uninitvar\n"
" int a;\n"
" a++;\n"
"}\n",
"");
ASSERT_EQUALS("[test.cpp:4]: (information) Unmatched suppression: uninitvar\n", errout_str());
// #5746 - exitcode
ASSERT_EQUALS(1U,
(this->*check)("int f() {\n"
" int a; return a;\n"
"}\n",
""));
ASSERT_EQUALS("[test.cpp:2]: (error) Uninitialized variable: a\n", errout_str());
ASSERT_EQUALS(0U,
(this->*check)("int f() {\n"
" int a; return a;\n"
"}\n",
"uninitvar"));
ASSERT_EQUALS("", errout_str());
// cppcheck-suppress-macro
(this->*check)("// cppcheck-suppress-macro zerodiv\n"
"#define DIV(A,B) A/B\n"
"a = DIV(10,0);\n",
"");
ASSERT_EQUALS("", errout_str());
(this->*check)("// cppcheck-suppress-macro abc\n"
"#define DIV(A,B) A/B\n"
"a = DIV(10,1);\n",
"");
ASSERT_EQUALS("", errout_str()); // <- no unmatched suppression reported for macro suppression
}
void suppressionsSettingsFiles() {
runChecks(&TestSuppressions::checkSuppressionFiles);
}
static void suppressionsSettingsFS() {
// TODO
// runChecks(&TestSuppressions::checkSuppressionFS);
}
void suppressionsSettingsThreadsFiles() {
runChecks(&TestSuppressions::checkSuppressionThreadsFiles);
}
void suppressionsSettingsThreadsFS() {
runChecks(&TestSuppressions::checkSuppressionThreadsFS);
}
#if !defined(WIN32) && !defined(__MINGW32__) && !defined(__CYGWIN__)
void suppressionsSettingsProcessesFiles() {
runChecks(&TestSuppressions::checkSuppressionProcessesFiles);
}
void suppressionsSettingsProcessesFS() {
runChecks(&TestSuppressions::checkSuppressionProcessesFS);
}
#endif
void suppressionsMultiFileInternal(unsigned int (TestSuppressions::*check)(std::map<std::string, std::string> &f, const std::string &)) {
std::map<std::string, std::string> files;
files["abc.cpp"] = "void f() {\n"
"}\n";
files["xyz.cpp"] = "void f() {\n"
" int a;\n"
" a++;\n"
"}\n";
// suppress uninitvar for this file and line
ASSERT_EQUALS(0, (this->*check)(files, "uninitvar:xyz.cpp:3"));
ASSERT_EQUALS("", errout_str());
}
void suppressionsMultiFileFiles() {
suppressionsMultiFileInternal(&TestSuppressions::checkSuppressionFiles);
}
void suppressionsMultiFileFS() {
suppressionsMultiFileInternal(&TestSuppressions::checkSuppressionFS);
}
void suppressionsPathSeparator() const {
const SuppressionList::Suppression s1("*", "test/foo/*");
ASSERT_EQUALS(true, s1.isSuppressed(errorMessage("someid", "test/foo/bar.cpp", 142)));
const SuppressionList::Suppression s2("abc", "include/1.h");
ASSERT_EQUALS(true, s2.isSuppressed(errorMessage("abc", "include/1.h", 142)));
}
void suppressionsLine0() const {
SuppressionList suppressions;
ASSERT_EQUALS("", suppressions.addSuppressionLine("syntaxError:*:0"));
ASSERT_EQUALS(true, suppressions.isSuppressed(errorMessage("syntaxError", "test.cpp", 0)));
}
void suppressionsFileComment() const {
std::istringstream file1("# comment\n"
"abc");
SuppressionList suppressions1;
ASSERT_EQUALS("", suppressions1.parseFile(file1));
ASSERT_EQUALS(true, suppressions1.isSuppressed(errorMessage("abc", "test.cpp", 123)));
std::istringstream file2("// comment\n"
"abc");
SuppressionList suppressions2;
ASSERT_EQUALS("", suppressions2.parseFile(file2));
ASSERT_EQUALS(true, suppressions2.isSuppressed(errorMessage("abc", "test.cpp", 123)));
std::istringstream file3("abc // comment");
SuppressionList suppressions3;
ASSERT_EQUALS("", suppressions3.parseFile(file3));
ASSERT_EQUALS(true, suppressions3.isSuppressed(errorMessage("abc", "test.cpp", 123)));
std::istringstream file4("abc\t\t # comment");
SuppressionList suppressions4;
ASSERT_EQUALS("", suppressions4.parseFile(file4));
ASSERT_EQUALS(true, suppressions4.isSuppressed(errorMessage("abc", "test.cpp", 123)));
std::istringstream file5("abc:test.cpp\t\t # comment");
SuppressionList suppressions5;
ASSERT_EQUALS("", suppressions5.parseFile(file5));
ASSERT_EQUALS(true, suppressions5.isSuppressed(errorMessage("abc", "test.cpp", 123)));
std::istringstream file6("abc:test.cpp:123\t\t # comment with . inside");
SuppressionList suppressions6;
ASSERT_EQUALS("", suppressions6.parseFile(file6));
ASSERT_EQUALS(true, suppressions6.isSuppressed(errorMessage("abc", "test.cpp", 123)));
std::istringstream file7(" // comment\n" // #11450
"abc");
SuppressionList suppressions7;
ASSERT_EQUALS("", suppressions7.parseFile(file7));
ASSERT_EQUALS(true, suppressions7.isSuppressed(errorMessage("abc", "test.cpp", 123)));
}
void inlinesuppress() const {
SuppressionList::Suppression s;
std::string msg;
// Suppress without attribute
ASSERT_EQUALS(false, s.parseComment("/* some text */", &msg));
ASSERT_EQUALS(false, s.parseComment("/* cppcheck-suppress */", &msg));
ASSERT_EQUALS(false, s.parseComment("/* cppcheck-suppress-file */", &msg));
ASSERT_EQUALS(false, s.parseComment("/* cppcheck-suppress-begin */", &msg));
ASSERT_EQUALS(false, s.parseComment("/* cppcheck-suppress-end */", &msg));
// Correct suppress
msg.clear();
ASSERT_EQUALS(true, s.parseComment("/* cppcheck-suppress id */", &msg));
ASSERT_EQUALS("", msg);
msg.clear();
ASSERT_EQUALS(true, s.parseComment("/* cppcheck-suppress-file id */", &msg));
ASSERT_EQUALS("", msg);
msg.clear();
ASSERT_EQUALS(true, s.parseComment("/* cppcheck-suppress-begin id */", &msg));
ASSERT_EQUALS("", msg);
msg.clear();
ASSERT_EQUALS(true, s.parseComment("/* cppcheck-suppress-end id */", &msg));
ASSERT_EQUALS("", msg);
// Bad cppcheck-suppress comment
ASSERT_EQUALS(false, s.parseComment("/* cppcheck-suppress-beggin id */", &msg));
// Bad attribute construction
const std::string badSuppressionAttribute = "Bad suppression attribute 'some'. You can write comments in the comment after a ; or //. Valid suppression attributes; symbolName=sym";
ASSERT_EQUALS(true, s.parseComment("/* cppcheck-suppress id some text */", &msg));
ASSERT_EQUALS(badSuppressionAttribute, msg);
ASSERT_EQUALS(true, s.parseComment("/* cppcheck-suppress-file id some text */", &msg));
ASSERT_EQUALS(badSuppressionAttribute, msg);
ASSERT_EQUALS(true, s.parseComment("/* cppcheck-suppress-begin id some text */", &msg));
ASSERT_EQUALS(badSuppressionAttribute, msg);
ASSERT_EQUALS(true, s.parseComment("/* cppcheck-suppress-end id some text */", &msg));
ASSERT_EQUALS(badSuppressionAttribute, msg);
}
void inlinesuppress_symbolname_Internal(unsigned int (TestSuppressions::*check)(const char[], const std::string &)) {
ASSERT_EQUALS(0, (this->*check)("void f() {\n"
" int a;\n"
" /* cppcheck-suppress uninitvar symbolName=a */\n"
" a++;\n"
"}\n",
""));
ASSERT_EQUALS("", errout_str());
ASSERT_EQUALS(1, (this->*check)("void f() {\n"
" int a,b;\n"
" /* cppcheck-suppress uninitvar symbolName=b */\n"
" a++; b++;\n"
"}\n",
""));
ASSERT_EQUALS("[test.cpp:4]: (error) Uninitialized variable: a\n", errout_str());
}
void inlinesuppress_symbolname_Files() {
inlinesuppress_symbolname_Internal(&TestSuppressions::checkSuppressionFiles);
}
void inlinesuppress_symbolname_FS() {
inlinesuppress_symbolname_Internal(&TestSuppressions::checkSuppressionFS);
}
void inlinesuppress_comment() const {
SuppressionList::Suppression s;
std::string errMsg;
ASSERT_EQUALS(true, s.parseComment("// cppcheck-suppress abc ; some comment", &errMsg));
ASSERT_EQUALS("", errMsg);
ASSERT_EQUALS(true, s.parseComment("// cppcheck-suppress abc // some comment", &errMsg));
ASSERT_EQUALS("", errMsg);
ASSERT_EQUALS(true, s.parseComment("// cppcheck-suppress abc -- some comment", &errMsg));
ASSERT_EQUALS("", errMsg);
}
void multi_inlinesuppress() const {
std::vector<SuppressionList::Suppression> suppressions;
std::string errMsg;
errMsg = "";
suppressions=SuppressionList::parseMultiSuppressComment("// cppcheck-suppress[errorId]", &errMsg);
ASSERT_EQUALS(1, suppressions.size());
ASSERT_EQUALS("errorId", suppressions[0].errorId);
ASSERT_EQUALS("", suppressions[0].symbolName);
ASSERT_EQUALS("", errMsg);
errMsg = "";
suppressions=SuppressionList::parseMultiSuppressComment("// cppcheck-suppress-begin[errorId]", &errMsg);
ASSERT_EQUALS(1, suppressions.size());
ASSERT_EQUALS("errorId", suppressions[0].errorId);
ASSERT_EQUALS("", suppressions[0].symbolName);
ASSERT_EQUALS("", errMsg);
errMsg = "";
suppressions=SuppressionList::parseMultiSuppressComment("// cppcheck-suppress-begin [errorId]", &errMsg);
ASSERT_EQUALS(1, suppressions.size());
ASSERT_EQUALS("errorId", suppressions[0].errorId);
ASSERT_EQUALS("", suppressions[0].symbolName);
ASSERT_EQUALS("", errMsg);
errMsg = "";
suppressions=SuppressionList::parseMultiSuppressComment("// cppcheck-suppress-end[errorId]", &errMsg);
ASSERT_EQUALS(1, suppressions.size());
ASSERT_EQUALS("errorId", suppressions[0].errorId);
ASSERT_EQUALS("", suppressions[0].symbolName);
ASSERT_EQUALS("", errMsg);
errMsg = "";
suppressions=SuppressionList::parseMultiSuppressComment("// cppcheck-suppress-end [errorId]", &errMsg);
ASSERT_EQUALS(1, suppressions.size());
ASSERT_EQUALS("errorId", suppressions[0].errorId);
ASSERT_EQUALS("", suppressions[0].symbolName);
ASSERT_EQUALS("", errMsg);
errMsg = "";
suppressions=SuppressionList::parseMultiSuppressComment("// cppcheck-suppress-file[errorId]", &errMsg);
ASSERT_EQUALS(1, suppressions.size());
ASSERT_EQUALS("errorId", suppressions[0].errorId);
ASSERT_EQUALS("", suppressions[0].symbolName);
ASSERT_EQUALS("", errMsg);
errMsg = "";
suppressions=SuppressionList::parseMultiSuppressComment("// cppcheck-suppress-file [errorId]", &errMsg);
ASSERT_EQUALS(1, suppressions.size());
ASSERT_EQUALS("errorId", suppressions[0].errorId);
ASSERT_EQUALS("", suppressions[0].symbolName);
ASSERT_EQUALS("", errMsg);
errMsg = "";
suppressions=SuppressionList::parseMultiSuppressComment("// cppcheck-suppress[errorId symbolName=arr]", &errMsg);
ASSERT_EQUALS(1, suppressions.size());
ASSERT_EQUALS("errorId", suppressions[0].errorId);
ASSERT_EQUALS("arr", suppressions[0].symbolName);
ASSERT_EQUALS("", errMsg);
errMsg = "";
suppressions=SuppressionList::parseMultiSuppressComment("// cppcheck-suppress[errorId symbolName=]", &errMsg);
ASSERT_EQUALS(1, suppressions.size());
ASSERT_EQUALS("errorId", suppressions[0].errorId);
ASSERT_EQUALS("", suppressions[0].symbolName);
ASSERT_EQUALS("", errMsg);
errMsg = "";
suppressions=SuppressionList::parseMultiSuppressComment("// cppcheck-suppress[errorId1, errorId2 symbolName=arr]", &errMsg);
ASSERT_EQUALS(2, suppressions.size());
ASSERT_EQUALS("errorId1", suppressions[0].errorId);
ASSERT_EQUALS("", suppressions[0].symbolName);
ASSERT_EQUALS("errorId2", suppressions[1].errorId);
ASSERT_EQUALS("arr", suppressions[1].symbolName);
ASSERT_EQUALS("", errMsg);
errMsg = "";
suppressions=SuppressionList::parseMultiSuppressComment("// cppcheck-suppress[]", &errMsg);
ASSERT_EQUALS(0, suppressions.size());
ASSERT_EQUALS(true, errMsg.empty());
errMsg = "";
suppressions=SuppressionList::parseMultiSuppressComment("// cppcheck-suppress[errorId", &errMsg);
ASSERT_EQUALS(0, suppressions.size());
ASSERT_EQUALS(false, errMsg.empty());
errMsg = "";
suppressions=SuppressionList::parseMultiSuppressComment("// cppcheck-suppress errorId", &errMsg);
ASSERT_EQUALS(0, suppressions.size());
ASSERT_EQUALS(false, errMsg.empty());
errMsg = "";
suppressions=SuppressionList::parseMultiSuppressComment("// cppcheck-suppress[errorId1 errorId2 symbolName=arr]", &errMsg);
ASSERT_EQUALS(0, suppressions.size());
ASSERT_EQUALS(false, errMsg.empty());
errMsg = "";
suppressions=SuppressionList::parseMultiSuppressComment("// cppcheck-suppress[errorId1, errorId2 symbol=arr]", &errMsg);
ASSERT_EQUALS(0, suppressions.size());
ASSERT_EQUALS(false, errMsg.empty());
errMsg = "";
suppressions=SuppressionList::parseMultiSuppressComment("// cppcheck-suppress[errorId1, errorId2 symbolName]", &errMsg);
ASSERT_EQUALS(0, suppressions.size());
ASSERT_EQUALS(false, errMsg.empty());
}
void multi_inlinesuppress_comment() const {
std::vector<SuppressionList::Suppression> suppressions;
std::string errMsg;
errMsg = "";
suppressions=SuppressionList::parseMultiSuppressComment("//cppcheck-suppress[errorId1, errorId2 symbolName=arr]", &errMsg);
ASSERT_EQUALS(2, suppressions.size());
ASSERT_EQUALS(true, errMsg.empty());
errMsg = "";
suppressions=SuppressionList::parseMultiSuppressComment("//cppcheck-suppress[errorId1, errorId2 symbolName=arr] some text", &errMsg);
ASSERT_EQUALS(2, suppressions.size());
ASSERT_EQUALS(true, errMsg.empty());
errMsg = "";
suppressions=SuppressionList::parseMultiSuppressComment("/*cppcheck-suppress[errorId1, errorId2 symbolName=arr]*/", &errMsg);
ASSERT_EQUALS(2, suppressions.size());
ASSERT_EQUALS(true, errMsg.empty());
}
void globalSuppressions() { // Testing that Cppcheck::useGlobalSuppressions works (#8515)
CppCheck cppCheck(*this, false, nullptr); // <- do not "use global suppressions". pretend this is a thread that just checks a file.
Settings& settings = cppCheck.settings();
settings.quiet = true;
ASSERT_EQUALS("", settings.supprs.nomsg.addSuppressionLine("uninitvar"));
settings.exitCode = 1;
const char code[] = "int f() { int a; return a; }";
ASSERT_EQUALS(0, cppCheck.check(FileWithDetails("test.c"), code)); // <- no unsuppressed error is seen
ASSERT_EQUALS("[test.c:1]: (error) Uninitialized variable: a\n", errout_str()); // <- report error so ThreadExecutor can suppress it and make sure the global suppression is matched.
}
void inlinesuppress_unusedFunction() const { // #4210, #4946 - wrong report of "unmatchedSuppression" for "unusedFunction"
SuppressionList suppressions;
SuppressionList::Suppression suppression("unusedFunction", "test.c", 3);
suppression.checked = true; // have to do this because fixes for #5704
ASSERT_EQUALS("", suppressions.addSuppression(std::move(suppression)));
ASSERT_EQUALS(true, !suppressions.getUnmatchedLocalSuppressions(FileWithDetails("test.c"), true).empty());
ASSERT_EQUALS(false, !suppressions.getUnmatchedGlobalSuppressions(true).empty());
ASSERT_EQUALS(false, !suppressions.getUnmatchedLocalSuppressions(FileWithDetails("test.c"), false).empty());
ASSERT_EQUALS(false, !suppressions.getUnmatchedGlobalSuppressions(false).empty());
}
void globalsuppress_unusedFunction() const { // #4946 - wrong report of "unmatchedSuppression" for "unusedFunction"
SuppressionList suppressions;
ASSERT_EQUALS("", suppressions.addSuppressionLine("unusedFunction:*"));
ASSERT_EQUALS(false, !suppressions.getUnmatchedLocalSuppressions(FileWithDetails("test.c"), true).empty());
ASSERT_EQUALS(true, !suppressions.getUnmatchedGlobalSuppressions(true).empty());
ASSERT_EQUALS(false, !suppressions.getUnmatchedLocalSuppressions(FileWithDetails("test.c"), false).empty());
ASSERT_EQUALS(false, !suppressions.getUnmatchedGlobalSuppressions(false).empty());
}
void suppressionWithRelativePaths() {
CppCheck cppCheck(*this, true, nullptr);
Settings& settings = cppCheck.settings();
settings.quiet = true;
settings.severity.enable(Severity::style);
settings.inlineSuppressions = true;
settings.relativePaths = true;
settings.basePaths.emplace_back("/somewhere");
const char code[] =
"struct Point\n"
"{\n"
" // cppcheck-suppress unusedStructMember\n"
" int x;\n"
" // cppcheck-suppress unusedStructMember\n"
" int y;\n"
"};";
ASSERT_EQUALS(0, cppCheck.check(FileWithDetails("/somewhere/test.cpp"), code));
ASSERT_EQUALS("",errout_str());
}
void suppressingSyntaxErrorsInternal(unsigned int (TestSuppressions::*check)(const char[], const std::string &)) { // syntaxErrors should be suppressible (#7076)
const char code[] = "if if\n";
ASSERT_EQUALS(0, (this->*check)(code, "syntaxError:test.cpp:1"));
ASSERT_EQUALS("", errout_str());
}
void suppressingSyntaxErrorsFiles() {
suppressingSyntaxErrorsInternal(&TestSuppressions::checkSuppressionFiles);
}
void suppressingSyntaxErrorsFS() {
suppressingSyntaxErrorsInternal(&TestSuppressions::checkSuppressionFiles);
}
void suppressingSyntaxErrorsInlineInternal(unsigned int (TestSuppressions::*check)(const char[], const std::string &)) { // syntaxErrors should be suppressible (#5917)
const char code[] = "double result(0.0);\n"
"_asm\n"
"{\n"
" // cppcheck-suppress syntaxError\n"
" push EAX ; save EAX for callers\n"
" mov EAX,Real10 ; get the address pointed to by Real10\n"
" fld TBYTE PTR [EAX] ; load an extended real (10 bytes)\n"
" fstp QWORD PTR result ; store a double (8 bytes)\n"
" pop EAX ; restore EAX\n"
"}";
ASSERT_EQUALS(0, (this->*check)(code, ""));
ASSERT_EQUALS("", errout_str());
}
void suppressingSyntaxErrorsInlineFiles() {
suppressingSyntaxErrorsInlineInternal(&TestSuppressions::checkSuppressionFiles);
}
void suppressingSyntaxErrorsInlineFS() {
suppressingSyntaxErrorsInlineInternal(&TestSuppressions::checkSuppressionFS);
}
void suppressingSyntaxErrorsWhileFileReadInternal(unsigned int (TestSuppressions::*check)(const char[], const std::string &)) { // syntaxError while file read should be suppressible (PR #1333)
const char code[] = "CONST (genType, KS_CONST) genService[KS_CFG_NR_OF_NVM_BLOCKS] =\n"
"{\n"
"[!VAR \"BC\" = \"$BC + 1\"!][!//\n"
"[!IF \"(as:modconf('Ks')[1]/KsGeneral/KsType = 'KS_CFG_TYPE_KS_MASTER') and\n"
" (as:modconf('Ks')[1]/KsGeneral/KsUseShe = 'true')\"!][!//\n"
" {\n"
" &varNB_GetErrorStatus,\n"
" &varNB_WriteBlock,\n"
" &varNB_ReadBlock\n"
" },\n"
"[!VAR \"BC\" = \"$BC + 1\"!][!//\n"
"[!ENDIF!][!//\n"
"};";
ASSERT_EQUALS(0, (this->*check)(code, "syntaxError:test.cpp:4"));
ASSERT_EQUALS("", errout_str());
}
void suppressingSyntaxErrorsWhileFileReadFiles() {
suppressingSyntaxErrorsWhileFileReadInternal(&TestSuppressions::checkSuppressionFiles);
}
void suppressingSyntaxErrorsWhileFileReadFS() {
suppressingSyntaxErrorsWhileFileReadInternal(&TestSuppressions::checkSuppressionFiles);
}
void symbol() const {
SuppressionList::Suppression s;
s.errorId = "foo";
s.symbolName = "array*";
SuppressionList::ErrorMessage errorMsg;
errorMsg.errorId = "foo";
errorMsg.setFileName("test.cpp");
errorMsg.lineNumber = 123;
errorMsg.symbolNames = "";
ASSERT_EQUALS(false, s.isSuppressed(errorMsg));
errorMsg.symbolNames = "x\n";
ASSERT_EQUALS(false, s.isSuppressed(errorMsg));
errorMsg.symbolNames = "array1\n";
ASSERT_EQUALS(true, s.isSuppressed(errorMsg));
errorMsg.symbolNames = "x\n"
"array2\n";
ASSERT_EQUALS(true, s.isSuppressed(errorMsg));
errorMsg.symbolNames = "array3\n"
"x\n";
ASSERT_EQUALS(true, s.isSuppressed(errorMsg));
}
void unusedFunctionInternal(unsigned int (TestSuppressions::*check)(const char[], const std::string &)) {
ASSERT_EQUALS(0, (this->*check)("void f() {}", "unusedFunction"));
}
void unusedFunctionFiles() {
unusedFunctionInternal(&TestSuppressions::checkSuppressionFiles);
}
void unusedFunctionFS() {
unusedFunctionInternal(&TestSuppressions::checkSuppressionFS);
}
void suppressingSyntaxErrorAndExitCodeInternal(unsigned int (TestSuppressions::*check)(const char[], const std::string &)) {
const char code[] = "fi if;";
ASSERT_EQUALS(0, (this->*check)(code, "*:test.cpp"));
ASSERT_EQUALS("", errout_str());
// multi error in file, but only suppression one error
const char code2[] = "fi fi\n"
"if if;";
ASSERT_EQUALS(1, (this->*check)(code2, "*:test.cpp:1")); // suppress all error at line 1 of test.cpp
ASSERT_EQUALS("[test.cpp:2]: (error) syntax error\n", errout_str());
// multi error in file, but only suppression one error (2)
const char code3[] = "void f(int x, int y){\n"
" int a = x/0;\n"
" int b = y/0;\n"
"}\n"
"f(0, 1);\n";
ASSERT_EQUALS(1, (this->*check)(code3, "zerodiv:test.cpp:3")); // suppress 'zerodiv' at line 3 of test.cpp
ASSERT_EQUALS("[test.cpp:2]: (error) Division by zero.\n", errout_str());
}
void suppressingSyntaxErrorAndExitCodeFiles() {
suppressingSyntaxErrorAndExitCodeInternal(&TestSuppressions::checkSuppressionFiles);
}
static void suppressingSyntaxErrorAndExitCodeFS() {
// TODO
// suppressingSyntaxErrorAndExitCodeInternal(&TestSuppressions::checkSuppressionFS);
}
void suppressingSyntaxErrorAndExitCodeMultiFileInternal(unsigned int (TestSuppressions::*check)(std::map<std::string, std::string> &f, const std::string &)) {
// multi files, but only suppression one
std::map<std::string, std::string> mfiles;
mfiles["test.cpp"] = "fi if;";
mfiles["test2.cpp"] = "fi if";
ASSERT_EQUALS(1, (this->*check)(mfiles, "*:test.cpp"));
ASSERT_EQUALS("[test2.cpp:1]: (error) syntax error\n", errout_str());
}
void suppressingSyntaxErrorAndExitCodeMultiFileFiles() {
suppressingSyntaxErrorAndExitCodeMultiFileInternal(&TestSuppressions::checkSuppressionFiles);
}
static void suppressingSyntaxErrorAndExitCodeMultiFileFS() {
// TODO
// suppressingSyntaxErrorAndExitCodeMultiFileInternal(&TestSuppressions::checkSuppressionFS);
}
void suppressLocal() const {
SuppressionList suppressions;
std::istringstream s("errorid:test.cpp\n"
"errorid2");
ASSERT_EQUALS("", suppressions.parseFile(s));
ASSERT_EQUALS(true, suppressions.isSuppressed(errorMessage("errorid", "test.cpp", 1)));
ASSERT_EQUALS(true, suppressions.isSuppressed(errorMessage("errorid", "test.cpp", 1), false));
ASSERT_EQUALS(false, suppressions.isSuppressed(errorMessage("errorid", "test2.cpp", 1)));
ASSERT_EQUALS(false, suppressions.isSuppressed(errorMessage("errorid", "test2.cpp", 1), false));
ASSERT_EQUALS(true, suppressions.isSuppressed(errorMessage("errorid2", "test.cpp", 1)));
ASSERT_EQUALS(false, suppressions.isSuppressed(errorMessage("errorid2", "test.cpp", 1), false));
ASSERT_EQUALS(true, suppressions.isSuppressed(errorMessage("errorid2", "test2.cpp", 1)));
ASSERT_EQUALS(false, suppressions.isSuppressed(errorMessage("errorid2", "test2.cpp", 1), false));
}
void suppressUnmatchedSuppressions() {
std::list<SuppressionList::Suppression> suppressions;
// No unmatched suppression
suppressions.clear();
ASSERT_EQUALS(false, SuppressionList::reportUnmatchedSuppressions(suppressions, *this));
ASSERT_EQUALS("", errout_str());
// suppress all unmatchedSuppression
suppressions.clear();
suppressions.emplace_back("abc", "a.c", 10U);
suppressions.emplace_back("unmatchedSuppression", "*", SuppressionList::Suppression::NO_LINE);
ASSERT_EQUALS(false, SuppressionList::reportUnmatchedSuppressions(suppressions, *this));
ASSERT_EQUALS("", errout_str());
// suppress all unmatchedSuppression (corresponds to "--suppress=unmatchedSuppression")
suppressions.clear();
suppressions.emplace_back("abc", "a.c", 10U);
suppressions.emplace_back("unmatchedSuppression", "", SuppressionList::Suppression::NO_LINE);
ASSERT_EQUALS(false, SuppressionList::reportUnmatchedSuppressions(suppressions, *this));
ASSERT_EQUALS("", errout_str());
// suppress all unmatchedSuppression in a.c
suppressions.clear();
suppressions.emplace_back("abc", "a.c", 10U);
suppressions.emplace_back("unmatchedSuppression", "a.c", SuppressionList::Suppression::NO_LINE);
ASSERT_EQUALS(false, SuppressionList::reportUnmatchedSuppressions(suppressions, *this));
ASSERT_EQUALS("", errout_str());
// suppress unmatchedSuppression in a.c at line 10
suppressions.clear();
suppressions.emplace_back("abc", "a.c", 10U);
suppressions.emplace_back("unmatchedSuppression", "a.c", 10U);
ASSERT_EQUALS(false, SuppressionList::reportUnmatchedSuppressions(suppressions, *this));
ASSERT_EQUALS("", errout_str());
// don't suppress unmatchedSuppression when file is mismatching
suppressions.clear();
suppressions.emplace_back("abc", "a.c", 10U);
suppressions.emplace_back("unmatchedSuppression", "b.c", SuppressionList::Suppression::NO_LINE);
ASSERT_EQUALS(true, SuppressionList::reportUnmatchedSuppressions(suppressions, *this));
ASSERT_EQUALS("[a.c:10]: (information) Unmatched suppression: abc\n", errout_str());
// don't suppress unmatchedSuppression when line is mismatching
suppressions.clear();
suppressions.emplace_back("abc", "a.c", 10U);
suppressions.emplace_back("unmatchedSuppression", "a.c", 1U);
ASSERT_EQUALS(true, SuppressionList::reportUnmatchedSuppressions(suppressions, *this));
ASSERT_EQUALS("[a.c:10]: (information) Unmatched suppression: abc\n", errout_str());
}
void suppressionsParseXmlFile() const {
{
ScopedFile file("suppressparsexml.xml",
"<suppressions>\n"
"<suppress>\n"
"<id>uninitvar</id>\n"
"<fileName>file.c</fileName>\n"
"<lineNumber>10</lineNumber>\n"
"<symbolName>sym</symbolName>\n"
"</suppress>\n"
"</suppressions>");
SuppressionList supprList;
ASSERT_EQUALS("", supprList.parseXmlFile(file.path().c_str()));
const auto& supprs = supprList.getSuppressions();
ASSERT_EQUALS(1, supprs.size());
const auto& suppr = *supprs.cbegin();
ASSERT_EQUALS("uninitvar", suppr.errorId);
ASSERT_EQUALS("file.c", suppr.fileName);
ASSERT_EQUALS(10, suppr.lineNumber);
ASSERT_EQUALS("sym", suppr.symbolName);
}
// no file specified
{
SuppressionList supprList;
ASSERT_EQUALS("failed to load suppressions XML '' (XML_ERROR_FILE_NOT_FOUND).", supprList.parseXmlFile(""));
}
// missing file
{
SuppressionList supprList;
ASSERT_EQUALS("failed to load suppressions XML 'suppressparsexml.xml' (XML_ERROR_FILE_NOT_FOUND).", supprList.parseXmlFile("suppressparsexml.xml"));
}
// empty file
{
ScopedFile file("suppressparsexml.xml",
"");
SuppressionList supprList;
ASSERT_EQUALS("failed to load suppressions XML 'suppressparsexml.xml' (XML_ERROR_EMPTY_DOCUMENT).", supprList.parseXmlFile(file.path().c_str()));
}
// wrong root node
{
ScopedFile file("suppressparsexml.xml",
"<suppress/>\n");
SuppressionList supprList;
ASSERT_EQUALS("", supprList.parseXmlFile(file.path().c_str()));
}
// no root node
{
ScopedFile file("suppressparsexml.xml",
"<?xml version=\"1.0\"?>\n");
SuppressionList supprList;
ASSERT_EQUALS("failed to load suppressions XML 'suppressparsexml.xml' (no root node found).", supprList.parseXmlFile(file.path().c_str()));
}
// unknown element
{
ScopedFile file("suppressparsexml.xml",
"<suppressions>\n"
"<suppress>\n"
"<eid>uninitvar</eid>\n"
"</suppress>\n"
"</suppressions>");
SuppressionList supprList;
ASSERT_EQUALS("unknown element 'eid' in suppressions XML 'suppressparsexml.xml', expected id/fileName/lineNumber/symbolName/hash.", supprList.parseXmlFile(file.path().c_str()));
}
}
};
REGISTER_TEST(TestSuppressions)
| null |
977 | cpp | cppcheck | testcmdlineparser.cpp | test/testcmdlineparser.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "cmdlinelogger.h"
#include "cmdlineparser.h"
#include "config.h"
#include "errorlogger.h"
#include "errortypes.h"
#include "helpers.h"
#include "path.h"
#include "platform.h"
#include "redirect.h"
#include "settings.h"
#include "standards.h"
#include "suppressions.h"
#include "fixture.h"
#include "timer.h"
#include "utils.h"
#include <cstdio>
#include <list>
#include <memory>
#include <set>
#include <stdexcept>
#include <string>
#include <unordered_set>
#include <vector>
class TestCmdlineParser : public TestFixture {
public:
TestCmdlineParser() : TestFixture("TestCmdlineParser")
{}
private:
class CmdLineLoggerTest : public CmdLineLogger
{
public:
CmdLineLoggerTest() = default;
void printMessage(const std::string &message) override
{
printInternal("cppcheck: " + message + '\n');
}
void printError(const std::string &message) override
{
printMessage("error: " + message);
}
void printRaw(const std::string &message) override
{
printInternal(message + '\n');
}
std::string str()
{
std::string s;
std::swap(buf, s);
return s;
}
void destroy()
{
if (!buf.empty())
throw std::runtime_error("unconsumed messages: " + buf);
}
private:
void printInternal(const std::string &message)
{
buf += message;
}
std::string buf;
};
std::unique_ptr<CmdLineLoggerTest> logger;
std::unique_ptr<Settings> settings;
std::unique_ptr<CmdLineParser> parser;
void prepareTestInternal() override {
logger.reset(new CmdLineLoggerTest());
settings.reset(new Settings());
parser.reset(new CmdLineParser(*logger, *settings, settings->supprs));
}
void teardownTestInternal() override {
logger->destroy();
}
void asPremium() {
// set this so we think it is the premium
settings->cppcheckCfgProductName = "Cppcheck Premium 0.0.0";
}
void run() override {
TEST_CASE(nooptions);
TEST_CASE(helpshort);
TEST_CASE(helpshortExclusive);
TEST_CASE(helplong);
TEST_CASE(helplongExclusive);
TEST_CASE(version);
TEST_CASE(versionWithCfg);
TEST_CASE(versionExclusive);
TEST_CASE(versionWithInvalidCfg);
TEST_CASE(checkVersionCorrect);
TEST_CASE(checkVersionIncorrect);
TEST_CASE(onefile);
TEST_CASE(onepath);
TEST_CASE(optionwithoutfile);
TEST_CASE(verboseshort);
TEST_CASE(verboselong);
TEST_CASE(debugSimplified);
TEST_CASE(debugwarnings);
TEST_CASE(forceshort);
TEST_CASE(forcelong);
TEST_CASE(relativePaths1);
TEST_CASE(relativePaths2);
TEST_CASE(relativePaths3);
TEST_CASE(relativePaths4);
TEST_CASE(quietshort);
TEST_CASE(quietlong);
TEST_CASE(defines_noarg);
TEST_CASE(defines_noarg2);
TEST_CASE(defines_noarg3);
TEST_CASE(defines);
TEST_CASE(defines2);
TEST_CASE(defines3);
TEST_CASE(defines4);
TEST_CASE(enforceLanguage1);
TEST_CASE(enforceLanguage2);
TEST_CASE(enforceLanguage3);
TEST_CASE(enforceLanguage4);
TEST_CASE(enforceLanguage5);
TEST_CASE(enforceLanguage6);
TEST_CASE(enforceLanguage7);
TEST_CASE(includesnopath);
TEST_CASE(includes);
TEST_CASE(includesslash);
TEST_CASE(includesbackslash);
TEST_CASE(includesnospace);
TEST_CASE(includes2);
TEST_CASE(includesFile);
TEST_CASE(includesFileNoFile);
TEST_CASE(configExcludesFile);
TEST_CASE(configExcludesFileNoFile);
TEST_CASE(enabledAll);
TEST_CASE(enabledStyle);
TEST_CASE(enabledPerformance);
TEST_CASE(enabledPortability);
TEST_CASE(enabledInformation);
TEST_CASE(enabledUnusedFunction);
TEST_CASE(enabledMissingInclude);
TEST_CASE(disabledMissingIncludeWithInformation);
TEST_CASE(enabledMissingIncludeWithInformation);
TEST_CASE(enabledMissingIncludeWithInformationReverseOrder);
#ifdef CHECK_INTERNAL
TEST_CASE(enabledInternal);
#endif
TEST_CASE(enabledMultiple);
TEST_CASE(enabledInvalid);
TEST_CASE(enabledError);
TEST_CASE(enabledEmpty);
TEST_CASE(disableAll);
TEST_CASE(disableMultiple);
TEST_CASE(disableStylePartial);
TEST_CASE(disableInformationPartial);
TEST_CASE(disableInformationPartial2);
TEST_CASE(disableInvalid);
TEST_CASE(disableError);
TEST_CASE(disableEmpty);
TEST_CASE(inconclusive);
TEST_CASE(errorExitcode);
TEST_CASE(errorExitcodeMissing);
TEST_CASE(errorExitcodeStr);
TEST_CASE(exitcodeSuppressionsOld);
TEST_CASE(exitcodeSuppressions);
TEST_CASE(exitcodeSuppressionsNoFile);
TEST_CASE(fileFilterStdin);
TEST_CASE(fileList);
TEST_CASE(fileListNoFile);
TEST_CASE(fileListStdin);
TEST_CASE(fileListInvalid);
TEST_CASE(inlineSuppr);
TEST_CASE(jobs);
TEST_CASE(jobs2);
TEST_CASE(jobsMissingCount);
TEST_CASE(jobsInvalid);
TEST_CASE(jobsNoJobs);
TEST_CASE(jobsTooBig);
TEST_CASE(maxConfigs);
TEST_CASE(maxConfigsMissingCount);
TEST_CASE(maxConfigsInvalid);
TEST_CASE(maxConfigsTooSmall);
TEST_CASE(outputFormatSarif);
TEST_CASE(outputFormatXml);
TEST_CASE(outputFormatOther);
TEST_CASE(outputFormatImplicitPlist);
TEST_CASE(outputFormatImplicitXml);
TEST_CASE(premiumOptions1);
TEST_CASE(premiumOptions2);
TEST_CASE(premiumOptions3);
TEST_CASE(premiumOptions4);
TEST_CASE(premiumOptions5);
TEST_CASE(premiumOptionsCertCIntPrecision);
TEST_CASE(premiumOptionsLicenseFile);
TEST_CASE(premiumOptionsInvalid1);
TEST_CASE(premiumOptionsInvalid2);
TEST_CASE(premiumSafety);
TEST_CASE(reportProgress1);
TEST_CASE(reportProgress2);
TEST_CASE(reportProgress3);
TEST_CASE(reportProgress4);
TEST_CASE(reportProgress5);
TEST_CASE(stdc99);
TEST_CASE(stdgnu17);
TEST_CASE(stdiso9899_1999);
TEST_CASE(stdcpp11);
TEST_CASE(stdgnupp23);
TEST_CASE(stdunknown1);
TEST_CASE(stdunknown2);
TEST_CASE(stdunknown3);
TEST_CASE(stdoverwrite1);
TEST_CASE(stdoverwrite2);
TEST_CASE(stdoverwrite3);
TEST_CASE(stdoverwrite4);
TEST_CASE(stdmulti1);
TEST_CASE(stdmulti2);
TEST_CASE(platformWin64);
TEST_CASE(platformWin32A);
TEST_CASE(platformWin32W);
TEST_CASE(platformUnix32);
TEST_CASE(platformUnix32Unsigned);
TEST_CASE(platformUnix64);
TEST_CASE(platformUnix64Unsigned);
TEST_CASE(platformNative);
TEST_CASE(platformUnspecified);
TEST_CASE(platformPlatformFile);
TEST_CASE(platformUnknown);
TEST_CASE(plistEmpty);
TEST_CASE(plistDoesNotExist);
TEST_CASE(suppressionsOld);
TEST_CASE(suppressions);
TEST_CASE(suppressionsNoFile1);
TEST_CASE(suppressionsNoFile2);
TEST_CASE(suppressionsNoFile3);
TEST_CASE(suppressionSingle);
TEST_CASE(suppressionSingleFile);
TEST_CASE(suppressionTwo);
TEST_CASE(suppressionTwoSeparate);
TEST_CASE(templates);
TEST_CASE(templatesGcc);
TEST_CASE(templatesVs);
TEST_CASE(templatesEdit);
TEST_CASE(templatesCppcheck1);
TEST_CASE(templatesDaca2);
TEST_CASE(templatesSelfcheck);
TEST_CASE(templatesSimple);
TEST_CASE(templatesNoPlaceholder);
TEST_CASE(templateFormatInvalid);
TEST_CASE(templateFormatEmpty);
TEST_CASE(templateLocationInvalid);
TEST_CASE(templateLocationEmpty);
TEST_CASE(xml);
TEST_CASE(xmlver2);
TEST_CASE(xmlver2both);
TEST_CASE(xmlver2both2);
TEST_CASE(xmlverunknown);
TEST_CASE(xmlverinvalid);
TEST_CASE(doc);
TEST_CASE(docExclusive);
TEST_CASE(showtimeSummary);
TEST_CASE(showtimeFile);
TEST_CASE(showtimeFileTotal);
TEST_CASE(showtimeTop5);
TEST_CASE(showtimeTop5File);
TEST_CASE(showtimeTop5Summary);
TEST_CASE(showtimeNone);
TEST_CASE(showtimeEmpty);
TEST_CASE(showtimeInvalid);
TEST_CASE(errorlist);
TEST_CASE(errorlistWithCfg);
TEST_CASE(errorlistExclusive);
TEST_CASE(errorlistWithInvalidCfg);
TEST_CASE(ignorepathsnopath);
#if defined(USE_WINDOWS_SEH) || defined(USE_UNIX_SIGNAL_HANDLING)
TEST_CASE(exceptionhandling);
TEST_CASE(exceptionhandling2);
TEST_CASE(exceptionhandling3);
TEST_CASE(exceptionhandlingInvalid);
TEST_CASE(exceptionhandlingInvalid2);
#else
TEST_CASE(exceptionhandlingNotSupported);
TEST_CASE(exceptionhandlingNotSupported2);
#endif
TEST_CASE(clang);
TEST_CASE(clang2);
TEST_CASE(clangInvalid);
TEST_CASE(valueFlowMaxIterations);
TEST_CASE(valueFlowMaxIterations2);
TEST_CASE(valueFlowMaxIterationsInvalid);
TEST_CASE(valueFlowMaxIterationsInvalid2);
TEST_CASE(valueFlowMaxIterationsInvalid3);
TEST_CASE(checksMaxTime);
TEST_CASE(checksMaxTime2);
TEST_CASE(checksMaxTimeInvalid);
#ifdef HAS_THREADING_MODEL_FORK
TEST_CASE(loadAverage);
TEST_CASE(loadAverage2);
TEST_CASE(loadAverageInvalid);
#else
TEST_CASE(loadAverageNotSupported);
#endif
TEST_CASE(maxCtuDepth);
TEST_CASE(maxCtuDepth2);
TEST_CASE(maxCtuDepthLimit);
TEST_CASE(maxCtuDepthInvalid);
TEST_CASE(performanceValueflowMaxTime);
TEST_CASE(performanceValueflowMaxTimeInvalid);
TEST_CASE(performanceValueFlowMaxIfCount);
TEST_CASE(performanceValueFlowMaxIfCountInvalid);
TEST_CASE(templateMaxTime);
TEST_CASE(templateMaxTimeInvalid);
TEST_CASE(templateMaxTimeInvalid2);
TEST_CASE(typedefMaxTime);
TEST_CASE(typedefMaxTimeInvalid);
TEST_CASE(typedefMaxTimeInvalid2);
TEST_CASE(templateMaxTime);
TEST_CASE(templateMaxTime);
TEST_CASE(project);
TEST_CASE(projectMultiple);
TEST_CASE(projectAndSource);
TEST_CASE(projectEmpty);
TEST_CASE(projectMissing);
TEST_CASE(projectNoPaths);
TEST_CASE(addon);
TEST_CASE(addonMissing);
#ifdef HAVE_RULES
TEST_CASE(rule);
TEST_CASE(ruleMissingPattern);
#else
TEST_CASE(ruleNotSupported);
#endif
#ifdef HAVE_RULES
TEST_CASE(ruleFileMulti);
TEST_CASE(ruleFileSingle);
TEST_CASE(ruleFileEmpty);
TEST_CASE(ruleFileMissing);
TEST_CASE(ruleFileInvalid);
TEST_CASE(ruleFileNoRoot);
TEST_CASE(ruleFileEmptyElements1);
TEST_CASE(ruleFileEmptyElements2);
TEST_CASE(ruleFileUnknownElement1);
TEST_CASE(ruleFileUnknownElement2);
TEST_CASE(ruleFileMissingTokenList);
TEST_CASE(ruleFileUnknownTokenList);
TEST_CASE(ruleFileMissingId);
TEST_CASE(ruleFileInvalidSeverity1);
TEST_CASE(ruleFileInvalidSeverity2);
#else
TEST_CASE(ruleFileNotSupported);
#endif
TEST_CASE(signedChar);
TEST_CASE(signedChar2);
TEST_CASE(unsignedChar);
TEST_CASE(unsignedChar2);
TEST_CASE(signedCharUnsignedChar);
TEST_CASE(library);
TEST_CASE(libraryMissing);
TEST_CASE(libraryMultiple);
TEST_CASE(libraryMultipleEmpty);
TEST_CASE(libraryMultipleEmpty2);
TEST_CASE(suppressXml);
TEST_CASE(suppressXmlEmpty);
TEST_CASE(suppressXmlMissing);
TEST_CASE(suppressXmlInvalid);
TEST_CASE(suppressXmlNoRoot);
TEST_CASE(executorDefault);
TEST_CASE(executorAuto);
TEST_CASE(executorAutoNoJobs);
#if defined(HAS_THREADING_MODEL_THREAD)
TEST_CASE(executorThread);
TEST_CASE(executorThreadNoJobs);
#else
TEST_CASE(executorThreadNotSupported);
#endif
#if defined(HAS_THREADING_MODEL_FORK)
TEST_CASE(executorProcess);
TEST_CASE(executorProcessNoJobs);
#else
TEST_CASE(executorProcessNotSupported);
#endif
TEST_CASE(checkLevelDefault);
TEST_CASE(checkLevelNormal);
TEST_CASE(checkLevelExhaustive);
TEST_CASE(checkLevelUnknown);
TEST_CASE(cppHeaderProbe);
TEST_CASE(cppHeaderProbe2);
TEST_CASE(noCppHeaderProbe);
TEST_CASE(noCppHeaderProbe2);
TEST_CASE(debugLookup);
TEST_CASE(debugLookupAll);
TEST_CASE(debugLookupAddon);
TEST_CASE(debugLookupConfig);
TEST_CASE(debugLookupLibrary);
TEST_CASE(debugLookupPlatform);
TEST_CASE(maxTemplateRecursion);
TEST_CASE(maxTemplateRecursionMissingCount);
TEST_CASE(ignorepaths1);
TEST_CASE(ignorepaths2);
TEST_CASE(ignorepaths3);
TEST_CASE(ignorepaths4);
TEST_CASE(ignorefilepaths1);
TEST_CASE(ignorefilepaths2);
TEST_CASE(ignorefilepaths3);
TEST_CASE(checkconfig);
TEST_CASE(unknownParam);
TEST_CASE(undefs_noarg);
TEST_CASE(undefs_noarg2);
TEST_CASE(undefs_noarg3);
TEST_CASE(undefs);
TEST_CASE(undefs2);
TEST_CASE(cppcheckBuildDirExistent);
TEST_CASE(cppcheckBuildDirNonExistent);
TEST_CASE(cppcheckBuildDirEmpty);
TEST_CASE(cppcheckBuildDirMultiple);
TEST_CASE(noCppcheckBuildDir);
TEST_CASE(noCppcheckBuildDir2);
TEST_CASE(invalidCppcheckCfg);
}
void nooptions() {
REDIRECT;
const char * const argv[] = {"cppcheck"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Exit, parser->parseFromArgs(1, argv));
ASSERT(startsWith(logger->str(), "Cppcheck - A tool for static C/C++ code analysis"));
}
void helpshort() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-h"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Exit, parser->parseFromArgs(2, argv));
ASSERT(startsWith(logger->str(), "Cppcheck - A tool for static C/C++ code analysis"));
}
void helpshortExclusive() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--library=missing", "-h"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Exit, parser->parseFromArgs(3, argv));
ASSERT(startsWith(logger->str(), "Cppcheck - A tool for static C/C++ code analysis"));
}
void helplong() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--help"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Exit, parser->parseFromArgs(2, argv));
ASSERT(startsWith(logger->str(), "Cppcheck - A tool for static C/C++ code analysis"));
}
void helplongExclusive() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--library=missing", "--help"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Exit, parser->parseFromArgs(3, argv));
ASSERT(startsWith(logger->str(), "Cppcheck - A tool for static C/C++ code analysis"));
}
void version() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--version"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Exit, parser->parseFromArgs(2, argv));
ASSERT(logger->str().compare(0, 11, "Cppcheck 2.") == 0);
}
void versionWithCfg() {
REDIRECT;
ScopedFile file(Path::join(Path::getPathFromFilename(Path::getCurrentExecutablePath("")), "cppcheck.cfg"),
"{\n"
"\"productName\": \"The Product\""
"}\n");
const char * const argv[] = {"cppcheck", "--version"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Exit, parser->parseFromArgs(2, argv));
// TODO: somehow the config is not loaded on some systems
(void)logger->str(); //ASSERT_EQUALS("The Product\n", logger->str()); // TODO: include version?
}
// TODO: test --version with extraVersion
void versionExclusive() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--library=missing", "--version"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Exit, parser->parseFromArgs(3, argv));
ASSERT(logger->str().compare(0, 11, "Cppcheck 2.") == 0);
}
void versionWithInvalidCfg() {
REDIRECT;
ScopedFile file(Path::join(Path::getPathFromFilename(Path::getCurrentExecutablePath("")), "cppcheck.cfg"),
"{\n");
const char * const argv[] = {"cppcheck", "--version"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(2, argv));
ASSERT_EQUALS("cppcheck: error: could not load cppcheck.cfg - not a valid JSON - syntax error at line 2 near: \n", logger->str());
}
void checkVersionCorrect() {
REDIRECT;
const std::string currentVersion = parser->getVersion();
const std::string checkVersion = "--check-version=" + currentVersion;
const char * const argv[] = {"cppcheck", checkVersion.c_str(), "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
}
void checkVersionIncorrect() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--check-version=Cppcheck 2.0", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: --check-version check failed. Aborting.\n", logger->str());
}
void onefile() {
REDIRECT;
const char * const argv[] = {"cppcheck", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(2, argv));
ASSERT_EQUALS(1, (int)parser->getPathNames().size());
ASSERT_EQUALS("file.cpp", parser->getPathNames().at(0));
}
void onepath() {
REDIRECT;
const char * const argv[] = {"cppcheck", "src"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(2, argv));
ASSERT_EQUALS(1, (int)parser->getPathNames().size());
ASSERT_EQUALS("src", parser->getPathNames().at(0));
}
void optionwithoutfile() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-v"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(2, argv));
ASSERT_EQUALS(0, (int)parser->getPathNames().size());
ASSERT_EQUALS("cppcheck: error: no C or C++ source files found.\n", logger->str());
}
void verboseshort() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-v", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(true, settings->verbose);
}
void verboselong() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--verbose", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(true, settings->verbose);
}
void debugSimplified() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--debug-simplified", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(true, settings->debugSimplified);
}
void debugwarnings() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--debug-warnings", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(true, settings->debugwarnings);
}
void forceshort() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-f", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(true, settings->force);
}
void forcelong() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--force", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(true, settings->force);
}
void relativePaths1() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-rp", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(true, settings->relativePaths);
}
void relativePaths2() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--relative-paths", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(true, settings->relativePaths);
}
void relativePaths3() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-rp=C:/foo;C:\\bar", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(true, settings->relativePaths);
ASSERT_EQUALS(2, settings->basePaths.size());
ASSERT_EQUALS("C:/foo", settings->basePaths[0]);
ASSERT_EQUALS("C:/bar", settings->basePaths[1]);
}
void relativePaths4() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--relative-paths=C:/foo;C:\\bar", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(true, settings->relativePaths);
ASSERT_EQUALS(2, settings->basePaths.size());
ASSERT_EQUALS("C:/foo", settings->basePaths[0]);
ASSERT_EQUALS("C:/bar", settings->basePaths[1]);
}
void quietshort() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-q", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(true, settings->quiet);
}
void quietlong() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--quiet", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(true, settings->quiet);
}
void defines_noarg() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-D"};
// Fails since -D has no param
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(2, argv));
ASSERT_EQUALS("cppcheck: error: argument to '-D' is missing.\n", logger->str());
}
void defines_noarg2() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-D", "-v", "file.cpp"};
// Fails since -D has no param
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(4, argv));
ASSERT_EQUALS("cppcheck: error: argument to '-D' is missing.\n", logger->str());
}
void defines_noarg3() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-D", "--quiet", "file.cpp"};
// Fails since -D has no param
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(4, argv));
ASSERT_EQUALS("cppcheck: error: argument to '-D' is missing.\n", logger->str());
}
void defines() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-D_WIN32", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("_WIN32=1", settings->userDefines);
}
void defines2() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-D_WIN32", "-DNODEBUG", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(4, argv));
ASSERT_EQUALS("_WIN32=1;NODEBUG=1", settings->userDefines);
}
void defines3() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-D", "DEBUG", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(4, argv));
ASSERT_EQUALS("DEBUG=1", settings->userDefines);
}
void defines4() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-DDEBUG=", "file.cpp"}; // #5137 - defining empty macro
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("DEBUG=", settings->userDefines);
}
void enforceLanguage1() {
REDIRECT;
const char * const argv[] = {"cppcheck", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(2, argv));
ASSERT_EQUALS(Standards::Language::None, settings->enforcedLang);
}
void enforceLanguage2() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-x", "c++", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(4, argv));
ASSERT_EQUALS(Standards::Language::CPP, settings->enforcedLang);
}
void enforceLanguage3() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-x"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(2, argv));
ASSERT_EQUALS("cppcheck: error: no language given to '-x' option.\n", logger->str());
}
void enforceLanguage4() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-x", "--inconclusive", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(4, argv));
ASSERT_EQUALS("cppcheck: error: no language given to '-x' option.\n", logger->str());
}
void enforceLanguage5() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--language=c++", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(Standards::Language::CPP, settings->enforcedLang);
}
void enforceLanguage6() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--language=c", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(Standards::Language::C, settings->enforcedLang);
}
void enforceLanguage7() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--language=unknownLanguage", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: unknown language 'unknownLanguage' enforced.\n", logger->str());
}
void includesnopath() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-I"};
// Fails since -I has no param
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(2, argv));
ASSERT_EQUALS("cppcheck: error: argument to '-I' is missing.\n", logger->str());
}
void includes() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-I", "include", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(4, argv));
ASSERT_EQUALS("include/", settings->includePaths.front());
}
void includesslash() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-I", "include/", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(4, argv));
ASSERT_EQUALS("include/", settings->includePaths.front());
}
void includesbackslash() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-I", "include\\", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(4, argv));
ASSERT_EQUALS("include/", settings->includePaths.front());
}
void includesnospace() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-Iinclude", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("include/", settings->includePaths.front());
}
void includes2() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-I", "include/", "-I", "framework/", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(6, argv));
ASSERT_EQUALS("include/", settings->includePaths.front());
settings->includePaths.pop_front();
ASSERT_EQUALS("framework/", settings->includePaths.front());
}
void includesFile() {
REDIRECT;
ScopedFile file("includes.txt",
"path/sub\n"
"path2/sub1\n");
const char * const argv[] = {"cppcheck", "--includes-file=includes.txt", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(2, settings->includePaths.size());
auto it = settings->includePaths.cbegin();
ASSERT_EQUALS("path/sub/", *it++);
ASSERT_EQUALS("path2/sub1/", *it);
}
void includesFileNoFile() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--includes-file=fileThatDoesNotExist.txt", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: unable to open includes file at 'fileThatDoesNotExist.txt'\n", logger->str());
}
void configExcludesFile() {
REDIRECT;
ScopedFile file("excludes.txt",
"path/sub\n"
"path2/sub1\n");
const char * const argv[] = {"cppcheck", "--config-excludes-file=excludes.txt", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(2, settings->configExcludePaths.size());
auto it = settings->configExcludePaths.cbegin();
ASSERT_EQUALS("path/sub/", *it++);
ASSERT_EQUALS("path2/sub1/", *it);
}
void configExcludesFileNoFile() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--config-excludes-file=fileThatDoesNotExist.txt", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: unable to open config excludes file at 'fileThatDoesNotExist.txt'\n", logger->str());
}
void enabledAll() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--enable=all", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT(settings->severity.isEnabled(Severity::error));
ASSERT(settings->severity.isEnabled(Severity::style));
ASSERT(settings->severity.isEnabled(Severity::warning));
ASSERT(settings->checks.isEnabled(Checks::unusedFunction));
ASSERT(settings->checks.isEnabled(Checks::missingInclude));
ASSERT(!settings->checks.isEnabled(Checks::internalCheck));
}
void enabledStyle() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--enable=style", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT(settings->severity.isEnabled(Severity::error));
ASSERT(settings->severity.isEnabled(Severity::style));
ASSERT(settings->severity.isEnabled(Severity::warning));
ASSERT(settings->severity.isEnabled(Severity::performance));
ASSERT(settings->severity.isEnabled(Severity::portability));
ASSERT(!settings->checks.isEnabled(Checks::unusedFunction));
ASSERT(!settings->checks.isEnabled(Checks::internalCheck));
}
void enabledPerformance() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--enable=performance", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT(settings->severity.isEnabled(Severity::error));
ASSERT(!settings->severity.isEnabled(Severity::style));
ASSERT(!settings->severity.isEnabled(Severity::warning));
ASSERT(settings->severity.isEnabled(Severity::performance));
ASSERT(!settings->severity.isEnabled(Severity::portability));
ASSERT(!settings->checks.isEnabled(Checks::unusedFunction));
ASSERT(!settings->checks.isEnabled(Checks::missingInclude));
}
void enabledPortability() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--enable=portability", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT(settings->severity.isEnabled(Severity::error));
ASSERT(!settings->severity.isEnabled(Severity::style));
ASSERT(!settings->severity.isEnabled(Severity::warning));
ASSERT(!settings->severity.isEnabled(Severity::performance));
ASSERT(settings->severity.isEnabled(Severity::portability));
ASSERT(!settings->checks.isEnabled(Checks::unusedFunction));
ASSERT(!settings->checks.isEnabled(Checks::missingInclude));
}
void enabledInformation() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--enable=information", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT(settings->severity.isEnabled(Severity::error));
ASSERT(settings->severity.isEnabled(Severity::information));
ASSERT(!settings->checks.isEnabled(Checks::missingInclude));
}
void enabledUnusedFunction() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--enable=unusedFunction", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT(settings->severity.isEnabled(Severity::error));
ASSERT(settings->checks.isEnabled(Checks::unusedFunction));
}
void enabledMissingInclude() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--enable=missingInclude", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT(settings->severity.isEnabled(Severity::error));
ASSERT(settings->checks.isEnabled(Checks::missingInclude));
}
void disabledMissingIncludeWithInformation() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--disable=missingInclude", "--enable=information", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(4, argv));
ASSERT(settings->severity.isEnabled(Severity::error));
ASSERT(settings->severity.isEnabled(Severity::information));
ASSERT(!settings->checks.isEnabled(Checks::missingInclude));
ASSERT_EQUALS("", logger->str());
}
void enabledMissingIncludeWithInformation() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--enable=information", "--enable=missingInclude", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(4, argv));
ASSERT(settings->severity.isEnabled(Severity::error));
ASSERT(settings->severity.isEnabled(Severity::information));
ASSERT(settings->checks.isEnabled(Checks::missingInclude));
ASSERT_EQUALS("", logger->str());
}
void enabledMissingIncludeWithInformationReverseOrder() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--enable=missingInclude", "--enable=information", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(4, argv));
ASSERT(settings->severity.isEnabled(Severity::error));
ASSERT(settings->severity.isEnabled(Severity::information));
ASSERT(settings->checks.isEnabled(Checks::missingInclude));
ASSERT_EQUALS("", logger->str());
}
#ifdef CHECK_INTERNAL
void enabledInternal() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--enable=internal", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT(settings->severity.isEnabled(Severity::error));
ASSERT(settings->checks.isEnabled(Checks::internalCheck));
}
#endif
void enabledMultiple() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--enable=missingInclude,portability,warning", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT(settings->severity.isEnabled(Severity::error));
ASSERT(!settings->severity.isEnabled(Severity::style));
ASSERT(settings->severity.isEnabled(Severity::warning));
ASSERT(!settings->severity.isEnabled(Severity::performance));
ASSERT(settings->severity.isEnabled(Severity::portability));
ASSERT(!settings->checks.isEnabled(Checks::unusedFunction));
ASSERT(settings->checks.isEnabled(Checks::missingInclude));
}
void enabledInvalid() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--enable=warning,missingIncludeSystem,style", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: --enable parameter with the unknown name 'missingIncludeSystem'\n", logger->str());
}
void enabledError() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--enable=error", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: --enable parameter with the unknown name 'error'\n", logger->str());
}
void enabledEmpty() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--enable=", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: --enable parameter is empty\n", logger->str());
}
void disableAll() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--enable=all", "--disable=all", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(4, argv));
ASSERT_EQUALS(true, settings->severity.isEnabled(Severity::error));
ASSERT_EQUALS(false, settings->severity.isEnabled(Severity::warning));
ASSERT_EQUALS(false, settings->severity.isEnabled(Severity::style));
ASSERT_EQUALS(false, settings->severity.isEnabled(Severity::performance));
ASSERT_EQUALS(false, settings->severity.isEnabled(Severity::portability));
ASSERT_EQUALS(false, settings->severity.isEnabled(Severity::debug));
ASSERT_EQUALS(false, settings->checks.isEnabled(Checks::unusedFunction));
ASSERT_EQUALS(false, settings->checks.isEnabled(Checks::missingInclude));
ASSERT_EQUALS(false, settings->checks.isEnabled(Checks::internalCheck));
}
void disableMultiple() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--enable=all", "--disable=style", "--disable=unusedFunction", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(5, argv));
ASSERT_EQUALS(true, settings->severity.isEnabled(Severity::error));
ASSERT_EQUALS(true, settings->severity.isEnabled(Severity::warning));
ASSERT_EQUALS(false, settings->severity.isEnabled(Severity::style));
ASSERT_EQUALS(true, settings->severity.isEnabled(Severity::performance));
ASSERT_EQUALS(true, settings->severity.isEnabled(Severity::portability));
ASSERT_EQUALS(true, settings->severity.isEnabled(Severity::debug));
ASSERT_EQUALS(false, settings->checks.isEnabled(Checks::unusedFunction));
ASSERT_EQUALS(true, settings->checks.isEnabled(Checks::missingInclude));
ASSERT_EQUALS(false, settings->checks.isEnabled(Checks::internalCheck));
}
// make sure the implied "style" checks are not added when "--enable=style" is specified
void disableStylePartial() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--enable=style", "--disable=performance", "--enable=unusedFunction", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(5, argv));
ASSERT_EQUALS(true, settings->severity.isEnabled(Severity::error));
ASSERT_EQUALS(true, settings->severity.isEnabled(Severity::warning));
ASSERT_EQUALS(true, settings->severity.isEnabled(Severity::style));
ASSERT_EQUALS(false, settings->severity.isEnabled(Severity::performance));
ASSERT_EQUALS(true, settings->severity.isEnabled(Severity::portability));
ASSERT_EQUALS(false, settings->severity.isEnabled(Severity::debug));
ASSERT_EQUALS(true, settings->checks.isEnabled(Checks::unusedFunction));
ASSERT_EQUALS(false, settings->checks.isEnabled(Checks::missingInclude));
ASSERT_EQUALS(false, settings->checks.isEnabled(Checks::internalCheck));
}
void disableInformationPartial() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--enable=information", "--disable=missingInclude", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(4, argv));
ASSERT(settings->severity.isEnabled(Severity::information));
ASSERT(!settings->checks.isEnabled(Checks::missingInclude));
ASSERT_EQUALS("", logger->str());
}
void disableInformationPartial2() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--enable=missingInclude", "--disable=information", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(4, argv));
ASSERT(!settings->severity.isEnabled(Severity::information));
ASSERT(settings->checks.isEnabled(Checks::missingInclude));
}
void disableInvalid() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--disable=leaks", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: --disable parameter with the unknown name 'leaks'\n", logger->str());
}
void disableError() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--disable=error", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: --disable parameter with the unknown name 'error'\n", logger->str());
}
void disableEmpty() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--disable=", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: --disable parameter is empty\n", logger->str());
}
void inconclusive() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--inconclusive", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(true, settings->certainty.isEnabled(Certainty::inconclusive));
}
void errorExitcode() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--error-exitcode=5", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(5, settings->exitCode);
}
void errorExitcodeMissing() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--error-exitcode=", "file.cpp"};
// Fails since exit code not given
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: argument to '--error-exitcode=' is not valid - not an integer.\n", logger->str());
}
void errorExitcodeStr() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--error-exitcode=foo", "file.cpp"};
// Fails since invalid exit code
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: argument to '--error-exitcode=' is not valid - not an integer.\n", logger->str());
}
void exitcodeSuppressionsOld() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--exitcode-suppressions", "suppr.txt", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(4, argv));
ASSERT_EQUALS("cppcheck: error: unrecognized command line option: \"--exitcode-suppressions\".\n", logger->str());
}
void exitcodeSuppressions() {
REDIRECT;
ScopedFile file("suppr.txt",
"uninitvar\n"
"unusedFunction\n");
const char * const argv[] = {"cppcheck", "--exitcode-suppressions=suppr.txt", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(2, settings->supprs.nofail.getSuppressions().size());
auto it = settings->supprs.nofail.getSuppressions().cbegin();
ASSERT_EQUALS("uninitvar", (it++)->errorId);
ASSERT_EQUALS("unusedFunction", it->errorId);
}
void exitcodeSuppressionsNoFile() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--exitcode-suppressions", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: unrecognized command line option: \"--exitcode-suppressions\".\n", logger->str());
}
void fileFilterStdin() {
REDIRECT;
RedirectInput input("file1.c\nfile2.cpp\n");
const char * const argv[] = {"cppcheck", "--file-filter=-"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(2, argv));
ASSERT_EQUALS("cppcheck: error: no C or C++ source files found.\n", logger->str());
ASSERT_EQUALS(2U, settings->fileFilters.size());
ASSERT_EQUALS("file1.c", settings->fileFilters[0]);
ASSERT_EQUALS("file2.cpp", settings->fileFilters[1]);
}
void fileList() {
REDIRECT;
ScopedFile file("files.txt",
"file1.c\n"
"file2.cpp\n");
const char * const argv[] = {"cppcheck", "--file-list=files.txt", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(3, parser->getPathNames().size());
auto it = parser->getPathNames().cbegin();
ASSERT_EQUALS("file1.c", *it++);
ASSERT_EQUALS("file2.cpp", *it++);
ASSERT_EQUALS("file.cpp", *it);
}
void fileListNoFile() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--file-list=files.txt", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: couldn't open the file: \"files.txt\".\n", logger->str());
}
void fileListStdin() {
REDIRECT;
RedirectInput input("file1.c\nfile2.cpp\n");
const char * const argv[] = {"cppcheck", "--file-list=-", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(3, parser->getPathNames().size());
auto it = parser->getPathNames().cbegin();
ASSERT_EQUALS("file1.c", *it++);
ASSERT_EQUALS("file2.cpp", *it++);
ASSERT_EQUALS("file.cpp", *it);
}
void fileListInvalid() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--file-list", "files.txt", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(4, argv));
ASSERT_EQUALS("cppcheck: error: unrecognized command line option: \"--file-list\".\n", logger->str());
}
void inlineSuppr() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--inline-suppr", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT(settings->inlineSuppressions);
}
void jobs() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-j", "3", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(4, argv));
ASSERT_EQUALS(3, settings->jobs);
}
void jobs2() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-j3", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(3, settings->jobs);
}
void jobsMissingCount() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-j", "file.cpp"};
// Fails since -j is missing thread count
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: argument to '-j' is not valid - not an integer.\n", logger->str());
}
void jobsInvalid() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-j", "e", "file.cpp"};
// Fails since invalid count given for -j
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(4, argv));
ASSERT_EQUALS("cppcheck: error: argument to '-j' is not valid - not an integer.\n", logger->str());
}
void jobsNoJobs() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-j0", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: argument for '-j' must be greater than 0.\n", logger->str());
}
void jobsTooBig() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-j1025", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: argument for '-j' is allowed to be 1024 at max.\n", logger->str());
}
void maxConfigs() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-f", "--max-configs=12", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(4, argv));
ASSERT_EQUALS(12, settings->maxConfigs);
ASSERT_EQUALS(false, settings->force);
}
void maxConfigsMissingCount() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--max-configs=", "file.cpp"};
// Fails since --max-configs= is missing limit
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: argument to '--max-configs=' is not valid - not an integer.\n", logger->str());
}
void maxConfigsInvalid() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--max-configs=e", "file.cpp"};
// Fails since invalid count given for --max-configs=
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: argument to '--max-configs=' is not valid - not an integer.\n", logger->str());
}
void maxConfigsTooSmall() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--max-configs=0", "file.cpp"};
// Fails since limit must be greater than 0
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: argument to '--max-configs=' must be greater than 0.\n", logger->str());
}
void outputFormatSarif() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--output-format=sarif", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS_ENUM(Settings::OutputFormat::sarif, settings->outputFormat);
}
void outputFormatXml() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--output-format=xml", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS_ENUM(Settings::OutputFormat::xml, settings->outputFormat);
}
void outputFormatOther() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--output-format=text", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: argument to '--output-format=' must be 'sarif' or 'xml'.\n", logger->str());
}
void outputFormatImplicitPlist() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--plist-output=.", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS_ENUM(Settings::OutputFormat::plist, settings->outputFormat);
}
void outputFormatImplicitXml() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--xml", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS_ENUM(Settings::OutputFormat::xml, settings->outputFormat);
}
void premiumOptions1() {
REDIRECT;
asPremium();
const char * const argv[] = {"cppcheck", "--premium=autosar", "file.c"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT(settings->severity.isEnabled(Severity::error));
ASSERT_EQUALS(true, settings->severity.isEnabled(Severity::warning));
}
void premiumOptions2() {
REDIRECT;
asPremium();
const char * const argv[] = {"cppcheck", "--premium=misra-c-2012", "file.c"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT(settings->severity.isEnabled(Severity::error));
ASSERT_EQUALS(true, settings->severity.isEnabled(Severity::warning));
}
void premiumOptions3() {
REDIRECT;
asPremium();
const char * const argv[] = {"cppcheck", "--premium=misra-c++-2023", "file.c"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT(settings->severity.isEnabled(Severity::error));
ASSERT_EQUALS(true, settings->severity.isEnabled(Severity::warning));
}
void premiumOptions4() {
REDIRECT;
asPremium();
const char * const argv[] = {"cppcheck", "--premium=cert-c++-2016", "file.c"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT(settings->severity.isEnabled(Severity::error));
ASSERT_EQUALS(true, settings->severity.isEnabled(Severity::warning));
}
void premiumOptions5() {
REDIRECT;
asPremium();
const char * const argv[] = {"cppcheck", "--premium=safety", "file.c"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT(settings->severity.isEnabled(Severity::error));
ASSERT_EQUALS(false, settings->severity.isEnabled(Severity::warning));
}
void premiumOptionsCertCIntPrecision() {
REDIRECT;
asPremium();
const char * const argv[] = {"cppcheck", "--premium-cert-c-int-precision=12", "file.c"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("--cert-c-int-precision=12", settings->premiumArgs);
}
void premiumOptionsLicenseFile() {
REDIRECT;
asPremium();
const char * const argv[] = {"cppcheck", "--premium-license-file=file.lic", "file.c"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("--license-file=file.lic", settings->premiumArgs);
}
void premiumOptionsInvalid1() {
REDIRECT;
asPremium();
const char * const argv[] = {"cppcheck", "--premium=misra", "file.c"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: invalid --premium option 'misra'.\n", logger->str());
}
void premiumOptionsInvalid2() {
REDIRECT;
asPremium();
const char * const argv[] = {"cppcheck", "--premium=cert", "file.c"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: invalid --premium option 'cert'.\n", logger->str());
}
void premiumSafety() {
REDIRECT;
asPremium();
const char * const argv[] = {"cppcheck", "--premium=safety", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(true, settings->safety);
}
void reportProgress1() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--report-progress", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(10, settings->reportProgress);
}
void reportProgress2() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--report-progress=", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: argument to '--report-progress=' is not valid - not an integer.\n", logger->str());
}
void reportProgress3() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--report-progress=-1", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: argument to '--report-progress=' needs to be a positive integer.\n", logger->str());
}
void reportProgress4() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--report-progress=0", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(0, settings->reportProgress);
}
void reportProgress5() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--report-progress=1", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(1, settings->reportProgress);
}
void stdc99() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--std=c99", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT(settings->standards.c == Standards::C99);
}
void stdgnu17() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--std=gnu17", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT(settings->standards.c == Standards::C17);
}
void stdiso9899_1999() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--std=iso9899:1999", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT(settings->standards.c == Standards::C99);
}
void stdcpp11() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--std=c++11", "file.cpp"};
settings->standards.cpp = Standards::CPP03;
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT(settings->standards.cpp == Standards::CPP11);
}
void stdgnupp23() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--std=gnu++23", "file.cpp"};
settings->standards.cpp = Standards::CPP03;
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT(settings->standards.cpp == Standards::CPP23);
}
void stdunknown1() {
REDIRECT;
const char *const argv[] = {"cppcheck", "--std=d++11", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: unknown --std value 'd++11'\n", logger->str());
}
void stdunknown2() {
REDIRECT;
const char *const argv[] = {"cppcheck", "--std=cplusplus11", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: unknown --std value 'cplusplus11'\n", logger->str());
}
void stdunknown3() {
REDIRECT;
const char *const argv[] = {"cppcheck", "--std=C++11", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: unknown --std value 'C++11'\n", logger->str());
}
void stdoverwrite1() {
REDIRECT;
const char *const argv[] = {"cppcheck", "--std=c++11", "--std=c++23", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(4, argv));
ASSERT_EQUALS_ENUM(Standards::CPP23, settings->standards.cpp);
ASSERT_EQUALS_ENUM(Standards::CLatest, settings->standards.c);
}
void stdoverwrite2() {
REDIRECT;
const char *const argv[] = {"cppcheck", "--std=c99", "--std=c11", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(4, argv));
ASSERT_EQUALS_ENUM(Standards::C11, settings->standards.c);
ASSERT_EQUALS_ENUM(Standards::CPPLatest, settings->standards.cpp);
}
void stdoverwrite3() {
REDIRECT;
const char *const argv[] = {"cppcheck", "--std=c99", "--std=c++11", "--std=c11", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(5, argv));
ASSERT_EQUALS_ENUM(Standards::C11, settings->standards.c);
ASSERT_EQUALS_ENUM(Standards::CPP11, settings->standards.cpp);
}
void stdoverwrite4() {
REDIRECT;
const char *const argv[] = {"cppcheck", "--std=c++11", "--std=c99", "--std=c++23", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(5, argv));
ASSERT_EQUALS_ENUM(Standards::CPP23, settings->standards.cpp);
ASSERT_EQUALS_ENUM(Standards::C99, settings->standards.c);
}
void stdmulti1() {
REDIRECT;
const char *const argv[] = {"cppcheck", "--std=c99", "--std=c++11", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(4, argv));
ASSERT_EQUALS_ENUM(Standards::C99, settings->standards.c);
ASSERT_EQUALS_ENUM(Standards::CPP11, settings->standards.cpp);
}
void stdmulti2() {
REDIRECT;
const char *const argv[] = {"cppcheck", "--std=c++20", "--std=c11", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(4, argv));
ASSERT_EQUALS_ENUM(Standards::C11, settings->standards.c);
ASSERT_EQUALS_ENUM(Standards::CPP20, settings->standards.cpp);
}
void platformWin64() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--platform=win64", "file.cpp"};
ASSERT(settings->platform.set(Platform::Type::Unspecified));
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(Platform::Type::Win64, settings->platform.type);
}
void platformWin32A() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--platform=win32A", "file.cpp"};
ASSERT(settings->platform.set(Platform::Type::Unspecified));
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(Platform::Type::Win32A, settings->platform.type);
}
void platformWin32W() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--platform=win32W", "file.cpp"};
ASSERT(settings->platform.set(Platform::Type::Unspecified));
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(Platform::Type::Win32W, settings->platform.type);
}
void platformUnix32() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--platform=unix32", "file.cpp"};
ASSERT(settings->platform.set(Platform::Type::Unspecified));
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(Platform::Type::Unix32, settings->platform.type);
}
void platformUnix32Unsigned() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--platform=unix32-unsigned", "file.cpp"};
ASSERT(settings->platform.set(Platform::Type::Unspecified));
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(Platform::Type::Unix32, settings->platform.type);
}
void platformUnix64() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--platform=unix64", "file.cpp"};
ASSERT(settings->platform.set(Platform::Type::Unspecified));
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(Platform::Type::Unix64, settings->platform.type);
}
void platformUnix64Unsigned() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--platform=unix64-unsigned", "file.cpp"};
ASSERT(settings->platform.set(Platform::Type::Unspecified));
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(Platform::Type::Unix64, settings->platform.type);
}
void platformNative() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--platform=native", "file.cpp"};
ASSERT(settings->platform.set(Platform::Type::Unspecified));
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(Platform::Type::Native, settings->platform.type);
}
void platformUnspecified() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--platform=unspecified", "file.cpp"};
ASSERT(settings->platform.set(Platform::Type::Native));
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(Platform::Type::Unspecified, settings->platform.type);
}
void platformPlatformFile() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--platform=avr8", "file.cpp"};
ASSERT(settings->platform.set(Platform::Type::Unspecified));
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(Platform::Type::File, settings->platform.type);
}
void platformUnknown() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--platform=win128", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: unrecognized platform: 'win128'.\n", logger->str());
}
void plistEmpty() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--plist-output=", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT(settings->plistOutput == "./");
}
void plistDoesNotExist() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--plist-output=./cppcheck_reports", "file.cpp"};
// Fails since folder pointed by --plist-output= does not exist
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: plist folder does not exist: 'cppcheck_reports'.\n", logger->str());
}
void suppressionsOld() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--suppressions", "suppr.txt", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(4, argv));
ASSERT_EQUALS("cppcheck: error: unrecognized command line option: \"--suppressions\".\n", logger->str());
}
void suppressions() {
REDIRECT;
ScopedFile file("suppr.txt",
"uninitvar\n"
"unusedFunction\n");
const char * const argv[] = {"cppcheck", "--suppressions-list=suppr.txt", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(2, settings->supprs.nomsg.getSuppressions().size());
auto it = settings->supprs.nomsg.getSuppressions().cbegin();
ASSERT_EQUALS("uninitvar", (it++)->errorId);
ASSERT_EQUALS("unusedFunction", it->errorId);
}
void suppressionsNoFile1() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--suppressions-list=", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(false, logger->str().find("If you want to pass two files") != std::string::npos);
}
void suppressionsNoFile2() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--suppressions-list=a.suppr,b.suppr", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(true, logger->str().find("If you want to pass two files") != std::string::npos);
}
void suppressionsNoFile3() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--suppressions-list=a.suppr b.suppr", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(true, logger->str().find("If you want to pass two files") != std::string::npos);
}
static SuppressionList::ErrorMessage errorMessage(const std::string &errorId, const std::string &fileName, int lineNumber) {
SuppressionList::ErrorMessage e;
e.errorId = errorId;
e.setFileName(fileName);
e.lineNumber = lineNumber;
return e;
}
void suppressionSingle() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--suppress=uninitvar", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(true, settings->supprs.nomsg.isSuppressed(errorMessage("uninitvar", "file.cpp", 1)));
}
void suppressionSingleFile() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--suppress=uninitvar:file.cpp", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(true, settings->supprs.nomsg.isSuppressed(errorMessage("uninitvar", "file.cpp", 1U)));
}
void suppressionTwo() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--suppress=uninitvar,noConstructor", "file.cpp"};
TODO_ASSERT_EQUALS(static_cast<int>(CmdLineParser::Result::Success), static_cast<int>(CmdLineParser::Result::Fail), static_cast<int>(parser->parseFromArgs(3, argv)));
TODO_ASSERT_EQUALS(true, false, settings->supprs.nomsg.isSuppressed(errorMessage("uninitvar", "file.cpp", 1U)));
TODO_ASSERT_EQUALS(true, false, settings->supprs.nomsg.isSuppressed(errorMessage("noConstructor", "file.cpp", 1U)));
TODO_ASSERT_EQUALS("", "cppcheck: error: Failed to add suppression. Invalid id \"uninitvar,noConstructor\"\n", logger->str());
}
void suppressionTwoSeparate() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--suppress=uninitvar", "--suppress=noConstructor", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(4, argv));
ASSERT_EQUALS(true, settings->supprs.nomsg.isSuppressed(errorMessage("uninitvar", "file.cpp", 1U)));
ASSERT_EQUALS(true, settings->supprs.nomsg.isSuppressed(errorMessage("noConstructor", "file.cpp", 1U)));
}
void templates() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--template={file}:{line},{severity},{id},{message}", "--template-location={file}:{line}:{column} {info}", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(4, argv));
ASSERT_EQUALS("{file}:{line},{severity},{id},{message}", settings->templateFormat);
ASSERT_EQUALS("{file}:{line}:{column} {info}", settings->templateLocation);
}
void templatesGcc() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--template=gcc", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("{file}:{line}:{column}: warning: {message} [{id}]\n{code}", settings->templateFormat);
ASSERT_EQUALS("{file}:{line}:{column}: note: {info}\n{code}", settings->templateLocation);
}
void templatesVs() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--template=vs", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("{file}({line}): {severity}: {message}", settings->templateFormat);
ASSERT_EQUALS("", settings->templateLocation);
}
void templatesEdit() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--template=edit", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("{file} +{line}: {severity}: {message}", settings->templateFormat);
ASSERT_EQUALS("", settings->templateLocation);
}
void templatesCppcheck1() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--template=cppcheck1", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("{callstack}: ({severity}{inconclusive:, inconclusive}) {message}", settings->templateFormat);
ASSERT_EQUALS("", settings->templateLocation);
}
void templatesDaca2() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--template=daca2", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("{file}:{line}:{column}: {severity}:{inconclusive:inconclusive:} {message} [{id}]", settings->templateFormat);
ASSERT_EQUALS("{file}:{line}:{column}: note: {info}", settings->templateLocation);
ASSERT_EQUALS(true, settings->daca);
}
void templatesSelfcheck() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--template=selfcheck", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("{file}:{line}:{column}: {severity}:{inconclusive:inconclusive:} {message} [{id}]\n{code}", settings->templateFormat);
ASSERT_EQUALS("{file}:{line}:{column}: note: {info}\n{code}", settings->templateLocation);
}
void templatesSimple() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--template=simple", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("{file}:{line}:{column}: {severity}:{inconclusive:inconclusive:} {message} [{id}]", settings->templateFormat);
ASSERT_EQUALS("", settings->templateLocation);
}
// TODO: we should bail out on this
void templatesNoPlaceholder() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--template=selfchek", "file.cpp"};
TODO_ASSERT_EQUALS(static_cast<int>(CmdLineParser::Result::Fail), static_cast<int>(CmdLineParser::Result::Success), static_cast<int>(parser->parseFromArgs(3, argv)));
ASSERT_EQUALS("selfchek", settings->templateFormat);
ASSERT_EQUALS("", settings->templateLocation);
}
void templateFormatInvalid() {
REDIRECT;
const char* const argv[] = { "cppcheck", "--template", "file.cpp" };
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: unrecognized command line option: \"--template\".\n", logger->str());
}
// will use the default
// TODO: bail out on empty?
void templateFormatEmpty() {
REDIRECT;
const char* const argv[] = { "cppcheck", "--template=", "file.cpp" };
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("{file}:{line}:{column}: {inconclusive:}{severity}:{inconclusive: inconclusive:} {message} [{id}]\n{code}", settings->templateFormat);
ASSERT_EQUALS("{file}:{line}:{column}: note: {info}\n{code}", settings->templateLocation);
}
void templateLocationInvalid() {
REDIRECT;
const char* const argv[] = { "cppcheck", "--template-location", "--template={file}", "file.cpp" };
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(4, argv));
ASSERT_EQUALS("cppcheck: error: unrecognized command line option: \"--template-location\".\n", logger->str());
}
// will use the default
// TODO: bail out on empty?
void templateLocationEmpty() {
REDIRECT;
const char* const argv[] = { "cppcheck", "--template-location=", "file.cpp" };
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("{file}:{line}:{column}: {inconclusive:}{severity}:{inconclusive: inconclusive:} {message} [{id}]\n{code}", settings->templateFormat);
ASSERT_EQUALS("{file}:{line}:{column}: note: {info}\n{code}", settings->templateLocation);
}
void xml() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--xml", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT(settings->xml);
ASSERT_EQUALS(2, settings->xml_version);
}
void xmlver2() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--xml-version=2", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT(settings->xml);
ASSERT_EQUALS(2, settings->xml_version);
}
void xmlver2both() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--xml", "--xml-version=2", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(4, argv));
ASSERT(settings->xml);
ASSERT_EQUALS(2, settings->xml_version);
}
void xmlver2both2() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--xml-version=2", "--xml", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(4, argv));
ASSERT(settings->xml);
ASSERT_EQUALS(2, settings->xml_version);
}
void xmlverunknown() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--xml", "--xml-version=4", "file.cpp"};
// FAils since unknown XML format version
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(4, argv));
ASSERT_EQUALS("cppcheck: error: '--xml-version' can only be 2 or 3.\n", logger->str());
}
void xmlverinvalid() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--xml", "--xml-version=a", "file.cpp"};
// FAils since unknown XML format version
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(4, argv));
ASSERT_EQUALS("cppcheck: error: argument to '--xml-version=' is not valid - not an integer.\n", logger->str());
}
void doc() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--doc"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Exit, parser->parseFromArgs(2, argv));
ASSERT(startsWith(logger->str(), "## "));
}
void docExclusive() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--library=missing", "--doc"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Exit, parser->parseFromArgs(3, argv));
ASSERT(startsWith(logger->str(), "## "));
}
void showtimeSummary() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--showtime=summary", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT(settings->showtime == SHOWTIME_MODES::SHOWTIME_SUMMARY);
}
void showtimeFile() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--showtime=file", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT(settings->showtime == SHOWTIME_MODES::SHOWTIME_FILE);
}
void showtimeFileTotal() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--showtime=file-total", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT(settings->showtime == SHOWTIME_MODES::SHOWTIME_FILE_TOTAL);
}
void showtimeTop5() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--showtime=top5", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT(settings->showtime == SHOWTIME_MODES::SHOWTIME_TOP5_FILE);
ASSERT_EQUALS("cppcheck: --showtime=top5 is deprecated and will be removed in Cppcheck 2.14. Please use --showtime=top5_file or --showtime=top5_summary instead.\n", logger->str());
}
void showtimeTop5File() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--showtime=top5_file", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT(settings->showtime == SHOWTIME_MODES::SHOWTIME_TOP5_FILE);
}
void showtimeTop5Summary() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--showtime=top5_summary", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT(settings->showtime == SHOWTIME_MODES::SHOWTIME_TOP5_SUMMARY);
}
void showtimeNone() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--showtime=none", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT(settings->showtime == SHOWTIME_MODES::SHOWTIME_NONE);
}
void showtimeEmpty() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--showtime=", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: no mode provided for --showtime\n", logger->str());
}
void showtimeInvalid() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--showtime=top10", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: unrecognized --showtime mode: 'top10'. Supported modes: file, file-total, summary, top5, top5_file, top5_summary.\n", logger->str());
}
void errorlist() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--errorlist"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Exit, parser->parseFromArgs(2, argv));
ASSERT_EQUALS("", logger->str()); // empty since it is logged via ErrorLogger
const std::string errout_s = GET_REDIRECT_OUTPUT;
ASSERT(startsWith(errout_s, ErrorMessage::getXMLHeader("")));
ASSERT(endsWith(errout_s, "</results>\n"));
}
void errorlistWithCfg() {
REDIRECT;
ScopedFile file(Path::join(Path::getPathFromFilename(Path::getCurrentExecutablePath("")), "cppcheck.cfg"),
R"({"productName": "The Product"}\n)");
const char * const argv[] = {"cppcheck", "--errorlist"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Exit, parser->parseFromArgs(2, argv));
ASSERT_EQUALS("", logger->str()); // empty since it is logged via ErrorLogger
ASSERT(startsWith(GET_REDIRECT_OUTPUT, ErrorMessage::getXMLHeader("The Product")));
}
void errorlistExclusive() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--library=missing", "--errorlist"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Exit, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("", logger->str()); // empty since it is logged via ErrorLogger
const std::string errout_s = GET_REDIRECT_OUTPUT;
ASSERT(startsWith(errout_s, ErrorMessage::getXMLHeader("")));
ASSERT(endsWith(errout_s, "</results>\n"));
}
void errorlistWithInvalidCfg() {
REDIRECT;
ScopedFile file(Path::join(Path::getPathFromFilename(Path::getCurrentExecutablePath("")), "cppcheck.cfg"),
"{\n");
const char * const argv[] = {"cppcheck", "--errorlist"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(2, argv));
ASSERT_EQUALS("cppcheck: error: could not load cppcheck.cfg - not a valid JSON - syntax error at line 2 near: \n", logger->str());
}
void ignorepathsnopath() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-i"};
// Fails since no ignored path given
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(2, argv));
ASSERT_EQUALS("cppcheck: error: argument to '-i' is missing.\n", logger->str());
}
#if defined(USE_WINDOWS_SEH) || defined(USE_UNIX_SIGNAL_HANDLING)
void exceptionhandling() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--exception-handling", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT(settings->exceptionHandling);
ASSERT_EQUALS(stdout, settings->exceptionOutput);
}
void exceptionhandling2() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--exception-handling=stderr", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT(settings->exceptionHandling);
ASSERT_EQUALS(stderr, settings->exceptionOutput);
}
void exceptionhandling3() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--exception-handling=stdout", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT(settings->exceptionHandling);
ASSERT_EQUALS(stdout, settings->exceptionOutput);
}
void exceptionhandlingInvalid() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--exception-handling=exfile"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(2, argv));
ASSERT_EQUALS("cppcheck: error: invalid '--exception-handling' argument\n", logger->str());
}
void exceptionhandlingInvalid2() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--exception-handling-foo"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(2, argv));
ASSERT_EQUALS("cppcheck: error: unrecognized command line option: \"--exception-handling-foo\".\n", logger->str());
}
#else
void exceptionhandlingNotSupported() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--exception-handling", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: Option --exception-handling is not supported since Cppcheck has not been built with any exception handling enabled.\n", logger->str());
}
void exceptionhandlingNotSupported2() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--exception-handling=stderr", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: Option --exception-handling is not supported since Cppcheck has not been built with any exception handling enabled.\n", logger->str());
}
#endif
void clang() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--clang", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT(settings->clang);
ASSERT_EQUALS("clang", settings->clangExecutable);
}
void clang2() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--clang=clang-14", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT(settings->clang);
ASSERT_EQUALS("clang-14", settings->clangExecutable);
}
void clangInvalid() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--clang-foo"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(2, argv));
ASSERT_EQUALS("cppcheck: error: unrecognized command line option: \"--clang-foo\".\n", logger->str());
}
void valueFlowMaxIterations() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--valueflow-max-iterations=0", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(0, settings->vfOptions.maxIterations);
}
void valueFlowMaxIterations2() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--valueflow-max-iterations=11", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(11, settings->vfOptions.maxIterations);
}
void valueFlowMaxIterationsInvalid() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--valueflow-max-iterations"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(2, argv));
ASSERT_EQUALS("cppcheck: error: unrecognized command line option: \"--valueflow-max-iterations\".\n", logger->str());
}
void valueFlowMaxIterationsInvalid2() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--valueflow-max-iterations=seven"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(2, argv));
ASSERT_EQUALS("cppcheck: error: argument to '--valueflow-max-iterations=' is not valid - not an integer.\n", logger->str());
}
void valueFlowMaxIterationsInvalid3() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--valueflow-max-iterations=-1"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(2, argv));
ASSERT_EQUALS("cppcheck: error: argument to '--valueflow-max-iterations=' is not valid - needs to be positive.\n", logger->str());
}
void checksMaxTime() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--checks-max-time=12", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(12, settings->checksMaxTime);
}
void checksMaxTime2() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--checks-max-time=-1", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: argument to '--checks-max-time=' needs to be a positive integer.\n", logger->str());
}
void checksMaxTimeInvalid() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--checks-max-time=one", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: argument to '--checks-max-time=' is not valid - not an integer.\n", logger->str());
}
#ifdef HAS_THREADING_MODEL_FORK
void loadAverage() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-l", "12", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(4, argv));
ASSERT_EQUALS(12, settings->loadAverage);
}
void loadAverage2() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-l12", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(12, settings->loadAverage);
}
void loadAverageInvalid() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-l", "one", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(4, argv));
ASSERT_EQUALS("cppcheck: error: argument to '-l' is not valid - not an integer.\n", logger->str());
}
#else
void loadAverageNotSupported() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-l", "12", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(4, argv));
ASSERT_EQUALS("cppcheck: error: Option -l cannot be used as Cppcheck has not been built with fork threading model.\n", logger->str());
}
#endif
void maxCtuDepth() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--max-ctu-depth=5", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(5, settings->maxCtuDepth);
}
void maxCtuDepth2() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--max-ctu-depth=10", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(10, settings->maxCtuDepth);
}
void maxCtuDepthLimit() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--max-ctu-depth=12", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(10, settings->maxCtuDepth);
ASSERT_EQUALS("cppcheck: --max-ctu-depth is being capped at 10. This limitation will be removed in a future Cppcheck version.\n", logger->str());
}
void maxCtuDepthInvalid() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--max-ctu-depth=one", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: argument to '--max-ctu-depth=' is not valid - not an integer.\n", logger->str());
}
void performanceValueflowMaxTime() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--performance-valueflow-max-time=12", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(12, settings->vfOptions.maxTime);
}
void performanceValueflowMaxTimeInvalid() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--performance-valueflow-max-time=one", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: argument to '--performance-valueflow-max-time=' is not valid - not an integer.\n", logger->str());
}
void performanceValueFlowMaxIfCount() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--performance-valueflow-max-if-count=12", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(12, settings->vfOptions.maxIfCount);
}
void performanceValueFlowMaxIfCountInvalid() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--performance-valueflow-max-if-count=one", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: argument to '--performance-valueflow-max-if-count=' is not valid - not an integer.\n", logger->str());
}
void templateMaxTime() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--template-max-time=12", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(12, settings->templateMaxTime);
}
void templateMaxTimeInvalid() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--template-max-time=one", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: argument to '--template-max-time=' is not valid - not an integer.\n", logger->str());
}
void templateMaxTimeInvalid2() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--template-max-time=-1", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: argument to '--template-max-time=' is not valid - needs to be positive.\n", logger->str());
}
void typedefMaxTime() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--typedef-max-time=12", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(12, settings->typedefMaxTime);
}
void typedefMaxTimeInvalid() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--typedef-max-time=one", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: argument to '--typedef-max-time=' is not valid - not an integer.\n", logger->str());
}
void typedefMaxTimeInvalid2() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--typedef-max-time=-1", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: argument to '--typedef-max-time=' is not valid - needs to be positive.\n", logger->str());
}
void project() {
REDIRECT;
ScopedFile file("project.cppcheck",
"<project>\n"
"<paths>\n"
"<dir name=\"dir\"/>\n"
"</paths>\n"
"</project>");
const char * const argv[] = {"cppcheck", "--project=project.cppcheck"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(2, argv));
ASSERT_EQUALS(1, parser->getPathNames().size());
auto it = parser->getPathNames().cbegin();
ASSERT_EQUALS("dir", *it);
}
void projectMultiple() {
REDIRECT;
ScopedFile file("project.cppcheck", "<project></project>");
const char * const argv[] = {"cppcheck", "--project=project.cppcheck", "--project=project.cppcheck", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(4, argv));
ASSERT_EQUALS("cppcheck: error: multiple --project options are not supported.\n", logger->str());
}
void projectAndSource() {
REDIRECT;
ScopedFile file("project.cppcheck", "<project></project>");
const char * const argv[] = {"cppcheck", "--project=project.cppcheck", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: --project cannot be used in conjunction with source files.\n", logger->str());
}
void projectEmpty() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--project=", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: failed to open project ''. The file does not exist.\n", logger->str());
}
void projectMissing() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--project=project.cppcheck", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: failed to open project 'project.cppcheck'. The file does not exist.\n", logger->str());
}
void projectNoPaths() {
ScopedFile file("project.cppcheck", "<project></project>");
const char * const argv[] = {"cppcheck", "--project=project.cppcheck"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(2, argv));
ASSERT_EQUALS("cppcheck: error: no C or C++ source files found.\n", logger->str());
}
void addon() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--addon=misra", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(1, settings->addons.size());
ASSERT_EQUALS("misra", *settings->addons.cbegin());
}
void addonMissing() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--addon=misra2", "file.cpp"};
ASSERT(!parser->fillSettingsFromArgs(3, argv));
ASSERT_EQUALS(1, settings->addons.size());
ASSERT_EQUALS("misra2", *settings->addons.cbegin());
ASSERT_EQUALS("Did not find addon misra2.py\n", logger->str());
}
void signedChar() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--fsigned-char", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS('s', settings->platform.defaultSign);
}
void signedChar2() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--platform=avr8", "--fsigned-char", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(4, argv));
ASSERT_EQUALS('s', settings->platform.defaultSign);
}
void unsignedChar() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--funsigned-char", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS('u', settings->platform.defaultSign);
}
void unsignedChar2() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--platform=mips32", "--funsigned-char", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(4, argv));
ASSERT_EQUALS('u', settings->platform.defaultSign);
}
void signedCharUnsignedChar() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--fsigned-char", "--funsigned-char", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(4, argv));
ASSERT_EQUALS('u', settings->platform.defaultSign);
}
#ifdef HAVE_RULES
void rule() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--rule=.+", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(1, settings->rules.size());
auto it = settings->rules.cbegin();
ASSERT_EQUALS(".+", it->pattern);
}
void ruleMissingPattern() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--rule=", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: no rule pattern provided.\n", logger->str());
}
#else
void ruleNotSupported() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--rule=.+", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: Option --rule cannot be used as Cppcheck has not been built with rules support.\n", logger->str());
}
#endif
#ifdef HAVE_RULES
void ruleFileMulti() {
REDIRECT;
ScopedFile file("rule.xml",
"<rules>\n"
"<rule>\n"
"<tokenlist>raw</tokenlist>\n"
"<pattern>.+</pattern>\n"
"<message>\n"
"<severity>error</severity>\n"
"<id>ruleId1</id>\n"
"<summary>ruleSummary1</summary>\n"
"</message>\n"
"</rule>\n"
"<rule>\n"
"<tokenlist>define</tokenlist>\n"
"<pattern>.*</pattern>\n"
"<message>\n"
"<severity>warning</severity>\n"
"<id>ruleId2</id>\n"
"<summary>ruleSummary2</summary>\n"
"</message>\n"
"</rule>\n"
"</rules>");
const char * const argv[] = {"cppcheck", "--rule-file=rule.xml", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(2, settings->rules.size());
auto it = settings->rules.cbegin();
ASSERT_EQUALS("raw", it->tokenlist);
ASSERT_EQUALS(".+", it->pattern);
ASSERT_EQUALS_ENUM(Severity::error, it->severity);
ASSERT_EQUALS("ruleId1", it->id);
ASSERT_EQUALS("ruleSummary1", it->summary);
++it;
ASSERT_EQUALS("define", it->tokenlist);
ASSERT_EQUALS(".*", it->pattern);
ASSERT_EQUALS_ENUM(Severity::warning, it->severity);
ASSERT_EQUALS("ruleId2", it->id);
ASSERT_EQUALS("ruleSummary2", it->summary);
}
void ruleFileSingle() {
REDIRECT;
ScopedFile file("rule.xml",
"<rule>\n"
"<tokenlist>define</tokenlist>\n"
"<pattern>.+</pattern>\n"
"<message>\n"
"<severity>error</severity>\n"
"<id>ruleId</id>\n"
"<summary>ruleSummary</summary>\n"
"</message>\n"
"</rule>\n");
const char * const argv[] = {"cppcheck", "--rule-file=rule.xml", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(1, settings->rules.size());
auto it = settings->rules.cbegin();
ASSERT_EQUALS("define", it->tokenlist);
ASSERT_EQUALS(".+", it->pattern);
ASSERT_EQUALS_ENUM(Severity::error, it->severity);
ASSERT_EQUALS("ruleId", it->id);
ASSERT_EQUALS("ruleSummary", it->summary);
}
void ruleFileEmpty() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--rule-file=", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: unable to load rule-file '' (XML_ERROR_FILE_NOT_FOUND).\n", logger->str());
}
void ruleFileMissing() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--rule-file=rule.xml", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: unable to load rule-file 'rule.xml' (XML_ERROR_FILE_NOT_FOUND).\n", logger->str());
}
void ruleFileInvalid() {
REDIRECT;
ScopedFile file("rule.xml", "");
const char * const argv[] = {"cppcheck", "--rule-file=rule.xml", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: unable to load rule-file 'rule.xml' (XML_ERROR_EMPTY_DOCUMENT).\n", logger->str());
}
void ruleFileNoRoot() {
REDIRECT;
ScopedFile file("rule.xml", "<?xml version=\"1.0\"?>");
const char * const argv[] = {"cppcheck", "--rule-file=rule.xml", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(0, settings->rules.size());
}
void ruleFileEmptyElements1() {
REDIRECT;
ScopedFile file("rule.xml",
"<rule>"
"<tokenlist/>"
"<pattern/>"
"<message/>"
"</rule>"
);
const char * const argv[] = {"cppcheck", "--rule-file=rule.xml", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv)); // do not crash
ASSERT_EQUALS("cppcheck: error: unable to load rule-file 'rule.xml' - a rule is lacking a pattern.\n", logger->str());
}
void ruleFileEmptyElements2() {
REDIRECT;
ScopedFile file("rule.xml",
"<rule>"
"<message>"
"<severity/>"
"<id/>"
"<summary/>"
"</message>"
"</rule>"
);
const char * const argv[] = {"cppcheck", "--rule-file=rule.xml", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv)); // do not crash
ASSERT_EQUALS("cppcheck: error: unable to load rule-file 'rule.xml' - a rule is lacking a pattern.\n", logger->str());
}
void ruleFileUnknownElement1() {
REDIRECT;
ScopedFile file("rule.xml",
"<rule>"
"<messages/>"
"</rule>"
);
const char * const argv[] = {"cppcheck", "--rule-file=rule.xml", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: unable to load rule-file 'rule.xml' - unknown element 'messages' encountered in 'rule'.\n", logger->str());
}
void ruleFileUnknownElement2() {
REDIRECT;
ScopedFile file("rule.xml",
"<rule>"
"<message>"
"<pattern/>"
"</message>"
"</rule>"
);
const char * const argv[] = {"cppcheck", "--rule-file=rule.xml", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: unable to load rule-file 'rule.xml' - unknown element 'pattern' encountered in 'message'.\n", logger->str());
}
void ruleFileMissingTokenList() {
REDIRECT;
ScopedFile file("rule.xml",
"<rule>\n"
"<tokenlist/>\n"
"<pattern>.+</pattern>\n"
"</rule>\n");
const char * const argv[] = {"cppcheck", "--rule-file=rule.xml", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: unable to load rule-file 'rule.xml' - a rule is lacking a tokenlist.\n", logger->str());
}
void ruleFileUnknownTokenList() {
REDIRECT;
ScopedFile file("rule.xml",
"<rule>\n"
"<tokenlist>simple</tokenlist>\n"
"<pattern>.+</pattern>\n"
"</rule>\n");
const char * const argv[] = {"cppcheck", "--rule-file=rule.xml", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: unable to load rule-file 'rule.xml' - a rule is using the unsupported tokenlist 'simple'.\n", logger->str());
}
void ruleFileMissingId() {
REDIRECT;
ScopedFile file("rule.xml",
"<rule>\n"
"<pattern>.+</pattern>\n"
"<message>\n"
"<id/>"
"</message>\n"
"</rule>\n");
const char * const argv[] = {"cppcheck", "--rule-file=rule.xml", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: unable to load rule-file 'rule.xml' - a rule is lacking an id.\n", logger->str());
}
void ruleFileInvalidSeverity1() {
REDIRECT;
ScopedFile file("rule.xml",
"<rule>\n"
"<pattern>.+</pattern>\n"
"<message>\n"
"<severity/>"
"</message>\n"
"</rule>\n");
const char * const argv[] = {"cppcheck", "--rule-file=rule.xml", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: unable to load rule-file 'rule.xml' - a rule has an invalid severity.\n", logger->str());
}
void ruleFileInvalidSeverity2() {
REDIRECT;
ScopedFile file("rule.xml",
"<rule>\n"
"<pattern>.+</pattern>\n"
"<message>\n"
"<severity>none</severity>"
"</message>\n"
"</rule>\n");
const char * const argv[] = {"cppcheck", "--rule-file=rule.xml", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: unable to load rule-file 'rule.xml' - a rule has an invalid severity.\n", logger->str());
}
#else
void ruleFileNotSupported() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--rule-file=rule.xml", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: Option --rule-file cannot be used as Cppcheck has not been built with rules support.\n", logger->str());
}
#endif
void library() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--library=posix", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(1, settings->libraries.size());
ASSERT_EQUALS("posix", *settings->libraries.cbegin());
}
void libraryMissing() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--library=posix2", "file.cpp"};
ASSERT_EQUALS(false, parser->fillSettingsFromArgs(3, argv));
ASSERT_EQUALS(1, settings->libraries.size());
ASSERT_EQUALS("posix2", *settings->libraries.cbegin());
ASSERT_EQUALS("cppcheck: Failed to load library configuration file 'posix2'. File not found\n", logger->str());
}
void libraryMultiple() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--library=posix,gnu", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(2, settings->libraries.size());
auto it = settings->libraries.cbegin();
ASSERT_EQUALS("posix", *it++);
ASSERT_EQUALS("gnu", *it);
}
void libraryMultipleEmpty() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--library=posix,,gnu", "file.cpp"};
ASSERT_EQUALS(false, parser->fillSettingsFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: empty library specified.\n", logger->str());
}
void libraryMultipleEmpty2() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--library=posix,gnu,", "file.cpp"};
ASSERT_EQUALS(false, parser->fillSettingsFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: empty library specified.\n", logger->str());
}
void suppressXml() {
REDIRECT;
ScopedFile file("suppress.xml",
"<suppressions>\n"
"<suppress>\n"
"<id>uninitvar</id>\n"
"</suppress>\n"
"</suppressions>");
const char * const argv[] = {"cppcheck", "--suppress-xml=suppress.xml", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
const auto& supprs = settings->supprs.nomsg.getSuppressions();
ASSERT_EQUALS(1, supprs.size());
const auto it = supprs.cbegin();
ASSERT_EQUALS("uninitvar", it->errorId);
}
void suppressXmlEmpty() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--suppress-xml=", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: failed to load suppressions XML '' (XML_ERROR_FILE_NOT_FOUND).\n", logger->str());
}
void suppressXmlMissing() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--suppress-xml=suppress.xml", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: failed to load suppressions XML 'suppress.xml' (XML_ERROR_FILE_NOT_FOUND).\n", logger->str());
}
void suppressXmlInvalid() {
REDIRECT;
ScopedFile file("suppress.xml", "");
const char * const argv[] = {"cppcheck", "--suppress-xml=suppress.xml", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: failed to load suppressions XML 'suppress.xml' (XML_ERROR_EMPTY_DOCUMENT).\n", logger->str());
}
void suppressXmlNoRoot() {
REDIRECT;
ScopedFile file("suppress.xml", "<?xml version=\"1.0\"?>");
const char * const argv[] = {"cppcheck", "--suppress-xml=suppress.xml", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: failed to load suppressions XML 'suppress.xml' (no root node found).\n", logger->str());
}
void executorDefault() {
REDIRECT;
const char * const argv[] = {"cppcheck", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(2, argv));
#if defined(HAS_THREADING_MODEL_FORK)
ASSERT_EQUALS_ENUM(Settings::ExecutorType::Process, settings->executor);
#elif defined(HAS_THREADING_MODEL_THREAD)
ASSERT_EQUALS_ENUM(Settings::ExecutorType::Thread, settings->executor);
#endif
}
void executorAuto() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-j2", "--executor=auto", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(4, argv));
#if defined(HAS_THREADING_MODEL_FORK)
ASSERT_EQUALS_ENUM(Settings::ExecutorType::Process, settings->executor);
#elif defined(HAS_THREADING_MODEL_THREAD)
ASSERT_EQUALS_ENUM(Settings::ExecutorType::Thread, settings->executor);
#endif
}
void executorAutoNoJobs() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--executor=auto", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
#if defined(HAS_THREADING_MODEL_FORK)
ASSERT_EQUALS_ENUM(Settings::ExecutorType::Process, settings->executor);
#elif defined(HAS_THREADING_MODEL_THREAD)
ASSERT_EQUALS_ENUM(Settings::ExecutorType::Thread, settings->executor);
#endif
}
#if defined(HAS_THREADING_MODEL_THREAD)
void executorThread() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-j2", "--executor=thread", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(4, argv));
ASSERT_EQUALS_ENUM(Settings::ExecutorType::Thread, settings->executor);
}
void executorThreadNoJobs() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--executor=thread", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS_ENUM(Settings::ExecutorType::Thread, settings->executor);
ASSERT_EQUALS("cppcheck: '--executor' has no effect as only a single job will be used.\n", logger->str());
}
#else
void executorThreadNotSupported() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-j2", "--executor=thread", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(4, argv));
ASSERT_EQUALS("cppcheck: error: executor type 'thread' cannot be used as Cppcheck has not been built with a respective threading model.\n", logger->str());
}
#endif
#if defined(HAS_THREADING_MODEL_FORK)
void executorProcess() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-j2", "--executor=process", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(4, argv));
ASSERT_EQUALS_ENUM(Settings::ExecutorType::Process, settings->executor);
}
void executorProcessNoJobs() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--executor=process", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS_ENUM(Settings::ExecutorType::Process, settings->executor);
ASSERT_EQUALS("cppcheck: '--executor' has no effect as only a single job will be used.\n", logger->str());
}
#else
void executorProcessNotSupported() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-j2", "--executor=process", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(4, argv));
ASSERT_EQUALS("cppcheck: error: executor type 'process' cannot be used as Cppcheck has not been built with a respective threading model.\n", logger->str());
}
#endif
// the CLI default to --check-level=normal
void checkLevelDefault() {
REDIRECT;
const char * const argv[] = {"cppcheck", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(2, argv));
ASSERT_EQUALS_ENUM(Settings::CheckLevel::normal, settings->checkLevel);
ASSERT_EQUALS(100, settings->vfOptions.maxIfCount);
ASSERT_EQUALS(8, settings->vfOptions.maxSubFunctionArgs);
ASSERT_EQUALS(false, settings->vfOptions.doConditionExpressionAnalysis);
ASSERT_EQUALS(4, settings->vfOptions.maxForwardBranches);
}
void checkLevelNormal() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--check-level=normal", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS_ENUM(Settings::CheckLevel::normal, settings->checkLevel);
ASSERT_EQUALS(100, settings->vfOptions.maxIfCount);
ASSERT_EQUALS(8, settings->vfOptions.maxSubFunctionArgs);
ASSERT_EQUALS(false, settings->vfOptions.doConditionExpressionAnalysis);
ASSERT_EQUALS(4, settings->vfOptions.maxForwardBranches);
}
void checkLevelExhaustive() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--check-level=exhaustive", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS_ENUM(Settings::CheckLevel::exhaustive, settings->checkLevel);
ASSERT_EQUALS(-1, settings->vfOptions.maxIfCount);
ASSERT_EQUALS(256, settings->vfOptions.maxSubFunctionArgs);
ASSERT_EQUALS(true, settings->vfOptions.doConditionExpressionAnalysis);
ASSERT_EQUALS(-1, settings->vfOptions.maxForwardBranches);
}
void checkLevelUnknown() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--check-level=default", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: unknown '--check-level' value 'default'.\n", logger->str());
}
void cppHeaderProbe() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--cpp-header-probe", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(true, settings->cppHeaderProbe);
}
void cppHeaderProbe2() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--no-cpp-header-probe", "--cpp-header-probe", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(4, argv));
ASSERT_EQUALS(true, settings->cppHeaderProbe);
}
void noCppHeaderProbe() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--no-cpp-header-probe", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(false, settings->cppHeaderProbe);
}
void noCppHeaderProbe2() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--cpp-header-probe", "--no-cpp-header-probe", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(4, argv));
ASSERT_EQUALS(false, settings->cppHeaderProbe);
}
void debugLookup() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--debug-lookup", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(true, settings->debuglookup);
GET_REDIRECT_OUTPUT; // ignore config lookup output
}
void debugLookupAll() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--debug-lookup=all", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(true, settings->debuglookup);
GET_REDIRECT_OUTPUT; // ignore config lookup output
}
void debugLookupAddon() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--debug-lookup=addon", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(true, settings->debuglookupAddon);
}
void debugLookupConfig() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--debug-lookup=config", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(true, settings->debuglookupConfig);
GET_REDIRECT_OUTPUT; // ignore config lookup output
}
void debugLookupLibrary() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--debug-lookup=library", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(true, settings->debuglookupLibrary);
}
void debugLookupPlatform() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--debug-lookup=platform", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(true, settings->debuglookupPlatform);
}
void maxTemplateRecursion() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--max-template-recursion=12", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(12, settings->maxTemplateRecursion);
}
void maxTemplateRecursionMissingCount() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--max-template-recursion=", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: argument to '--max-template-recursion=' is not valid - not an integer.\n", logger->str());
}
void ignorepaths1() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-isrc", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(1, parser->getIgnoredPaths().size());
ASSERT_EQUALS("src", parser->getIgnoredPaths()[0]);
}
void ignorepaths2() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-i", "src", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(4, argv));
ASSERT_EQUALS(1, parser->getIgnoredPaths().size());
ASSERT_EQUALS("src", parser->getIgnoredPaths()[0]);
}
void ignorepaths3() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-isrc", "-imodule", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(4, argv));
ASSERT_EQUALS(2, parser->getIgnoredPaths().size());
ASSERT_EQUALS("src", parser->getIgnoredPaths()[0]);
ASSERT_EQUALS("module", parser->getIgnoredPaths()[1]);
}
void ignorepaths4() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-i", "src", "-i", "module", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(6, argv));
ASSERT_EQUALS(2, parser->getIgnoredPaths().size());
ASSERT_EQUALS("src", parser->getIgnoredPaths()[0]);
ASSERT_EQUALS("module", parser->getIgnoredPaths()[1]);
}
void ignorefilepaths1() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-ifoo.cpp", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(1, parser->getIgnoredPaths().size());
ASSERT_EQUALS("foo.cpp", parser->getIgnoredPaths()[0]);
}
void ignorefilepaths2() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-isrc/foo.cpp", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(1, parser->getIgnoredPaths().size());
ASSERT_EQUALS("src/foo.cpp", parser->getIgnoredPaths()[0]);
}
void ignorefilepaths3() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-i", "foo.cpp", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(4, argv));
ASSERT_EQUALS(1, parser->getIgnoredPaths().size());
ASSERT_EQUALS("foo.cpp", parser->getIgnoredPaths()[0]);
}
void checkconfig() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--check-config", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(true, settings->checkConfiguration);
}
void unknownParam() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--foo", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: unrecognized command line option: \"--foo\".\n", logger->str());
}
void undefs() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-U_WIN32", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(1, settings->userUndefs.size());
ASSERT(settings->userUndefs.find("_WIN32") != settings->userUndefs.end());
}
void undefs2() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-U_WIN32", "-UNODEBUG", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(4, argv));
ASSERT_EQUALS(2, settings->userUndefs.size());
ASSERT(settings->userUndefs.find("_WIN32") != settings->userUndefs.end());
ASSERT(settings->userUndefs.find("NODEBUG") != settings->userUndefs.end());
}
void undefs_noarg() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-U"};
// Fails since -U has no param
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(2, argv));
ASSERT_EQUALS("cppcheck: error: argument to '-U' is missing.\n", logger->str());
}
void undefs_noarg2() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-U", "-v", "file.cpp"};
// Fails since -U has no param
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(4, argv));
ASSERT_EQUALS("cppcheck: error: argument to '-U' is missing.\n", logger->str());
}
void undefs_noarg3() {
REDIRECT;
const char * const argv[] = {"cppcheck", "-U", "--quiet", "file.cpp"};
// Fails since -U has no param
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(4, argv));
ASSERT_EQUALS("cppcheck: error: argument to '-U' is missing.\n", logger->str());
}
void cppcheckBuildDirExistent() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--cppcheck-build-dir=.", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT_EQUALS(".", settings->buildDir);
}
void cppcheckBuildDirNonExistent() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--cppcheck-build-dir=non-existent-path", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: Directory 'non-existent-path' specified by --cppcheck-build-dir argument has to be existent.\n", logger->str());
}
void cppcheckBuildDirEmpty() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--cppcheck-build-dir=", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(3, argv));
ASSERT_EQUALS("cppcheck: error: no path has been specified for --cppcheck-build-dir\n", logger->str());
}
void cppcheckBuildDirMultiple() {
REDIRECT;
const char * const argv[] = {"cppcheck", "--cppcheck-build-dir=non-existent-path", "--cppcheck-build-dir=.", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(4, argv));
ASSERT_EQUALS(".", settings->buildDir);
}
void noCppcheckBuildDir()
{
REDIRECT;
const char * const argv[] = {"cppcheck", "--no-cppcheck-build-dir", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(3, argv));
ASSERT(settings->buildDir.empty());
}
void noCppcheckBuildDir2()
{
REDIRECT;
const char * const argv[] = {"cppcheck", "--cppcheck-build-dir=b1", "--no-cppcheck-build-dir", "file.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Success, parser->parseFromArgs(4, argv));
ASSERT(settings->buildDir.empty());
}
void invalidCppcheckCfg() {
REDIRECT;
ScopedFile file(Path::join(Path::getPathFromFilename(Path::getCurrentExecutablePath("")), "cppcheck.cfg"),
"{\n");
const char * const argv[] = {"cppcheck", "test.cpp"};
ASSERT_EQUALS_ENUM(CmdLineParser::Result::Fail, parser->parseFromArgs(2, argv));
ASSERT_EQUALS("cppcheck: error: could not load cppcheck.cfg - not a valid JSON - syntax error at line 2 near: \n", logger->str());
}
};
REGISTER_TEST(TestCmdlineParser)
| null |
978 | cpp | cppcheck | testanalyzerinformation.cpp | test/testanalyzerinformation.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2023 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "analyzerinfo.h"
#include "fixture.h"
#include <sstream>
class TestAnalyzerInformation : public TestFixture, private AnalyzerInformation {
public:
TestAnalyzerInformation() : TestFixture("TestAnalyzerInformation") {}
private:
void run() override {
TEST_CASE(getAnalyzerInfoFile);
}
void getAnalyzerInfoFile() const {
constexpr char filesTxt[] = "file1.a4::file1.c\n";
std::istringstream f1(filesTxt);
ASSERT_EQUALS("file1.a4", getAnalyzerInfoFileFromFilesTxt(f1, "file1.c", ""));
std::istringstream f2(filesTxt);
ASSERT_EQUALS("file1.a4", getAnalyzerInfoFileFromFilesTxt(f2, "./file1.c", ""));
ASSERT_EQUALS("builddir/file1.c.analyzerinfo", AnalyzerInformation::getAnalyzerInfoFile("builddir", "file1.c", ""));
ASSERT_EQUALS("builddir/file1.c.analyzerinfo", AnalyzerInformation::getAnalyzerInfoFile("builddir", "some/path/file1.c", ""));
}
};
REGISTER_TEST(TestAnalyzerInformation)
| null |
979 | cpp | cppcheck | testsummaries.cpp | test/testsummaries.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "fixture.h"
#include "helpers.h"
#include "summaries.h"
#include <cstddef>
#include <string>
class TestSummaries : public TestFixture {
public:
TestSummaries() : TestFixture("TestSummaries") {}
private:
void run() override {
TEST_CASE(createSummaries1);
TEST_CASE(createSummariesGlobal);
TEST_CASE(createSummariesNoreturn);
}
#define createSummaries(...) createSummaries_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
std::string createSummaries_(const char* file, int line, const char (&code)[size], bool cpp = true) {
// tokenize..
SimpleTokenizer tokenizer(settingsDefault, *this);
ASSERT_LOC(tokenizer.tokenize(code, cpp), file, line);
return Summaries::create(tokenizer, "");
}
void createSummaries1() {
ASSERT_EQUALS("foo\n", createSummaries("void foo() {}"));
}
void createSummariesGlobal() {
ASSERT_EQUALS("foo global:[x]\n", createSummaries("int x; void foo() { x=0; }"));
}
void createSummariesNoreturn() {
ASSERT_EQUALS("foo call:[bar] noreturn:[bar]\n", createSummaries("void foo() { bar(); }"));
}
};
REGISTER_TEST(TestSummaries)
| null |
980 | cpp | cppcheck | testclangimport.cpp | test/testclangimport.cpp | null | // Cppcheck - A tool for static C/C++ code analysis
// Copyright (C) 2007-2024 Cppcheck team.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#include "clangimport.h"
#include "platform.h"
#include "settings.h"
#include "symboldatabase.h"
#include "token.h"
#include "tokenize.h"
#include "fixture.h"
#include <cstdint>
#include <list>
#include <sstream>
#include <string>
#include <vector>
class TestClangImport : public TestFixture {
public:
TestClangImport()
: TestFixture("TestClangImport") {}
private:
void run() override {
TEST_CASE(breakStmt);
TEST_CASE(callExpr);
TEST_CASE(caseStmt1);
TEST_CASE(characterLiteral);
TEST_CASE(class1);
TEST_CASE(classTemplateDecl1);
TEST_CASE(classTemplateDecl2);
TEST_CASE(conditionalExpr);
TEST_CASE(compoundAssignOperator);
TEST_CASE(continueStmt);
TEST_CASE(cstyleCastExpr);
TEST_CASE(cxxBoolLiteralExpr);
TEST_CASE(cxxConstructorDecl1);
TEST_CASE(cxxConstructorDecl2);
TEST_CASE(cxxConstructExpr1);
TEST_CASE(cxxConstructExpr2);
TEST_CASE(cxxConstructExpr3);
TEST_CASE(cxxDeleteExpr);
TEST_CASE(cxxDestructorDecl);
TEST_CASE(cxxForRangeStmt1);
TEST_CASE(cxxForRangeStmt2);
TEST_CASE(cxxFunctionalCastExpr);
TEST_CASE(cxxMemberCall);
TEST_CASE(cxxMethodDecl1);
TEST_CASE(cxxMethodDecl2);
TEST_CASE(cxxMethodDecl3);
TEST_CASE(cxxMethodDecl4);
TEST_CASE(cxxNewExpr1);
TEST_CASE(cxxNewExpr2);
TEST_CASE(cxxNullPtrLiteralExpr);
TEST_CASE(cxxOperatorCallExpr);
TEST_CASE(cxxRecordDecl1);
TEST_CASE(cxxRecordDecl2);
TEST_CASE(cxxRecordDeclDerived);
TEST_CASE(cxxStaticCastExpr1);
TEST_CASE(cxxStaticCastExpr2);
TEST_CASE(cxxStaticCastExpr3);
TEST_CASE(cxxStdInitializerListExpr);
TEST_CASE(cxxThrowExpr);
TEST_CASE(defaultStmt);
TEST_CASE(doStmt);
TEST_CASE(enumDecl1);
TEST_CASE(enumDecl2);
TEST_CASE(enumDecl3);
TEST_CASE(enumDecl4);
TEST_CASE(forStmt);
TEST_CASE(funcdecl1);
TEST_CASE(funcdecl2);
TEST_CASE(funcdecl3);
TEST_CASE(funcdecl4);
TEST_CASE(funcdecl5);
TEST_CASE(funcdecl6);
TEST_CASE(functionTemplateDecl1);
TEST_CASE(functionTemplateDecl2);
TEST_CASE(initListExpr);
TEST_CASE(ifelse);
TEST_CASE(ifStmt);
TEST_CASE(labelStmt);
TEST_CASE(memberExpr);
TEST_CASE(namespaceDecl1);
TEST_CASE(namespaceDecl2);
TEST_CASE(recordDecl1);
TEST_CASE(recordDecl2);
TEST_CASE(switchStmt);
TEST_CASE(typedefDeclPrologue);
TEST_CASE(unaryExprOrTypeTraitExpr1);
TEST_CASE(unaryExprOrTypeTraitExpr2);
TEST_CASE(unaryOperator);
TEST_CASE(vardecl1);
TEST_CASE(vardecl2);
TEST_CASE(vardecl3);
TEST_CASE(vardecl4);
TEST_CASE(vardecl5);
TEST_CASE(vardecl6);
TEST_CASE(vardecl7);
TEST_CASE(whileStmt1);
TEST_CASE(whileStmt2);
TEST_CASE(tokenIndex);
TEST_CASE(symbolDatabaseEnum1);
TEST_CASE(symbolDatabaseFunction1);
TEST_CASE(symbolDatabaseFunction2);
TEST_CASE(symbolDatabaseFunction3);
TEST_CASE(symbolDatabaseFunctionConst);
TEST_CASE(symbolDatabaseVariableRef);
TEST_CASE(symbolDatabaseVariableRRef);
TEST_CASE(symbolDatabaseVariablePointerRef);
TEST_CASE(symbolDatabaseNodeType1);
TEST_CASE(symbolDatabaseForVariable);
TEST_CASE(stdinLoc);
TEST_CASE(valueFlow1);
TEST_CASE(valueFlow2);
TEST_CASE(valueType1);
TEST_CASE(valueType2);
TEST_CASE(crash);
}
std::string parse(const char clang[]) {
const Settings settings = settingsBuilder().clang().build();
Tokenizer tokenizer(settings, *this);
std::istringstream istr(clang);
clangimport::parseClangAstDump(tokenizer, istr);
if (!tokenizer.tokens()) {
return std::string();
}
return tokenizer.tokens()->stringifyList(true, false, false, false, false);
}
void breakStmt() {
const char clang[] = "`-FunctionDecl 0x2c31b18 <1.c:1:1, col:34> col:6 foo 'void ()'\n"
" `-CompoundStmt 0x2c31c40 <col:12, col:34>\n"
" `-WhileStmt 0x2c31c20 <col:14, col:24>\n"
" |-<<<NULL>>>\n"
" |-IntegerLiteral 0x2c31bf8 <col:21> 'int' 0\n"
" `-BreakStmt 0x3687c18 <col:24>";
ASSERT_EQUALS("void foo ( ) { while ( 0 ) { break ; } }", parse(clang));
}
void callExpr() {
const char clang[] = "`-FunctionDecl 0x2444b60 <1.c:1:1, line:8:1> line:1:6 foo 'void (int)'\n"
" |-ParmVarDecl 0x2444aa0 <col:10, col:14> col:14 used x 'int'\n"
" `-CompoundStmt 0x2444e00 <col:17, line:8:1>\n"
" `-CallExpr 0x7f5a6c04b158 <line:1:16, col:60> 'bool'\n"
" |-ImplicitCastExpr 0x7f5a6c04b140 <col:16, col:23> 'bool (*)(const Token *, const char *, int)' <FunctionToPointerDecay>\n"
" | `-DeclRefExpr 0x7f5a6c04b0a8 <col:16, col:23> 'bool (const Token *, const char *, int)' lvalue CXXMethod 0x43e5600 'Match' 'bool (const Token *, const char *, int)'\n"
" |-ImplicitCastExpr 0x7f5a6c04b1c8 <col:29> 'const Token *' <NoOp>\n"
" | `-ImplicitCastExpr 0x7f5a6c04b1b0 <col:29> 'Token *' <LValueToRValue>\n"
" | `-DeclRefExpr 0x7f5a6c04b0e0 <col:29> 'Token *' lvalue Var 0x7f5a6c045968 'tokAfterCondition' 'Token *'\n"
" |-ImplicitCastExpr 0x7f5a6c04b1e0 <col:48> 'const char *' <ArrayToPointerDecay>\n"
" | `-StringLiteral 0x7f5a6c04b108 <col:48> 'const char [11]' lvalue \"%name% : {\"\n"
" `-CXXDefaultArgExpr 0x7f5a6c04b1f8 <<invalid sloc>> 'int'\n";
ASSERT_EQUALS("void foo ( int x@1 ) { Match ( tokAfterCondition , \"%name% : {\" ) ; }", parse(clang));
}
void caseStmt1() {
const char clang[] = "`-FunctionDecl 0x2444b60 <1.c:1:1, line:8:1> line:1:6 foo 'void (int)'\n"
" |-ParmVarDecl 0x2444aa0 <col:10, col:14> col:14 used x 'int'\n"
" `-CompoundStmt 0x2444e00 <col:17, line:8:1>\n"
" `-SwitchStmt 0x2444c88 <line:2:5, line:7:5>\n"
" |-<<<NULL>>>\n"
" |-<<<NULL>>>\n"
" |-ImplicitCastExpr 0x2444c70 <line:2:13> 'int' <LValueToRValue>\n"
" | `-DeclRefExpr 0x2444c48 <col:13> 'int' lvalue ParmVar 0x2444aa0 'x' 'int'\n"
" `-CompoundStmt 0x2444de0 <col:16, line:7:5>\n"
" |-CaseStmt 0x2444cd8 <line:3:9, line:5:15>\n"
" | |-IntegerLiteral 0x2444cb8 <line:3:14> 'int' 16\n"
" | |-<<<NULL>>>\n"
" | `-CaseStmt 0x2444d30 <line:4:9, line:5:15>\n"
" | |-IntegerLiteral 0x2444d10 <line:4:14> 'int' 32\n"
" | |-<<<NULL>>>\n"
" | `-BinaryOperator 0x2444db0 <line:5:13, col:15> 'int' '='\n"
" | |-DeclRefExpr 0x2444d68 <col:13> 'int' lvalue ParmVar 0x2444aa0 'x' 'int'\n"
" | `-IntegerLiteral 0x2444d90 <col:15> 'int' 123\n"
" `-BreakStmt 0x2444dd8 <line:6:13>";
ASSERT_EQUALS("void foo ( int x@1 ) { switch ( x@1 ) { case 16 : case 32 : x@1 = 123 ; break ; } }", parse(clang));
}
void characterLiteral() {
const char clang[] = "`-VarDecl 0x3df8608 <a.cpp:1:1, col:10> col:6 c 'char' cinit\n"
" `-CharacterLiteral 0x3df86a8 <col:10> 'char' 120";
ASSERT_EQUALS("char c@1 = 'x' ;", parse(clang));
}
void class1() {
const char clang[] = "`-CXXRecordDecl 0x274c638 <a.cpp:1:1, col:25> col:7 class C definition\n"
" |-DefinitionData pass_in_registers empty aggregate standard_layout trivially_copyable pod trivial literal has_constexpr_non_copy_move_ctor can_const_default_init\n"
" | |-DefaultConstructor exists trivial constexpr needs_implicit defaulted_is_constexpr\n"
" | |-CopyConstructor simple trivial has_const_param needs_implicit implicit_has_const_param\n"
" | |-MoveConstructor exists simple trivial needs_implicit\n"
" | |-CopyAssignment trivial has_const_param needs_implicit implicit_has_const_param\n"
" | |-MoveAssignment exists simple trivial needs_implicit\n"
" | `-Destructor simple irrelevant trivial needs_implicit\n"
" |-CXXRecordDecl 0x274c758 <col:1, col:7> col:7 implicit class C\n"
" `-CXXMethodDecl 0x274c870 <col:11, col:23> col:16 foo 'void ()'\n"
" `-CompoundStmt 0x274c930 <col:22, col:23>";
ASSERT_EQUALS("class C { void foo ( ) { } } ;", parse(clang));
}
void classTemplateDecl1() {
const char clang[] = "`-ClassTemplateDecl 0x29d1748 <a.cpp:1:1, col:59> col:25 C\n"
" |-TemplateTypeParmDecl 0x29d15f8 <col:10, col:16> col:16 referenced class depth 0 index 0 T\n"
" `-CXXRecordDecl 0x29d16b0 <col:19, col:59> col:25 class C definition\n"
" |-DefinitionData empty aggregate standard_layout trivially_copyable pod trivial literal has_constexpr_non_copy_move_ctor can_const_default_init\n"
" | |-DefaultConstructor exists trivial constexpr needs_implicit defaulted_is_constexpr\n"
" | |-CopyConstructor simple trivial has_const_param needs_implicit implicit_has_const_param\n"
" | |-MoveConstructor exists simple trivial needs_implicit\n"
" | |-CopyAssignment trivial has_const_param needs_implicit implicit_has_const_param\n"
" | |-MoveAssignment exists simple trivial needs_implicit\n"
" | `-Destructor simple irrelevant trivial needs_implicit\n"
" |-CXXRecordDecl 0x29d19b0 <col:19, col:25> col:25 implicit class C\n"
" |-AccessSpecDecl 0x29d1a48 <col:29, col:35> col:29 public\n"
" `-CXXMethodDecl 0x29d1b20 <col:37, col:57> col:39 foo 'T ()'\n"
" `-CompoundStmt 0x29d1c18 <col:45, col:57>\n"
" `-ReturnStmt 0x29d1c00 <col:47, col:54>\n"
" `-IntegerLiteral 0x29d1be0 <col:54> 'int' 0";
ASSERT_EQUALS("", parse(clang));
}
void classTemplateDecl2() {
const char clang[] = "|-ClassTemplateDecl 0x244e748 <a.cpp:1:1, col:59> col:25 C\n"
"| |-TemplateTypeParmDecl 0x244e5f8 <col:10, col:16> col:16 referenced class depth 0 index 0 T\n"
"| |-CXXRecordDecl 0x244e6b0 <col:19, col:59> col:25 class C definition\n"
"| | |-DefinitionData empty aggregate standard_layout trivially_copyable pod trivial literal has_constexpr_non_copy_move_ctor can_const_default_init\n"
"| | | |-DefaultConstructor exists trivial constexpr needs_implicit defaulted_is_constexpr\n"
"| | | |-CopyConstructor simple trivial has_const_param needs_implicit implicit_has_const_param\n"
"| | | |-MoveConstructor exists simple trivial needs_implicit\n"
"| | | |-CopyAssignment trivial has_const_param needs_implicit implicit_has_const_param\n"
"| | | |-MoveAssignment exists simple trivial needs_implicit\n"
"| | | `-Destructor simple irrelevant trivial needs_implicit\n"
"| | |-CXXRecordDecl 0x244e9b0 <col:19, col:25> col:25 implicit class C\n"
"| | |-AccessSpecDecl 0x244ea48 <col:29, col:35> col:29 public\n"
"| | `-CXXMethodDecl 0x244eb20 <col:37, col:57> col:39 foo 'T ()'\n"
"| | `-CompoundStmt 0x244ec18 <col:45, col:57>\n"
"| | `-ReturnStmt 0x244ec00 <col:47, col:54>\n"
"| | `-IntegerLiteral 0x244ebe0 <col:54> 'int' 0\n"
"| `-ClassTemplateSpecializationDecl 0x244ed78 <col:1, col:59> col:25 class C definition\n"
"| |-DefinitionData pass_in_registers empty aggregate standard_layout trivially_copyable pod trivial literal has_constexpr_non_copy_move_ctor can_const_default_init\n"
"| | |-DefaultConstructor exists trivial constexpr defaulted_is_constexpr\n"
"| | |-CopyConstructor simple trivial has_const_param implicit_has_const_param\n"
"| | |-MoveConstructor exists simple trivial\n"
"| | |-CopyAssignment trivial has_const_param needs_implicit implicit_has_const_param\n"
"| | |-MoveAssignment exists simple trivial needs_implicit\n"
"| | `-Destructor simple irrelevant trivial needs_implicit\n"
"| |-TemplateArgument type 'int'\n"
"| |-CXXRecordDecl 0x244eff0 prev 0x244ed78 <col:19, col:25> col:25 implicit class C\n"
"| |-AccessSpecDecl 0x244f088 <col:29, col:35> col:29 public\n"
"| |-CXXMethodDecl 0x244f160 <col:37, col:57> col:39 used foo 'int ()'\n"
"| | `-CompoundStmt 0x247cb40 <col:45, col:57>\n"
"| | `-ReturnStmt 0x247cb28 <col:47, col:54>\n"
"| | `-IntegerLiteral 0x244ebe0 <col:54> 'int' 0\n"
"| |-CXXConstructorDecl 0x247c540 <col:25> col:25 implicit used constexpr C 'void () noexcept' inline default trivial\n"
"| | `-CompoundStmt 0x247ca00 <col:25>\n"
"| |-CXXConstructorDecl 0x247c658 <col:25> col:25 implicit constexpr C 'void (const C<int> &)' inline default trivial noexcept-unevaluated 0x247c658\n"
"| | `-ParmVarDecl 0x247c790 <col:25> col:25 'const C<int> &'\n"
"| `-CXXConstructorDecl 0x247c828 <col:25> col:25 implicit constexpr C 'void (C<int> &&)' inline default trivial noexcept-unevaluated 0x247c828\n"
"| `-ParmVarDecl 0x247c960 <col:25> col:25 'C<int> &&'\n";
ASSERT_EQUALS("class C { int foo ( ) { return 0 ; } C ( ) { } C ( const C<int> & ) = default ; C ( C<int> && ) = default ; } ;", parse(clang));
}
void conditionalExpr() {
const char clang[] = "`-VarDecl 0x257cc88 <a.cpp:4:1, col:13> col:5 x 'int' cinit\n"
" `-ConditionalOperator 0x257cda8 <col:9, col:13> 'int'\n"
" |-ImplicitCastExpr 0x257cd60 <col:9> 'int' <LValueToRValue>\n"
" | `-DeclRefExpr 0x257cce8 <col:9> 'int' lvalue Var 0x257cae0 'a' 'int'\n"
" |-ImplicitCastExpr 0x257cd78 <col:11> 'int' <LValueToRValue>\n"
" | `-DeclRefExpr 0x257cd10 <col:11> 'int' lvalue Var 0x257cb98 'b' 'int'\n"
" `-ImplicitCastExpr 0x257cd90 <col:13> 'int' <LValueToRValue>\n"
" `-DeclRefExpr 0x257cd38 <col:13> 'int' lvalue Var 0x257cc10 'c' 'int'";
ASSERT_EQUALS("int x@1 = a ? b : c ;", parse(clang));
}
void compoundAssignOperator() {
const char clang[] = "`-FunctionDecl 0x3570690 <1.cpp:2:1, col:25> col:6 f 'void ()'\n"
" `-CompoundStmt 0x3570880 <col:10, col:25>\n"
" `-CompoundAssignOperator 0x3570848 <col:19, col:22> 'int' lvalue '+=' ComputeLHSTy='int' ComputeResultTy='int'\n"
" |-DeclRefExpr 0x3570800 <col:19> 'int' lvalue Var 0x3570788 'x' 'int'\n"
" `-IntegerLiteral 0x3570828 <col:22> 'int' 1";
ASSERT_EQUALS("void f ( ) { x += 1 ; }", parse(clang));
}
void continueStmt() {
const char clang[] = "`-FunctionDecl 0x2c31b18 <1.c:1:1, col:34> col:6 foo 'void ()'\n"
" `-CompoundStmt 0x2c31c40 <col:12, col:34>\n"
" `-WhileStmt 0x2c31c20 <col:14, col:24>\n"
" |-<<<NULL>>>\n"
" |-IntegerLiteral 0x2c31bf8 <col:21> 'int' 0\n"
" `-ContinueStmt 0x2c31c18 <col:24>";
ASSERT_EQUALS("void foo ( ) { while ( 0 ) { continue ; } }", parse(clang));
}
void cstyleCastExpr() {
const char clang[] = "`-VarDecl 0x2336aa0 <1.c:1:1, col:14> col:5 x 'int' cinit\n"
" `-CStyleCastExpr 0x2336b70 <col:9, col:14> 'int' <NoOp>\n"
" `-CharacterLiteral 0x2336b40 <col:14> 'int' 97";
ASSERT_EQUALS("int x@1 = ( int ) 'a' ;", parse(clang));
}
void cxxBoolLiteralExpr() {
const char clang[] = "`-VarDecl 0x3940608 <a.cpp:1:1, col:10> col:6 x 'bool' cinit\n"
" `-CXXBoolLiteralExpr 0x39406a8 <col:10> 'bool' true";
ASSERT_EQUALS("bool x@1 = true ;", parse(clang));
}
void cxxConstructorDecl1() {
const char clang[] = "|-CXXConstructorDecl 0x428e890 <a.cpp:11:1, col:24> col:11 C 'void ()'\n"
"| `-CompoundStmt 0x428ea58 <col:15, col:24>\n"
"| `-BinaryOperator 0x428ea30 <col:17, col:21> 'int' lvalue '='\n"
"| |-MemberExpr 0x428e9d8 <col:17> 'int' lvalue ->x 0x428e958\n"
"| | `-CXXThisExpr 0x428e9c0 <col:17> 'C *' this\n"
"| `-IntegerLiteral 0x428ea10 <col:21> 'int' 0\n"
"`-FieldDecl 0x428e958 <col:26, col:30> col:30 referenced x 'int'";
ASSERT_EQUALS("C ( ) { this . x@1 = 0 ; } int x@1", parse(clang));
}
void cxxConstructorDecl2() {
const char clang[] = "`-CXXConstructorDecl 0x1c208c0 <a.cpp:1:11> col:11 implicit constexpr basic_string 'void (std::basic_string<char> &&)' inline default trivial noexcept-unevaluated 0x1c208c0\n"
" `-ParmVarDecl 0x1c209f0 <col:11> col:11 'std::basic_string<char> &&'";
ASSERT_EQUALS("basic_string ( std::basic_string<char> && ) = default ;", parse(clang));
}
void cxxConstructExpr1() {
const char clang[] = "`-FunctionDecl 0x2dd7940 <a.cpp:2:1, col:30> col:5 f 'Foo (Foo)'\n"
" |-ParmVarDecl 0x2dd7880 <col:7, col:11> col:11 used foo 'Foo'\n"
" `-CompoundStmt 0x2dd80c0 <col:16, col:30>\n"
" `-ReturnStmt 0x2dd80a8 <col:18, col:25>\n"
" `-CXXConstructExpr 0x2dd8070 <col:25> 'Foo' 'void (Foo &&) noexcept'\n"
" `-ImplicitCastExpr 0x2dd7f28 <col:25> 'Foo' xvalue <NoOp>\n"
" `-DeclRefExpr 0x2dd7a28 <col:25> 'Foo' lvalue ParmVar 0x2dd7880 'foo' 'Foo'";
ASSERT_EQUALS("Foo f ( Foo foo@1 ) { return foo@1 ; }", parse(clang));
}
void cxxConstructExpr2() {
const char clang[] = "`-FunctionDecl 0x3e44180 <1.cpp:2:1, col:30> col:13 f 'std::string ()'\n"
" `-CompoundStmt 0x3e4cb80 <col:17, col:30>\n"
" `-ReturnStmt 0x3e4cb68 <col:19, col:27>\n"
" `-CXXConstructExpr 0x3e4cb38 <col:26, col:27> 'std::string':'std::__cxx11::basic_string<char>' '....' list";
ASSERT_EQUALS("std :: string f ( ) { return std :: string ( ) ; }", parse(clang));
}
void cxxConstructExpr3() {
const char clang[] = "`-FunctionDecl 0x2c585b8 <1.cpp:4:1, col:39> col:6 f 'void ()'\n"
" `-CompoundStmt 0x2c589d0 <col:10, col:39>\n"
" |-DeclStmt 0x2c586d0 <col:12, col:19>\n"
" | `-VarDecl 0x2c58670 <col:12, col:18> col:18 used p 'char *'\n"
" `-DeclStmt 0x2c589b8 <col:21, col:37>\n"
" `-VarDecl 0x2c58798 <col:21, col:36> col:33 s 'std::string':'std::__cxx11::basic_string<char>' callinit\n"
" `-ExprWithCleanups 0x2c589a0 <col:33, col:36> 'std::string':'std::__cxx11::basic_string<char>'\n"
" `-CXXConstructExpr 0x2c58960 <col:33, col:36> 'std::string':'std::__cxx11::basic_string<char>' 'void (const char *, const std::allocator<char> &)'\n"
" |-ImplicitCastExpr 0x2c58870 <col:35> 'const char *' <NoOp>\n"
" | `-ImplicitCastExpr 0x2c58858 <col:35> 'char *' <LValueToRValue>\n"
" | `-DeclRefExpr 0x2c58750 <col:35> 'char *' lvalue Var 0x2c58670 'p' 'char *'\n"
" `-CXXDefaultArgExpr 0x2c58940 <<invalid sloc>> 'const std::allocator<char>':'const std::allocator<char>' lvalue\n";
ASSERT_EQUALS("void f ( ) { char * p@1 ; std :: string s@2 ( p@1 ) ; }", parse(clang));
}
void cxxDeleteExpr() {
const char clang[] = "|-FunctionDecl 0x2e0e740 <1.cpp:1:1, col:28> col:6 f 'void (int *)'\n"
"| |-ParmVarDecl 0x2e0e680 <col:8, col:13> col:13 used p 'int *'\n"
"| `-CompoundStmt 0x2e0ee70 <col:16, col:28>\n"
"| `-CXXDeleteExpr 0x2e0ee48 <col:18, col:25> 'void' Function 0x2e0ebb8 'operator delete' 'void (void *) noexcept'\n"
"| `-ImplicitCastExpr 0x2e0e850 <col:25> 'int *' <LValueToRValue>\n"
"| `-DeclRefExpr 0x2e0e828 <col:25> 'int *' lvalue ParmVar 0x2e0e680 'p' 'int *'";
ASSERT_EQUALS("void f ( int * p@1 ) { delete p@1 ; }", parse(clang));
}
void cxxDestructorDecl() {
const char clang[] = "`-CXXRecordDecl 0x8ecd60 <1.cpp:1:1, line:4:1> line:1:8 struct S definition\n"
" `-CXXDestructorDecl 0x8ed088 <line:3:3, col:9> col:3 ~S 'void () noexcept'\n"
" `-CompoundStmt 0x8ed1a8 <col:8, col:9>";
ASSERT_EQUALS("struct S { ~S ( ) { } } ;", parse(clang));
}
void cxxForRangeStmt1() {
const char clang[] = "`-FunctionDecl 0x4280820 <a.cpp:4:1, line:8:1> line:4:6 foo 'void ()'\n"
" `-CompoundStmt 0x42810f0 <col:12, line:8:1>\n"
" `-CXXForRangeStmt 0x4281090 <line:5:3, line:7:3>\n"
" |-DeclStmt 0x4280c30 <line:5:17>\n"
" | `-VarDecl 0x42809c8 <col:17> col:17 implicit referenced __range1 'char const (&)[6]' cinit\n"
" | `-DeclRefExpr 0x42808c0 <col:17> 'const char [6]' lvalue Var 0x4280678 'hello' 'const char [6]'\n"
" |-DeclStmt 0x4280ef8 <col:15>\n"
" | `-VarDecl 0x4280ca8 <col:15> col:15 implicit used __begin1 'const char *':'const char *' cinit\n"
" | `-ImplicitCastExpr 0x4280e10 <col:15> 'const char *' <ArrayToPointerDecay>\n"
" | `-DeclRefExpr 0x4280c48 <col:15> 'char const[6]' lvalue Var 0x42809c8 '__range1' 'char const (&)[6]'\n"
" |-DeclStmt 0x4280f10 <col:15>\n"
" | `-VarDecl 0x4280d18 <col:15, col:17> col:15 implicit used __end1 'const char *':'const char *' cinit\n"
" | `-BinaryOperator 0x4280e60 <col:15, col:17> 'const char *' '+'\n"
" | |-ImplicitCastExpr 0x4280e48 <col:15> 'const char *' <ArrayToPointerDecay>\n"
" | | `-DeclRefExpr 0x4280c70 <col:15> 'char const[6]' lvalue Var 0x42809c8 '__range1' 'char const (&)[6]'\n"
" | `-IntegerLiteral 0x4280e28 <col:17> 'long' 6\n"
" |-BinaryOperator 0x4280fa8 <col:15> 'bool' '!='\n"
" | |-ImplicitCastExpr 0x4280f78 <col:15> 'const char *':'const char *' <LValueToRValue>\n"
" | | `-DeclRefExpr 0x4280f28 <col:15> 'const char *':'const char *' lvalue Var 0x4280ca8 '__begin1' 'const char *':'const char *'\n"
" | `-ImplicitCastExpr 0x4280f90 <col:15> 'const char *':'const char *' <LValueToRValue>\n"
" | `-DeclRefExpr 0x4280f50 <col:15> 'const char *':'const char *' lvalue Var 0x4280d18 '__end1' 'const char *':'const char *'\n"
" |-UnaryOperator 0x4280ff8 <col:15> 'const char *':'const char *' lvalue prefix '++'\n"
" | `-DeclRefExpr 0x4280fd0 <col:15> 'const char *':'const char *' lvalue Var 0x4280ca8 '__begin1' 'const char *':'const char *'\n"
" |-DeclStmt 0x4280958 <col:8, col:22>\n"
" | `-VarDecl 0x42808f8 <col:8, col:15> col:13 c1 'char' cinit\n"
" | `-ImplicitCastExpr 0x4281078 <col:15> 'char' <LValueToRValue>\n"
" | `-UnaryOperator 0x4281058 <col:15> 'const char' lvalue prefix '*' cannot overflow\n"
" | `-ImplicitCastExpr 0x4281040 <col:15> 'const char *':'const char *' <LValueToRValue>\n"
" | `-DeclRefExpr 0x4281018 <col:15> 'const char *':'const char *' lvalue Var 0x4280ca8 '__begin1' 'const char *':'const char *'\n"
" `-CompoundStmt 0x42810e0 <col:24, line:7:3>";
ASSERT_EQUALS("void foo ( ) { for ( char c1@1 : hello ) { } }",
parse(clang));
}
void cxxForRangeStmt2() {
// clang 9
const char clang[] = "`-FunctionDecl 0xc15d98 <a.cpp:3:1, col:36> col:6 foo 'void ()'\n"
" `-CompoundStmt 0xc16668 <col:12, col:36>\n"
" `-CXXForRangeStmt 0xc165f8 <col:14, col:34>\n"
" |-<<<NULL>>>\n"
" |-DeclStmt 0xc161c0 <col:25>\n"
" | `-VarDecl 0xc15f48 <col:25> col:25 implicit referenced __range1 'int const (&)[4]' cinit\n"
" | `-DeclRefExpr 0xc15e38 <col:25> 'const int [4]' lvalue Var 0xc15ac0 'values' 'const int [4]'\n"
" |-DeclStmt 0xc16498 <col:24>\n"
" | `-VarDecl 0xc16228 <col:24> col:24 implicit used __begin1 'const int *':'const int *' cinit\n"
" | `-ImplicitCastExpr 0xc163b0 <col:24> 'const int *' <ArrayToPointerDecay>\n"
" | `-DeclRefExpr 0xc161d8 <col:24> 'int const[4]' lvalue Var 0xc15f48 '__range1' 'int const (&)[4]' non_odr_use_constant\n"
" |-DeclStmt 0xc164b0 <col:24>\n"
" | `-VarDecl 0xc162a0 <col:24, col:25> col:24 implicit used __end1 'const int *':'const int *' cinit\n"
" | `-BinaryOperator 0xc16400 <col:24, col:25> 'const int *' '+'\n"
" | |-ImplicitCastExpr 0xc163e8 <col:24> 'const int *' <ArrayToPointerDecay>\n"
" | | `-DeclRefExpr 0xc161f8 <col:24> 'int const[4]' lvalue Var 0xc15f48 '__range1' 'int const (&)[4]' non_odr_use_constant\n"
" | `-IntegerLiteral 0xc163c8 <col:25> 'long' 4\n"
" |-BinaryOperator 0xc16538 <col:24> 'bool' '!='\n"
" | |-ImplicitCastExpr 0xc16508 <col:24> 'const int *':'const int *' <LValueToRValue>\n"
" | | `-DeclRefExpr 0xc164c8 <col:24> 'const int *':'const int *' lvalue Var 0xc16228 '__begin1' 'const int *':'const int *'\n"
" | `-ImplicitCastExpr 0xc16520 <col:24> 'const int *':'const int *' <LValueToRValue>\n"
" | `-DeclRefExpr 0xc164e8 <col:24> 'const int *':'const int *' lvalue Var 0xc162a0 '__end1' 'const int *':'const int *'\n"
" |-UnaryOperator 0xc16578 <col:24> 'const int *':'const int *' lvalue prefix '++'\n"
" | `-DeclRefExpr 0xc16558 <col:24> 'const int *':'const int *' lvalue Var 0xc16228 '__begin1' 'const int *':'const int *'\n"
" |-DeclStmt 0xc15ed8 <col:19, col:31>\n"
" | `-VarDecl 0xc15e70 <col:19, col:24> col:23 v 'int' cinit\n"
" | `-ImplicitCastExpr 0xc165e0 <col:24> 'int' <LValueToRValue>\n"
" | `-UnaryOperator 0xc165c8 <col:24> 'const int' lvalue prefix '*' cannot overflow\n"
" | `-ImplicitCastExpr 0xc165b0 <col:24> 'const int *':'const int *' <LValueToRValue>\n"
" | `-DeclRefExpr 0xc16590 <col:24> 'const int *':'const int *' lvalue Var 0xc16228 '__begin1' 'const int *':'const int *'\n"
" `-CompoundStmt 0xc16658 <col:33, col:34>";
ASSERT_EQUALS("void foo ( ) { for ( int v@1 : values ) { } }",
parse(clang));
}
void cxxFunctionalCastExpr() {
const char clang[] = "`-FunctionDecl 0x156fe98 <a.cpp:1:1, line:3:1> line:1:5 main 'int (int, char **)'\n"
" |-ParmVarDecl 0x156fd00 <col:10, col:14> col:14 argc 'int'\n"
" |-ParmVarDecl 0x156fdb8 <col:20, col:27> col:27 argv 'char **'\n"
" `-CompoundStmt 0x1596410 <line:2:1, line:2:1>\n"
" |-DeclStmt 0x15946a8 <line:2:15, line:2:29>\n"
" | `-VarDecl 0x1570118 <line:2:15, line:2:28> col:11 used setCode 'MyVar<int>':'MyVar<int>' cinit\n"
" | `-ExprWithCleanups 0x1594690 <line:2:15, line:3:28> 'MyVar<int>':'MyVar<int>'\n"
" | `-CXXConstructExpr 0x1594660 <line:2:15, line:3:28> 'MyVar<int>':'MyVar<int>' 'void (MyVar<int> &&) noexcept' elidable\n"
" | `-MaterializeTemporaryExpr 0x1592b68 <line:2:15, line:3:28> 'MyVar<int>':'MyVar<int>' xvalue\n"
" | `-CXXFunctionalCastExpr 0x1592b40 <line:2:15, line:3:28> 'MyVar<int>':'MyVar<int>' functional cast to MyVar<int> <ConstructorConversion>\n"
" | `-CXXConstructExpr 0x15929f0 <line:2:15, line:3:28> 'MyVar<int>':'MyVar<int>' 'void (int)'\n"
" | `-IntegerLiteral 0x1570248 <col:27> 'int' 5\n";
ASSERT_EQUALS("int main ( int argc@1 , char * * argv@2 ) { MyVar<int> setCode@3 = MyVar<int> ( 5 ) ; }",
parse(clang));
}
void cxxMemberCall() {
const char clang[] = "`-FunctionDecl 0x320dc80 <a.cpp:2:1, col:33> col:6 bar 'void ()'\n"
" `-CompoundStmt 0x323bb08 <col:12, col:33>\n"
" |-DeclStmt 0x323ba40 <col:14, col:22>\n"
" | `-VarDecl 0x320df28 <col:14, col:21> col:21 used c 'C<int>':'C<int>' callinit\n"
" | `-CXXConstructExpr 0x323ba10 <col:21> 'C<int>':'C<int>' 'void () noexcept'\n"
" `-CXXMemberCallExpr 0x323bab8 <col:24, col:30> 'int':'int'\n"
" `-MemberExpr 0x323ba80 <col:24, col:26> '<bound member function type>' .foo 0x320e160\n"
" `-DeclRefExpr 0x323ba58 <col:24> 'C<int>':'C<int>' lvalue Var 0x320df28 'c' 'C<int>':'C<int>'";
ASSERT_EQUALS("void bar ( ) { C<int> c@1 ( C<int> ( ) ) ; c@1 . foo ( ) ; }", parse(clang));
}
void cxxMethodDecl1() {
const char clang[] = "|-CXXMethodDecl 0x55c786f5ad60 <a.cpp:56:5, col:179> col:10 analyzeFile '_Bool (const std::string &, const std::string &, const std::string &, unsigned long long, std::list<ErrorLogger::ErrorMessage> *)'\n"
"| |-ParmVarDecl 0x55c786f5a4c8 <col:22, col:41> col:41 buildDir 'const std::string &'\n"
"| |-ParmVarDecl 0x55c786f5a580 <col:51, col:70> col:70 sourcefile 'const std::string &'\n"
"| |-ParmVarDecl 0x55c786f5a638 <col:82, col:101> col:101 cfg 'const std::string &'\n"
"| |-ParmVarDecl 0x55c786f5a6a8 <col:106, col:125> col:125 checksum 'unsigned long long'\n"
"| |-ParmVarDecl 0x55c786f5ac00 <col:135, col:173> col:173 errors 'std::list<ErrorLogger::ErrorMessage> *'\n"
" `-CompoundStmt 0x0 <>";
ASSERT_EQUALS("_Bool analyzeFile ( const std :: string & buildDir@1 , const std :: string & sourcefile@2 , const std :: string & cfg@3 , unsigned long long checksum@4 , std::list<ErrorLogger::ErrorMessage> * errors@5 ) { }", parse(clang));
}
void cxxMethodDecl2() { // "unexpanded" template method
const char clang[] = "`-CXXMethodDecl 0x220ecb0 parent 0x21e4c28 prev 0x21e5338 <a.cpp:11:1, line:18:1> line:14:1 find 'const typename char_traits<_CharT>::char_type *(const char_traits::char_type *, int, const char_traits::char_type &)'\n"
" `-CompoundStmt 0x220ede0 <line:15:1, line:18:1>\n"
" `-ReturnStmt 0x220edd0 <line:17:5, col:12>\n"
" `-IntegerLiteral 0x220edb0 <col:12> 'int' 0";
ASSERT_EQUALS("", parse(clang));
}
void cxxMethodDecl3() {
const char clang[] = "|-CXXRecordDecl 0x21cca40 <2.cpp:2:1, line:4:1> line:2:7 class Fred definition\n"
"| |-DefinitionData pass_in_registers empty aggregate standard_layout trivially_copyable pod trivial literal has_constexpr_non_copy_move_ctor can_const_default_init\n"
"| | |-DefaultConstructor exists trivial constexpr needs_implicit defaulted_is_constexpr\n"
"| | |-CopyConstructor simple trivial has_const_param needs_implicit implicit_has_const_param\n"
"| | |-MoveConstructor exists simple trivial needs_implicit\n"
"| | |-CopyAssignment trivial has_const_param needs_implicit implicit_has_const_param\n"
"| | |-MoveAssignment exists simple trivial needs_implicit\n"
"| | `-Destructor simple irrelevant trivial needs_implicit\n"
"| |-CXXRecordDecl 0x21ccb58 <col:1, col:7> col:7 implicit class Fred\n"
"| `-CXXMethodDecl 0x21ccc68 <line:3:1, col:10> col:6 foo 'void ()'\n"
"`-CXXMethodDecl 0x21ccd60 parent 0x21cca40 prev 0x21ccc68 <line:6:1, col:19> col:12 foo 'void ()'\n"
" `-CompoundStmt 0x21cce50 <col:18, col:19>";
ASSERT_EQUALS("class Fred { void foo ( ) ; } ; void Fred :: foo ( ) { }", parse(clang));
}
void cxxMethodDecl4() {
const char clang[] = "|-ClassTemplateSpecializationDecl 0x15d82f8 <a.cpp:7:3, line:18:3> line:8:12 struct char_traits definition\n"
"| |-TemplateArgument type 'char'\n"
"| | `-BuiltinType 0x15984c0 'char'\n"
"| |-CXXRecordDecl 0x15d8520 <col:5, col:12> col:12 implicit struct char_traits\n"
"| |-CXXMethodDecl 0x15d8738 <line:12:7, line:16:7> line:13:7 move 'char *(char *)' static\n"
"| | |-ParmVarDecl 0x15d8630 <col:12, col:18> col:18 used __s1 'char *'\n"
"| | `-CompoundStmt 0x15d88e8 <line:14:7, line:16:7>\n";
ASSERT_EQUALS("struct char_traits<char> { static char * move ( char * __s1@1 ) { } } ;",
parse(clang));
}
void cxxNewExpr1() {
const char clang[] = "|-VarDecl 0x3a97680 <1.cpp:2:1, col:14> col:6 i 'int *' cinit\n"
"| `-CXXNewExpr 0x3a97d18 <col:10, col:14> 'int *' Function 0x3a97778 'operator new' 'void *(unsigned long)'\n"
"`-VarDecl 0x3a97d80 <line:3:1, col:21> col:6 j 'int *' cinit\n"
" `-CXXNewExpr 0x3a97e68 <col:10, col:21> 'int *' array Function 0x3a978c0 'operator new[]' 'void *(unsigned long)'\n"
" `-ImplicitCastExpr 0x3a97e18 <col:18> 'unsigned long' <IntegralCast>\n"
" `-IntegerLiteral 0x3a97de0 <col:18> 'int' 100";
ASSERT_EQUALS("int * i@1 = new int ; int * j@2 = new int [ 100 ] ;",
parse(clang));
}
void cxxNewExpr2() {
const char clang[] = "|-FunctionDecl 0x59a188 <a.cpp:7:1, line:9:1> line:7:11 f 'struct S *()'\n"
"| `-CompoundStmt 0x5c4318 <col:15, line:9:1>\n"
"| `-ReturnStmt 0x5c4308 <line:8:3, col:14>\n"
"| `-CXXNewExpr 0x5c42c8 <col:10, col:14> 'S *' Function 0x59a378 'operator new' 'void *(unsigned long)'\n"
"| `-CXXConstructExpr 0x5c42a0 <col:14> 'S' 'void () noexcept'";
ASSERT_EQUALS("struct S * f ( ) { return new S ( ) ; }",
parse(clang));
}
void cxxNullPtrLiteralExpr() {
const char clang[] = "`-VarDecl 0x2a7d650 <1.cpp:1:1, col:17> col:13 p 'const char *' cinit\n"
" `-ImplicitCastExpr 0x2a7d708 <col:17> 'const char *' <NullToPointer>\n"
" `-CXXNullPtrLiteralExpr 0x2a7d6f0 <col:17> 'nullptr_t'";
ASSERT_EQUALS("const char * p@1 = nullptr ;", parse(clang));
}
void cxxOperatorCallExpr() {
const char clang[] = "`-FunctionDecl 0x3c099f0 <a.cpp:2:1, col:24> col:6 foo 'void ()'\n"
" `-CompoundStmt 0x3c37308 <col:12, col:24>\n"
" |-DeclStmt 0x3c0a060 <col:14, col:17>\n"
" | `-VarDecl 0x3c09ae0 <col:14, col:16> col:16 used c 'C' callinit\n"
" | `-CXXConstructExpr 0x3c0a030 <col:16> 'C' 'void () noexcept'\n"
" `-CXXOperatorCallExpr 0x3c372c0 <col:19, col:21> 'void'\n"
" |-ImplicitCastExpr 0x3c372a8 <col:20> 'void (*)(int)' <FunctionToPointerDecay>\n"
" | `-DeclRefExpr 0x3c37250 <col:20> 'void (int)' lvalue CXXMethod 0x3c098c0 'operator=' 'void (int)'\n"
" |-DeclRefExpr 0x3c0a078 <col:19> 'C' lvalue Var 0x3c09ae0 'c' 'C'\n"
" `-IntegerLiteral 0x3c0a0a0 <col:21> 'int' 4";
ASSERT_EQUALS("void foo ( ) { C c@1 ( C ( ) ) ; c@1 . operator= ( 4 ) ; }", parse(clang));
}
void cxxRecordDecl1() {
const char* clang = "`-CXXRecordDecl 0x34cc5f8 <1.cpp:2:1, col:7> col:7 class Foo";
ASSERT_EQUALS("class Foo ;", parse(clang));
clang = "`-CXXRecordDecl 0x34cc5f8 <C:\\Foo\\Bar Baz\\1.cpp:2:1, col:7> col:7 class Foo";
ASSERT_EQUALS("class Foo ;", parse(clang));
clang = "`-CXXRecordDecl 0x34cc5f8 <C:/Foo/Bar Baz/1.cpp:2:1, col:7> col:7 class Foo";
ASSERT_EQUALS("class Foo ;", parse(clang));
}
void cxxRecordDecl2() {
const char clang[] = "`-CXXRecordDecl 0x34cc5f8 <1.cpp:2:1, col:7> col:7 struct Foo definition";
ASSERT_EQUALS("struct Foo { } ;", parse(clang));
}
void cxxRecordDeclDerived() {
const char clang[] = "|-CXXRecordDecl 0x19ccd38 <e.cpp:4:1, line:6:1> line:4:8 referenced struct base definition\n"
"| `-VarDecl 0x19ccf00 <line:5:5, col:35> col:27 value 'const bool' static constexpr cinit\n"
"| |-value: Int 0\n"
"| `-CXXBoolLiteralExpr 0x19ccf68 <col:35> 'bool' false\n"
"`-CXXRecordDecl 0x19ccfe8 <line:8:1, col:32> col:8 struct derived definition\n"
" |-public 'base'\n"
" `-CXXRecordDecl 0x19cd150 <col:1, col:8> col:8 implicit struct derived";
ASSERT_EQUALS("struct base { static const bool value@1 = false ; } ; struct derived : public base { } ;", parse(clang));
}
void cxxStaticCastExpr1() {
const char clang[] = "`-VarDecl 0x2e0e650 <a.cpp:2:1, col:27> col:5 a 'int' cinit\n"
" `-CXXStaticCastExpr 0x2e0e728 <col:9, col:27> 'int' static_cast<int> <NoOp>\n"
" `-IntegerLiteral 0x2e0e6f0 <col:26> 'int' 0";
ASSERT_EQUALS("int a@1 = static_cast<int> ( 0 ) ;", parse(clang));
}
void cxxStaticCastExpr2() {
const char clang[] = "`-VarDecl 0x2e0e650 <a.cpp:2:1, col:27> col:5 a 'int' cinit\n"
" `-CXXStaticCastExpr 0x3e453e8 <col:12> 'std::_Rb_tree_iterator<std::pair<const std::__cxx11::basic_string<char>, Library::AllocFunc> >' xvalue static_cast<struct std::_Rb_tree_iterator<struct std::pair<const class std::__cxx11::basic_string<char>, struct Library::AllocFunc> > &&> <NoOp>\n"
" `-DeclRefExpr 0x3e453b0 <col:12> 'std::_Rb_tree_iterator<std::pair<const std::__cxx11::basic_string<char>, Library::AllocFunc> >' lvalue ParmVar 0x3e45250 '' 'std::_Rb_tree_iterator<std::pair<const std::__cxx11::basic_string<char>, Library::AllocFunc> > &&'";
ASSERT_EQUALS("int a@1 = static_cast<structstd::_Rb_tree_iterator<structstd::pair<constclassstd::__cxx11::basic_string<char>,structLibrary::AllocFunc>>&&> ( <NoName> ) ;", parse(clang));
}
void cxxStaticCastExpr3() {
const char clang[] = "`-ClassTemplateSpecializationDecl 0xd842d8 <a.cpp:4:3, line:7:3> line:4:21 struct char_traits definition\n"
" |-TemplateArgument type 'char'\n"
" | `-BuiltinType 0xd444c0 'char'\n"
" |-CXXRecordDecl 0xd84500 <col:14, col:21> col:21 implicit struct char_traits\n"
" |-TypedefDecl 0xd845a0 <line:5:7, col:20> col:20 referenced char_type 'char'\n"
" | `-BuiltinType 0xd444c0 'char'\n"
" `-CXXMethodDecl 0xd847b0 <line:6:7, col:80> col:18 assign 'char_traits<char>::char_type *(char_traits<char>::char_type *)'\n"
" |-ParmVarDecl 0xd84670 <col:25, col:36> col:36 used __s 'char_traits<char>::char_type *'\n"
" `-CompoundStmt 0xd848f8 <col:41, col:80>\n"
" `-ReturnStmt 0xd848e8 <col:43, col:77>\n"
" `-CXXStaticCastExpr 0xd848b8 <col:50, col:77> 'char_traits<char>::char_type *' static_cast<char_traits<char>::char_type *> <NoOp>\n"
" `-ImplicitCastExpr 0xd848a0 <col:74> 'char_traits<char>::char_type *' <LValueToRValue> part_of_explicit_cast\n"
" `-DeclRefExpr 0xd84870 <col:74> 'char_traits<char>::char_type *' lvalue ParmVar 0xd84670 '__s' 'char_traits<char>::char_type *'\n";
ASSERT_EQUALS("struct char_traits<char> { typedef char char_type ; char_traits<char>::char_type * assign ( char_traits<char>::char_type * __s@1 ) { return static_cast<char_traits<char>::char_type*> ( __s@1 ) ; } } ;", parse(clang));
}
void cxxStdInitializerListExpr() {
const char clang[] = "`-VarDecl 0x2f92060 <1.cpp:3:1, col:25> col:18 x 'std::vector<int>':'std::vector<int, std::allocator<int> >' listinit\n"
" `-ExprWithCleanups 0x2fb0b40 <col:18, col:25> 'std::vector<int>':'std::vector<int, std::allocator<int> >'\n"
" `-CXXConstructExpr 0x2fb0b00 <col:18, col:25> 'std::vector<int>':'std::vector<int, std::allocator<int> >' 'void (initializer_list<std::vector<int, std::allocator<int> >::value_type>, const std::vector<int, std::allocator<int> >::allocator_type &)' list std::initializer_list\n"
" |-CXXStdInitializerListExpr 0x2fb0928 <col:19, col:25> 'initializer_list<std::vector<int, std::allocator<int> >::value_type>':'std::initializer_list<int>'\n"
" | `-MaterializeTemporaryExpr 0x2fb0910 <col:19, col:25> 'const int [3]' xvalue\n"
" | `-InitListExpr 0x2fb08b8 <col:19, col:25> 'const int [3]'\n"
" | |-IntegerLiteral 0x2f920c0 <col:20> 'int' 1\n"
" | |-IntegerLiteral 0x2f920e0 <col:22> 'int' 2\n"
" | `-IntegerLiteral 0x2f92100 <col:24> 'int' 3\n"
" `-CXXDefaultArgExpr 0x2fb0ae0 <<invalid sloc>> 'const std::vector<int, std::allocator<int> >::allocator_type':'const std::allocator<int>' lvalue";
ASSERT_EQUALS("std :: vector<int> x@1 { 1 , 2 , 3 } ;", parse(clang));
}
void cxxThrowExpr() {
const char clang[] = "`-FunctionDecl 0x3701690 <1.cpp:2:1, col:23> col:6 foo 'void ()'\n"
" `-CompoundStmt 0x37017b0 <col:12, col:23>\n"
" `-CXXThrowExpr 0x3701790 <col:14, col:20> 'void'\n"
" `-IntegerLiteral 0x3701770 <col:20> 'int' 1";
ASSERT_EQUALS("void foo ( ) { throw 1 ; }", parse(clang));
}
void defaultStmt() {
const char clang[] = "`-FunctionDecl 0x18476b8 <1.c:3:1, line:9:1> line:3:5 foo 'int (int)'\n"
" |-ParmVarDecl 0x18475e0 <col:9, col:13> col:13 used rc 'int'\n"
" `-CompoundStmt 0x1847868 <line:4:1, line:9:1>\n"
" `-SwitchStmt 0x18477e0 <line:5:3, line:8:3>\n"
" |-ImplicitCastExpr 0x18477c8 <line:5:10> 'int' <LValueToRValue>\n"
" | `-DeclRefExpr 0x18477a8 <col:10> 'int' lvalue ParmVar 0x18475e0 'rc' 'int'\n"
" `-CompoundStmt 0x1847850 <col:14, line:8:3>\n"
" `-DefaultStmt 0x1847830 <line:6:3, line:7:12>\n"
" `-ReturnStmt 0x1847820 <col:5, col:12>\n"
" `-IntegerLiteral 0x1847800 <col:12> 'int' 1";
ASSERT_EQUALS("int foo ( int rc@1 ) { switch ( rc@1 ) { default : return 1 ; } }", parse(clang));
}
void doStmt() {
const char clang[] = "`-FunctionDecl 0x27fbbc8 <a.cpp:2:1, col:34> col:6 foo 'void ()'\n"
" `-CompoundStmt 0x27fbd08 <col:12, col:34>\n"
" `-DoStmt 0x27fbce8 <col:14, col:31>\n"
" |-CompoundStmt 0x27fbcb0 <col:17, col:22>\n"
" | `-UnaryOperator 0x27fbc90 <col:18, col:19> 'int' postfix '++'\n"
" | `-DeclRefExpr 0x27fbc68 <col:18> 'int' lvalue Var 0x27fbae0 'x' 'int'\n"
" `-IntegerLiteral 0x27fbcc8 <col:30> 'int' 1";
ASSERT_EQUALS("void foo ( ) { do { ++ x ; } while ( 1 ) ; }", parse(clang));
}
void enumDecl1() {
const char clang[] = "`-EnumDecl 0x2660660 <a.cpp:3:1, col:16> col:6 referenced abc\n"
" |-EnumConstantDecl 0x2660720 <col:11> col:11 referenced a 'abc'\n"
" |-EnumConstantDecl 0x2660768 <col:13> col:13 b 'abc'\n"
" `-EnumConstantDecl 0x26607b0 <col:15> col:15 c 'abc'";
ASSERT_EQUALS("enum abc { a , b , c }", parse(clang));
}
void enumDecl2() {
const char clang[] = "`-EnumDecl 0xb55d50 <2.cpp:4:3, col:44> col:8 syntax_option_type 'unsigned int'";
ASSERT_EQUALS("enum syntax_option_type : unsigned int { }", parse(clang));
}
void enumDecl3() {
const char clang[] = "|-EnumDecl 0x1586e48 <2.cpp:1:3, line:5:3> line:1:8 __syntax_option\n"
"| |-EnumConstantDecl 0x1586f18 <line:3:5> col:5 referenced _S_polynomial '__syntax_option'\n"
"| `-EnumConstantDecl 0x1586f68 <line:4:5> col:5 _S_syntax_last '__syntax_option'";
ASSERT_EQUALS("enum __syntax_option { _S_polynomial , _S_syntax_last }", parse(clang));
}
void enumDecl4() {
const char clang[] = "|-EnumDecl 0xace1f8 <e1.cpp:3:1, col:51> col:1\n"
"| |-EnumConstantDecl 0xace2c8 <col:7> col:7 A '(anonymous enum at e1.cpp:3:1)'\n"
"| |-EnumConstantDecl 0xace318 <col:16> col:16 B '(anonymous enum at e1.cpp:3:1)'\n"
"| `-EnumConstantDecl 0xace3b8 <col:46> col:46 referenced C '(anonymous enum at e1.cpp:3:1)'\n"
"`-VarDecl 0xace470 <col:1, col:66> col:53 x 'enum (anonymous enum at e1.cpp:3:1)':'(anonymous enum at e1.cpp:3:1)' cinit\n"
" `-DeclRefExpr 0xace520 <col:66> '(anonymous enum at e1.cpp:3:1)' EnumConstant 0xace3b8 'C' '(anonymous enum at e1.cpp:3:1)'";
ASSERT_EQUALS("enum { A , B , C } x@1 = C ;", parse(clang));
}
void forStmt() {
const char clang[] = "`-FunctionDecl 0x2f93ae0 <1.c:1:1, col:56> col:5 main 'int ()'\n"
" `-CompoundStmt 0x2f93dc0 <col:12, col:56>\n"
" |-ForStmt 0x2f93d50 <col:14, col:44>\n"
" | |-DeclStmt 0x2f93c58 <col:19, col:28>\n"
" | | `-VarDecl 0x2f93bd8 <col:19, col:27> col:23 used i 'int' cinit\n"
" | | `-IntegerLiteral 0x2f93c38 <col:27> 'int' 0\n"
" | |-<<<NULL>>>\n"
" | |-BinaryOperator 0x2f93cd0 <col:30, col:34> 'int' '<'\n"
" | | |-ImplicitCastExpr 0x2f93cb8 <col:30> 'int' <LValueToRValue>\n"
" | | | `-DeclRefExpr 0x2f93c70 <col:30> 'int' lvalue Var 0x2f93bd8 'i' 'int'\n"
" | | `-IntegerLiteral 0x2f93c98 <col:34> 'int' 10\n"
" | |-UnaryOperator 0x2f93d20 <col:38, col:39> 'int' postfix '++'\n"
" | | `-DeclRefExpr 0x2f93cf8 <col:38> 'int' lvalue Var 0x2f93bd8 'i' 'int'\n"
" | `-CompoundStmt 0x2f93d40 <col:43, col:44>\n"
" `-ReturnStmt 0x2f93da8 <col:46, col:53>\n"
" `-IntegerLiteral 0x2f93d88 <col:53> 'int' 0";
ASSERT_EQUALS("int main ( ) { for ( int i@1 = 0 ; i@1 < 10 ; ++ i@1 ) { } return 0 ; }", parse(clang));
}
void funcdecl1() {
const char clang[] = "`-FunctionDecl 0x3122c30 <1.c:1:1, col:22> col:6 foo 'void (int, int)'\n"
" |-ParmVarDecl 0x3122ae0 <col:10, col:14> col:14 x 'int'\n"
" `-ParmVarDecl 0x3122b58 <col:17, col:21> col:21 y 'int'";
ASSERT_EQUALS("void foo ( int x@1 , int y@2 ) ;", parse(clang));
}
void funcdecl2() {
const char clang[] = "`-FunctionDecl 0x24b2c38 <1.c:1:1, line:4:1> line:1:5 foo 'int (int, int)'\n"
" |-ParmVarDecl 0x24b2ae0 <col:9, col:13> col:13 used x 'int'\n"
" |-ParmVarDecl 0x24b2b58 <col:16, col:20> col:20 used y 'int'\n"
" `-CompoundStmt 0x24b2de8 <line:2:1, line:4:1>\n"
" `-ReturnStmt 0x24b2dd0 <line:3:5, col:16>\n"
" `-BinaryOperator 0x24b2da8 <col:12, col:16> 'int' '/'\n"
" |-ImplicitCastExpr 0x24b2d78 <col:12> 'int' <LValueToRValue>\n"
" | `-DeclRefExpr 0x24b2d28 <col:12> 'int' lvalue ParmVar 0x24b2ae0 'x' 'int'\n"
" `-ImplicitCastExpr 0x24b2d90 <col:16> 'int' <LValueToRValue>\n"
" `-DeclRefExpr 0x24b2d50 <col:16> 'int' lvalue ParmVar 0x24b2b58 'y' 'int'";
ASSERT_EQUALS("int foo ( int x@1 , int y@2 ) { return x@1 / y@2 ; }", parse(clang));
}
void funcdecl3() {
const char clang[] = "|-FunctionDecl 0x27cb6b8 <a.cpp:865:1, col:35> col:12 __overflow 'int (FILE *, int)' extern\n"
"| |-ParmVarDecl 0x27cb528 <col:24, col:29> col:30 'FILE *'\n"
"| `-ParmVarDecl 0x27cb5a0 <col:32> col:35 'int'";
ASSERT_EQUALS("int __overflow ( FILE * , int ) ;", parse(clang));
}
void funcdecl4() {
const char clang[] = "|-FunctionDecl 0x272bb60 <a.cpp:658:15> col:15 implicit fwrite 'unsigned long (const void *, unsigned long, unsigned long, FILE *)' extern\n"
"| |-ParmVarDecl 0x272cc40 <<invalid sloc>> <invalid sloc> 'const void *'\n"
"| |-ParmVarDecl 0x272cca0 <<invalid sloc>> <invalid sloc> 'unsigned long'\n"
"| |-ParmVarDecl 0x272cd00 <<invalid sloc>> <invalid sloc> 'unsigned long'\n"
"| `-ParmVarDecl 0x272cd60 <<invalid sloc>> <invalid sloc> 'FILE *'";
ASSERT_EQUALS("unsigned long fwrite ( const void * , unsigned long , unsigned long , FILE * ) ;", parse(clang));
}
void funcdecl5() {
const char clang[] = "`-FunctionDecl 0x59d670 <1.c:1:1, col:28> col:20 foo 'void (void)' static inline";
ASSERT_EQUALS("static inline void foo ( ) ;", parse(clang));
}
void funcdecl6() {
const char clang[] = "`-FunctionDecl 0x196eea8 <1.cpp:3:5, col:27> col:12 foo 'void **(int)'\n"
" `-ParmVarDecl 0x196eda0 <col:17, col:21> col:21 count 'int'";
ASSERT_EQUALS("void * * foo ( int count@1 ) ;", parse(clang));
}
void functionTemplateDecl1() {
const char clang[] = "`-FunctionTemplateDecl 0x3242860 <a.cpp:1:1, col:46> col:21 foo";
ASSERT_EQUALS("", parse(clang));
}
void functionTemplateDecl2() {
const char clang[] = "|-FunctionTemplateDecl 0x333a860 <a.cpp:1:1, col:46> col:21 foo\n"
"| |-TemplateTypeParmDecl 0x333a5f8 <col:10, col:16> col:16 referenced class depth 0 index 0 T\n"
"| |-FunctionDecl 0x333a7c0 <col:19, col:46> col:21 foo 'T (T)'\n"
"| | |-ParmVarDecl 0x333a6c0 <col:25, col:27> col:27 referenced t 'T'\n"
"| | `-CompoundStmt 0x333a980 <col:30, col:46>\n"
"| | `-ReturnStmt 0x333a968 <col:32, col:43>\n"
"| | `-BinaryOperator 0x333a940 <col:39, col:43> '<dependent type>' '+'\n"
"| | |-DeclRefExpr 0x333a8f8 <col:39> 'T' lvalue ParmVar 0x333a6c0 't' 'T'\n"
"| | `-IntegerLiteral 0x333a920 <col:43> 'int' 1\n"
"| `-FunctionDecl 0x333ae00 <col:19, col:46> col:21 used foo 'int (int)'\n"
"| |-TemplateArgument type 'int'\n"
"| |-ParmVarDecl 0x333ad00 <col:25, col:27> col:27 used t 'int':'int'\n"
"| `-CompoundStmt 0x333b0a8 <col:30, col:46>\n"
"| `-ReturnStmt 0x333b090 <col:32, col:43>\n"
"| `-BinaryOperator 0x333b068 <col:39, col:43> 'int' '+'\n"
"| |-ImplicitCastExpr 0x333b050 <col:39> 'int':'int' <LValueToRValue>\n"
"| | `-DeclRefExpr 0x333b028 <col:39> 'int':'int' lvalue ParmVar 0x333ad00 't' 'int':'int'\n"
"| `-IntegerLiteral 0x333a920 <col:43> 'int' 1\n"
"`-FunctionDecl 0x333a9f8 <line:2:1, col:22> col:1 invalid bar 'int ()'\n"
" `-CompoundStmt 0x333b010 <col:7, col:22>\n"
" `-CallExpr 0x333afe0 <col:9, col:19> 'int':'int'\n"
" |-ImplicitCastExpr 0x333afc8 <col:9, col:16> 'int (*)(int)' <FunctionToPointerDecay>\n"
" | `-DeclRefExpr 0x333af00 <col:9, col:16> 'int (int)' lvalue Function 0x333ae00 'foo' 'int (int)' (FunctionTemplate 0x333a860 'foo')\n"
" `-IntegerLiteral 0x333ab48 <col:18> 'int' 1";
ASSERT_EQUALS("int foo<int> ( int t@1 ) { return t@1 + 1 ; } int bar ( ) { foo ( 1 ) ; }", parse(clang));
}
void ifelse() {
const char clang[] = "`-FunctionDecl 0x2637ba8 <1.c:1:1, line:4:1> line:1:5 foo 'int (int)'\n"
" |-ParmVarDecl 0x2637ae0 <col:9, col:13> col:13 used x 'int'\n"
" `-CompoundStmt 0x2637d70 <col:16, line:4:1>\n"
" `-IfStmt 0x2637d38 <line:2:5, line:3:11>\n"
" |-<<<NULL>>>\n"
" |-<<<NULL>>>\n"
" |-BinaryOperator 0x2637cf0 <line:2:9, col:13> 'int' '>'\n"
" | |-ImplicitCastExpr 0x2637cd8 <col:9> 'int' <LValueToRValue>\n"
" | | `-DeclRefExpr 0x2637c90 <col:9> 'int' lvalue ParmVar 0x2637ae0 'x' 'int'\n"
" | `-IntegerLiteral 0x2637cb8 <col:13> 'int' 10\n"
" |-CompoundStmt 0x2637d18 <col:17, col:18>\n"
" `-CompoundStmt 0x2637d28 <line:3:10, col:11>";
ASSERT_EQUALS("int foo ( int x@1 ) { if ( x@1 > 10 ) { } else { } }", parse(clang));
}
void ifStmt() {
// Clang 8 in cygwin
const char clang[] = "`-FunctionDecl 0x41d0690 <2.cpp:1:1, col:24> col:6 foo 'void ()'\n"
" `-CompoundStmt 0x41d07f0 <col:12, col:24>\n"
" `-IfStmt 0x41d07b8 <col:14, col:22>\n"
" |-ImplicitCastExpr 0x41d0790 <col:18> 'bool' <IntegralToBoolean>\n"
" | `-IntegerLiteral 0x41d0770 <col:18> 'int' 1\n"
" |-CompoundStmt 0x41d07a8 <col:21, col:22>\n";
ASSERT_EQUALS("void foo ( ) { if ( 1 ) { } }", parse(clang));
}
void initListExpr() {
const char clang[] = "|-VarDecl 0x397c680 <1.cpp:2:1, col:26> col:11 used ints 'const int [3]' cinit\n"
"| `-InitListExpr 0x397c7d8 <col:20, col:26> 'const int [3]'\n"
"| |-IntegerLiteral 0x397c720 <col:21> 'int' 1\n"
"| |-IntegerLiteral 0x397c740 <col:23> 'int' 2\n"
"| `-IntegerLiteral 0x397c760 <col:25> 'int' 3";
ASSERT_EQUALS("const int [3] ints@1 = { 1 , 2 , 3 } ;", parse(clang));
}
void labelStmt() {
const char clang[] = "`-FunctionDecl 0x2ed1ba0 <1.c:1:1, col:36> col:6 foo 'void (int)'\n"
" `-CompoundStmt 0x2ed1d00 <col:17, col:36>\n"
" `-LabelStmt 0x2ed1ce8 <col:19, col:30> 'loop'\n"
" `-GotoStmt 0x2ed1cd0 <col:25, col:30> 'loop' 0x2ed1c88";
ASSERT_EQUALS("void foo ( ) { loop : goto loop ; }", parse(clang));
}
void memberExpr() {
// C code:
// struct S { int x };
// int foo(struct S s) { return s.x; }
const char clang[] = "|-RecordDecl 0x2441a88 <1.c:1:1, col:18> col:8 struct S definition\n"
"| `-FieldDecl 0x2441b48 <col:12, col:16> col:16 referenced x 'int'\n"
"`-FunctionDecl 0x2441cf8 <line:2:1, col:35> col:5 foo 'int (struct S)'\n"
" |-ParmVarDecl 0x2441be8 <col:9, col:18> col:18 used s 'struct S':'struct S'\n"
" `-CompoundStmt 0x2441e70 <col:21, col:35>\n"
" `-ReturnStmt 0x2441e58 <col:23, col:32>\n"
" `-ImplicitCastExpr 0x2441e40 <col:30, col:32> 'int' <LValueToRValue>\n"
" `-MemberExpr 0x2441e08 <col:30, col:32> 'int' lvalue .x 0x2441b48\n"
" `-DeclRefExpr 0x2441de0 <col:30> 'struct S':'struct S' lvalue ParmVar 0x2441be8 's' 'struct S':'struct S'";
ASSERT_EQUALS("struct S { int x@1 ; } ; int foo ( struct S s@2 ) { return s@2 . x@1 ; }",
parse(clang));
}
void namespaceDecl1() {
const char clang[] = "`-NamespaceDecl 0x2e5f658 <hello.cpp:1:1, col:24> col:11 x\n"
" `-VarDecl 0x2e5f6d8 <col:15, col:19> col:19 var 'int'";
ASSERT_EQUALS("namespace x { int var@1 ; }",
parse(clang));
}
void namespaceDecl2() {
const char clang[] = "`-NamespaceDecl 0x1753e60 <1.cpp:1:1, line:4:1> line:1:11 std\n"
" |-VisibilityAttr 0x1753ed0 <col:31, col:56> Default\n"
" `-VarDecl 0x1753f40 <line:3:5, col:9> col:9 x 'int'";
ASSERT_EQUALS("namespace std { int x@1 ; }",
parse(clang));
}
void recordDecl1() {
const char clang[] = "`-RecordDecl 0x354eac8 <1.c:1:1, line:4:1> line:1:8 struct S definition\n"
" |-FieldDecl 0x354eb88 <line:2:3, col:7> col:7 x 'int'\n"
" `-FieldDecl 0x354ebe8 <line:3:3, col:7> col:7 y 'int'";
ASSERT_EQUALS("struct S { int x@1 ; int y@2 ; } ;",
parse(clang));
}
void recordDecl2() {
const char clang[] = "`-RecordDecl 0x3befac8 <2.c:2:1, col:22> col:1 struct definition\n"
" `-FieldDecl 0x3befbf0 <col:10, col:19> col:14 val 'int'";
ASSERT_EQUALS("struct { int val@1 ; } ;",
parse(clang));
}
void switchStmt() {
const char clang[] = "`-FunctionDecl 0x2796ba0 <1.c:1:1, col:35> col:6 foo 'void (int)'\n"
" |-ParmVarDecl 0x2796ae0 <col:10, col:14> col:14 used x 'int'\n"
" `-CompoundStmt 0x2796d18 <col:17, col:35>\n"
" |-SwitchStmt 0x2796cc8 <col:19, col:32>\n"
" | |-<<<NULL>>>\n"
" | |-<<<NULL>>>\n"
" | |-ImplicitCastExpr 0x2796cb0 <col:27> 'int' <LValueToRValue>\n"
" | | `-DeclRefExpr 0x2796c88 <col:27> 'int' lvalue ParmVar 0x2796ae0 'x' 'int'\n"
" | `-CompoundStmt 0x2796cf8 <col:30, col:32>\n"
" `-NullStmt 0x2796d08 <col:33>";
ASSERT_EQUALS("void foo ( int x@1 ) { switch ( x@1 ) { } ; }",
parse(clang));
}
void typedefDeclPrologue()
{
// these TypedefDecl are included in *any* AST dump and we should ignore them as they should not be of interest to us
// see https://github.com/llvm/llvm-project/issues/120228#issuecomment-2549212109 for an explanation
const char clang[] =
"TranslationUnitDecl 0x60efd80ef9f8 <<invalid sloc>> <invalid sloc>\n"
"|-TypedefDecl 0x60efd80f0228 <<invalid sloc>> <invalid sloc> implicit __int128_t '__int128'\n"
"| `-BuiltinType 0x60efd80effc0 '__int128'\n"
"|-TypedefDecl 0x60efd80f0298 <<invalid sloc>> <invalid sloc> implicit __uint128_t 'unsigned __int128'\n"
"| `-BuiltinType 0x60efd80effe0 'unsigned __int128'\n"
"|-TypedefDecl 0x60efd80f05a0 <<invalid sloc>> <invalid sloc> implicit __NSConstantString 'struct __NSConstantString_tag'\n"
"| `-RecordType 0x60efd80f0370 'struct __NSConstantString_tag'\n"
"| `-Record 0x60efd80f02f0 '__NSConstantString_tag'\n"
"|-TypedefDecl 0x60efd80f0648 <<invalid sloc>> <invalid sloc> implicit __builtin_ms_va_list 'char *'\n"
"| `-PointerType 0x60efd80f0600 'char *'\n"
"| `-BuiltinType 0x60efd80efaa0 'char'\n"
"|-TypedefDecl 0x60efd80f0940 <<invalid sloc>> <invalid sloc> implicit __builtin_va_list 'struct __va_list_tag[1]'\n"
"| `-ConstantArrayType 0x60efd80f08e0 'struct __va_list_tag[1]' 1\n"
"| `-RecordType 0x60efd80f0720 'struct __va_list_tag'\n"
"| `-Record 0x60efd80f06a0 '__va_list_tag'\n"
"`-FunctionDecl 0x60efd8151470 <a.cpp:1:1, line:3:1> line:1:6 f 'void ()'\n"
"`-CompoundStmt 0x60efd8151560 <line:2:1, line:3:1>\n";
ASSERT_EQUALS("void f ( ) ;", parse(clang));
}
void unaryExprOrTypeTraitExpr1() {
const char clang[] = "`-VarDecl 0x24cc610 <a.cpp:1:1, col:19> col:5 x 'int' cinit\n"
" `-ImplicitCastExpr 0x24cc6e8 <col:9, col:19> 'int' <IntegralCast>\n"
" `-UnaryExprOrTypeTraitExpr 0x24cc6c8 <col:9, col:19> 'unsigned long' sizeof 'int'\n";
ASSERT_EQUALS("int x@1 = sizeof ( int ) ;", parse(clang));
}
void unaryExprOrTypeTraitExpr2() {
const char clang[] = "`-VarDecl 0x27c6c00 <a.cpp:3:5, col:23> col:9 x 'int' cinit\n"
" `-ImplicitCastExpr 0x27c6cc8 <col:13, col:23> 'int' <IntegralCast>\n"
" `-UnaryExprOrTypeTraitExpr 0x27c6ca8 <col:13, col:23> 'unsigned long' sizeof\n"
" `-ParenExpr 0x27c6c88 <col:19, col:23> 'char [10]' lvalue\n"
" `-DeclRefExpr 0x27c6c60 <col:20> 'char [10]' lvalue Var 0x27c6b48 'buf' 'char [10]'";
ASSERT_EQUALS("int x@1 = sizeof ( buf ) ;", parse(clang));
}
void unaryOperator() {
const char clang[] = "`-FunctionDecl 0x2dd9748 <1.cpp:2:1, col:44> col:5 foo 'int (int *)'\n"
" |-ParmVarDecl 0x2dd9680 <col:14, col:19> col:19 used p 'int *'\n"
" `-CompoundStmt 0x2dd9908 <col:22, col:44>\n"
" `-ReturnStmt 0x2dd98f0 <col:24, col:41>\n"
" `-BinaryOperator 0x2dd98c8 <col:31, col:41> 'int' '/'\n"
" |-IntegerLiteral 0x2dd9830 <col:31> 'int' 100000\n"
" `-ImplicitCastExpr 0x2dd98b0 <col:40, col:41> 'int' <LValueToRValue>\n"
" `-UnaryOperator 0x2dd9890 <col:40, col:41> 'int' lvalue prefix '*' cannot overflow\n"
" `-ImplicitCastExpr 0x2dd9878 <col:41> 'int *' <LValueToRValue>\n"
" `-DeclRefExpr 0x2dd9850 <col:41> 'int *' lvalue ParmVar 0x2dd9680 'p' 'int *'";
ASSERT_EQUALS("int foo ( int * p@1 ) { return 100000 / * p@1 ; }", parse(clang));
}
void vardecl1() {
const char clang[] = "|-VarDecl 0x32b8aa0 <1.c:1:1, col:9> col:5 used a 'int' cinit\n"
"| `-IntegerLiteral 0x32b8b40 <col:9> 'int' 1\n"
"`-VarDecl 0x32b8b78 <line:2:1, col:9> col:5 b 'int' cinit\n"
" `-ImplicitCastExpr 0x32b8c00 <col:9> 'int' <LValueToRValue>\n"
" `-DeclRefExpr 0x32b8bd8 <col:9> 'int' lvalue Var 0x32b8aa0 'a' 'int'";
ASSERT_EQUALS("int a@1 = 1 ; int b@2 = a@1 ;",
parse(clang));
}
void vardecl2() {
const char clang[] = "|-VarDecl 0x3873b50 <1.c:1:1, col:9> col:5 used a 'int [10]'\n"
"`-FunctionDecl 0x3873c38 <line:3:1, line:6:1> line:3:6 foo 'void ()'\n"
" `-CompoundStmt 0x3873dd0 <line:4:1, line:6:1>\n"
" `-BinaryOperator 0x3873da8 <line:5:3, col:10> 'int' '='\n"
" |-ArraySubscriptExpr 0x3873d60 <col:3, col:6> 'int' lvalue\n"
" | |-ImplicitCastExpr 0x3873d48 <col:3> 'int *' <ArrayToPointerDecay>\n"
" | | `-DeclRefExpr 0x3873cd8 <col:3> 'int [10]' lvalue Var 0x3873b50 'a' 'int [10]'\n"
" | `-IntegerLiteral 0x3873d00 <col:5> 'int' 0\n"
" `-IntegerLiteral 0x3873d88 <col:10> 'int' 0\n";
ASSERT_EQUALS("int [10] a@1 ; void foo ( ) { a@1 [ 0 ] = 0 ; }",
parse(clang));
}
void vardecl3() {
const char clang[] = "`-VarDecl 0x25a8aa0 <1.c:1:1, col:12> col:12 p 'const int *'";
ASSERT_EQUALS("const int * p@1 ;", parse(clang));
}
void vardecl4() {
const char clang[] = "|-VarDecl 0x23d6c78 <a.cpp:137:1, col:14> col:14 stdin 'FILE *' extern";
ASSERT_EQUALS("FILE * stdin@1 ;", parse(clang));
}
void vardecl5() {
const char clang[] = "|-VarDecl 0x2e31fc0 <a.cpp:27:1, col:38> col:26 sys_errlist 'const char *const []' extern";
ASSERT_EQUALS("const char * const [] sys_errlist@1 ;", parse(clang));
}
void vardecl6() {
const char clang[] = "`-VarDecl 0x278e170 <1.c:1:1, col:16> col:12 x 'int' static cinit\n"
" `-IntegerLiteral 0x278e220 <col:16> 'int' 3";
ASSERT_EQUALS("static int x@1 = 3 ;", parse(clang));
}
void vardecl7() {
const char clang[] = "`-VarDecl 0x2071f20 <1.cpp:2:1, col:23> col:9 start 'void *(*)(void *)'";
ASSERT_EQUALS("void * * start@1 ;", parse(clang));
}
void whileStmt1() {
const char clang[] = "`-FunctionDecl 0x3d45b18 <1.c:1:1, line:3:1> line:1:6 foo 'void ()'\n"
" `-CompoundStmt 0x3d45c48 <col:12, line:3:1>\n"
" `-WhileStmt 0x3d45c28 <line:2:5, col:14>\n"
" |-<<<NULL>>>\n"
" |-IntegerLiteral 0x3d45bf8 <col:12> 'int' 0\n"
" `-NullStmt 0x3d45c18 <col:14>";
ASSERT_EQUALS("void foo ( ) { while ( 0 ) { ; } }",
parse(clang));
}
void whileStmt2() {
// clang 9
const char clang[] = "`-FunctionDecl 0x1c99ac8 <1.cpp:1:1, col:27> col:6 foo 'void ()'\n"
" `-CompoundStmt 0x1c99c10 <col:12, col:27>\n"
" `-WhileStmt 0x1c99bf8 <col:14, col:25>\n"
" |-ImplicitCastExpr 0x1c99bd0 <col:21> 'bool' <IntegralToBoolean>\n"
" | `-IntegerLiteral 0x1c99bb0 <col:21> 'int' 1\n"
" `-CompoundStmt 0x1c99be8 <col:24, col:25>";
ASSERT_EQUALS("void foo ( ) { while ( 1 ) { } }", parse(clang));
}
#define GET_SYMBOL_DB(AST) \
const Settings settings = settingsBuilder().clang().platform(Platform::Type::Unix64).build(); \
Tokenizer tokenizer(settings, *this); \
{ \
std::istringstream istr(AST); \
clangimport::parseClangAstDump(tokenizer, istr); \
} \
const SymbolDatabase *db = tokenizer.getSymbolDatabase(); \
ASSERT(db)
void tokenIndex() {
const char clang[] = "`-FunctionDecl 0x1e07dd0 <67.cpp:1:1, col:13> col:6 foo 'void ()'\n"
" `-CompoundStmt 0x1e07eb8 <col:12, col:13>";
ASSERT_EQUALS("void foo ( ) { }", parse(clang));
GET_SYMBOL_DB(clang);
const Token *tok = tokenizer.tokens();
ASSERT_EQUALS(tok->index() + 1, tok->next()->index());
}
void symbolDatabaseEnum1() {
const char clang[] = "|-NamespaceDecl 0x29ad5f8 <1.cpp:1:1, line:3:1> line:1:11 ns\n"
"| `-EnumDecl 0x29ad660 <line:2:1, col:16> col:6 referenced abc\n"
"| |-EnumConstantDecl 0x29ad720 <col:11> col:11 a 'ns::abc'\n"
"| |-EnumConstantDecl 0x29ad768 <col:13> col:13 b 'ns::abc'\n"
"| `-EnumConstantDecl 0x29ad7b0 <col:15> col:15 referenced c 'ns::abc'\n"
"`-VarDecl 0x29ad898 <line:5:1, col:22> col:9 x 'ns::abc':'ns::abc' cinit\n"
" `-DeclRefExpr 0x29ad998 <col:13, col:22> 'ns::abc' EnumConstant 0x29ad7b0 'c' 'ns::abc'\n";
ASSERT_EQUALS("namespace ns { enum abc { a , b , c } } ns :: abc x@1 = c ;", parse(clang));
GET_SYMBOL_DB(clang);
// Enum scope and type
ASSERT_EQUALS(3, db->scopeList.size());
const Scope &enumScope = db->scopeList.back();
ASSERT_EQUALS(Scope::ScopeType::eEnum, enumScope.type);
ASSERT_EQUALS("abc", enumScope.className);
const Type *enumType = enumScope.definedType;
ASSERT_EQUALS("abc", enumType->name());
// Variable
const Token *vartok = Token::findsimplematch(tokenizer.tokens(), "x");
ASSERT(vartok);
ASSERT(vartok->variable());
ASSERT(vartok->variable()->valueType());
ASSERT_EQUALS(uintptr_t(&enumScope), uintptr_t(vartok->variable()->valueType()->typeScope));
}
void symbolDatabaseFunction1() {
const char clang[] = "|-FunctionDecl 0x3aea7a0 <1.cpp:2:1, col:22> col:6 used foo 'void (int, int)'\n"
" |-ParmVarDecl 0x3aea650 <col:10, col:14> col:14 x 'int'\n"
" |-ParmVarDecl 0x3aea6c8 <col:17, col:21> col:21 y 'int'\n"
" `-CompoundStmt 0x3d45c48 <col:12>\n";
GET_SYMBOL_DB(clang);
// There is a function foo that has 2 arguments
ASSERT_EQUALS(1, db->functionScopes.size());
const Scope *scope = db->functionScopes[0];
const Function *func = scope->function;
ASSERT_EQUALS(2, func->argCount());
ASSERT_EQUALS("x", func->getArgumentVar(0)->name());
ASSERT_EQUALS("y", func->getArgumentVar(1)->name());
ASSERT_EQUALS(ValueType::Type::INT, func->getArgumentVar(0)->valueType()->type);
ASSERT_EQUALS(ValueType::Type::INT, func->getArgumentVar(1)->valueType()->type);
}
void symbolDatabaseFunction2() {
const char clang[] = "|-FunctionDecl 0x3aea7a0 <1.cpp:2:1, col:22> col:6 used foo 'void (int, int)'\n"
"| |-ParmVarDecl 0x3aea650 <col:10, col:14> col:14 'int'\n"
"| |-ParmVarDecl 0x3aea6c8 <col:17, col:21> col:21 'int'\n"
" `-CompoundStmt 0x3d45c48 <col:12>\n";
GET_SYMBOL_DB(clang);
// There is a function foo that has 2 arguments
ASSERT_EQUALS(1, db->functionScopes.size());
const Scope *scope = db->functionScopes[0];
const Function *func = scope->function;
ASSERT_EQUALS(2, func->argCount());
ASSERT_EQUALS(0, (long long)func->getArgumentVar(0)->nameToken());
ASSERT_EQUALS(0, (long long)func->getArgumentVar(1)->nameToken());
}
void symbolDatabaseFunction3() { // #9640
const char clang[] = "`-FunctionDecl 0x238fcd8 <9640.cpp:1:1, col:26> col:6 used bar 'bool (const char, int &)'\n"
" |-ParmVarDecl 0x238fb10 <col:10, col:16> col:20 'const char'\n"
" |-ParmVarDecl 0x238fbc0 <col:22, col:25> col:26 'int &'\n"
" `-CompoundStmt 0x3d45c48 <col:12>\n";
GET_SYMBOL_DB(clang);
// There is a function foo that has 2 arguments
ASSERT_EQUALS(1, db->functionScopes.size());
const Scope *scope = db->functionScopes[0];
const Function *func = scope->function;
ASSERT_EQUALS(2, func->argCount());
ASSERT_EQUALS(false, func->getArgumentVar(0)->isReference());
ASSERT_EQUALS(true, func->getArgumentVar(1)->isReference());
}
void symbolDatabaseFunctionConst() {
const char clang[] = "`-CXXRecordDecl 0x7e2d98 <1.cpp:2:1, line:5:1> line:2:7 class foo definition\n"
" `-CXXMethodDecl 0x7e3000 <line:4:3, col:12> col:8 f 'void () const'";
GET_SYMBOL_DB(clang);
// There is a function f that is const
ASSERT_EQUALS(2, db->scopeList.size());
ASSERT_EQUALS(1, db->scopeList.back().functionList.size());
const Function &func = db->scopeList.back().functionList.back();
ASSERT(func.isConst());
}
void symbolDatabaseVariableRef() {
const char clang[] = "`-FunctionDecl 0x1593df0 <3.cpp:1:1, line:4:1> line:1:6 foo 'void ()'\n"
" `-CompoundStmt 0x15940b0 <col:12, line:4:1>\n"
" |-DeclStmt 0x1593f58 <line:2:3, col:8>\n"
" | `-VarDecl 0x1593ef0 <col:3, col:7> col:7 used x 'int'\n"
" `-DeclStmt 0x1594098 <line:3:3, col:15>\n"
" `-VarDecl 0x1593fb8 <col:3, col:14> col:8 ref 'int &' cinit\n"
" `-DeclRefExpr 0x1594020 <col:14> 'int' lvalue Var 0x1593ef0 'x' 'int'";
GET_SYMBOL_DB(clang);
const Variable *refVar = db->variableList().back();
ASSERT(refVar->isReference());
}
void symbolDatabaseVariableRRef() {
const char clang[] = "`-FunctionDecl 0x1a40df0 <3.cpp:1:1, line:4:1> line:1:6 foo 'void ()'\n"
" `-CompoundStmt 0x1a41180 <col:12, line:4:1>\n"
" |-DeclStmt 0x1a40f58 <line:2:3, col:8>\n"
" | `-VarDecl 0x1a40ef0 <col:3, col:7> col:7 used x 'int'\n"
" `-DeclStmt 0x1a41168 <line:3:3, col:18>\n"
" `-VarDecl 0x1a40fb8 <col:3, col:17> col:9 ref 'int &&' cinit\n"
" `-ExprWithCleanups 0x1a410f8 <col:15, col:17> 'int' xvalue\n"
" `-MaterializeTemporaryExpr 0x1a41098 <col:15, col:17> 'int' xvalue extended by Var 0x1a40fb8 'ref' 'int &&'\n"
" `-BinaryOperator 0x1a41078 <col:15, col:17> 'int' '+'\n"
" |-ImplicitCastExpr 0x1a41060 <col:15> 'int' <LValueToRValue>\n"
" | `-DeclRefExpr 0x1a41020 <col:15> 'int' lvalue Var 0x1a40ef0 'x' 'int'\n"
" `-IntegerLiteral 0x1a41040 <col:17> 'int' 1\n";
ASSERT_EQUALS("void foo ( ) { int x@1 ; int && ref@2 = x@1 + 1 ; }", parse(clang));
GET_SYMBOL_DB(clang);
const Variable *refVar = db->variableList().back();
ASSERT(refVar->isReference());
ASSERT(refVar->isRValueReference());
}
void symbolDatabaseVariablePointerRef() {
const char clang[] = "`-FunctionDecl 0x9b4f10 <3.cpp:1:1, col:17> col:6 used foo 'void (int *&)'\n"
" `-ParmVarDecl 0x9b4e40 <col:10, col:16> col:16 p 'int *&'\n";
ASSERT_EQUALS("void foo ( int * & p@1 ) ;", parse(clang));
GET_SYMBOL_DB(clang);
const Variable *p = db->variableList().back();
ASSERT(p->isPointer());
ASSERT(p->isReference());
}
void symbolDatabaseNodeType1() {
const char clang[] = "`-FunctionDecl 0x32438c0 <a.cpp:5:1, line:7:1> line:5:6 foo 'a::b (a::b)'\n"
" |-ParmVarDecl 0x32437b0 <col:10, col:15> col:15 used i 'a::b':'long'\n"
" `-CompoundStmt 0x3243a60 <col:18, line:7:1>\n"
" `-ReturnStmt 0x3243a48 <line:6:3, col:12>\n"
" `-BinaryOperator 0x3243a20 <col:10, col:12> 'long' '+'\n"
" |-ImplicitCastExpr 0x32439f0 <col:10> 'a::b':'long' <LValueToRValue>\n"
" | `-DeclRefExpr 0x32439a8 <col:10> 'a::b':'long' lvalue ParmVar 0x32437b0 'i' 'a::b':'long'\n"
" `-ImplicitCastExpr 0x3243a08 <col:12> 'long' <IntegralCast>\n"
" `-IntegerLiteral 0x32439d0 <col:12> 'int' 1\n";
GET_SYMBOL_DB(clang);
const Token *tok = Token::findsimplematch(tokenizer.tokens(), "i + 1");
ASSERT(!!tok);
ASSERT(!!tok->valueType());
ASSERT_EQUALS("signed long", tok->valueType()->str());
}
void symbolDatabaseForVariable() {
const char clang[] = "`-FunctionDecl 0x38f8bb0 <10100.c:2:1, line:4:1> line:2:6 f 'void (void)'\n"
" `-CompoundStmt 0x38f8d88 <col:14, line:4:1>\n"
" `-ForStmt 0x38f8d50 <line:3:5, col:26>\n"
" |-DeclStmt 0x38f8d28 <col:10, col:19>\n"
" | `-VarDecl 0x38f8ca8 <col:10, col:18> col:14 i 'int' cinit\n"
" | `-IntegerLiteral 0x38f8d08 <col:18> 'int' 0\n"
" |-<<<NULL>>>\n"
" |-<<<NULL>>>\n"
" |-<<<NULL>>>\n"
" `-CompoundStmt 0x38f8d40 <col:25, col:26>";
ASSERT_EQUALS("void f ( ) { for ( int i@1 = 0 ; ; ) { } }", parse(clang));
GET_SYMBOL_DB(clang);
const Token *tok = Token::findsimplematch(tokenizer.tokens(), "i");
ASSERT(!!tok);
ASSERT(!!tok->variable());
ASSERT_EQUALS(Scope::ScopeType::eFor, tok->variable()->scope()->type);
}
void valueFlow1() {
// struct S { int x; int buf[10]; } ; int sz = sizeof(struct S);
const char clang[] = "|-RecordDecl 0x2fc5a88 <1.c:1:1, line:4:1> line:1:8 struct S definition\n"
"| |-FieldDecl 0x2fc5b48 <line:2:3, col:7> col:7 x 'int'\n"
"| `-FieldDecl 0x2fc5c10 <line:3:3, col:13> col:7 buf 'int [10]'\n"
"`-VarDecl 0x2fc5c70 <line:6:1, col:25> col:5 sz 'int' cinit\n"
" `-ImplicitCastExpr 0x2fc5d88 <col:10, col:25> 'int' <IntegralCast>\n"
" `-UnaryExprOrTypeTraitExpr 0x2fc5d68 <col:10, col:25> 'unsigned long' sizeof 'struct S':'struct S'";
GET_SYMBOL_DB(clang);
const Token *tok = Token::findsimplematch(tokenizer.tokens(), "sizeof (");
ASSERT(!!tok);
tok = tok->next();
ASSERT(tok->hasKnownIntValue());
ASSERT_EQUALS(44, tok->getKnownIntValue());
}
void valueFlow2() {
// int buf[42];
// int x = sizeof(buf);
const char clang[] = "|-VarDecl 0x10f6de8 <66.cpp:3:1, col:11> col:5 referenced buf 'int [42]'\n"
"`-VarDecl 0x10f6eb0 <line:4:1, col:19> col:5 x 'int' cinit\n"
" `-ImplicitCastExpr 0x10f6f78 <col:9, col:19> 'int' <IntegralCast>\n"
" `-UnaryExprOrTypeTraitExpr 0x10f6f58 <col:9, col:19> 'unsigned long' sizeof\n"
" `-ParenExpr 0x10f6f38 <col:15, col:19> 'int [42]' lvalue\n"
" `-DeclRefExpr 0x10f6f18 <col:16> 'int [42]' lvalue Var 0x10f6de8 'buf' 'int [42]' non_odr_use_unevaluated";
GET_SYMBOL_DB(clang);
const Token *tok = Token::findsimplematch(tokenizer.tokens(), "sizeof (");
ASSERT(!!tok);
tok = tok->next();
TODO_ASSERT_EQUALS(true, false, tok->hasKnownIntValue() && tok->getKnownIntValue() == 10);
}
void valueType1() {
const char clang[] = "`-FunctionDecl 0x32438c0 <a.cpp:5:1, line:7:1> line:5:6 foo 'a::b (a::b)'\n"
" |-ParmVarDecl 0x32437b0 <col:10, col:15> col:15 used i 'a::b':'long'\n"
" `-CompoundStmt 0x3243a60 <col:18, line:7:1>\n"
" `-ReturnStmt 0x3243a48 <line:6:3, col:12>\n"
" `-ImplicitCastExpr 0x2176ca8 <col:9> 'int' <IntegralCast>\n"
" `-ImplicitCastExpr 0x2176c90 <col:9> 'bool' <LValueToRValue>\n"
" `-DeclRefExpr 0x2176c60 <col:9> 'bool' lvalue Var 0x2176bd0 'e' 'bool'\n";
GET_SYMBOL_DB(clang);
const Token *tok = Token::findsimplematch(tokenizer.tokens(), "e");
ASSERT(!!tok);
ASSERT(!!tok->valueType());
ASSERT_EQUALS("bool", tok->valueType()->str());
}
void valueType2() {
const char clang[] = "`-VarDecl 0xc9eda0 <1.cpp:2:1, col:17> col:13 s 'const char *' cinit\n"
" `-ImplicitCastExpr 0xc9eef0 <col:17> 'const char *' <ArrayToPointerDecay>\n"
" `-StringLiteral 0xc9eed0 <col:17> 'const char [6]' lvalue \"hello\"\n";
GET_SYMBOL_DB(clang);
const Token *tok = Token::findsimplematch(tokenizer.tokens(), "\"hello\"");
ASSERT(!!tok);
ASSERT(!!tok->valueType());
ASSERT_EQUALS("const signed char *", tok->valueType()->str());
}
void stdinLoc() {
// we should never encounter this
/*
int i;
*/
const char clang[] = "`-VarDecl 0x5776bb240470 <<stdin>:1:1, col:5> col:5 i 'int'\n";
ASSERT_THROW_INTERNAL_EQUALS(parse(clang), AST, "invalid AST location: <<stdin>");
}
void crash() {
const char* clang = "TranslationUnitDecl 0x56037914f998 <<invalid sloc>> <invalid sloc>\n"
"|-ClassTemplateDecl 0x560379196b58 <test1.cpp:1:1, col:50> col:37 A\n"
"| |-TemplateTypeParmDecl 0x560379196950 <col:11> col:19 typename depth 0 index 0\n"
"| |-TemplateTypeParmDecl 0x5603791969f8 <col:21> col:29 typename depth 0 index 1\n"
"| `-CXXRecordDecl 0x560379196ac8 <col:31, col:50> col:37 class A definition\n"
"| |-DefinitionData empty aggregate standard_layout trivially_copyable pod trivial literal has_constexpr_non_copy_move_ctor can_const_default_init\n"
"| | |-DefaultConstructor exists trivial constexpr needs_implicit defaulted_is_constexpr\n"
"| | |-CopyConstructor simple trivial has_const_param needs_implicit implicit_has_const_param\n"
"| | |-MoveConstructor exists simple trivial needs_implicit\n"
"| | |-CopyAssignment simple trivial has_const_param needs_implicit implicit_has_const_param\n"
"| | |-MoveAssignment exists simple trivial needs_implicit\n"
"| | `-Destructor simple irrelevant trivial needs_implicit\n"
"| |-CXXRecordDecl 0x560379196de0 <col:31, col:37> col:37 implicit referenced class A\n"
"| `-CXXRecordDecl 0x560379196e70 <col:41, col:47> col:47 class b\n"
"|-CXXRecordDecl 0x560379197110 parent 0x560379196ac8 prev 0x560379196e70 <line:2:1, col:63> col:50 class b definition\n"
"| |-DefinitionData empty standard_layout trivially_copyable has_user_declared_ctor can_const_default_init\n"
"| | |-DefaultConstructor defaulted_is_constexpr\n"
"| | |-CopyConstructor simple trivial has_const_param needs_implicit implicit_has_const_param\n"
"| | |-MoveConstructor exists simple trivial needs_implicit\n"
"| | |-CopyAssignment simple trivial has_const_param needs_implicit implicit_has_const_param\n"
"| | |-MoveAssignment exists simple trivial needs_implicit\n"
"| | `-Destructor simple irrelevant trivial needs_implicit\n"
"| |-CXXRecordDecl 0x560379197250 <col:35, col:50> col:50 implicit referenced class b\n"
"| `-CXXConstructorDecl 0x5603791974b8 <col:54, col:60> col:54 b 'void (A<type-parameter-0-0, type-parameter-0-1> &)'\n"
"| `-ParmVarDecl 0x560379197380 <col:56, col:59> col:59 a 'A<type-parameter-0-0, type-parameter-0-1> &'\n"
"`-CXXConstructorDecl 0x5603791b5600 parent 0x560379197110 prev 0x5603791974b8 <line:3:1, col:55> col:47 b 'void (A<type-parameter-0-0, type-parameter-0-1> &)'\n"
" |-ParmVarDecl 0x5603791b5570 <col:49, col:51> col:52 'A<type-parameter-0-0, type-parameter-0-1> &'\n"
" `-CompoundStmt 0x5603791b5700 <col:54, col:55>\n";
(void)parse(clang); // don't crash
}
};
REGISTER_TEST(TestClangImport)
| null |
981 | cpp | cppcheck | testunusedprivfunc.cpp | test/testunusedprivfunc.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "checkclass.h"
#include "errortypes.h"
#include "helpers.h"
#include "platform.h"
#include "settings.h"
#include "fixture.h"
#include "tokenize.h"
#include <string>
#include <vector>
class TestUnusedPrivateFunction : public TestFixture {
public:
TestUnusedPrivateFunction() : TestFixture("TestUnusedPrivateFunction") {}
private:
const Settings settings = settingsBuilder().severity(Severity::style).build();
void run() override {
TEST_CASE(test1);
TEST_CASE(test2);
TEST_CASE(test3);
TEST_CASE(test4);
TEST_CASE(test5);
TEST_CASE(test6); // ticket #2602
TEST_CASE(test7); // ticket #9282
// [ 2236547 ] False positive --style unused function, called via pointer
TEST_CASE(func_pointer1);
TEST_CASE(func_pointer2);
TEST_CASE(func_pointer3);
TEST_CASE(func_pointer4); // ticket #2807
TEST_CASE(func_pointer5); // ticket #2233
TEST_CASE(func_pointer6); // ticket #4787
TEST_CASE(func_pointer7); // ticket #10516
TEST_CASE(ctor);
TEST_CASE(ctor2);
TEST_CASE(classInClass);
TEST_CASE(sameFunctionNames);
TEST_CASE(incompleteImplementation);
TEST_CASE(derivedClass); // skip warning for derived classes. It might be a virtual function.
TEST_CASE(friendClass);
TEST_CASE(borland1); // skip FP when using __property
TEST_CASE(borland2); // skip FP when using __published
// No false positives when there are "unused" templates that are removed in the simplified token list
TEST_CASE(template1);
// #2407 - FP when called from operator()
TEST_CASE(fp_operator);
TEST_CASE(testDoesNotIdentifyMethodAsFirstFunctionArgument); // #2480
TEST_CASE(testDoesNotIdentifyMethodAsMiddleFunctionArgument);
TEST_CASE(testDoesNotIdentifyMethodAsLastFunctionArgument);
TEST_CASE(multiFile);
TEST_CASE(unknownBaseTemplate); // ticket #2580
TEST_CASE(hierarchy_loop); // ticket 5590
TEST_CASE(staticVariable); //ticket #5566
TEST_CASE(templateSimplification); //ticket #6183
TEST_CASE(maybeUnused);
TEST_CASE(trailingReturn);
}
#define check(...) check_(__FILE__, __LINE__, __VA_ARGS__)
void check_(const char* file, int line, const char code[], Platform::Type platform = Platform::Type::Native) {
const Settings settings1 = settingsBuilder(settings).platform(platform).build();
std::vector<std::string> files(1, "test.cpp");
Tokenizer tokenizer(settings1, *this);
PreprocessorHelper::preprocess(code, files, tokenizer, *this);
// Tokenize..
ASSERT_LOC(tokenizer.simplifyTokens1(""), file, line);
// Check for unused private functions..
CheckClass checkClass(&tokenizer, &settings1, this);
checkClass.privateFunctions();
}
void test1() {
check("class Fred\n"
"{\n"
"private:\n"
" unsigned int f();\n"
"public:\n"
" Fred();\n"
"};\n"
"\n"
"Fred::Fred()\n"
"{ }\n"
"\n"
"unsigned int Fred::f()\n"
"{ }");
ASSERT_EQUALS("[test.cpp:4]: (style) Unused private function: 'Fred::f'\n", errout_str());
check("#line 1 \"p.h\"\n"
"class Fred\n"
"{\n"
"private:\n"
" unsigned int f();\n"
"public:\n"
" Fred();\n"
"};\n"
"\n"
"#line 1 \"p.cpp\"\n"
"Fred::Fred()\n"
"{ }\n"
"\n"
"unsigned int Fred::f()\n"
"{ }");
ASSERT_EQUALS("[p.h:4]: (style) Unused private function: 'Fred::f'\n", errout_str());
check("#line 1 \"p.h\"\n"
"class Fred\n"
"{\n"
"private:\n"
"void f();\n"
"};\n"
"\n"
"\n"
"#line 1 \"p.cpp\"\n"
"\n"
"void Fred::f()\n"
"{\n"
"}");
ASSERT_EQUALS("[p.h:4]: (style) Unused private function: 'Fred::f'\n", errout_str());
// Don't warn about include files which implementation we don't see
check("#line 1 \"p.h\"\n"
"class Fred\n"
"{\n"
"private:\n"
"void f();\n"
"void g() {}\n"
"};\n"
"\n"
"#line 1 \"p.cpp\"\n"
"\n"
"int main()\n"
"{\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void test2() {
check("class A {\n"
"public:\n"
" A();\n"
"\n"
" void a() const\n"
" { b(); }\n"
"private:\n"
" void b( ) const\n"
" { }\n"
"};\n"
"\n"
"A::A()\n"
"{ }");
ASSERT_EQUALS("", errout_str());
}
void test3() {
check("class A {\n"
"public:\n"
" A() { }\n"
" ~A();\n"
"private:\n"
" void B() { }\n"
"};\n"
"\n"
"A::~A()\n"
"{ B(); }");
ASSERT_EQUALS("", errout_str());
}
void test4() {
check("class A {\n"
"public:\n"
" A();\n"
"private:\n"
" bool _owner;\n"
" void b() { }\n"
"};\n"
"\n"
"A::A() : _owner(false)\n"
"{ b(); }");
ASSERT_EQUALS("", errout_str());
}
void test5() {
check("class A {\n"
"private:\n"
" A() : lock(new Lock())\n"
" { }\n"
" Lock *lock;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void test6() { // ticket #2602 segmentation fault
check("class A {\n"
" A& operator=(const A&);\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void test7() { // ticket #9282
check("class C {\n"
" double f1() const noexcept, f2(double) const noexcept;\n"
" void f3() const noexcept;\n"
"};\n"
"double C::f1() const noexcept { f3(); }\n"
"void C::f3() const noexcept {}\n");
ASSERT_EQUALS("", errout_str());
}
void func_pointer1() {
check("class Fred\n"
"{\n"
"private:\n"
" typedef void (*testfp)();\n"
"\n"
" testfp get()\n"
" {\n"
" return test;\n"
" }\n"
"\n"
" static void test()\n"
" { }\n"
"\n"
"public:\n"
" Fred();\n"
"};\n"
"\n"
"Fred::Fred()\n"
"{}");
ASSERT_EQUALS("[test.cpp:6]: (style) Unused private function: 'Fred::get'\n", errout_str());
}
void func_pointer2() {
check("class UnusedPrivateFunctionMemberPointer\n"
"{\n"
"public:\n"
" UnusedPrivateFunctionMemberPointer()\n"
" : mObserver(this, &UnusedPrivateFunctionMemberPointer::callback)\n"
" {}\n"
"\n"
"private:\n"
" void callback(const& unsigned) const {}\n"
"\n"
" Observer<UnusedPrivateFunctionMemberPointer, unsigned> mObserver;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void func_pointer3() {
check("class c1\n"
"{\n"
"public:\n"
" c1()\n"
" { sigc::mem_fun(this, &c1::f1); }\n"
"\n"
"private:\n"
" void f1() const {}\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void func_pointer4() { // ticket #2807
check("class myclass {\n"
"public:\n"
" myclass();\n"
"private:\n"
" static void f();\n"
" void (*fptr)();\n"
"};\n"
"myclass::myclass() { fptr = &f; }\n"
"void myclass::f() {}");
ASSERT_EQUALS("", errout_str());
}
void func_pointer5() {
check("class A {\n"
"public:\n"
" A() { f = A::func; }\n"
" void (*f)();\n"
"private:\n"
" static void func() { }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void func_pointer6() { // #4787
check("class Test {\n"
"private:\n"
" static void a(const char* p) { }\n"
"public:\n"
" void test(void* f = a) {\n"
" f(\"test\");\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void func_pointer7() { // #10516
check("class C {\n"
" static void f() {}\n"
" static constexpr void(*p)() = f;\n"
"};\n");
ASSERT_EQUALS("", errout_str());
check("class C {\n"
" static void f() {}\n"
" static constexpr void(*p)() = &f;\n"
"};\n");
ASSERT_EQUALS("", errout_str());
check("class C {\n"
" static void f() {}\n"
" static constexpr void(*p)() = C::f;\n"
"};\n");
ASSERT_EQUALS("", errout_str());
check("class C {\n"
" static void f() {}\n"
" static constexpr void(*p)() = &C::f;\n"
"};\n");
ASSERT_EQUALS("", errout_str());
}
void ctor() {
check("class PrivateCtor\n"
"{\n"
"private:\n"
" PrivateCtor(int threadNum) :\n"
" numOfThreads(threadNum)\n"
" {\n"
" }\n"
"\n"
" int numOfThreads;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void ctor2() {
check("struct State {\n"
" State(double const totalWeighting= TotalWeighting()) :\n"
" totalWeighting_(totalWeighting) {}\n"
"private:\n"
" double TotalWeighting() { return 123.0; }\n" // called from constructor
"public:\n"
" double totalWeighting_;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void classInClass() {
check("class A\n"
"{\n"
"public:\n"
"\n"
" class B\n"
" {\n"
" private:\n"
" };\n"
"private:\n"
" static void f()\n"
" { }\n"
"};");
ASSERT_EQUALS("[test.cpp:10]: (style) Unused private function: 'A::f'\n", errout_str());
check("class A\n"
"{\n"
"public:\n"
" A()\n"
" { }\n"
"\n"
"private:\n"
" void f()\n"
" { }\n"
"\n"
" class B\n"
" {\n"
" public:\n"
" B(A *a)\n"
" { a->f(); }\n"
" };\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class A {\n" // #6968 - outer definition
"public:\n"
" class B;\n"
"private:\n"
" void f() {}\n"
"}\n"
"class A::B {"
" B() { A a; a.f(); }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void sameFunctionNames() {
check("class A\n"
"{\n"
"public:\n"
" void a()\n"
" {\n"
" f(1);\n"
" }\n"
"\n"
"private:\n"
" void f() { }\n"
" void f(int) { }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void incompleteImplementation() {
// The implementation for "A::a" is missing - so don't check if
// "A::b" is used or not
check("#file \"test.h\"\n"
"class A\n"
"{\n"
"public:\n"
" A();\n"
" void a();\n"
"private:\n"
" void b();\n"
"};\n"
"#endfile\n"
"A::A() { }\n"
"void A::b() { }");
ASSERT_EQUALS("", errout_str());
}
void derivedClass() {
// skip warning in derived classes in case the base class is invisible
check("class derived : public base\n"
"{\n"
"public:\n"
" derived() : base() { }\n"
"private:\n"
" void f();\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class base {\n"
"public:\n"
" virtual void foo();\n"
" void bar();\n"
"};\n"
"class derived : public base {\n"
"private:\n"
" void foo() {}\n" // Skip for overrides of virtual functions of base
" void bar() {}\n" // Don't skip if no function is overridden
"};");
ASSERT_EQUALS("[test.cpp:9]: (style) Unused private function: 'derived::bar'\n", errout_str());
check("class Base {\n"
"private:\n"
" virtual void func() = 0;\n"
"public:\n"
" void public_func() {\n"
" func();\n"
" };\n"
"};\n"
"\n"
"class Derived1: public Base {\n"
"private:\n"
" void func() {}\n"
"};\n"
"class Derived2: public Derived1 {\n"
"private:\n"
" void func() {}\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class Base {\n"
"public:\n"
" void dostuff() {\n"
" f();\n"
" }\n"
"\n"
"private:\n"
" virtual Base* f() = 0;\n"
"};\n"
"\n"
"class Derived : public Base {\n"
"private:\n"
" Derived* f() {\n"
" return 0;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void friendClass() {
// ticket #2459 - friend class
check("class Foo {\n"
"private:\n"
" friend Bar;\n" // Unknown friend class
" void f() { }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct Bar {\n"
" void g() { f(); }\n" // Friend class seen, but f not seen
"};\n"
"class Foo {\n"
"private:\n"
" friend Bar;\n"
" void f();\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct Bar {\n"
" void g() { f(); }\n" // Friend class seen, but f() used in it
"};\n"
"class Foo {\n"
"private:\n"
" friend Bar;\n"
" void f() { }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class Bar {\n" // Friend class seen, f() not used in it
"};\n"
"class Foo {\n"
" friend Bar;\n"
" void f() { }\n"
"};");
ASSERT_EQUALS("[test.cpp:5]: (style) Unused private function: 'Foo::f'\n", errout_str());
check("struct F;\n" // #10265
"struct S {\n"
" int i{};\n"
" friend struct F;\n"
"private:\n"
" int f() const { return i; }\n"
"};\n"
"struct F {\n"
" bool operator()(const S& lhs, const S& rhs) const {\n"
" return lhs.f() < rhs.f();\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void borland1() {
// ticket #2034 - Borland C++ __property
check("class Foo {\n"
"private:\n"
" int getx() {\n"
" return 123;\n"
" }\n"
"public:\n"
" Foo() { }\n"
" __property int x = {read=getx}\n"
"};", Platform::Type::Win32A);
ASSERT_EQUALS("", errout_str());
}
void borland2() {
// ticket #3661 - Borland C++ __published
check("class Foo {\n"
"__published:\n"
" int getx() {\n"
" return 123;\n"
" }\n"
"public:\n"
" Foo() { }\n"
"};", Platform::Type::Win32A);
ASSERT_EQUALS("", errout_str());
}
void template1() {
// ticket #2067 - Template methods do not "use" private ones
check("class A {\n"
"public:\n"
" template <class T>\n"
" T getVal() const;\n"
"\n"
"private:\n"
" int internalGetVal() const { return 8000; }\n"
"};\n"
"\n"
"template <class T>\n"
"T A::getVal() const {\n"
" return internalGetVal();\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void fp_operator() {
// #2407 - FP when function is called from operator()
check("class Fred\n"
"{\n"
"public:\n"
" void operator()(int x) {\n"
" startListening();\n"
" }\n"
"\n"
"private:\n"
" void startListening() {\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class Fred\n"
"{\n"
"public:\n"
" void operator()(int x) {\n"
" }\n"
"\n"
"private:\n"
" void startListening() {\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:8]: (style) Unused private function: 'Fred::startListening'\n", errout_str());
// #5059
check("class Fred {\n"
" void* operator new(size_t obj_size, size_t buf_size) {}\n"
"};");
TODO_ASSERT_EQUALS("[test.cpp:2]: (style) Unused private function: 'Fred::operatornew'\n", "", errout_str()); // No message for operators - we currently cannot check their usage
check("class Fred {\n"
" void* operator new(size_t obj_size, size_t buf_size) {}\n"
"public:\n"
" void* foo() { return new(size) Fred(); }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void testDoesNotIdentifyMethodAsFirstFunctionArgument() {
check("void callback(void (*func)(int), int arg)"
"{"
" (*func)(arg);"
"}"
"class MountOperation"
"{"
" static void Completed(int i);"
"public:"
" MountOperation(int i);"
"};"
"void MountOperation::Completed(int i)"
"{"
" std::cerr << i << std::endl;"
"}"
"MountOperation::MountOperation(int i)"
"{"
" callback(MountOperation::Completed, i);"
"}"
"int main(void)"
"{"
" MountOperation aExample(10);"
"}"
);
ASSERT_EQUALS("", errout_str());
}
void testDoesNotIdentifyMethodAsMiddleFunctionArgument() {
check("void callback(char, void (*func)(int), int arg)"
"{"
" (*func)(arg);"
"}"
"class MountOperation"
"{"
" static void Completed(int i);"
"public:"
" MountOperation(int i);"
"};"
"void MountOperation::Completed(int i)"
"{"
" std::cerr << i << std::endl;"
"}"
"MountOperation::MountOperation(int i)"
"{"
" callback('a', MountOperation::Completed, i);"
"}"
"int main(void)"
"{"
" MountOperation aExample(10);"
"}"
);
ASSERT_EQUALS("", errout_str());
}
void testDoesNotIdentifyMethodAsLastFunctionArgument() {
check("void callback(int arg, void (*func)(int))"
"{"
" (*func)(arg);"
"}"
"class MountOperation"
"{"
" static void Completed(int i);"
"public:"
" MountOperation(int i);"
"};"
"void MountOperation::Completed(int i)"
"{"
" std::cerr << i << std::endl;"
"}"
"MountOperation::MountOperation(int i)"
"{"
" callback(i, MountOperation::Completed);"
"}"
"int main(void)"
"{"
" MountOperation aExample(10);"
"}"
);
ASSERT_EQUALS("", errout_str());
}
void multiFile() { // ticket #2567
check("#file \"test.h\"\n"
"struct Fred\n"
"{\n"
" Fred()\n"
" {\n"
" Init();\n"
" }\n"
"private:\n"
" void Init();\n"
"};\n"
"#endfile\n"
"void Fred::Init()\n"
"{\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void unknownBaseTemplate() { // ticket #2580
check("class Bla : public Base2<Base> {\n"
"public:\n"
" Bla() {}\n"
"private:\n"
" virtual void F() const;\n"
"};\n"
"void Bla::F() const { }");
ASSERT_EQUALS("", errout_str());
}
void hierarchy_loop() {
check("class InfiniteB : InfiniteA {\n"
" class D {\n"
" };\n"
"};\n"
"namespace N {\n"
" class InfiniteA : InfiniteB {\n"
" };\n"
"}\n"
"class InfiniteA : InfiniteB {\n"
" void foo();\n"
"};\n"
"void InfiniteA::foo() {\n"
" C a;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void staticVariable() {
check("class Foo {\n"
" static int i;\n"
" static int F() const { return 1; }\n"
"};\n"
"int Foo::i = Foo::F();");
ASSERT_EQUALS("", errout_str());
check("class Foo {\n"
" static int i;\n"
" int F() const { return 1; }\n"
"};\n"
"Foo f;\n"
"int Foo::i = f.F();");
ASSERT_EQUALS("", errout_str());
check("class Foo {\n"
" static int i;\n"
" static int F() const { return 1; }\n"
"};\n"
"int Foo::i = sth();"
"int i = F();");
ASSERT_EQUALS("[test.cpp:3]: (style) Unused private function: 'Foo::F'\n", errout_str());
}
void templateSimplification() { //ticket #6183
check("class CTest {\n"
"public:\n"
" template <typename T>\n"
" static void Greeting(T val) {\n"
" std::cout << val << std::endl;\n"
" }\n"
"private:\n"
" static void SayHello() {\n"
" std::cout << \"Hello World!\" << std::endl;\n"
" }\n"
"};\n"
"template<>\n"
"void CTest::Greeting(bool) {\n"
" CTest::SayHello();\n"
"}\n"
"int main() {\n"
" CTest::Greeting<bool>(true);\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void maybeUnused() {
check("class C {\n"
" [[maybe_unused]] int f() { return 42; }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void trailingReturn() {
check("struct B { virtual void f(); };\n"
"struct D : B {\n"
" auto f() -> void override;\n"
"private:\n"
" auto g() -> void;\n"
"};\n"
"auto D::f() -> void { g(); }\n"
"auto D::g() -> void {}\n");
ASSERT_EQUALS("", errout_str());
}
};
REGISTER_TEST(TestUnusedPrivateFunction)
| null |
982 | cpp | cppcheck | testconstructors.cpp | test/testconstructors.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "checkclass.h"
#include "errortypes.h"
#include "fixture.h"
#include "helpers.h"
#include "standards.h"
#include "settings.h"
#include <cstddef>
class TestConstructors : public TestFixture {
public:
TestConstructors() : TestFixture("TestConstructors") {}
private:
const Settings settings = settingsBuilder().severity(Severity::style).severity(Severity::warning).build();
#define check(...) check_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
void check_(const char* file, int line, const char (&code)[size], bool inconclusive = false) {
const Settings settings1 = settingsBuilder(settings).certainty(Certainty::inconclusive, inconclusive).build();
// Tokenize..
SimpleTokenizer tokenizer(settings1, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
// Check class constructors..
CheckClass checkClass(&tokenizer, &settings1, this);
checkClass.constructors();
}
template<size_t size>
void check_(const char* file, int line, const char (&code)[size], const Settings &s) {
// Tokenize..
SimpleTokenizer tokenizer(s, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
// Check class constructors..
CheckClass checkClass(&tokenizer, &s, this);
checkClass.constructors();
}
void run() override {
TEST_CASE(simple1);
TEST_CASE(simple2);
TEST_CASE(simple3);
TEST_CASE(simple4);
TEST_CASE(simple5); // ticket #2560
TEST_CASE(simple6); // ticket #4085 - uninstantiated template class
TEST_CASE(simple7); // ticket #4531
TEST_CASE(simple8);
TEST_CASE(simple9); // ticket #4574
TEST_CASE(simple10); // ticket #4388
TEST_CASE(simple11); // ticket #4536, #6214
TEST_CASE(simple12); // ticket #4620
TEST_CASE(simple13); // #5498 - no constructor, c++11 assignments
TEST_CASE(simple14); // #6253 template base
TEST_CASE(simple15); // #8942 multiple arguments, decltype
TEST_CASE(simple16); // copy members with c++11 init
TEST_CASE(simple17); // #10360
TEST_CASE(simple18);
TEST_CASE(noConstructor1);
TEST_CASE(noConstructor2);
TEST_CASE(noConstructor3);
TEST_CASE(noConstructor4);
TEST_CASE(noConstructor5);
TEST_CASE(noConstructor6); // ticket #4386
TEST_CASE(noConstructor7); // ticket #4391
TEST_CASE(noConstructor8); // ticket #4404
TEST_CASE(noConstructor9); // ticket #4419
TEST_CASE(noConstructor10); // ticket #6614
TEST_CASE(noConstructor11); // ticket #3552
TEST_CASE(noConstructor12); // #8951 - member initialization
TEST_CASE(noConstructor13); // #9998
TEST_CASE(noConstructor14); // #10770
TEST_CASE(noConstructor15); // #5499
TEST_CASE(forwardDeclaration); // ticket #4290/#3190
TEST_CASE(initvar_with_this); // BUG 2190300
TEST_CASE(initvar_if); // BUG 2190290
TEST_CASE(initvar_operator_eq1); // BUG 2190376
TEST_CASE(initvar_operator_eq2); // BUG 2190376
TEST_CASE(initvar_operator_eq3);
TEST_CASE(initvar_operator_eq4); // ticket #2204
TEST_CASE(initvar_operator_eq5); // ticket #4119
TEST_CASE(initvar_operator_eq6);
TEST_CASE(initvar_operator_eq7);
TEST_CASE(initvar_operator_eq8);
TEST_CASE(initvar_operator_eq9);
TEST_CASE(initvar_operator_eq10);
TEST_CASE(initvar_operator_eq11);
TEST_CASE(initvar_same_classname); // BUG 2208157
TEST_CASE(initvar_chained_assign); // BUG 2270433
TEST_CASE(initvar_2constructors); // BUG 2270353
TEST_CASE(initvar_constvar);
TEST_CASE(initvar_mutablevar);
TEST_CASE(initvar_staticvar);
TEST_CASE(initvar_brace_init);
TEST_CASE(initvar_union);
TEST_CASE(initvar_delegate); // ticket #4302
TEST_CASE(initvar_delegate2);
TEST_CASE(initvar_derived_class);
TEST_CASE(initvar_derived_pod_struct_with_union); // #11101
TEST_CASE(initvar_private_constructor); // BUG 2354171 - private constructor
TEST_CASE(initvar_copy_constructor); // ticket #1611
TEST_CASE(initvar_nested_constructor); // ticket #1375
TEST_CASE(initvar_nocopy1); // ticket #2474
TEST_CASE(initvar_nocopy2); // ticket #2484
TEST_CASE(initvar_nocopy3); // ticket #3611
TEST_CASE(initvar_nocopy4); // ticket #9247
TEST_CASE(initvar_with_member_function_this); // ticket #4824
TEST_CASE(initvar_destructor); // No variables need to be initialized in a destructor
TEST_CASE(initvar_func_ret_func_ptr); // ticket #4449
TEST_CASE(initvar_alias); // #6921
TEST_CASE(initvar_templateMember); // #7205
TEST_CASE(initvar_smartptr); // #10237
TEST_CASE(operatorEqSTL);
TEST_CASE(uninitVar1);
TEST_CASE(uninitVar2);
TEST_CASE(uninitVar3);
TEST_CASE(uninitVar4);
TEST_CASE(uninitVar5);
TEST_CASE(uninitVar6);
TEST_CASE(uninitVar7);
TEST_CASE(uninitVar8);
TEST_CASE(uninitVar9); // ticket #1730
TEST_CASE(uninitVar10); // ticket #1993
TEST_CASE(uninitVar11);
TEST_CASE(uninitVar12); // ticket #2078
TEST_CASE(uninitVar13); // ticket #1195
TEST_CASE(uninitVar14); // ticket #2149
TEST_CASE(uninitVar15);
TEST_CASE(uninitVar16);
TEST_CASE(uninitVar17);
TEST_CASE(uninitVar18); // ticket #2465
TEST_CASE(uninitVar19); // ticket #2792
TEST_CASE(uninitVar20); // ticket #2867
TEST_CASE(uninitVar21); // ticket #2947
TEST_CASE(uninitVar22); // ticket #3043
TEST_CASE(uninitVar23); // ticket #3702
TEST_CASE(uninitVar24); // ticket #3190
TEST_CASE(uninitVar25); // ticket #4789
TEST_CASE(uninitVar26);
TEST_CASE(uninitVar27); // ticket #5170 - rtl::math::setNan(&d)
TEST_CASE(uninitVar28); // ticket #6258
TEST_CASE(uninitVar29);
TEST_CASE(uninitVar30); // ticket #6417
TEST_CASE(uninitVar31); // ticket #8271
TEST_CASE(uninitVar32); // ticket #8835
TEST_CASE(uninitVar33); // ticket #10295
TEST_CASE(uninitVar34); // ticket #10841
TEST_CASE(uninitVar35);
TEST_CASE(uninitVarEnum1);
TEST_CASE(uninitVarEnum2); // ticket #8146
TEST_CASE(uninitVarStream);
TEST_CASE(uninitVarTypedef);
TEST_CASE(uninitVarMemset);
TEST_CASE(uninitVarArray1);
TEST_CASE(uninitVarArray2);
TEST_CASE(uninitVarArray3);
TEST_CASE(uninitVarArray4);
TEST_CASE(uninitVarArray5);
TEST_CASE(uninitVarArray6);
TEST_CASE(uninitVarArray7);
TEST_CASE(uninitVarArray8);
TEST_CASE(uninitVarArray9); // ticket #6957, #6959
TEST_CASE(uninitVarArray10);
TEST_CASE(uninitVarArray11);
TEST_CASE(uninitVarArray2D);
TEST_CASE(uninitVarArray3D);
TEST_CASE(uninitVarCpp11Init1);
TEST_CASE(uninitVarCpp11Init2);
TEST_CASE(uninitVarStruct1); // ticket #2172
TEST_CASE(uninitVarStruct2); // ticket #838
TEST_CASE(uninitVarUnion1); // ticket #3196
TEST_CASE(uninitVarUnion2);
TEST_CASE(uninitMissingFuncDef); // can't expand function in constructor
TEST_CASE(privateCtor1); // If constructor is private..
TEST_CASE(privateCtor2); // If constructor is private..
TEST_CASE(function); // Function is not variable
TEST_CASE(uninitVarPublished); // Borland C++: Variables in the published section are auto-initialized
TEST_CASE(uninitVarInheritClassInit); // Borland C++: if class inherits from TObject, all variables are initialized
TEST_CASE(uninitOperator); // No FP about uninitialized 'operator[]'
TEST_CASE(uninitFunction1); // No FP when initialized in function
TEST_CASE(uninitFunction2); // No FP when initialized in function
TEST_CASE(uninitFunction3); // No FP when initialized in function
TEST_CASE(uninitFunction4);
TEST_CASE(uninitFunction5);
TEST_CASE(uninitSameClassName); // No FP when two classes have the same name
TEST_CASE(uninitFunctionOverload); // No FP when there are overloaded functions
TEST_CASE(uninitVarOperatorEqual); // ticket #2415
TEST_CASE(uninitVarPointer); // ticket #3801
TEST_CASE(uninitConstVar);
TEST_CASE(constructors_crash1); // ticket #5641
TEST_CASE(classWithOperatorInName);// ticket #2827
TEST_CASE(templateConstructor); // ticket #7942
TEST_CASE(typedefArray); // ticket #5766
TEST_CASE(uninitAssignmentWithOperator); // ticket #7429
TEST_CASE(uninitCompoundAssignment); // ticket #7429
TEST_CASE(uninitComparisonAssignment); // ticket #7429
TEST_CASE(uninitTemplate1); // ticket #7372
TEST_CASE(unknownTemplateType);
}
void simple1() {
check("class Fred\n"
"{\n"
"public:\n"
" int i;\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class Fred\n"
"{\n"
"private:\n"
" int i;\n"
"};");
ASSERT_EQUALS("[test.cpp:1]: (style) The class 'Fred' does not declare a constructor although it has private member variables which likely require initialization.\n", errout_str());
check("struct Fred\n"
"{\n"
"private:\n"
" int i;\n"
"};");
ASSERT_EQUALS("[test.cpp:1]: (style) The struct 'Fred' does not declare a constructor although it has private member variables which likely require initialization.\n", errout_str());
}
void simple2() {
check("class Fred\n"
"{\n"
"public:\n"
" Fred() : i(0) { }\n"
" Fred(Fred const & other) : i(other.i) {}\n"
" Fred(Fred && other) : i(other.i) {}\n"
" int i;\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class Fred\n"
"{\n"
"public:\n"
" Fred() { i = 0; }\n"
" Fred(Fred const & other) {i=other.i}\n"
" Fred(Fred && other) {i=other.i}\n"
" int i;\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class Fred\n"
"{\n"
"public:\n"
" Fred() { }\n"
" Fred(Fred const & other) {}\n"
" Fred(Fred && other) {}\n"
" int i;\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (warning) Member variable 'Fred::i' is not initialized in the constructor.\n"
"[test.cpp:5]: (warning) Member variable 'Fred::i' is not initialized in the copy constructor.\n"
"[test.cpp:6]: (warning) Member variable 'Fred::i' is not initialized in the move constructor.\n", errout_str());
check("struct Fred\n"
"{\n"
" Fred() { }\n"
" Fred(Fred const & other) {}\n"
" Fred(Fred && other) {}\n"
" int i;\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (warning) Member variable 'Fred::i' is not initialized in the constructor.\n"
"[test.cpp:4]: (warning) Member variable 'Fred::i' is not initialized in the copy constructor.\n"
"[test.cpp:5]: (warning) Member variable 'Fred::i' is not initialized in the move constructor.\n", errout_str());
}
void simple3() {
check("struct Fred\n"
"{\n"
" Fred();\n"
" int i;\n"
"};\n"
"Fred::Fred() :i(0)\n"
"{ }");
ASSERT_EQUALS("", errout_str());
check("struct Fred\n"
"{\n"
" Fred();\n"
" int i;\n"
"};\n"
"Fred::Fred()\n"
"{ i = 0; }");
ASSERT_EQUALS("", errout_str());
check("struct Fred\n"
"{\n"
" Fred();\n"
" int i;\n"
"};\n"
"Fred::Fred()\n"
"{ }");
ASSERT_EQUALS("[test.cpp:6]: (warning) Member variable 'Fred::i' is not initialized in the constructor.\n", errout_str());
}
void simple4() {
check("struct Fred\n"
"{\n"
" Fred();\n"
" explicit Fred(int _i);\n"
" Fred(Fred const & other);\n"
" int i;\n"
"};\n"
"Fred::Fred()\n"
"{ }\n"
"Fred::Fred(int _i)\n"
"{\n"
" i = _i;\n"
"}\n", true);
ASSERT_EQUALS("[test.cpp:8]: (warning, inconclusive) Member variable 'Fred::i' is not initialized in the constructor.\n", errout_str());
}
void simple5() { // ticket #2560
check("namespace Nsp\n"
"{\n"
" class B { };\n"
"}\n"
"class Altren : public Nsp::B\n"
"{\n"
"public:\n"
" Altren () : Nsp::B(), mValue(0)\n"
" {\n"
" }\n"
"private:\n"
" int mValue;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void simple6() { // ticket #4085 - uninstantiated template class
check("template <class T> struct A {\n"
" A<T>() { x = 0; }\n"
" A<T>(const T & t) { x = t.x; }\n"
"private:\n"
" int x;\n"
"};");
ASSERT_EQUALS("", errout_str());
check("template <class T> struct A {\n"
" A<T>() : x(0) { }\n"
" A<T>(const T & t) : x(t.x) { }\n"
"private:\n"
" int x;\n"
"};");
ASSERT_EQUALS("", errout_str());
check("template <class T> struct A {\n"
" A<T>() : x(0) { }\n"
" A<T>(const T & t) : x(t.x) { }\n"
"private:\n"
" int x;\n"
" int y;\n"
"};");
ASSERT_EQUALS("[test.cpp:2]: (warning) Member variable 'A::y' is not initialized in the constructor.\n"
"[test.cpp:3]: (warning) Member variable 'A::y' is not initialized in the constructor.\n", errout_str());
}
void simple7() { // ticket #4531
check("class Fred;\n"
"struct Fred {\n"
" int x;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void simple8() {
check("struct Fred { int x; };\n"
"class Barney { Fred fred; };\n"
"class Wilma { struct Betty { int x; } betty; };");
ASSERT_EQUALS("[test.cpp:2]: (style) The class 'Barney' does not declare a constructor although it has private member variables which likely require initialization.\n"
"[test.cpp:3]: (style) The class 'Wilma' does not declare a constructor although it has private member variables which likely require initialization.\n", errout_str());
}
void simple9() { // ticket #4574
check("class Unknown::Fred {\n"
"public:\n"
" Fred() : x(0) { }\n"
"private:\n"
" int x;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void simple10() {
check("class Fred {\n" // ticket #4388
"public:\n"
" Fred() = default;\n"
"private:\n"
" int x;\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (warning) Member variable 'Fred::x' is not initialized in the constructor.\n", errout_str());
check("struct S {\n" // #9391
" S() = default;\n"
" ~S() = default;\n"
" S(const S&) = default;\n"
" S(S&&) = default;\n"
" S& operator=(const S&) = default;\n"
" S& operator=(S&&) = default;\n"
" int i;\n"
"};\n");
ASSERT_EQUALS("[test.cpp:2]: (warning) Member variable 'S::i' is not initialized in the constructor.\n", errout_str());
}
void simple11() { // ticket #4536, #6214
check("class Fred {\n"
"public:\n"
" Fred() {}\n"
"private:\n"
" int x = 0;\n"
" int y = f();\n"
" int z{0};\n"
" int (*pf[2])(){nullptr, nullptr};\n"
" int a[2][3] = {{1,2,3},{4,5,6}};\n"
" int b{1}, c{2};\n"
" int d, e{3};\n"
" int f{4}, g;\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (warning) Member variable 'Fred::d' is not initialized in the constructor.\n"
"[test.cpp:3]: (warning) Member variable 'Fred::g' is not initialized in the constructor.\n", errout_str());
}
void simple12() { // ticket #4620
check("class Fred {\n"
" int x;\n"
"public:\n"
" Fred() { Init(); }\n"
" void Init(int i = 0);\n"
"};\n"
"void Fred::Init(int i) { x = i; }");
ASSERT_EQUALS("", errout_str());
check("class Fred {\n"
" int x;\n"
" int y;\n"
"public:\n"
" Fred() { Init(0); }\n"
" void Init(int i, int j = 0);\n"
"};\n"
"void Fred::Init(int i, int j) { x = i; y = j; }");
ASSERT_EQUALS("", errout_str());
}
void simple13() { // #5498
check("class Fred {\n"
" int x=1;\n"
" int *y=0;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void simple14() { // #6253 template base
check("class Fred : public Base<A, B> {"
"public:"
" Fred()\n"
" :Base<A, B>(1),\n"
" x(1)\n"
" {}\n"
"private:\n"
" int x;\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class Fred : public Base<A, B> {"
"public:"
" Fred()\n"
" :Base<A, B>{1},\n"
" x{1}\n"
" {}\n"
"private:\n"
" int x;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void simple15() { // #8942
check("class A\n"
"{\n"
"public:\n"
" int member;\n"
"};\n"
"class B\n"
"{\n"
"public:\n"
" B(const decltype(A::member)& x, const decltype(A::member)& y) : x(x), y(y) {}\n"
"private:\n"
" const decltype(A::member)& x;\n"
" const decltype(A::member)& y;\n"
"};\n");
ASSERT_EQUALS("", errout_str());
}
void simple16() {
check("struct S {\n"
" int i{};\n"
" S() = default;\n"
" S(const S& s) {}\n"
" S& operator=(const S& s) { return *this; }\n"
"};\n", /*inconclusive*/ true);
ASSERT_EQUALS("[test.cpp:4]: (warning, inconclusive) Member variable 'S::i' is not assigned in the copy constructor. Should it be copied?\n"
"[test.cpp:5]: (warning) Member variable 'S::i' is not assigned a value in 'S::operator='.\n",
errout_str());
check("struct S {\n"
" int i;\n"
" S() : i(0) {}\n"
" S(const S& s) {}\n"
" S& operator=(const S& s) { return *this; }\n"
"};\n");
ASSERT_EQUALS("[test.cpp:4]: (warning) Member variable 'S::i' is not initialized in the copy constructor.\n"
"[test.cpp:5]: (warning) Member variable 'S::i' is not assigned a value in 'S::operator='.\n",
errout_str());
}
void simple17() { // #10360
check("class Base {\n"
"public:\n"
" virtual void Copy(const Base& Src) = 0;\n"
"};\n"
"class Derived : public Base {\n"
"public:\n"
" Derived() : i(0) {}\n"
" Derived(const Derived& Src);\n"
" void Copy(const Base& Src) override;\n"
" int i;\n"
"};\n"
"Derived::Derived(const Derived& Src) {\n"
" Copy(Src);\n"
"}\n"
"void Derived::Copy(const Base& Src) {\n"
" auto d = dynamic_cast<const Derived&>(Src);\n"
" i = d.i;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void simple18() { // #13302
check("struct S {};\n"
"class C1 { S& r; };\n"
"class C2 { S* p; };\n");
ASSERT_EQUALS("[test.cpp:2]: (style) The class 'C1' does not declare a constructor although it has private member variables which likely require initialization.\n"
"[test.cpp:3]: (style) The class 'C2' does not declare a constructor although it has private member variables which likely require initialization.\n",
errout_str());
}
void noConstructor1() {
// There are nonstatic member variables - constructor is needed
check("class Fred\n"
"{\n"
" int i;\n"
"};");
ASSERT_EQUALS("[test.cpp:1]: (style) The class 'Fred' does not declare a constructor although it has private member variables which likely require initialization.\n", errout_str());
}
void noConstructor2() {
check("class Fred\n"
"{\n"
"public:\n"
" static void foobar();\n"
"};\n"
"\n"
"void Fred::foobar()\n"
"{ }");
ASSERT_EQUALS("", errout_str());
}
void noConstructor3() {
check("class Fred\n"
"{\n"
"private:\n"
" static int foobar;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void noConstructor4() {
check("class Fred\n"
"{\n"
"public:\n"
" int foobar;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void noConstructor5() {
check("namespace Foo\n"
"{\n"
" int i;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void noConstructor6() {
// ticket #4386
check("class Ccpucycles {\n"
" friend class foo::bar;\n"
" Ccpucycles() :\n"
" m_v(0), m_b(true)\n"
" {}\n"
"private:\n"
" cpucyclesT m_v;\n"
" bool m_b;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void noConstructor7() {
// ticket #4391
check("short bar;\n"
"class foo;");
ASSERT_EQUALS("", errout_str());
}
void noConstructor8() {
// ticket #4404
check("class LineSegment;\n"
"class PointArray { };\n"
"void* tech_ = NULL;");
ASSERT_EQUALS("", errout_str());
}
void noConstructor9() {
// ticket #4419
check("class CGreeting : public CGreetingBase<char> {\n"
"public:\n"
" CGreeting() : CGreetingBase<char>(), MessageSet(false) {}\n"
"private:\n"
" bool MessageSet;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void noConstructor10() {
// ticket #6614
check("class A : public wxDialog\n"
"{\n"
"private:\n"
" DECLARE_EVENT_TABLE()\n"
"public:\n"
" A(wxWindow *parent,\n"
" wxWindowID id = 1,\n"
" const wxString &title = wxT(" "),\n"
" const wxPoint& pos = wxDefaultPosition,\n"
" const wxSize& size = wxDefaultSize,\n"
" long style = wxDIALOG_NO_PARENT | wxMINIMIZE_BOX | wxMAXIMIZE_BOX | wxCLOSE_BOX);\n"
" virtual ~A();\n"
"private:\n"
" wxTimer *WxTimer1;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void noConstructor11() { // #3552
check("class Fred { int x; };\n"
"union U { int y; Fred fred; };");
ASSERT_EQUALS("", errout_str());
}
void noConstructor12() { // #8951
check("class Fred { int x{0}; };");
ASSERT_EQUALS("", errout_str());
check("class Fred { int x=0; };");
ASSERT_EQUALS("", errout_str());
check("class Fred { int x[1]={0}; };"); // #8850
ASSERT_EQUALS("", errout_str());
check("class Fred { int x[1]{0}; };");
ASSERT_EQUALS("", errout_str());
}
void noConstructor13() { // #9998
check("struct C { int v; };\n"
"struct B { C c[5] = {}; };\n"
"struct A {\n"
" A() {}\n"
" B b;\n"
"};\n");
ASSERT_EQUALS("", errout_str());
}
void noConstructor14() { // #10770
check("typedef void (*Func)();\n"
"class C {\n"
"public:\n"
" void f();\n"
"private:\n"
" Func fp = nullptr;\n"
"};\n");
ASSERT_EQUALS("", errout_str());
}
void noConstructor15() { // #5499
check("class C {\n"
"private:\n"
" int i1 = 0;\n"
" int i2;\n"
"};\n");
ASSERT_EQUALS("[test.cpp:4]: (warning) Member variable 'C::i2' is not initialized.\n", errout_str());
check("class C {\n"
"private:\n"
" int i1;\n"
" int i2;\n"
"};\n");
ASSERT_EQUALS("[test.cpp:1]: (style) The class 'C' does not declare a constructor although it has private member variables which likely require initialization.\n", errout_str());
check("class C {\n"
"public:\n"
" C(int i) : i1(i) {}\n"
"private:\n"
" int i1;\n"
" int i2;\n"
"};\n");
ASSERT_EQUALS("[test.cpp:3]: (warning) Member variable 'C::i2' is not initialized in the constructor.\n", errout_str());
}
// ticket #4290 "False Positive: style (noConstructor): The class 'foo' does not have a constructor."
// ticket #3190 "SymbolDatabase: Parse of sub class constructor fails"
void forwardDeclaration() {
check("class foo;\n"
"int bar;");
ASSERT_EQUALS("", errout_str());
check("class foo;\n"
"class foo;");
ASSERT_EQUALS("", errout_str());
check("class foo{};\n"
"class foo;");
ASSERT_EQUALS("", errout_str());
}
void initvar_with_this() {
check("struct Fred\n"
"{\n"
" Fred()\n"
" { this->i = 0; }\n"
" int i;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void initvar_if() {
check("struct Fred\n"
"{\n"
" Fred()\n"
" {\n"
" if (true)\n"
" i = 0;\n"
" else\n"
" i = 1;\n"
" }\n"
" int i;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void initvar_operator_eq1() {
// Bug 2190376 and #3820 - False positive, Uninitialized member variable with operator=
check("struct Fred\n"
"{\n"
" int i;\n"
"\n"
" Fred()\n"
" { i = 0; }\n"
"\n"
" Fred(const Fred &fred)\n"
" { *this = fred; }\n"
"\n"
" const Fred & operator=(const Fred &fred)\n"
" { i = fred.i; return *this; }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct Fred {\n"
" int i;\n"
"\n"
" Fred(const Fred &fred)\n"
" { (*this) = fred; }\n"
"\n"
" const Fred & operator=(const Fred &fred)\n"
" { i = fred.i; return *this; }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct A\n"
"{\n"
" A() : i(0), j(0) {}\n"
"\n"
" A &operator=(const int &value)\n"
" {\n"
" i = value;\n"
" return (*this);\n"
" }\n"
"\n"
" int i;\n"
" int j;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void initvar_operator_eq2() {
check("struct Fred\n"
"{\n"
" Fred() { i = 0; }\n"
" void operator=(const Fred &fred) { }\n"
" int i;\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (warning) Member variable 'Fred::i' is not assigned a value in 'Fred::operator='.\n", errout_str());
}
void initvar_operator_eq3() {
check("struct Fred\n"
"{\n"
" Fred() { Init(); }\n"
" void operator=(const Fred &fred) { Init(); }\n"
"private:\n"
" void Init() { i = 0; }\n"
" int i;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void initvar_operator_eq4() {
check("class Fred\n"
"{\n"
" int i;\n"
"public:\n"
" Fred() : i(5) { }\n"
" Fred & operator=(const Fred &fred)\n"
" {\n"
" if (&fred != this)\n"
" {\n"
" }\n"
" return *this\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:6]: (warning) Member variable 'Fred::i' is not assigned a value in 'Fred::operator='.\n", errout_str());
check("class Fred\n"
"{\n"
" int * i;\n"
"public:\n"
" Fred() : i(NULL) { }\n"
" Fred & operator=(const Fred &fred)\n"
" {\n"
" if (&fred != this)\n"
" {\n"
" }\n"
" return *this\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:6]: (warning) Member variable 'Fred::i' is not assigned a value in 'Fred::operator='.\n", errout_str());
check("class Fred\n"
"{\n"
" const int * i;\n"
"public:\n"
" Fred() : i(NULL) { }\n"
" Fred & operator=(const Fred &fred)\n"
" {\n"
" if (&fred != this)\n"
" {\n"
" }\n"
" return *this\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:6]: (warning) Member variable 'Fred::i' is not assigned a value in 'Fred::operator='.\n", errout_str());
check("class Fred\n"
"{\n"
" const int i;\n"
"public:\n"
" Fred() : i(5) { }\n"
" Fred & operator=(const Fred &fred)\n"
" {\n"
" if (&fred != this)\n"
" {\n"
" }\n"
" return *this\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void initvar_operator_eq5() { // #4119 - false positive when using swap to assign variables
check("class Fred {\n"
" int i;\n"
"public:\n"
" Fred() : i(5) { }\n"
" ~Fred() { }\n"
" Fred(const Fred &fred) : i(fred.i) { }\n"
" Fred & operator=(const Fred &rhs) {\n"
" Fred(rhs).swap(*this);\n"
" return *this;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void initvar_operator_eq6() { // std::vector
check("struct Fred {\n"
" uint8_t data;\n"
" Fred & operator=(const Fred &rhs) {\n"
" return *this;\n"
" }\n"
"};",true);
ASSERT_EQUALS("[test.cpp:3]: (warning, inconclusive) Member variable 'Fred::data' is not assigned a value in 'Fred::operator='.\n", errout_str());
check("struct Fred {\n"
" std::vector<int> ints;\n"
" Fred & operator=(const Fred &rhs) {\n"
" return *this;\n"
" }\n"
"};",true);
ASSERT_EQUALS("[test.cpp:3]: (warning, inconclusive) Member variable 'Fred::ints' is not assigned a value in 'Fred::operator='.\n", errout_str());
check("struct Fred {\n"
" Data data;\n"
" Fred & operator=(const Fred &rhs) {\n"
" return *this;\n"
" }\n"
"};",true);
ASSERT_EQUALS("[test.cpp:3]: (warning, inconclusive) Member variable 'Fred::data' is not assigned a value in 'Fred::operator='.\n", errout_str());
}
void initvar_operator_eq7() {
check("struct B {\n"
" virtual void CopyImpl(const B& Src) = 0;\n"
" void Copy(const B& Src);\n"
"};\n"
"struct D : B {};\n"
"struct DD : D {\n"
" void CopyImpl(const B& Src) override;\n"
" DD& operator=(const DD& Src);\n"
" int i{};\n"
"};\n"
"DD& DD::operator=(const DD& Src) {\n"
" if (this != &Src)\n"
" Copy(Src);\n"
" return *this;\n"
"}\n", true);
ASSERT_EQUALS("", errout_str());
}
void initvar_operator_eq8() {
check("struct B {\n"
" int b;\n"
"};\n"
"struct D1 : B {\n"
" D1& operator=(const D1& src);\n"
" int d1;\n"
"};\n"
"struct D2 : D1 {\n"
" D2& operator=(const D2& src);\n"
" int d2;\n"
"};\n"
"struct D3 : D2 {\n"
" D3& operator=(const D3& src) {\n"
" D1::operator=(src);\n"
" d3_1 = src.d3_1;\n"
" }\n"
" int d3_1;\n"
" int d3_2;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:13]: (warning) Member variable 'D3::d3_2' is not assigned a value in 'D3::operator='.\n"
"[test.cpp:13]: (warning) Member variable 'D3::d2' is not assigned a value in 'D3::operator='.\n", errout_str());
}
void initvar_operator_eq9() { // ticket #13203
check("struct S {\n"
" int* m_data;\n"
" S() : m_data(new int()) {}\n"
" S& operator=(const S& s) {\n"
" if (&s != this) {\n"
" *(m_data) = *(s.m_data);\n"
" }\n"
" return *this;\n"
" }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
}
void initvar_operator_eq10() {
check("struct S {\n"
" int* m_data;\n"
" S() : m_data(new int()) {}\n"
" S& operator=(const S& s) {\n"
" if (&s != this) {\n"
" (*m_data) = *(s.m_data);\n"
" }\n"
" return *this;\n"
" }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
}
void initvar_operator_eq11() {
check("struct S {\n"
" int* m_data;\n"
" S() : m_data(new int()) {}\n"
" S& operator=(const S& s) {\n"
" return *this;\n"
" }\n"
"};\n");
ASSERT_EQUALS("[test.cpp:4]: (warning) Member variable 'S::m_data' is not assigned a value in 'S::operator='.\n", errout_str());
}
void initvar_same_classname() {
// Bug 2208157 - False positive: Uninitialized variable, same class name
check("void func1()\n"
"{\n"
" class Fred\n"
" {\n"
" int a;\n"
" Fred() { a = 0; }\n"
" };\n"
"}\n"
"\n"
"void func2()\n"
"{\n"
" class Fred\n"
" {\n"
" int b;\n"
" Fred() { b = 0; }\n"
" };\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void func1()\n"
"{\n"
" struct Fred\n"
" {\n"
" int a;\n"
" Fred() { a = 0; }\n"
" };\n"
"}\n"
"\n"
"void func2()\n"
"{\n"
" class Fred\n"
" {\n"
" int b;\n"
" Fred() { b = 0; }\n"
" };\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void func1()\n"
"{\n"
" struct Fred\n"
" {\n"
" int a;\n"
" Fred() { a = 0; }\n"
" };\n"
"}\n"
"\n"
"void func2()\n"
"{\n"
" struct Fred\n"
" {\n"
" int b;\n"
" Fred() { b = 0; }\n"
" };\n"
"}");
ASSERT_EQUALS("", errout_str());
check("class Foo {\n"
" void func1()\n"
" {\n"
" struct Fred\n"
" {\n"
" int a;\n"
" Fred() { a = 0; }\n"
" };\n"
" }\n"
"\n"
" void func2()\n"
" {\n"
" struct Fred\n"
" {\n"
" int b;\n"
" Fred() { b = 0; }\n"
" };\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class Foo {\n"
" void func1()\n"
" {\n"
" struct Fred\n"
" {\n"
" int a;\n"
" Fred() { }\n"
" };\n"
" }\n"
"\n"
" void func2()\n"
" {\n"
" struct Fred\n"
" {\n"
" int b;\n"
" Fred() { }\n"
" };\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:7]: (warning) Member variable 'Fred::a' is not initialized in the constructor.\n"
"[test.cpp:16]: (warning) Member variable 'Fred::b' is not initialized in the constructor.\n", errout_str());
}
void initvar_chained_assign() {
// Bug 2270433 - Uninitialized variable false positive on chained assigns
check("struct c\n"
"{\n"
" c();\n"
"\n"
" int m_iMyInt1;\n"
" int m_iMyInt2;\n"
"}\n"
"\n"
"c::c()\n"
"{\n"
" m_iMyInt1 = m_iMyInt2 = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void initvar_2constructors() {
check("struct c\n"
"{\n"
" c();\n"
" explicit c(bool b);"
"\n"
" void InitInt();\n"
"\n"
" int m_iMyInt;\n"
" int m_bMyBool;\n"
"}\n"
"\n"
"c::c()\n"
"{\n"
" m_bMyBool = false;\n"
" InitInt();"
"}\n"
"\n"
"c::c(bool b)\n"
"{\n"
" m_bMyBool = b;\n"
" InitInt();\n"
"}\n"
"\n"
"void c::InitInt()\n"
"{\n"
" m_iMyInt = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void initvar_constvar() {
check("struct Fred\n"
"{\n"
" const char *s;\n"
" Fred();\n"
"};\n"
"Fred::Fred() : s(NULL)\n"
"{ }");
ASSERT_EQUALS("", errout_str());
check("struct Fred\n"
"{\n"
" const char *s;\n"
" Fred();\n"
"};\n"
"Fred::Fred()\n"
"{ s = NULL; }");
ASSERT_EQUALS("", errout_str());
check("struct Fred\n"
"{\n"
" const char *s;\n"
" Fred();\n"
"};\n"
"Fred::Fred()\n"
"{ }");
ASSERT_EQUALS("[test.cpp:6]: (warning) Member variable 'Fred::s' is not initialized in the constructor.\n", errout_str());
}
void initvar_mutablevar() {
check("class Foo {\n"
"public:\n"
" Foo() { update(); }\n"
"private:\n"
" void update() const;\n"
" mutable int x;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void initvar_staticvar() {
check("class Fred\n"
"{\n"
"public:\n"
" Fred() { }\n"
" static void *p;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void initvar_brace_init() { // #10142
check("class C\n"
"{\n"
"public:\n"
" C() {}\n"
"\n"
"private:\n"
" std::map<int, double> * values_{};\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void initvar_union() {
check("class Fred\n"
"{\n"
" union\n"
" {\n"
" int a;\n"
" char b[4];\n"
" } U;\n"
"public:\n"
" Fred()\n"
" {\n"
" U.a = 0;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class Fred\n"
"{\n"
" union\n"
" {\n"
" int a;\n"
" char b[4];\n"
" } U;\n"
"public:\n"
" Fred()\n"
" {\n"
" }\n"
"};");
TODO_ASSERT_EQUALS("[test.cpp:9]: (warning) Member variable 'Fred::U' is not initialized in the constructor.\n", "", errout_str());
}
void initvar_delegate() {
check("class A {\n"
" int number;\n"
"public:\n"
" A(int n) { }\n"
" A() : A(42) {}\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (warning) Member variable 'A::number' is not initialized in the constructor.\n"
"[test.cpp:5]: (warning) Member variable 'A::number' is not initialized in the constructor.\n", errout_str());
check("class A {\n"
" int number;\n"
"public:\n"
" A(int n) { number = n; }\n"
" A() : A(42) {}\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class A {\n"
" int number;\n"
"public:\n"
" A(int n) : A() { }\n"
" A() {}\n"
"};", true);
ASSERT_EQUALS("[test.cpp:4]: (warning) Member variable 'A::number' is not initialized in the constructor.\n"
"[test.cpp:5]: (warning, inconclusive) Member variable 'A::number' is not initialized in the constructor.\n", errout_str());
check("class A {\n"
" int number;\n"
"public:\n"
" A(int n) : A() { }\n"
" A() { number = 42; }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class A {\n"
" int number;\n"
"public:\n"
" A(int n) { }\n"
" A() : A{42} {}\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (warning) Member variable 'A::number' is not initialized in the constructor.\n"
"[test.cpp:5]: (warning) Member variable 'A::number' is not initialized in the constructor.\n", errout_str());
check("class A {\n"
" int number;\n"
"public:\n"
" A(int n) { number = n; }\n"
" A() : A{42} {}\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class A {\n"
" int number;\n"
"public:\n"
" A(int n) : A{} { }\n"
" A() {}\n"
"};", true);
ASSERT_EQUALS("[test.cpp:4]: (warning) Member variable 'A::number' is not initialized in the constructor.\n"
"[test.cpp:5]: (warning, inconclusive) Member variable 'A::number' is not initialized in the constructor.\n", errout_str());
check("class A {\n"
" int number;\n"
"public:\n"
" A(int n) : A{} { }\n"
" A() { number = 42; }\n"
"};");
ASSERT_EQUALS("", errout_str());
// Ticket #6675
check("struct Foo {\n"
" Foo();\n"
" Foo(int foo);\n"
" int foo_;\n"
"};\n"
"Foo::Foo() : Foo(0) {}\n"
"Foo::Foo(int foo) : foo_(foo) {}");
ASSERT_EQUALS("", errout_str());
// Noexcept ctors
check("class A {\n"
"private:\n"
" int _a;\n"
"public:\n"
" A(const int a) noexcept : _a{a} {}\n"
" A() noexcept;\n"
"};\n"
"\n"
"A::A() noexcept: A(0) {}");
ASSERT_EQUALS("", errout_str());
// Ticket #8581
check("class A {\n"
"private:\n"
" int _a;\n"
"public:\n"
" A(int a) : _a(a) {}\n"
" A(float a) : A(int(a)) {}\n"
"};");
ASSERT_EQUALS("", errout_str());
// Ticket #8258
check("struct F{};\n"
"struct Foo {\n"
" Foo(int a, F&& f, int b = 21) : _a(a), _b(b), _f(f) {}\n"
" Foo(int x, const char* value) : Foo(x, F(), 42) {}\n"
" Foo(int x, int* value) : Foo(x, F()) {}\n"
" int _a;\n"
" int _b;\n"
" F _f;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void initvar_delegate2() {
check("class Foo {\n"
"public:\n"
" explicit Foo(const Bar bar);\n"
" Foo(const std::string& id);\n"
" virtual ~RtpSession() { }\n"
"protected:\n"
" bool a;\n"
" uint16_t b;\n"
"};\n"
"\n"
"Foo::Foo(const Bar var)\n"
" : Foo(bar->getId())\n"
"{\n"
"}\n"
"\n"
"Foo::Foo(const std::string& id)\n"
" : a(true)\n"
" , b(0)\n"
"{\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void initvar_derived_class() {
check("class Base {\n" // #10161
"public:\n"
" virtual void foo() = 0;\n"
" int x;\n" // <- uninitialized
"};\n"
"\n"
"class Derived: public Base {\n"
"public:\n"
" Derived() {}\n"
" void foo() override;\n"
"};");
ASSERT_EQUALS("[test.cpp:9]: (warning) Member variable 'Base::x' is not initialized in the constructor. Maybe it should be initialized directly in the class Base?\n", errout_str());
check("struct A {\n" // #3462
" char ca;\n"
" A& operator=(const A& a) {\n"
" ca = a.ca;\n"
" return *this;\n"
" }\n"
"};\n"
"struct B : public A {\n"
" char cb;\n"
" B& operator=(const B& b) {\n"
" A::operator=(b);\n"
" return *this;\n"
" }\n"
"};\n");
ASSERT_EQUALS("[test.cpp:10]: (warning) Member variable 'B::cb' is not assigned a value in 'B::operator='.\n", errout_str());
check("struct A {\n"
" char ca;\n"
" A& operator=(const A& a) {\n"
" return *this;\n"
" }\n"
"};\n"
"struct B : public A {\n"
" char cb;\n"
" B& operator=(const B& b) {\n"
" A::operator=(b);\n"
" return *this;\n"
" }\n"
"};\n");
ASSERT_EQUALS("[test.cpp:3]: (warning) Member variable 'A::ca' is not assigned a value in 'A::operator='.\n"
"[test.cpp:9]: (warning) Member variable 'B::cb' is not assigned a value in 'B::operator='.\n"
"[test.cpp:9]: (warning) Member variable 'B::ca' is not assigned a value in 'B::operator='.\n",
errout_str());
check("class C : B {\n" // don't crash
" virtual C& operator=(C& c);\n"
"};\n"
"class D : public C {\n"
" virtual C& operator=(C& c) { return C::operator=(c); };\n"
"};\n");
ASSERT_EQUALS("", errout_str());
check("struct B;\n" // don't crash
"struct D : B { D& operator=(const D&); };\n"
"struct E : D { E& operator=(const E& rhs); };\n"
"E& E::operator=(const E& rhs) {\n"
" if (this != &rhs)\n"
" D::operator=(rhs);\n"
" return *this;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("template <class T>\n" // #12128
"struct B {\n"
" T x;\n"
"};\n"
"struct D : B<double> {\n"
" D(double x) : B{ x } {}\n"
"};\n");
ASSERT_EQUALS("", errout_str());
check("struct B {\n"
" int x;\n"
"};\n"
"struct D : B {\n"
" D(int i) : B{ i } {}\n"
"};\n");
ASSERT_EQUALS("", errout_str());
}
void initvar_derived_pod_struct_with_union() {
check("struct S {\n"
" union {\n"
" unsigned short all;\n"
" struct {\n"
" unsigned char flag1;\n"
" unsigned char flag2;\n"
" };\n"
" };\n"
"};\n"
"\n"
"class C : public S {\n"
"public:\n"
" C() { all = 0; tick = 0; }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct S {\n"
" union {\n"
" unsigned short all;\n"
" struct {\n"
" unsigned char flag1;\n"
" unsigned char flag2;\n"
" };\n"
" };\n"
"};\n"
"\n"
"class C : public S {\n"
"public:\n"
" C() { flag1 = flag2 = 0; tick = 0; }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct S {\n"
" union {\n"
" unsigned short all;\n"
" struct {\n"
" unsigned char flag1;\n"
" unsigned char flag2;\n"
" };\n"
" };\n"
"};\n"
"\n"
"class C : public S {\n"
"public:\n"
" C() {}\n"
"};");
ASSERT_EQUALS("[test.cpp:13]: (warning) Member variable 'S::all' is not initialized in the constructor. Maybe it should be initialized directly in the class S?\n"
"[test.cpp:13]: (warning) Member variable 'S::flag1' is not initialized in the constructor. Maybe it should be initialized directly in the class S?\n"
"[test.cpp:13]: (warning) Member variable 'S::flag2' is not initialized in the constructor. Maybe it should be initialized directly in the class S?\n", errout_str());
}
void initvar_private_constructor() {
{
const Settings s = settingsBuilder(settings).cpp( Standards::CPP11).build();
check("class Fred\n"
"{\n"
"private:\n"
" int var;\n"
" Fred();\n"
"};\n"
"Fred::Fred()\n"
"{ }", s);
ASSERT_EQUALS("[test.cpp:7]: (warning) Member variable 'Fred::var' is not initialized in the constructor.\n", errout_str());
}
{
const Settings s = settingsBuilder(settings).cpp(Standards::CPP03).build();
check("class Fred\n"
"{\n"
"private:\n"
" int var;\n"
" Fred();\n"
"};\n"
"Fred::Fred()\n"
"{ }", s);
ASSERT_EQUALS("", errout_str());
}
}
void initvar_copy_constructor() { // ticket #1611
check("class Fred\n"
"{\n"
"private:\n"
" std::string var;\n"
"public:\n"
" Fred() { };\n"
" Fred(const Fred &) { };\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class Fred\n"
"{\n"
"private:\n"
" std::string var;\n"
"public:\n"
" Fred() { };\n"
" Fred(const Fred &) { };\n"
"};", true);
ASSERT_EQUALS("[test.cpp:7]: (warning, inconclusive) Member variable 'Fred::var' is not assigned in the copy constructor. Should it be copied?\n", errout_str());
check("class Fred\n"
"{\n"
"private:\n"
" std::string var;\n"
"public:\n"
" Fred();\n"
" Fred(const Fred &);\n"
"};\n"
"Fred::Fred() { };\n"
"Fred::Fred(const Fred &) { };\n", true);
ASSERT_EQUALS("[test.cpp:10]: (warning, inconclusive) Member variable 'Fred::var' is not assigned in the copy constructor. Should it be copied?\n", errout_str());
check("class Baz {};\n" // #8496
"class Bar {\n"
"public:\n"
" explicit Bar(Baz* pBaz = NULL) : i(0) {}\n"
" Bar(const Bar& bar) {}\n"
" int i;\n"
"};\n", true);
ASSERT_EQUALS("[test.cpp:5]: (warning) Member variable 'Bar::i' is not initialized in the copy constructor.\n", errout_str());
}
void initvar_nested_constructor() { // ticket #1375
check("class A {\n"
"public:\n"
" A();\n"
" struct B {\n"
" explicit B(int x);\n"
" struct C {\n"
" explicit C(int y);\n"
" struct D {\n"
" int d;\n"
" explicit D(int z);\n"
" };\n"
" int c;\n"
" };\n"
" int b;\n"
" };\n"
"private:\n"
" int a;\n"
" B b;\n"
"};\n"
"A::A(){}\n"
"A::B::B(int x){}\n"
"A::B::C::C(int y){}\n"
"A::B::C::D::D(int z){}");
// Note that the example code is not compilable. The A constructor must
// explicitly initialize A::b. A warning for A::b is not necessary.
ASSERT_EQUALS("[test.cpp:20]: (warning) Member variable 'A::a' is not initialized in the constructor.\n"
"[test.cpp:21]: (warning) Member variable 'B::b' is not initialized in the constructor.\n"
"[test.cpp:22]: (warning) Member variable 'C::c' is not initialized in the constructor.\n"
"[test.cpp:23]: (warning) Member variable 'D::d' is not initialized in the constructor.\n", errout_str());
check("class A {\n"
"public:\n"
" A();\n"
" struct B {\n"
" explicit B(int x);\n"
" struct C {\n"
" explicit C(int y);\n"
" struct D {\n"
" D(const D &);\n"
" int d;\n"
" };\n"
" int c;\n"
" };\n"
" int b;\n"
" };\n"
"private:\n"
" int a;\n"
" B b;\n"
"};\n"
"A::A(){}\n"
"A::B::B(int x){}\n"
"A::B::C::C(int y){}\n"
"A::B::C::D::D(const A::B::C::D & d){}");
// Note that the example code is not compilable. The A constructor must
// explicitly initialize A::b. A warning for A::b is not necessary.
ASSERT_EQUALS("[test.cpp:20]: (warning) Member variable 'A::a' is not initialized in the constructor.\n"
"[test.cpp:21]: (warning) Member variable 'B::b' is not initialized in the constructor.\n"
"[test.cpp:22]: (warning) Member variable 'C::c' is not initialized in the constructor.\n"
"[test.cpp:23]: (warning) Member variable 'D::d' is not initialized in the copy constructor.\n", errout_str());
check("class A {\n"
"public:\n"
" A();\n"
" struct B {\n"
" explicit B(int x);\n"
" struct C {\n"
" explicit C(int y);\n"
" struct D {\n"
" struct E { int e; };\n"
" struct E d;\n"
" explicit D(const E &);\n"
" };\n"
" int c;\n"
" };\n"
" int b;\n"
" };\n"
"private:\n"
" int a;\n"
" B b;\n"
"};\n"
"A::A(){}\n"
"A::B::B(int x){}\n"
"A::B::C::C(int y){}\n"
"A::B::C::D::D(const A::B::C::D::E & e){}");
// Note that the example code is not compilable. The A constructor must
// explicitly initialize A::b. A warning for A::b is not necessary.
ASSERT_EQUALS("[test.cpp:21]: (warning) Member variable 'A::a' is not initialized in the constructor.\n"
"[test.cpp:22]: (warning) Member variable 'B::b' is not initialized in the constructor.\n"
"[test.cpp:23]: (warning) Member variable 'C::c' is not initialized in the constructor.\n"
"[test.cpp:24]: (warning) Member variable 'D::d' is not initialized in the constructor.\n", errout_str());
}
void initvar_nocopy1() { // ticket #2474
check("class B\n"
"{\n"
" B (const B & Var);\n"
"};\n"
"class A\n"
"{\n"
" B m_SemVar;\n"
"public:\n"
" A(){}\n"
" A(const A&){}\n"
" A(A &&){}\n"
" const A& operator=(const A&){return *this;}\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class B\n"
"{\n"
" B (B && Var);\n"
"};\n"
"class A\n"
"{\n"
" B m_SemVar;\n"
"public:\n"
" A(){}\n"
" A(const A&){}\n"
" A(A &&){}\n"
" const A& operator=(const A&){return *this;}\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class B\n"
"{\n"
" B & operator= (const B & Var);\n"
"public:\n"
" B ();\n"
"};\n"
"class A\n"
"{\n"
" B m_SemVar;\n"
"public:\n"
" A(){}\n"
" A(const A&){}\n"
" A(A &&){}\n"
" const A& operator=(const A&){return *this;}\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class B\n"
"{\n"
"public:\n"
" B (const B & Var);\n"
"};\n"
"class A\n"
"{\n"
" B m_SemVar;\n"
"public:\n"
" A(){}\n"
" A(const A&){}\n"
" A(A &&){}\n"
" const A& operator=(const A&){return *this;}\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class A : public std::vector<int>\n"
"{\n"
"public:\n"
" A(const A &a);\n"
"};\n"
"class B\n"
"{\n"
" A a;\n"
"public:\n"
" B(){}\n"
" B(const B&){}\n"
" B(B &&){}\n"
" const B& operator=(const B&){return *this;}\n"
"};", true);
ASSERT_EQUALS("[test.cpp:11]: (warning, inconclusive) Member variable 'B::a' is not assigned in the copy constructor. Should it be copied?\n"
"[test.cpp:12]: (warning, inconclusive) Member variable 'B::a' is not assigned in the move constructor. Should it be moved?\n"
"[test.cpp:13]: (warning, inconclusive) Member variable 'B::a' is not assigned a value in 'B::operator='.\n",
errout_str());
check("class B\n"
"{\n"
"public:\n"
" B (B && Var);\n"
" int data;\n"
"};\n"
"class A\n"
"{\n"
" B m_SemVar;\n"
"public:\n"
" A(){}\n"
" A(const A&){}\n"
" A(A &&){}\n"
" const A& operator=(const A&){return *this;}\n"
"};");
ASSERT_EQUALS("[test.cpp:13]: (warning) Member variable 'A::m_SemVar' is not initialized in the move constructor.\n", errout_str());
check("class B\n"
"{\n"
"public:\n"
" B ();\n"
" B & operator= (const B & Var);\n"
" int data;\n"
"};\n"
"class A\n"
"{\n"
" B m_SemVar;\n"
"public:\n"
" A(){}\n"
" A(const A&){}\n"
" A(A &&){}\n"
" const A& operator=(const A&){return *this;}\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class A\n"
"{\n"
" B m_SemVar;\n"
"public:\n"
" A(){}\n"
" A(const A&){}\n"
" const A& operator=(const A&){return *this;}\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void initvar_nocopy2() { // ticket #2484
check("class B\n"
"{\n"
" B (B & Var);\n"
" B & operator= (const B & Var);\n"
" int data;\n"
"};\n"
"class A\n"
"{\n"
" B m_SemVar;\n"
"public:\n"
" A(){}\n"
" A(const A&){}\n"
" const A& operator=(const A&){return *this;}\n"
"};", true);
ASSERT_EQUALS("", errout_str());
check("class B\n"
"{\n"
"public:\n"
" B (B & Var);\n"
" B & operator= (const B & Var);\n"
" int data;\n"
"};\n"
"class A\n"
"{\n"
" B m_SemVar;\n"
"public:\n"
" A(){}\n"
" A(const A&){}\n"
" const A& operator=(const A&){return *this;}\n"
"};", true);
ASSERT_EQUALS("[test.cpp:12]: (warning) Member variable 'A::m_SemVar' is not initialized in the constructor.\n"
"[test.cpp:13]: (warning) Member variable 'A::m_SemVar' is not initialized in the copy constructor.\n"
"[test.cpp:14]: (warning) Member variable 'A::m_SemVar' is not assigned a value in 'A::operator='.\n", errout_str());
}
void initvar_nocopy3() { // #3611 - unknown type is non-copyable
check("struct A {\n"
" B b;\n"
" A() {}\n"
" A(const A& rhs) {}\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct A {\n"
" B b;\n"
" A() {}\n"
" A(const A& rhs) {}\n"
"};", true);
ASSERT_EQUALS("[test.cpp:4]: (warning, inconclusive) Member variable 'A::b' is not assigned in the copy constructor. Should it be copied?\n", errout_str());
}
void initvar_nocopy4() { // #9247
check("struct S {\n"
" S(const S & s);\n"
" void S::Set(const T& val);\n"
" void S::Set(const U& val);\n"
" T t;\n"
"};\n"
"S::S(const S& s) {\n"
" Set(s.t);\n"
"}\n"
"void S::Set(const T& val) {\n"
" t = val;\n"
"}", /*inconclusive*/ true);
ASSERT_EQUALS("", errout_str());
}
void initvar_with_member_function_this() {
check("struct Foo {\n"
" Foo(int m) { this->setMember(m); }\n"
" void setMember(int m) { member = m; }\n"
" int member;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void initvar_destructor() {
check("class Fred\n"
"{\n"
"private:\n"
" int var;\n"
"public:\n"
" Fred() : var(0) {}\n"
" ~Fred() {}\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void initvar_func_ret_func_ptr() { // ticket #4449 (segmentation fault)
check("class something {\n"
" int * ( something :: * process()) () { return 0; }\n"
" something() { process(); }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void initvar_alias() { // #6921
check("struct S {\n"
" int a;\n"
" S() {\n"
" int& pa = a;\n"
" pa = 4;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct S {\n"
" int a;\n"
" S() {\n"
" int* pa = &a;\n"
" *pa = 4;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct S {\n"
" int a[2];\n"
" S() {\n"
" int* pa = a;\n"
" for (int i = 0; i < 2; i++)\n"
" *pa++ = i;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct S {\n"
" int* a[2];\n"
" S() {\n"
" int* pa = a[1];\n"
" *pa = 0;\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (warning) Member variable 'S::a' is not initialized in the constructor.\n", errout_str());
check("struct S {\n"
" int a;\n"
" S() {\n"
" int pa = a;\n"
" pa = 4;\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (warning) Member variable 'S::a' is not initialized in the constructor.\n", errout_str());
}
void initvar_templateMember() {
check("template<int n_>\n"
"struct Wrapper {\n"
" static void foo(int * x) {\n"
" for (int i(0); i <= n_; ++i)\n"
" x[i] = 5;\n"
" }\n"
"};\n"
"class A {\n"
"public:\n"
" static constexpr int dim = 5;\n"
" int x[dim + 1];\n"
" A() {\n"
" Wrapper<dim>::foo(x);\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void initvar_smartptr() { // #10237
// TODO: test should probably not pass without library
const Settings s = settingsBuilder() /*.library("std.cfg")*/.build();
check("struct S {\n"
" explicit S(const std::shared_ptr<S>& sp) {\n"
" set(*sp);\n"
" }\n"
" double get() const {\n"
" return d;\n"
" }\n"
" void set(const S& rhs) {\n"
" d = rhs.get();\n"
" }\n"
" double d;\n"
"};", s);
ASSERT_EQUALS("", errout_str());
check("struct S {\n" // #8485
" explicit S(const T& rhs) { set(*rhs); }\n"
" void set(const S& v) {\n"
" d = v.d;\n"
" }\n"
" double d; \n"
"};\n");
ASSERT_EQUALS("", errout_str());
}
void operatorEqSTL() {
check("class Fred\n"
"{\n"
"private:\n"
" std::vector<int> ints;\n"
"public:\n"
" Fred();\n"
" void operator=(const Fred &f);\n"
"};\n"
"\n"
"Fred::Fred()\n"
"{ }\n"
"\n"
"void Fred::operator=(const Fred &f)\n"
"{ }", true);
ASSERT_EQUALS("[test.cpp:13]: (warning, inconclusive) Member variable 'Fred::ints' is not assigned a value in 'Fred::operator='.\n", errout_str());
const Settings s = settingsBuilder().certainty(Certainty::inconclusive).severity(Severity::style).severity(Severity::warning).library("std.cfg").build();
check("struct S {\n"
" S& operator=(const S& s) { return *this; }\n"
" std::mutex m;\n"
"};\n", s);
ASSERT_EQUALS("", errout_str());
}
void uninitVar1() {
check("enum ECODES\n"
"{\n"
" CODE_1 = 0,\n"
" CODE_2 = 1\n"
"};\n"
"\n"
"class Fred\n"
"{\n"
"public:\n"
" Fred() {}\n"
"\n"
"private:\n"
" ECODES _code;\n"
"};");
ASSERT_EQUALS("[test.cpp:10]: (warning) Member variable 'Fred::_code' is not initialized in the constructor.\n", errout_str());
check("class A{};\n"
"\n"
"class B : public A\n"
"{\n"
"public:\n"
" B() {}\n"
"private:\n"
" float f;\n"
"};");
ASSERT_EQUALS("[test.cpp:6]: (warning) Member variable 'B::f' is not initialized in the constructor.\n", errout_str());
check("class C\n"
"{\n"
" FILE *fp;\n"
"\n"
"public:\n"
" explicit C(FILE *fp);\n"
"};\n"
"\n"
"C::C(FILE *fp) {\n"
" C::fp = fp;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void uninitVar2() {
check("class John\n"
"{\n"
"public:\n"
" John() { (*this).i = 0; }\n"
"private:\n"
" int i;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void uninitVar3() {
// No FP when struct has constructor
check("class Foo\n"
"{\n"
"public:\n"
" Foo() { }\n"
"private:\n"
" struct Bar {\n"
" Bar();\n"
" };\n"
" Bar bars[2];\n"
"};");
ASSERT_EQUALS("", errout_str());
// Using struct that doesn't have constructor
check("class Foo\n"
"{\n"
"public:\n"
" Foo() { }\n"
"private:\n"
" struct Bar {\n"
" int x;\n"
" };\n"
" Bar bars[2];\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (warning) Member variable 'Foo::bars' is not initialized in the constructor.\n", errout_str());
}
void uninitVar4() {
check("class Foo\n"
"{\n"
"public:\n"
" Foo() { bar.x = 0; }\n"
"private:\n"
" struct Bar {\n"
" int x;\n"
" };\n"
" struct Bar bar;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void uninitVar5() {
check("class Foo\n"
"{\n"
"public:\n"
" Foo() { }\n"
" Foo &operator=(const Foo &)\n"
" { return *this; }\n"
" static int i;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void uninitVar6() {
check("class Foo : public Bar\n"
"{\n"
"public:\n"
" explicit Foo(int i) : Bar(mi=i) { }\n"
"private:\n"
" int mi;\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class Foo : public Bar\n"
"{\n"
"public:\n"
" explicit Foo(int i) : Bar{mi=i} { }\n"
"private:\n"
" int mi;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void uninitVar7() {
check("class Foo {\n"
" int a;\n"
"public:\n"
" Foo() : a(0) {}\n"
" Foo& operator=(const Foo&);\n"
" void Swap(Foo& rhs);\n"
"};\n"
"\n"
"void Foo::Swap(Foo& rhs) {\n"
" std::swap(a,rhs.a);\n"
"}\n"
"\n"
"Foo& Foo::operator=(const Foo& rhs) {\n"
" Foo copy(rhs);\n"
" copy.Swap(*this);\n"
" return *this;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void uninitVar8() {
check("class Foo {\n"
" int a;\n"
"public:\n"
" Foo() : a(0) {}\n"
" Foo& operator=(const Foo&);\n"
"};\n"
"\n"
"Foo& Foo::operator=(const Foo& rhs) {\n"
" if (&rhs != this)\n"
" {\n"
" }\n"
" return *this;\n"
"}");
ASSERT_EQUALS("[test.cpp:8]: (warning) Member variable 'Foo::a' is not assigned a value in 'Foo::operator='.\n", errout_str());
}
void uninitVar9() { // ticket #1730
check("class Prefs {\n"
"private:\n"
" int xasd;\n"
"public:\n"
" explicit Prefs(wxSize size);\n"
"};\n"
"Prefs::Prefs(wxSize size)\n"
"{\n"
" SetMinSize( wxSize( 48,48 ) );\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (warning) Member variable 'Prefs::xasd' is not initialized in the constructor.\n", errout_str());
}
void uninitVar10() { // ticket #1993
check("class A {\n"
"public:\n"
" A();\n"
"private:\n"
" int var1;\n"
" int var2;\n"
"};\n"
"A::A() : var1(0) { }");
ASSERT_EQUALS("[test.cpp:8]: (warning) Member variable 'A::var2' is not initialized in the constructor.\n", errout_str());
}
void uninitVar11() {
check("class A {\n"
"public:\n"
" explicit A(int a = 0);\n"
"private:\n"
" int var;\n"
"};\n"
"A::A(int a) { }");
ASSERT_EQUALS("[test.cpp:7]: (warning) Member variable 'A::var' is not initialized in the constructor.\n", errout_str());
}
void uninitVar12() { // ticket #2078
check("class Point\n"
"{\n"
"public:\n"
" Point()\n"
" {\n"
" Point(0, 0);\n"
" }\n"
" Point(int x, int y)\n"
" : x(x), y(y)\n"
" {}\n"
" int x, y;\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (warning) Member variable 'Point::x' is not initialized in the constructor.\n"
"[test.cpp:4]: (warning) Member variable 'Point::y' is not initialized in the constructor.\n", errout_str());
}
void uninitVar13() { // ticket #1195
check("class A {\n"
"private:\n"
" std::vector<int> *ints;\n"
"public:\n"
" A()\n"
" {}\n"
"};");
ASSERT_EQUALS("[test.cpp:5]: (warning) Member variable 'A::ints' is not initialized in the constructor.\n", errout_str());
}
void uninitVar14() { // ticket #2149
// no namespace
check("class Foo\n"
"{\n"
"public:\n"
" Foo();\n"
"private:\n"
" bool mMember;\n"
"};\n"
"Foo::Foo()\n"
"{\n"
"}");
ASSERT_EQUALS("[test.cpp:8]: (warning) Member variable 'Foo::mMember' is not initialized in the constructor.\n", errout_str());
// single namespace
check("namespace Output\n"
"{\n"
" class Foo\n"
" {\n"
" public:\n"
" Foo();\n"
" private:\n"
" bool mMember;\n"
" };\n"
" Foo::Foo()\n"
" {\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:10]: (warning) Member variable 'Foo::mMember' is not initialized in the constructor.\n", errout_str());
// constructor outside namespace
check("namespace Output\n"
"{\n"
" class Foo\n"
" {\n"
" public:\n"
" Foo();\n"
" private:\n"
" bool mMember;\n"
" };\n"
"}\n"
"Foo::Foo()\n"
"{\n"
"}");
ASSERT_EQUALS("", errout_str());
// constructor outside namespace
check("namespace Output\n"
"{\n"
" class Foo\n"
" {\n"
" public:\n"
" Foo();\n"
" private:\n"
" bool mMember;\n"
" };\n"
"}\n"
"Output::Foo::Foo()\n"
"{\n"
"}");
ASSERT_EQUALS("[test.cpp:11]: (warning) Member variable 'Foo::mMember' is not initialized in the constructor.\n", errout_str());
// constructor outside namespace with using, #4792
check("namespace Output\n"
"{\n"
" class Foo\n"
" {\n"
" public:\n"
" Foo();\n"
" private:\n"
" bool mMember;\n"
" };\n"
"}\n"
"using namespace Output;"
"Foo::Foo()\n"
"{\n"
"}");
ASSERT_EQUALS("[test.cpp:11]: (warning) Member variable 'Foo::mMember' is not initialized in the constructor.\n", errout_str());
// constructor in separate namespace
check("namespace Output\n"
"{\n"
" class Foo\n"
" {\n"
" public:\n"
" Foo();\n"
" private:\n"
" bool mMember;\n"
" };\n"
"}\n"
"namespace Output\n"
"{\n"
" Foo::Foo()\n"
" {\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:13]: (warning) Member variable 'Foo::mMember' is not initialized in the constructor.\n", errout_str());
// constructor in different separate namespace
check("namespace Output\n"
"{\n"
" class Foo\n"
" {\n"
" public:\n"
" Foo();\n"
" private:\n"
" bool mMember;\n"
" };\n"
"}\n"
"namespace Input\n"
"{\n"
" Foo::Foo()\n"
" {\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// constructor in different separate namespace (won't compile)
check("namespace Output\n"
"{\n"
" class Foo\n"
" {\n"
" public:\n"
" Foo();\n"
" private:\n"
" bool mMember;\n"
" };\n"
"}\n"
"namespace Input\n"
"{\n"
" Output::Foo::Foo()\n"
" {\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// constructor in nested separate namespace
check("namespace A\n"
"{\n"
" namespace Output\n"
" {\n"
" class Foo\n"
" {\n"
" public:\n"
" Foo();\n"
" private:\n"
" bool mMember;\n"
" };\n"
" }\n"
" namespace Output\n"
" {\n"
" Foo::Foo()\n"
" {\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:15]: (warning) Member variable 'Foo::mMember' is not initialized in the constructor.\n", errout_str());
// constructor in nested different separate namespace
check("namespace A\n"
"{\n"
" namespace Output\n"
" {\n"
" class Foo\n"
" {\n"
" public:\n"
" Foo();\n"
" private:\n"
" bool mMember;\n"
" };\n"
" }\n"
" namespace Input\n"
" {\n"
" Foo::Foo()\n"
" {\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// constructor in nested different separate namespace
check("namespace A\n"
"{\n"
" namespace Output\n"
" {\n"
" class Foo\n"
" {\n"
" public:\n"
" Foo();\n"
" private:\n"
" bool mMember;\n"
" };\n"
" }\n"
" namespace Input\n"
" {\n"
" Output::Foo::Foo()\n"
" {\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void uninitVar15() {
check("class Fred\n"
"{\n"
" int a;\n"
"public:\n"
" Fred();\n"
" ~Fred();\n"
"};\n"
"Fred::~Fred()\n"
"{\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void uninitVar16() {
check("struct Foo\n"
"{\n"
" int a;\n"
" void set(int x) { a = x; }\n"
"};\n"
"class Bar\n"
"{\n"
" Foo foo;\n"
"public:\n"
" Bar()\n"
" {\n"
" foo.set(0);\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct Foo\n"
"{\n"
" int a;\n"
" void set(int x) { a = x; }\n"
"};\n"
"class Bar\n"
"{\n"
" Foo foo;\n"
"public:\n"
" Bar()\n"
" {\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:10]: (warning) Member variable 'Bar::foo' is not initialized in the constructor.\n", errout_str());
}
void uninitVar17() {
check("struct Foo\n"
"{\n"
" int a;\n"
"};\n"
"class Bar\n"
"{\n"
" Foo foo[10];\n"
"public:\n"
" Bar()\n"
" {\n"
" foo[0].a = 0;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct Foo\n"
"{\n"
" int a;\n"
"};\n"
"class Bar\n"
"{\n"
" Foo foo[10];\n"
"public:\n"
" Bar()\n"
" {\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:9]: (warning) Member variable 'Bar::foo' is not initialized in the constructor.\n", errout_str());
}
void uninitVar18() { // ticket #2465
check("struct Altren\n"
"{\n"
" explicit Altren(int _a = 0) : value(0) { }\n"
" int value;\n"
"};\n"
"class A\n"
"{\n"
"public:\n"
" A() { }\n"
"private:\n"
" Altren value;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void uninitVar19() { // ticket #2792
check("class mystring\n"
"{\n"
" char* m_str;\n"
" int m_len;\n"
"public:\n"
" explicit mystring(const char* str)\n"
" {\n"
" m_len = strlen(str);\n"
" m_str = (char*) malloc(m_len+1);\n"
" memcpy(m_str, str, m_len+1);\n"
" }\n"
" mystring& operator=(const mystring& copy)\n"
" {\n"
" return (*this = copy.m_str);\n"
" }\n"
" ~mystring()\n"
" {\n"
" free(m_str);\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void uninitVar20() { // ticket #2867
check("Object::MemFunc() {\n"
" class LocalClass {\n"
" public:\n"
" LocalClass() : dataLength_(0) {}\n"
" std::streamsize dataLength_;\n"
" double bitsInData_;\n"
" } obj;\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (warning) Member variable 'LocalClass::bitsInData_' is not initialized in the constructor.\n", errout_str());
check("struct copy_protected;\n"
"Object::MemFunc() {\n"
" class LocalClass : public copy_protected {\n"
" public:\n"
" LocalClass() : copy_protected(1), dataLength_(0) {}\n"
" std::streamsize dataLength_;\n"
" double bitsInData_;\n"
" } obj;\n"
"};");
ASSERT_EQUALS(
"[test.cpp:5]: (warning) Member variable 'LocalClass::bitsInData_' is not initialized in the constructor.\n",
errout_str());
check("struct copy_protected;\n"
"Object::MemFunc() {\n"
" class LocalClass : ::copy_protected {\n"
" public:\n"
" LocalClass() : copy_protected(1), dataLength_(0) {}\n"
" std::streamsize dataLength_;\n"
" double bitsInData_;\n"
" } obj;\n"
"};");
ASSERT_EQUALS(
"[test.cpp:5]: (warning) Member variable 'LocalClass::bitsInData_' is not initialized in the constructor.\n",
errout_str());
}
void uninitVar21() { // ticket #2947
check("class Fred {\n"
"private:\n"
" int a[23];\n"
"public:\n"
" Fred();\n"
"};\n"
"Fred::Fred() {\n"
" a[x::y] = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void uninitVar22() { // ticket #3043
check("class Fred {\n"
" public:\n"
" Fred & operator=(const Fred &);\n"
" virtual Fred & clone(const Fred & other);\n"
" int x;\n"
"};\n"
"Fred & Fred::operator=(const Fred & other) {\n"
" return clone(other);\n"
"}\n"
"Fred & Fred::clone(const Fred & other) {\n"
" x = 0;\n"
" return *this;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("class Fred {\n"
" public:\n"
" Fred & operator=(const Fred &);\n"
" virtual Fred & clone(const Fred & other);\n"
" int x;\n"
"};\n"
"Fred & Fred::operator=(const Fred & other) {\n"
" return clone(other);\n"
"}\n"
"Fred & Fred::clone(const Fred & other) {\n"
" return *this;\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (warning) Member variable 'Fred::x' is not assigned a value in 'Fred::operator='.\n", errout_str());
}
void uninitVar23() { // ticket #3702
check("class Fred {\n"
" int x;\n"
"public:\n"
" Fred(struct A a, struct B b);\n"
" Fred(C c, struct D d);\n"
" Fred(struct E e, F f);\n"
" Fred(struct G, struct H);\n"
" Fred(I, J);\n"
"};\n"
"Fred::Fred(A a, B b) { }\n"
"Fred::Fred(struct C c, D d) { }\n"
"Fred::Fred(E e, struct F f) { }\n"
"Fred::Fred(G g, H h) { }\n"
"Fred::Fred(struct I i, struct J j) { }");
ASSERT_EQUALS("[test.cpp:10]: (warning) Member variable 'Fred::x' is not initialized in the constructor.\n"
"[test.cpp:11]: (warning) Member variable 'Fred::x' is not initialized in the constructor.\n"
"[test.cpp:12]: (warning) Member variable 'Fred::x' is not initialized in the constructor.\n"
"[test.cpp:13]: (warning) Member variable 'Fred::x' is not initialized in the constructor.\n"
"[test.cpp:14]: (warning) Member variable 'Fred::x' is not initialized in the constructor.\n", errout_str());
}
void uninitVar24() { // ticket #3190
check("class Foo;\n"
"class Bar;\n"
"class Sub;\n"
"class Foo { class Sub; };\n"
"class Bar { class Sub; };\n"
"class Bar::Sub {\n"
" int b;\n"
"public:\n"
" Sub() { }\n"
" Sub(int);\n"
"};\n"
"Bar::Sub::Sub(int) { };\n"
"class ::Foo::Sub {\n"
" int f;\n"
"public:\n"
" ~Sub();\n"
" Sub();\n"
"};\n"
"::Foo::Sub::~Sub() { }\n"
"::Foo::Sub::Sub() { }\n"
"class Foo;\n"
"class Bar;\n"
"class Sub;\n", true);
ASSERT_EQUALS("[test.cpp:9]: (warning, inconclusive) Member variable 'Sub::b' is not initialized in the constructor.\n"
"[test.cpp:12]: (warning) Member variable 'Sub::b' is not initialized in the constructor.\n"
"[test.cpp:20]: (warning) Member variable 'Sub::f' is not initialized in the constructor.\n", errout_str());
}
void uninitVar25() { // ticket #4789
check("struct A {\n"
" int a;\n"
" int b;\n"
" int c;\n"
" A(int x = 0, int y = 0, int z = 0);\n"
"};\n"
"A::A(int x = 0, int y = 0, int z = 0) { }\n"
"struct B {\n"
" int a;\n"
" int b;\n"
" int c;\n"
" B(int x = 0, int y = 0, int z = 0);\n"
"};\n"
"B::B(int x, int y, int z) { }\n"
"struct C {\n"
" int a;\n"
" int b;\n"
" int c;\n"
" C(int, int, int);\n"
"};\n"
"C::C(int x = 0, int y = 0, int z = 0) { }\n"
"struct D {\n"
" int a;\n"
" int b;\n"
" int c;\n"
" D(int, int, int);\n"
"};\n"
"D::D(int x, int y, int z) { }\n"
"struct E {\n"
" int a;\n"
" int b;\n"
" int c;\n"
" E(int x, int y, int z);\n"
"};\n"
"E::E(int, int, int) { }\n"
"struct F {\n"
" int a;\n"
" int b;\n"
" int c;\n"
" F(int x = 0, int y = 0, int z = 0);\n"
"};\n"
"F::F(int, int, int) { }\n", true);
ASSERT_EQUALS("[test.cpp:7]: (warning) Member variable 'A::a' is not initialized in the constructor.\n"
"[test.cpp:7]: (warning) Member variable 'A::b' is not initialized in the constructor.\n"
"[test.cpp:7]: (warning) Member variable 'A::c' is not initialized in the constructor.\n"
"[test.cpp:14]: (warning) Member variable 'B::a' is not initialized in the constructor.\n"
"[test.cpp:14]: (warning) Member variable 'B::b' is not initialized in the constructor.\n"
"[test.cpp:14]: (warning) Member variable 'B::c' is not initialized in the constructor.\n"
"[test.cpp:21]: (warning) Member variable 'C::a' is not initialized in the constructor.\n"
"[test.cpp:21]: (warning) Member variable 'C::b' is not initialized in the constructor.\n"
"[test.cpp:21]: (warning) Member variable 'C::c' is not initialized in the constructor.\n"
"[test.cpp:28]: (warning) Member variable 'D::a' is not initialized in the constructor.\n"
"[test.cpp:28]: (warning) Member variable 'D::b' is not initialized in the constructor.\n"
"[test.cpp:28]: (warning) Member variable 'D::c' is not initialized in the constructor.\n"
"[test.cpp:35]: (warning) Member variable 'E::a' is not initialized in the constructor.\n"
"[test.cpp:35]: (warning) Member variable 'E::b' is not initialized in the constructor.\n"
"[test.cpp:35]: (warning) Member variable 'E::c' is not initialized in the constructor.\n"
"[test.cpp:42]: (warning) Member variable 'F::a' is not initialized in the constructor.\n"
"[test.cpp:42]: (warning) Member variable 'F::b' is not initialized in the constructor.\n"
"[test.cpp:42]: (warning) Member variable 'F::c' is not initialized in the constructor.\n", errout_str());
}
void uninitVar26() {
check("class A {\n"
" int * v;\n"
" int sz;\n"
"public:\n"
" A(int s) {\n"
" v = new int [sz = s];\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void uninitVar27() {
check("class A {\n"
" double d;\n"
"public:\n"
" A() {\n"
" rtl::math::setNan(&d);\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class A {\n"
" double d;\n"
"public:\n"
" A() {\n"
" ::rtl::math::setNan(&d);\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void uninitVar28() {
check("class Fred {\n"
" int i;\n"
" float f;\n"
"public:\n"
" Fred() {\n"
" foo(1);\n"
" foo(1.0f);\n"
" }\n"
" void foo(int a) { i = a; }\n"
" void foo(float a) { f = a; }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void uninitVar29() {
check("class A {\n"
" int i;\n"
"public:\n"
" A() { foo(); }\n"
" void foo() const { };\n"
" void foo() { i = 0; }\n"
"};\n"
"class B {\n"
" int i;\n"
"public:\n"
" B() { foo(); }\n"
" void foo() { i = 0; }\n"
" void foo() const { }\n"
"};\n"
"class C {\n"
" int i;\n"
"public:\n"
" C() { foo(); }\n"
" void foo() const { i = 0; }\n"
" void foo() { }\n"
"};\n"
"class D {\n"
" int i;\n"
"public:\n"
" D() { foo(); }\n"
" void foo() { }\n"
" void foo() const { i = 0; }\n"
"};");
ASSERT_EQUALS("[test.cpp:18]: (warning) Member variable 'C::i' is not initialized in the constructor.\n"
"[test.cpp:25]: (warning) Member variable 'D::i' is not initialized in the constructor.\n", errout_str());
}
void uninitVar30() { // ticket #6417
check("namespace NS {\n"
" class MyClass {\n"
" public:\n"
" MyClass();\n"
" ~MyClass();\n"
" private:\n"
" bool SomeVar;\n"
" };\n"
"}\n"
"using namespace NS;\n"
"MyClass::~MyClass() { }\n"
"MyClass::MyClass() : SomeVar(false) { }");
ASSERT_EQUALS("", errout_str());
}
void uninitVar31() { // ticket #8271
check("void bar();\n"
"class MyClass {\n"
"public:\n"
" MyClass();\n"
" void Restart();\n"
"protected:\n"
" int m_retCode;\n"
"};\n"
"MyClass::MyClass() {\n"
" bar(),Restart();\n"
"}\n"
"void MyClass::Restart() {\n"
" m_retCode = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void uninitVar32() { // ticket #8835
check("class Foo {\n"
" friend class Bar;\n"
" int member;\n"
"public:\n"
" Foo()\n"
" {\n"
" if (1) {}\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:5]: (warning) Member variable 'Foo::member' is not initialized in the constructor.\n", errout_str());
check("class Foo {\n"
" friend class Bar;\n"
" int member;\n"
"public:\n"
" Foo()\n"
" {\n"
" while (1) {}\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:5]: (warning) Member variable 'Foo::member' is not initialized in the constructor.\n", errout_str());
check("class Foo {\n"
" friend class Bar;\n"
" int member;\n"
"public:\n"
" Foo()\n"
" {\n"
" for (;;) {}\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:5]: (warning) Member variable 'Foo::member' is not initialized in the constructor.\n", errout_str());
}
void uninitVar33() { // ticket #10295
check("namespace app {\n"
" class B {\n"
" public:\n"
" B(void);\n"
" int x;\n"
" };\n"
"};\n"
"app::B::B(void){}");
ASSERT_EQUALS("[test.cpp:8]: (warning) Member variable 'B::x' is not initialized in the constructor.\n", errout_str());
}
void uninitVar34() { // ticket #10841
check("struct A { void f() {} };\n"
"struct B {\n"
" B() { a->f(); }\n"
" A* a;\n"
"};\n");
ASSERT_EQUALS("[test.cpp:3]: (warning) Member variable 'B::a' is not initialized in the constructor.\n", errout_str());
}
void uninitVar35() {
check("struct S {\n" // #12908
" int a, b;\n"
" explicit S(int h = 0);\n"
" S(S&& s) : a(s.a), b(a.b) {\n"
" s.a = 0;\n"
" }\n"
"};\n"
"S::S(int h) : a(h), b(0) {}\n");
ASSERT_EQUALS("", errout_str());
}
void uninitVarArray1() {
check("class John\n"
"{\n"
"public:\n"
" John() {}\n"
"\n"
"private:\n"
" char name[255];\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (warning) Member variable 'John::name' is not initialized in the constructor.\n", errout_str());
check("class John\n"
"{\n"
"public:\n"
" John() {John::name[0] = '\\0';}\n"
"\n"
"private:\n"
" char name[255];\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class John\n"
"{\n"
"public:\n"
" John() { strcpy(name, \"\"); }\n"
"\n"
"private:\n"
" char name[255];\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class John\n"
"{\n"
"public:\n"
" John() { }\n"
"\n"
" double operator[](const unsigned long i);\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class A;\n"
"class John\n"
"{\n"
"public:\n"
" John() { }\n"
" A a[5];\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class A;\n"
"class John\n"
"{\n"
"public:\n"
" John() { }\n"
" A (*a)[5];\n"
"};");
ASSERT_EQUALS("[test.cpp:5]: (warning) Member variable 'John::a' is not initialized in the constructor.\n", errout_str());
}
void uninitVarArray2() {
check("class John\n"
"{\n"
"public:\n"
" John() { *name = 0; }\n"
"\n"
"private:\n"
" char name[255];\n"
"};");
ASSERT_EQUALS("", errout_str());
// #5754
check("class John\n"
"{\n"
"public:\n"
" John() {*this->name = '\\0';}\n"
"\n"
"private:\n"
" char name[255];\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void uninitVarArray3() {
check("class John\n"
"{\n"
"private:\n"
" int a[100];\n"
" int b[100];\n"
"\n"
"public:\n"
" John()\n"
" {\n"
" memset(a,0,sizeof(a));\n"
" memset(b,0,sizeof(b));\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void uninitVarArray4() {
check("class John\n"
"{\n"
"private:\n"
" int a[100];\n"
" int b[100];\n"
"\n"
"public:\n"
" John()\n"
" {\n"
" if (snprintf(a,10,\"a\")) { }\n"
" if (snprintf(b,10,\"b\")) { }\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void uninitVarArray5() {
check("class Foo\n"
"{\n"
"private:\n"
" Bar bars[10];\n"
"public:\n"
" Foo()\n"
" { }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void uninitVarArray6() {
check("class Foo\n"
"{\n"
"public:\n"
" Foo();\n"
" static const char STR[];\n"
"};\n"
"const char Foo::STR[] = \"abc\";\n"
"Foo::Foo() { }");
ASSERT_EQUALS("", errout_str());
}
void uninitVarArray7() {
check("class Foo\n"
"{\n"
" int array[10];\n"
"public:\n"
" Foo() { }\n"
"};");
ASSERT_EQUALS("[test.cpp:5]: (warning) Member variable 'Foo::array' is not initialized in the constructor.\n", errout_str());
check("class Foo\n"
"{\n"
" int array[10];\n"
"public:\n"
" Foo() { memset(array, 0, sizeof(array)); }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class Foo\n"
"{\n"
" int array[10];\n"
"public:\n"
" Foo() { ::memset(array, 0, sizeof(array)); }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void uninitVarArray8() {
check("class Foo {\n"
" char a[10];\n"
"public:\n"
" Foo() { ::ZeroMemory(a); }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void uninitVarArray9() { // #6957
check("class BaseGDL;\n"
"struct IxExprListT {\n"
"private:\n"
" BaseGDL* eArr[3];\n"
"public:\n"
" IxExprListT() {}\n"
"};");
ASSERT_EQUALS("[test.cpp:6]: (warning) Member variable 'IxExprListT::eArr' is not initialized in the constructor.\n", errout_str());
check("struct sRAIUnitDefBL {\n"
" sRAIUnitDefBL();\n"
" ~sRAIUnitDefBL();\n"
"};\n"
"struct sRAIUnitDef {\n"
" sRAIUnitDef() {}\n"
" sRAIUnitDefBL *List[35];\n"
"};");
ASSERT_EQUALS("[test.cpp:6]: (warning) Member variable 'sRAIUnitDef::List' is not initialized in the constructor.\n", errout_str());
}
void uninitVarArray10() { // #11650
const Settings s = settingsBuilder(settings).library("std.cfg").build();
check("struct T { int j; };\n"
"struct U { int k{}; };\n"
"struct S {\n"
" std::array<int, 2> a;\n"
" std::array<T, 2> b;\n"
" std::array<std::size_t, 2> c;\n"
" std::array<clock_t, 2> d;\n"
" std::array<std::string, 2> e;\n"
" std::array<U, 2> f;\n"
"S() {}\n"
"};\n", s);
ASSERT_EQUALS("[test.cpp:10]: (warning) Member variable 'S::a' is not initialized in the constructor.\n"
"[test.cpp:10]: (warning) Member variable 'S::b' is not initialized in the constructor.\n"
"[test.cpp:10]: (warning) Member variable 'S::c' is not initialized in the constructor.\n"
"[test.cpp:10]: (warning) Member variable 'S::d' is not initialized in the constructor.\n",
errout_str());
}
void uninitVarArray11() {
check("class C {\n" // #12150
"private:\n"
" int buf[10];\n"
"public:\n"
" C() {\n"
" for (int& i : buf)\n"
" i = 0;\n"
" }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
}
void uninitVarArray2D() {
check("class John\n"
"{\n"
"public:\n"
" John() { a[0][0] = 0; }\n"
"\n"
"private:\n"
" char a[2][2];\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void uninitVarArray3D() {
check("class John\n"
"{\n"
"private:\n"
" char a[2][2][2];\n"
"public:\n"
" John() { a[0][0][0] = 0; }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void uninitVarCpp11Init1() {
check("class Foo {\n"
" std::vector<std::string> bar;\n"
"public:\n"
" Foo()\n"
" : bar({\"a\", \"b\"})\n"
" {}\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void uninitVarCpp11Init2() {
check("class Fred {\n"
" struct Foo {\n"
" int a;\n"
" bool b;\n"
" };\n"
" Foo f;\n"
" float g;\n"
"public:\n"
" Fred() : f{0, true} { }\n"
" float get() const;\n"
"};\n"
"float Fred::get() const { return g; }");
ASSERT_EQUALS("[test.cpp:9]: (warning) Member variable 'Fred::g' is not initialized in the constructor.\n", errout_str());
}
void uninitVarStruct1() { // ticket #2172
check("class A\n"
"{\n"
"private:\n"
" struct B {\n"
" std::string str1;\n"
" std::string str2;\n"
" }\n"
" struct B b;\n"
"public:\n"
" A() {\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class A\n"
"{\n"
"private:\n"
" struct B {\n"
" char *str1;\n"
" char *str2;\n"
" }\n"
" struct B b;\n"
"public:\n"
" A() {\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:10]: (warning) Member variable 'A::b' is not initialized in the constructor.\n", errout_str());
check("class A\n"
"{\n"
"private:\n"
" struct B {\n"
" char *str1;\n"
" char *str2;\n"
" B() : str1(NULL), str2(NULL) { }\n"
" }\n"
" struct B b;\n"
"public:\n"
" A() {\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void uninitVarStruct2() { // ticket #838
check("struct POINT\n"
"{\n"
" int x;\n"
" int y;\n"
"};\n"
"class Fred\n"
"{\n"
"private:\n"
" POINT p;\n"
"public:\n"
" Fred()\n"
" { }\n"
"};");
ASSERT_EQUALS("[test.cpp:11]: (warning) Member variable 'Fred::p' is not initialized in the constructor.\n", errout_str());
check("struct POINT\n"
"{\n"
" int x;\n"
" int y;\n"
" POINT();\n"
"};\n"
"class Fred\n"
"{\n"
"private:\n"
" POINT p;\n"
"public:\n"
" Fred()\n"
" { }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct POINT\n"
"{\n"
" int x;\n"
" int y;\n"
" POINT() :x(0), y(0) { }\n"
"};\n"
"class Fred\n"
"{\n"
"private:\n"
" POINT p;\n"
"public:\n"
" Fred()\n"
" { }\n"
"};");
ASSERT_EQUALS("", errout_str());
// non static data-member initialization
check("struct POINT\n"
"{\n"
" int x=0;\n"
" int y=0;\n"
"};\n"
"class Fred\n"
"{\n"
"private:\n"
" POINT p;\n"
"public:\n"
" Fred()\n"
" { }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void uninitVarUnion1() {
check("class Fred\n" // ticket #3196
"{\n"
"private:\n"
" union { int a; int b; };\n"
"public:\n"
" Fred()\n"
" { a = 0; }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class Fred {\n"
"private:\n"
" union { int a{}; int b; };\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void uninitVarUnion2() {
// If the "data_type" is 0 it means union member "data" is invalid.
// So it's ok to not initialize "data".
// related forum: http://sourceforge.net/apps/phpbb/cppcheck/viewtopic.php?f=3&p=1806
check("union Data { int id; int *ptr; };\n"
"\n"
"class Fred {\n"
"private:\n"
" int data_type;\n"
" Data data;\n"
"public:\n"
" Fred() : data_type(0)\n"
" { }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void uninitMissingFuncDef() {
// Unknown member function
check("class Fred\n"
"{\n"
"public:\n"
" Fred() { Init(); }\n"
"private:\n"
" void Init();"
" int i;\n"
"};");
ASSERT_EQUALS("", errout_str());
// Unknown non-member function (friend class)
check("class Fred\n"
"{\n"
"public:\n"
" Fred() { Init(); }\n"
"private:\n"
" friend ABC;\n"
" int i;\n"
"};");
ASSERT_EQUALS("", errout_str());
// Unknown non-member function (is Init a virtual function?)
check("class Fred : private ABC\n"
"{\n"
"public:\n"
" Fred() { Init(); }\n"
"private:\n"
" int i;\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (warning) Member variable 'Fred::i' is not initialized in the constructor.\n", errout_str());
// Unknown non-member function
check("class Fred\n"
"{\n"
"public:\n"
" Fred() { Init(); }\n"
"private:\n"
" int i;\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (warning) Member variable 'Fred::i' is not initialized in the constructor.\n", errout_str());
// Unknown non-member function
check("class ABC { };\n"
"class Fred : private ABC\n"
"{\n"
"public:\n"
" Fred() { Init(); }\n"
"private:\n"
" int i;\n"
"};");
ASSERT_EQUALS("[test.cpp:5]: (warning) Member variable 'Fred::i' is not initialized in the constructor.\n", errout_str());
// Unknown member functions and unknown static functions
check("class ABC {\n"
" static void static_base_func();\n"
" void const_base_func() const;\n"
"};\n"
"class Fred : private ABC {\n"
"public:\n"
" Fred() {\n"
" const_func();\n"
" static_func();\n"
" const_base_func();\n"
" ABC::static_base_func();\n"
" }\n"
" void const_func() const;\n"
" static void static_f();\n"
"private:\n"
" int i;\n"
"};");
ASSERT_EQUALS("[test.cpp:7]: (warning) Member variable 'Fred::i' is not initialized in the constructor.\n", errout_str());
// Unknown overloaded member functions
check("class Fred : private ABC {\n"
"public:\n"
" Fred() {\n"
" func();\n"
" }\n"
" void func() const;\n"
" void func();\n"
"private:\n"
" int i;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void uninitVarEnum1() {
check("class Fred\n"
"{\n"
"public:\n"
" enum abc {a,b,c};\n"
" Fred() {}\n"
"private:\n"
" unsigned int i;\n"
"};");
ASSERT_EQUALS("[test.cpp:5]: (warning) Member variable 'Fred::i' is not initialized in the constructor.\n", errout_str());
}
void uninitVarEnum2() { // ticket #8146
check("enum E { E1 };\n"
"struct X { E e = E1; };\n"
"struct Y {\n"
" Y() {}\n"
" X x;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void uninitVarStream() {
check("class Foo\n"
"{\n"
"private:\n"
" int foo;\n"
"public:\n"
" explicit Foo(std::istream &in)\n"
" {\n"
" if(!(in >> foo))\n"
" throw 0;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void uninitVarTypedef() {
check("class Foo\n"
"{\n"
"public:\n"
" typedef int * pointer;\n"
" Foo() : a(0) {}\n"
" pointer a;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void uninitVarMemset() {
check("class Foo\n"
"{\n"
"public:\n"
" int * pointer;\n"
" Foo() { memset(this, 0, sizeof(*this)); }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class Foo\n"
"{\n"
"public:\n"
" int * pointer;\n"
" Foo() { ::memset(this, 0, sizeof(*this)); }\n"
"};");
ASSERT_EQUALS("", errout_str());
// Ticket #7068
check("struct Foo {\n"
" int * p;\n"
" char c;\n"
" Foo() { memset(p, 0, sizeof(int)); }\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (warning) Member variable 'Foo::c' is not initialized in the constructor.\n", errout_str());
check("struct Foo {\n"
" int i;\n"
" char c;\n"
" Foo() { memset(&i, 0, sizeof(int)); }\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (warning) Member variable 'Foo::c' is not initialized in the constructor.\n", errout_str());
check("struct Foo { int f; };\n"
"struct Bar { int b; };\n"
"struct FooBar {\n"
" FooBar() {\n"
" memset(&foo, 0, sizeof(foo));\n"
" }\n"
" Foo foo;\n"
" Bar bar;\n"
"};\n"
"int main() {\n"
" FooBar foobar;\n"
" return foobar.foo.f + foobar.bar.b;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (warning) Member variable 'FooBar::bar' is not initialized in the constructor.\n", errout_str());
check("struct Foo { int f; };\n"
"struct Bar { int b; };\n"
"struct FooBar {\n"
" FooBar() {\n"
" memset(&this->foo, 0, sizeof(this->foo));\n"
" }\n"
" Foo foo;\n"
" Bar bar;\n"
"};\n"
"int main() {\n"
" FooBar foobar;\n"
" return foobar.foo.f + foobar.bar.b;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (warning) Member variable 'FooBar::bar' is not initialized in the constructor.\n", errout_str());
// #7755
check("struct A {\n"
" A() {\n"
" memset(this->data, 0, 42);\n"
" }\n"
" char data[42];\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void privateCtor1() {
{
const Settings s = settingsBuilder(settings).cpp(Standards::CPP03).build();
check("class Foo {\n"
" int foo;\n"
" Foo() { }\n"
"};", s);
ASSERT_EQUALS("", errout_str());
}
{
const Settings s = settingsBuilder(settings).cpp(Standards::CPP11).build();
check("class Foo {\n"
" int foo;\n"
" Foo() { }\n"
"};", s);
ASSERT_EQUALS("[test.cpp:3]: (warning) Member variable 'Foo::foo' is not initialized in the constructor.\n", errout_str());
}
}
void privateCtor2() {
check("class Foo\n"
"{\n"
"private:\n"
" int foo;\n"
" Foo() { }\n"
"public:\n"
" explicit Foo(int _i) { }\n"
"};");
ASSERT_EQUALS("[test.cpp:7]: (warning) Member variable 'Foo::foo' is not initialized in the constructor.\n", errout_str());
}
void function() {
check("class A\n"
"{\n"
"public:\n"
" A();\n"
" int* f(int*);\n"
"};\n"
"\n"
"A::A()\n"
"{\n"
"}\n"
"\n"
"int* A::f(int* p)\n"
"{\n"
" return p;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
// Borland C++: No FP for published pointers - they are automatically initialized
void uninitVarPublished() {
check("class Fred\n"
"{\n"
"__published:\n"
" int *i;\n"
"public:\n"
" Fred() { }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void uninitVarInheritClassInit() {
// TODO: test should probably not pass without library
const Settings s = settingsBuilder() /*.library("vcl.cfg")*/.build();
check("class Fred: public TObject\n"
"{\n"
"public:\n"
" Fred() { }\n"
"private:\n"
" int x;\n"
"};", s);
ASSERT_EQUALS("", errout_str());
}
void uninitOperator() {
check("class Fred\n"
"{\n"
"public:\n"
" Fred() { }\n"
" int *operator [] (int index) { return 0; }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void uninitFunction1() {
check("class Fred\n"
"{\n"
"public:\n"
" Fred() { init(*this); }\n"
"\n"
" static void init(Fred &f)\n"
" { f.d = 0; }\n"
"\n"
" double d;\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class Fred\n"
"{\n"
"public:\n"
" Fred() { init(*this); }\n"
"\n"
" static void init(Fred &f)\n"
" { }\n"
"\n"
" double d;\n"
"};");
TODO_ASSERT_EQUALS("[test.cpp:4]: (warning) Member variable 'Fred::d' is not initialized in the constructor.\n", "", errout_str());
}
void uninitFunction2() {
check("class Fred\n"
"{\n"
"public:\n"
" Fred() { if (!init(*this)); }\n"
"\n"
" static bool init(Fred &f)\n"
" { f.d = 0; return true; }\n"
"\n"
" double d;\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class Fred\n"
"{\n"
"public:\n"
" Fred() { if (!init(*this)); }\n"
"\n"
" static bool init(Fred &f)\n"
" { return true; }\n"
"\n"
" double d;\n"
"};");
TODO_ASSERT_EQUALS("[test.cpp:4]: (warning) Member variable 'Fred::d' is not initialized in the constructor.\n", "", errout_str());
}
void uninitFunction3() {
check("class Fred\n"
"{\n"
"public:\n"
" Fred() { if (!init()); }\n"
"\n"
" bool init()\n"
" { d = 0; return true; }\n"
"\n"
" double d;\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class Fred\n"
"{\n"
"public:\n"
" Fred() { if (!init()); }\n"
"\n"
" bool init()\n"
" { return true; }\n"
"\n"
" double d;\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (warning) Member variable 'Fred::d' is not initialized in the constructor.\n", errout_str());
}
void uninitFunction4() {
check("class Fred\n"
"{\n"
"public:\n"
" Fred() { init(this); }\n"
"\n"
" init(Fred *f)\n"
" { f.d = 0; }\n"
"\n"
" double d;\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class Fred\n"
"{\n"
"public:\n"
" Fred() { init(this); }\n"
"\n"
" init(Fred *f)\n"
" { }\n"
"\n"
" double d;\n"
"};");
TODO_ASSERT_EQUALS("[test.cpp:4]: (warning) Member variable 'Fred::d' is not initialized in the constructor.\n", "", errout_str());
}
void uninitFunction5() { // #4072 - FP about struct that is initialized in function
check("struct Structure {\n"
" int C;\n"
"};\n"
"\n"
"class A {\n"
" Structure B;\n"
"public:\n"
" A() { Init( B ); };\n"
" void Init( Structure& S ) { S.C = 0; };\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct Structure {\n"
" int C;\n"
"};\n"
"\n"
"class A {\n"
" Structure B;\n"
"public:\n"
" A() { Init( B ); };\n"
" void Init(const Structure& S) { }\n"
"};");
ASSERT_EQUALS("[test.cpp:8]: (warning) Member variable 'A::B' is not initialized in the constructor.\n", errout_str());
}
void uninitSameClassName() {
check("class B\n"
"{\n"
"public:\n"
" B();\n"
" int j;\n"
"};\n"
"\n"
"class A\n"
"{\n"
" class B\n"
" {\n"
" public:\n"
" B();\n"
" int i;\n"
" };\n"
"};\n"
"\n"
"A::B::B()\n"
"{\n"
" i = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("class B\n"
"{\n"
"public:\n"
" B();\n"
" int j;\n"
"};\n"
"\n"
"class A\n"
"{\n"
" class B\n"
" {\n"
" public:\n"
" B();\n"
" int i;\n"
" };\n"
"};\n"
"\n"
"B::B()\n"
"{\n"
"}\n"
"\n"
"A::B::B()\n"
"{\n"
"}");
ASSERT_EQUALS("[test.cpp:18]: (warning) Member variable 'B::j' is not initialized in the constructor.\n"
"[test.cpp:22]: (warning) Member variable 'B::i' is not initialized in the constructor.\n", errout_str());
// Ticket #1700
check("namespace n1\n"
"{\n"
"class Foo {"
"public:\n"
" Foo() : i(0) { }\n"
"private:\n"
" int i;\n"
"};\n"
"}\n"
"\n"
"namespace n2\n"
"{\n"
"class Foo {"
"public:\n"
" Foo() { }\n"
"};\n"
"}");
ASSERT_EQUALS("", errout_str());
check("namespace n1\n"
"{\n"
"class Foo {\n"
"public:\n"
" Foo();\n"
"private:\n"
" int i;\n"
"};\n"
"}\n"
"\n"
"n1::Foo::Foo()\n"
"{ }\n"
"\n"
"namespace n2\n"
"{\n"
"class Foo {\n"
"public:\n"
" Foo() { }\n"
"};\n"
"}");
ASSERT_EQUALS("[test.cpp:11]: (warning) Member variable 'Foo::i' is not initialized in the constructor.\n", errout_str());
check("namespace n1\n"
"{\n"
"class Foo {"
"public:\n"
" Foo();\n"
"private:\n"
" int i;\n"
"};\n"
"}\n"
"\n"
"n1::Foo::Foo() : i(0)\n"
"{ }\n"
"\n"
"namespace n2\n"
"{\n"
"class Foo {"
"public:\n"
" Foo() { }\n"
"};\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void uninitFunctionOverload() {
// Ticket #1783 - overloaded "init" functions
check("class A\n"
"{\n"
"private:\n"
" int i;\n"
"\n"
"public:\n"
" A()\n"
" {\n"
" init();\n"
" }\n"
"\n"
" void init() { init(0); }\n"
"\n"
" void init(int value)\n"
" { i = value; }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("class A\n"
"{\n"
"private:\n"
" int i;\n"
"\n"
"public:\n"
" A()\n"
" {\n"
" init();\n"
" }\n"
"\n"
" void init() { init(0); }\n"
"\n"
" void init(int value)\n"
" { }\n"
"};");
ASSERT_EQUALS("[test.cpp:7]: (warning) Member variable 'A::i' is not initialized in the constructor.\n", errout_str());
check("class bar {\n" // #9887
" int length;\n"
" bar() { length = 0; }\n"
"};\n"
"class foo {\n"
" int x;\n"
" foo() { Set(bar()); }\n"
" void Set(int num) { x = 1; }\n"
" void Set(bar num) { x = num.length; }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
}
void uninitVarOperatorEqual() { // ticket #2415
check("struct A {\n"
" int a;\n"
" A() { a=0; }\n"
" A(A const &a) { operator=(a); }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct A {\n"
" int a;\n"
" A() { a=0; }\n"
" A(A const &a) { operator=(a); }\n"
" A & operator = (const A & rhs) {\n"
" a = rhs.a;\n"
" return *this;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct A {\n"
" int a;\n"
" A() { a=0; }\n"
" A(A const &a) { operator=(a); }\n"
" A & operator = (const A & rhs) {\n"
" return *this;\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (warning) Member variable 'A::a' is not initialized in the copy constructor.\n"
"[test.cpp:5]: (warning) Member variable 'A::a' is not assigned a value in 'A::operator='.\n", errout_str());
}
void uninitVarPointer() { // #3801
check("struct A {\n"
" int a;\n"
"};\n"
"struct B {\n"
" A* a;\n"
" B() { }\n"
"};");
ASSERT_EQUALS("[test.cpp:6]: (warning) Member variable 'B::a' is not initialized in the constructor.\n", errout_str());
check("struct A;\n"
"struct B {\n"
" A* a;\n"
" B() { }\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (warning) Member variable 'B::a' is not initialized in the constructor.\n", errout_str());
check("struct A;\n"
"struct B {\n"
" const A* a;\n"
" B() { }\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (warning) Member variable 'B::a' is not initialized in the constructor.\n", errout_str());
check("struct A;\n"
"struct B {\n"
" A* const a;\n"
" B() { }\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (warning) Member variable 'B::a' is not initialized in the constructor.\n", errout_str());
check("class Test {\n" // #8498
"public:\n"
" Test() {}\n"
" std::map<int, int>* pMap = nullptr;\n"
" std::string* pStr = nullptr;\n"
"};\n");
ASSERT_EQUALS("", errout_str());
check("template <typename U>\n"
"class C1 {}; \n"
"template <typename U, typename V>\n"
"class C2 {};\n"
"namespace A {\n"
" template <typename U>\n"
" class D1 {};\n"
" template <typename U, typename V>\n"
" class D2 {};\n"
"}\n"
"class Test {\n"
"public:\n"
" Test() {}\n"
" C1<int>* c1 = nullptr;\n"
" C2<int, int >* c2 = nullptr;\n"
" A::D1<int>* d1 = nullptr;\n"
" A::D2<int, int >* d2 = nullptr;\n"
" std::map<int, int>* pMap = nullptr;\n"
"};\n");
ASSERT_EQUALS("", errout_str());
}
void uninitConstVar() {
check("struct A;\n"
"struct B {\n"
" A* const a;\n"
" B() { }\n"
" B(B& b) { }\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (warning) Member variable 'B::a' is not initialized in the constructor.\n"
"[test.cpp:5]: (warning) Member variable 'B::a' is not initialized in the copy constructor.\n", errout_str());
check("struct A;\n"
"struct B {\n"
" A* const a;\n"
" B& operator=(const B& r) { }\n"
"};");
ASSERT_EQUALS("", errout_str()); // #3804
check("struct B {\n"
" const int a;\n"
" B() { }\n"
" B(B& b) { }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (warning) Member variable 'B::a' is not initialized in the constructor.\n"
"[test.cpp:4]: (warning) Member variable 'B::a' is not initialized in the copy constructor.\n", errout_str());
check("struct B {\n"
" const int a;\n"
" B& operator=(const B& r) { }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
// Ticket #5641 "Regression. Crash for 'C() _STLP_NOTHROW {}'"
void constructors_crash1() {
check("class C {\n"
"public:\n"
" C() _STLP_NOTHROW {}\n"
" C(const C&) _STLP_NOTHROW {}\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void classWithOperatorInName() { // ticket #2827
check("class operatorX {\n"
" int mValue;\n"
"public:\n"
" operatorX() : mValue(0) {}\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void templateConstructor() { // ticket #7942
check("template <class T> struct Container {\n"
" Container();\n"
" T* mElements;\n"
"};\n"
"template <class T> Container<T>::Container() : mElements(nullptr) {}\n"
"Container<int> intContainer;");
ASSERT_EQUALS("", errout_str());
}
void typedefArray() { // ticket #5766
check("typedef float rvec[3];\n"
"class SelectionPosition {\n"
"public:\n"
" SelectionPosition() {}\n"
" const rvec &x() const;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void uninitAssignmentWithOperator() {
check("struct C {\n"
" int x;\n"
" C() {\n"
" bool b = false;\n"
" b = b && SetValue();\n"
" }\n"
" bool SetValue() {\n"
" x = 1;\n"
" return true;\n"
" }\n"
"};", true);
TODO_ASSERT_EQUALS("[test.cpp:3]: (warning, inconclusive) Member variable 'C::x' is not initialized in the constructor.\n",
"[test.cpp:3]: (warning) Member variable 'C::x' is not initialized in the constructor.\n", errout_str());
check("struct C {\n"
" int x;\n"
" C() {\n"
" bool b = false;\n"
" b = true || SetValue();\n"
" }\n"
" bool SetValue() {\n"
" x = 1;\n"
" return true;\n"
" }\n"
"};", true);
TODO_ASSERT_EQUALS("[test.cpp:3]: (warning, inconclusive) Member variable 'C::x' is not initialized in the constructor.\n",
"[test.cpp:3]: (warning) Member variable 'C::x' is not initialized in the constructor.\n", errout_str());
check("struct C {\n"
" int x;\n"
" C() {\n"
" bool b = true;\n"
" b = b & SetValue();\n"
" }\n"
" bool SetValue() {\n"
" x = 1;\n"
" return true;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct C {\n"
" int x;\n"
" C() {\n"
" bool b = false;\n"
" b = true | SetValue();\n"
" }\n"
" bool SetValue() {\n"
" x = 1;\n"
" return true;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct C {\n"
" int x;\n"
" C() {\n"
" int i = 0;\n"
" i = i * SetValue();\n"
" }\n"
" int SetValue() { return x = 1; }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct C {\n"
" int x;\n"
" C() {\n"
" int i = 0;\n"
" i = i / SetValue();\n"
" }\n"
" int SetValue() { return x = 1; }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct C {\n"
" int x;\n"
" C() {\n"
" int i = 0;\n"
" i = i % SetValue();\n"
" }\n"
" int SetValue() { return x = 1; }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct C {\n"
" int x;\n"
" C() {\n"
" int i = 0;\n"
" i = i + SetValue();\n"
" }\n"
" int SetValue() { return x = 1; }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct C {\n"
" int x;\n"
" C() {\n"
" int i = 0;\n"
" i = i - SetValue();\n"
" }\n"
" int SetValue() { return x = 1; }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct C {\n"
" int x;\n"
" C() {\n"
" int i = 0;\n"
" i = i << SetValue();\n"
" }\n"
" int SetValue() { return x = 1; }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct C {\n"
" int x;\n"
" C() {\n"
" int i = 0;\n"
" i = i >> SetValue();\n"
" }\n"
" int SetValue() { return x = 1; }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct C {\n"
" int x;\n"
" C() {\n"
" int i = 0;\n"
" i = i ^ SetValue();\n"
" }\n"
" int SetValue() { return x = 1; }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void uninitCompoundAssignment() {
check("struct C {\n"
" int x;\n"
" C() {\n"
" bool b = true;\n"
" b &= SetValue();\n"
" }\n"
" bool SetValue() {\n"
" x = 1;\n"
" return true;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct C {\n"
" int x;\n"
" C() {\n"
" bool b = false;\n"
" b |= SetValue();\n"
" }\n"
" bool SetValue() {\n"
" x = 1;\n"
" return true;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct C {\n"
" int x;\n"
" C() {\n"
" int i = 0;\n"
" i *= SetValue();\n"
" }\n"
" int SetValue() { return x = 1; }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct C {\n"
" int x;\n"
" C() {\n"
" int i = 0;\n"
" i /= SetValue();\n"
" }\n"
" int SetValue() { return x = 1; }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct C {\n"
" int x;\n"
" C() {\n"
" int i = 0;\n"
" i %= SetValue();\n"
" }\n"
" int SetValue() { return x = 1; }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct C {\n"
" int x;\n"
" C() {\n"
" int i = 0;\n"
" i += SetValue();\n"
" }\n"
" int SetValue() { return x = 1; }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct C {\n"
" int x;\n"
" C() {\n"
" int i = 0;\n"
" i -= SetValue();\n"
" }\n"
" int SetValue() { return x = 1; }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct C {\n"
" int x;\n"
" C() {\n"
" int i = 0;\n"
" i <<= SetValue();\n"
" }\n"
" int SetValue() { return x = 1; }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct C {\n"
" int x;\n"
" C() {\n"
" int i = 0;\n"
" i >>= SetValue();\n"
" }\n"
" int SetValue() { return x = 1; }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct C {\n"
" int x;\n"
" C() {\n"
" int i = 0;\n"
" i ^= SetValue();\n"
" }\n"
" int SetValue() { return x = 1; }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void uninitComparisonAssignment() {
check("struct C {\n"
" int x;\n"
" C() {\n"
" bool b = true;\n"
" b = (true == SetValue());\n"
" }\n"
" bool SetValue() {\n"
" x = 1;\n"
" return true;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct C {\n"
" int x;\n"
" C() {\n"
" bool b = false;\n"
" b |= (true != SetValue());\n"
" }\n"
" bool SetValue() {\n"
" x = 1;\n"
" return true;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct C {\n"
" int x;\n"
" C() {\n"
" bool b = (0 < SetValue());\n"
" }\n"
" int SetValue() { return x = 1; }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct C {\n"
" int x;\n"
" C() {\n"
" bool b = (0 <= SetValue());\n"
" }\n"
" int SetValue() { return x = 1; }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct C {\n"
" int x;\n"
" C() {\n"
" bool b = (0 > SetValue());\n"
" }\n"
" int SetValue() { return x = 1; }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct C {\n"
" int x;\n"
" C() {\n"
" bool b = (0 >= SetValue());\n"
" }\n"
" int SetValue() { return x = 1; }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void uninitTemplate1() {
check("template <class A, class T> class C;\n"
"template <class A>\n"
"class C<A, void> {\n"
" public:\n"
" C() : b(0) { }\n"
" C(A* a) : b(a) { }\n"
" private:\n"
" A* b;\n"
"};\n"
"template <class A, class T>\n"
"class C {\n"
" private:\n"
" A* b;\n"
"};");
ASSERT_EQUALS("", errout_str());
check("template<class T> class A{};\n"
"template<class T1, class T2> class B{};\n"
"template<class T1, class T2>\n"
"class A<B<T1, T2>> {\n"
" public:\n"
" A();\n"
" bool m_value;\n"
"};\n"
"template<class T1, class T2>\n"
"A<B<T1, T2>>::A() : m_value(false) {}");
ASSERT_EQUALS("", errout_str());
check("template <typename T> struct S;\n" // #11177
"template <> struct S<void> final {\n"
" explicit S(int& i);\n"
" int& m;\n"
"};\n"
"S<void>::S(int& i) : m(i) {}\n");
ASSERT_EQUALS("", errout_str());
}
void unknownTemplateType() {
check("template <typename T> class A {\n"
"private:\n"
" T m;\n"
"public:\n"
" A& operator=() { return *this; }\n"
"};\n"
"A<decltype(SOMETHING)> a;");
ASSERT_EQUALS("", errout_str());
}
};
REGISTER_TEST(TestConstructors)
| null |
983 | cpp | cppcheck | testclass.cpp | test/testclass.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "check.h"
#include "checkclass.h"
#include "errortypes.h"
#include "fixture.h"
#include "helpers.h"
#include "settings.h"
#include "tokenize.h"
#include "tokenlist.h"
#include <cstddef>
#include <list>
#include <sstream>
#include <string>
#include <vector>
class TestClass : public TestFixture {
public:
TestClass() : TestFixture("TestClass") {}
private:
const Settings settings0 = settingsBuilder().severity(Severity::style).library("std.cfg").build();
const Settings settings1 = settingsBuilder().severity(Severity::warning).library("std.cfg").build();
const Settings settings2 = settingsBuilder().severity(Severity::style).library("std.cfg").certainty(Certainty::inconclusive).build();
const Settings settings3 = settingsBuilder().severity(Severity::style).library("std.cfg").severity(Severity::warning).build();
void run() override {
TEST_CASE(virtualDestructor1); // Base class not found => no error
TEST_CASE(virtualDestructor2); // Base class doesn't have a destructor
TEST_CASE(virtualDestructor3); // Base class has a destructor, but it's not virtual
TEST_CASE(virtualDestructor4); // Derived class doesn't have a destructor => no error
TEST_CASE(virtualDestructor5); // Derived class has empty destructor => no error
TEST_CASE(virtualDestructor6); // only report error if base class pointer that points at derived class is deleted
TEST_CASE(virtualDestructorProtected);
TEST_CASE(virtualDestructorInherited);
TEST_CASE(virtualDestructorTemplate);
TEST_CASE(virtualDestructorInconclusive); // ticket # 5807
TEST_CASE(copyConstructor1);
TEST_CASE(copyConstructor2); // ticket #4458
TEST_CASE(copyConstructor3); // defaulted/deleted
TEST_CASE(copyConstructor4); // base class with private constructor
TEST_CASE(copyConstructor5); // multiple inheritance
TEST_CASE(copyConstructor6); // array of pointers
TEST_CASE(noOperatorEq); // class with memory management should have operator eq
TEST_CASE(noDestructor); // class with memory management should have destructor
TEST_CASE(operatorEqRetRefThis1);
TEST_CASE(operatorEqRetRefThis2); // ticket #1323
TEST_CASE(operatorEqRetRefThis3); // ticket #1405
TEST_CASE(operatorEqRetRefThis4); // ticket #1451
TEST_CASE(operatorEqRetRefThis5); // ticket #1550
TEST_CASE(operatorEqRetRefThis6); // ticket #2479
TEST_CASE(operatorEqRetRefThis7); // ticket #5782 endless recursion
TEST_CASE(operatorEqToSelf1); // single class
TEST_CASE(operatorEqToSelf2); // nested class
TEST_CASE(operatorEqToSelf3); // multiple inheritance
TEST_CASE(operatorEqToSelf4); // nested class with multiple inheritance
TEST_CASE(operatorEqToSelf5); // ticket # 1233
TEST_CASE(operatorEqToSelf6); // ticket # 1550
TEST_CASE(operatorEqToSelf7);
TEST_CASE(operatorEqToSelf8); // ticket #2179
TEST_CASE(operatorEqToSelf9); // ticket #2592
TEST_CASE(memsetOnStruct);
TEST_CASE(memsetVector);
TEST_CASE(memsetOnClass);
TEST_CASE(memsetOnInvalid); // Ticket #5425: Crash upon invalid
TEST_CASE(memsetOnStdPodType); // Ticket #5901 - std::uint8_t
TEST_CASE(memsetOnFloat); // Ticket #5421
TEST_CASE(memsetOnUnknown); // Ticket #7183
TEST_CASE(mallocOnClass);
TEST_CASE(this_subtraction); // warn about "this-x"
// can member function be made const
TEST_CASE(const1);
TEST_CASE(const2);
TEST_CASE(const3);
TEST_CASE(const4);
TEST_CASE(const5); // ticket #1482
TEST_CASE(const6); // ticket #1491
TEST_CASE(const7);
TEST_CASE(const8); // ticket #1517
TEST_CASE(const9); // ticket #1515
TEST_CASE(const10); // ticket #1522
TEST_CASE(const11); // ticket #1529
TEST_CASE(const12); // ticket #1552
TEST_CASE(const13); // ticket #1519
TEST_CASE(const14);
TEST_CASE(const15);
TEST_CASE(const16); // ticket #1551
TEST_CASE(const17); // ticket #1552
TEST_CASE(const18);
TEST_CASE(const19); // ticket #1612
TEST_CASE(const20); // ticket #1602
TEST_CASE(const21); // ticket #1683
TEST_CASE(const22);
TEST_CASE(const23); // ticket #1699
TEST_CASE(const24); // ticket #1708
TEST_CASE(const25); // ticket #1724
TEST_CASE(const26); // ticket #1847
TEST_CASE(const27); // ticket #1882
TEST_CASE(const28); // ticket #1883
TEST_CASE(const29); // ticket #1922
TEST_CASE(const30);
TEST_CASE(const31);
TEST_CASE(const32); // ticket #1905 - member array is assigned
TEST_CASE(const33);
TEST_CASE(const34); // ticket #1964
TEST_CASE(const35); // ticket #2001
TEST_CASE(const36); // ticket #2003
TEST_CASE(const37); // ticket #2081 and #2085
TEST_CASE(const38); // ticket #2135
TEST_CASE(const39);
TEST_CASE(const40); // ticket #2228
TEST_CASE(const41); // ticket #2255
TEST_CASE(const42); // ticket #2282
TEST_CASE(const43); // ticket #2377
TEST_CASE(const44); // ticket #2595
TEST_CASE(const45); // ticket #2664
TEST_CASE(const46); // ticket #2636
TEST_CASE(const47); // ticket #2670
TEST_CASE(const48); // ticket #2672
TEST_CASE(const49); // ticket #2795
TEST_CASE(const50); // ticket #2943
TEST_CASE(const51); // ticket #3040
TEST_CASE(const52); // ticket #3048
TEST_CASE(const53); // ticket #3049
TEST_CASE(const54); // ticket #3052
TEST_CASE(const55);
TEST_CASE(const56); // ticket #3149
TEST_CASE(const57); // tickets #2669 and #2477
TEST_CASE(const58); // ticket #2698
TEST_CASE(const59); // ticket #4646
TEST_CASE(const60); // ticket #3322
TEST_CASE(const61); // ticket #5606
TEST_CASE(const62); // ticket #5701
TEST_CASE(const63); // ticket #5983
TEST_CASE(const64); // ticket #6268
TEST_CASE(const65); // ticket #8693
TEST_CASE(const66); // ticket #7714
TEST_CASE(const67); // ticket #9193
TEST_CASE(const68); // ticket #6471
TEST_CASE(const69); // ticket #9806
TEST_CASE(const70); // variadic template can receive more arguments than in its definition
TEST_CASE(const71); // ticket #10146
TEST_CASE(const72); // ticket #10520
TEST_CASE(const73); // ticket #10735
TEST_CASE(const74); // ticket #10671
TEST_CASE(const75); // ticket #10065
TEST_CASE(const76); // ticket #10825
TEST_CASE(const77); // ticket #10307, #10311
TEST_CASE(const78); // ticket #10315
TEST_CASE(const79); // ticket #9861
TEST_CASE(const80); // ticket #11328
TEST_CASE(const81); // ticket #11330
TEST_CASE(const82); // ticket #11513
TEST_CASE(const83);
TEST_CASE(const84);
TEST_CASE(const85);
TEST_CASE(const86);
TEST_CASE(const87);
TEST_CASE(const88);
TEST_CASE(const89);
TEST_CASE(const90);
TEST_CASE(const91);
TEST_CASE(const92);
TEST_CASE(const93);
TEST_CASE(const94);
TEST_CASE(const95); // #13320 - do not warn about r-value ref method
TEST_CASE(const96);
TEST_CASE(const97);
TEST_CASE(const_handleDefaultParameters);
TEST_CASE(const_passThisToMemberOfOtherClass);
TEST_CASE(assigningPointerToPointerIsNotAConstOperation);
TEST_CASE(assigningArrayElementIsNotAConstOperation);
TEST_CASE(constoperator1); // operator< can often be const
TEST_CASE(constoperator2); // operator<<
TEST_CASE(constoperator3);
TEST_CASE(constoperator4);
TEST_CASE(constoperator5); // ticket #3252
TEST_CASE(constoperator6); // ticket #8669
TEST_CASE(constincdec); // increment/decrement => non-const
TEST_CASE(constassign1);
TEST_CASE(constassign2);
TEST_CASE(constincdecarray); // increment/decrement array element => non-const
TEST_CASE(constassignarray);
TEST_CASE(constReturnReference);
TEST_CASE(constDelete); // delete member variable => not const
TEST_CASE(constLPVOID); // a function that returns LPVOID can't be const
TEST_CASE(constFunc); // a function that calls const functions can be const
TEST_CASE(constVirtualFunc);
TEST_CASE(constIfCfg); // ticket #1881 - fp when there are #if
TEST_CASE(constFriend); // ticket #1921 - fp for friend function
TEST_CASE(constUnion); // ticket #2111 - fp when there is a union
TEST_CASE(constArrayOperator); // #4406
TEST_CASE(constRangeBasedFor); // #5514
TEST_CASE(const_shared_ptr);
TEST_CASE(constPtrToConstPtr);
TEST_CASE(constTrailingReturnType);
TEST_CASE(constRefQualified);
TEST_CASE(staticArrayPtrOverload);
TEST_CASE(qualifiedNameMember); // #10872
TEST_CASE(initializerListOrder);
TEST_CASE(initializerListArgument);
TEST_CASE(initializerListUsage);
TEST_CASE(selfInitialization);
TEST_CASE(virtualFunctionCallInConstructor);
TEST_CASE(pureVirtualFunctionCall);
TEST_CASE(pureVirtualFunctionCallOtherClass);
TEST_CASE(pureVirtualFunctionCallWithBody);
TEST_CASE(pureVirtualFunctionCallPrevented);
TEST_CASE(duplInheritedMembers);
TEST_CASE(explicitConstructors);
TEST_CASE(copyCtorAndEqOperator);
TEST_CASE(override1);
TEST_CASE(overrideCVRefQualifiers);
TEST_CASE(uselessOverride);
TEST_CASE(thisUseAfterFree);
TEST_CASE(unsafeClassRefMember);
TEST_CASE(ctuOneDefinitionRule);
TEST_CASE(testGetFileInfo);
TEST_CASE(returnByReference);
}
#define checkCopyCtorAndEqOperator(code) checkCopyCtorAndEqOperator_(code, __FILE__, __LINE__)
template<size_t size>
void checkCopyCtorAndEqOperator_(const char (&code)[size], const char* file, int line) {
const Settings settings = settingsBuilder().severity(Severity::warning).build();
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
// Check..
CheckClass checkClass(&tokenizer, &settings, this);
(checkClass.checkCopyCtorAndEqOperator)();
}
void copyCtorAndEqOperator() {
checkCopyCtorAndEqOperator("class A\n"
"{\n"
" A(const A& other) { }\n"
" A& operator=(const A& other) { return *this; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkCopyCtorAndEqOperator("class A\n"
"{\n"
"};");
ASSERT_EQUALS("", errout_str());
checkCopyCtorAndEqOperator("class A\n"
"{\n"
" A(const A& other) { }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkCopyCtorAndEqOperator("class A\n"
"{\n"
" A& operator=(const A& other) { return *this; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkCopyCtorAndEqOperator("class A\n"
"{\n"
" A(const A& other) { }\n"
" int x;\n"
"};");
TODO_ASSERT_EQUALS("[test.cpp:1]: (warning) The class 'A' has 'copy constructor' but lack of 'operator='.\n", "", errout_str());
// TODO the error message should be clarified. It should say something like 'copy constructor is empty and will not assign i and therefore the behaviour is different to the default assignment operator'
checkCopyCtorAndEqOperator("class A\n"
"{\n"
" A& operator=(const A& other) { return *this; }\n"
" int x;\n"
"};");
TODO_ASSERT_EQUALS("[test.cpp:1]: (warning) The class 'A' has 'operator=' but lack of 'copy constructor'.\n", "", errout_str());
// TODO the error message should be clarified. It should say something like 'assignment operator does not assign i and therefore the behaviour is different to the default copy constructor'
checkCopyCtorAndEqOperator("class A\n"
"{\n"
" A& operator=(const int &x) { this->x = x; return *this; }\n"
" int x;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkCopyCtorAndEqOperator("class A {\n"
"public:\n"
" A() : x(0) { }\n"
" A(const A & a) { x = a.x; }\n"
" A & operator = (const A & a) {\n"
" x = a.x;\n"
" return *this;\n"
" }\n"
"private:\n"
" int x;\n"
"};\n"
"class B : public A {\n"
"public:\n"
" B() { }\n"
" B(const B & b) :A(b) { }\n"
"private:\n"
" static int i;\n"
"};");
ASSERT_EQUALS("", errout_str());
// #7987 - Don't show warning when there is a move constructor
checkCopyCtorAndEqOperator("struct S {\n"
" std::string test;\n"
" S(S&& s) : test(std::move(s.test)) { }\n"
" S& operator = (S &&s) {\n"
" test = std::move(s.test);\n"
" return *this;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
// #8337 - False positive in copy constructor detection
checkCopyCtorAndEqOperator("struct StaticListNode {\n"
" StaticListNode(StaticListNode*& prev) : m_next(0) {}\n"
" StaticListNode* m_next;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
#define checkExplicitConstructors(code) checkExplicitConstructors_(code, __FILE__, __LINE__)
template<size_t size>
void checkExplicitConstructors_(const char (&code)[size], const char* file, int line) {
// Tokenize..
SimpleTokenizer tokenizer(settings0, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
// Check..
CheckClass checkClass(&tokenizer, &settings0, this);
(checkClass.checkExplicitConstructors)();
}
void explicitConstructors() {
checkExplicitConstructors("class Class {\n"
" Class() = delete;\n"
" Class(const Class& other) { }\n"
" Class(Class&& other) { }\n"
" explicit Class(int i) { }\n"
" explicit Class(const std::string&) { }\n"
" Class(int a, int b) { }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkExplicitConstructors("class Class {\n"
" Class() = delete;\n"
" explicit Class(const Class& other) { }\n"
" explicit Class(Class&& other) { }\n"
" virtual int i() = 0;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkExplicitConstructors("class Class {\n"
" Class() = delete;\n"
" Class(const Class& other) = delete;\n"
" Class(Class&& other) = delete;\n"
" virtual int i() = 0;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkExplicitConstructors("class Class {\n"
" Class(int i) { }\n"
"};");
ASSERT_EQUALS("[test.cpp:2]: (style) Class 'Class' has a constructor with 1 argument that is not explicit.\n", errout_str());
checkExplicitConstructors("class Class {\n"
" Class(const Class& other) { }\n"
" virtual int i() = 0;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkExplicitConstructors("class Class {\n"
" Class(Class&& other) { }\n"
" virtual int i() = 0;\n"
"};");
ASSERT_EQUALS("", errout_str());
// #6585
checkExplicitConstructors("class Class {\n"
" private: Class(const Class&);\n"
" virtual int i() = 0;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkExplicitConstructors("class Class {\n"
" public: Class(const Class&);\n"
" virtual int i() = 0;\n"
"};");
ASSERT_EQUALS("", errout_str());
// #7465: Error properly reported in templates
checkExplicitConstructors("template <class T> struct Test {\n"
" Test(int) : fData(0) {}\n"
" T fData;\n"
"};\n"
"int main() {\n"
" Test <int> test;\n"
" return 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Struct 'Test < int >' has a constructor with 1 argument that is not explicit.\n", errout_str());
// #7465: No error for copy or move constructors
checkExplicitConstructors("template <class T> struct Test {\n"
" Test() : fData(0) {}\n"
" Test (const Test<T>& aOther) : fData(aOther.fData) {}\n"
" Test (Test<T>&& aOther) : fData(std::move(aOther.fData)) {}\n"
" T fData;\n"
"};\n"
"int main() {\n"
" Test <int> test;\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #8600
checkExplicitConstructors("struct A { struct B; };\n"
"struct A::B {\n"
" B() = default;\n"
" B(const B&) {}\n"
"};");
ASSERT_EQUALS("", errout_str());
checkExplicitConstructors("struct A{"
" A(int, int y=2) {}"
"};");
ASSERT_EQUALS("[test.cpp:1]: (style) Struct 'A' has a constructor with 1 argument that is not explicit.\n", errout_str());
checkExplicitConstructors("struct Foo {\n" // #10515
" template <typename T>\n"
" explicit constexpr Foo(T) {}\n"
"};\n"
"struct Bar {\n"
" template <typename T>\n"
" constexpr explicit Bar(T) {}\n"
"};\n"
"struct Baz {\n"
" explicit constexpr Baz(int) {}\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkExplicitConstructors("class Token;\n" // #11126
"struct Branch {\n"
" Branch(Token* tok = nullptr) : endBlock(tok) {}\n"
" Token* endBlock = nullptr;\n"
"};\n");
ASSERT_EQUALS("[test.cpp:3]: (style) Struct 'Branch' has a constructor with 1 argument that is not explicit.\n", errout_str());
checkExplicitConstructors("struct S {\n"
" S(std::initializer_list<int> il) : v(il) {}\n"
" std::vector<int> v;\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkExplicitConstructors("template<class T>\n" // #10977
"struct A {\n"
" template<class... Ts>\n"
" A(Ts&&... ts) {}\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkExplicitConstructors("class Color {\n" // #7176
"public:\n"
" Color(unsigned int rgba);\n"
" Color(std::uint8_t r = 0, std::uint8_t g = 0, std::uint8_t b = 0, std::uint8_t a = 255);\n"
"};\n");
ASSERT_EQUALS("[test.cpp:3]: (style) Class 'Color' has a constructor with 1 argument that is not explicit.\n"
"[test.cpp:4]: (style) Class 'Color' has a constructor with 1 argument that is not explicit.\n",
errout_str());
}
#define checkDuplInheritedMembers(code) checkDuplInheritedMembers_(code, __FILE__, __LINE__)
template<size_t size>
void checkDuplInheritedMembers_(const char (&code)[size], const char* file, int line) {
// Tokenize..
SimpleTokenizer tokenizer(settings1, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
// Check..
CheckClass checkClass(&tokenizer, &settings1, this);
(checkClass.checkDuplInheritedMembers)();
}
void duplInheritedMembers() {
checkDuplInheritedMembers("class Base {\n"
" int x;\n"
"};\n"
"struct Derived : Base {\n"
" int x;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkDuplInheritedMembers("class Base {\n"
" protected:\n"
" int x;\n"
"};\n"
"struct Derived : Base {\n"
" int x;\n"
"};");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:6]: (warning) The struct 'Derived' defines member variable with name 'x' also defined in its parent class 'Base'.\n", errout_str());
checkDuplInheritedMembers("class Base {\n"
" protected:\n"
" int x;\n"
"};\n"
"struct Derived : public Base {\n"
" int x;\n"
"};");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:6]: (warning) The struct 'Derived' defines member variable with name 'x' also defined in its parent class 'Base'.\n", errout_str());
checkDuplInheritedMembers("class Base0 {\n"
" int x;\n"
"};\n"
"class Base1 {\n"
" int x;\n"
"};\n"
"struct Derived : Base0, Base1 {\n"
" int x;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkDuplInheritedMembers("class Base0 {\n"
" protected:\n"
" int x;\n"
"};\n"
"class Base1 {\n"
" int x;\n"
"};\n"
"struct Derived : Base0, Base1 {\n"
" int x;\n"
"};");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:9]: (warning) The struct 'Derived' defines member variable with name 'x' also defined in its parent class 'Base0'.\n", errout_str());
checkDuplInheritedMembers("class Base0 {\n"
" protected:\n"
" int x;\n"
"};\n"
"class Base1 {\n"
" public:\n"
" int x;\n"
"};\n"
"struct Derived : Base0, Base1 {\n"
" int x;\n"
"};");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:10]: (warning) The struct 'Derived' defines member variable with name 'x' also defined in its parent class 'Base0'.\n"
"[test.cpp:7] -> [test.cpp:10]: (warning) The struct 'Derived' defines member variable with name 'x' also defined in its parent class 'Base1'.\n", errout_str());
checkDuplInheritedMembers("class Base {\n"
" int x;\n"
"};\n"
"struct Derived : Base {\n"
" int y;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkDuplInheritedMembers("class A {\n"
" int x;\n"
"};\n"
"struct B {\n"
" int x;\n"
"};");
ASSERT_EQUALS("", errout_str());
// Unknown 'Base' class
checkDuplInheritedMembers("class Derived : public UnknownBase {\n"
" int x;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkDuplInheritedMembers("class Base {\n"
" int x;\n"
"};\n"
"class Derived : public Base {\n"
"};");
ASSERT_EQUALS("", errout_str());
// #6692
checkDuplInheritedMembers("namespace test1 {\n"
" struct SWibble{};\n"
" typedef SWibble wibble;\n"
"}\n"
"namespace test2 {\n"
" struct SWibble : public test1::wibble {\n"
" int Value;\n"
" };\n"
"}");
ASSERT_EQUALS("", errout_str());
// #9957
checkDuplInheritedMembers("class Base {\n"
" public:\n"
" int i;\n"
"};\n"
"class Derived1: public Base {\n"
" public:\n"
" int j;\n"
"};\n"
"class Derived2 : public Derived1 {\n"
" int i;\n"
"};");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:10]: (warning) The class 'Derived2' defines member variable with name 'i' also defined in its parent class 'Base'.\n", errout_str());
// don't crash on recursive template
checkDuplInheritedMembers("template<size_t N>\n"
"struct BitInt : public BitInt<N+1> { };");
ASSERT_EQUALS("", errout_str());
// don't crash on recursive template
checkDuplInheritedMembers("namespace _impl {\n"
" template <typename AlwaysVoid, typename>\n"
" struct fn_traits;\n"
"}\n"
"template <typename T>\n"
"struct function_traits\n"
" : public _impl::fn_traits<void, std::remove_reference_t<T>> {};\n"
"namespace _impl {\n"
" template <typename T>\n"
" struct fn_traits<decltype(void(&T::operator())), T>\n"
" : public fn_traits<void, decltype(&T::operator())> {};\n"
"}");
ASSERT_EQUALS("", errout_str());
// #10594
checkDuplInheritedMembers("template<int i> struct A { bool a = true; };\n"
"struct B { bool a; };\n"
"template<> struct A<1> : B {};\n");
ASSERT_EQUALS("", errout_str());
checkDuplInheritedMembers("struct B {\n"
" int g() const;\n"
" virtual int f() const { return g(); }\n"
"};\n"
"struct D : B {\n"
" int g() const;\n"
" int f() const override { return g(); }\n"
"};\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:6]: (warning) The struct 'D' defines member function with name 'g' also defined in its parent struct 'B'.\n",
errout_str());
checkDuplInheritedMembers("struct B {\n"
" int g() const;\n"
"};\n"
"struct D : B {\n"
" int g(int) const;\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkDuplInheritedMembers("struct S {\n"
" struct T {\n"
" T() {}\n"
" };\n"
"};\n"
"struct T : S::T {\n"
" T() : S::T() {}\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkDuplInheritedMembers("struct S {};\n" // #11827
"struct SPtr {\n"
" virtual S* operator->() const { return p; }\n"
" S* p = nullptr;\n"
"};\n"
"struct T : public S {};\n"
"struct TPtr : public SPtr {\n"
" T* operator->() const { return (T*)p; }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkDuplInheritedMembers("struct B { virtual int& get() = 0; };\n" // #12311
"struct D : B {\n"
" int i{};\n"
" int& get() override { return i; }\n"
" const int& get() const { return i; }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkDuplInheritedMembers("class Base {\n" // #12353
" public:\n"
" void One();\n"
" void Two();\n"
"};\n"
"class Derived : public Base {\n"
"public:\n"
" void Two() = delete;\n"
"};\n");
ASSERT_EQUALS("", errout_str());
}
#define checkCopyConstructor(code) checkCopyConstructor_(code, __FILE__, __LINE__)
template<size_t size>
void checkCopyConstructor_(const char (&code)[size], const char* file, int line) {
// Tokenize..
SimpleTokenizer tokenizer(settings3, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
// Check..
CheckClass checkClass(&tokenizer, &settings3, this);
checkClass.copyconstructors();
}
void copyConstructor1() {
checkCopyConstructor("class F\n"
"{\n"
" public:\n"
" char *c,*p,*d;\n"
" F(const F &f) : p(f.p), c(f.c)\n"
" {\n"
" p=(char *)malloc(strlen(f.p)+1);\n"
" strcpy(p,f.p);\n"
" }\n"
" F(char *str)\n"
" {\n"
" p=(char *)malloc(strlen(str)+1);\n"
" strcpy(p,str);\n"
" }\n"
" F&operator=(const F&);\n"
" ~F();\n"
"};");
TODO_ASSERT_EQUALS("[test.cpp:5]: (warning) Value of pointer 'p', which points to allocated memory, is copied in copy constructor instead of allocating new memory.\n", "", errout_str());
checkCopyConstructor("class F {\n"
" char *p;\n"
" F(const F &f) {\n"
" p = f.p;\n"
" }\n"
" F(char *str) {\n"
" p = malloc(strlen(str)+1);\n"
" }\n"
" ~F();\n"
" F& operator=(const F&f);\n"
"};");
TODO_ASSERT_EQUALS("[test.cpp:4]: (warning) Value of pointer 'p', which points to allocated memory, is copied in copy constructor instead of allocating new memory.\n"
"[test.cpp:3] -> [test.cpp:7]: (warning) Copy constructor does not allocate memory for member 'p' although memory has been allocated in other constructors.\n",
"[test.cpp:4]: (warning) Value of pointer 'p', which points to allocated memory, is copied in copy constructor instead of allocating new memory.\n"
, errout_str());
checkCopyConstructor("class F\n"
"{\n"
" public:\n"
" char *c,*p,*d;\n"
" F(const F &f) :p(f.p)\n"
" {\n"
" }\n"
" F(char *str)\n"
" {\n"
" p=(char *)malloc(strlen(str)+1);\n"
" strcpy(p,str);\n"
" }\n"
" ~F();\n"
" F& operator=(const F&f);\n"
"};");
TODO_ASSERT_EQUALS("[test.cpp:5]: (warning) Value of pointer 'p', which points to allocated memory, is copied in copy constructor instead of allocating new memory.\n"
"[test.cpp:5] -> [test.cpp:10]: (warning) Copy constructor does not allocate memory for member 'p' although memory has been allocated in other constructors.\n",
""
, errout_str());
checkCopyConstructor("class kalci\n"
"{\n"
" public:\n"
" char *c,*p,*d;\n"
" kalci()\n"
" {\n"
" p=(char *)malloc(100);\n"
" strcpy(p,\"hello\");\n"
" c=(char *)malloc(100);\n"
" strcpy(p,\"hello\");\n"
" d=(char *)malloc(100);\n"
" strcpy(p,\"hello\");\n"
" }\n"
" kalci(const kalci &f)\n"
" {\n"
" p=(char *)malloc(strlen(str)+1);\n"
" strcpy(p,f.p);\n"
" c=(char *)malloc(strlen(str)+1);\n"
" strcpy(p,f.p);\n"
" d=(char *)malloc(strlen(str)+1);\n"
" strcpy(p,f.p);\n"
" }\n"
" ~kalci();\n"
" kalci& operator=(const kalci&kalci);\n"
"};");
ASSERT_EQUALS("", errout_str());
checkCopyConstructor("class F\n"
"{\n"
" public:\n"
" char *c,*p,*d;\n"
" F(char *str,char *st,char *string)\n"
" {\n"
" p=(char *)malloc(100);\n"
" strcpy(p,str);\n"
" c=(char *)malloc(100);\n"
" strcpy(p,st);\n"
" d=(char *)malloc(100);\n"
" strcpy(p,string);\n"
" }\n"
" F(const F &f)\n"
" {\n"
" p=(char *)malloc(strlen(str)+1);\n"
" strcpy(p,f.p);\n"
" c=(char *)malloc(strlen(str)+1);\n"
" strcpy(p,f.p);\n"
" }\n"
" ~F();\n"
" F& operator=(const F&f);\n"
"};");
TODO_ASSERT_EQUALS("[test.cpp:14] -> [test.cpp:11]: (warning) Copy constructor does not allocate memory for member 'd' although memory has been allocated in other constructors.\n", "", errout_str());
checkCopyConstructor("class F {\n"
" char *c;\n"
" F(char *str,char *st,char *string) {\n"
" p=(char *)malloc(100);\n"
" }\n"
" F(const F &f)\n"
" : p(malloc(size))\n"
" {\n"
" }\n"
" ~F();\n"
" F& operator=(const F&f);\n"
"};");
ASSERT_EQUALS("", errout_str());
checkCopyConstructor("class F {\n"
" char *c;\n"
" F(char *str,char *st,char *string)\n"
" : p(malloc(size))\n"
" {\n"
" }\n"
" F(const F &f)\n"
" {\n"
" }\n"
" ~F();\n"
" F& operator=(const F&f);\n"
"};");
TODO_ASSERT_EQUALS("[test.cpp:7] -> [test.cpp:4]: (warning) Copy constructor does not allocate memory for member 'd' although memory has been allocated in other constructors.\n", "", errout_str());
checkCopyConstructor("class F\n"
"{\n"
" public:\n"
" char *c,*p,*d;\n"
" F()\n"
" {\n"
" p=(char *)malloc(100);\n"
" c=(char *)malloc(100);\n"
" d=(char*)malloc(100);\n"
" }\n"
" ~F();\n"
" F& operator=(const F&f);\n"
"};");
TODO_ASSERT_EQUALS("[test.cpp:8]: (warning) Class 'F' does not have a copy constructor which is recommended since it has dynamic memory/resource allocation(s).\n", "", errout_str());
checkCopyConstructor("class F\n"
"{\n"
" public:\n"
" char *c;\n"
" const char *p,*d;\n"
" F(char *str,char *st,char *string)\n"
" {\n"
" p=str;\n"
" d=st;\n"
" c=(char *)malloc(strlen(string)+1);\n"
" strcpy(d,string);\n"
" }\n"
" F(const F &f)\n"
" {\n"
" p=f.p;\n"
" d=f.d;\n"
" c=(char *)malloc(strlen(str)+1);\n"
" strcpy(d,f.p);\n"
" }\n"
" ~F();\n"
" F& operator=(const F&f);\n"
"};");
ASSERT_EQUALS("", errout_str());
checkCopyConstructor("class F : E\n"
"{\n"
" char *p;\n"
" F() {\n"
" p = malloc(100);\n"
" }\n"
" ~F();\n"
" F& operator=(const F&f);\n"
"};");
ASSERT_EQUALS("", errout_str());
checkCopyConstructor("class E { E(E&); };\n" // non-copyable
"class F : E\n"
"{\n"
" char *p;\n"
" F() {\n"
" p = malloc(100);\n"
" }\n"
" ~F();\n"
" F& operator=(const F&f);\n"
"};");
ASSERT_EQUALS("", errout_str());
checkCopyConstructor("class E {};\n"
"class F : E {\n"
" char *p;\n"
" F() {\n"
" p = malloc(100);\n"
" }\n"
" ~F();\n"
" F& operator=(const F&f);\n"
"};");
ASSERT_EQUALS("[test.cpp:5]: (warning) Class 'F' does not have a copy constructor which is recommended since it has dynamic memory/resource allocation(s).\n", errout_str());
checkCopyConstructor("class F {\n"
" char *p;\n"
" F() {\n"
" p = malloc(100);\n"
" }\n"
" F(F& f);\n"
" ~F();\n"
" F& operator=(const F&f);\n"
"};");
ASSERT_EQUALS("", errout_str());
checkCopyConstructor("class F {\n"
" char *p;\n"
" F() : p(malloc(100)) {}\n"
" ~F();\n"
" F& operator=(const F&f);\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (warning) Class 'F' does not have a copy constructor which is recommended since it has dynamic memory/resource allocation(s).\n", errout_str());
// #7198
checkCopyConstructor("struct F {\n"
" static char* c;\n"
" F() {\n"
" p = malloc(100);\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void copyConstructor2() { // ticket #4458
checkCopyConstructor("template <class _Tp>\n"
"class Vector\n"
"{\n"
"public:\n"
" Vector() {\n"
" _M_finish = new _Tp[ 42 ];\n"
" }\n"
" Vector( const Vector<_Tp>& v ) {\n"
" }\n"
" ~Vector();\n"
" Vector& operator=(const Vector&v);\n"
" _Tp* _M_finish;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void copyConstructor3() {
checkCopyConstructor("struct F {\n"
" char* c;\n"
" F() { c = malloc(100); }\n"
" F(const F &f) = delete;\n"
" F&operator=(const F &f);\n"
" ~F();\n"
"};");
ASSERT_EQUALS("", errout_str());
checkCopyConstructor("struct F {\n"
" char* c;\n"
" F() { c = malloc(100); }\n"
" F(const F &f) = default;\n"
" F&operator=(const F &f);\n"
" ~F();\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (warning) Struct 'F' has dynamic memory/resource allocation(s). The copy constructor is explicitly defaulted but the default copy constructor does not work well. It is recommended to define or delete the copy constructor.\n", errout_str());
}
void copyConstructor4() {
checkCopyConstructor("class noncopyable {\n"
"protected:\n"
" noncopyable() {}\n"
" ~noncopyable() {}\n"
"\n"
"private:\n"
" noncopyable( const noncopyable& );\n"
" const noncopyable& operator=( const noncopyable& );\n"
"};\n"
"\n"
"class Base : private noncopyable {};\n"
"\n"
"class Foo : public Base {\n"
"public:\n"
" Foo() : m_ptr(new int) {}\n"
" ~Foo() { delete m_ptr; }\n"
"private:\n"
" int* m_ptr;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void copyConstructor5() {
checkCopyConstructor("class Copyable {};\n"
"\n"
"class Foo : public Copyable, public UnknownType {\n"
"public:\n"
" Foo() : m_ptr(new int) {}\n"
" ~Foo() { delete m_ptr; }\n"
"private:\n"
" int* m_ptr;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkCopyConstructor("class Copyable {};\n"
"\n"
"class Foo : public UnknownType, public Copyable {\n"
"public:\n"
" Foo() : m_ptr(new int) {}\n"
" ~Foo() { delete m_ptr; }\n"
"private:\n"
" int* m_ptr;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void copyConstructor6() {
checkCopyConstructor("struct S {\n"
" S() {\n"
" for (int i = 0; i < 5; i++)\n"
" a[i] = new char[3];\n"
" }\n"
" char* a[5];\n"
"};\n");
TODO_ASSERT_EQUALS("[test.cpp:4]: (warning) Struct 'S' does not have a copy constructor which is recommended since it has dynamic memory/resource allocation(s).\n"
"[test.cpp:4]: (warning) Struct 'S' does not have a operator= which is recommended since it has dynamic memory/resource allocation(s).\n"
"[test.cpp:4]: (warning) Struct 'S' does not have a destructor which is recommended since it has dynamic memory/resource allocation(s).\n",
"",
errout_str());
}
void noOperatorEq() {
checkCopyConstructor("struct F {\n"
" char* c;\n"
" F() { c = malloc(100); }\n"
" F(const F &f);\n"
" ~F();\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (warning) Struct 'F' does not have a operator= which is recommended since it has dynamic memory/resource allocation(s).\n", errout_str());
// defaulted operator=
checkCopyConstructor("struct F {\n"
" char* c;\n"
" F() { c = malloc(100); }\n"
" F(const F &f);\n"
" F &operator=(const F &f) = default;\n"
" ~F();\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (warning) Struct 'F' has dynamic memory/resource allocation(s). The operator= is explicitly defaulted but the default operator= does not work well. It is recommended to define or delete the operator=.\n", errout_str());
// deleted operator=
checkCopyConstructor("struct F {\n"
" char* c;\n"
" F() { c = malloc(100); }\n"
" F(const F &f);\n"
" F &operator=(const F &f) = delete;\n"
" ~F();\n"
"};");
ASSERT_EQUALS("", errout_str());
// base class deletes operator=
checkCopyConstructor("struct F : NonCopyable {\n"
" char* c;\n"
" F() { c = malloc(100); }\n"
" F(const F &f);\n"
" ~F();\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void noDestructor() {
checkCopyConstructor("struct F {\n"
" char* c;\n"
" F() { c = malloc(100); }\n"
" F(const F &f);\n"
" F&operator=(const F&);"
"};");
ASSERT_EQUALS("[test.cpp:3]: (warning) Struct 'F' does not have a destructor which is recommended since it has dynamic memory/resource allocation(s).\n", errout_str());
checkCopyConstructor("struct F {\n"
" C* c;\n"
" F() { c = new C; }\n"
" F(const F &f);\n"
" F&operator=(const F&);"
"};");
ASSERT_EQUALS("", errout_str());
checkCopyConstructor("struct F {\n"
" int* i;\n"
" F() { i = new int(); }\n"
" F(const F &f);\n"
" F& operator=(const F&);"
"};");
ASSERT_EQUALS("[test.cpp:3]: (warning) Struct 'F' does not have a destructor which is recommended since it has dynamic memory/resource allocation(s).\n", errout_str());
checkCopyConstructor("struct Data { int x; int y; };\n"
"struct F {\n"
" Data* c;\n"
" F() { c = new Data; }\n"
" F(const F &f);\n"
" F&operator=(const F&);"
"};");
ASSERT_EQUALS("[test.cpp:4]: (warning) Struct 'F' does not have a destructor which is recommended since it has dynamic memory/resource allocation(s).\n", errout_str());
// defaulted destructor
checkCopyConstructor("struct F {\n"
" char* c;\n"
" F() { c = malloc(100); }\n"
" F(const F &f);\n"
" F &operator=(const F &f);\n"
" ~F() = default;\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (warning) Struct 'F' has dynamic memory/resource allocation(s). The destructor is explicitly defaulted but the default destructor does not work well. It is recommended to define the destructor.\n", errout_str());
// deleted destructor
checkCopyConstructor("struct F {\n"
" char* c;\n"
" F() { c = malloc(100); }\n"
" F(const F &f);\n"
" F &operator=(const F &f);\n"
" ~F() = delete;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
// Check that operator Equal returns reference to this
#define checkOpertorEqRetRefThis(code) checkOpertorEqRetRefThis_(code, __FILE__, __LINE__)
template<size_t size>
void checkOpertorEqRetRefThis_(const char (&code)[size], const char* file, int line) {
// Tokenize..
SimpleTokenizer tokenizer(settings0, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
// Check..
CheckClass checkClass(&tokenizer, &settings0, this);
checkClass.operatorEqRetRefThis();
}
void operatorEqRetRefThis1() {
checkOpertorEqRetRefThis(
"class A\n"
"{\n"
"public:\n"
" A & operator=(const A &a) { return *this; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkOpertorEqRetRefThis(
"class A\n"
"{\n"
"public:\n"
" A & operator=(const A &a) { return a; }\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (style) 'operator=' should return reference to 'this' instance.\n", errout_str());
checkOpertorEqRetRefThis(
"class A\n"
"{\n"
"public:\n"
" A & operator=(const A &);\n"
"};\n"
"A & A::operator=(const A &a) { return *this; }");
ASSERT_EQUALS("", errout_str());
checkOpertorEqRetRefThis(
"class A\n"
"{\n"
"public:\n"
" A & operator=(const A &a);\n"
"};\n"
"A & A::operator=(const A &a) { return *this; }");
ASSERT_EQUALS("", errout_str());
checkOpertorEqRetRefThis(
"class A\n"
"{\n"
"public:\n"
" A & operator=(const A &);\n"
"};\n"
"A & A::operator=(const A &a) { return a; }");
ASSERT_EQUALS("[test.cpp:6]: (style) 'operator=' should return reference to 'this' instance.\n", errout_str());
checkOpertorEqRetRefThis(
"class A\n"
"{\n"
"public:\n"
" A & operator=(const A &a);\n"
"};\n"
"A & A::operator=(const A &a) { return a; }");
ASSERT_EQUALS("[test.cpp:6]: (style) 'operator=' should return reference to 'this' instance.\n", errout_str());
checkOpertorEqRetRefThis(
"class A\n"
"{\n"
"public:\n"
" class B\n"
" {\n"
" public:\n"
" B & operator=(const B &b) { return *this; }\n"
" };\n"
"};");
ASSERT_EQUALS("", errout_str());
checkOpertorEqRetRefThis(
"class A\n"
"{\n"
"public:\n"
" class B\n"
" {\n"
" public:\n"
" B & operator=(const B &b) { return b; }\n"
" };\n"
"};");
ASSERT_EQUALS("[test.cpp:7]: (style) 'operator=' should return reference to 'this' instance.\n", errout_str());
checkOpertorEqRetRefThis(
"class A\n"
"{\n"
"public:\n"
" class B\n"
" {\n"
" public:\n"
" B & operator=(const B &);\n"
" };\n"
"};\n"
"A::B & A::B::operator=(const A::B &b) { return *this; }");
ASSERT_EQUALS("", errout_str());
checkOpertorEqRetRefThis(
"class A\n"
"{\n"
"public:\n"
" class B\n"
" {\n"
" public:\n"
" B & operator=(const B &);\n"
" };\n"
"};\n"
"A::B & A::B::operator=(const A::B &b) { return b; }");
ASSERT_EQUALS("[test.cpp:10]: (style) 'operator=' should return reference to 'this' instance.\n", errout_str());
checkOpertorEqRetRefThis(
"class A {\n"
" class B;\n"
"};\n"
"class A::B\n"
"{\n"
" B & operator=(const B & b) { return b; }\n"
"};");
ASSERT_EQUALS("[test.cpp:6]: (style) 'operator=' should return reference to 'this' instance.\n", errout_str());
checkOpertorEqRetRefThis(
"class A {\n"
" class B;\n"
"};\n"
"class A::B\n"
"{\n"
" B & operator=(const B &);\n"
"};\n"
"A::B & A::B::operator=(const A::B & b) { return b; }");
ASSERT_EQUALS("[test.cpp:8]: (style) 'operator=' should return reference to 'this' instance.\n", errout_str());
checkOpertorEqRetRefThis(
"class A {\n"
" class B;\n"
"};\n"
"class A::B\n"
"{\n"
" A::B & operator=(const A::B & b) { return b; }\n"
"};");
ASSERT_EQUALS("[test.cpp:6]: (style) 'operator=' should return reference to 'this' instance.\n", errout_str());
checkOpertorEqRetRefThis(
"class A {\n"
" class B;\n"
"};\n"
"class A::B\n"
"{\n"
" A::B & operator=(const A::B &);\n"
"};\n"
"A::B & A::B::operator=(const A::B & b) { return b; }");
ASSERT_EQUALS("[test.cpp:8]: (style) 'operator=' should return reference to 'this' instance.\n", errout_str());
checkOpertorEqRetRefThis(
"namespace A {\n"
" class B;\n"
"}\n"
"class A::B\n"
"{\n"
" B & operator=(const B & b) { return b; }\n"
"};");
ASSERT_EQUALS("[test.cpp:6]: (style) 'operator=' should return reference to 'this' instance.\n", errout_str());
checkOpertorEqRetRefThis(
"namespace A {\n"
" class B;\n"
"}\n"
"class A::B\n"
"{\n"
" B & operator=(const B &);\n"
"};\n"
"A::B & A::B::operator=(const A::B & b) { return b; }");
ASSERT_EQUALS("[test.cpp:8]: (style) 'operator=' should return reference to 'this' instance.\n", errout_str());
checkOpertorEqRetRefThis(
"namespace A {\n"
" class B;\n"
"}\n"
"class A::B\n"
"{\n"
" A::B & operator=(const A::B & b) { return b; }\n"
"};");
ASSERT_EQUALS("[test.cpp:6]: (style) 'operator=' should return reference to 'this' instance.\n", errout_str());
checkOpertorEqRetRefThis(
"namespace A {\n"
" class B;\n"
"}\n"
"class A::B\n"
"{\n"
" A::B & operator=(const A::B &);\n"
"};\n"
"A::B & A::B::operator=(const A::B & b) { return b; }");
ASSERT_EQUALS("[test.cpp:8]: (style) 'operator=' should return reference to 'this' instance.\n", errout_str());
checkOpertorEqRetRefThis( // #11380
"struct S {\n"
" S& operator=(const S& other) {\n"
" i = []() { return 42; }();\n"
" return *this;\n"
" }\n"
" int i;\n"
"};\n");
ASSERT_EQUALS("", errout_str());
}
void operatorEqRetRefThis2() {
// ticket # 1323
checkOpertorEqRetRefThis(
"class szp\n"
"{\n"
" szp &operator =(int *other) {}\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (error) No 'return' statement in non-void function causes undefined behavior.\n", errout_str());
checkOpertorEqRetRefThis(
"class szp\n"
"{\n"
" szp &operator =(int *other);\n"
"};\n"
"szp &szp::operator =(int *other) {}");
ASSERT_EQUALS("[test.cpp:5]: (error) No 'return' statement in non-void function causes undefined behavior.\n", errout_str());
checkOpertorEqRetRefThis(
"namespace NS {\n"
" class szp;\n"
"}\n"
"class NS::szp\n"
"{\n"
" szp &operator =(int *other) {}\n"
"};");
ASSERT_EQUALS("[test.cpp:6]: (error) No 'return' statement in non-void function causes undefined behavior.\n", errout_str());
checkOpertorEqRetRefThis(
"namespace NS {\n"
" class szp;\n"
"}\n"
"class NS::szp\n"
"{\n"
" szp &operator =(int *other);\n"
"};\n"
"NS::szp &NS::szp::operator =(int *other) {}");
ASSERT_EQUALS("[test.cpp:8]: (error) No 'return' statement in non-void function causes undefined behavior.\n", errout_str());
checkOpertorEqRetRefThis(
"namespace NS {\n"
" class szp;\n"
"}\n"
"class NS::szp\n"
"{\n"
" NS::szp &operator =(int *other) {}\n"
"};");
ASSERT_EQUALS("[test.cpp:6]: (error) No 'return' statement in non-void function causes undefined behavior.\n", errout_str());
checkOpertorEqRetRefThis(
"namespace NS {\n"
" class szp;\n"
"}\n"
"class NS::szp\n"
"{\n"
" NS::szp &operator =(int *other);\n"
"};\n"
"NS::szp &NS::szp::operator =(int *other) {}");
ASSERT_EQUALS("[test.cpp:8]: (error) No 'return' statement in non-void function causes undefined behavior.\n", errout_str());
checkOpertorEqRetRefThis(
"class A {\n"
" class szp;\n"
"};\n"
"class A::szp\n"
"{\n"
" szp &operator =(int *other) {}\n"
"};");
ASSERT_EQUALS("[test.cpp:6]: (error) No 'return' statement in non-void function causes undefined behavior.\n", errout_str());
checkOpertorEqRetRefThis(
"class A {\n"
" class szp;\n"
"};\n"
"class A::szp\n"
"{\n"
" szp &operator =(int *other);\n"
"};\n"
"A::szp &A::szp::operator =(int *other) {}");
ASSERT_EQUALS("[test.cpp:8]: (error) No 'return' statement in non-void function causes undefined behavior.\n", errout_str());
checkOpertorEqRetRefThis(
"class A {\n"
" class szp;\n"
"};\n"
"class A::szp\n"
"{\n"
" A::szp &operator =(int *other) {}\n"
"};");
ASSERT_EQUALS("[test.cpp:6]: (error) No 'return' statement in non-void function causes undefined behavior.\n", errout_str());
checkOpertorEqRetRefThis(
"class A {\n"
" class szp;\n"
"};\n"
"class A::szp\n"
"{\n"
" A::szp &operator =(int *other);\n"
"};\n"
"A::szp &A::szp::operator =(int *other) {}");
ASSERT_EQUALS("[test.cpp:8]: (error) No 'return' statement in non-void function causes undefined behavior.\n", errout_str());
}
void operatorEqRetRefThis3() {
// ticket # 1405
checkOpertorEqRetRefThis(
"class A {\n"
"public:\n"
" inline A &operator =(int *other) { return (*this); };\n"
" inline A &operator =(long *other) { return (*this = 0); };\n"
"};");
ASSERT_EQUALS("", errout_str());
checkOpertorEqRetRefThis(
"class A {\n"
"public:\n"
" A &operator =(int *other);\n"
" A &operator =(long *other);\n"
"};\n"
"A &A::operator =(int *other) { return (*this); };\n"
"A &A::operator =(long *other) { return (*this = 0); };");
ASSERT_EQUALS("", errout_str());
checkOpertorEqRetRefThis(
"class A {\n"
"public:\n"
" inline A &operator =(int *other) { return (*this); };\n"
" inline A &operator =(long *other) { return operator = (*(int *)other); };\n"
"};");
ASSERT_EQUALS("", errout_str());
checkOpertorEqRetRefThis(
"class A {\n"
"public:\n"
" A &operator =(int *other);\n"
" A &operator =(long *other);\n"
"};\n"
"A &A::operator =(int *other) { return (*this); };\n"
"A &A::operator =(long *other) { return operator = (*(int *)other); };");
ASSERT_EQUALS("", errout_str());
checkOpertorEqRetRefThis(
"class A {\n"
"public:\n"
" A &operator =(int *other);\n"
" A &operator =(long *other);\n"
"};\n"
"A &A::operator =(int *other) { return (*this); };\n"
"A &A::operator =(long *other) { return this->operator = (*(int *)other); };");
ASSERT_EQUALS("", errout_str());
checkOpertorEqRetRefThis( // #9045
"class V {\n"
"public:\n"
" V& operator=(const V& r) {\n"
" if (this == &r) {\n"
" return ( *this );\n"
" }\n"
" return *this;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void operatorEqRetRefThis4() {
// ticket # 1451
checkOpertorEqRetRefThis(
"P& P::operator = (const P& pc)\n"
"{\n"
" return (P&)(*this += pc);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void operatorEqRetRefThis5() {
// ticket # 1550
checkOpertorEqRetRefThis(
"class A {\n"
"public:\n"
" A & operator=(const A &a) { }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (error) No 'return' statement in non-void function causes undefined behavior.\n", errout_str());
checkOpertorEqRetRefThis(
"class A {\n"
"protected:\n"
" A & operator=(const A &a) {}\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (style) 'operator=' should return reference to 'this' instance.\n", errout_str());
checkOpertorEqRetRefThis(
"class A {\n"
"private:\n"
" A & operator=(const A &a) {}\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (style) 'operator=' should return reference to 'this' instance.\n", errout_str());
checkOpertorEqRetRefThis(
"class A {\n"
"public:\n"
" A & operator=(const A &a) {\n"
" rand();\n"
" throw std::exception();\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (style) 'operator=' should either return reference to 'this' instance or be declared private and left unimplemented.\n", errout_str());
checkOpertorEqRetRefThis(
"class A {\n"
"public:\n"
" A & operator=(const A &a) {\n"
" rand();\n"
" abort();\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (style) 'operator=' should either return reference to 'this' instance or be declared private and left unimplemented.\n", errout_str());
checkOpertorEqRetRefThis(
"class A {\n"
"public:\n"
" A & operator=(const A &a);\n"
"};\n"
"A & A :: operator=(const A &a) { }");
ASSERT_EQUALS("[test.cpp:5]: (error) No 'return' statement in non-void function causes undefined behavior.\n", errout_str());
}
void operatorEqRetRefThis6() { // ticket #2478 (segmentation fault)
checkOpertorEqRetRefThis(
"class UString {\n"
"public:\n"
" UString& assign( const char* c_str );\n"
" UString& operator=( const UString& s );\n"
"};\n"
"UString& UString::assign( const char* c_str ) {\n"
" std::string tmp( c_str );\n"
" return assign( tmp );\n"
"}\n"
"UString& UString::operator=( const UString& s ) {\n"
" return assign( s );\n"
"}");
}
void operatorEqRetRefThis7() { // ticket #5782 Endless recursion in CheckClass::checkReturnPtrThis()
checkOpertorEqRetRefThis(
"class basic_fbstring {\n"
" basic_fbstring& operator=(int il) {\n"
" return assign();\n"
" }\n"
" basic_fbstring& assign() {\n"
" return replace();\n"
" }\n"
" basic_fbstring& replaceImplDiscr() {\n"
" return replace();\n"
" }\n"
" basic_fbstring& replace() {\n"
" return replaceImplDiscr();\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
// Check that operator Equal checks for assignment to self
#define checkOpertorEqToSelf(code) checkOpertorEqToSelf_(code, __FILE__, __LINE__)
template<size_t size>
void checkOpertorEqToSelf_(const char (&code)[size], const char* file, int line) {
// Tokenize..
SimpleTokenizer tokenizer(settings1, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
// Check..
CheckClass checkClass(&tokenizer, &settings1, this);
checkClass.operatorEqToSelf();
}
void operatorEqToSelf1() {
// this test has an assignment test but it is not needed
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" A & operator=(const A &a) { if (&a != this) { } return *this; }\n"
"};");
ASSERT_EQUALS("", errout_str());
// this test doesn't have an assignment test but it is not needed
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" A & operator=(const A &a) { return *this; }\n"
"};");
ASSERT_EQUALS("", errout_str());
// this test needs an assignment test and has it
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" char *s;\n"
" A & operator=(const A &a)\n"
" {\n"
" if (&a != this)\n"
" {\n"
" free(s);\n"
" s = strdup(a.s);\n"
" }\n"
" return *this;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
// this class needs an assignment test but doesn't have it
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" char *s;\n"
" A & operator=(const A &a)\n"
" {\n"
" free(s);\n"
" s = strdup(a.s);\n"
" return *this;\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:5]: (warning) 'operator=' should check for assignment to self to avoid problems with dynamic memory.\n", errout_str());
// this test has an assignment test but doesn't need it
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" A & operator=(const A &);\n"
"};\n"
"A & A::operator=(const A &a) { if (&a != this) { } return *this; }");
ASSERT_EQUALS("", errout_str());
// this test doesn't have an assignment test but doesn't need it
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" A & operator=(const A &);\n"
"};\n"
"A & A::operator=(const A &a) { return *this; }");
ASSERT_EQUALS("", errout_str());
// this test needs an assignment test and has it
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" char *s;\n"
" A & operator=(const A &);\n"
"};\n"
"A & A::operator=(const A &a)\n"
"{\n"
" if (&a != this)\n"
" {\n"
" free(s);\n"
" s = strdup(a.s);\n"
" }\n"
" return *this;\n"
"}");
ASSERT_EQUALS("", errout_str());
// this test needs an assignment test and has the inverse test
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" char *s;\n"
" A & operator=(const A &);\n"
"};\n"
"A & A::operator=(const A &a)\n"
"{\n"
" if (&a == this)\n"
" {\n"
" free(s);\n"
" s = strdup(a.s);\n"
" }\n"
" return *this;\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (warning) 'operator=' should check for assignment to self to avoid problems with dynamic memory.\n", errout_str());
// this test needs an assignment test and has the inverse test
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" char *s;\n"
" A & operator=(const A &);\n"
"};\n"
"A & A::operator=(const A &a)\n"
"{\n"
" if ((&a == this) == true)\n"
" {\n"
" free(s);\n"
" s = strdup(a.s);\n"
" }\n"
" return *this;\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (warning) 'operator=' should check for assignment to self to avoid problems with dynamic memory.\n", errout_str());
// this test needs an assignment test and has the inverse test
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" char *s;\n"
" A & operator=(const A &);\n"
"};\n"
"A & A::operator=(const A &a)\n"
"{\n"
" if ((&a == this) != false)\n"
" {\n"
" free(s);\n"
" s = strdup(a.s);\n"
" }\n"
" return *this;\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (warning) 'operator=' should check for assignment to self to avoid problems with dynamic memory.\n", errout_str());
// this test needs an assignment test and has the inverse test
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" char *s;\n"
" A & operator=(const A &);\n"
"};\n"
"A & A::operator=(const A &a)\n"
"{\n"
" if (!((&a == this) == false))\n"
" {\n"
" free(s);\n"
" s = strdup(a.s);\n"
" }\n"
" return *this;\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (warning) 'operator=' should check for assignment to self to avoid problems with dynamic memory.\n", errout_str());
// this test needs an assignment test and has the inverse test
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" char *s;\n"
" A & operator=(const A &);\n"
"};\n"
"A & A::operator=(const A &a)\n"
"{\n"
" if ((&a != this) == false)\n"
" {\n"
" free(s);\n"
" s = strdup(a.s);\n"
" }\n"
" return *this;\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (warning) 'operator=' should check for assignment to self to avoid problems with dynamic memory.\n", errout_str());
// this test needs an assignment test and has the inverse test
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" char *s;\n"
" A & operator=(const A &);\n"
"};\n"
"A & A::operator=(const A &a)\n"
"{\n"
" if (&a != this)\n"
" {\n"
" }\n"
" else\n"
" {\n"
" free(s);\n"
" s = strdup(a.s);\n"
" }\n"
" return *this;\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (warning) 'operator=' should check for assignment to self to avoid problems with dynamic memory.\n", errout_str());
// this test needs an assignment test and has the inverse test
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" char *s;\n"
" A & operator=(const A &);\n"
"};\n"
"A & A::operator=(const A &a)\n"
"{\n"
" if (&a != this)\n"
" free(s);\n"
" else\n"
" {\n"
" free(s);\n"
" s = strdup(a.s);\n"
" }\n"
" return *this;\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (warning) 'operator=' should check for assignment to self to avoid problems with dynamic memory.\n", errout_str());
// this test needs an assignment test but doesn’t have it
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" char *s;\n"
" A & operator=(const A &);\n"
"};\n"
"A & A::operator=(const A &a)\n"
"{\n"
" free(s);\n"
" s = strdup(a.s);\n"
" return *this;\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (warning) 'operator=' should check for assignment to self to avoid problems with dynamic memory.\n", errout_str());
// ticket #1224
checkOpertorEqToSelf(
"const SubTree &SubTree::operator= (const SubTree &b)\n"
"{\n"
" CodeTree *oldtree = tree;\n"
" tree = new CodeTree(*b.tree);\n"
" delete oldtree;\n"
" return *this;\n"
"}\n"
"const SubTree &SubTree::operator= (const CodeTree &b)\n"
"{\n"
" CodeTree *oldtree = tree;\n"
" tree = new CodeTree(b);\n"
" delete oldtree;\n"
" return *this;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void operatorEqToSelf2() {
// this test has an assignment test but doesn't need it
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" class B\n"
" {\n"
" public:\n"
" B & operator=(const B &b) { if (&b != this) { } return *this; }\n"
" };\n"
"};");
ASSERT_EQUALS("", errout_str());
// this test doesn't have an assignment test but doesn't need it
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" class B\n"
" {\n"
" public:\n"
" B & operator=(const B &b) { return *this; }\n"
" };\n"
"};");
ASSERT_EQUALS("", errout_str());
// this test needs an assignment test but has it
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" class B\n"
" {\n"
" public:\n"
" char *s;\n"
" B & operator=(const B &b)\n"
" {\n"
" if (&b != this)\n"
" {\n"
" }\n"
" return *this;\n"
" }\n"
" };\n"
"};");
ASSERT_EQUALS("", errout_str());
// this test needs an assignment test but doesn't have it
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" class B\n"
" {\n"
" public:\n"
" char *s;\n"
" B & operator=(const B &b)\n"
" {\n"
" free(s);\n"
" s = strdup(b.s);\n"
" return *this;\n"
" }\n"
" };\n"
"};");
ASSERT_EQUALS("[test.cpp:8]: (warning) 'operator=' should check for assignment to self to avoid problems with dynamic memory.\n", errout_str());
// this test has an assignment test but doesn't need it
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" class B\n"
" {\n"
" public:\n"
" B & operator=(const B &);\n"
" };\n"
"};\n"
"A::B & A::B::operator=(const A::B &b) { if (&b != this) { } return *this; }");
ASSERT_EQUALS("", errout_str());
// this test doesn't have an assignment test but doesn't need it
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" class B\n"
" {\n"
" public:\n"
" B & operator=(const B &);\n"
" };\n"
"};\n"
"A::B & A::B::operator=(const A::B &b) { return *this; }");
ASSERT_EQUALS("", errout_str());
// this test needs an assignment test and has it
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" class B\n"
" {\n"
" public:\n"
" char * s;\n"
" B & operator=(const B &);\n"
" };\n"
"};\n"
"A::B & A::B::operator=(const A::B &b)\n"
"{\n"
" if (&b != this)\n"
" {\n"
" free(s);\n"
" s = strdup(b.s);\n"
" }\n"
" return *this;\n"
" }");
ASSERT_EQUALS("", errout_str());
// this test needs an assignment test but doesn't have it
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" class B\n"
" {\n"
" public:\n"
" char * s;\n"
" B & operator=(const B &);\n"
" };\n"
"};\n"
"A::B & A::B::operator=(const A::B &b)\n"
"{\n"
" free(s);\n"
" s = strdup(b.s);\n"
" return *this;\n"
" }");
ASSERT_EQUALS("[test.cpp:11]: (warning) 'operator=' should check for assignment to self to avoid problems with dynamic memory.\n", errout_str());
}
void operatorEqToSelf3() {
// this test has multiple inheritance so there is no trivial way to test for self assignment but doesn't need it
checkOpertorEqToSelf(
"class A : public B, public C\n"
"{\n"
"public:\n"
" A & operator=(const A &a) { return *this; }\n"
"};");
ASSERT_EQUALS("", errout_str());
// this test has multiple inheritance and needs an assignment test but there is no trivial way to test for it
checkOpertorEqToSelf(
"class A : public B, public C\n"
"{\n"
"public:\n"
" char *s;\n"
" A & operator=(const A &a)\n"
" {\n"
" free(s);\n"
" s = strdup(a.s);\n"
" return *this;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
// this test has multiple inheritance so there is no trivial way to test for self assignment but doesn't need it
checkOpertorEqToSelf(
"class A : public B, public C\n"
"{\n"
"public:\n"
" A & operator=(const A &);\n"
"};\n"
"A & A::operator=(const A &a) { return *this; }");
ASSERT_EQUALS("", errout_str());
// this test has multiple inheritance and needs an assignment test but there is no trivial way to test for it
checkOpertorEqToSelf(
"class A : public B, public C\n"
"{\n"
"public:\n"
" char *s;\n"
" A & operator=(const A &);\n"
"};\n"
"A & A::operator=(const A &a)\n"
"{\n"
" free(s);\n"
" s = strdup(a.s);\n"
" return *this;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void operatorEqToSelf4() {
// this test has multiple inheritance so there is no trivial way to test for self assignment but doesn't need it
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" class B : public C, public D\n"
" {\n"
" public:\n"
" B & operator=(const B &b) { return *this; }\n"
" };\n"
"};");
ASSERT_EQUALS("", errout_str());
// this test has multiple inheritance and needs an assignment test but there is no trivial way to test for it
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" class B : public C, public D\n"
" {\n"
" public:\n"
" char * s;\n"
" B & operator=(const B &b)\n"
" {\n"
" free(s);\n"
" s = strdup(b.s);\n"
" return *this;\n"
" }\n"
" };\n"
"};");
ASSERT_EQUALS("", errout_str());
// this test has multiple inheritance so there is no trivial way to test for self assignment but doesn't need it
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" class B : public C, public D\n"
" {\n"
" public:\n"
" B & operator=(const B &);\n"
" };\n"
"};\n"
"A::B & A::B::operator=(const A::B &b) { return *this; }");
ASSERT_EQUALS("", errout_str());
// this test has multiple inheritance and needs an assignment test but there is no trivial way to test for it
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" class B : public C, public D\n"
" {\n"
" public:\n"
" char * s;\n"
" B & operator=(const B &);\n"
" };\n"
"};\n"
"A::B & A::B::operator=(const A::B &b)\n"
"{\n"
" free(s);\n"
" s = strdup(b.s);\n"
" return *this;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void operatorEqToSelf5() {
// ticket # 1233
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" char *s;\n"
" A & operator=(const A &a)\n"
" {\n"
" if((&a!=this))\n"
" {\n"
" free(s);\n"
" s = strdup(a.s);\n"
" }\n"
" return *this;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" char *s;\n"
" A & operator=(const A &a)\n"
" {\n"
" if((this!=&a))\n"
" {\n"
" free(s);\n"
" s = strdup(a.s);\n"
" }\n"
" return *this;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" char *s;\n"
" A & operator=(const A &a)\n"
" {\n"
" if(!(&a==this))\n"
" {\n"
" free(s);\n"
" s = strdup(a.s);\n"
" }\n"
" return *this;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" char *s;\n"
" A & operator=(const A &a)\n"
" {\n"
" if(!(this==&a))\n"
" {\n"
" free(s);\n"
" s = strdup(a.s);\n"
" }\n"
" return *this;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" char *s;\n"
" A & operator=(const A &a)\n"
" {\n"
" if(false==(&a==this))\n"
" {\n"
" free(s);\n"
" s = strdup(a.s);\n"
" }\n"
" return *this;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" char *s;\n"
" A & operator=(const A &a)\n"
" {\n"
" if(false==(this==&a))\n"
" {\n"
" free(s);\n"
" s = strdup(a.s);\n"
" }\n"
" return *this;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" char *s;\n"
" A & operator=(const A &a)\n"
" {\n"
" if(true!=(&a==this))\n"
" {\n"
" free(s);\n"
" s = strdup(a.s);\n"
" }\n"
" return *this;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" char *s;\n"
" A & operator=(const A &a)\n"
" {\n"
" if(true!=(this==&a))\n"
" {\n"
" free(s);\n"
" s = strdup(a.s);\n"
" }\n"
" return *this;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" char *s;\n"
" A & operator=(const A &a);\n"
"};\n"
"A & A::operator=(const A &a)\n"
"{\n"
" if((&a!=this))\n"
" {\n"
" free(s);\n"
" s = strdup(a.s);\n"
" }\n"
" return *this;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" char *s;\n"
" A & operator=(const A &a);\n"
"};\n"
"A & A::operator=(const A &a)\n"
"{\n"
" if((this!=&a))\n"
" {\n"
" free(s);\n"
" s = strdup(a.s);\n"
" }\n"
" return *this;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" char *s;\n"
" A & operator=(const A &a);\n"
"};\n"
"A & A::operator=(const A &a)\n"
"{\n"
" if(!(&a==this))\n"
" {\n"
" free(s);\n"
" s = strdup(a.s);\n"
" }\n"
" return *this;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" char *s;\n"
" A & operator=(const A &a);\n"
"};\n"
"A & A::operator=(const A &a)\n"
"{\n"
" if(!(this==&a))\n"
" {\n"
" free(s);\n"
" s = strdup(a.s);\n"
" }\n"
" return *this;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" char *s;\n"
" A & operator=(const A &a);\n"
"};\n"
"A & A::operator=(const A &a)\n"
"{\n"
" if(false==(&a==this))\n"
" {\n"
" free(s);\n"
" s = strdup(a.s);\n"
" }\n"
" return *this;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" char *s;\n"
" A & operator=(const A &a);\n"
"};\n"
"A & A::operator=(const A &a)\n"
"{\n"
" if(false==(this==&a))\n"
" {\n"
" free(s);\n"
" s = strdup(a.s);\n"
" }\n"
" return *this;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" char *s;\n"
" A & operator=(const A &a);\n"
"};\n"
"A & A::operator=(const A &a)\n"
"{\n"
" if(true!=(&a==this))\n"
" {\n"
" free(s);\n"
" s = strdup(a.s);\n"
" }\n"
" return *this;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" char *s;\n"
" A & operator=(const A &a);\n"
"};\n"
"A & A::operator=(const A &a)\n"
"{\n"
" if(true!=(this==&a))\n"
" {\n"
" free(s);\n"
" s = strdup(a.s);\n"
" }\n"
" return *this;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkOpertorEqToSelf(
"struct A {\n"
" char *s;\n"
" A& operator=(const B &b);\n"
"};\n"
"A& A::operator=(const B &b) {\n"
" free(s);\n"
" s = strdup(a.s);\n"
" return *this;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void operatorEqToSelf6() {
// ticket # 1550
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" A & operator=(const A &a)\n"
" {\n"
" delete [] data;\n"
" data = new char[strlen(a.data) + 1];\n"
" strcpy(data, a.data);\n"
" return *this;\n"
" }\n"
"private:\n"
" char * data;\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (warning) 'operator=' should check for assignment to self to avoid problems with dynamic memory.\n", errout_str());
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" A & operator=(const A &a);\n"
"private:\n"
" char * data;\n"
"};\n"
"A & A::operator=(const A &a)\n"
"{\n"
" delete [] data;\n"
" data = new char[strlen(a.data) + 1];\n"
" strcpy(data, a.data);\n"
" return *this;\n"
"};");
ASSERT_EQUALS("[test.cpp:8]: (warning) 'operator=' should check for assignment to self to avoid problems with dynamic memory.\n", errout_str());
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" A & operator=(const A &a)\n"
" {\n"
" delete data;\n"
" data = new char;\n"
" *data = *a.data;\n"
" return *this;\n"
" }\n"
"private:\n"
" char * data;\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (warning) 'operator=' should check for assignment to self to avoid problems with dynamic memory.\n", errout_str());
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" A & operator=(const A &a);\n"
"private:\n"
" char * data;\n"
"};\n"
"A & A::operator=(const A &a)\n"
"{\n"
" delete data;\n"
" data = new char;\n"
" *data = *a.data;\n"
" return *this;\n"
"};");
ASSERT_EQUALS("[test.cpp:8]: (warning) 'operator=' should check for assignment to self to avoid problems with dynamic memory.\n", errout_str());
}
void operatorEqToSelf7() {
checkOpertorEqToSelf(
"class A\n"
"{\n"
"public:\n"
" A & assign(const A & a)\n"
" {\n"
" return *this;\n"
" }\n"
" A & operator=(const A &a)\n"
" {\n"
" return assign(a);\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void operatorEqToSelf8() {
checkOpertorEqToSelf(
"class FMat\n"
"{\n"
"public:\n"
" FMat& copy(const FMat& rhs);\n"
" FMat& operator=(const FMat& in);\n"
"};\n"
"FMat& FMat::copy(const FMat& rhs)\n"
"{\n"
" return *this;\n"
"}\n"
"FMat& FMat::operator=(const FMat& in)\n"
"{\n"
" return copy(in);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void operatorEqToSelf9() {
checkOpertorEqToSelf(
"class Foo\n"
"{\n"
"public:\n"
" Foo& operator=(Foo* pOther);\n"
" Foo& operator=(Foo& other);\n"
"};\n"
"Foo& Foo::operator=(Foo* pOther)\n"
"{\n"
" return *this;\n"
"}\n"
"Foo& Foo::operator=(Foo& other)\n"
"{\n"
" return Foo::operator=(&other);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
// Check that base classes have virtual destructors
#define checkVirtualDestructor(...) checkVirtualDestructor_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
void checkVirtualDestructor_(const char* file, int line, const char (&code)[size], bool inconclusive = false) {
const Settings s = settingsBuilder(settings0).certainty(Certainty::inconclusive, inconclusive).severity(Severity::warning).build();
// Tokenize..
SimpleTokenizer tokenizer(s, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
// Check..
CheckClass checkClass(&tokenizer, &s, this);
checkClass.virtualDestructor();
}
void virtualDestructor1() {
// Base class not found
checkVirtualDestructor("class Derived : public Base { };\n"
"Base *base = new Derived;\n"
"delete base;");
ASSERT_EQUALS("", errout_str());
checkVirtualDestructor("class Derived : Base { };\n"
"Base *base = new Derived;\n"
"delete base;");
ASSERT_EQUALS("", errout_str());
}
void virtualDestructor2() {
// Base class doesn't have a destructor
checkVirtualDestructor("class Base { };\n"
"class Derived : public Base { public: ~Derived() { (void)11; } };"
"Base *base = new Derived;\n"
"delete base;");
ASSERT_EQUALS("[test.cpp:1]: (error) Class 'Base' which is inherited by class 'Derived' does not have a virtual destructor.\n", errout_str());
checkVirtualDestructor("class Base { };\n"
"class Derived : protected Base { public: ~Derived() { (void)11; } };"
"Base *base = new Derived;\n"
"delete base;");
ASSERT_EQUALS("[test.cpp:1]: (error) Class 'Base' which is inherited by class 'Derived' does not have a virtual destructor.\n", errout_str());
checkVirtualDestructor("class Base { };\n"
"class Derived : private Base { public: ~Derived() { (void)11; } };"
"Base *base = new Derived;\n"
"delete base;");
ASSERT_EQUALS("", errout_str());
checkVirtualDestructor("class Base { };\n"
"class Derived : Base { public: ~Derived() { (void)11; } };"
"Base *base = new Derived;\n"
"delete base;");
ASSERT_EQUALS("", errout_str());
// #9104
checkVirtualDestructor("struct A\n"
"{\n"
" A() { cout << \"A is constructing\\n\"; }\n"
" ~A() { cout << \"A is destructing\\n\"; }\n"
"};\n"
" \n"
"struct Base {};\n"
" \n"
"struct Derived : Base\n"
"{\n"
" A a;\n"
"};\n"
" \n"
"int main(void)\n"
"{\n"
" Base* p = new Derived();\n"
" delete p;\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (error) Class 'Base' which is inherited by class 'Derived' does not have a virtual destructor.\n", errout_str());
checkVirtualDestructor("using namespace std;\n"
"struct A\n"
"{\n"
" A() { cout << \"A is constructing\\n\"; }\n"
" ~A() { cout << \"A is destructing\\n\"; }\n"
"};\n"
" \n"
"struct Base {};\n"
" \n"
"struct Derived : Base\n"
"{\n"
" A a;\n"
"};\n"
" \n"
"int main(void)\n"
"{\n"
" Base* p = new Derived();\n"
" delete p;\n"
"}");
ASSERT_EQUALS("[test.cpp:8]: (error) Class 'Base' which is inherited by class 'Derived' does not have a virtual destructor.\n", errout_str());
}
void virtualDestructor3() {
// Base class has a destructor, but it's not virtual
checkVirtualDestructor("class Base { public: ~Base(); };\n"
"class Derived : public Base { public: ~Derived() { (void)11; } };"
"Base *base = new Derived;\n"
"delete base;");
ASSERT_EQUALS("[test.cpp:1]: (error) Class 'Base' which is inherited by class 'Derived' does not have a virtual destructor.\n", errout_str());
checkVirtualDestructor("class Base { public: ~Base(); };\n"
"class Derived : protected Base { public: ~Derived() { (void)11; } };"
"Base *base = new Derived;\n"
"delete base;");
ASSERT_EQUALS("[test.cpp:1]: (error) Class 'Base' which is inherited by class 'Derived' does not have a virtual destructor.\n", errout_str());
checkVirtualDestructor("class Base { public: ~Base(); };\n"
"class Derived : private Fred, public Base { public: ~Derived() { (void)11; } };"
"Base *base = new Derived;\n"
"delete base;");
ASSERT_EQUALS("[test.cpp:1]: (error) Class 'Base' which is inherited by class 'Derived' does not have a virtual destructor.\n", errout_str());
}
void virtualDestructor4() {
// Derived class doesn't have a destructor => undefined behaviour according to paragraph 3 in [expr.delete]
checkVirtualDestructor("class Base { public: ~Base(); };\n"
"class Derived : public Base { };"
"Base *base = new Derived;\n"
"delete base;");
ASSERT_EQUALS("[test.cpp:1]: (error) Class 'Base' which is inherited by class 'Derived' does not have a virtual destructor.\n", errout_str());
checkVirtualDestructor("class Base { public: ~Base(); };\n"
"class Derived : private Fred, public Base { };"
"Base *base = new Derived;\n"
"delete base;");
ASSERT_EQUALS("[test.cpp:1]: (error) Class 'Base' which is inherited by class 'Derived' does not have a virtual destructor.\n", errout_str());
}
void virtualDestructor5() {
// Derived class has empty destructor => undefined behaviour according to paragraph 3 in [expr.delete]
checkVirtualDestructor("class Base { public: ~Base(); };\n"
"class Derived : public Base { public: ~Derived() {} };"
"Base *base = new Derived;\n"
"delete base;");
ASSERT_EQUALS("[test.cpp:1]: (error) Class 'Base' which is inherited by class 'Derived' does not have a virtual destructor.\n", errout_str());
checkVirtualDestructor("class Base { public: ~Base(); };\n"
"class Derived : public Base { public: ~Derived(); }; Derived::~Derived() {}"
"Base *base = new Derived;\n"
"delete base;");
ASSERT_EQUALS("[test.cpp:1]: (error) Class 'Base' which is inherited by class 'Derived' does not have a virtual destructor.\n", errout_str());
}
void virtualDestructor6() {
// Only report error if base class pointer is deleted that
// points at derived class
checkVirtualDestructor("class Base { public: ~Base(); };\n"
"class Derived : public Base { public: ~Derived() { (void)11; } };");
ASSERT_EQUALS("", errout_str());
}
void virtualDestructorProtected() {
// Base class has protected destructor, it makes Base *p = new Derived(); fail
// during compilation time, so error is not possible. => no error
checkVirtualDestructor("class A\n"
"{\n"
"protected:\n"
" ~A() { }\n"
"};\n"
"\n"
"class B : public A\n"
"{\n"
"public:\n"
" ~B() { int a; }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void virtualDestructorInherited() {
// class A inherits virtual destructor from class Base -> no error
checkVirtualDestructor("class Base\n"
"{\n"
"public:\n"
"virtual ~Base() {}\n"
"};\n"
"class A : private Base\n"
"{\n"
"public:\n"
" ~A() { }\n"
"};\n"
"\n"
"class B : public A\n"
"{\n"
"public:\n"
" ~B() { int a; }\n"
"};");
ASSERT_EQUALS("", errout_str());
// class A inherits virtual destructor from struct Base -> no error
// also notice that public is not given, but destructor is public, because
// we are using struct instead of class
checkVirtualDestructor("struct Base\n"
"{\n"
"virtual ~Base() {}\n"
"};\n"
"class A : public Base\n"
"{\n"
"};\n"
"\n"
"class B : public A\n"
"{\n"
"public:\n"
" ~B() { int a; }\n"
"};");
ASSERT_EQUALS("", errout_str());
// Unknown Base class -> it could have virtual destructor, so ignore
checkVirtualDestructor("class A : private Base\n"
"{\n"
"public:\n"
" ~A() { }\n"
"};\n"
"\n"
"class B : public A\n"
"{\n"
"public:\n"
" ~B() { int a; }\n"
"};");
ASSERT_EQUALS("", errout_str());
// Virtual destructor is inherited -> no error
checkVirtualDestructor("class Base2\n"
"{\n"
"virtual ~Base2() {}\n"
"};\n"
"class Base : public Base2\n"
"{\n"
"};\n"
"class A : private Base\n"
"{\n"
"public:\n"
" ~A() { }\n"
"};\n"
"\n"
"class B : public A\n"
"{\n"
"public:\n"
" ~B() { int a; }\n"
"};");
ASSERT_EQUALS("", errout_str());
// class A doesn't inherit virtual destructor from class Base -> error
checkVirtualDestructor("class Base\n"
"{\n"
"public:\n"
" ~Base() {}\n"
"};\n"
"class A : private Base\n"
"{\n"
"public:\n"
" ~A() { }\n"
"};\n"
"\n"
"class B : public A\n"
"{\n"
"public:\n"
" ~B() { int a; }\n"
"};");
TODO_ASSERT_EQUALS("[test.cpp:7]: (error) Class 'Base' which is inherited by class 'B' does not have a virtual destructor.\n",
"", errout_str());
}
void virtualDestructorTemplate() {
checkVirtualDestructor("template <typename T> class A\n"
"{\n"
" public:\n"
" virtual ~A(){}\n"
"};\n"
"template <typename T> class AA\n"
"{\n"
" public:\n"
" ~AA(){}\n"
"};\n"
"class B : public A<int>, public AA<double>\n"
"{\n"
" public:\n"
" ~B(){int a;}\n"
"};\n"
"\n"
"AA<double> *p = new B; delete p;");
ASSERT_EQUALS("[test.cpp:9]: (error) Class 'AA < double >' which is inherited by class 'B' does not have a virtual destructor.\n", errout_str());
}
void virtualDestructorInconclusive() {
checkVirtualDestructor("class Base {\n"
"public:\n"
" ~Base(){}\n"
" virtual void foo(){}\n"
"};\n", true);
ASSERT_EQUALS("[test.cpp:3]: (warning, inconclusive) Class 'Base' which has virtual members does not have a virtual destructor.\n", errout_str());
checkVirtualDestructor("class Base {\n"
"public:\n"
" ~Base(){}\n"
" virtual void foo(){}\n"
"};\n"
"class Derived : public Base {\n"
"public:\n"
" ~Derived() { bar(); }\n"
"};\n"
"void foo() {\n"
" Base * base = new Derived();\n"
" delete base;\n"
"}\n", true);
ASSERT_EQUALS("[test.cpp:3]: (error) Class 'Base' which is inherited by class 'Derived' does not have a virtual destructor.\n", errout_str());
// class Base destructor is not virtual but protected -> no error
checkVirtualDestructor("class Base {\n"
"public:\n"
" virtual void foo(){}\n"
"protected:\n"
" ~Base(){}\n"
"};\n", true);
ASSERT_EQUALS("", errout_str());
checkVirtualDestructor("class C {\n"
"private:\n"
" C();\n"
" virtual ~C();\n"
"};\n", true);
ASSERT_EQUALS("", errout_str());
}
#define checkNoMemset(...) checkNoMemset_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
void checkNoMemset_(const char* file, int line, const char (&code)[size]) {
const Settings settings = settingsBuilder().severity(Severity::warning).severity(Severity::portability).library("std.cfg").library("posix.cfg").build();
checkNoMemset_(file, line, code, settings);
}
template<size_t size>
void checkNoMemset_(const char* file, int line, const char (&code)[size], const Settings &settings) {
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
// Check..
CheckClass checkClass(&tokenizer, &settings, this);
checkClass.checkMemset();
}
void memsetOnClass() {
checkNoMemset("class Fred\n"
"{\n"
"};\n"
"void f()\n"
"{\n"
" Fred fred;\n"
" memset(&fred, 0, sizeof(Fred));\n"
"}");
ASSERT_EQUALS("", errout_str());
checkNoMemset("class Fred\n"
"{\n"
" static std::string b;\n"
"};\n"
"void f()\n"
"{\n"
" Fred fred;\n"
" memset(&fred, 0, sizeof(Fred));\n"
"}");
ASSERT_EQUALS("", errout_str());
checkNoMemset("class Fred\n"
"{\n"
" std::string * b;\n"
"};\n"
"void f()\n"
"{\n"
" Fred fred;\n"
" memset(&fred, 0, sizeof(Fred));\n"
"}");
ASSERT_EQUALS("", errout_str());
checkNoMemset("class Fred\n"
"{\n"
" std::string b;\n"
"};\n"
"void f()\n"
"{\n"
" Fred fred;\n"
" memset(&fred, 0, sizeof(Fred));\n"
"}");
ASSERT_EQUALS("[test.cpp:8]: (error) Using 'memset' on class that contains a 'std::string'.\n", errout_str());
checkNoMemset("class Fred\n"
"{\n"
" mutable std::string b;\n"
"};\n"
"void f()\n"
"{\n"
" Fred fred;\n"
" memset(&fred, 0, sizeof(Fred));\n"
"}");
ASSERT_EQUALS("[test.cpp:8]: (error) Using 'memset' on class that contains a 'std::string'.\n", errout_str());
checkNoMemset("class Fred {\n"
" std::string b;\n"
" void f();\n"
"};\n"
"void Fred::f() {\n"
" memset(this, 0, sizeof(*this));\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Using 'memset' on class that contains a 'std::string'.\n", errout_str());
checkNoMemset("class Fred\n"
"{\n"
"};\n"
"void f()\n"
"{\n"
" Fred fred;\n"
" memset(&fred, 0, sizeof(fred));\n"
"}");
ASSERT_EQUALS("", errout_str());
checkNoMemset("class Fred\n"
"{\n"
" std::string s;\n"
"};\n"
"void f()\n"
"{\n"
" Fred fred;\n"
" memset(&fred, 0, sizeof(fred));\n"
"}");
ASSERT_EQUALS("[test.cpp:8]: (error) Using 'memset' on class that contains a 'std::string'.\n", errout_str());
checkNoMemset("class Fred\n"
"{\n"
" std::string s;\n"
"};\n"
"class Pebbles: public Fred {};\n"
"void f()\n"
"{\n"
" Pebbles pebbles;\n"
" memset(&pebbles, 0, sizeof(pebbles));\n"
"}");
ASSERT_EQUALS("[test.cpp:9]: (error) Using 'memset' on class that contains a 'std::string'.\n", errout_str());
checkNoMemset("class Fred\n"
"{\n"
" virtual ~Fred();\n"
"};\n"
"void f()\n"
"{\n"
" Fred fred;\n"
" memset(&fred, 0, sizeof(fred));\n"
"}");
ASSERT_EQUALS("[test.cpp:8]: (error) Using 'memset' on class that contains a virtual function.\n", errout_str());
checkNoMemset("class Fred\n"
"{\n"
" virtual ~Fred();\n"
"};\n"
"void f()\n"
"{\n"
" static Fred fred;\n"
" memset(&fred, 0, sizeof(fred));\n"
"}");
ASSERT_EQUALS("[test.cpp:8]: (error) Using 'memset' on class that contains a virtual function.\n", errout_str());
checkNoMemset("class Fred\n"
"{\n"
"};\n"
"class Wilma\n"
"{\n"
" virtual ~Wilma();\n"
"};\n"
"class Pebbles: public Fred, Wilma {};\n"
"void f()\n"
"{\n"
" Pebbles pebbles;\n"
" memset(&pebbles, 0, sizeof(pebbles));\n"
"}");
ASSERT_EQUALS("[test.cpp:12]: (error) Using 'memset' on class that contains a virtual function.\n", errout_str());
// Fred not defined in scope
checkNoMemset("namespace n1 {\n"
" class Fred\n"
" {\n"
" std::string b;\n"
" };\n"
"}\n"
"void f()\n"
"{\n"
" Fred fred;\n"
" memset(&fred, 0, sizeof(Fred));\n"
"}");
ASSERT_EQUALS("", errout_str());
// Fred with namespace qualifier
checkNoMemset("namespace n1 {\n"
" class Fred\n"
" {\n"
" std::string b;\n"
" };\n"
"}\n"
"void f()\n"
"{\n"
" n1::Fred fred;\n"
" memset(&fred, 0, sizeof(n1::Fred));\n"
"}");
ASSERT_EQUALS("[test.cpp:10]: (error) Using 'memset' on class that contains a 'std::string'.\n", errout_str());
// Fred with namespace qualifier
checkNoMemset("namespace n1 {\n"
" class Fred\n"
" {\n"
" std::string b;\n"
" };\n"
"}\n"
"void f()\n"
"{\n"
" n1::Fred fred;\n"
" memset(&fred, 0, sizeof(fred));\n"
"}");
ASSERT_EQUALS("[test.cpp:10]: (error) Using 'memset' on class that contains a 'std::string'.\n", errout_str());
checkNoMemset("class A {\n"
" virtual ~A() { }\n"
" std::string s;\n"
"};\n"
"int f() {\n"
" const int N = 10;\n"
" A** arr = new A*[N];\n"
" memset(arr, 0, N * sizeof(A*));\n"
"}");
ASSERT_EQUALS("", errout_str());
checkNoMemset("class A {\n" // #5116 - nested class data is mixed in the SymbolDatabase
" std::string s;\n"
" struct B { int x; };\n"
"};\n"
"void f(A::B *b) {\n"
" memset(b,0,4);\n"
"}");
ASSERT_EQUALS("", errout_str());
// #4461 Warn about memset/memcpy on class with references as members
checkNoMemset("class A {\n"
" std::string &s;\n"
"};\n"
"void f() {\n"
" A a;\n"
" memset(&a, 0, sizeof(a));\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Using 'memset' on class that contains a reference.\n", errout_str());
checkNoMemset("class A {\n"
" const B&b;\n"
"};\n"
"void f() {\n"
" A a;\n"
" memset(&a, 0, sizeof(a));\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (error) Using 'memset' on class that contains a reference.\n", errout_str());
// #7456
checkNoMemset("struct A {\n"
" A() {}\n"
" virtual ~A() {}\n"
"};\n"
"struct B {\n"
" A* arr[4];\n"
"};\n"
"void func() {\n"
" B b[4];\n"
" memset(b, 0, sizeof(b));\n"
"}");
ASSERT_EQUALS("", errout_str());
// #8619
checkNoMemset("struct S { std::vector<int> m; };\n"
"void f() {\n"
" std::vector<S> v(5);\n"
" memset(&v[0], 0, sizeof(S) * v.size());\n"
" memset(&v[0], 0, v.size() * sizeof(S));\n"
" memset(&v[0], 0, 5 * sizeof(S));\n"
" memset(&v[0], 0, sizeof(S) * 5);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (error) Using 'memset' on struct that contains a 'std::vector'.\n"
"[test.cpp:5]: (error) Using 'memset' on struct that contains a 'std::vector'.\n"
"[test.cpp:6]: (error) Using 'memset' on struct that contains a 'std::vector'.\n"
"[test.cpp:7]: (error) Using 'memset' on struct that contains a 'std::vector'.\n",
errout_str());
// #1655
const Settings s = settingsBuilder().library("std.cfg").build();
checkNoMemset("void f() {\n"
" char c[] = \"abc\";\n"
" std::string s;\n"
" memcpy(&s, c, strlen(c) + 1);\n"
"}\n", s);
ASSERT_EQUALS("[test.cpp:4]: (error) Using 'memcpy' on std::string.\n", errout_str());
checkNoMemset("template <typename T>\n"
" void f(T* dst, const T* src, int N) {\n"
" std::memcpy(dst, src, N * sizeof(T));\n"
"}\n"
"void g() {\n"
" typedef std::vector<int>* P;\n"
" P Src[2]{};\n"
" P Dst[2];\n"
" f<P>(Dst, Src, 2);\n"
"}\n", s);
ASSERT_EQUALS("", errout_str());
checkNoMemset("void f() {\n"
" std::array<char, 4> a;\n"
" std::memset(&a, 0, 4);\n"
"}\n", s);
ASSERT_EQUALS("", errout_str());
}
void memsetOnInvalid() { // Ticket #5425
checkNoMemset("union ASFStreamHeader {\n"
" struct AVMPACKED {\n"
" union {\n"
" struct AVMPACKED {\n"
" int width;\n"
" } vid;\n"
" };\n"
" } hdr;\n"
"};"
"void parseHeader() {\n"
" ASFStreamHeader strhdr;\n"
" memset(&strhdr, 0, sizeof(strhdr));\n"
"}");
}
void memsetOnStruct() {
checkNoMemset("struct A\n"
"{\n"
"};\n"
"void f()\n"
"{\n"
" A a;\n"
" memset(&a, 0, sizeof(A));\n"
"}");
ASSERT_EQUALS("", errout_str());
checkNoMemset("struct A\n"
"{\n"
"};\n"
"void f()\n"
"{\n"
" struct A a;\n"
" memset(&a, 0, sizeof(struct A));\n"
"}");
ASSERT_EQUALS("", errout_str());
checkNoMemset("struct A\n"
"{\n"
"};\n"
"void f()\n"
"{\n"
" struct A a;\n"
" memset(&a, 0, sizeof(A));\n"
"}");
ASSERT_EQUALS("", errout_str());
checkNoMemset("void f()\n"
"{\n"
" struct sockaddr_in6 fail;\n"
" memset(&fail, 0, sizeof(struct sockaddr_in6));\n"
"}");
ASSERT_EQUALS("", errout_str());
checkNoMemset("struct A\n"
"{\n"
" void g( struct sockaddr_in6& a);\n"
"private:\n"
" std::string b;\n"
"};\n"
"void f()\n"
"{\n"
" struct A fail;\n"
" memset(&fail, 0, sizeof(struct A));\n"
"}");
ASSERT_EQUALS("[test.cpp:10]: (error) Using 'memset' on struct that contains a 'std::string'.\n", errout_str());
checkNoMemset("struct Fred\n"
"{\n"
" std::string s;\n"
"};\n"
"void f()\n"
"{\n"
" Fred fred;\n"
" memset(&fred, 0, sizeof(fred));\n"
"}");
ASSERT_EQUALS("[test.cpp:8]: (error) Using 'memset' on struct that contains a 'std::string'.\n", errout_str());
checkNoMemset("struct Stringy {\n"
" std::string inner;\n"
"};\n"
"struct Foo {\n"
" Stringy s;\n"
"};\n"
"int main() {\n"
" Foo foo;\n"
" memset(&foo, 0, sizeof(Foo));\n"
"}");
ASSERT_EQUALS("[test.cpp:9]: (error) Using 'memset' on struct that contains a 'std::string'.\n", errout_str());
}
void memsetVector() {
checkNoMemset("class A\n"
"{ std::vector<int> ints; };\n"
"\n"
"void f()\n"
"{\n"
" A a;\n"
" memset(&a, 0, sizeof(A));\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (error) Using 'memset' on class that contains a 'std::vector'.\n", errout_str());
checkNoMemset("struct A\n"
"{ std::vector<int> ints; };\n"
"\n"
"void f()\n"
"{\n"
" A a;\n"
" memset(&a, 0, sizeof(A));\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (error) Using 'memset' on struct that contains a 'std::vector'.\n", errout_str());
checkNoMemset("struct A\n"
"{ std::vector<int> ints; };\n"
"\n"
"void f()\n"
"{\n"
" A a;\n"
" memset(&a, 0, sizeof(struct A));\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (error) Using 'memset' on struct that contains a 'std::vector'.\n", errout_str());
checkNoMemset("struct A\n"
"{ std::vector<int> ints; };\n"
"\n"
"void f()\n"
"{\n"
" A a;\n"
" memset(&a, 0, sizeof(a));\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (error) Using 'memset' on struct that contains a 'std::vector'.\n", errout_str());
checkNoMemset("class A\n"
"{ std::vector< std::vector<int> > ints; };\n"
"\n"
"void f()\n"
"{\n"
" A a;\n"
" memset(&a, 0, sizeof(A));\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (error) Using 'memset' on class that contains a 'std::vector'.\n", errout_str());
checkNoMemset("struct A\n"
"{ std::vector< std::vector<int> > ints; };\n"
"\n"
"void f()\n"
"{\n"
" A a;\n"
" memset(&a, 0, sizeof(A));\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (error) Using 'memset' on struct that contains a 'std::vector'.\n", errout_str());
checkNoMemset("struct A\n"
"{ std::vector< std::vector<int> > ints; };\n"
"\n"
"void f()\n"
"{\n"
" A a;\n"
" memset(&a, 0, sizeof(a));\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (error) Using 'memset' on struct that contains a 'std::vector'.\n", errout_str());
checkNoMemset("struct A\n"
"{ std::vector<int *> ints; };\n"
"\n"
"void f()\n"
"{\n"
" A a;\n"
" memset(&a, 0, sizeof(A));\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (error) Using 'memset' on struct that contains a 'std::vector'.\n", errout_str());
checkNoMemset("struct A {\n"
" std::vector<int *> buf;\n"
" operator int*() {return &buf[0];}\n"
"};\n"
"void f() {\n"
" A a;\n"
" memset(a, 0, 100);\n"
"}");
ASSERT_EQUALS("", errout_str()); // #4460
checkNoMemset("struct C {\n"
" std::string s;\n"
"};\n"
"int foo() {\n"
" C* c1[10][10];\n"
" C* c2[10];\n"
" C c3[10][10];\n"
" C** c4 = new C*[10];\n"
" memset(**c1, 0, 10);\n"
" memset(*c1, 0, 10);\n"
" memset(*c2, 0, 10);\n"
" memset(*c3, 0, 10);\n"
" memset(*c4, 0, 10);\n"
" memset(c2, 0, 10);\n"
" memset(c3, 0, 10);\n"
"}");
ASSERT_EQUALS("[test.cpp:9]: (error) Using 'memset' on struct that contains a 'std::string'.\n"
"[test.cpp:11]: (error) Using 'memset' on struct that contains a 'std::string'.\n"
"[test.cpp:12]: (error) Using 'memset' on struct that contains a 'std::string'.\n"
"[test.cpp:13]: (error) Using 'memset' on struct that contains a 'std::string'.\n", errout_str());
// Ticket #6953
checkNoMemset("typedef float realnum;\n"
"struct multilevel_data {\n"
" realnum *GammaInv;\n"
" realnum data[1];\n"
"};\n"
"void *new_internal_data() const {\n"
" multilevel_data *d = (multilevel_data *) malloc(sizeof(multilevel_data));\n"
" memset(d, 0, sizeof(multilevel_data));\n"
" return (void*) d;\n"
"}");
ASSERT_EQUALS("[test.cpp:8]: (portability) Using memset() on struct which contains a floating point number.\n", errout_str());
}
void memsetOnStdPodType() { // Ticket #5901
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <podtype name=\"std::uint8_t\" sign=\"u\" size=\"1\"/>\n"
" <podtype name=\"std::atomic_bool\"/>\n"
"</def>";
const Settings settings = settingsBuilder().libraryxml(xmldata, sizeof(xmldata)).build();
checkNoMemset("class A {\n"
" std::array<int, 10> ints;\n"
"};\n"
"void f() {\n"
" A a;\n"
" memset(&a, 0, sizeof(A));\n"
"}");
ASSERT_EQUALS("", errout_str()); // std::array is POD (#5481)
checkNoMemset("struct st {\n"
" std::uint8_t a;\n"
" std::atomic_bool b;\n"
"};\n"
"\n"
"void f() {\n"
" st s;\n"
" std::memset(&s, 0, sizeof(st));\n"
"}", settings);
ASSERT_EQUALS("", errout_str());
}
void memsetOnFloat() {
checkNoMemset("struct A {\n"
" float f;\n"
"};\n"
"void f() {\n"
" A a;\n"
" memset(&a, 0, sizeof(A));\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (portability) Using memset() on struct which contains a floating point number.\n", errout_str());
checkNoMemset("struct A {\n"
" float f[4];\n"
"};\n"
"void f() {\n"
" A a;\n"
" memset(&a, 0, sizeof(A));\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (portability) Using memset() on struct which contains a floating point number.\n", errout_str());
checkNoMemset("struct A {\n"
" float f[4];\n"
"};\n"
"void f(const A& b) {\n"
" A a;\n"
" memcpy(&a, &b, sizeof(A));\n"
"}");
ASSERT_EQUALS("", errout_str());
checkNoMemset("struct A {\n"
" float* f;\n"
"};\n"
"void f() {\n"
" A a;\n"
" memset(&a, 0, sizeof(A));\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void memsetOnUnknown() {
checkNoMemset("void clang_tokenize(CXToken **Tokens) {\n"
" *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());\n"
" memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void mallocOnClass() {
checkNoMemset("class C { C() {} };\n"
"void foo(C*& p) {\n"
" p = malloc(sizeof(C));\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:1]: (warning) Memory for class instance allocated with malloc(), but class provides constructors.\n", errout_str());
checkNoMemset("class C { C(int z, Foo bar) { bar(); } };\n"
"void foo(C*& p) {\n"
" p = malloc(sizeof(C));\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:1]: (warning) Memory for class instance allocated with malloc(), but class provides constructors.\n", errout_str());
checkNoMemset("struct C { C() {} };\n"
"void foo(C*& p) {\n"
" p = realloc(p, sizeof(C));\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:1]: (warning) Memory for class instance allocated with realloc(), but class provides constructors.\n", errout_str());
checkNoMemset("struct C { virtual void bar(); };\n"
"void foo(C*& p) {\n"
" p = malloc(sizeof(C));\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:1]: (error) Memory for class instance allocated with malloc(), but class contains a virtual function.\n", errout_str());
checkNoMemset("struct C { std::string s; };\n"
"void foo(C*& p) {\n"
" p = malloc(sizeof(C));\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:1]: (error) Memory for class instance allocated with malloc(), but class contains a 'std::string'.\n", errout_str());
checkNoMemset("class C { };\n" // C-Style class/struct
"void foo(C*& p) {\n"
" p = malloc(sizeof(C));\n"
"}");
ASSERT_EQUALS("", errout_str());
checkNoMemset("struct C { C() {} };\n"
"void foo(C*& p) {\n"
" p = new C();\n"
"}");
ASSERT_EQUALS("", errout_str());
checkNoMemset("class C { C() {} };\n"
"void foo(D*& p) {\n" // Unknown type
" p = malloc(sizeof(C));\n"
"}");
ASSERT_EQUALS("", errout_str());
checkNoMemset("class AutoCloseFD {\n"
" int fd;\n"
"public:\n"
" AutoCloseFD(int fd);\n"
" ~AutoCloseFD();\n"
"};\n"
"void f() {\n"
" AutoCloseFD fd = open(\"abc\", O_RDONLY | O_CLOEXEC);\n"
"}");
ASSERT_EQUALS("", errout_str());
checkNoMemset("struct C {\n" // #12313
" char* p;\n"
" C(char* ptr) : p(ptr) {}\n"
"};\n"
"void f() {\n"
" C c = strdup(\"abc\");\n"
"}");
ASSERT_EQUALS("", errout_str());
}
#define checkThisSubtraction(code) checkThisSubtraction_(code, __FILE__, __LINE__)
template<size_t size>
void checkThisSubtraction_(const char (&code)[size], const char* file, int line) {
// Tokenize..
SimpleTokenizer tokenizer(settings1, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
// Check..
CheckClass checkClass(&tokenizer, &settings1, this);
checkClass.thisSubtraction();
}
void this_subtraction() {
checkThisSubtraction("; this-x ;");
ASSERT_EQUALS("[test.cpp:1]: (warning) Suspicious pointer subtraction. Did you intend to write '->'?\n", errout_str());
checkThisSubtraction("; *this = *this-x ;");
ASSERT_EQUALS("", errout_str());
checkThisSubtraction("; *this = *this-x ;\n"
"this-x ;");
ASSERT_EQUALS("[test.cpp:2]: (warning) Suspicious pointer subtraction. Did you intend to write '->'?\n", errout_str());
checkThisSubtraction("; *this = *this-x ;\n"
"this-x ;\n"
"this-x ;");
ASSERT_EQUALS("[test.cpp:2]: (warning) Suspicious pointer subtraction. Did you intend to write '->'?\n"
"[test.cpp:3]: (warning) Suspicious pointer subtraction. Did you intend to write '->'?\n", errout_str());
}
#define checkConst(...) checkConst_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
void checkConst_(const char* file, int line, const char (&code)[size], const Settings *s = nullptr, bool inconclusive = true) {
const Settings settings = settingsBuilder(s ? *s : settings0).certainty(Certainty::inconclusive, inconclusive).build();
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
CheckClass checkClass(&tokenizer, &settings, this);
(checkClass.checkConst)();
}
void const1() {
checkConst("class Fred {\n"
" int a;\n"
" int getA() { return a; }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (style, inconclusive) Technically the member function 'Fred::getA' can be const.\n", errout_str());
checkConst("class Fred {\n"
" const std::string foo() { return \"\"; }\n"
"};");
ASSERT_EQUALS("[test.cpp:2]: (performance, inconclusive) Technically the member function 'Fred::foo' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
checkConst("class Fred {\n"
" std::string s;\n"
" const std::string & foo() { return \"\"; }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (performance, inconclusive) Technically the member function 'Fred::foo' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
// constructors can't be const..
checkConst("class Fred {\n"
" int a;\n"
"public:\n"
" Fred() { }\n"
"};");
ASSERT_EQUALS("", errout_str());
// assignment through |=..
checkConst("class Fred {\n"
" int a;\n"
" int setA() { a |= true; }\n"
"};");
ASSERT_EQUALS("", errout_str());
// functions with a call to a member function can only be const, if that member function is const, too.. (#1305)
checkConst("class foo {\n"
"public:\n"
" int x;\n"
" void a() { x = 1; }\n"
" void b() { a(); }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class Fred {\n"
"public:\n"
" int x;\n"
" int a() const { return x; }\n"
" void b() { a(); }\n"
"};");
ASSERT_EQUALS("[test.cpp:5]: (style, inconclusive) Technically the member function 'Fred::b' can be const.\n", errout_str());
checkConst("class Fred {\n"
"public:\n"
" int x;\n"
" void b() { a(); }\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (performance, inconclusive) Technically the member function 'Fred::b' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
// static functions can't be const..
checkConst("class foo\n"
"{\n"
"public:\n"
" static unsigned get()\n"
" { return 0; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class Fred {\n"
" const std::string foo() const throw() { return \"\"; }\n"
"};");
ASSERT_EQUALS("[test.cpp:2]: (performance, inconclusive) Technically the member function 'Fred::foo' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
}
void const2() {
// ticket 1344
// assignment to variable can't be const
checkConst("class Fred {\n"
" std::string s;\n"
" void foo() { s = \"\"; }\n"
"};");
ASSERT_EQUALS("", errout_str());
// assignment to function argument reference can be const
checkConst("class Fred {\n"
" std::string s;\n"
" void foo(std::string & a) { a = s; }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (style, inconclusive) Technically the member function 'Fred::foo' can be const.\n", errout_str());
// assignment to variable can't be const
checkConst("class Fred {\n"
" std::string s;\n"
" void foo(std::string & a) { s = a; }\n"
"};");
ASSERT_EQUALS("", errout_str());
// assignment to function argument references can be const
checkConst("class Fred {\n"
" std::string s;\n"
" void foo(std::string & a, std::string & b) { a = s; b = s; }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (style, inconclusive) Technically the member function 'Fred::foo' can be const.\n", errout_str());
// assignment to variable, can't be const
checkConst("class Fred {\n"
" std::string s;\n"
" void foo(std::string & a, std::string & b) { s = a; s = b; }\n"
"};");
ASSERT_EQUALS("", errout_str());
// assignment to variable, can't be const
checkConst("class Fred {\n"
" std::string s;\n"
" void foo(std::string & a, std::string & b) { s = a; b = a; }\n"
"};");
ASSERT_EQUALS("", errout_str());
// assignment to variable, can't be const
checkConst("class Fred {\n"
" std::string s;\n"
" void foo(std::string & a, std::string & b) { a = s; s = b; }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void const3() {
// assignment to function argument pointer can be const
checkConst("class Fred {\n"
" int s;\n"
" void foo(int * a) { *a = s; }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (style, inconclusive) Technically the member function 'Fred::foo' can be const.\n", errout_str());
// assignment to variable, can't be const
checkConst("class Fred {\n"
" int s;\n"
" void foo(int * a) { s = *a; }\n"
"};");
ASSERT_EQUALS("", errout_str());
// assignment to function argument pointers can be const
checkConst("class Fred {\n"
" std::string s;\n"
" void foo(std::string * a, std::string * b) { *a = s; *b = s; }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (style, inconclusive) Technically the member function 'Fred::foo' can be const.\n", errout_str());
// assignment to variable, can't be const
checkConst("class Fred {\n"
" std::string s;\n"
" void foo(std::string * a, std::string * b) { s = *a; s = *b; }\n"
"};");
ASSERT_EQUALS("", errout_str());
// assignment to variable, can't be const
checkConst("class Fred {\n"
" std::string s;\n"
" void foo(std::string * a, std::string * b) { s = *a; *b = s; }\n"
"};");
ASSERT_EQUALS("", errout_str());
// assignment to variable, can't be const
checkConst("class Fred {\n"
" std::string s;\n"
" void foo(std::string * a, std::string * b) { *a = s; s = b; }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void const4() {
checkConst("class Fred {\n"
" int a;\n"
" int getA();\n"
"};\n"
"int Fred::getA() { return a; }");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:3]: (style, inconclusive) Technically the member function 'Fred::getA' can be const.\n", errout_str());
checkConst("class Fred {\n"
" std::string s;\n"
" const std::string & foo();\n"
"};\n"
"const std::string & Fred::foo() { return \"\"; }");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:3]: (performance, inconclusive) Technically the member function 'Fred::foo' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
// functions with a function call to a non-const member can't be const.. (#1305)
checkConst("class Fred\n"
"{\n"
"public:\n"
" int x;\n"
" void a() { x = 1; }\n"
" void b();\n"
"};\n"
"void Fred::b() { a(); }");
ASSERT_EQUALS("", errout_str());
// static functions can't be const..
checkConst("class Fred\n"
"{\n"
"public:\n"
" static unsigned get();\n"
"};\n"
"static unsigned Fred::get() { return 0; }");
ASSERT_EQUALS("", errout_str());
// assignment to variable can't be const
checkConst("class Fred {\n"
" std::string s;\n"
" void foo();\n"
"};\n"
"void Fred::foo() { s = \"\"; }");
ASSERT_EQUALS("", errout_str());
// assignment to function argument reference can be const
checkConst("class Fred {\n"
" std::string s;\n"
" void foo(std::string & a);\n"
"};\n"
"void Fred::foo(std::string & a) { a = s; }");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:3]: (style, inconclusive) Technically the member function 'Fred::foo' can be const.\n", errout_str());
// assignment to variable can't be const
checkConst("class Fred {\n"
" std::string s;\n"
" void foo(std::string & a);\n"
"};\n"
"void Fred::foo(std::string & a) { s = a; }");
ASSERT_EQUALS("", errout_str());
// assignment to function argument references can be const
checkConst("class Fred {\n"
" std::string s;\n"
" void foo(std::string & a, std::string & b);\n"
"};\n"
"void Fred::foo(std::string & a, std::string & b) { a = s; b = s; }");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:3]: (style, inconclusive) Technically the member function 'Fred::foo' can be const.\n", errout_str());
// assignment to variable, can't be const
checkConst("class Fred {\n"
" std::string s;\n"
" void foo(std::string & a, std::string & b);\n"
"};\n"
"void Fred::foo(std::string & a, std::string & b) { s = a; s = b; }");
ASSERT_EQUALS("", errout_str());
// assignment to variable, can't be const
checkConst("class Fred {\n"
" std::string s;\n"
" void foo(std::string & a, std::string & b);\n"
"};\n"
"void Fred::foo(std::string & a, std::string & b) { s = a; b = a; }");
ASSERT_EQUALS("", errout_str());
// assignment to variable, can't be const
checkConst("class Fred {\n"
" std::string s;\n"
" void foo(std::string & a, std::string & b);\n"
"};\n"
"void Fred::foo(std::string & a, std::string & b) { a = s; s = b; }");
ASSERT_EQUALS("", errout_str());
// assignment to function argument pointer can be const
checkConst("class Fred {\n"
" int s;\n"
" void foo(int * a);\n"
"};\n"
"void Fred::foo(int * a) { *a = s; }");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:3]: (style, inconclusive) Technically the member function 'Fred::foo' can be const.\n", errout_str());
// assignment to variable, can't be const
checkConst("class Fred {\n"
" int s;\n"
" void foo(int * a);\n"
"};\n"
"void Fred::foo(int * a) { s = *a; }");
ASSERT_EQUALS("", errout_str());
// assignment to function argument pointers can be const
checkConst("class Fred {\n"
" std::string s;\n"
" void foo(std::string * a, std::string * b);\n"
"};\n"
"void Fred::foo(std::string * a, std::string * b) { *a = s; *b = s; }");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:3]: (style, inconclusive) Technically the member function 'Fred::foo' can be const.\n", errout_str());
// assignment to variable, can't be const
checkConst("class Fred {\n"
" std::string s;\n"
" void foo(std::string * a, std::string * b);\n"
"};\n"
"void Fred::foo(std::string * a, std::string * b) { s = *a; s = *b; }");
ASSERT_EQUALS("", errout_str());
// assignment to variable, can't be const
checkConst("class Fred {\n"
" std::string s;\n"
" void foo(std::string * a, std::string * b);\n"
"};\n"
"void Fred::foo(std::string * a, std::string * b) { s = *a; *b = s; }");
ASSERT_EQUALS("", errout_str());
// assignment to variable, can't be const
checkConst("class Fred {\n"
" std::string s;\n"
" void foo(std::string * a, std::string * b);\n"
"};\n"
"void Fred::foo(std::string * a, std::string * b) { *a = s; s = b; }");
ASSERT_EQUALS("", errout_str());
// check functions with same name
checkConst("class Fred {\n"
" std::string s;\n"
" void foo();\n"
" void foo(std::string & a);\n"
" void foo(const std::string & a);\n"
"};\n"
"void Fred::foo() { }"
"void Fred::foo(std::string & a) { a = s; }"
"void Fred::foo(const std::string & a) { s = a; }");
ASSERT_EQUALS("[test.cpp:7] -> [test.cpp:3]: (performance, inconclusive) Technically the member function 'Fred::foo' can be static (but you may consider moving to unnamed namespace).\n"
"[test.cpp:7] -> [test.cpp:4]: (style, inconclusive) Technically the member function 'Fred::foo' can be const.\n", errout_str());
// check functions with different or missing parameter names
checkConst("class Fred {\n"
" std::string s;\n"
" void foo1(int, int);\n"
" void foo2(int a, int b);\n"
" void foo3(int, int b);\n"
" void foo4(int a, int);\n"
" void foo5(int a, int b);\n"
"};\n"
"void Fred::foo1(int a, int b) { }\n"
"void Fred::foo2(int c, int d) { }\n"
"void Fred::foo3(int a, int b) { }\n"
"void Fred::foo4(int a, int b) { }\n"
"void Fred::foo5(int, int) { }");
ASSERT_EQUALS("[test.cpp:9] -> [test.cpp:3]: (performance, inconclusive) Technically the member function 'Fred::foo1' can be static (but you may consider moving to unnamed namespace).\n"
"[test.cpp:10] -> [test.cpp:4]: (performance, inconclusive) Technically the member function 'Fred::foo2' can be static (but you may consider moving to unnamed namespace).\n"
"[test.cpp:11] -> [test.cpp:5]: (performance, inconclusive) Technically the member function 'Fred::foo3' can be static (but you may consider moving to unnamed namespace).\n"
"[test.cpp:12] -> [test.cpp:6]: (performance, inconclusive) Technically the member function 'Fred::foo4' can be static (but you may consider moving to unnamed namespace).\n"
"[test.cpp:13] -> [test.cpp:7]: (performance, inconclusive) Technically the member function 'Fred::foo5' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
// check nested classes
checkConst("class Fred {\n"
" class A {\n"
" int a;\n"
" int getA() { return a; }\n"
" };\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (style, inconclusive) Technically the member function 'Fred::A::getA' can be const.\n", errout_str());
checkConst("class Fred {\n"
" class A {\n"
" int a;\n"
" int getA();\n"
" };\n"
" int A::getA() { return a; }\n"
"};");
ASSERT_EQUALS("[test.cpp:6] -> [test.cpp:4]: (style, inconclusive) Technically the member function 'Fred::A::getA' can be const.\n", errout_str());
checkConst("class Fred {\n"
" class A {\n"
" int a;\n"
" int getA();\n"
" };\n"
"};\n"
"int Fred::A::getA() { return a; }");
ASSERT_EQUALS("[test.cpp:7] -> [test.cpp:4]: (style, inconclusive) Technically the member function 'Fred::A::getA' can be const.\n", errout_str());
// check deeply nested classes
checkConst("class Fred {\n"
" class B {\n"
" int b;\n"
" int getB() { return b; }\n"
" class A {\n"
" int a;\n"
" int getA() { return a; }\n"
" };\n"
" };\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (style, inconclusive) Technically the member function 'Fred::B::getB' can be const.\n"
"[test.cpp:7]: (style, inconclusive) Technically the member function 'Fred::B::A::getA' can be const.\n"
, errout_str());
checkConst("class Fred {\n"
" class B {\n"
" int b;\n"
" int getB();\n"
" class A {\n"
" int a;\n"
" int getA();\n"
" };\n"
" int A::getA() { return a; }\n"
" };\n"
" int B::getB() { return b; }\n"
"};");
ASSERT_EQUALS("[test.cpp:11] -> [test.cpp:4]: (style, inconclusive) Technically the member function 'Fred::B::getB' can be const.\n"
"[test.cpp:9] -> [test.cpp:7]: (style, inconclusive) Technically the member function 'Fred::B::A::getA' can be const.\n", errout_str());
checkConst("class Fred {\n"
" class B {\n"
" int b;\n"
" int getB();\n"
" class A {\n"
" int a;\n"
" int getA();\n"
" };\n"
" };\n"
" int B::A::getA() { return a; }\n"
" int B::getB() { return b; }\n"
"};");
ASSERT_EQUALS("[test.cpp:11] -> [test.cpp:4]: (style, inconclusive) Technically the member function 'Fred::B::getB' can be const.\n"
"[test.cpp:10] -> [test.cpp:7]: (style, inconclusive) Technically the member function 'Fred::B::A::getA' can be const.\n", errout_str());
checkConst("class Fred {\n"
" class B {\n"
" int b;\n"
" int getB();\n"
" class A {\n"
" int a;\n"
" int getA();\n"
" };\n"
" };\n"
"};\n"
"int Fred::B::A::getA() { return a; }\n"
"int Fred::B::getB() { return b; }");
ASSERT_EQUALS("[test.cpp:12] -> [test.cpp:4]: (style, inconclusive) Technically the member function 'Fred::B::getB' can be const.\n"
"[test.cpp:11] -> [test.cpp:7]: (style, inconclusive) Technically the member function 'Fred::B::A::getA' can be const.\n", errout_str());
}
// operator< can often be const
void constoperator1() {
checkConst("struct Fred {\n"
" int a;\n"
" bool operator<(const Fred &f) { return a < f.a; }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (style, inconclusive) Technically the member function 'Fred::operator<' can be const.\n", errout_str());
}
// operator<<
void constoperator2() {
checkConst("struct Foo {\n"
" void operator<<(int);\n"
"};\n"
"struct Fred {\n"
" Foo foo;\n"
" void x()\n"
" {\n"
" foo << 123;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("struct Foo {\n"
" void operator<<(int);\n"
"};\n"
"struct Fred {\n"
" Foo foo;\n"
" void x()\n"
" {\n"
" std::cout << foo << 123;\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:6]: (style, inconclusive) Technically the member function 'Fred::x' can be const.\n", errout_str());
}
void constoperator3() {
checkConst("struct Fred {\n"
" int array[10];\n"
" int const & operator [] (unsigned int index) const { return array[index]; }\n"
" int & operator [] (unsigned int index) { return array[index]; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("struct Fred {\n"
" int array[10];\n"
" int const & operator [] (unsigned int index) { return array[index]; }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (style, inconclusive) Technically the member function 'Fred::operator[]' can be const.\n", errout_str());
}
void constoperator4() {
// #7953
checkConst("class A {\n"
" int c;\n"
"public:\n"
" operator int*() { return &c; };\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class A {\n"
" int c;\n"
"public:\n"
" operator const int*() { return &c; };\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (style, inconclusive) Technically the member function 'A::operatorconstint*' can be const.\n", errout_str());
// #2375
checkConst("struct Fred {\n"
" int array[10];\n"
" typedef int* (Fred::*UnspecifiedBoolType);\n"
" operator UnspecifiedBoolType() { };\n"
"};");
TODO_ASSERT_EQUALS("[test.cpp:4]: (style, inconclusive) Technically the member function 'Fred::operatorint**' can be const.\n", "", errout_str());
checkConst("struct Fred {\n"
" int array[10];\n"
" typedef int* (Fred::*UnspecifiedBoolType);\n"
" operator UnspecifiedBoolType() { array[0] = 0; };\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void constoperator5() { // ticket #3252
checkConst("class A {\n"
" int c;\n"
"public:\n"
" operator int& () {return c}\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class A {\n"
" int c;\n"
"public:\n"
" operator const int& () {return c}\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (style, inconclusive) Technically the member function 'A::operatorconstint&' can be const.\n", errout_str());
checkConst("class A {\n"
" int c;\n"
"public:\n"
" operator int () {return c}\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (style, inconclusive) Technically the member function 'A::operatorint' can be const.\n", errout_str());
}
void constoperator6() { // ticket #8669
checkConst("class A {\n"
" int c;\n"
" void f() { os >> *this; }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void const5() {
// ticket #1482
checkConst("class A {\n"
" int a;\n"
" bool foo(int i)\n"
" {\n"
" bool same;\n"
" same = (i == a);\n"
" return same;\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (style, inconclusive) Technically the member function 'A::foo' can be const.\n", errout_str());
}
void const6() {
// ticket #1491
checkConst("class foo {\n"
"public:\n"
"};\n"
"void bar() {}");
ASSERT_EQUALS("", errout_str());
checkConst("class Fred\n"
"{\n"
"public:\n"
" void foo() { }\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (performance, inconclusive) Technically the member function 'Fred::foo' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
checkConst("struct fast_string\n"
"{\n"
" union\n"
" {\n"
" char buff[100];\n"
" };\n"
" void set_type(char t);\n"
"};\n"
"inline void fast_string::set_type(char t)\n"
"{\n"
" buff[10] = t;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void const7() {
checkConst("class foo {\n"
" int a;\n"
"public:\n"
" void set(int i) { a = i; }\n"
" void set(const foo & f) { *this = f; }\n"
"};\n"
"void bar() {}");
ASSERT_EQUALS("", errout_str());
}
void const8() {
// ticket #1517
checkConst("class A {\n"
"public:\n"
" A():m_strValue(\"\"){}\n"
" std::string strGetString() { return m_strValue; }\n"
"private:\n"
" std::string m_strValue;\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (style, inconclusive) Technically the member function 'A::strGetString' can be const.\n", errout_str());
}
void const9() {
// ticket #1515
checkConst("class wxThreadInternal {\n"
"public:\n"
" void SetExitCode(wxThread::ExitCode exitcode) { m_exitcode = exitcode; }\n"
"private:\n"
" wxThread::ExitCode m_exitcode;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void const10() {
// ticket #1522
checkConst("class A {\n"
"public:\n"
" int foo() { return x = 0; }\n"
"private:\n"
" int x;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class A {\n"
"public:\n"
" int foo() { return x ? x : x = 0; }\n"
"private:\n"
" int x;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class A {\n"
"public:\n"
" int foo() { return x ? x = 0 : x; }\n"
"private:\n"
" int x;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void const11() {
// ticket #1529
checkConst("class A {\n"
"public:\n"
" void set(struct tm time) { m_time = time; }\n"
"private:\n"
" struct tm m_time;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void const12() {
// ticket #1525
checkConst("class A {\n"
"public:\n"
" int foo() { x = 0; }\n"
"private:\n"
" mutable int x;\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (style, inconclusive) Technically the member function 'A::foo' can be const.\n", errout_str());
}
void const13() {
// ticket #1519
checkConst("class A {\n"
"public:\n"
" A(){}\n"
" std::vector<int> GetVec() {return m_vec;}\n"
" std::pair<int,double> GetPair() {return m_pair;}\n"
"private:\n"
" std::vector<int> m_vec;\n"
" std::pair<int,double> m_pair;\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (style, inconclusive) Technically the member function 'A::GetVec' can be const.\n"
"[test.cpp:5]: (style, inconclusive) Technically the member function 'A::GetPair' can be const.\n", errout_str());
checkConst("class A {\n"
"public:\n"
" A(){}\n"
" const std::vector<int> & GetVec() {return m_vec;}\n"
" const std::pair<int,double> & GetPair() {return m_pair;}\n"
"private:\n"
" std::vector<int> m_vec;\n"
" std::pair<int,double> m_pair;\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (style, inconclusive) Technically the member function 'A::GetVec' can be const.\n"
"[test.cpp:5]: (style, inconclusive) Technically the member function 'A::GetPair' can be const.\n", errout_str());
}
void const14() {
// extends ticket 1519
checkConst("class A {\n"
"public:\n"
" A(){}\n"
" std::pair<std::vector<int>,double> GetPair() {return m_pair;}\n"
"private:\n"
" std::pair<std::vector<int>,double> m_pair;\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (style, inconclusive) Technically the member function 'A::GetPair' can be const.\n", errout_str());
checkConst("class A {\n"
"public:\n"
" A(){}\n"
" const std::pair<std::vector<int>,double>& GetPair() {return m_pair;}\n"
"private:\n"
" std::pair<std::vector<int>,double> m_pair;\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (style, inconclusive) Technically the member function 'A::GetPair' can be const.\n", errout_str());
checkConst("class A {\n"
"public:\n"
" A(){}\n"
" std::pair<std::vector<int>,double>& GetPair() {return m_pair;}\n"
"private:\n"
" std::pair<std::vector<int>,double> m_pair;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("using namespace std;"
"class A {\n"
"public:\n"
" A(){}\n"
" pair<int ,double> GetPair() {return m_pair;}\n"
"private:\n"
" pair<int ,double> m_pair;\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (style, inconclusive) Technically the member function 'A::GetPair' can be const.\n", errout_str());
checkConst("using namespace std;"
"class A {\n"
"public:\n"
" A(){}\n"
" const pair<int ,double> & GetPair() {return m_pair;}\n"
"private:\n"
" pair<int ,double> m_pair;\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (style, inconclusive) Technically the member function 'A::GetPair' can be const.\n", errout_str());
checkConst("using namespace std;"
"class A {\n"
"public:\n"
" A(){}\n"
" pair<int ,double> & GetPair() {return m_pair;}\n"
"private:\n"
" pair<int ,double> m_pair;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class A {\n"
"public:\n"
" A(){}\n"
" std::pair< int,std::vector<int> > GetPair() {return m_pair;}\n"
"private:\n"
" std::pair< int,std::vector<int> > m_pair;\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (style, inconclusive) Technically the member function 'A::GetPair' can be const.\n", errout_str());
checkConst("class A {\n"
"public:\n"
" A(){}\n"
" const std::pair< int,std::vector<int> >& GetPair() {return m_pair;}\n"
"private:\n"
" std::pair< int,std::vector<int> > m_pair;\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (style, inconclusive) Technically the member function 'A::GetPair' can be const.\n", errout_str());
checkConst("class A {\n"
"public:\n"
" A(){}\n"
" std::pair< int,std::vector<int> >& GetPair() {return m_pair;}\n"
"private:\n"
" std::pair< int,std::vector<int> > m_pair;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("using namespace std;"
"class A {\n"
"public:\n"
" A(){}\n"
" pair< vector<int>, int > GetPair() {return m_pair;}\n"
"private:\n"
" pair< vector<int>, int > m_pair;\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (style, inconclusive) Technically the member function 'A::GetPair' can be const.\n", errout_str());
checkConst("using namespace std;"
"class A {\n"
"public:\n"
" A(){}\n"
" const pair< vector<int>, int >& GetPair() {return m_pair;}\n"
"private:\n"
" pair< vector<int>, int > m_pair;\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (style, inconclusive) Technically the member function 'A::GetPair' can be const.\n", errout_str());
checkConst("using namespace std;"
"class A {\n"
"public:\n"
" A(){}\n"
" pair< vector<int>, int >& GetPair() {return m_pair;}\n"
"private:\n"
" pair< vector<int>, int > m_pair;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class A {\n"
"public:\n"
" A(){}\n"
" std::pair< std::vector<int>,std::vector<int> > GetPair() {return m_pair;}\n"
"private:\n"
" std::pair< std::vector<int>,std::vector<int> > m_pair;\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (style, inconclusive) Technically the member function 'A::GetPair' can be const.\n", errout_str());
checkConst("class A {\n"
"public:\n"
" A(){}\n"
" const std::pair< std::vector<int>,std::vector<int> >& GetPair() {return m_pair;}\n"
"private:\n"
" std::pair< std::vector<int>,std::vector<int> > m_pair;\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (style, inconclusive) Technically the member function 'A::GetPair' can be const.\n", errout_str());
checkConst("class A {\n"
"public:\n"
" A(){}\n"
" std::pair< std::vector<int>,std::vector<int> >& GetPair() {return m_pair;}\n"
"private:\n"
" std::pair< std::vector<int>,std::vector<int> > m_pair;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class A {\n"
"public:\n"
" A(){}\n"
" std::pair< std::pair < int, char > , int > GetPair() {return m_pair;}\n"
"private:\n"
" std::pair< std::pair < int, char > , int > m_pair;\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (style, inconclusive) Technically the member function 'A::GetPair' can be const.\n", errout_str());
checkConst("class A {\n"
"public:\n"
" A(){}\n"
" const std::pair< std::pair < int, char > , int > & GetPair() {return m_pair;}\n"
"private:\n"
" std::pair< std::pair < int, char > , int > m_pair;\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (style, inconclusive) Technically the member function 'A::GetPair' can be const.\n", errout_str());
checkConst("class A {\n"
"public:\n"
" A(){}\n"
" std::pair< std::pair < int, char > , int > & GetPair() {return m_pair;}\n"
"private:\n"
" std::pair< std::pair < int, char > , int > m_pair;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class A {\n"
"public:\n"
" A(){}\n"
" std::pair< int , std::pair < int, char > > GetPair() {return m_pair;}\n"
"private:\n"
" std::pair< int , std::pair < int, char > > m_pair;\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (style, inconclusive) Technically the member function 'A::GetPair' can be const.\n", errout_str());
checkConst("class A {\n"
"public:\n"
" A(){}\n"
" const std::pair< int , std::pair < int, char > >& GetPair() {return m_pair;}\n"
"private:\n"
" std::pair< int , std::pair < int, char > > m_pair;\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (style, inconclusive) Technically the member function 'A::GetPair' can be const.\n", errout_str());
checkConst("class A {\n"
"public:\n"
" A(){}\n"
" std::pair< int , std::pair < int, char > >& GetPair() {return m_pair;}\n"
"private:\n"
" std::pair< int , std::pair < int, char > > m_pair;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("using namespace std;"
"class A {\n"
"public:\n"
" A(){}\n"
" vector<int> GetVec() {return m_Vec;}\n"
"private:\n"
" vector<int> m_Vec;\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (style, inconclusive) Technically the member function 'A::GetVec' can be const.\n", errout_str());
checkConst("using namespace std;"
"class A {\n"
"public:\n"
" A(){}\n"
" const vector<int>& GetVec() {return m_Vec;}\n"
"private:\n"
" vector<int> m_Vec;\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (style, inconclusive) Technically the member function 'A::GetVec' can be const.\n", errout_str());
checkConst("using namespace std;"
"class A {\n"
"public:\n"
" A(){}\n"
" vector<int>& GetVec() {return m_Vec;}\n"
"private:\n"
" vector<int> m_Vec;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class A {\n"
"public:\n"
" int * * foo() { return &x; }\n"
"private:\n"
" const int * x;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class A {\n"
"public:\n"
" const int ** foo() { return &x; }\n"
"private:\n"
" const int * x;\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (style, inconclusive) Technically the member function 'A::foo' can be const.\n", errout_str());
}
void const15() {
checkConst("class Fred {\n"
" unsigned long long int a;\n"
" unsigned long long int getA() { return a; }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (style, inconclusive) Technically the member function 'Fred::getA' can be const.\n", errout_str());
// constructors can't be const..
checkConst("class Fred {\n"
" unsigned long long int a;\n"
"public:\n"
" Fred() { }\n"
"};");
ASSERT_EQUALS("", errout_str());
// assignment through |=..
checkConst("class Fred {\n"
" unsigned long long int a;\n"
" unsigned long long int setA() { a |= true; }\n"
"};");
ASSERT_EQUALS("", errout_str());
// static functions can't be const..
checkConst("class foo\n"
"{\n"
"public:\n"
" static unsigned long long int get()\n"
" { return 0; }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void const16() {
// ticket #1551
checkConst("class Fred {\n"
" int a;\n"
" void set(int i) { Fred::a = i; }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void const17() {
// ticket #1552
checkConst("class Fred {\n"
"public:\n"
" void set(int i, int j) { a[i].k = i; }\n"
"private:\n"
" struct { int k; } a[4];\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void const18() {
checkConst("class Fred {\n"
"static int x;\n"
"public:\n"
" void set(int i) { x = i; }\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (performance, inconclusive) Technically the member function 'Fred::set' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
}
void const19() {
// ticket #1612
checkConst("using namespace std;\n"
"class Fred {\n"
"private:\n"
" std::string s;\n"
"public:\n"
" void set(std::string ss) { s = ss; }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void const20() {
// ticket #1602
checkConst("class Fred {\n"
" int x : 3;\n"
"public:\n"
" void set(int i) { x = i; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class Fred {\n"
" list<int *> x;\n"
"public:\n"
" list<int *> get() { return x; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class Fred {\n"
" list<const int *> x;\n"
"public:\n"
" list<const int *> get() { return x; }\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (style, inconclusive) Technically the member function 'Fred::get' can be const.\n", errout_str());
checkConst("class Fred {\n"
" std::list<std::string &> x;\n"
"public:\n"
" std::list<std::string &> get() { return x; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class Fred {\n"
" std::list<const std::string &> x;\n"
"public:\n"
" std::list<const std::string &> get() { return x; }\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (style, inconclusive) Technically the member function 'Fred::get' can be const.\n", errout_str());
}
void const21() {
// ticket #1683
checkConst("class A\n"
"{\n"
"private:\n"
" const char * l1[10];\n"
"public:\n"
" A()\n"
" {\n"
" for (int i = 0 ; i < 10; l1[i] = NULL, i++);\n"
" }\n"
" void f1() { l1[0] = \"Hello\"; }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void const22() {
checkConst("class A\n"
"{\n"
"private:\n"
" B::C * v1;\n"
"public:\n"
" void f1() { v1 = 0; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class A\n"
"{\n"
"private:\n"
" B::C * v1[0];\n"
"public:\n"
" void f1() { v1[0] = 0; }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void const23() {
checkConst("class Class {\n"
"public:\n"
" typedef Template<double> Type;\n"
" typedef Template2<Type> Type2;\n"
" void set_member(Type2 m) { _m = m; }\n"
"private:\n"
" Type2 _m;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void const24() {
checkConst("class Class {\n"
"public:\n"
"void Settings::SetSetting(QString strSetting, QString strNewVal)\n"
"{\n"
" (*m_pSettings)[strSetting] = strNewVal;\n"
"}\n"
"private:\n"
" std::map<QString, QString> *m_pSettings;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void const25() { // ticket #1724
checkConst("class A{\n"
"public:\n"
"A(){m_strVal=\"\";}\n"
"std::string strGetString() const\n"
"{return m_strVal.c_str();}\n"
"const std::string strGetString1() const\n"
"{return m_strVal.c_str();}\n"
"private:\n"
"std::string m_strVal;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class A{\n"
"public:\n"
"A(){m_strVal=\"\";}\n"
"std::string strGetString()\n"
"{return m_strVal.c_str();}\n"
"private:\n"
"std::string m_strVal;\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (style, inconclusive) Technically the member function 'A::strGetString' can be const.\n", errout_str());
checkConst("class A{\n"
"public:\n"
"A(){m_strVal=\"\";}\n"
"const std::string strGetString1()\n"
"{return m_strVal.c_str();}\n"
"private:\n"
"std::string m_strVal;\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (style, inconclusive) Technically the member function 'A::strGetString1' can be const.\n", errout_str());
checkConst("class A{\n"
"public:\n"
"A(){m_strVec.push_back(\"\");}\n"
"size_t strGetSize()\n"
"{return m_strVec.size();}\n"
"private:\n"
"std::vector<std::string> m_strVec;\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (style, inconclusive) Technically the member function 'A::strGetSize' can be const.\n", errout_str());
checkConst("class A{\n"
"public:\n"
"A(){m_strVec.push_back(\"\");}\n"
"bool strGetEmpty()\n"
"{return m_strVec.empty();}\n"
"private:\n"
"std::vector<std::string> m_strVec;\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (style, inconclusive) Technically the member function 'A::strGetEmpty' can be const.\n", errout_str());
}
void const26() { // ticket #1847
checkConst("class DelayBase {\n"
"public:\n"
"void swapSpecificDelays(int index1, int index2) {\n"
" std::swap<float>(delays_[index1], delays_[index2]);\n"
"}\n"
"float delays_[4];\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("struct DelayBase {\n"
" float swapSpecificDelays(int index1) {\n"
" return delays_[index1];\n"
" }\n"
" float delays_[4];\n"
"};");
ASSERT_EQUALS("[test.cpp:2]: (style, inconclusive) Technically the member function 'DelayBase::swapSpecificDelays' can be const.\n", errout_str());
}
void const27() { // ticket #1882
checkConst("class A {\n"
"public:\n"
" A(){m_d=1.0; m_iRealVal=2.0;}\n"
" double dGetValue();\n"
"private:\n"
" double m_d;\n"
" double m_iRealVal;\n"
"};\n"
"double A::dGetValue() {\n"
" double dRet = m_iRealVal;\n"
" if( m_d != 0 )\n"
" return m_iRealVal / m_d;\n"
" return dRet;\n"
"};", nullptr, true);
ASSERT_EQUALS("[test.cpp:9] -> [test.cpp:4]: (style, inconclusive) Technically the member function 'A::dGetValue' can be const.\n", errout_str());
}
void const28() { // ticket #1883
checkConst("class P {\n"
"public:\n"
" P() { x=0.0; y=0.0; }\n"
" double x,y;\n"
"};\n"
"class A : public P {\n"
"public:\n"
" A():P(){}\n"
" void SetPos(double xPos, double yPos) {\n"
" x=xPos;\n"
" y=yPos;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class AA : public P {\n"
"public:\n"
" AA():P(){}\n"
" inline void vSetXPos(int x_)\n"
" {\n"
" UnknownScope::x = x_;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class AA {\n"
"public:\n"
" AA():P(){}\n"
" inline void vSetXPos(int x_)\n"
" {\n"
" UnknownScope::x = x_;\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (performance, inconclusive) Technically the member function 'AA::vSetXPos' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
}
void const29() { // ticket #1922
checkConst("class test {\n"
" public:\n"
" test();\n"
" const char* get() const;\n"
" char* get();\n"
" private:\n"
" char* value_;\n"
"};\n"
"test::test()\n"
"{\n"
" value_ = 0;\n"
"}\n"
"const char* test::get() const\n"
"{\n"
" return value_;\n"
"}\n"
"char* test::get()\n"
"{\n"
" return value_;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void const30() {
// check for false negatives
checkConst("class Base {\n"
"public:\n"
" int a;\n"
"};\n"
"class Derived : public Base {\n"
"public:\n"
" int get() {\n"
" return a;\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:7]: (style, inconclusive) Technically the member function 'Derived::get' can be const.\n", errout_str());
checkConst("class Base1 {\n"
"public:\n"
" int a;\n"
"};\n"
"class Base2 {\n"
"public:\n"
" int b;\n"
"};\n"
"class Derived : public Base1, public Base2 {\n"
"public:\n"
" int getA() {\n"
" return a;\n"
" }\n"
" int getB() {\n"
" return b;\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:11]: (style, inconclusive) Technically the member function 'Derived::getA' can be const.\n"
"[test.cpp:14]: (style, inconclusive) Technically the member function 'Derived::getB' can be const.\n", errout_str());
checkConst("class Base {\n"
"public:\n"
" int a;\n"
"};\n"
"class Derived1 : public Base { };\n"
"class Derived2 : public Derived1 {\n"
"public:\n"
" int get() {\n"
" return a;\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:8]: (style, inconclusive) Technically the member function 'Derived2::get' can be const.\n", errout_str());
checkConst("class Base {\n"
"public:\n"
" int a;\n"
"};\n"
"class Derived1 : public Base { };\n"
"class Derived2 : public Derived1 { };\n"
"class Derived3 : public Derived2 { };\n"
"class Derived4 : public Derived3 {\n"
"public:\n"
" int get() {\n"
" return a;\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:10]: (style, inconclusive) Technically the member function 'Derived4::get' can be const.\n", errout_str());
// check for false positives
checkConst("class Base {\n"
"public:\n"
" int a;\n"
"};\n"
"class Derived : public Base {\n"
"public:\n"
" int get() const {\n"
" return a;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class Base1 {\n"
"public:\n"
" int a;\n"
"};\n"
"class Base2 {\n"
"public:\n"
" int b;\n"
"};\n"
"class Derived : public Base1, public Base2 {\n"
"public:\n"
" int getA() const {\n"
" return a;\n"
" }\n"
" int getB() const {\n"
" return b;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class Base {\n"
"public:\n"
" int a;\n"
"};\n"
"class Derived1 : public Base { };\n"
"class Derived2 : public Derived1 {\n"
"public:\n"
" int get() const {\n"
" return a;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class Base {\n"
"public:\n"
" int a;\n"
"};\n"
"class Derived1 : public Base { };\n"
"class Derived2 : public Derived1 { };\n"
"class Derived3 : public Derived2 { };\n"
"class Derived4 : public Derived3 {\n"
"public:\n"
" int get() const {\n"
" return a;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void const31() {
checkConst("namespace std { }\n"
"class Fred {\n"
"public:\n"
" int a;\n"
" int get() { return a; }\n"
"};");
ASSERT_EQUALS("[test.cpp:5]: (style, inconclusive) Technically the member function 'Fred::get' can be const.\n", errout_str());
}
void const32() {
checkConst("class Fred {\n"
"public:\n"
" std::string a[10];\n"
" void seta() { a[0] = \"\"; }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void const33() {
checkConst("class derived : public base {\n"
"public:\n"
" void f(){}\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (performance, inconclusive) Either there is a missing 'override', or the member function 'derived::f' can be static.\n", errout_str());
}
void const34() { // ticket #1964
checkConst("class Bar {\n"
" void init(Foo * foo) {\n"
" foo.bar = this;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void const35() { // ticket #2001
checkConst("namespace N\n"
"{\n"
" class Base\n"
" {\n"
" };\n"
"}\n"
"namespace N\n"
"{\n"
" class Derived : public Base\n"
" {\n"
" public:\n"
" int getResourceName() { return var; }\n"
" int var;\n"
" };\n"
"}");
ASSERT_EQUALS("[test.cpp:12]: (style, inconclusive) Technically the member function 'N::Derived::getResourceName' can be const.\n", errout_str());
checkConst("namespace N\n"
"{\n"
" class Base\n"
" {\n"
" public:\n"
" int getResourceName();\n"
" int var;\n"
" };\n"
"}\n"
"int N::Base::getResourceName() { return var; }");
ASSERT_EQUALS("[test.cpp:10] -> [test.cpp:6]: (style, inconclusive) Technically the member function 'N::Base::getResourceName' can be const.\n", errout_str());
checkConst("namespace N\n"
"{\n"
" class Base\n"
" {\n"
" public:\n"
" int getResourceName();\n"
" int var;\n"
" };\n"
"}\n"
"namespace N\n"
"{\n"
" int Base::getResourceName() { return var; }\n"
"}");
ASSERT_EQUALS("[test.cpp:12] -> [test.cpp:6]: (style, inconclusive) Technically the member function 'N::Base::getResourceName' can be const.\n", errout_str());
checkConst("namespace N\n"
"{\n"
" class Base\n"
" {\n"
" public:\n"
" int getResourceName();\n"
" int var;\n"
" };\n"
"}\n"
"using namespace N;\n"
"int Base::getResourceName() { return var; }");
ASSERT_EQUALS("[test.cpp:11] -> [test.cpp:6]: (style, inconclusive) Technically the member function 'N::Base::getResourceName' can be const.\n", errout_str());
}
void const36() { // ticket #2003
checkConst("class Foo {\n"
"public:\n"
" Blue::Utility::Size m_MaxQueueSize;\n"
" void SetMaxQueueSize(Blue::Utility::Size a_MaxQueueSize)\n"
" {\n"
" m_MaxQueueSize = a_MaxQueueSize;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void const37() { // ticket #2081 and #2085
checkConst("class A\n"
"{\n"
"public:\n"
" A(){};\n"
" std::string operator+(const char *c)\n"
" {\n"
" return m_str+std::string(c);\n"
" }\n"
"private:\n"
" std::string m_str;\n"
"};");
ASSERT_EQUALS("[test.cpp:5]: (style, inconclusive) Technically the member function 'A::operator+' can be const.\n", errout_str());
checkConst("class Fred\n"
"{\n"
"private:\n"
" long x;\n"
"public:\n"
" Fred() {\n"
" x = 0;\n"
" }\n"
" bool isValid() {\n"
" return (x == 0x11224488);\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:9]: (style, inconclusive) Technically the member function 'Fred::isValid' can be const.\n", errout_str());
}
void const38() { // ticket #2135
checkConst("class Foo {\n"
"public:\n"
" ~Foo() { delete oArq; }\n"
" Foo(): oArq(new std::ofstream(\"...\")) {}\n"
" void MyMethod();\n"
"private:\n"
" std::ofstream *oArq;\n"
"};\n"
"void Foo::MyMethod()\n"
"{\n"
" (*oArq) << \"</table>\";\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void const39() {
checkConst("class Foo\n"
"{\n"
" int * p;\n"
"public:\n"
" Foo () : p(0) { }\n"
" int * f();\n"
" const int * f() const;\n"
"};\n"
"const int * Foo::f() const\n"
"{\n"
" return p;\n"
"}\n"
"int * Foo::f()\n"
"{\n"
" return p;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void const40() { // ticket #2228
checkConst("class SharedPtrHolder\n"
"{\n"
" private:\n"
" std::tr1::shared_ptr<int> pView;\n"
" public:\n"
" SharedPtrHolder()\n"
" { }\n"
" void SetView(const std::shared_ptr<int> & aView)\n"
" {\n"
" pView = aView;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void const41() { // ticket #2255
checkConst("class Fred\n"
"{\n"
" ::std::string m_name;\n"
"public:\n"
" void SetName(const ::std::string & name)\n"
" {\n"
" m_name = name;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class SharedPtrHolder\n"
"{\n"
" ::std::tr1::shared_ptr<int> pNum;\n"
" public :\n"
" void SetNum(const ::std::tr1::shared_ptr<int> & apNum)\n"
" {\n"
" pNum = apNum;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class SharedPtrHolder2\n"
"{\n"
" public:\n"
" typedef ::std::tr1::shared_ptr<int> IntSharedPtr;\n"
" private:\n"
" IntSharedPtr pNum;\n"
" public :\n"
" void SetNum(const IntSharedPtr & apNum)\n"
" {\n"
" pNum = apNum;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("struct IntPtrTypes\n"
"{\n"
" typedef ::std::tr1::shared_ptr<int> Shared;\n"
"};\n"
"class SharedPtrHolder3\n"
"{\n"
" private:\n"
" IntPtrTypes::Shared pNum;\n"
" public :\n"
" void SetNum(const IntPtrTypes::Shared & apNum)\n"
" {\n"
" pNum = apNum;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("template <typename T>\n"
"struct PtrTypes\n"
"{\n"
" typedef ::std::tr1::shared_ptr<T> Shared;\n"
"};\n"
"class SharedPtrHolder4\n"
"{\n"
" private:\n"
" PtrTypes<int>::Shared pNum;\n"
" public :\n"
" void SetNum(const PtrTypes<int>::Shared & apNum)\n"
" {\n"
" pNum = apNum;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void const42() { // ticket #2282
checkConst("class Fred\n"
"{\n"
"public:\n"
" struct AB { };\n"
" bool f(AB * ab);\n"
"};\n"
"bool Fred::f(Fred::AB * ab)\n"
"{\n"
"}");
ASSERT_EQUALS("[test.cpp:7] -> [test.cpp:5]: (performance, inconclusive) Technically the member function 'Fred::f' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
checkConst("class Fred\n"
"{\n"
"public:\n"
" struct AB {\n"
" struct CD { };\n"
" };\n"
" bool f(AB::CD * cd);\n"
"};\n"
"bool Fred::f(Fred::AB::CD * cd)\n"
"{\n"
"}");
ASSERT_EQUALS("[test.cpp:9] -> [test.cpp:7]: (performance, inconclusive) Technically the member function 'Fred::f' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
checkConst("namespace NS {\n"
" class Fred\n"
" {\n"
" public:\n"
" struct AB {\n"
" struct CD { };\n"
" };\n"
" bool f(AB::CD * cd);\n"
" };\n"
" bool Fred::f(Fred::AB::CD * cd)\n"
" {\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:10] -> [test.cpp:8]: (performance, inconclusive) Technically the member function 'NS::Fred::f' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
checkConst("namespace NS {\n"
" class Fred\n"
" {\n"
" public:\n"
" struct AB {\n"
" struct CD { };\n"
" };\n"
" bool f(AB::CD * cd);\n"
" };\n"
"}\n"
"bool NS::Fred::f(NS::Fred::AB::CD * cd)\n"
"{\n"
"}");
ASSERT_EQUALS("[test.cpp:11] -> [test.cpp:8]: (performance, inconclusive) Technically the member function 'NS::Fred::f' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
checkConst("class Foo {\n"
" class Fred\n"
" {\n"
" public:\n"
" struct AB {\n"
" struct CD { };\n"
" };\n"
" bool f(AB::CD * cd);\n"
" };\n"
"};\n"
"bool Foo::Fred::f(Foo::Fred::AB::CD * cd)\n"
"{\n"
"}");
ASSERT_EQUALS("[test.cpp:11] -> [test.cpp:8]: (performance, inconclusive) Technically the member function 'Foo::Fred::f' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
}
void const43() { // ticket 2377
checkConst("class A\n"
"{\n"
"public:\n"
" void foo( AA::BB::CC::DD b );\n"
" AA::BB::CC::DD a;\n"
"};\n"
"void A::foo( AA::BB::CC::DD b )\n"
"{\n"
" a = b;\n"
"}");
ASSERT_EQUALS("", errout_str());
checkConst("namespace AA\n"
"{\n"
" namespace BB\n"
" {\n"
" namespace CC\n"
" {\n"
" struct DD\n"
" {};\n"
" }\n"
" }\n"
"}\n"
"class A\n"
"{\n"
" public:\n"
"\n"
" AA::BB::CC::DD a;\n"
" void foo(AA::BB::CC::DD b)\n"
" {\n"
" a = b;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("namespace ZZ\n"
"{\n"
" namespace YY\n"
" {\n"
" struct XX\n"
" {};\n"
" }\n"
"}\n"
"class B\n"
"{\n"
" public:\n"
" ZZ::YY::XX a;\n"
" void foo(ZZ::YY::XX b)\n"
" {\n"
" a = b;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void const44() { // ticket 2595
checkConst("class A\n"
"{\n"
"public:\n"
" bool bOn;\n"
" bool foo()\n"
" {\n"
" return 0 != (bOn = bOn);\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void const45() { // ticket 2664
checkConst("namespace wraps {\n"
" class BaseLayout {};\n"
"}\n"
"namespace tools {\n"
" class WorkspaceControl :\n"
" public wraps::BaseLayout\n"
" {\n"
" int toGrid(int _value)\n"
" {\n"
" }\n"
" };\n"
"}");
ASSERT_EQUALS("[test.cpp:8]: (performance, inconclusive) Technically the member function 'tools::WorkspaceControl::toGrid' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
}
void const46() { // ticket 2663
checkConst("class Altren {\n"
"public:\n"
" int fun1() {\n"
" int a;\n"
" a++;\n"
" }\n"
" int fun2() {\n"
" b++;\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (performance, inconclusive) Technically the member function 'Altren::fun1' can be static (but you may consider moving to unnamed namespace).\n"
"[test.cpp:7]: (performance, inconclusive) Technically the member function 'Altren::fun2' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
}
void const47() { // ticket 2670
checkConst("class Altren {\n"
"public:\n"
" void foo() { delete this; }\n"
" void foo(int i) const { }\n"
" void bar() { foo(); }\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (performance, inconclusive) Technically the member function 'Altren::foo' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
checkConst("class Altren {\n"
"public:\n"
" void foo() { delete this; }\n"
" void foo(int i) const { }\n"
" void bar() { foo(1); }\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (performance, inconclusive) Technically the member function 'Altren::foo' can be static (but you may consider moving to unnamed namespace).\n"
"[test.cpp:5]: (style, inconclusive) Technically the member function 'Altren::bar' can be const.\n", errout_str());
}
void const48() { // ticket 2672
checkConst("class S0 {\n"
" class S1 {\n"
" class S2 {\n"
" class S3 {\n"
" class S4 { };\n"
" };\n"
" };\n"
" };\n"
"};\n"
"class TextIterator {\n"
" S0::S1::S2::S3::S4 mCurrent, mSave;\n"
"public:\n"
" bool setTagColour();\n"
"};\n"
"bool TextIterator::setTagColour() {\n"
" mSave = mCurrent;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void const49() { // ticket 2795
checkConst("class A {\n"
" private:\n"
" std::map<unsigned int,unsigned int> _hash;\n"
" public:\n"
" A() : _hash() {}\n"
" unsigned int fetch(unsigned int key)\n" // cannot be 'const'
" {\n"
" return _hash[key];\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void const50() { // ticket 2943
checkConst("class Altren\n"
"{\n"
" class SubClass : public std::vector<int>\n"
" {\n"
" };\n"
"};\n"
"void _setAlign()\n"
"{\n"
" if (mTileSize.height > 0) return;\n"
" if (mEmptyView) return;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void const51() { // ticket 3040
checkConst("class PSIPTable {\n"
"public:\n"
" PSIPTable() : _pesdata(0) { }\n"
" const unsigned char* pesdata() const { return _pesdata; }\n"
" unsigned char* pesdata() { return _pesdata; }\n"
" void SetSection(uint num) { pesdata()[6] = num; }\n"
"private:\n"
" unsigned char *_pesdata;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class PESPacket {\n"
"public:\n"
" PESPacket() : _pesdata(0) { }\n"
" const unsigned char* pesdata() const { return _pesdata; }\n"
" unsigned char* pesdata() { return _pesdata; }\n"
"private:\n"
" unsigned char *_pesdata;\n"
"};\n"
"class PSIPTable : public PESPacket\n"
"{\n"
"public:\n"
" void SetSection(uint num) { pesdata()[6] = num; }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void const52() { // ticket 3048
checkConst("class foo {\n"
" void DoSomething(int &a) const { a = 1; }\n"
" void DoSomethingElse() { DoSomething(bar); }\n"
"private:\n"
" int bar;\n"
"};");
ASSERT_EQUALS("[test.cpp:2]: (performance, inconclusive) Technically the member function 'foo::DoSomething' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
}
void const53() { // ticket 3049
checkConst("class A {\n"
" public:\n"
" A() : foo(false) {};\n"
" virtual bool One(bool b = false) { foo = b; return false; }\n"
" private:\n"
" bool foo;\n"
"};\n"
"class B : public A {\n"
" public:\n"
" B() {};\n"
" bool One(bool b = false) { return false; }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void const54() { // ticket 3052
checkConst("class Example {\n"
" public:\n"
" void Clear(void) { Example tmp; (*this) = tmp; }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void const55() {
checkConst("class MyObject {\n"
" int tmp;\n"
" MyObject() : tmp(0) {}\n"
"public:\n"
" void set(std::stringstream &in) { in >> tmp; }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void const56() { // ticket #3149
checkConst("class MyObject {\n"
"public:\n"
" void foo(int x) {\n"
" switch (x) { }\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (performance, inconclusive) Technically the member function 'MyObject::foo' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
checkConst("class A\n"
"{\n"
" protected:\n"
" unsigned short f (unsigned short X);\n"
" public:\n"
" A ();\n"
"};\n"
"\n"
"unsigned short A::f (unsigned short X)\n"
"{\n"
" enum ERetValues {RET_NOK = 0, RET_OK = 1};\n"
" enum ETypes {FLOAT_TYPE = 1, INT_TYPE = 2};\n"
"\n"
" try\n"
" {\n"
" switch (X)\n"
" {\n"
" case FLOAT_TYPE:\n"
" {\n"
" return RET_OK;\n"
" }\n"
" case INT_TYPE:\n"
" {\n"
" return RET_OK;\n"
" }\n"
" default:\n"
" {\n"
" return RET_NOK;\n"
" }\n"
" }\n"
" }\n"
" catch (...)\n"
" {\n"
" return RET_NOK;\n"
" }\n"
"\n"
" return RET_NOK;\n"
"}");
ASSERT_EQUALS("[test.cpp:9] -> [test.cpp:4]: (performance, inconclusive) Technically the member function 'A::f' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
checkConst("class MyObject {\n"
"public:\n"
" void foo(int x) {\n"
" for (int i = 0; i < 5; i++) { }\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (performance, inconclusive) Technically the member function 'MyObject::foo' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
}
void const57() { // tickets #2669 and #2477
checkConst("namespace MyGUI\n"
"{\n"
" namespace types\n"
" {\n"
" struct TSize {};\n"
" struct TCoord {\n"
" TSize size() const { }\n"
" };\n"
" }\n"
" typedef types::TSize IntSize;\n"
" typedef types::TCoord IntCoord;\n"
"}\n"
"class SelectorControl\n"
"{\n"
" MyGUI::IntSize getSize()\n"
" {\n"
" return mCoordValue.size();\n"
" }\n"
"private:\n"
" MyGUI::IntCoord mCoordValue;\n"
"};");
TODO_ASSERT_EQUALS("[test.cpp:7]: (performance, inconclusive) Technically the member function 'MyGUI::types::TCoord::size' can be static (but you may consider moving to unnamed namespace).\n"
"[test.cpp:15]: (style, inconclusive) Technically the member function 'SelectorControl::getSize' can be const.\n",
"[test.cpp:7]: (performance, inconclusive) Technically the member function 'MyGUI::types::TCoord::size' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
checkConst("struct Foo {\n"
" Bar b;\n"
" void foo(Foo f) {\n"
" b.run();\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("struct Bar {\n"
" int i = 0;\n"
" void run() { i++; }\n"
"};\n"
"struct Foo {\n"
" Bar b;\n"
" void foo(Foo f) {\n"
" b.run();\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("struct Bar {\n"
" void run() const { }\n"
"};\n"
"struct Foo {\n"
" Bar b;\n"
" void foo(Foo f) {\n"
" b.run();\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:2]: (performance, inconclusive) Technically the member function 'Bar::run' can be static (but you may consider moving to unnamed namespace).\n"
"[test.cpp:6]: (style, inconclusive) Technically the member function 'Foo::foo' can be const.\n", errout_str());
}
void const58() {
checkConst("struct MyObject {\n"
" void foo(Foo f) {\n"
" f.clear();\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:2]: (performance, inconclusive) Technically the member function 'MyObject::foo' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
checkConst("struct MyObject {\n"
" int foo(Foo f) {\n"
" return f.length();\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:2]: (performance, inconclusive) Technically the member function 'MyObject::foo' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
checkConst("struct MyObject {\n"
" Foo f;\n"
" int foo() {\n"
" return f.length();\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("struct MyObject {\n"
" std::string f;\n"
" int foo() {\n"
" return f.length();\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (style, inconclusive) Technically the member function 'MyObject::foo' can be const.\n", errout_str());
}
void const59() { // ticket #4646
checkConst("class C {\n"
"public:\n"
" inline void operator += (const int &x ) { re += x; }\n"
" friend inline void exp(C & c, const C & x) { }\n"
"protected:\n"
" int re;\n"
" int im;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void const60() { // ticket #3322
checkConst("class MyString {\n"
"public:\n"
" MyString() : m_ptr(0){}\n"
" MyString& operator+=( const MyString& rhs ) {\n"
" delete m_ptr;\n"
" m_ptr = new char[42];\n"
" }\n"
" MyString append( const MyString& str )\n"
" { return operator+=( str ); }\n"
" char *m_ptr;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class MyString {\n"
"public:\n"
" MyString() : m_ptr(0){}\n"
" MyString& operator+=( const MyString& rhs );\n"
" MyString append( const MyString& str )\n"
" { return operator+=( str ); }\n"
" char *m_ptr;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void const61() { // ticket #5606 - don't crash
// this code is invalid so a false negative is OK
checkConst("class MixerParticipant : public MixerParticipant {\n"
" int GetAudioFrame();\n"
"};\n"
"int MixerParticipant::GetAudioFrame() {\n"
" return 0;\n"
"}");
// this code is invalid so a false negative is OK
checkConst("class MixerParticipant : public MixerParticipant {\n"
" bool InitializeFileReader() {\n"
" printf(\"music\");\n"
" }\n"
"};");
// Based on an example from SVN source code causing an endless recursion within CheckClass::isConstMemberFunc()
// A more complete example including a template declaration like
// template<typename K> class Hash{/* ... */};
// didn't .
checkConst("template<>\n"
"class Hash<void> {\n"
"protected:\n"
" typedef Key::key_type key_type;\n"
" void set(const Key& key);\n"
"};\n"
"template<typename K, int KeySize>\n"
"class Hash : private Hash<void> {\n"
" typedef Hash<void> inherited;\n"
" void set(const Key& key) {\n"
" inherited::set(inherited::Key(key));\n"
" }\n"
"};\n", nullptr, false);
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:2]: (performance, inconclusive) Either there is a missing 'override', or the member function 'MixerParticipant::GetAudioFrame' can be static.\n",
errout_str());
}
void const62() {
checkConst("class A {\n"
" private:\n"
" std::unordered_map<unsigned int,unsigned int> _hash;\n"
" public:\n"
" A() : _hash() {}\n"
" unsigned int fetch(unsigned int key)\n" // cannot be 'const'
" {\n"
" return _hash[key];\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void const63() {
checkConst("struct A {\n"
" std::string s;\n"
" void clear() {\n"
" std::string* p = &s;\n"
" p->clear();\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("struct A {\n"
" std::string s;\n"
" void clear() {\n"
" std::string& r = s;\n"
" r.clear();\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("struct A {\n"
" std::string s;\n"
" void clear() {\n"
" std::string& r = sth; r = s;\n"
" r.clear();\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (style, inconclusive) Technically the member function 'A::clear' can be const.\n", errout_str());
checkConst("struct A {\n"
" std::string s;\n"
" void clear() {\n"
" const std::string* p = &s;\n"
" p->somefunction();\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (style, inconclusive) Technically the member function 'A::clear' can be const.\n", errout_str());
checkConst("struct A {\n"
" std::string s;\n"
" void clear() {\n"
" const std::string& r = s;\n"
" r.somefunction();\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (style, inconclusive) Technically the member function 'A::clear' can be const.\n", errout_str());
}
void const64() {
checkConst("namespace B {\n"
" namespace D {\n"
" typedef int DKIPtr;\n"
" }\n"
" class ZClass {\n"
" void set(const ::B::D::DKIPtr& p) {\n"
" membervariable = p;\n"
" }\n"
" ::B::D::DKIPtr membervariable;\n"
" };\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void const65() {
checkConst("template <typename T>\n"
"class TemplateClass {\n"
"public:\n"
" TemplateClass() { }\n"
"};\n"
"template <>\n"
"class TemplateClass<float> {\n"
"public:\n"
" TemplateClass() { }\n"
"};\n"
"int main() {\n"
" TemplateClass<int> a;\n"
" TemplateClass<float> b;\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void const66() {
checkConst("struct C {\n"
" C() : n(0) {}\n"
" void f(int v) { g((char *) &v); }\n"
" void g(char *) { n++; }\n"
" int n;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void const67() { // #9193
checkConst("template <class VALUE_T, class LIST_T = std::list<VALUE_T> >\n"
"class TestList {\n"
"public:\n"
" LIST_T m_list;\n"
"};\n"
"class Test {\n"
"public:\n"
" const std::list<std::shared_ptr<int>>& get() { return m_test.m_list; }\n"
" TestList<std::shared_ptr<int>> m_test;\n"
"};");
ASSERT_EQUALS("[test.cpp:8]: (style, inconclusive) Technically the member function 'Test::get' can be const.\n", errout_str());
}
void const68() { // #6471
checkConst("class MyClass {\n"
" void clear() {\n"
" SVecPtr v = (SVecPtr) m_data;\n"
" v->clear();\n"
" }\n"
" void* m_data;\n"
"};\n");
ASSERT_EQUALS("", errout_str());
}
void const69() { // #9806
checkConst("struct A {\n"
" int a = 0;\n"
" template <typename... Args> void call(const Args &... args) { a = 1; }\n"
" template <typename T, typename... Args> auto call(const Args &... args) -> T {\n"
" a = 2;\n"
" return T{};\n"
" }\n"
"};\n"
"\n"
"struct B : public A {\n"
" void test() {\n"
" call();\n"
" call<int>(1, 2, 3);\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void const70() {
checkConst("struct A {\n"
" template <typename... Args> void call(Args ... args) {\n"
" func(this);\n"
" }\n"
"\n"
" void test() {\n"
" call(1, 2);\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void const71() { // #10146
checkConst("struct Bar {\n"
" int j = 5;\n"
" void f(int& i) const { i += j; }\n"
"};\n"
"struct Foo {\n"
" Bar bar;\n"
" int k{};\n"
" void g() { bar.f(k); }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkConst("struct S {\n"
" A a;\n"
" void f(int j, int*& p) {\n"
" p = &(((a[j])));\n"
" }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
}
void const72() { // #10520
checkConst("struct S {\n"
" explicit S(int* p) : mp(p) {}\n"
" int* mp{};\n"
"};\n"
"struct C {\n"
" int i{};\n"
" S f() { return S{ &i }; }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkConst("struct S {\n"
" explicit S(int* p) : mp(p) {}\n"
" int* mp{};\n"
"};\n"
"struct C {\n"
" int i{};\n"
" S f() { return S(&i); }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkConst("struct S {\n"
" int* mp{};\n"
"};\n"
"struct C {\n"
" int i{};\n"
" S f() { return S{ &i }; }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkConst("struct S {\n"
" int* mp{};\n"
"};\n"
"struct C {\n"
" int i{};\n"
" S f() { return { &i }; }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkConst("struct S {\n"
" explicit S(const int* p) : mp(p) {}\n"
" const int* mp{};\n"
"};\n"
"struct C {\n"
" int i{};\n"
" S f() { return S{ &i }; }\n"
"};\n");
ASSERT_EQUALS("[test.cpp:7]: (style, inconclusive) Technically the member function 'C::f' can be const.\n", errout_str());
checkConst("struct S {\n"
" explicit S(const int* p) : mp(p) {}\n"
" const int* mp{};\n"
"};\n"
"struct C {\n"
" int i{};\n"
" S f() { return S(&i); }\n"
"};\n");
ASSERT_EQUALS("[test.cpp:7]: (style, inconclusive) Technically the member function 'C::f' can be const.\n", errout_str());
checkConst("struct S {\n"
" const int* mp{};\n"
"};\n"
"struct C {\n"
" int i{};\n"
" S f() { return S{ &i }; }\n"
"};\n");
TODO_ASSERT_EQUALS("[test.cpp:7]: (style, inconclusive) Technically the member function 'C::f' can be const.\n", "", errout_str());
checkConst("struct S {\n"
" const int* mp{};\n"
"};\n"
"struct C {\n"
" int i{};\n"
" S f() { return { &i }; }\n"
"};\n");
TODO_ASSERT_EQUALS("[test.cpp:7]: (style, inconclusive) Technically the member function 'C::f' can be const.\n", "", errout_str());
}
void const73() {
checkConst("struct A {\n"
" int* operator[](int i);\n"
" const int* operator[](int i) const;\n"
"};\n"
"struct S {\n"
" A a;\n"
" void f(int j) {\n"
" int* p = a[j];\n"
" *p = 0;\n"
" }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkConst("struct S {\n" // #10758
" T* h;\n"
" void f(); \n"
"};\n"
"void S::f() {\n"
" char* c = h->x[y];\n"
"};\n");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:3]: (style, inconclusive) Technically the member function 'S::f' can be const.\n", errout_str());
}
void const74() { // #10671
checkConst("class A {\n"
" std::vector<std::string> m_str;\n"
"public:\n"
" A() {}\n"
" void bar(void) {\n"
" for(std::vector<std::string>::const_iterator it = m_str.begin(); it != m_str.end(); ++it) {;}\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:5]: (style, inconclusive) Technically the member function 'A::bar' can be const.\n", errout_str());
// Don't crash
checkConst("struct S {\n"
" std::vector<T*> v;\n"
" void f() const;\n"
"};\n"
"void S::f() const {\n"
" for (std::vector<T*>::const_iterator it = v.begin(), end = v.end(); it != end; ++it) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void const75() { // #10065
checkConst("namespace N { int i = 0; }\n"
"struct S {\n"
" int i;\n"
" void f() {\n"
" if (N::i) {}\n"
" }\n"
"};\n");
ASSERT_EQUALS("[test.cpp:4]: (performance, inconclusive) Technically the member function 'S::f' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
checkConst("int i = 0;\n"
"struct S {\n"
" int i;\n"
" void f() {\n"
" if (::i) {}\n"
" }\n"
"};\n");
ASSERT_EQUALS("[test.cpp:4]: (performance, inconclusive) Technically the member function 'S::f' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
checkConst("namespace N {\n"
" struct S {\n"
" int i;\n"
" void f() {\n"
" if (N::S::i) {}\n"
" }\n"
" };\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (style, inconclusive) Technically the member function 'N::S::f' can be const.\n", errout_str());
}
void const76() { // #10825
checkConst("struct S {\n"
" enum E {};\n"
" void f(const T* t);\n"
" E e;\n"
"};\n"
"struct T { void e(); };\n"
"void S::f(const T* t) {\n"
" const_cast<T*>(t)->e();\n"
"};\n");
ASSERT_EQUALS("[test.cpp:7] -> [test.cpp:3]: (performance, inconclusive) Technically the member function 'S::f' can be static (but you may consider moving to unnamed namespace).\n",
errout_str());
}
void const77() {
checkConst("template <typename T>\n" // #10307
"struct S {\n"
" std::vector<T> const* f() const { return p; }\n"
" std::vector<T> const* p;\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkConst("struct S {\n" // #10311
" std::vector<const int*> v;\n"
" std::vector<const int*>& f() { return v; }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
}
void const78() { // #10315
checkConst("struct S {\n"
" typedef void(S::* F)();\n"
" void g(F f);\n"
"};\n"
"void S::g(F f) {\n"
" (this->*f)();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkConst("struct S {\n"
" using F = void(S::*)();\n"
" void g(F f);\n"
"};\n"
"void S::g(F f) {\n"
" (this->*f)();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void const79() { // #9861
checkConst("class A {\n"
"public:\n"
" char* f() {\n"
" return nullptr;\n"
" }\n"
"};\n");
ASSERT_EQUALS("[test.cpp:3]: (performance, inconclusive) Technically the member function 'A::f' can be static (but you may consider moving to unnamed namespace).\n",
errout_str());
}
void const80() { // #11328
checkConst("struct B { static void b(); };\n"
"struct S : B {\n"
" static void f() {}\n"
" void g() const;\n"
" void h();\n"
" void k();\n"
" void m();\n"
" void n();\n"
" int i;\n"
"};\n"
"void S::g() const {\n"
" this->f();\n"
"}\n"
"void S::h() {\n"
" this->f();\n"
"}\n"
"void S::k() {\n"
" if (i)\n"
" this->f();\n"
"}\n"
"void S::m() {\n"
" this->B::b();\n"
"}\n"
"void S::n() {\n"
" this->h();\n"
"}\n");
ASSERT_EQUALS("[test.cpp:11] -> [test.cpp:4]: (performance, inconclusive) Technically the member function 'S::g' can be static (but you may consider moving to unnamed namespace).\n"
"[test.cpp:14] -> [test.cpp:5]: (performance, inconclusive) Technically the member function 'S::h' can be static (but you may consider moving to unnamed namespace).\n"
"[test.cpp:17] -> [test.cpp:6]: (style, inconclusive) Technically the member function 'S::k' can be const.\n"
"[test.cpp:21] -> [test.cpp:7]: (performance, inconclusive) Technically the member function 'S::m' can be static (but you may consider moving to unnamed namespace).\n",
errout_str());
}
void const81() {
checkConst("struct A {\n" // #11330
" bool f() const;\n"
"};\n"
"struct S {\n"
" std::shared_ptr<A> a;\n"
" void g() {\n"
" if (a->f()) {}\n"
" }\n"
"};\n");
ASSERT_EQUALS("[test.cpp:6]: (style, inconclusive) Technically the member function 'S::g' can be const.\n",
errout_str());
checkConst("struct A {\n" // #11499
" void f() const;\n"
"};\n"
"template<class T>\n"
"struct P {\n"
" T* operator->();\n"
" const T* operator->() const;\n"
"};\n"
"struct S {\n"
" P<A> p;\n"
" void g() { p->f(); }\n"
"};\n");
ASSERT_EQUALS("[test.cpp:11]: (style, inconclusive) Technically the member function 'S::g' can be const.\n",
errout_str());
checkConst("struct A {\n"
" void f(int) const;\n"
"};\n"
"template<class T>\n"
"struct P {\n"
" T* operator->();\n"
" const T* operator->() const;\n"
"};\n"
"struct S {\n"
" P<A> p;\n"
" void g() { p->f(1); }\n"
"};\n");
ASSERT_EQUALS("[test.cpp:11]: (style, inconclusive) Technically the member function 'S::g' can be const.\n", errout_str());
checkConst("struct A {\n"
" void f(void*) const;\n"
"};\n"
"template<class T>\n"
"struct P {\n"
" T* operator->();\n"
" const T* operator->() const;\n"
" P<T>& operator=(P) {\n"
" return *this;\n"
" }\n"
"};\n"
"struct S {\n"
" P<A> p;\n"
" std::vector<S> g() { p->f(nullptr); return {}; }\n"
"};\n");
ASSERT_EQUALS("[test.cpp:14]: (style, inconclusive) Technically the member function 'S::g' can be const.\n", errout_str());
checkConst("struct A {\n"
" void f();\n"
"};\n"
"template<class T>\n"
"struct P {\n"
" T* operator->();\n"
" const T* operator->() const;\n"
"};\n"
"struct S {\n"
" P<A> p;\n"
" void g() { p->f(); }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkConst("struct A {\n"
" void f() const;\n"
"};\n"
"template<class T>\n"
"struct P {\n"
" T* operator->();\n"
"};\n"
"struct S {\n"
" P<A> p;\n"
" void g() { p->f(); }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkConst("struct A {\n"
" void f(int&) const;\n"
"};\n"
"template<class T>\n"
"struct P {\n"
" T* operator->();\n"
" const T* operator->() const;\n"
"};\n"
"struct S {\n"
" P<A> p;\n"
" int i;\n"
" void g() { p->f(i); }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkConst("struct A {\n" // #11501
" enum E { E1 };\n"
" virtual void f(E) const = 0;\n"
"};\n"
"struct F {\n"
" A* a;\n"
" void g() { a->f(A::E1); }\n"
"};\n");
ASSERT_EQUALS("[test.cpp:7]: (style, inconclusive) Technically the member function 'F::g' can be const.\n", errout_str());
}
void const82() { // #11513
checkConst("struct S {\n"
" int i;\n"
" void h(bool) const;\n"
" void g() { h(i == 1); }\n"
"};\n");
ASSERT_EQUALS("[test.cpp:4]: (style, inconclusive) Technically the member function 'S::g' can be const.\n",
errout_str());
checkConst("struct S {\n"
" int i;\n"
" void h(int, int*) const;\n"
" void g() { int a; h(i, &a); }\n"
"};\n");
ASSERT_EQUALS("[test.cpp:4]: (style, inconclusive) Technically the member function 'S::g' can be const.\n",
errout_str());
}
void const83() {
checkConst("struct S {\n"
" int i1, i2;\n"
" void f(bool b);\n"
" void g(bool b, int j);\n"
"};\n"
"void S::f(bool b) {\n"
" int& r = b ? i1 : i2;\n"
" r = 5;\n"
"}\n"
"void S::g(bool b, int j) {\n"
" int& r = b ? j : i2;\n"
" r = 5;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void const84() {
checkConst("class S {};\n" // #11616
"struct T {\n"
" T(const S*);\n"
" T(const S&);\n"
"};\n"
"struct C {\n"
" const S s;\n"
" void f1() {\n"
" T t(&s);\n"
" }\n"
" void f2() {\n"
" T t(s);\n"
" }\n"
"};\n");
ASSERT_EQUALS("[test.cpp:8]: (style, inconclusive) Technically the member function 'C::f1' can be const.\n"
"[test.cpp:11]: (style, inconclusive) Technically the member function 'C::f2' can be const.\n",
errout_str());
}
void const85() { // #11618
checkConst("struct S {\n"
" int a[2], b[2];\n"
" void f() { f(a, b); }\n"
" static void f(const int p[2], int q[2]);\n"
"};\n"
"void S::f(const int p[2], int q[2]) {\n"
" q[0] = p[0];\n"
" q[1] = p[1];\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void const86() { // #11621
checkConst("struct S { int* p; };\n"
"struct T { int m; int* p; };\n"
"struct U {\n"
" int i;\n"
" void f() { S s = { &i }; }\n"
" void g() { int* a[] = { &i }; }\n"
" void h() { T t = { 1, &i }; }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void const87() {
checkConst("struct Tokenizer {\n" // #11720
" bool isCPP() const {\n"
" return cpp;\n"
" }\n"
" bool cpp;\n"
"};\n"
"struct Check {\n"
" const Tokenizer* const mTokenizer;\n"
" const int* const mSettings;\n"
"};\n"
"struct CheckA : Check {\n"
" static bool test(const std::string& funcname, const int* settings, bool cpp);\n"
"};\n"
"struct CheckB : Check {\n"
" bool f(const std::string& s);\n"
"};\n"
"bool CheckA::test(const std::string& funcname, const int* settings, bool cpp) {\n"
" return !funcname.empty() && settings && cpp;\n"
"}\n"
"bool CheckB::f(const std::string& s) {\n"
" return CheckA::test(s, mSettings, mTokenizer->isCPP());\n"
"}\n");
ASSERT_EQUALS("[test.cpp:20] -> [test.cpp:15]: (style, inconclusive) Technically the member function 'CheckB::f' can be const.\n", errout_str());
checkConst("void g(int&);\n"
"struct S {\n"
" struct { int i; } a[1];\n"
" void f() { g(a[0].i); }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkConst("struct S {\n"
" const int& g() const { return i; }\n"
" int i;\n"
"};\n"
"void h(int, const int&);\n"
"struct T {\n"
" S s;\n"
" int j;\n"
" void f() { h(j, s.g()); }\n"
"};\n");
ASSERT_EQUALS("[test.cpp:9]: (style, inconclusive) Technically the member function 'T::f' can be const.\n", errout_str());
checkConst("struct S {\n"
" int& g() { return i; }\n"
" int i;\n"
"};\n"
"void h(int, int&);\n"
"struct T {\n"
" S s;\n"
" int j;\n"
" void f() { h(j, s.g()); }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkConst("struct S {\n"
" const int& g() const { return i; }\n"
" int i;\n"
"};\n"
"void h(int, const int*);\n"
"struct T {\n"
" S s;\n"
" int j;\n"
" void f() { h(j, &s.g()); }\n"
"};\n");
ASSERT_EQUALS("[test.cpp:9]: (style, inconclusive) Technically the member function 'T::f' can be const.\n", errout_str());
checkConst("struct S {\n"
" int& g() { return i; }\n"
" int i;\n"
"};\n"
"void h(int, int*);\n"
"struct T {\n"
" S s;\n"
" int j;\n"
" void f() { h(j, &s.g()); }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkConst("void j(int** x);\n"
"void k(int* const* y);\n"
"struct S {\n"
" int* p;\n"
" int** q;\n"
" int* const* r;\n"
" void f1() { j(&p); }\n"
" void f2() { j(q); }\n"
" void g1() { k(&p); }\n"
" void g2() { k(q); }\n"
" void g3() { k(r); }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkConst("void m(int*& r);\n"
"void n(int* const& s);\n"
"struct T {\n"
" int i;\n"
" int* p;\n"
" void f1() { m(p); }\n"
" void f2() { n(&i); }\n"
" void f3() { n(p); }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
}
void const88() { // #11626
checkConst("struct S {\n"
" bool f() { return static_cast<bool>(p); }\n"
" const int* g() { return const_cast<const int*>(p); }\n"
" const int* h() { return (const int*)p; }\n"
" char* j() { return reinterpret_cast<char*>(p); }\n"
" char* k() { return (char*)p; }\n"
" int* p;\n"
"};\n");
ASSERT_EQUALS("[test.cpp:2]: (style, inconclusive) Technically the member function 'S::f' can be const.\n"
"[test.cpp:3]: (style, inconclusive) Technically the member function 'S::g' can be const.\n"
"[test.cpp:4]: (style, inconclusive) Technically the member function 'S::h' can be const.\n",
errout_str());
checkConst("struct S {\n"
" bool f() { return p != nullptr; }\n"
" std::shared_ptr<int> p;\n"
"};\n");
ASSERT_EQUALS("[test.cpp:2]: (style, inconclusive) Technically the member function 'S::f' can be const.\n",
errout_str());
}
void const89() {
checkConst("struct S {\n" // #11654
" void f(bool b);\n"
" int i;\n"
"};\n"
"void S::f(bool b) {\n"
" if (i && b)\n"
" f(false);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:2]: (style, inconclusive) Technically the member function 'S::f' can be const.\n", errout_str());
checkConst("struct S {\n"
" void f(int& r);\n"
" int i;\n"
"};\n"
"void S::f(int& r) {\n"
" r = 0;\n"
" if (i)\n"
" f(i);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkConst("struct S {\n" // #11744
" S* p;\n"
" int f() {\n"
" if (p)\n"
" return 1 + p->f();\n"
" return 1;\n"
" }\n"
" int g(int i) {\n"
" if (i > 0)\n"
" return i + g(i - 1);\n"
" return 0;\n"
" }\n"
"};\n");
ASSERT_EQUALS("[test.cpp:3]: (style, inconclusive) Technically the member function 'S::f' can be const.\n"
"[test.cpp:8]: (performance, inconclusive) Technically the member function 'S::g' can be static (but you may consider moving to unnamed namespace).\n",
errout_str());
checkConst("class C {\n" // #11653
"public:\n"
" void f(bool b) const;\n"
"};\n"
"void C::f(bool b) const {\n"
" if (b)\n"
" f(false);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:3]: (performance, inconclusive) Technically the member function 'C::f' can be static (but you may consider moving to unnamed namespace).\n",
errout_str());
}
void const90() { // #11637
checkConst("class S {};\n"
"struct C {\n"
" C(const S*);\n"
" C(const S&);\n"
"};\n"
"class T {\n"
" S s;\n"
" void f1() { C c = C{ &s }; }\n"
" void f2() { C c = C{ s }; }\n"
"};\n");
ASSERT_EQUALS("[test.cpp:8]: (style, inconclusive) Technically the member function 'T::f1' can be const.\n"
"[test.cpp:9]: (style, inconclusive) Technically the member function 'T::f2' can be const.\n",
errout_str());
}
void const91() { // #11790
checkConst("struct S {\n"
" char* p;\n"
" template <typename T>\n"
" T* get() {\n"
" return reinterpret_cast<T*>(p);\n"
" }\n"
"};\n"
"const int* f(S& s) {\n"
" return s.get<const int>();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void const92() { // #11886
checkConst("void g(int);\n"
"template<int n>\n"
"struct S : public S<n - 1> {\n"
" void f() {\n"
" g(n - 1);\n"
" }\n"
"};\n"
"template<>\n"
"struct S<0> {};\n"
"struct D : S<150> {};\n");
// don't hang
}
void const93() { // #12162
checkConst("struct S {\n"
" bool f() {\n"
" return m.cbegin()->first == 0;\n"
" }\n"
" bool g() {\n"
" return m.count(0);\n"
" }\n"
" std::map<int, int> m;\n"
"};\n");
ASSERT_EQUALS("[test.cpp:2]: (style, inconclusive) Technically the member function 'S::f' can be const.\n"
"[test.cpp:5]: (style, inconclusive) Technically the member function 'S::g' can be const.\n",
errout_str());
}
void const94() { // #7459
checkConst("class A {\n"
"public:\n"
" A() : tickFunction(&A::nop) {}\n"
" void tick() { (this->*tickFunction)(); }\n"
"private:\n"
" typedef void (A::* Fn)();\n"
" Fn tickFunction;\n"
" void nop() {}\n"
"};\n");
ASSERT_EQUALS("", errout_str());
}
void const95() { // #13320
checkConst("class C {\n"
" std::string x;\n"
" std::string get() && { return x; }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
}
void const96() {
checkConst("struct S : B {\n" // #13282
" bool f() { return b; }\n"
" bool g() override { return b; }\n"
" bool b;\n"
"};\n");
ASSERT_EQUALS("[test.cpp:2]: (style, inconclusive) Either there is a missing 'override', or the member function 'S::f' can be const.\n", errout_str());
checkConst("struct B;\n" // #13382
"struct S : B {\n"
" void f();\n"
"};\n"
"void S::f() {\n"
" B::g(0);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void const97() { // #13301
checkConst("struct S {\n"
" std::vector<int> v;\n"
" int f() {\n"
" const int& r = v.front();\n"
" return r;\n"
" }\n"
" int g() {\n"
" const int& r = v.at(0);\n"
" return r;\n"
" }\n"
" void h() {\n"
" if (v.front() == 0) {}\n"
" if (1 == v.front()) {}\n"
" }\n"
" void i() {\n"
" v.at(0) = 0;\n"
" }\n"
" void j() {\n"
" dostuff(1, v.at(0));\n"
" }\n"
" void k() {\n"
" int& r = v.front();\n"
" r = 0;\n"
" }\n"
"};\n");
ASSERT_EQUALS("[test.cpp:3]: (style, inconclusive) Technically the member function 'S::f' can be const.\n"
"[test.cpp:7]: (style, inconclusive) Technically the member function 'S::g' can be const.\n"
"[test.cpp:11]: (style, inconclusive) Technically the member function 'S::h' can be const.\n",
errout_str());
checkConst("struct B { std::string s; };\n"
"struct D : B {\n"
" bool f(std::string::iterator it) { return it == B::s.begin(); }\n"
"};\n");
ASSERT_EQUALS("[test.cpp:3]: (style, inconclusive) Technically the member function 'D::f' can be const.\n",
errout_str());
}
void const_handleDefaultParameters() {
checkConst("struct Foo {\n"
" void foo1(int i, int j = 0) {\n"
" return func(this);\n"
" }\n"
" int bar1() {\n"
" return foo1(1);\n"
" }\n"
" int bar2() {\n"
" return foo1(1, 2);\n"
" }\n"
" int bar3() {\n"
" return foo1(1, 2, 3);\n"
" }\n"
" int bar4() {\n"
" return foo1();\n"
" }\n"
" void foo2(int i = 0) {\n"
" return func(this);\n"
" }\n"
" int bar5() {\n"
" return foo2();\n"
" }\n"
" void foo3() {\n"
" return func(this);\n"
" }\n"
" int bar6() {\n"
" return foo3();\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:11]: (performance, inconclusive) Technically the member function 'Foo::bar3' can be static (but you may consider moving to unnamed namespace).\n"
"[test.cpp:14]: (performance, inconclusive) Technically the member function 'Foo::bar4' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
}
void const_passThisToMemberOfOtherClass() {
checkConst("struct Foo {\n"
" void foo() {\n"
" Bar b;\n"
" b.takeFoo(this);\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("struct Foo {\n"
" void foo() {\n"
" Foo f;\n"
" f.foo();\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:2]: (performance, inconclusive) Technically the member function 'Foo::foo' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
checkConst("struct A;\n" // #5839 - operator()
"struct B {\n"
" void operator()(A *a);\n"
"};\n"
"struct A {\n"
" void dostuff() {\n"
" B()(this);\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void assigningPointerToPointerIsNotAConstOperation() {
checkConst("struct s\n"
"{\n"
" int** v;\n"
" void f()\n"
" {\n"
" v = 0;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void assigningArrayElementIsNotAConstOperation() {
checkConst("struct s\n"
"{\n"
" ::std::string v[3];\n"
" void f()\n"
" {\n"
" v[0] = \"Happy new year!\";\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
// increment/decrement => not const
void constincdec() {
checkConst("class Fred {\n"
" int a;\n"
" void nextA() { return ++a; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class Fred {\n"
" int a;\n"
" void nextA() { return --a; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class Fred {\n"
" int a;\n"
" void nextA() { return a++; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class Fred {\n"
" int a;\n"
" void nextA() { return a--; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("int a;\n"
"class Fred {\n"
" void nextA() { return ++a; }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (performance, inconclusive) Technically the member function 'Fred::nextA' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
checkConst("int a;\n"
"class Fred {\n"
" void nextA() { return --a; }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (performance, inconclusive) Technically the member function 'Fred::nextA' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
checkConst("int a;\n"
"class Fred {\n"
" void nextA() { return a++; }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (performance, inconclusive) Technically the member function 'Fred::nextA' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
checkConst("int a;\n"
"class Fred {\n"
" void nextA() { return a--; }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (performance, inconclusive) Technically the member function 'Fred::nextA' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
checkConst("struct S {\n" // #10077
" int i{};\n"
" S& operator ++() { ++i; return *this; }\n"
" S operator ++(int) { S s = *this; ++(*this); return s; }\n"
" void f() { (*this)--; }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
}
void constassign1() {
checkConst("class Fred {\n"
" int a;\n"
" void nextA() { return a=1; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class Fred {\n"
" int a;\n"
" void nextA() { return a-=1; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class Fred {\n"
" int a;\n"
" void nextA() { return a+=1; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class Fred {\n"
" int a;\n"
" void nextA() { return a*=-1; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class Fred {\n"
" int a;\n"
" void nextA() { return a/=-2; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("int a;\n"
"class Fred {\n"
" void nextA() { return a=1; }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (performance, inconclusive) Technically the member function 'Fred::nextA' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
checkConst("int a;\n"
"class Fred {\n"
" void nextA() { return a-=1; }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (performance, inconclusive) Technically the member function 'Fred::nextA' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
checkConst("int a;\n"
"class Fred {\n"
" void nextA() { return a+=1; }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (performance, inconclusive) Technically the member function 'Fred::nextA' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
checkConst("int a;\n"
"class Fred {\n"
" void nextA() { return a*=-1; }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (performance, inconclusive) Technically the member function 'Fred::nextA' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
checkConst("int a;\n"
"class Fred {\n"
" void nextA() { return a/=-2; }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (performance, inconclusive) Technically the member function 'Fred::nextA' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
}
void constassign2() {
checkConst("class Fred {\n"
" struct A { int a; } s;\n"
" void nextA() { return s.a=1; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class Fred {\n"
" struct A { int a; } s;\n"
" void nextA() { return s.a-=1; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class Fred {\n"
" struct A { int a; } s;\n"
" void nextA() { return s.a+=1; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class Fred {\n"
" struct A { int a; } s;\n"
" void nextA() { return s.a*=-1; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("struct A { int a; } s;\n"
"class Fred {\n"
" void nextA() { return s.a=1; }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (performance, inconclusive) Technically the member function 'Fred::nextA' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
checkConst("struct A { int a; } s;\n"
"class Fred {\n"
" void nextA() { return s.a-=1; }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (performance, inconclusive) Technically the member function 'Fred::nextA' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
checkConst("struct A { int a; } s;\n"
"class Fred {\n"
" void nextA() { return s.a+=1; }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (performance, inconclusive) Technically the member function 'Fred::nextA' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
checkConst("struct A { int a; } s;\n"
"class Fred {\n"
" void nextA() { return s.a*=-1; }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (performance, inconclusive) Technically the member function 'Fred::nextA' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
checkConst("struct A { int a; } s;\n"
"class Fred {\n"
" void nextA() { return s.a/=-2; }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (performance, inconclusive) Technically the member function 'Fred::nextA' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
checkConst("struct A { int a; };\n"
"class Fred {\n"
" A s;\n"
" void nextA() { return s.a=1; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("struct A { int a; };\n"
"class Fred {\n"
" A s;\n"
" void nextA() { return s.a-=1; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("struct A { int a; };\n"
"class Fred {\n"
" A s;\n"
" void nextA() { return s.a+=1; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("struct A { int a; };\n"
"class Fred {\n"
" A s;\n"
" void nextA() { return s.a*=-1; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("struct A { int a; };\n"
"class Fred {\n"
" A s;\n"
" void nextA() { return s.a/=-2; }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
// increment/decrement array element => not const
void constincdecarray() {
checkConst("class Fred {\n"
" int a[2];\n"
" void nextA() { return ++a[0]; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class Fred {\n"
" int a[2];\n"
" void nextA() { return --a[0]; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class Fred {\n"
" int a[2];\n"
" void nextA() { return a[0]++; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class Fred {\n"
" int a[2];\n"
" void nextA() { return a[0]--; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("int a[2];\n"
"class Fred {\n"
" void nextA() { return ++a[0]; }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (performance, inconclusive) Technically the member function 'Fred::nextA' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
checkConst("int a[2];\n"
"class Fred {\n"
" void nextA() { return --a[0]; }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (performance, inconclusive) Technically the member function 'Fred::nextA' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
checkConst("int a[2];\n"
"class Fred {\n"
" void nextA() { return a[0]++; }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (performance, inconclusive) Technically the member function 'Fred::nextA' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
checkConst("int a[2];\n"
"class Fred {\n"
" void nextA() { return a[0]--; }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (performance, inconclusive) Technically the member function 'Fred::nextA' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
}
void constassignarray() {
checkConst("class Fred {\n"
" int a[2];\n"
" void nextA() { return a[0]=1; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class Fred {\n"
" int a[2];\n"
" void nextA() { return a[0]-=1; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class Fred {\n"
" int a[2];\n"
" void nextA() { return a[0]+=1; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class Fred {\n"
" int a[2];\n"
" void nextA() { return a[0]*=-1; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class Fred {\n"
" int a[2];\n"
" void nextA() { return a[0]/=-2; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("int a[2];\n"
"class Fred {\n"
" void nextA() { return a[0]=1; }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (performance, inconclusive) Technically the member function 'Fred::nextA' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
checkConst("int a[2];\n"
"class Fred {\n"
" void nextA() { return a[0]-=1; }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (performance, inconclusive) Technically the member function 'Fred::nextA' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
checkConst("int a[2];\n"
"class Fred {\n"
" void nextA() { return a[0]+=1; }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (performance, inconclusive) Technically the member function 'Fred::nextA' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
checkConst("int a[2];\n"
"class Fred {\n"
" void nextA() { return a[0]*=-1; }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (performance, inconclusive) Technically the member function 'Fred::nextA' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
checkConst("int a[2];\n"
"class Fred {\n"
" void nextA() { return a[0]/=-2; }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (performance, inconclusive) Technically the member function 'Fred::nextA' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
}
// return pointer/reference => not const
void constReturnReference() {
checkConst("class Fred {\n"
" int a;\n"
" int &getR() { return a; }\n"
" int *getP() { return &a; }"
"};");
ASSERT_EQUALS("", errout_str());
}
// delete member variable => not const (but technically it can, it compiles without errors)
void constDelete() {
checkConst("class Fred {\n"
" int *a;\n"
" void clean() { delete a; }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
// A function that returns unknown types can't be const (#1579)
void constLPVOID() {
checkConst("class Fred {\n"
" UNKNOWN a() { return 0; };\n"
"};");
TODO_ASSERT_EQUALS("[test.cpp:2]: (performance, inconclusive) Technically the member function 'Fred::a' can be static.\n", "", errout_str());
// #1579 - HDC
checkConst("class Fred {\n"
" foo bar;\n"
" UNKNOWN a() { return b; };\n"
"};");
ASSERT_EQUALS("", errout_str());
}
// a function that calls const functions can be const
void constFunc() {
checkConst("class Fred {\n"
" void f() const { };\n"
" void a() { f(); };\n"
"};");
ASSERT_EQUALS("[test.cpp:2]: (performance, inconclusive) Technically the member function 'Fred::f' can be static (but you may consider moving to unnamed namespace).\n"
"[test.cpp:3]: (style, inconclusive) Technically the member function 'Fred::a' can be const.\n", errout_str());
// ticket #1593
checkConst("class A\n"
"{\n"
" std::vector<int> m_v;\n"
"public:\n"
" A(){}\n"
" unsigned int GetVecSize() {return m_v.size();}\n"
"};");
ASSERT_EQUALS("[test.cpp:6]: (style, inconclusive) Technically the member function 'A::GetVecSize' can be const.\n", errout_str());
checkConst("class A\n"
"{\n"
" std::vector<int> m_v;\n"
"public:\n"
" A(){}\n"
" bool GetVecEmpty() {return m_v.empty();}\n"
"};");
ASSERT_EQUALS("[test.cpp:6]: (style, inconclusive) Technically the member function 'A::GetVecEmpty' can be const.\n", errout_str());
}
void constVirtualFunc() {
// base class has no virtual function
checkConst("class A { };\n"
"class B : public A {\n"
" int b;\n"
"public:\n"
" B() : b(0) { }\n"
" int func() { return b; }\n"
"};");
ASSERT_EQUALS("[test.cpp:6]: (style, inconclusive) Technically the member function 'B::func' can be const.\n", errout_str());
checkConst("class A { };\n"
"class B : public A {\n"
" int b;\n"
"public:\n"
" B() : b(0) { }\n"
" int func();\n"
"};\n"
"int B::func() { return b; }");
ASSERT_EQUALS("[test.cpp:8] -> [test.cpp:6]: (style, inconclusive) Technically the member function 'B::func' can be const.\n", errout_str());
// base class has no virtual function
checkConst("class A {\n"
"public:\n"
" int func();\n"
"};\n"
"class B : public A {\n"
" int b;\n"
"public:\n"
" B() : b(0) { }\n"
" int func() { return b; }\n"
"};");
ASSERT_EQUALS("[test.cpp:9]: (style, inconclusive) Technically the member function 'B::func' can be const.\n", errout_str());
checkConst("class A {\n"
"public:\n"
" int func();\n"
"};\n"
"class B : public A {\n"
" int b;\n"
"public:\n"
" B() : b(0) { }\n"
" int func();\n"
"};\n"
"int B::func() { return b; }");
ASSERT_EQUALS("[test.cpp:11] -> [test.cpp:9]: (style, inconclusive) Technically the member function 'B::func' can be const.\n", errout_str());
// base class has virtual function
checkConst("class A {\n"
"public:\n"
" virtual int func();\n"
"};\n"
"class B : public A {\n"
" int b;\n"
"public:\n"
" B() : b(0) { }\n"
" int func() { return b; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class A {\n"
"public:\n"
" virtual int func();\n"
"};\n"
"class B : public A {\n"
" int b;\n"
"public:\n"
" B() : b(0) { }\n"
" int func();\n"
"};\n"
"int B::func() { return b; }");
ASSERT_EQUALS("", errout_str());
checkConst("class A {\n"
"public:\n"
" virtual int func() = 0;\n"
"};\n"
"class B : public A {\n"
" int b;\n"
"public:\n"
" B() : b(0) { }\n"
" int func();\n"
"};\n"
"int B::func() { return b; }");
ASSERT_EQUALS("", errout_str());
// base class has no virtual function
checkConst("class A {\n"
" int a;\n"
"public:\n"
" A() : a(0) { }\n"
" int func() { return a; }\n"
"};\n"
"class B : public A {\n"
" int b;\n"
"public:\n"
" B() : b(0) { }\n"
" int func() { return b; }\n"
"};\n"
"class C : public B {\n"
" int c;\n"
"public:\n"
" C() : c(0) { }\n"
" int func() { return c; }\n"
"};");
ASSERT_EQUALS("[test.cpp:5]: (style, inconclusive) Technically the member function 'A::func' can be const.\n"
"[test.cpp:11]: (style, inconclusive) Technically the member function 'B::func' can be const.\n"
"[test.cpp:17]: (style, inconclusive) Technically the member function 'C::func' can be const.\n", errout_str());
checkConst("class A {\n"
" int a;\n"
"public:\n"
" A() : a(0) { }\n"
" int func();\n"
"};\n"
"int A::func() { return a; }\n"
"class B : public A {\n"
" int b;\n"
"public:\n"
" B() : b(0) { }\n"
" int func();\n"
"};\n"
"int B::func() { return b; }\n"
"class C : public B {\n"
" int c;\n"
"public:\n"
" C() : c(0) { }\n"
" int func();\n"
"};\n"
"int C::func() { return c; }");
ASSERT_EQUALS("[test.cpp:7] -> [test.cpp:5]: (style, inconclusive) Technically the member function 'A::func' can be const.\n"
"[test.cpp:14] -> [test.cpp:12]: (style, inconclusive) Technically the member function 'B::func' can be const.\n"
"[test.cpp:21] -> [test.cpp:19]: (style, inconclusive) Technically the member function 'C::func' can be const.\n", errout_str());
// base class has virtual function
checkConst("class A {\n"
" int a;\n"
"public:\n"
" A() : a(0) { }\n"
" virtual int func() { return a; }\n"
"};\n"
"class B : public A {\n"
" int b;\n"
"public:\n"
" B() : b(0) { }\n"
" int func() { return b; }\n"
"};\n"
"class C : public B {\n"
" int c;\n"
"public:\n"
" C() : c(0) { }\n"
" int func() { return c; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkConst("class A {\n"
" int a;\n"
"public:\n"
" A() : a(0) { }\n"
" virtual int func();\n"
"};\n"
"int A::func() { return a; }\n"
"class B : public A {\n"
" int b;\n"
"public:\n"
" B() : b(0) { }\n"
" int func();\n"
"};\n"
"int B::func() { return b; }\n"
"class C : public B {\n"
" int c;\n"
"public:\n"
" C() : c(0) { }\n"
" int func();\n"
"};\n"
"int C::func() { return c; }");
ASSERT_EQUALS("", errout_str());
// ticket #1311
checkConst("class X {\n"
" int x;\n"
"public:\n"
" X(int x) : x(x) { }\n"
" int getX() { return x; }\n"
"};\n"
"class Y : public X {\n"
" int y;\n"
"public:\n"
" Y(int x, int y) : X(x), y(y) { }\n"
" int getY() { return y; }\n"
"};\n"
"class Z : public Y {\n"
" int z;\n"
"public:\n"
" Z(int x, int y, int z) : Y(x, y), z(z) { }\n"
" int getZ() { return z; }\n"
"};");
ASSERT_EQUALS("[test.cpp:5]: (style, inconclusive) Technically the member function 'X::getX' can be const.\n"
"[test.cpp:11]: (style, inconclusive) Technically the member function 'Y::getY' can be const.\n"
"[test.cpp:17]: (style, inconclusive) Technically the member function 'Z::getZ' can be const.\n", errout_str());
checkConst("class X {\n"
" int x;\n"
"public:\n"
" X(int x) : x(x) { }\n"
" int getX();\n"
"};\n"
"int X::getX() { return x; }\n"
"class Y : public X {\n"
" int y;\n"
"public:\n"
" Y(int x, int y) : X(x), y(y) { }\n"
" int getY();\n"
"};\n"
"int Y::getY() { return y; }\n"
"class Z : public Y {\n"
" int z;\n"
"public:\n"
" Z(int x, int y, int z) : Y(x, y), z(z) { }\n"
" int getZ();\n"
"};\n"
"int Z::getZ() { return z; }");
ASSERT_EQUALS("[test.cpp:7] -> [test.cpp:5]: (style, inconclusive) Technically the member function 'X::getX' can be const.\n"
"[test.cpp:14] -> [test.cpp:12]: (style, inconclusive) Technically the member function 'Y::getY' can be const.\n"
"[test.cpp:21] -> [test.cpp:19]: (style, inconclusive) Technically the member function 'Z::getZ' can be const.\n", errout_str());
}
void constIfCfg() {
const char code[] = "struct foo {\n"
" int i;\n"
" void f() {\n"
//"#ifdef ABC\n"
//" i = 4;\n"
//"endif\n"
" }\n"
"};";
checkConst(code, &settings0, true);
ASSERT_EQUALS("[test.cpp:3]: (performance, inconclusive) Technically the member function 'foo::f' can be static (but you may consider moving to unnamed namespace).\n", errout_str());
checkConst(code, &settings0, false); // TODO: Set inconclusive to true (preprocess it)
ASSERT_EQUALS("", errout_str());
}
void constFriend() { // ticket #1921
const char code[] = "class foo {\n"
" friend void f() { }\n"
"};";
checkConst(code);
ASSERT_EQUALS("", errout_str());
}
void constUnion() { // ticket #2111
checkConst("class foo {\n"
"public:\n"
" union {\n"
" int i;\n"
" float f;\n"
" } d;\n"
" void setf(float x) {\n"
" d.f = x;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void constArrayOperator() {
checkConst("struct foo {\n"
" int x;\n"
" int y[5][724];\n"
" T a() {\n"
" return y[x++][6];\n"
" }\n"
" T b() {\n"
" return y[1][++x];\n"
" }\n"
" T c() {\n"
" return y[1][6];\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:10]: (style, inconclusive) Technically the member function 'foo::c' can be const.\n", errout_str());
}
void constRangeBasedFor() { // #5514
checkConst("class Fred {\n"
" int array[256];\n"
"public:\n"
" void f1() {\n"
" for (auto & e : array)\n"
" foo(e);\n"
" }\n"
" void f2() {\n"
" for (const auto & e : array)\n"
" foo(e);\n"
" }\n"
" void f3() {\n"
" for (decltype(auto) e : array)\n"
" foo(e);\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:8]: (style, inconclusive) Technically the member function 'Fred::f2' can be const.\n", errout_str());
}
void const_shared_ptr() { // #8674
checkConst("class Fred {\n"
"public:\n"
" std::shared_ptr<Data> getData();\n"
"private:\n"
" std::shared_ptr<Data> data;\n"
"};\n"
"\n"
"std::shared_ptr<Data> Fred::getData() { return data; }");
ASSERT_EQUALS("", errout_str());
}
void constPtrToConstPtr() {
checkConst("class Fred {\n"
"public:\n"
" const char *const *data;\n"
" const char *const *getData() { return data; }\n}");
ASSERT_EQUALS("[test.cpp:4]: (style, inconclusive) Technically the member function 'Fred::getData' can be const.\n", errout_str());
}
void constTrailingReturnType() { // #9814
checkConst("struct A {\n"
" int x = 1;\n"
" auto get() -> int & { return x; }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void constRefQualified() { // #12920
checkConst("class Fred {\n"
"public:\n"
" const Data& get() & { return data; }\n"
"private:\n"
" Data data;\n"
"};\n");
ASSERT_EQUALS("", errout_str());
}
void staticArrayPtrOverload() {
checkConst("struct S {\n"
" template<size_t N>\n"
" void f(const std::array<std::string_view, N>& sv);\n"
" template<long N>\n"
" void f(const char* const (&StrArr)[N]);\n"
"};\n"
"template<size_t N>\n"
"void S::f(const std::array<std::string_view, N>& sv) {\n"
" const char* ptrs[N]{};\n"
" return f(ptrs);\n"
"}\n"
"template void S::f(const std::array<std::string_view, 3>& sv);\n");
ASSERT_EQUALS("", errout_str());
}
void qualifiedNameMember() { // #10872
const Settings s = settingsBuilder().severity(Severity::style).debugwarnings().library("std.cfg").build();
checkConst("struct data {};\n"
" struct S {\n"
" std::vector<data> std;\n"
" void f();\n"
"};\n"
"void S::f() {\n"
" std::vector<data>::const_iterator end = std.end();\n"
"}\n", &s);
ASSERT_EQUALS("[test.cpp:6] -> [test.cpp:4]: (style, inconclusive) Technically the member function 'S::f' can be const.\n", errout_str());
}
#define checkInitializerListOrder(code) checkInitializerListOrder_(code, __FILE__, __LINE__)
template<size_t size>
void checkInitializerListOrder_(const char (&code)[size], const char* file, int line) {
// Tokenize..
SimpleTokenizer tokenizer(settings2, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
CheckClass checkClass(&tokenizer, &settings2, this);
checkClass.initializerListOrder();
}
void initializerListOrder() {
checkInitializerListOrder("class Fred {\n"
" int a, b, c;\n"
"public:\n"
" Fred() : c(0), b(0), a(0) { }\n"
"};");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:2]: (style, inconclusive) Member variable 'Fred::b' is in the wrong place in the initializer list.\n"
"[test.cpp:4] -> [test.cpp:2]: (style, inconclusive) Member variable 'Fred::a' is in the wrong place in the initializer list.\n", errout_str());
checkInitializerListOrder("class Fred {\n"
" int a, b, c;\n"
"public:\n"
" Fred() : c{0}, b{0}, a{0} { }\n"
"};");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:2]: (style, inconclusive) Member variable 'Fred::b' is in the wrong place in the initializer list.\n"
"[test.cpp:4] -> [test.cpp:2]: (style, inconclusive) Member variable 'Fred::a' is in the wrong place in the initializer list.\n", errout_str());
checkInitializerListOrder("struct S {\n"
" S() : b(a = 1) {}\n"
" int a, b;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkInitializerListOrder("struct S {\n"
" int nCols() const;\n"
" int nRows() const;\n"
"};\n"
"struct B {\n"
" const char* m_name;\n"
" int nCols;\n"
" int nRows;\n"
" B(const char* p_name, int nR, int nC)\n"
" : m_name(p_name)\n"
" , nCols(nC)\n"
" , nRows(nR)\n"
" {}\n"
"};\n"
"struct D : public B {\n"
" const int m_i;\n"
" D(const S& s, int _i)\n"
" : B(\"abc\", s.nRows(), s.nCols())\n"
" , m_i(_i)\n"
" {}\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void initializerListArgument() {
checkInitializerListOrder("struct A { A(); };\n" // #12322
"struct B { explicit B(const A* a); };\n"
"struct C {\n"
" C() : b(&a) {}\n"
" B b;\n"
" const A a;\n"
"};");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:5]: (style, inconclusive) Member variable 'C::b' uses an uninitialized argument 'a' due to the order of declarations.\n",
errout_str());
checkInitializerListOrder("struct S {\n"
" S(const std::string& f, std::string i, int b, int c) : a(0), b(b), c(c) {}\n"
" int a, b, c;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkInitializerListOrder("struct S {\n"
" S() : p(a) {}\n"
" int* p;\n"
" int a[1];\n"
"};");
ASSERT_EQUALS("", errout_str());
checkInitializerListOrder("struct S {\n"
" S() : p(&i) {}\n"
" int* p;\n"
" int i;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkInitializerListOrder("struct S {\n"
" S() : a(b = 1) {}\n"
" int a, b;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkInitializerListOrder("struct S {\n"
" S() : r(i) {}\n"
" int& r;\n"
" int i{};\n"
"};");
ASSERT_EQUALS("", errout_str());
checkInitializerListOrder("struct B {\n"
" int a{}, b{};\n"
"};\n"
"struct D : B {\n"
" D() : B(), j(b) {}\n"
" int j;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkInitializerListOrder("struct S {\n"
" S() : a(i) {}\n"
" int a;\n"
" static int i;\n"
"};\n"
"int S::i = 0;");
ASSERT_EQUALS("", errout_str());
checkInitializerListOrder("struct S {\n"
" S(int b) : a(b) {}\n"
" int a, b{};\n"
"};");
ASSERT_EQUALS("", errout_str());
checkInitializerListOrder("class Foo {\n" // #3524
"public:\n"
" Foo(int arg) : a(b), b(arg) {}\n"
" int a;\n"
" int b;\n"
"};\n");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (style, inconclusive) Member variable 'Foo::a' uses an uninitialized argument 'b' due to the order of declarations.\n",
errout_str());
checkInitializerListOrder("struct S { double d = 0; };\n" // #12730
"struct T {\n"
" T() : s(), a(s.d), d(0) {}\n"
" S s;\n"
" double a, d;\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkInitializerListOrder("struct S { static const int d = 1; };\n"
"struct T {\n"
" T() : s(), a(S::d), d(0) {}\n"
" S s;\n"
" int a, d;\n"
"};\n");
ASSERT_EQUALS("", errout_str());
}
#define checkInitializationListUsage(code) checkInitializationListUsage_(code, __FILE__, __LINE__)
template<size_t size>
void checkInitializationListUsage_(const char (&code)[size], const char* file, int line) {
// Check..
const Settings settings = settingsBuilder().severity(Severity::performance).build();
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
CheckClass checkClass(&tokenizer, &settings, this);
checkClass.initializationListUsage();
}
void initializerListUsage() {
checkInitializationListUsage("enum Enum { C = 0 };\n"
"class Fred {\n"
" int a;\n" // No message for builtin types: No performance gain
" int* b;\n" // No message for pointers: No performance gain
" Enum c;\n" // No message for enums: No performance gain
" Fred() { a = 0; b = 0; c = C; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkInitializationListUsage("class Fred {\n"
" std::string s;\n"
" Fred() { a = 0; s = \"foo\"; }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (performance) Variable 's' is assigned in constructor body. Consider performing initialization in initialization list.\n", errout_str());
checkInitializationListUsage("class Fred {\n"
" std::string& s;\n" // Message is invalid for references, since their initialization in initializer list is required anyway and behaves different from assignment (#5004)
" Fred(const std::string& s_) : s(s_) { s = \"foo\"; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkInitializationListUsage("class Fred {\n"
" std::vector<int> v;\n"
" Fred() { v = unknown; }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (performance) Variable 'v' is assigned in constructor body. Consider performing initialization in initialization list.\n", errout_str());
checkInitializationListUsage("class C { std::string s; };\n"
"class Fred {\n"
" C c;\n"
" Fred() { c = unknown; }\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (performance) Variable 'c' is assigned in constructor body. Consider performing initialization in initialization list.\n", errout_str());
checkInitializationListUsage("class C;\n"
"class Fred {\n"
" C c;\n"
" Fred() { c = unknown; }\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (performance) Variable 'c' is assigned in constructor body. Consider performing initialization in initialization list.\n", errout_str());
checkInitializationListUsage("class C;\n"
"class Fred {\n"
" C c;\n"
" Fred(Fred const & other) { c = other.c; }\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (performance) Variable 'c' is assigned in constructor body. Consider performing initialization in initialization list.\n", errout_str());
checkInitializationListUsage("class C;\n"
"class Fred {\n"
" C c;\n"
" Fred(Fred && other) { c = other.c; }\n"
"};");
ASSERT_EQUALS("[test.cpp:4]: (performance) Variable 'c' is assigned in constructor body. Consider performing initialization in initialization list.\n", errout_str());
checkInitializationListUsage("class C;\n"
"class Fred {\n"
" C a;\n"
" Fred() { initB(); a = b; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkInitializationListUsage("class C;\n"
"class Fred {\n"
" C a;\n"
" Fred() : a(0) { if(b) a = 0; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkInitializationListUsage("class C;\n"
"class Fred {\n"
" C a[5];\n"
" Fred() { for(int i = 0; i < 5; i++) a[i] = 0; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkInitializationListUsage("class C;\n"
"class Fred {\n"
" C a; int b;\n"
" Fred() : b(5) { a = b; }\n" // Don't issue a message here: You actually could move it to the initialization list, but it would cause problems if you change the order of the variable declarations.
"};");
ASSERT_EQUALS("", errout_str());
checkInitializationListUsage("class C;\n"
"class Fred {\n"
" C a;\n"
" Fred() { try { a = new int; } catch(...) {} }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkInitializationListUsage("class Fred {\n"
" std::string s;\n"
" Fred() { s = toString((size_t)this); }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkInitializationListUsage("class Fred {\n"
" std::string a;\n"
" std::string foo();\n"
" Fred() { a = foo(); }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkInitializationListUsage("class Fred {\n"
" std::string a;\n"
" Fred() { a = foo(); }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (performance) Variable 'a' is assigned in constructor body. Consider performing initialization in initialization list.\n", errout_str());
checkInitializationListUsage("class Fred {\n" // #4332
" static std::string s;\n"
" Fred() { s = \"foo\"; }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkInitializationListUsage("class Fred {\n" // #5640
" std::string s;\n"
" Fred() {\n"
" char str[2];\n"
" str[0] = c;\n"
" str[1] = 0;\n"
" s = str;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkInitializationListUsage("class B {\n" // #5640
" std::shared_ptr<A> _d;\n"
" B(const B& other) : _d(std::make_shared<A>()) {\n"
" *_d = *other._d;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkInitializationListUsage("class Bar {\n" // #8466
"public:\n"
" explicit Bar(const Bar &bar) : Bar{bar.s} {}\n"
" explicit Bar(const char s) : s{s} {}\n"
"private:\n"
" char s;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkInitializationListUsage("unsigned bar(std::string);\n" // #8291
"class Foo {\n"
"public:\n"
" int a_, b_;\n"
" Foo(int a, int b) : a_(a), b_(b) {}\n"
" Foo(int a, const std::string& b) : Foo(a, bar(b)) {}\n"
"};");
ASSERT_EQUALS("", errout_str());
checkInitializationListUsage("class Fred {\n" // #8111
" std::string a;\n"
" Fred() {\n"
" std::ostringstream ostr;\n"
" ostr << x;\n"
" a = ostr.str();\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
// bailout: multi line lambda in rhs => do not warn
checkInitializationListUsage("class Fred {\n"
" std::function f;\n"
" Fred() {\n"
" f = [](){\n"
" return 1;\n"
" };\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
// don't warn if some other instance's members are assigned to
checkInitializationListUsage("class C {\n"
"public:\n"
" C(C& c) : m_i(c.m_i) { c.m_i = (Foo)-1; }\n"
"private:\n"
" Foo m_i;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkInitializationListUsage("class A {\n" // #9821 - delegate constructor
"public:\n"
" A() : st{} {}\n"
"\n"
" explicit A(const std::string &input): A() {\n"
" st = input;\n"
" }\n"
"\n"
"private:\n"
" std::string st;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
#define checkSelfInitialization(code) checkSelfInitialization_(code, __FILE__, __LINE__)
template<size_t size>
void checkSelfInitialization_(const char (&code)[size], const char* file, int line) {
// Tokenize..
SimpleTokenizer tokenizer(settings0, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
CheckClass checkClass(&tokenizer, &settings0, this);
(checkClass.checkSelfInitialization)();
}
void selfInitialization() {
checkSelfInitialization("class Fred {\n"
" int i;\n"
" Fred() : i(i) {\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (error) Member variable 'i' is initialized by itself.\n", errout_str());
checkSelfInitialization("class Fred {\n"
" int i;\n"
" Fred() : i{i} {\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (error) Member variable 'i' is initialized by itself.\n", errout_str());
checkSelfInitialization("class Fred {\n"
" int i;\n"
" Fred();\n"
"};\n"
"Fred::Fred() : i(i) {\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Member variable 'i' is initialized by itself.\n", errout_str());
checkSelfInitialization("class A {\n" // #10427
"public:\n"
" explicit A(int x) : _x(static_cast<int>(_x)) {}\n"
"private:\n"
" int _x;\n"
"};\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Member variable '_x' is initialized by itself.\n", errout_str());
checkSelfInitialization("class A {\n"
"public:\n"
" explicit A(int x) : _x((int)(_x)) {}\n"
"private:\n"
" int _x;\n"
"};\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Member variable '_x' is initialized by itself.\n", errout_str());
checkSelfInitialization("class Fred {\n"
" std::string s;\n"
" Fred() : s(s) {\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (error) Member variable 's' is initialized by itself.\n", errout_str());
checkSelfInitialization("class Fred {\n"
" int x;\n"
" Fred(int x);\n"
"};\n"
"Fred::Fred(int x) : x(x) { }");
ASSERT_EQUALS("", errout_str());
checkSelfInitialization("class Fred {\n"
" int x;\n"
" Fred(int x);\n"
"};\n"
"Fred::Fred(int x) : x{x} { }");
ASSERT_EQUALS("", errout_str());
checkSelfInitialization("class Fred {\n"
" std::string s;\n"
" Fred(const std::string& s) : s(s) {\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkSelfInitialization("class Fred {\n"
" std::string s;\n"
" Fred(const std::string& s) : s{s} {\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkSelfInitialization("struct Foo : Bar {\n"
" int i;\n"
" Foo(int i)\n"
" : Bar(\"\"), i(i) {}\n"
"};");
ASSERT_EQUALS("", errout_str());
checkSelfInitialization("struct Foo : std::Bar {\n" // #6073
" int i;\n"
" Foo(int i)\n"
" : std::Bar(\"\"), i(i) {}\n"
"};");
ASSERT_EQUALS("", errout_str());
checkSelfInitialization("struct Foo : std::Bar {\n" // #6073
" int i;\n"
" Foo(int i)\n"
" : std::Bar(\"\"), i{i} {}\n"
"};");
ASSERT_EQUALS("", errout_str());
}
#define checkVirtualFunctionCall(...) checkVirtualFunctionCall_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
void checkVirtualFunctionCall_(const char* file, int line, const char (&code)[size], bool inconclusive = true) {
// Check..
const Settings settings = settingsBuilder().severity(Severity::warning).severity(Severity::style).certainty(Certainty::inconclusive, inconclusive).build();
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
CheckClass checkClass(&tokenizer, &settings, this);
checkClass.checkVirtualFunctionCallInConstructor();
}
void virtualFunctionCallInConstructor() {
checkVirtualFunctionCall("class A\n"
"{\n"
" virtual int f() { return 1; }\n"
" A();\n"
"};\n"
"A::A()\n"
"{f();}");
ASSERT_EQUALS("[test.cpp:7] -> [test.cpp:3]: (style) Virtual function 'f' is called from constructor 'A()' at line 7. Dynamic binding is not used.\n", errout_str());
checkVirtualFunctionCall("class A {\n"
" virtual int f();\n"
" A() {f();}\n"
"};\n"
"int A::f() { return 1; }");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:2]: (style) Virtual function 'f' is called from constructor 'A()' at line 3. Dynamic binding is not used.\n", errout_str());
checkVirtualFunctionCall("class A : B {\n"
" int f() override;\n"
" A() {f();}\n"
"};\n"
"int A::f() { return 1; }");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:2]: (style) Virtual function 'f' is called from constructor 'A()' at line 3. Dynamic binding is not used.\n", errout_str());
checkVirtualFunctionCall("class B {\n"
" virtual int f() = 0;\n"
"};\n"
"class A : B {\n"
" int f();\n" // <- not explicitly virtual
" A() {f();}\n"
"};\n"
"int A::f() { return 1; }");
ASSERT_EQUALS("", errout_str());
checkVirtualFunctionCall("class A\n"
"{\n"
" A() { A::f(); }\n"
" virtual void f() {}\n"
"};");
ASSERT_EQUALS("", errout_str());
checkVirtualFunctionCall("class A : B {\n"
" int f() final { return 1; }\n"
" A() { f(); }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkVirtualFunctionCall("class B {\n"
"public:"
" virtual void f() {}\n"
"};\n"
"class A : B {\n"
"public:"
" void f() override final {}\n"
" A() { f(); }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkVirtualFunctionCall("class Base {\n"
"public:\n"
" virtual void Copy(const Base& Src) = 0;\n"
"};\n"
"class Derived : public Base {\n"
"public:\n"
" Derived() : i(0) {}\n"
" Derived(const Derived& Src);\n"
" void Copy(const Base& Src) override;\n"
" int i;\n"
"};\n"
"Derived::Derived(const Derived& Src) {\n"
" Copy(Src);\n"
"}\n"
"void Derived::Copy(const Base& Src) {\n"
" auto d = dynamic_cast<const Derived&>(Src);\n"
" i = d.i;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:13] -> [test.cpp:9]: (style) Virtual function 'Copy' is called from copy constructor 'Derived(const Derived&Src)' at line 13. Dynamic binding is not used.\n",
errout_str());
checkVirtualFunctionCall("struct B {\n"
" B() { auto pf = &f; }\n"
" virtual void f() {}\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkVirtualFunctionCall("struct B {\n"
" B() { auto pf = &B::f; }\n"
" virtual void f() {}\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkVirtualFunctionCall("struct B {\n"
" B() { (f)(); }\n"
" virtual void f() {}\n"
"};\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) Virtual function 'f' is called from constructor 'B()' at line 2. Dynamic binding is not used.\n", errout_str());
checkVirtualFunctionCall("class S {\n" // don't crash
" ~S();\n"
"public:\n"
" S();\n"
"};\n"
"S::S() {\n"
" typeid(S);\n"
"}\n"
"S::~S() = default;\n");
ASSERT_EQUALS("", errout_str());
checkVirtualFunctionCall("struct Base: { virtual void wibble() = 0; virtual ~Base() {} };\n" // #11167
"struct D final : public Base {\n"
" void wibble() override;\n"
" D() {}\n"
" virtual ~D() { wibble(); }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
}
void pureVirtualFunctionCall() {
checkVirtualFunctionCall("class A\n"
"{\n"
" virtual void pure()=0;\n"
" A();\n"
"};\n"
"A::A()\n"
"{pure();}");
ASSERT_EQUALS("[test.cpp:7] -> [test.cpp:3]: (warning) Call of pure virtual function 'pure' in constructor.\n", errout_str());
checkVirtualFunctionCall("class A\n"
"{\n"
" virtual int pure()=0;\n"
" A();\n"
" int m;\n"
"};\n"
"A::A():m(A::pure())\n"
"{}");
ASSERT_EQUALS("[test.cpp:7] -> [test.cpp:3]: (warning) Call of pure virtual function 'pure' in constructor.\n", errout_str());
checkVirtualFunctionCall("namespace N {\n"
" class A\n"
" {\n"
" virtual int pure() = 0;\n"
" A();\n"
" int m;\n"
" };\n"
"}\n"
"N::A::A() : m(N::A::pure()) {}\n");
ASSERT_EQUALS("[test.cpp:9] -> [test.cpp:4]: (warning) Call of pure virtual function 'pure' in constructor.\n", errout_str());
checkVirtualFunctionCall("class A\n"
" {\n"
" virtual void pure()=0;\n"
" virtual ~A();\n"
" int m;\n"
"};\n"
"A::~A()\n"
"{pure();}");
ASSERT_EQUALS("[test.cpp:8] -> [test.cpp:3]: (warning) Call of pure virtual function 'pure' in destructor.\n", errout_str());
checkVirtualFunctionCall("class A\n"
" {\n"
" virtual void pure()=0;\n"
" void nonpure()\n"
" {pure();}\n"
" A();\n"
"};\n"
"A::A()\n"
"{nonpure();}");
ASSERT_EQUALS("[test.cpp:9] -> [test.cpp:5] -> [test.cpp:3]: (warning) Call of pure virtual function 'pure' in constructor.\n", errout_str());
checkVirtualFunctionCall("class A\n"
" {\n"
" virtual int pure()=0;\n"
" int nonpure()\n"
" {return pure();}\n"
" A();\n"
" int m;\n"
"};\n"
"A::A():m(nonpure())\n"
"{}");
TODO_ASSERT_EQUALS("[test.cpp:9] -> [test.cpp:5] -> [test.cpp:3]: (warning) Call of pure virtual function 'pure' in constructor.\n", "", errout_str());
checkVirtualFunctionCall("class A\n"
" {\n"
" virtual void pure()=0;\n"
" void nonpure()\n"
" {pure();}\n"
" virtual ~A();\n"
" int m;\n"
"};\n"
"A::~A()\n"
"{nonpure();}");
ASSERT_EQUALS("[test.cpp:10] -> [test.cpp:5] -> [test.cpp:3]: (warning) Call of pure virtual function 'pure' in destructor.\n", errout_str());
checkVirtualFunctionCall("class A\n"
"{\n"
" virtual void pure()=0;\n"
" A(bool b);\n"
"};\n"
"A::A(bool b)\n"
"{if (b) pure();}");
ASSERT_EQUALS("[test.cpp:7] -> [test.cpp:3]: (warning) Call of pure virtual function 'pure' in constructor.\n", errout_str());
checkVirtualFunctionCall("class A\n"
"{\n"
" virtual void pure()=0;\n"
" virtual ~A();\n"
" int m;\n"
"};\n"
"A::~A()\n"
"{if (b) pure();}");
ASSERT_EQUALS("[test.cpp:8] -> [test.cpp:3]: (warning) Call of pure virtual function 'pure' in destructor.\n", errout_str());
// #5831
checkVirtualFunctionCall("class abc {\n"
"public:\n"
" virtual ~abc() throw() {}\n"
" virtual void def(void* g) throw () = 0;\n"
"};");
ASSERT_EQUALS("", errout_str());
// #4992
checkVirtualFunctionCall("class CMyClass {\n"
" std::function< void(void) > m_callback;\n"
"public:\n"
" CMyClass() {\n"
" m_callback = [this]() { return VirtualMethod(); };\n"
" }\n"
" virtual void VirtualMethod() = 0;\n"
"};");
ASSERT_EQUALS("", errout_str());
// #10559
checkVirtualFunctionCall("struct S {\n"
" S(const int x) : m(std::bind(&S::f, this, x, 42)) {}\n"
" virtual int f(const int x, const int y) = 0;\n"
" std::function<int()> m;\n"
"};\n");
ASSERT_EQUALS("", errout_str());
}
void pureVirtualFunctionCallOtherClass() {
checkVirtualFunctionCall("class A\n"
"{\n"
" virtual void pure()=0;\n"
" A(const A & a);\n"
"};\n"
"A::A(const A & a)\n"
"{a.pure();}");
ASSERT_EQUALS("", errout_str());
checkVirtualFunctionCall("class A\n"
"{\n"
" virtual void pure()=0;\n"
" A();\n"
"};\n"
"class B\n"
"{\n"
" virtual void pure()=0;\n"
"};\n"
"A::A()\n"
"{B b; b.pure();}");
ASSERT_EQUALS("", errout_str());
}
void pureVirtualFunctionCallWithBody() {
checkVirtualFunctionCall("class A\n"
"{\n"
" virtual void pureWithBody()=0;\n"
" A();\n"
"};\n"
"A::A()\n"
"{pureWithBody();}\n"
"void A::pureWithBody()\n"
"{}");
ASSERT_EQUALS("", errout_str());
checkVirtualFunctionCall("class A\n"
" {\n"
" virtual void pureWithBody()=0;\n"
" void nonpure()\n"
" {pureWithBody();}\n"
" A();\n"
"};\n"
"A::A()\n"
"{nonpure();}\n"
"void A::pureWithBody()\n"
"{}");
ASSERT_EQUALS("", errout_str());
}
void pureVirtualFunctionCallPrevented() {
checkVirtualFunctionCall("class A\n"
" {\n"
" virtual void pure()=0;\n"
" void nonpure(bool bCallPure)\n"
" { if (bCallPure) pure();}\n"
" A();\n"
"};\n"
"A::A()\n"
"{nonpure(false);}");
ASSERT_EQUALS("", errout_str());
checkVirtualFunctionCall("class A\n"
" {\n"
" virtual void pure()=0;\n"
" void nonpure(bool bCallPure)\n"
" { if (!bCallPure) ; else pure();}\n"
" A();\n"
"};\n"
"A::A()\n"
"{nonpure(false);}");
ASSERT_EQUALS("", errout_str());
checkVirtualFunctionCall("class A\n"
" {\n"
" virtual void pure()=0;\n"
" void nonpure(bool bCallPure)\n"
" {\n"
" switch (bCallPure) {\n"
" case true: pure(); break;\n"
" }\n"
" }\n"
" A();\n"
"};\n"
"A::A()\n"
"{nonpure(false);}");
ASSERT_EQUALS("", errout_str());
}
#define checkOverride(code) checkOverride_(code, __FILE__, __LINE__)
template<size_t size>
void checkOverride_(const char (&code)[size], const char* file, int line) {
const Settings settings = settingsBuilder().severity(Severity::style).build();
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
// Check..
CheckClass checkClass(&tokenizer, &settings, this);
(checkClass.checkOverride)();
}
void override1() {
checkOverride("class Base { virtual void f(); };\n"
"class Derived : Base { virtual void f(); };");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:2]: (style) The function 'f' overrides a function in a base class but is not marked with a 'override' specifier.\n", errout_str());
checkOverride("class Base { virtual void f(); };\n"
"class Derived : Base { virtual void f() override; };");
ASSERT_EQUALS("", errout_str());
checkOverride("class Base { virtual void f(); };\n"
"class Derived : Base { virtual void f() final; };");
ASSERT_EQUALS("", errout_str());
checkOverride("class Base {\n"
"public:\n"
" virtual auto foo( ) const -> size_t { return 1; }\n"
" virtual auto bar( ) const -> size_t { return 1; }\n"
"};\n"
"class Derived : public Base {\n"
"public :\n"
" auto foo( ) const -> size_t { return 0; }\n"
" auto bar( ) const -> size_t override { return 0; }\n"
"};");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:8]: (style) The function 'foo' overrides a function in a base class but is not marked with a 'override' specifier.\n", errout_str());
checkOverride("namespace Test {\n"
" class C {\n"
" public:\n"
" virtual ~C();\n"
" };\n"
"}\n"
"class C : Test::C {\n"
"public:\n"
" ~C();\n"
"};");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:9]: (style) The destructor '~C' overrides a destructor in a base class but is not marked with a 'override' specifier.\n", errout_str());
checkOverride("struct Base {\n"
" virtual void foo();\n"
"};\n"
"\n"
"struct Derived: public Base {\n"
" void foo() override;\n"
" void foo(int);\n"
"};");
ASSERT_EQUALS("", errout_str());
checkOverride("struct B {\n" // #9092
" virtual int f(int i) const = 0;\n"
"};\n"
"namespace N {\n"
" struct D : B {\n"
" virtual int f(int i) const;\n"
" };\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:6]: (style) The function 'f' overrides a function in a base class but is not marked with a 'override' specifier.\n", errout_str());
checkOverride("struct A {\n"
" virtual void f(int);\n"
"};\n"
"struct D : A {\n"
" void f(double);\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkOverride("struct A {\n"
" virtual void f(int);\n"
"};\n"
"struct D : A {\n"
" void f(int);\n"
"};\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:5]: (style) The function 'f' overrides a function in a base class but is not marked with a 'override' specifier.\n", errout_str());
checkOverride("struct A {\n"
" virtual void f(char, int);\n"
"};\n"
"struct D : A {\n"
" void f(char, int);\n"
"};\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:5]: (style) The function 'f' overrides a function in a base class but is not marked with a 'override' specifier.\n", errout_str());
checkOverride("struct A {\n"
" virtual void f(char, int);\n"
"};\n"
"struct D : A {\n"
" void f(char, double);\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkOverride("struct A {\n"
" virtual void f(char, int);\n"
"};\n"
"struct D : A {\n"
" void f(char c = '\\0', double);\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkOverride("struct A {\n"
" virtual void f(char, int);\n"
"};\n"
"struct D : A {\n"
" void f(char c = '\\0', int);\n"
"};\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:5]: (style) The function 'f' overrides a function in a base class but is not marked with a 'override' specifier.\n", errout_str());
checkOverride("struct A {\n"
" virtual void f(char c, std::vector<int>);\n"
"};\n"
"struct D : A {\n"
" void f(char c, std::vector<double>);\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkOverride("struct A {\n"
" virtual void f(char c, std::vector<int>);\n"
"};\n"
"struct D : A {\n"
" void f(char c, std::set<int>);\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkOverride("struct A {\n"
" virtual void f(char c, std::vector<int> v);\n"
"};\n"
"struct D : A {\n"
" void f(char c, std::vector<int> w = {});\n"
"};\n");
TODO_ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:5]: (style) The function 'f' overrides a function in a base class but is not marked with a 'override' specifier.\n", "", errout_str());
checkOverride("struct T {};\n" // #10920
"struct B {\n"
" virtual T f() = 0;\n"
"};\n"
"struct D : B {\n"
" friend T f();\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkOverride("struct S {};\n" // #11827
"struct SPtr {\n"
" virtual S* operator->() const { return p; }\n"
" S* p = nullptr;\n"
"};\n"
"struct T : public S {};\n"
"struct TPtr : public SPtr {\n"
" T* operator->() const { return (T*)p; }\n"
"};\n");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:8]: (style) The function 'operator->' overrides a function in a base class but is not marked with a 'override' specifier.\n",
errout_str());
checkOverride("class Base {\n" // #12131
" virtual int Calculate(int arg) = 0;\n"
"};\n"
"class Derived : public Base {\n"
" int Calculate(int arg = 0) {\n"
" return arg * 2;\n"
" }\n"
"};\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:5]: (style) The function 'Calculate' overrides a function in a base class but is not marked with a 'override' specifier.\n", errout_str());
checkOverride("struct S {\n" // #12439
" virtual ~S() = default;\n"
"};\n"
"struct D : S {\n"
" ~D() {}\n"
"};\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:5]: (style) The destructor '~D' overrides a destructor in a base class but is not marked with a 'override' specifier.\n",
errout_str());
}
void overrideCVRefQualifiers() {
checkOverride("class Base { virtual void f(); };\n"
"class Derived : Base { void f() const; }");
ASSERT_EQUALS("", errout_str());
checkOverride("class Base { virtual void f(); };\n"
"class Derived : Base { void f() volatile; }");
ASSERT_EQUALS("", errout_str());
checkOverride("class Base { virtual void f(); };\n"
"class Derived : Base { void f() &; }");
ASSERT_EQUALS("", errout_str());
checkOverride("class Base { virtual void f(); };\n"
"class Derived : Base { void f() &&; }");
ASSERT_EQUALS("", errout_str());
}
#define checkUselessOverride(...) checkUselessOverride_(__FILE__, __LINE__, __VA_ARGS__)
void checkUselessOverride_(const char* file, int line, const char code[]) {
const Settings settings = settingsBuilder().severity(Severity::style).build();
std::vector<std::string> files(1, "test.cpp");
Tokenizer tokenizer(settings, *this);
PreprocessorHelper::preprocess(code, files, tokenizer, *this);
ASSERT_LOC(tokenizer.simplifyTokens1(""), file, line);
// Check..
CheckClass checkClass(&tokenizer, &settings, this);
(checkClass.checkUselessOverride)();
}
void uselessOverride() {
checkUselessOverride("struct B { virtual int f() { return 5; } };\n" // #11757
"struct D : B {\n"
" int f() override { return B::f(); }\n"
"};");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:3]: (style) The function 'f' overrides a function in a base class but just delegates back to the base class.\n", errout_str());
checkUselessOverride("struct B { virtual void f(); };\n"
"struct D : B {\n"
" void f() override { B::f(); }\n"
"};");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:3]: (style) The function 'f' overrides a function in a base class but just delegates back to the base class.\n", errout_str());
checkUselessOverride("struct B { virtual int f() = 0; };\n"
"int B::f() { return 5; }\n"
"struct D : B {\n"
" int f() override { return B::f(); }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkUselessOverride("struct B { virtual int f(int i); };\n"
"struct D : B {\n"
" int f(int i) override { return B::f(i); }\n"
"};");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:3]: (style) The function 'f' overrides a function in a base class but just delegates back to the base class.\n", errout_str());
checkUselessOverride("struct B { virtual int f(int i); };\n"
"struct D : B {\n"
" int f(int i) override { return B::f(i + 1); }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkUselessOverride("struct B { virtual int f(int i, int j); };\n"
"struct D : B {\n"
" int f(int i, int j) override { return B::f(j, i); }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkUselessOverride("struct B { virtual int f(); };\n"
"struct I { virtual int f() = 0; };\n"
"struct D : B, I {\n"
" int f() override { return B::f(); }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkUselessOverride("struct S { virtual void f(); };\n"
"struct D : S {\n"
" void f() final { S::f(); }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkUselessOverride("struct S {\n"
"protected:\n"
" virtual void f();\n"
"};\n"
"struct D : S {\n"
"public:\n"
" void f() override { S::f(); }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkUselessOverride("struct B { virtual void f(int, int, int) const; };\n" // #11799
"struct D : B {\n"
" int m = 42;\n"
" void f(int a, int b, int c) const override;\n"
"};\n"
"void D::f(int a, int b, int c) const {\n"
" B::f(a, b, m);\n"
"};");
ASSERT_EQUALS("", errout_str());
checkUselessOverride("struct B {\n" // #11803
" virtual void f();\n"
" virtual void f(int i);\n"
"};\n"
"struct D : B {\n"
" void f() override { B::f(); }\n"
" void f(int i) override;\n"
" void g() { f(); }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkUselessOverride("struct B { virtual void f(); };\n" // #11808
"struct D : B { void f() override {} };\n"
"struct D2 : D {\n"
" void f() override {\n"
" B::f();\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
checkUselessOverride("struct B {\n"
" virtual int f() { return 1; }\n"
" virtual int g() { return 7; }\n"
" virtual int h(int i, int j) { return i + j; }\n"
" virtual int j(int i, int j) { return i + j; }\n"
"};\n"
"struct D : B {\n"
" int f() override { return 2; }\n"
" int g() override { return 7; }\n"
" int h(int j, int i) override { return i + j; }\n"
" int j(int i, int j) override { return i + j; }\n"
"};");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:9]: (style) The function 'g' overrides a function in a base class but is identical to the overridden function\n"
"[test.cpp:5] -> [test.cpp:11]: (style) The function 'j' overrides a function in a base class but is identical to the overridden function\n",
errout_str());
checkUselessOverride("struct B : std::exception {\n"
" virtual void f() { throw *this; }\n"
"};\n"
"struct D : B {\n"
" void f() override { throw *this; }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkUselessOverride("#define MACRO virtual void f() {}\n"
"struct B {\n"
" MACRO\n"
"};\n"
"struct D : B {\n"
" MACRO\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkUselessOverride("struct B {\n"
" B() = default;\n"
" explicit B(int i) : m(i) {}\n"
" int m{};\n"
" virtual int f() const { return m; }\n"
"};\n"
"struct D : B {\n"
" explicit D(int i) : m(i) {}\n"
" int m{};\n"
" int f() const override { return m; }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkUselessOverride("struct B {\n"
" int g() const;\n"
" virtual int f() const { return g(); }\n"
"};\n"
"struct D : B {\n"
" int g() const;\n"
" int f() const override { return g(); }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkUselessOverride("#define MACRO 1\n"
"struct B { virtual int f() { return 1; } };\n"
"struct D : B {\n"
" int f() override { return MACRO; }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkUselessOverride("struct B {\n" // #12706
" virtual void f() { g(); }\n"
" void g() { std::cout << \"Base\\n\"; }\n"
"};\n"
"struct D : B {\n"
" void f() override { g(); }\n"
" virtual void g() { std::cout << \"Derived\\n\"; }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkUselessOverride("struct B {\n" // #12946
" virtual int f() { return i; }\n"
" int i;\n"
"};\n"
"struct D : B {\n"
" int f() override { return b.f(); }\n"
" B b;\n"
"};\n");
ASSERT_EQUALS("", errout_str());
}
#define checkUnsafeClassRefMember(code) checkUnsafeClassRefMember_(code, __FILE__, __LINE__)
template<size_t size>
void checkUnsafeClassRefMember_(const char (&code)[size], const char* file, int line) {
/*const*/ Settings settings = settingsBuilder().severity(Severity::warning).build();
settings.safeChecks.classes = true;
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
// Check..
CheckClass checkClass(&tokenizer, &settings, this);
(checkClass.checkUnsafeClassRefMember)();
}
void unsafeClassRefMember() {
checkUnsafeClassRefMember("class C { C(const std::string &s) : s(s) {} const std::string &s; };");
ASSERT_EQUALS("[test.cpp:1]: (warning) Unsafe class: The const reference member 'C::s' is initialized by a const reference constructor argument. You need to be careful about lifetime issues.\n", errout_str());
}
#define checkThisUseAfterFree(code) checkThisUseAfterFree_(code, __FILE__, __LINE__)
template<size_t size>
void checkThisUseAfterFree_(const char (&code)[size], const char* file, int line) {
// Tokenize..
SimpleTokenizer tokenizer(settings1, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
// Check..
CheckClass checkClass(&tokenizer, &settings1, this);
(checkClass.checkThisUseAfterFree)();
}
void thisUseAfterFree() {
setMultiline();
// Calling method..
checkThisUseAfterFree("class C {\n"
"public:\n"
" void dostuff() { delete mInstance; hello(); }\n"
"private:\n"
" static C *mInstance;\n"
" void hello() {}\n"
"};");
ASSERT_EQUALS("test.cpp:3:warning:Calling method 'hello()' when 'this' might be invalid\n"
"test.cpp:5:note:Assuming 'mInstance' is used as 'this'\n"
"test.cpp:3:note:Delete 'mInstance', invalidating 'this'\n"
"test.cpp:3:note:Call method when 'this' is invalid\n",
errout_str());
checkThisUseAfterFree("class C {\n"
"public:\n"
" void dostuff() { mInstance.reset(); hello(); }\n"
"private:\n"
" static std::shared_ptr<C> mInstance;\n"
" void hello() {}\n"
"};");
ASSERT_EQUALS("test.cpp:3:warning:Calling method 'hello()' when 'this' might be invalid\n"
"test.cpp:5:note:Assuming 'mInstance' is used as 'this'\n"
"test.cpp:3:note:Delete 'mInstance', invalidating 'this'\n"
"test.cpp:3:note:Call method when 'this' is invalid\n",
errout_str());
checkThisUseAfterFree("class C {\n"
"public:\n"
" void dostuff() { reset(); hello(); }\n"
"private:\n"
" static std::shared_ptr<C> mInstance;\n"
" void hello();\n"
" void reset() { mInstance.reset(); }\n"
"};");
ASSERT_EQUALS("test.cpp:3:warning:Calling method 'hello()' when 'this' might be invalid\n"
"test.cpp:5:note:Assuming 'mInstance' is used as 'this'\n"
"test.cpp:7:note:Delete 'mInstance', invalidating 'this'\n"
"test.cpp:3:note:Call method when 'this' is invalid\n",
errout_str());
// Use member..
checkThisUseAfterFree("class C {\n"
"public:\n"
" void dostuff() { delete self; x = 123; }\n"
"private:\n"
" static C *self;\n"
" int x;\n"
"};");
ASSERT_EQUALS("test.cpp:3:warning:Using member 'x' when 'this' might be invalid\n"
"test.cpp:5:note:Assuming 'self' is used as 'this'\n"
"test.cpp:3:note:Delete 'self', invalidating 'this'\n"
"test.cpp:3:note:Call method when 'this' is invalid\n",
errout_str());
checkThisUseAfterFree("class C {\n"
"public:\n"
" void dostuff() { delete self; x[1] = 123; }\n"
"private:\n"
" static C *self;\n"
" std::map<int,int> x;\n"
"};");
ASSERT_EQUALS("test.cpp:3:warning:Using member 'x' when 'this' might be invalid\n"
"test.cpp:5:note:Assuming 'self' is used as 'this'\n"
"test.cpp:3:note:Delete 'self', invalidating 'this'\n"
"test.cpp:3:note:Call method when 'this' is invalid\n",
errout_str());
// Assign 'shared_from_this()' to non-static smart pointer
checkThisUseAfterFree("class C {\n"
"public:\n"
" void hold() { mInstance = shared_from_this(); }\n"
" void dostuff() { mInstance.reset(); hello(); }\n"
"private:\n"
" std::shared_ptr<C> mInstance;\n"
" void hello() {}\n"
"};");
ASSERT_EQUALS("test.cpp:4:warning:Calling method 'hello()' when 'this' might be invalid\n"
"test.cpp:6:note:Assuming 'mInstance' is used as 'this'\n"
"test.cpp:4:note:Delete 'mInstance', invalidating 'this'\n"
"test.cpp:4:note:Call method when 'this' is invalid\n",
errout_str());
// Avoid FP..
checkThisUseAfterFree("class C {\n"
"public:\n"
" void dostuff() { delete self; x = 123; }\n"
"private:\n"
" C *self;\n"
" int x;\n"
"};");
ASSERT_EQUALS("", errout_str());
checkThisUseAfterFree("class C {\n"
"public:\n"
" void hold() { mInstance = shared_from_this(); }\n"
" void dostuff() { if (x) { mInstance.reset(); return; } hello(); }\n"
"private:\n"
" std::shared_ptr<C> mInstance;\n"
" void hello() {}\n"
"};");
ASSERT_EQUALS("", errout_str());
checkThisUseAfterFree("class C\n"
"{\n"
"public:\n"
" explicit C(const QString& path) : mPath( path ) {}\n"
"\n"
" static void initialize(const QString& path) {\n" // <- avoid fp in static method
" if (instanceSingleton)\n"
" delete instanceSingleton;\n"
" instanceSingleton = new C(path);\n"
" }\n"
"private:\n"
" static C* instanceSingleton;\n"
"};\n"
"\n"
"C* C::instanceSingleton;");
ASSERT_EQUALS("", errout_str());
// Avoid false positive when pointer is deleted in lambda
checkThisUseAfterFree("class C {\n"
"public:\n"
" void foo();\n"
" void set() { p = this; }\n"
" void dostuff() {}\n"
" C* p;\n"
"};\n"
"\n"
"void C::foo() {\n"
" auto done = [this] () { delete p; };\n"
" dostuff();\n"
" done();\n"
"}");
ASSERT_EQUALS("", errout_str());
checkThisUseAfterFree("class C {\n" // #13311
"public:\n"
" static void init();\n"
"private:\n"
" C();\n"
" static C* self;\n"
" bool use;\n"
"};\n"
"C::C() { use = true; }\n"
"void C::init() {\n"
" if (self)\n"
" delete self;\n"
" self = new C();\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void ctu(const std::vector<std::string> &code) {
Check &check = getCheck<CheckClass>();
// getFileInfo
std::list<Check::FileInfo*> fileInfo;
for (const std::string& c: code) {
Tokenizer tokenizer(settingsDefault, *this);
std::istringstream istr(c);
const std::string filename = std::to_string(fileInfo.size()) + ".cpp";
ASSERT(tokenizer.list.createTokens(istr, filename));
ASSERT(tokenizer.simplifyTokens1(""));
fileInfo.push_back(check.getFileInfo(tokenizer, settingsDefault));
}
// Check code..
check.analyseWholeProgram(nullptr, fileInfo, settingsDefault, *this); // TODO: check result
while (!fileInfo.empty()) {
delete fileInfo.back();
fileInfo.pop_back();
}
}
void ctuOneDefinitionRule() {
ctu({"class C { C() { std::cout << 0; } };", "class C { C() { std::cout << 1; } };"});
ASSERT_EQUALS("[1.cpp:1] -> [0.cpp:1]: (error) The one definition rule is violated, different classes/structs have the same name 'C'\n", errout_str());
ctu({"class C { C(); }; C::C() { std::cout << 0; }", "class C { C(); }; C::C() { std::cout << 1; }"});
ASSERT_EQUALS("[1.cpp:1] -> [0.cpp:1]: (error) The one definition rule is violated, different classes/structs have the same name 'C'\n", errout_str());
ctu({"class C { C() {} };\n", "class C { C() {} };\n"});
ASSERT_EQUALS("", errout_str());
ctu({"class C { C(); }; C::C(){}", "class C { C(); }; C::C(){}"});
ASSERT_EQUALS("", errout_str());
ctu({"class A::C { C() { std::cout << 0; } };", "class B::C { C() { std::cout << 1; } };"});
ASSERT_EQUALS("", errout_str());
// 11435 - template specialisations
const std::string header = "template<typename T1, typename T2> struct Test {};\n";
ctu({header + "template<typename T1> struct Test<T1, int> {};\n",
header + "template<typename T1> struct Test<T1, double> {};\n"});
ASSERT_EQUALS("", errout_str());
}
#define getFileInfo(code) getFileInfo_(code, __FILE__, __LINE__)
template<size_t size>
void getFileInfo_(const char (&code)[size], const char* file, int line) {
// Tokenize..
SimpleTokenizer tokenizer(settings1, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
// Check..
const Check& c = getCheck<CheckClass>();
Check::FileInfo * fileInfo = (c.getFileInfo)(tokenizer, settings1);
delete fileInfo;
}
void testGetFileInfo() {
getFileInfo("void foo() { union { struct { }; }; }"); // don't crash
getFileInfo("struct sometype { sometype(); }; sometype::sometype() = delete;"); // don't crash
}
#define checkReturnByReference(...) checkReturnByReference_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
void checkReturnByReference_(const char* file, int line, const char (&code)[size]) {
const Settings settings = settingsBuilder().severity(Severity::performance).library("std.cfg").build();
std::vector<std::string> files(1, "test.cpp");
Tokenizer tokenizer(settings, *this);
PreprocessorHelper::preprocess(code, files, tokenizer, *this);
ASSERT_LOC(tokenizer.simplifyTokens1(""), file, line);
// Check..
CheckClass checkClass(&tokenizer, &settings, this);
(checkClass.checkReturnByReference)();
}
void returnByReference() {
checkReturnByReference("struct T { int a[10]; };\n" // #12546
"struct S {\n"
" T t;\n"
" int i;\n"
" std::string s;\n"
" T getT() const { return t; }\n"
" int getI() const { return i; }\n"
" std::string getS() const { return s; }\n"
" unknown_t f() { return; }\n"
"};\n");
ASSERT_EQUALS("[test.cpp:6]: (performance) Function 'getT()' should return member 't' by const reference.\n"
"[test.cpp:8]: (performance) Function 'getS()' should return member 's' by const reference.\n",
errout_str());
checkReturnByReference("struct B {\n" // #12608
" virtual std::string f() { return \"abc\"; }\n"
"};\n"
"struct D : B {\n"
" std::string f() override { return s; }\n"
" std::string s;\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkReturnByReference("struct S {\n"
" std::string f(std::string s) { return s; }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkReturnByReference("struct S { S(); };\n" // #12620
"S::S() = delete;\n");
ASSERT_EQUALS("", errout_str()); // don't crash
checkReturnByReference("struct S {\n" // #12626
" std::string s;\n"
" operator std::string_view() const { return s; }\n"
" std::string_view get() const { return s; }\n"
"};\n"
"template<typename T>\n"
"struct U {\n"
" T t;\n"
" operator const T& () const { return t; }\n"
"};\n"
"U<std::string> u;\n");
ASSERT_EQUALS("", errout_str());
checkReturnByReference("struct S {\n" // #13011
" std::string s;\n"
" const std::string& foo() const & { return s; }\n"
" std::string foo() && { return s; }\n" // <- used for temporary objects
"};\n");
ASSERT_EQUALS("", errout_str());
checkReturnByReference("struct S1 {\n" // #13056
" std::string str;\n"
" struct T { std::string strT; } mT;\n"
"};\n"
"struct S2 {\n"
" std::string get1() const {\n"
" return mS1->str;\n"
" }\n"
" std::string get2() const {\n"
" return mS1->mT.strT;\n"
" }\n"
" S1* mS1;\n"
"};\n");
ASSERT_EQUALS("[test.cpp:6]: (performance) Function 'get1()' should return member 'str' by const reference.\n"
"[test.cpp:9]: (performance) Function 'get2()' should return member 'strT' by const reference.\n",
errout_str());
checkReturnByReference("struct S { std::string str; };\n" // #13059
"struct T {\n"
" S temp() const;\n"
" S s[1];\n"
"};\n"
"struct U {\n"
" std::string get1() const {\n"
" return t.temp().str;\n"
" }\n"
" std::string get2() const {\n"
" return t.s[0].str;\n"
" }\n"
" T t;\n"
"};\n");
ASSERT_EQUALS("[test.cpp:10]: (performance) Function 'get2()' should return member 'str' by const reference.\n",
errout_str());
}
};
REGISTER_TEST(TestClass)
| null |
984 | cpp | cppcheck | testvarid.cpp | test/testvarid.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "helpers.h"
#include "platform.h"
#include "settings.h"
#include "standards.h"
#include "fixture.h"
#include "token.h"
#include "tokenize.h"
#include "tokenlist.h"
#include <cstddef>
#include <sstream>
#include <string>
#include <vector>
class TestVarID : public TestFixture {
public:
TestVarID() : TestFixture("TestVarID") {}
private:
const Settings settings = settingsBuilder().c(Standards::C89).platform(Platform::Type::Unix64).build();
void run() override {
TEST_CASE(varid1);
TEST_CASE(varid2);
TEST_CASE(varid3);
TEST_CASE(varid4);
TEST_CASE(varid5);
TEST_CASE(varid6);
TEST_CASE(varid7);
TEST_CASE(varidReturn1);
TEST_CASE(varidReturn2);
TEST_CASE(varid8);
TEST_CASE(varid9);
TEST_CASE(varid10);
TEST_CASE(varid11);
TEST_CASE(varid12);
TEST_CASE(varid13);
TEST_CASE(varid14);
TEST_CASE(varid15);
TEST_CASE(varid16);
TEST_CASE(varid17); // ticket #1810
TEST_CASE(varid18);
TEST_CASE(varid19);
TEST_CASE(varid20);
TEST_CASE(varid24);
TEST_CASE(varid25);
TEST_CASE(varid26); // ticket #1967 (list of function pointers)
TEST_CASE(varid27); // Ticket #2280 (same name for namespace and variable)
TEST_CASE(varid28); // ticket #2630
TEST_CASE(varid29); // ticket #1974
TEST_CASE(varid30); // ticket #2614
TEST_CASE(varid34); // ticket #2825
TEST_CASE(varid35); // function declaration inside function body
TEST_CASE(varid36); // ticket #2980 (segmentation fault)
TEST_CASE(varid37); // ticket #3092 (varid for 'Bar bar(*this);')
TEST_CASE(varid38); // ticket #3272 (varid for 'FOO class C;')
TEST_CASE(varid39); // ticket #3279 (varid for 'FOO::BAR const')
TEST_CASE(varid40); // ticket #3279
TEST_CASE(varid41); // ticket #3340 (varid for union type)
TEST_CASE(varid42); // ticket #3316 (varid for array)
TEST_CASE(varid43);
TEST_CASE(varid44);
TEST_CASE(varid45); // #3466
TEST_CASE(varid46); // struct varname
TEST_CASE(varid47); // function parameters
TEST_CASE(varid48); // #3785 - return (a*b)
TEST_CASE(varid49); // #3799 - void f(std::vector<int>)
TEST_CASE(varid50); // #3760 - explicit
TEST_CASE(varid51); // don't set varid for template function
TEST_CASE(varid52); // Set varid for nested templates
TEST_CASE(varid53); // #4172 - Template instantiation: T<&functionName> list[4];
TEST_CASE(varid54); // hang
TEST_CASE(varid55); // #5868: Function::addArgument with varid 0 for argument named the same as a typedef
TEST_CASE(varid56); // function with a throw()
TEST_CASE(varid57); // #6636: new scope by {}
TEST_CASE(varid58); // #6638: for loop in for condition
TEST_CASE(varid59); // #6696
TEST_CASE(varid60); // #7267 cast '(unsigned x)10'
TEST_CASE(varid61); // #4988 inline function
TEST_CASE(varid62);
TEST_CASE(varid63);
TEST_CASE(varid64); // #9922 - extern const char (*x[256])
TEST_CASE(varid65); // #10936
TEST_CASE(varid66);
TEST_CASE(varid67); // #11711 - NOT function pointer
TEST_CASE(varid68); // #11740 - switch (str_chars(&strOut)[0])
TEST_CASE(varid69);
TEST_CASE(varid70); // #12660 - function
TEST_CASE(varid71); // #12676 - wrong varid in uninstantiated templated constructor
TEST_CASE(varid_for_1);
TEST_CASE(varid_for_2);
TEST_CASE(varid_cpp_keywords_in_c_code);
TEST_CASE(varid_cpp_keywords_in_c_code2); // #5373: varid=0 for argument called "delete"
TEST_CASE(varid_cpp_keywords_in_c_code3);
TEST_CASE(varidFunctionCall1);
TEST_CASE(varidFunctionCall2);
TEST_CASE(varidFunctionCall3);
TEST_CASE(varidFunctionCall4); // ticket #3280
TEST_CASE(varidFunctionCall5);
TEST_CASE(varidStl);
TEST_CASE(varidStl2);
TEST_CASE(varid_newauto); // not declaration: new const auto(0);
TEST_CASE(varid_delete);
TEST_CASE(varid_functions);
TEST_CASE(varid_sizeof);
TEST_CASE(varid_reference_to_containers);
TEST_CASE(varid_in_class1);
TEST_CASE(varid_in_class2);
TEST_CASE(varid_in_class3); // #3092 - shadow variable in member function
TEST_CASE(varid_in_class4); // #3271 - public: class C;
TEST_CASE(varid_in_class5); // #3584 - std::vector<::FOO::B> b;
TEST_CASE(varid_in_class6); // #3755
TEST_CASE(varid_in_class7); // set variable id for struct members
TEST_CASE(varid_in_class8); // unknown macro in class
TEST_CASE(varid_in_class9); // #4291 - id for variables accessed through 'this'
TEST_CASE(varid_in_class10);
TEST_CASE(varid_in_class11); // #4277 - anonymous union
TEST_CASE(varid_in_class12); // #4637 - method
TEST_CASE(varid_in_class13); // #4637 - method
TEST_CASE(varid_in_class14);
TEST_CASE(varid_in_class15); // #5533 - functions
TEST_CASE(varid_in_class16);
TEST_CASE(varid_in_class17); // #6056 - no varid for member functions
TEST_CASE(varid_in_class18); // #7127
TEST_CASE(varid_in_class19);
TEST_CASE(varid_in_class20); // #7267
TEST_CASE(varid_in_class21); // #7788
TEST_CASE(varid_in_class22); // #10872
TEST_CASE(varid_in_class23); // #11293
TEST_CASE(varid_in_class24);
TEST_CASE(varid_in_class25);
TEST_CASE(varid_in_class26);
TEST_CASE(varid_in_class27);
TEST_CASE(varid_namespace_1); // #7272
TEST_CASE(varid_namespace_2); // #7000
TEST_CASE(varid_namespace_3); // #8627
TEST_CASE(varid_namespace_4);
TEST_CASE(varid_namespace_5);
TEST_CASE(varid_namespace_6);
TEST_CASE(varid_initList);
TEST_CASE(varid_initListWithBaseTemplate);
TEST_CASE(varid_initListWithScope);
TEST_CASE(varid_operator);
TEST_CASE(varid_throw);
TEST_CASE(varid_unknown_macro); // #2638 - unknown macro is not type
TEST_CASE(varid_using); // ticket #3648
TEST_CASE(varid_catch);
TEST_CASE(varid_functionPrototypeTemplate);
TEST_CASE(varid_templatePtr); // #4319
TEST_CASE(varid_templateNamespaceFuncPtr); // #4172
TEST_CASE(varid_templateArray);
TEST_CASE(varid_templateParameter); // #7046 set varid for "X": std::array<int,X> Y;
TEST_CASE(varid_templateParameterFunctionPointer); // #11050
TEST_CASE(varid_templateUsing); // #5781 #7273
TEST_CASE(varid_templateSpecializationFinal);
TEST_CASE(varid_not_template_in_condition); // #7988
TEST_CASE(varid_cppcast); // #6190
TEST_CASE(varid_variadicFunc);
TEST_CASE(varid_typename); // #4644
TEST_CASE(varid_rvalueref);
TEST_CASE(varid_arrayFuncPar); // #5294
TEST_CASE(varid_sizeofPassed); // #5295
TEST_CASE(varid_classInFunction); // #5293
TEST_CASE(varid_pointerToArray); // #2645
TEST_CASE(varid_cpp11initialization); // #4344
TEST_CASE(varid_inheritedMembers); // #4101
TEST_CASE(varid_header); // #6386
TEST_CASE(varid_rangeBasedFor);
TEST_CASE(varid_structinit); // #6406
TEST_CASE(varid_arrayinit); // #7579
TEST_CASE(varid_lambda_arg);
TEST_CASE(varid_lambda_mutable);
TEST_CASE(varid_trailing_return1); // #8889
TEST_CASE(varid_trailing_return2); // #9066
TEST_CASE(varid_trailing_return3); // #11423
TEST_CASE(varid_parameter_pack); // #9383
TEST_CASE(varid_for_auto_cpp17);
TEST_CASE(varid_not); // #9689 'not x'
TEST_CASE(varid_declInIfCondition);
TEST_CASE(varid_globalScope);
TEST_CASE(varid_function_pointer_args);
TEST_CASE(varid_alignas);
TEST_CASE(varidclass1);
TEST_CASE(varidclass2);
TEST_CASE(varidclass3);
TEST_CASE(varidclass4);
TEST_CASE(varidclass5);
TEST_CASE(varidclass6);
TEST_CASE(varidclass7);
TEST_CASE(varidclass8);
TEST_CASE(varidclass9);
TEST_CASE(varidclass10); // variable declaration below usage
TEST_CASE(varidclass11); // variable declaration below usage
TEST_CASE(varidclass12);
TEST_CASE(varidclass13);
TEST_CASE(varidclass14);
TEST_CASE(varidclass15); // initializer list
TEST_CASE(varidclass16); // #4577
TEST_CASE(varidclass17); // #6073
TEST_CASE(varidclass18);
TEST_CASE(varidclass19); // initializer list
TEST_CASE(varidclass20); // #7578: int (*p)[2]
TEST_CASE(varid_classnameshaddowsvariablename); // #3990
TEST_CASE(varid_classnametemplate); // #10221
TEST_CASE(varidenum1);
TEST_CASE(varidenum2);
TEST_CASE(varidenum3);
TEST_CASE(varidenum4);
TEST_CASE(varidenum5);
TEST_CASE(varidenum6); // #9180
TEST_CASE(varidenum7); // #8991
TEST_CASE(varidnamespace1);
TEST_CASE(varidnamespace2);
TEST_CASE(usingNamespace1);
TEST_CASE(usingNamespace2);
TEST_CASE(usingNamespace3);
TEST_CASE(setVarIdStructMembers1);
TEST_CASE(decltype1);
TEST_CASE(decltype2);
TEST_CASE(exprid1);
TEST_CASE(exprid2);
TEST_CASE(exprid3);
TEST_CASE(exprid4);
TEST_CASE(exprid5);
TEST_CASE(exprid6);
TEST_CASE(exprid7);
TEST_CASE(exprid8);
TEST_CASE(exprid9);
TEST_CASE(exprid10);
TEST_CASE(exprid11);
TEST_CASE(exprid12);
TEST_CASE(exprid13);
TEST_CASE(structuredBindings);
}
#define tokenize(...) tokenize_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
std::string tokenize_(const char* file, int line, const char (&code)[size], bool cpp = true, const Settings *s = nullptr) {
const Settings *settings1 = s ? s : &settings;
SimpleTokenizer tokenizer(*settings1, *this);
ASSERT_LOC((tokenizer.tokenize)(code, cpp), file, line);
// result..
Token::stringifyOptions options = Token::stringifyOptions::forDebugVarId();
options.files = false;
return tokenizer.tokens()->stringifyList(options);
}
#define tokenizeHeader(...) tokenizeHeader_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
std::string tokenizeHeader_(const char* file, int line, const char (&code)[size], const char filename[]) {
Tokenizer tokenizer(settings, *this);
std::istringstream istr(code);
ASSERT_LOC(tokenizer.list.createTokens(istr, filename), file, line);
ASSERT_EQUALS(true, tokenizer.simplifyTokens1(""));
// result..
Token::stringifyOptions options = Token::stringifyOptions::forDebugVarId();
options.files = false;
return tokenizer.tokens()->stringifyList(options);
}
#define tokenizeExpr(...) tokenizeExpr_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
std::string tokenizeExpr_(const char* file, int line, const char (&code)[size], const char filename[] = "test.cpp") {
std::vector<std::string> files(1, filename);
Tokenizer tokenizer(settings, *this);
PreprocessorHelper::preprocess(code, files, tokenizer, *this);
ASSERT_LOC(tokenizer.simplifyTokens1(""), file, line);
// result..
Token::stringifyOptions options = Token::stringifyOptions::forDebugExprId();
options.files = false;
return tokenizer.tokens()->stringifyList(options);
}
#define compareVaridsForVariable(...) compareVaridsForVariable_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
std::string compareVaridsForVariable_(const char* file, int line, const char (&code)[size], const char varname[], bool cpp = true) {
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC((tokenizer.tokenize)(code, cpp), file, line);
unsigned int varid = ~0U;
for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) {
if (tok->str() == varname) {
if (varid == ~0U)
varid = tok->varId();
else if (varid != tok->varId())
return std::string("Variable ") + varname + " has different varids:\n" + tokenizer.tokens()->stringifyList(true,true,true,true,false);
}
}
return "same varid";
}
void varid1() {
{
const std::string actual = tokenize(
"static int i = 1;\n"
"void f()\n"
"{\n"
" int i = 2;\n"
" for (int i = 0; i < 10; ++i)\n"
" i = 3;\n"
" i = 4;\n"
"}\n", false);
const char expected[] = "1: static int i@1 = 1 ;\n"
"2: void f ( )\n"
"3: {\n"
"4: int i@2 ; i@2 = 2 ;\n"
"5: for ( int i@3 = 0 ; i@3 < 10 ; ++ i@3 ) {\n"
"6: i@3 = 3 ; }\n"
"7: i@2 = 4 ;\n"
"8: }\n";
ASSERT_EQUALS(expected, actual);
}
{
const std::string actual = tokenize(
"static int i = 1;\n"
"void f()\n"
"{\n"
" int i = 2;\n"
" for (int i = 0; i < 10; ++i)\n"
" {\n"
" i = 3;\n"
" }\n"
" i = 4;\n"
"}\n", false);
const char expected[] = "1: static int i@1 = 1 ;\n"
"2: void f ( )\n"
"3: {\n"
"4: int i@2 ; i@2 = 2 ;\n"
"5: for ( int i@3 = 0 ; i@3 < 10 ; ++ i@3 )\n"
"6: {\n"
"7: i@3 = 3 ;\n"
"8: }\n"
"9: i@2 = 4 ;\n"
"10: }\n";
ASSERT_EQUALS(expected, actual);
}
}
void varid2() {
const std::string actual = tokenize(
"void f()\n"
"{\n"
" struct ABC abc;\n"
" abc.a = 3;\n"
" i = abc.a;\n"
"}\n", false);
const char expected[] = "1: void f ( )\n"
"2: {\n"
"3: struct ABC abc@1 ;\n"
"4: abc@1 . a@2 = 3 ;\n"
"5: i = abc@1 . a@2 ;\n"
"6: }\n";
ASSERT_EQUALS(expected, actual);
}
void varid3() {
const std::string actual = tokenize(
"static char str[4];\n"
"void f()\n"
"{\n"
" char str[10];\n"
" str[0] = 0;\n"
"}\n", false);
const char expected[] = "1: static char str@1 [ 4 ] ;\n"
"2: void f ( )\n"
"3: {\n"
"4: char str@2 [ 10 ] ;\n"
"5: str@2 [ 0 ] = 0 ;\n"
"6: }\n";
ASSERT_EQUALS(expected, actual);
}
void varid4() {
const std::string actual = tokenize(
"void f(const unsigned int a[])\n"
"{\n"
" int i = *(a+10);\n"
"}\n", false);
const char expected[] = "1: void f ( const unsigned int a@1 [ ] )\n"
"2: {\n"
"3: int i@2 ; i@2 = * ( a@1 + 10 ) ;\n"
"4: }\n";
ASSERT_EQUALS(expected, actual);
}
void varid5() {
const std::string actual = tokenize(
"void f()\n"
"{\n"
" int a,b;\n"
"}\n", false);
const char expected[] = "1: void f ( )\n"
"2: {\n"
"3: int a@1 ; int b@2 ;\n"
"4: }\n";
ASSERT_EQUALS(expected, actual);
}
void varid6() {
const std::string actual = tokenize(
"int f(int a, int b)\n"
"{\n"
" return a+b;\n"
"}\n", false);
const char expected[] = "1: int f ( int a@1 , int b@2 )\n"
"2: {\n"
"3: return a@1 + b@2 ;\n"
"4: }\n";
ASSERT_EQUALS(expected, actual);
}
void varid7() {
const std::string actual = tokenize(
"void func() {\n"
" char a[256] = \"test\";\n"
" {\n"
" char b[256] = \"test\";\n"
" }\n"
"}\n", false);
const char expected[] = "1: void func ( ) {\n"
"2: char a@1 [ 256 ] = \"test\" ;\n"
"3: {\n"
"4: char b@2 [ 256 ] = \"test\" ;\n"
"5: }\n"
"6: }\n";
ASSERT_EQUALS(expected, actual);
}
void varidReturn1() {
const std::string actual = tokenize(
"int f()\n"
"{\n"
" int a;\n"
" return a;\n"
"}\n", false);
const char expected[] = "1: int f ( )\n"
"2: {\n"
"3: int a@1 ;\n"
"4: return a@1 ;\n"
"5: }\n";
ASSERT_EQUALS(expected, actual);
}
void varidReturn2() {
const std::string actual = tokenize(
"void foo()\n"
"{\n"
" unsigned long mask = (1UL << size_) - 1;\n"
" return (abits_val_ & mask);\n"
"}\n", false);
const char expected[] = "1: void foo ( )\n"
"2: {\n"
"3: unsigned long mask@1 ; mask@1 = ( 1UL << size_ ) - 1 ;\n"
"4: return ( abits_val_ & mask@1 ) ;\n"
"5: }\n";
ASSERT_EQUALS(expected, actual);
}
void varid8() {
const std::string actual = tokenize(
"void func()\n"
"{\n"
" std::string str(\"test\");\n"
" str.clear();\n"
"}");
const char expected[] = "1: void func ( )\n"
"2: {\n"
"3: std :: string str@1 ( \"test\" ) ;\n"
"4: str@1 . clear ( ) ;\n"
"5: }\n";
ASSERT_EQUALS(expected, actual);
}
void varid9() {
const std::string actual = tokenize(
"typedef int INT32;\n", false);
const char expected[] = "1: ;\n";
ASSERT_EQUALS(expected, actual);
}
void varid10() {
const std::string actual = tokenize(
"void foo()\n"
"{\n"
" int abc;\n"
" struct abc abc1;\n"
"}", false);
const char expected[] = "1: void foo ( )\n"
"2: {\n"
"3: int abc@1 ;\n"
"4: struct abc abc1@2 ;\n"
"5: }\n";
ASSERT_EQUALS(expected, actual);
}
void varid11() {
const std::string actual = tokenize("class Foo;");
const char expected[] = "1: class Foo ;\n";
ASSERT_EQUALS(expected, actual);
}
void varid12() {
const std::string actual = tokenize(
"static void a()\n"
"{\n"
" class Foo *foo;\n"
"}");
const char expected[] = "1: static void a ( )\n"
"2: {\n"
"3: class Foo * foo@1 ;\n"
"4: }\n";
ASSERT_EQUALS(expected, actual);
}
void varid13() {
const std::string actual = tokenize(
"void f()\n"
"{\n"
" int a; int b;\n"
" a = a;\n"
"}\n", false);
const char expected[] = "1: void f ( )\n"
"2: {\n"
"3: int a@1 ; int b@2 ;\n"
"4: a@1 = a@1 ;\n"
"5: }\n";
ASSERT_EQUALS(expected, actual);
}
void varid14() {
// Overloaded operator*
const std::string actual = tokenize(
"void foo()\n"
"{\n"
"A a;\n"
"B b;\n"
"b * a;\n"
"}", false);
const char expected[] = "1: void foo ( )\n"
"2: {\n"
"3: A a@1 ;\n"
"4: B b@2 ;\n"
"5: b@2 * a@1 ;\n"
"6: }\n";
ASSERT_EQUALS(expected, actual);
}
void varid15() {
{
const std::string actual = tokenize(
"struct S {\n"
" struct T {\n"
" } t;\n"
"} s;", false);
const char expected[] = "1: struct S {\n"
"2: struct T {\n"
"3: } ; struct T t@1 ;\n"
"4: } ; struct S s@2 ;\n";
ASSERT_EQUALS(expected, actual);
}
{
const std::string actual = tokenize(
"struct S {\n"
" struct T {\n"
" } t;\n"
"};", false);
const char expected[] = "1: struct S {\n"
"2: struct T {\n"
"3: } ; struct T t@1 ;\n"
"4: } ;\n";
ASSERT_EQUALS(expected, actual);
}
}
void varid16() {
const char code[] ="void foo()\n"
"{\n"
" int x = 1;\n"
" y = (z * x);\n"
"}\n";
const char expected[] = "1: void foo ( )\n"
"2: {\n"
"3: int x@1 ; x@1 = 1 ;\n"
"4: y = z * x@1 ;\n"
"5: }\n";
ASSERT_EQUALS(expected, tokenize(code, false));
}
void varid17() { // ticket #1810
const char code[] ="char foo()\n"
"{\n"
" char c('c');\n"
" return c;\n"
"}\n";
const char expected[] = "1: char foo ( )\n"
"2: {\n"
"3: char c@1 ( 'c' ) ;\n"
"4: return c@1 ;\n"
"5: }\n";
ASSERT_EQUALS(expected, tokenize(code, false));
}
void varid18() {
const char code[] ="char foo(char c)\n"
"{\n"
" bar::c = c;\n"
"}\n";
const char expected[] = "1: char foo ( char c@1 )\n"
"2: {\n"
"3: bar :: c = c@1 ;\n"
"4: }\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void varid19() {
const char code[] ="void foo()\n"
"{\n"
" std::pair<std::vector<double>, int> x;\n"
"}\n";
const char expected[] = "1: void foo ( )\n"
"2: {\n"
"3: std :: pair < std :: vector < double > , int > x@1 ;\n"
"4: }\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void varid20() {
const char code[] ="void foo()\n"
"{\n"
" pair<vector<int>, vector<double> > x;\n"
"}\n";
const char expected[] = "1: void foo ( )\n"
"2: {\n"
"3: pair < vector < int > , vector < double > > x@1 ;\n"
"4: }\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void varid24() {
const char code[] ="class foo()\n"
"{\n"
"public:\n"
" ;\n"
"private:\n"
" static int i;\n"
"};\n";
const char expected[] = "1: class foo ( )\n"
"2: {\n"
"3: public:\n"
"4: ;\n"
"5: private:\n"
"6: static int i@1 ;\n"
"7: } ;\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void varid25() {
const char code[] ="class foo()\n"
"{\n"
"public:\n"
" ;\n"
"private:\n"
" mutable int i;\n"
"};\n";
const char expected[] = "1: class foo ( )\n"
"2: {\n"
"3: public:\n"
"4: ;\n"
"5: private:\n"
"6: mutable int i@1 ;\n"
"7: } ;\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void varid26() {
const char code[] ="list<int (*)()> functions;\n";
const char expected[] = "1: list < int ( * ) ( ) > functions@1 ;\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void varid27() {
const char code[] ="int fooled_ya;\n"
"fooled_ya::iterator iter;\n";
const char expected[] = "1: int fooled_ya@1 ;\n"
"2: fooled_ya :: iterator iter@2 ;\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void varid28() { // ticket #2630 (segmentation fault)
ASSERT_THROW_INTERNAL(tokenize("template <typedef A>\n"), SYNTAX);
}
void varid29() {
const char code[] ="class A {\n"
" B<C<1>,1> b;\n"
"};\n";
const char expected[] = "1: class A {\n"
"2: B < C < 1 > , 1 > b@1 ;\n"
"3: } ;\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void varid30() { // ticket #2614
const char code1[] = "void f(EventPtr *eventP, ActionPtr **actionsP)\n"
"{\n"
" EventPtr event = *eventP;\n"
" *actionsP = &event->actions;\n"
"}\n";
const char expected1[] = "1: void f ( EventPtr * eventP@1 , ActionPtr * * actionsP@2 )\n"
"2: {\n"
"3: EventPtr event@3 ; event@3 = * eventP@1 ;\n"
"4: * actionsP@2 = & event@3 . actions@4 ;\n"
"5: }\n";
ASSERT_EQUALS(expected1, tokenize(code1, false));
const char code2[] = "void f(int b, int c) {\n"
" x(a*b*c,10);\n"
"}\n";
const char expected2[] = "1: void f ( int b@1 , int c@2 ) {\n"
"2: x ( a * b@1 * c@2 , 10 ) ;\n"
"3: }\n";
ASSERT_EQUALS(expected2, tokenize(code2, false));
const char code3[] = "class Nullpointer : public ExecutionPath\n"
" {\n"
" Nullpointer(Check *c, const unsigned int id, const std::string &name)\n"
" : ExecutionPath(c, id)\n"
" {\n"
" }\n"
"};\n";
const char expected3[] = "1: class Nullpointer : public ExecutionPath\n"
"2: {\n"
"3: Nullpointer ( Check * c@1 , const unsigned int id@2 , const std :: string & name@3 )\n"
"4: : ExecutionPath ( c@1 , id@2 )\n"
"5: {\n"
"6: }\n"
"7: } ;\n";
ASSERT_EQUALS(expected3, tokenize(code3));
}
void varid34() { // ticket #2825
const char code[] ="class Fred : public B1, public B2\n"
"{\n"
"public:\n"
" Fred() { a = 0; }\n"
"private:\n"
" int a;\n"
"};\n";
const char expected[] = "1: class Fred : public B1 , public B2\n"
"2: {\n"
"3: public:\n"
"4: Fred ( ) { a@1 = 0 ; }\n"
"5: private:\n"
"6: int a@1 ;\n"
"7: } ;\n";
ASSERT_EQUALS(expected, tokenize(code));
ASSERT_EQUALS("", errout_str());
}
void varid35() { // function declaration inside function body
// #2937
const char code[] ="int foo() {\n"
" int f(x);\n"
" return f;\n"
"}\n";
const char expected[] = "1: int foo ( ) {\n"
"2: int f@1 ( x ) ;\n"
"3: return f@1 ;\n"
"4: }\n";
ASSERT_EQUALS(expected, tokenize(code));
// #4627
const char code2[] = "void f() {\n"
" int *p;\n"
" void bar(int *p);\n"
"}";
const char expected2[] = "1: void f ( ) {\n"
"2: int * p@1 ;\n"
"3: void bar ( int * p ) ;\n"
"4: }\n";
ASSERT_EQUALS(expected2, tokenize(code2));
// #7740
const char code3[] = "Float f(float scale) {\n"
" return Float(val * scale);\n"
"}\n";
const char expected3[] = "1: Float f ( float scale@1 ) {\n"
"2: return Float ( val * scale@1 ) ;\n"
"3: }\n";
ASSERT_EQUALS(expected3, tokenize(code3));
}
void varid36() { // ticket #2980 (segmentation fault)
const char code[] ="#elif A\n"
"A,a<b<x0\n";
(void)tokenize(code);
ASSERT_EQUALS("", errout_str());
}
void varid37() {
{
const char code[] = "void blah() {"
" Bar bar(*x);"
"}";
ASSERT_EQUALS("1: void blah ( ) { Bar bar@1 ( * x ) ; }\n",
tokenize(code));
}
{
const char code[] = "void blah() {"
" Bar bar(&x);"
"}";
ASSERT_EQUALS("1: void blah ( ) { Bar bar@1 ( & x ) ; }\n",
tokenize(code));
}
}
void varid38() {
const char code[] = "FOO class C;\n";
ASSERT_EQUALS("1: FOO class C ;\n",
tokenize(code));
}
void varid39() {
// const..
{
const char code[] = "void f(FOO::BAR const);\n";
ASSERT_EQUALS("1: void f ( const FOO :: BAR ) ;\n",
tokenize(code));
}
{
const char code[] = "static int const SZ = 22;\n";
ASSERT_EQUALS("1: static const int SZ@1 = 22 ;\n",
tokenize(code, false));
}
}
void varid40() {
const char code[] ="extern \"C\" int (*a())();";
ASSERT_EQUALS("1: int * a ( ) ;\n",
tokenize(code));
}
void varid41() {
const char code1[] = "union evt; void f(const evt & event);";
ASSERT_EQUALS("1: union evt ; void f ( const evt & event@1 ) ;\n",
tokenize(code1));
ASSERT_THROW_INTERNAL(tokenize(code1, false), SYNTAX);
const char code2[] = "struct evt; void f(const evt & event);";
ASSERT_EQUALS("1: struct evt ; void f ( const evt & event@1 ) ;\n",
tokenize(code2));
ASSERT_THROW_INTERNAL(tokenize(code2, false), SYNTAX);
}
void varid42() {
const char code[] ="namespace fruit { struct banana {}; };\n"
"class Fred {\n"
"public:\n"
" struct fruit::banana Bananas[25];\n"
"};";
ASSERT_EQUALS("1: namespace fruit { struct banana { } ; } ;\n"
"2: class Fred {\n"
"3: public:\n"
"4: struct fruit :: banana Bananas@1 [ 25 ] ;\n"
"5: } ;\n",
tokenize(code));
}
void varid43() {
const char code[] ="int main(int flag) { if(a & flag) { return 1; } }";
ASSERT_EQUALS("1: int main ( int flag@1 ) { if ( a & flag@1 ) { return 1 ; } }\n",
tokenize(code, false));
}
void varid44() {
const char code[] ="class A:public B,public C,public D {};";
ASSERT_EQUALS("1: class A : public B , public C , public D { } ;\n",
tokenize(code));
}
void varid45() { // #3466
const char code[] ="void foo() { B b(this); A a(this, b); }";
ASSERT_EQUALS("1: void foo ( ) { B b@1 ( this ) ; A a@2 ( this , b@1 ) ; }\n",
tokenize(code));
}
void varid46() { // #3756
const char code[] ="void foo() { int t; x = (struct t *)malloc(); f(t); }";
ASSERT_EQUALS("1: void foo ( ) { int t@1 ; x = ( struct t * ) malloc ( ) ; f ( t@1 ) ; }\n",
tokenize(code, false));
}
void varid47() { // function parameters
// #3768
{
const char code[] ="void f(std::string &string, std::string &len) {}";
ASSERT_EQUALS("1: void f ( std :: string & string@1 , std :: string & len@2 ) { }\n",
tokenize(code, true));
}
// #4729
{
const char code[] = "int x;\n"
"void a(int x);\n"
"void b() { x = 0; }\n";
ASSERT_EQUALS("1: int x@1 ;\n"
"2: void a ( int x@2 ) ;\n"
"3: void b ( ) { x@1 = 0 ; }\n",
tokenize(code));
}
}
void varid48() { // #3785 - return (a*b)
const char code[] ="int X::f(int b) const { return(a*b); }";
ASSERT_EQUALS("1: int X :: f ( int b@1 ) const { return ( a * b@1 ) ; }\n",
tokenize(code));
}
void varid49() { // #3799 - void f(std::vector<int>)
const char code[] ="void f(std::vector<int>)";
ASSERT_EQUALS("1: void f ( std :: vector < int > )\n",
tokenize(code, true));
}
void varid50() { // #3760 - explicit
const char code[] ="class A { explicit A(const A&); };";
ASSERT_EQUALS("1: class A { explicit A ( const A & ) ; } ;\n",
tokenize(code, true));
}
void varid51() { // don't set varid on template function
const char code[] ="T t; t.x<0>();";
ASSERT_EQUALS("1: T t@1 ; t@1 . x < 0 > ( ) ;\n",
tokenize(code, true));
}
void varid52() {
const char code[] ="A<B<C>::D> e;\n"
"B< C<> > b[10];\n"
"B<C<>> c[10];";
ASSERT_EQUALS("1: A < B < C > :: D > e@1 ;\n"
"2: B < C < > > b@2 [ 10 ] ;\n"
"3: B < C < > > c@3 [ 10 ] ;\n",
tokenize(code, true));
}
void varid53() { // #4172 - Template instantiation: T<&functionName> list[4];
ASSERT_EQUALS("1: A < & f > list@1 [ 4 ] ;\n",
tokenize("A<&f> list[4];", true));
}
void varid54() { // hang
// Original source code: libgc
(void)tokenize("STATIC ptr_t GC_approx_sp(void) { word sp; sp = (word)&sp; return((ptr_t)sp); }");
}
void varid55() { // Ticket #5868
const char code[] = "typedef struct foo {} foo; "
"void bar1(struct foo foo) {} "
"void baz1(foo foo) {} "
"void bar2(struct foo& foo) {} "
"void baz2(foo& foo) {} "
"void bar3(struct foo* foo) {} "
"void baz3(foo* foo) {}";
const char expected[] = "1: "
"struct foo { } ; "
"void bar1 ( struct foo foo@1 ) { } "
"void baz1 ( struct foo foo@2 ) { } "
"void bar2 ( struct foo & foo@3 ) { } "
"void baz2 ( struct foo & foo@4 ) { } "
"void bar3 ( struct foo * foo@5 ) { } "
"void baz3 ( struct foo * foo@6 ) { }\n";
ASSERT_EQUALS(expected, tokenize(code, true));
}
void varid56() { // Ticket #6548 - function with a throw()
const char code1[] = "void fred(int x) throw() {}"
"void wilma() { x++; }";
const char expected1[] = "1: "
"void fred ( int x@1 ) throw ( ) { } "
"void wilma ( ) { x ++ ; }\n";
ASSERT_EQUALS(expected1, tokenize(code1, true));
const char code2[] = "void fred(int x) const throw(EXCEPT) {}"
"void wilma() { x++; }";
const char expected2[] = "1: "
"void fred ( int x@1 ) const throw ( EXCEPT ) { } "
"void wilma ( ) { x ++ ; }\n";
ASSERT_EQUALS(expected2, tokenize(code2, true));
const char code3[] = "void fred(int x) throw() ABCD {}"
"void wilma() { x++; }";
const char expected3[] = "1: "
"void fred ( int x@1 ) throw ( ) { } "
"void wilma ( ) { x ++ ; }\n";
ASSERT_EQUALS(expected3, tokenize(code3, true));
const char code4[] = "void fred(int x) noexcept() {}"
"void wilma() { x++; }";
const char expected4[] = "1: "
"void fred ( int x@1 ) noexcept ( ) { } "
"void wilma ( ) { x ++ ; }\n";
ASSERT_EQUALS(expected4, tokenize(code4, true));
const char code5[] = "void fred(int x) noexcept {}"
"void wilma() { x++; }";
const char expected5[] = "1: "
"void fred ( int x@1 ) noexcept ( true ) { } "
"void wilma ( ) { x ++ ; }\n";
ASSERT_EQUALS(expected5, tokenize(code5, true));
const char code6[] = "void fred(int x) noexcept ( false ) {}"
"void wilma() { x++; }";
const char expected6[] = "1: "
"void fred ( int x@1 ) noexcept ( false ) { } "
"void wilma ( ) { x ++ ; }\n";
ASSERT_EQUALS(expected6, tokenize(code6, true));
}
void varid57() { // #6636: new scope by {}
const char code1[] = "void SmoothPath() {\n"
" {\n" // new scope
" float dfx = (p2p0.x > 0.0f)?\n"
" ((n0->xmax() * SQUARE_SIZE) - p0.x):\n"
" ((n0->xmin() * SQUARE_SIZE) - p0.x);\n"
" float tx = dfx / dx;\n"
" if (hEdge) {\n"
" }\n"
" if (vEdge) {\n"
" pi.z = tx;\n"
" }\n"
" }\n"
"}\n";
const char expected1[] = "1: void SmoothPath ( ) {\n"
"2:\n"
"3: float dfx@1 ; dfx@1 = ( p2p0 . x > 0.0f ) ?\n"
"4: ( ( n0 . xmax ( ) * SQUARE_SIZE ) - p0 . x ) :\n"
"5: ( ( n0 . xmin ( ) * SQUARE_SIZE ) - p0 . x ) ;\n"
"6: float tx@2 ; tx@2 = dfx@1 / dx ;\n"
"7: if ( hEdge ) {\n"
"8: }\n"
"9: if ( vEdge ) {\n"
"10: pi . z = tx@2 ;\n"
"11: }\n"
"12:\n"
"13: }\n";
ASSERT_EQUALS(expected1, tokenize(code1, true));
}
void varid58() { // #6638: for loop in for condition
const char code1[] = "void f() {\n"
" for (int i;\n"
" ({for(int i;i;++i){i++;}i++;}),i;\n"
" ({for(int i;i;++i){i++;}i++;}),i++) {\n"
" i++;\n"
" }\n"
"}\n";
const char expected1[] = "1: void f ( ) {\n"
"2: for ( int i@1 ;\n"
"3: ( { for ( int i@2 ; i@2 ; ++ i@2 ) { i@2 ++ ; } i@1 ++ ; } ) , i@1 ;\n"
"4: ( { for ( int i@3 ; i@3 ; ++ i@3 ) { i@3 ++ ; } i@1 ++ ; } ) , i@1 ++ ) {\n"
"5: i@1 ++ ;\n"
"6: }\n"
"7: }\n";
ASSERT_EQUALS(expected1, tokenize(code1, true));
}
void varid59() { // #6696
const char code[] = "class DLLSYM B;\n"
"struct B {\n"
" ~B() {}\n"
"};";
const char expected[] = "1: class DLLSYM B@1 ;\n" // In this line, we cannot really do better...
"2: struct B {\n"
"3: ~ B@1 ( ) { }\n" // ...but here we could
"4: } ;\n";
const char wanted[] = "1: class DLLSYM B@1 ;\n"
"2: struct B {\n"
"3: ~ B ( ) { }\n"
"4: } ;\n";
TODO_ASSERT_EQUALS(wanted, expected, tokenize(code, true));
}
void varid60() { // #7267 - cast
ASSERT_EQUALS("1: a = ( x y ) 10 ;\n",
tokenize("a=(x y)10;"));
}
void varid61() {
const char code[] = "void foo(int b) {\n"
" void bar(int a, int b) {}\n"
"}";
const char expected[] = "1: void foo ( int b@1 ) {\n"
"2: void bar ( int a@2 , int b@3 ) { }\n"
"3: }\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void varid62() {
const char code[] = "void bar(int,int);\n"
"void f() {\n"
" for (size_t c = 0; c < 42; ++c) {\n"
" int x;\n"
" bar(r, r * x);\n"
" }\n"
"}";
// Ensure that there is only one variable id for "x"
ASSERT_EQUALS("same varid", compareVaridsForVariable(code, "x"));
}
void varid63() {
const char code[] = "void f(boost::optional<int> const& x) {}";
const char expected[] = "1: void f ( const boost :: optional < int > & x@1 ) { }\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void varid64() {
const char code[] = "extern const char (*x[256]);";
const char expected[] = "1: extern const char ( * x@1 [ 256 ] ) ;\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void varid65() { // #10936
{
const char code[] = "extern int (*p);";
const char expected[] = "1: extern int ( * p@1 ) ;\n";
ASSERT_EQUALS(expected, tokenize(code));
}
{
const char code[] = "extern int (i);";
const char expected[] = "1: extern int ( i@1 ) ;\n";
ASSERT_EQUALS(expected, tokenize(code));
}
{
const char code[] = "int (*p);";
const char expected[] = "1: int ( * p@1 ) ;\n";
ASSERT_EQUALS(expected, tokenize(code));
}
{
const char code[] = "int (i);";
const char expected[] = "1: int ( i@1 ) ;\n";
ASSERT_EQUALS(expected, tokenize(code));
}
}
void varid66() {
{
const char code[] = "std::string g();\n"
"const std::string s(g() + \"abc\");\n";
const char expected[] = "1: std :: string g ( ) ;\n"
"2: const std :: string s@1 ( g ( ) + \"abc\" ) ;\n";
ASSERT_EQUALS(expected, tokenize(code));
}
{
const char code[] = "enum E {};\n"
"typedef E(*fp_t)();\n"
"E f(fp_t fp);\n";
const char expected[] = "1: enum E { } ;\n"
"2:\n"
"3: E f ( E ( * fp@1 ) ( ) ) ;\n";
ASSERT_EQUALS(expected, tokenize(code));
}
}
void varid67() { // #11711
const char code1[] = "int *x;\n"
"_Generic(*x, int: foo, default: bar)();";
const char expected1[] = "1: int * x@1 ;\n"
"2: _Generic ( * x@1 , int : foo , default : bar ) ( ) ;\n";
ASSERT_EQUALS(expected1, tokenize(code1, false));
}
void varid68() { // #11740
const char code1[] = "struct S {};\n"
"char* str_chars(struct S* s);\n"
"void f(struct S strOut) {\n"
" switch (str_chars(&strOut)[0]) {}\n"
"}";
const char expected1[] = "1: struct S { } ;\n"
"2: char * str_chars ( struct S * s@1 ) ;\n"
"3: void f ( struct S strOut@2 ) {\n"
"4: switch ( str_chars ( & strOut@2 ) [ 0 ] ) { }\n"
"5: }\n";
ASSERT_EQUALS(expected1, tokenize(code1, false));
ASSERT_EQUALS(expected1, tokenize(code1, true));
}
void varid69() {
const char code1[] = "void f() {\n"
" auto g = [](int&, int& r, int i) {};\n"
"}";
const char expected1[] = "1: void f ( ) {\n"
"2: auto g@1 ; g@1 = [ ] ( int & , int & r@2 , int i@3 ) { } ;\n"
"3: }\n";
ASSERT_EQUALS(expected1, tokenize(code1, true));
}
void varid70() {
// isFunctionHead
const char code1[] = "int x = 1 ? (1 << 0) : 0;\n"
"void foo(bool init);\n"
"void init();\n";
const char expected1[] = "1: int x@1 ; x@1 = 1 ? ( 1 << 0 ) : 0 ;\n"
"2: void foo ( bool init@2 ) ;\n"
"3: void init ( ) ;\n";
ASSERT_EQUALS(expected1, tokenize(code1, true));
const char code2[] = "int x = 1 ? f(1 << 0) : 0;\n"
"void foo(bool init);\n"
"void init();\n";
const char expected2[] = "1: int x@1 ; x@1 = 1 ? f ( 1 << 0 ) : 0 ;\n"
"2: void foo ( bool init@2 ) ;\n"
"3: void init ( ) ;\n";
ASSERT_EQUALS(expected2, tokenize(code2, true));
const char code3[] = "extern void (*arr[10])(uint32_t some);\n";
const char expected3[] = "1: extern void ( * arr@1 [ 10 ] ) ( uint32_t some@2 ) ;\n";
ASSERT_EQUALS(expected3, tokenize(code3, true));
const char code4[] = "_Static_assert(sizeof((struct S){0}.i) == 4);\n"; // #12729
const char expected4[] = "1: _Static_assert ( sizeof ( ( struct S ) { 0 } . i ) == 4 ) ;\n";
ASSERT_EQUALS(expected4, tokenize(code4, false));
}
void varid71() {
const char code[] = "namespace myspace {\n"
"\n"
"template <typename T>\n"
"class CounterTest {\n"
"public:\n"
" CounterTest(T _obj);\n"
" template <typename T2>\n"
" CounterTest(const CounterTest<T2>& ptr);\n"
" T obj;\n"
" int count;\n"
"};\n"
"\n"
"template <typename T>\n"
"CounterTest<T>::CounterTest(T _obj) : obj(_obj) {\n"
" count = 0;\n"
"}\n"
"\n"
"template <typename T>\n"
"template <typename T2>\n"
"CounterTest<T>::CounterTest(const CounterTest<T2>& p) : obj(0) {\n"
" count = p.count;\n"
"}\n"
"\n"
"}\n"
"\n"
"using namespace myspace;\n"
"CounterTest<int> myobj(0);\n";
const char expected[] = "1: namespace myspace {\n"
"2:\n"
"3: class CounterTest<int> ;\n"
"4:\n"
"|\n"
"17:\n"
"18: template < typename T >\n"
"19: template < typename T2 >\n"
"20: CounterTest < T > :: CounterTest ( const CounterTest < T2 > & p@1 ) : obj ( 0 ) {\n"
"21: count = p@1 . count@2 ;\n"
"22: }\n"
"23:\n"
"24: }\n"
"25:\n"
"26: using namespace myspace ;\n"
"27: myspace :: CounterTest<int> myobj@3 ( 0 ) ;\n"
"4: class myspace :: CounterTest<int> {\n"
"5: public:\n"
"6: CounterTest<int> ( int _obj@4 ) ;\n"
"7: template < typename T2 >\n"
"8: CounterTest<int> ( const myspace :: CounterTest < T2 > & ptr@5 ) ;\n"
"9: int obj@6 ;\n"
"10: int count@7 ;\n"
"11: } ;\n"
"12:\n"
"13:\n"
"14: myspace :: CounterTest<int> :: CounterTest<int> ( int _obj@8 ) : obj@6 ( _obj@8 ) {\n"
"15: count@7 = 0 ;\n"
"16: }\n"
"17:\n"
"18:\n"
"19:\n"
"20: myspace :: CounterTest<int> :: CounterTest<int> ( const myspace :: CounterTest < T2 > & p@9 ) : obj@6 ( 0 ) {\n"
"21: count@7 = p@9 . count@10 ;\n"
"22: }\n";
ASSERT_EQUALS(expected, tokenize(code, true));
}
void varid_for_1() {
const char code[] = "void foo(int a, int b) {\n"
" for (int a=1,b=2;;) {}\n"
"}";
const char expected[] = "1: void foo ( int a@1 , int b@2 ) {\n"
"2: for ( int a@3 = 1 , b@4 = 2 ; ; ) { }\n"
"3: }\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void varid_for_2() {
const char code[] = "void foo(int a, int b) {\n"
" for (int a=f(x,y,z),b=2;;) {}\n"
"}";
const char expected[] = "1: void foo ( int a@1 , int b@2 ) {\n"
"2: for ( int a@3 = f ( x , y , z ) , b@4 = 2 ; ; ) { }\n"
"3: }\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void varid_cpp_keywords_in_c_code() {
const char code[] = "void f() {\n"
" delete d;\n"
" throw t;\n"
"}";
const char expected[] = "1: void f ( ) {\n"
"2: delete d@1 ;\n"
"3: throw t@2 ;\n"
"4: }\n";
ASSERT_EQUALS(expected, tokenize(code, false));
}
void varid_cpp_keywords_in_c_code2() { // #5373
const char code[] = "int clear_extent_bit(struct extent_io_tree *tree, u64 start, u64 end, "
"unsigned long bits, int wake, int delete, struct extent_state **cached_state, "
"gfp_t mask) {\n"
" struct extent_state *state;\n"
"}"
"int clear_extent_dirty() {\n"
" return clear_extent_bit(tree, start, end, EXTENT_DIRTY | EXTENT_DELALLOC | "
" EXTENT_DO_ACCOUNTING, 0, 0, NULL, mask);\n"
"}";
ASSERT_NO_THROW(tokenize(code, false));
}
void varid_cpp_keywords_in_c_code3() { // #12120
const char code[] = "const struct class *p;";
const char expected[] = "1: const struct class * p@1 ;\n";
ASSERT_EQUALS(expected, tokenize(code, false));
}
void varidFunctionCall1() {
const char code[] ="void f() {\n"
" int x;\n"
" x = a(y*x,10);\n"
"}";
const char expected[] = "1: void f ( ) {\n"
"2: int x@1 ;\n"
"3: x@1 = a ( y * x@1 , 10 ) ;\n"
"4: }\n";
ASSERT_EQUALS(expected, tokenize(code, false));
}
void varidFunctionCall2() {
// #2491
const char code[] ="void f(int b) {\n"
" x(a*b,10);\n"
"}";
const std::string expected1("1: void f ( int b@1 ) {\n"
"2: x ( a * b");
const std::string expected2(" , 10 ) ;\n"
"3: }\n");
ASSERT_EQUALS(expected1+"@1"+expected2, tokenize(code, false));
}
void varidFunctionCall3() {
// Ticket #2339
const char code[] ="void f() {\n"
" int a = 0;\n"
" int b = c - (foo::bar * a);\n"
"}";
const char expected[] = "1: void f ( ) {\n"
"2: int a@1 ; a@1 = 0 ;\n"
"3: int b@2 ; b@2 = c - ( foo :: bar * a@1 ) ;\n"
"4: }\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void varidFunctionCall4() {
// Ticket #3280
const char code1[] = "void f() { int x; fun(a,b*x); }";
ASSERT_EQUALS("1: void f ( ) { int x@1 ; fun ( a , b * x@1 ) ; }\n",
tokenize(code1, false));
const char code2[] = "void f(int a) { int x; fun(a,b*x); }";
ASSERT_EQUALS("1: void f ( int a@1 ) { int x@2 ; fun ( a@1 , b * x@2 ) ; }\n",
tokenize(code2, false));
}
void varidFunctionCall5() {
const char code[] = "void foo() { (f(x[2]))(x[2]); }";
ASSERT_EQUALS("1: void foo ( ) { f ( x [ 2 ] ) ( x [ 2 ] ) ; }\n",
tokenize(code, false));
}
void varidStl() {
const std::string actual = tokenize(
"list<int> ints;\n"
"list<int>::iterator it;\n"
"std::vector<std::string> dirs;\n"
"std::map<int, int> coords;\n"
"std::tr1::unordered_map<int, int> xy;\n"
"std::list<boost::wave::token_id> tokens;\n"
"static std::vector<CvsProcess*> ex1;\n"
"extern std::vector<CvsProcess*> ex2;\n"
"std::map<int, 1> m;");
const char expected[] = "1: list < int > ints@1 ;\n"
"2: list < int > :: iterator it@2 ;\n"
"3: std :: vector < std :: string > dirs@3 ;\n"
"4: std :: map < int , int > coords@4 ;\n"
"5: std :: tr1 :: unordered_map < int , int > xy@5 ;\n"
"6: std :: list < boost :: wave :: token_id > tokens@6 ;\n"
"7: static std :: vector < CvsProcess * > ex1@7 ;\n"
"8: extern std :: vector < CvsProcess * > ex2@8 ;\n"
"9: std :: map < int , 1 > m@9 ;\n";
ASSERT_EQUALS(expected, actual);
}
void varidStl2() {
const std::string actual = tokenize("std::bitset<static_cast<int>(2)> x;");
const char expected[] = "1: std :: bitset < static_cast < int > ( 2 ) > x@1 ;\n";
ASSERT_EQUALS(expected, actual);
}
void varid_newauto() {
ASSERT_EQUALS("1: void f ( ) { const new auto ( 0 ) ; }\n",
tokenize("void f(){new const auto(0);}"));
}
void varid_delete() {
const std::string actual = tokenize(
"void f()\n"
"{\n"
" int *a;\n"
" delete a;\n"
"}");
const char expected[] = "1: void f ( )\n"
"2: {\n"
"3: int * a@1 ;\n"
"4: delete a@1 ;\n"
"5: }\n";
ASSERT_EQUALS(expected, actual);
}
void varid_functions() {
{
const std::string actual = tokenize(
"void f();\n"
"void f(){}\n", false);
const char expected[] = "1: void f ( ) ;\n"
"2: void f ( ) { }\n";
ASSERT_EQUALS(expected, actual);
}
{
const std::string actual = tokenize(
"A f(3);\n"
"A f2(true);\n"
"A g();\n"
"A e(int c);\n", false);
const char expected[] = "1: A f@1 ( 3 ) ;\n"
"2: A f2@2 ( true ) ;\n"
"3: A g ( ) ;\n"
"4: A e ( int c@3 ) ;\n";
ASSERT_EQUALS(expected, actual);
}
{
const std::string actual = tokenize(
"void f1(int &p)\n"
"{\n"
" p = 0;\n"
"}\n"
"void f2(std::string &str)\n"
"{\n"
" str.clear();\n"
"}\n"
"void f3(const std::string &s)\n"
"{\n"
" s.size();\n"
"}");
const char expected[] = "1: void f1 ( int & p@1 )\n"
"2: {\n"
"3: p@1 = 0 ;\n"
"4: }\n"
"5: void f2 ( std :: string & str@2 )\n"
"6: {\n"
"7: str@2 . clear ( ) ;\n"
"8: }\n"
"9: void f3 ( const std :: string & s@3 )\n"
"10: {\n"
"11: s@3 . size ( ) ;\n"
"12: }\n";
ASSERT_EQUALS(expected, actual);
}
{
const std::string actual = tokenize("void f(struct foobar);", false);
const char expected[] = "1: void f ( struct foobar ) ;\n";
ASSERT_EQUALS(expected, actual);
}
{
const std::string actual = tokenize("bool f(X x, int=3);", true);
const char expected[] = "1: bool f ( X x@1 , int = 3 ) ;\n";
ASSERT_EQUALS(expected, actual);
}
{
const std::string actual = tokenize("int main() {\n"
" int a[2];\n"
" extern void f(int a[2]);\n"
" f(a);\n"
" a[0] = 0;\n"
"}\n", true);
const char expected[] = "1: int main ( ) {\n"
"2: int a@1 [ 2 ] ;\n"
"3: extern void f ( int a [ 2 ] ) ;\n"
"4: f ( a@1 ) ;\n"
"5: a@1 [ 0 ] = 0 ;\n"
"6: }\n";
ASSERT_EQUALS(expected, actual);
}
{
const std::string actual = tokenize("void f(int n) {\n" // #12537
" int n1;\n"
" void g(int is, int n1);\n"
" n1 = n - 1;\n"
"}\n", true);
const char expected[] = "1: void f ( int n@1 ) {\n"
"2: int n1@2 ;\n"
"3: void g ( int is , int n1 ) ;\n"
"4: n1@2 = n@1 - 1 ;\n"
"5: }\n";
ASSERT_EQUALS(expected, actual);
}
}
void varid_sizeof() {
const char code[] = "x = sizeof(a*b);";
const char expected[] = "1: x = sizeof ( a * b ) ;\n";
ASSERT_EQUALS(expected, tokenize(code, false));
}
void varid_reference_to_containers() {
const std::string actual = tokenize(
"void f()\n"
"{\n"
" std::vector<int> b;\n"
" std::vector<int> &a = b;\n"
" std::vector<int> *c = &b;\n"
"}");
const char expected[] = "1: void f ( )\n"
"2: {\n"
"3: std :: vector < int > b@1 ;\n"
"4: std :: vector < int > & a@2 = b@1 ;\n"
"5: std :: vector < int > * c@3 ; c@3 = & b@1 ;\n"
"6: }\n";
ASSERT_EQUALS(expected, actual);
}
void varid_in_class1() {
{
const std::string actual = tokenize(
"class Foo\n"
"{\n"
"public:\n"
" std::string name1;\n"
" std::string name2;\n"
"};");
const char expected[] = "1: class Foo\n"
"2: {\n"
"3: public:\n"
"4: std :: string name1@1 ;\n"
"5: std :: string name2@2 ;\n"
"6: } ;\n";
ASSERT_EQUALS(expected, actual);
}
{
const std::string actual = tokenize(
"class foo\n"
"{\n"
"public:\n"
" void do_something(const int x, const int y);\n"
" void bar();\n"
"};\n"
"\n"
"void foo::bar()\n"
"{\n"
" POINT pOutput = { 0 , 0 };\n"
" int x = pOutput.x;\n"
" int y = pOutput.y;\n"
"}");
const char expected[] = "1: class foo\n"
"2: {\n"
"3: public:\n"
"4: void do_something ( const int x@1 , const int y@2 ) ;\n"
"5: void bar ( ) ;\n"
"6: } ;\n"
"7:\n"
"8: void foo :: bar ( )\n"
"9: {\n"
"10: POINT pOutput@3 ; pOutput@3 = { 0 , 0 } ;\n"
"11: int x@4 ; x@4 = pOutput@3 . x@5 ;\n"
"12: int y@6 ; y@6 = pOutput@3 . y@7 ;\n"
"13: }\n";
ASSERT_EQUALS(expected, actual);
}
}
void varid_in_class2() {
const std::string actual = tokenize(
"struct Foo {\n"
" int x;\n"
"};\n"
"\n"
"struct Bar {\n"
" Foo foo;\n"
" int x;\n"
" void f();\n"
"};\n"
"\n"
"void Bar::f()\n"
"{\n"
" foo.x = x;\n"
"}");
const char expected[] = "1: struct Foo {\n"
"2: int x@1 ;\n"
"3: } ;\n"
"4:\n"
"5: struct Bar {\n"
"6: Foo foo@2 ;\n"
"7: int x@3 ;\n"
"8: void f ( ) ;\n"
"9: } ;\n"
"10:\n"
"11: void Bar :: f ( )\n"
"12: {\n"
"13: foo@2 . x@4 = x@3 ;\n"
"14: }\n";
ASSERT_EQUALS(expected, actual);
}
void varid_in_class3() {
const char code[] = "class Foo {\n"
" void blah() {\n"
" Bar x(*this);\n" // <- ..
" }\n"
" int x;\n" // <- .. don't assign same varid
"};";
ASSERT_EQUALS("1: class Foo {\n"
"2: void blah ( ) {\n"
"3: Bar x@1 ( * this ) ;\n"
"4: }\n"
"5: int x@2 ;\n"
"6: } ;\n", tokenize(code));
}
void varid_in_class4() {
const char code[] = "class Foo {\n"
"public: class C;\n"
"};";
ASSERT_EQUALS("1: class Foo {\n"
"2: public: class C ;\n"
"3: } ;\n",
tokenize(code));
}
void varid_in_class5() {
const char code[] = "struct Foo {\n"
" std::vector<::X> v;\n"
"}";
ASSERT_EQUALS("1: struct Foo {\n"
"2: std :: vector < :: X > v@1 ;\n"
"3: }\n",
tokenize(code));
}
void varid_in_class6() {
const char code[] = "class A {\n"
" void f(const char *str) const {\n"
" std::stringstream sst;\n"
" sst.str();\n"
" }\n"
"};";
ASSERT_EQUALS("1: class A {\n"
"2: void f ( const char * str@1 ) const {\n"
"3: std :: stringstream sst@2 ;\n"
"4: sst@2 . str ( ) ;\n"
"5: }\n"
"6: } ;\n",
tokenize(code));
}
void varid_in_class7() {
const char code[] = "class A {\n"
" void f() {\n"
" abc.a = 0;\n"
" }\n"
" struct ABC abc;\n"
"};";
ASSERT_EQUALS("1: class A {\n"
"2: void f ( ) {\n"
"3: abc@1 . a@2 = 0 ;\n"
"4: }\n"
"5: struct ABC abc@1 ;\n"
"6: } ;\n",
tokenize(code));
}
void varid_in_class8() { // #3776 - unknown macro
const char code[] = "class A {\n"
" UNKNOWN_MACRO(A)\n"
"private:\n"
" int x;\n"
"};";
ASSERT_EQUALS("1: class A {\n"
"2: UNKNOWN_MACRO ( A )\n"
"3: private:\n"
"4: int x@1 ;\n"
"5: } ;\n",
tokenize(code));
}
void varid_in_class9() { // #4291 - id for variables accessed through 'this'
const char code1[] = "class A {\n"
" int var;\n"
"public:\n"
" void setVar();\n"
"};\n"
"void A::setVar() {\n"
" this->var = var;\n"
"}";
ASSERT_EQUALS("1: class A {\n"
"2: int var@1 ;\n"
"3: public:\n"
"4: void setVar ( ) ;\n"
"5: } ;\n"
"6: void A :: setVar ( ) {\n"
"7: this . var@1 = var@1 ;\n"
"8: }\n",
tokenize(code1));
const char code2[] = "class Foo : public FooBase {\n"
" void Clone(FooBase& g);\n"
" short m_bar;\n"
"};\n"
"void Foo::Clone(FooBase& g) {\n"
" g->m_bar = m_bar;\n"
"}";
ASSERT_EQUALS("1: class Foo : public FooBase {\n"
"2: void Clone ( FooBase & g@1 ) ;\n"
"3: short m_bar@2 ;\n"
"4: } ;\n"
"5: void Foo :: Clone ( FooBase & g@3 ) {\n"
"6: g@3 . m_bar@4 = m_bar@2 ;\n"
"7: }\n",
tokenize(code2)); // #4311
}
void varid_in_class10() {
const char code[] = "class Foo : public FooBase {\n"
" void Clone(FooBase& g);\n"
" short m_bar;\n"
"};\n"
"void Foo::Clone(FooBase& g) {\n"
" ((FooBase)g)->m_bar = m_bar;\n"
"}";
ASSERT_EQUALS("1: class Foo : public FooBase {\n"
"2: void Clone ( FooBase & g@1 ) ;\n"
"3: short m_bar@2 ;\n"
"4: } ;\n"
"5: void Foo :: Clone ( FooBase & g@3 ) {\n"
"6: ( ( FooBase ) g@3 ) . m_bar@4 = m_bar@2 ;\n"
"7: }\n",
tokenize(code));
}
void varid_in_class11() { // #4277 - anonymous union
const char code1[] = "class Foo {\n"
" union { float a; int b; };\n"
" void f() { a=0; }\n"
"};";
ASSERT_EQUALS("1: class Foo {\n"
"2: union { float a@1 ; int b@2 ; } ;\n"
"3: void f ( ) { a@1 = 0 ; }\n"
"4: } ;\n",
tokenize(code1));
const char code2[] = "class Foo {\n"
" void f() { a=0; }\n"
" union { float a; int b; };\n"
"};";
ASSERT_EQUALS("1: class Foo {\n"
"2: void f ( ) { a@1 = 0 ; }\n"
"3: union { float a@1 ; int b@2 ; } ;\n"
"4: } ;\n",
tokenize(code2));
const char code3[] = "void f() {\n"
" union {\n"
" struct {\n"
" char a, b, c, d;\n"
" };\n"
" int abcd;\n"
" };\n"
" g(abcd);\n"
" h(a, b, c, d);\n"
"}";
ASSERT_EQUALS("1: void f ( ) {\n"
"2: union {\n"
"3: struct {\n"
"4: char a@1 ; char b@2 ; char c@3 ; char d@4 ;\n"
"5: } ;\n"
"6: int abcd@5 ;\n"
"7: } ;\n"
"8: g ( abcd@5 ) ;\n"
"9: h ( a@1 , b@2 , c@3 , d@4 ) ;\n"
"10: }\n",
tokenize(code3));
// #7444
const char code4[] = "class Foo {\n"
" void f(float a) { this->a = a; }\n"
" union { float a; int b; };\n"
"};";
ASSERT_EQUALS("1: class Foo {\n"
"2: void f ( float a@1 ) { this . a@2 = a@1 ; }\n"
"3: union { float a@2 ; int b@3 ; } ;\n"
"4: } ;\n",
tokenize(code4));
}
void varid_in_class12() { // #4637 - method
const char code[] = "class Foo {\n"
"private:\n"
" void f(void);\n"
"};";
ASSERT_EQUALS("1: class Foo {\n"
"2: private:\n"
"3: void f ( ) ;\n"
"4: } ;\n",
tokenize(code));
}
void varid_in_class13() {
const char code1[] = "struct a { char typename; };";
ASSERT_EQUALS("1: struct a { char typename@1 ; } ;\n",
tokenize(code1, false));
ASSERT_EQUALS("1: struct a { char typename ; } ;\n", // not valid C++ code
tokenize(code1, true));
const char code2[] = "struct a { char typename[2]; };";
ASSERT_EQUALS("1: struct a { char typename@1 [ 2 ] ; } ;\n",
tokenize(code2, false));
ASSERT_EQUALS("1: struct a { char typename [ 2 ] ; } ;\n", // not valid C++ code
tokenize(code2, true));
}
void varid_in_class14() {
const char code[] = "class Tokenizer { TokenList list; };\n"
"\n"
"void Tokenizer::f() {\n"
" std::list<int> x;\n" // <- not member variable
" list.do_something();\n" // <- member variable
" Tokenizer::list.do_something();\n" // <- redundant scope info
"}\n";
ASSERT_EQUALS("1: class Tokenizer { TokenList list@1 ; } ;\n"
"2:\n"
"3: void Tokenizer :: f ( ) {\n"
"4: std :: list < int > x@2 ;\n"
"5: list@1 . do_something ( ) ;\n"
"6: Tokenizer :: list@1 . do_something ( ) ;\n"
"7: }\n", tokenize(code, true));
}
void varid_in_class15() { // #5533 - functions
const char code[] = "class Fred {\n"
" void x(int a) const;\n"
" void y() { a=0; }\n" // <- unknown variable
"}\n";
ASSERT_EQUALS("1: class Fred {\n"
"2: void x ( int a@1 ) const ;\n"
"3: void y ( ) { a = 0 ; }\n"
"4: }\n", tokenize(code, true));
}
void varid_in_class16() { // Set varId for inline member functions
{
const char code[] = "class Fred {\n"
" int x;\n"
" void foo(int x) { this->x = x; }\n"
"};\n";
ASSERT_EQUALS("1: class Fred {\n"
"2: int x@1 ;\n"
"3: void foo ( int x@2 ) { this . x@1 = x@2 ; }\n"
"4: } ;\n", tokenize(code, true));
}
{
const char code[] = "class Fred {\n"
" void foo(int x) { this->x = x; }\n"
" int x;\n"
"};\n";
ASSERT_EQUALS("1: class Fred {\n"
"2: void foo ( int x@1 ) { this . x@2 = x@1 ; }\n"
"3: int x@2 ;\n"
"4: } ;\n", tokenize(code, true));
}
{
const char code[] = "class Fred {\n"
" void foo(int x) { (*this).x = x; }\n"
" int x;\n"
"};\n";
ASSERT_EQUALS("1: class Fred {\n"
"2: void foo ( int x@1 ) { ( * this ) . x@2 = x@1 ; }\n"
"3: int x@2 ;\n"
"4: } ;\n", tokenize(code, true));
}
}
void varid_in_class17() { // #6056 - Set no varid for member functions
const char code1[] = "class Fred {\n"
" int method_with_internal(X&);\n"
" int method_with_internal(X*);\n"
" int method_with_internal(int&);\n"
" int method_with_internal(A* b, X&);\n"
" int method_with_internal(X&, A* b);\n"
" int method_with_internal(const B &, int);\n"
" void Set(BAR);\n"
" FOO Set(BAR);\n"
" int method_with_class(B<B> b);\n"
" bool function(std::map<int, int, MYless> & m);\n"
"};";
ASSERT_EQUALS("1: class Fred {\n"
"2: int method_with_internal ( X & ) ;\n"
"3: int method_with_internal ( X * ) ;\n"
"4: int method_with_internal ( int & ) ;\n"
"5: int method_with_internal ( A * b@1 , X & ) ;\n"
"6: int method_with_internal ( X & , A * b@2 ) ;\n"
"7: int method_with_internal ( const B & , int ) ;\n"
"8: void Set ( BAR ) ;\n"
"9: FOO Set ( BAR ) ;\n"
"10: int method_with_class ( B < B > b@3 ) ;\n"
"11: bool function ( std :: map < int , int , MYless > & m@4 ) ;\n"
"12: } ;\n", tokenize(code1, true));
const char code2[] = "int i;\n"
"SomeType someVar1(i, i);\n"
"SomeType someVar2(j, j);\n"
"SomeType someVar3(j, 1);\n"
"SomeType someVar4(new bar);";
ASSERT_EQUALS("1: int i@1 ;\n"
"2: SomeType someVar1@2 ( i@1 , i@1 ) ;\n"
"3: SomeType someVar2 ( j , j ) ;\n" // This one could be a function
"4: SomeType someVar3@3 ( j , 1 ) ;\n"
"5: SomeType someVar4@4 ( new bar ) ;\n", tokenize(code2, true));
}
void varid_in_class18() {
const char code[] = "class A {\n"
" class B;\n"
"};\n"
"class A::B {\n"
" B();\n"
" int* i;\n"
"};\n"
"A::B::B() :\n"
" i(0)\n"
"{}";
ASSERT_EQUALS("1: class A {\n"
"2: class B ;\n"
"3: } ;\n"
"4: class A :: B {\n"
"5: B ( ) ;\n"
"6: int * i@1 ;\n"
"7: } ;\n"
"8: A :: B :: B ( ) :\n"
"9: i@1 ( 0 )\n"
"10: { }\n", tokenize(code, true));
}
void varid_in_class19() {
const char code[] = "class Fred {\n"
" char *str1;\n"
" ~Fred();\n"
"};\n"
"Fred::~Fred() {\n"
" free(str1);\n"
"}";
ASSERT_EQUALS("1: class Fred {\n"
"2: char * str1@1 ;\n"
"3: ~ Fred ( ) ;\n"
"4: } ;\n"
"5: Fred :: ~ Fred ( ) {\n"
"6: free ( str1@1 ) ;\n"
"7: }\n", tokenize(code, true));
}
void varid_in_class20() {
const char code[] = "template<class C> class cacheEntry {\n"
"protected:\n"
" int m_key;\n"
"public:\n"
" cacheEntry();\n"
"};\n"
"\n"
"template<class C> cacheEntry<C>::cacheEntry() : m_key() {}";
ASSERT_EQUALS("1: template < class C > class cacheEntry {\n"
"2: protected:\n"
"3: int m_key@1 ;\n"
"4: public:\n"
"5: cacheEntry ( ) ;\n"
"6: } ;\n"
"7:\n"
"8: template < class C > cacheEntry < C > :: cacheEntry ( ) : m_key@1 ( ) { }\n", tokenize(code, true));
}
void varid_in_class21() {
const char code[] = "template <typename t1,typename t2>\n"
"class A::B {\n"
" B();\n"
" int x;\n"
"};\n"
"\n"
"template <typename t1,typename t2>\n"
"A::B<t1,t2>::B() : x(9) {}";
const char expected[] = "1: template < typename t1 , typename t2 >\n"
"2: class A :: B {\n"
"3: B ( ) ;\n"
"4: int x@1 ;\n"
"5: } ;\n"
"6:\n"
"7: template < typename t1 , typename t2 >\n"
"8: A :: B < t1 , t2 > :: B ( ) : x@1 ( 9 ) { }\n";
ASSERT_EQUALS(expected, tokenize(code, true));
}
void varid_in_class22() {
const char code[] = "struct data {};\n"
" struct S {\n"
" std::vector<data> std;\n"
" void f();\n"
"};\n"
"void S::f() {\n"
" std::vector<data>::const_iterator end = std.end();\n"
" for (std::vector<data>::const_iterator i = std.begin(); i != end; ++i) {}\n"
"}\n";
const char expected[] = "1: struct data { } ;\n"
"2: struct S {\n"
"3: std :: vector < data > std@1 ;\n"
"4: void f ( ) ;\n"
"5: } ;\n"
"6: void S :: f ( ) {\n"
"7: std :: vector < data > :: const_iterator end@2 ; end@2 = std@1 . end ( ) ;\n"
"8: for ( std :: vector < data > :: const_iterator i@3 = std@1 . begin ( ) ; i@3 != end@2 ; ++ i@3 ) { }\n"
"9: }\n";
ASSERT_EQUALS(expected, tokenize(code, true));
}
void varid_in_class23() { // #11293
const char code[] = "struct A {\n"
" struct S {\n"
" bool b;\n"
" };\n"
"};\n"
"struct B : A::S {\n"
" void f() { b = false; }\n"
"};\n";
const char expected[] = "1: struct A {\n"
"2: struct S {\n"
"3: bool b@1 ;\n"
"4: } ;\n"
"5: } ;\n"
"6: struct B : A :: S {\n"
"7: void f ( ) { b@1 = false ; }\n"
"8: } ;\n";
ASSERT_EQUALS(expected, tokenize(code, true));
}
void varid_in_class24() {
const char *expected{};
{
const char code[] = "class A {\n"
" Q_OBJECT\n"
"public:\n"
" using QPtr = QPointer<A>;\n"
"};\n";
expected = "1: class A {\n"
"2: Q_OBJECT\n"
"3: public:\n"
"4:\n"
"5: } ;\n";
ASSERT_EQUALS(expected, tokenize(code, true));
}
{
const char code[] = "class A {\n"
" Q_OBJECT\n"
" using QPtr = QPointer<A>;\n"
"};\n";
expected = "1: class A {\n"
"2: Q_OBJECT\n"
"3:\n"
"4: } ;\n";
ASSERT_EQUALS(expected, tokenize(code, true));
}
}
void varid_in_class25() {
const Settings s = settingsBuilder(settings).library("std.cfg").build();
const char *expected{};
{
const char code[] = "struct F {\n" // #11497
" int i;\n"
" void f(const std::vector<F>&v) {\n"
" if (v.front().i) {}\n"
" }\n"
"};\n";
expected = "1: struct F {\n"
"2: int i@1 ;\n"
"3: void f ( const std :: vector < F > & v@2 ) {\n"
"4: if ( v@2 . front ( ) . i@3 ) { }\n"
"5: }\n"
"6: } ;\n";
ASSERT_EQUALS(expected, tokenize(code, true, &s));
}
{
const char code[] = "struct T { };\n" // 11533
"struct U { T t; };\n"
"std::vector<U*>* g();\n"
"void f() {\n"
" std::vector<U*>* p = g();\n"
" auto t = p->front()->t;\n"
"}\n";
expected = "1: struct T { } ;\n"
"2: struct U { T t@1 ; } ;\n"
"3: std :: vector < U * > * g ( ) ;\n"
"4: void f ( ) {\n"
"5: std :: vector < U * > * p@2 ; p@2 = g ( ) ;\n"
"6: auto t@3 ; t@3 = p@2 . front ( ) . t@4 ;\n"
"7: }\n";
ASSERT_EQUALS(expected, tokenize(code, true, &s));
}
}
void varid_in_class26() {
const char *expected{}; // #11334
const char code[] = "struct S {\n"
" union {\n"
" uint8_t u8[4];\n"
" uint32_t u32;\n"
" };\n"
" void f();\n"
"};\n"
"void S::f() {\n"
" u8[0] = 0;\n"
"}\n";
expected = "1: struct S {\n"
"2: union {\n"
"3: uint8_t u8@1 [ 4 ] ;\n"
"4: uint32_t u32@2 ;\n"
"5: } ;\n"
"6: void f ( ) ;\n"
"7: } ;\n"
"8: void S :: f ( ) {\n"
"9: u8@1 [ 0 ] = 0 ;\n"
"10: }\n";
ASSERT_EQUALS(expected, tokenize(code, true));
}
void varid_in_class27() {
const char code[] = "struct S {\n" // #13291
" int** pp;\n"
" void f() { int x(*pp[0]); }\n"
"};\n";
const char expected[] = "1: struct S {\n"
"2: int * * pp@1 ;\n"
"3: void f ( ) { int x@2 ( * pp@1 [ 0 ] ) ; }\n"
"4: } ;\n";
ASSERT_EQUALS(expected, tokenize(code, true));
}
void varid_namespace_1() { // #7272
const char code[] = "namespace Blah {\n"
" struct foo { int x;};\n"
" struct bar {\n"
" int x;\n"
" union { char y; };\n"
" };\n"
"}";
ASSERT_EQUALS("1: namespace Blah {\n"
"2: struct foo { int x@1 ; } ;\n"
"3: struct bar {\n"
"4: int x@2 ;\n"
"5: union { char y@3 ; } ;\n"
"6: } ;\n"
"7: }\n", tokenize(code, true));
}
void varid_namespace_2() { // #7000
const char code[] = "namespace Ui {\n"
" class C { int X; };\n" // X@1
"}\n"
"\n"
"class C {\n"
" void dostuff();\n"
" int X;\n" // X@2
"};\n"
"\n"
"void C::dostuff() {\n"
" X = 0;\n" // X@2
"}";
const std::string actual = tokenize(code, true);
ASSERT(actual.find("X@2 = 0") != std::string::npos);
}
static std::string getLine(const std::string &code, int lineNumber) {
std::string nr = std::to_string(lineNumber);
const std::string::size_type pos1 = code.find('\n' + nr + ": ");
if (pos1 == std::string::npos)
return "";
const std::string::size_type pos2 = code.find('\n', pos1+1);
if (pos2 == std::string::npos)
return "";
return code.substr(pos1+1, pos2-pos1-1);
}
void varid_namespace_3() { // #8627
const char code[] = "namespace foo {\n"
"struct Bar {\n"
" explicit Bar(int type);\n"
" void f();\n"
" int type;\n" // <- Same varid here ...
"};\n"
"\n"
"Bar::Bar(int type) : type(type) {}\n"
"\n"
"void Bar::f() {\n"
" type = 0;\n" // <- ... and here
"}\n"
"}";
const std::string actual = tokenize(code, true);
ASSERT_EQUALS("5: int type@2 ;", getLine(actual,5));
ASSERT_EQUALS("11: type@2 = 0 ;", getLine(actual,11));
}
void varid_namespace_4() {
const char code[] = "namespace X {\n"
" struct foo { int x;};\n"
" struct bar: public foo {\n"
" void dostuff();\n"
" };\n"
" void bar::dostuff() { int x2 = x * 2; }\n"
"}";
ASSERT_EQUALS("1: namespace X {\n"
"2: struct foo { int x@1 ; } ;\n"
"3: struct bar : public foo {\n"
"4: void dostuff ( ) ;\n"
"5: } ;\n"
"6: void bar :: dostuff ( ) { int x2@2 ; x2@2 = x@1 * 2 ; }\n"
"7: }\n", tokenize(code, true));
}
void varid_namespace_5() {
const char code[] = "namespace X {\n"
" struct foo { int x;};\n"
" namespace Y {\n"
" struct bar: public foo {\n"
" void dostuff();\n"
" };\n"
" void bar::dostuff() { int x2 = x * 2; }\n"
" }\n"
"}";
ASSERT_EQUALS("1: namespace X {\n"
"2: struct foo { int x@1 ; } ;\n"
"3: namespace Y {\n"
"4: struct bar : public foo {\n"
"5: void dostuff ( ) ;\n"
"6: } ;\n"
"7: void bar :: dostuff ( ) { int x2@2 ; x2@2 = x@1 * 2 ; }\n"
"8: }\n"
"9: }\n", tokenize(code, true));
}
void varid_namespace_6() {
const char code[] = "namespace N {\n" // #12077
" namespace O {\n"
" U::U(int* map) : id(0) {\n"
" this->p = map;\n"
" }\n"
" void U::f() {\n"
" std::map<Vec2i, int>::iterator iter;\n"
" }\n"
" }\n"
"}";
ASSERT_EQUALS("1: namespace N {\n"
"2: namespace O {\n"
"3: U :: U ( int * map@1 ) : id ( 0 ) {\n"
"4: this . p = map@1 ;\n"
"5: }\n"
"6: void U :: f ( ) {\n"
"7: std :: map < Vec2i , int > :: iterator iter@2 ;\n"
"8: }\n"
"9: }\n"
"10: }\n", tokenize(code, true));
}
void varid_initList() {
const char code1[] = "class A {\n"
" A() : x(0) {}\n"
" int x;\n"
"};";
ASSERT_EQUALS("1: class A {\n"
"2: A ( ) : x@1 ( 0 ) { }\n"
"3: int x@1 ;\n"
"4: } ;\n",
tokenize(code1));
const char code2[] = "class A {\n"
" A(int x) : x(x) {}\n"
" int x;\n"
"};";
ASSERT_EQUALS("1: class A {\n"
"2: A ( int x@1 ) : x@2 ( x@1 ) { }\n"
"3: int x@2 ;\n"
"4: } ;\n",
tokenize(code2));
const char code3[] = "class A {\n"
" A(int x);\n"
" int x;\n"
"};\n"
"A::A(int x) : x(x) {}";
ASSERT_EQUALS("1: class A {\n"
"2: A ( int x@1 ) ;\n"
"3: int x@2 ;\n"
"4: } ;\n"
"5: A :: A ( int x@3 ) : x@2 ( x@3 ) { }\n",
tokenize(code3));
const char code4[] = "struct A {\n"
" int x;\n"
" A(int x) : x(x) {}\n"
"};\n";
ASSERT_EQUALS("1: struct A {\n"
"2: int x@1 ;\n"
"3: A ( int x@2 ) : x@1 ( x@2 ) { }\n"
"4: } ;\n",
tokenize(code4));
const char code5[] = "class A {\n"
" A(int x) noexcept : x(x) {}\n"
" int x;\n"
"};";
ASSERT_EQUALS("1: class A {\n"
"2: A ( int x@1 ) noexcept ( true ) : x@2 ( x@1 ) { }\n"
"3: int x@2 ;\n"
"4: } ;\n",
tokenize(code5));
const char code6[] = "class A {\n"
" A(int x) noexcept(true) : x(x) {}\n"
" int x;\n"
"};";
ASSERT_EQUALS("1: class A {\n"
"2: A ( int x@1 ) noexcept ( true ) : x@2 ( x@1 ) { }\n"
"3: int x@2 ;\n"
"4: } ;\n",
tokenize(code6));
const char code7[] = "class A {\n"
" A(int x) noexcept(false) : x(x) {}\n"
" int x;\n"
"};";
ASSERT_EQUALS("1: class A {\n"
"2: A ( int x@1 ) noexcept ( false ) : x@2 ( x@1 ) { }\n"
"3: int x@2 ;\n"
"4: } ;\n",
tokenize(code7));
const char code8[] = "class Foo : public Bar {\n"
" explicit Foo(int i) : Bar(mi = i) { }\n"
" int mi;\n"
"};";
ASSERT_EQUALS("1: class Foo : public Bar {\n"
"2: explicit Foo ( int i@1 ) : Bar ( mi@2 = i@1 ) { }\n"
"3: int mi@2 ;\n"
"4: } ;\n",
tokenize(code8));
// #6520
const char code9[] = "class A {\n"
" A(int x) : y(a?0:1), x(x) {}\n"
" int x, y;\n"
"};";
ASSERT_EQUALS("1: class A {\n"
"2: A ( int x@1 ) : y@3 ( a ? 0 : 1 ) , x@2 ( x@1 ) { }\n"
"3: int x@2 ; int y@3 ;\n"
"4: } ;\n",
tokenize(code9));
// #7123
const char code10[] = "class A {\n"
" double *work;\n"
" A(const Matrix &m) throw (e);\n"
"};\n"
"A::A(const Matrix &m) throw (e) : work(0)\n"
"{}";
ASSERT_EQUALS("1: class A {\n"
"2: double * work@1 ;\n"
"3: A ( const Matrix & m@2 ) throw ( e ) ;\n"
"4: } ;\n"
"5: A :: A ( const Matrix & m@3 ) throw ( e ) : work@1 ( 0 )\n"
"6: { }\n",
tokenize(code10));
const char code11[] = "struct S {\n" // #12733
" explicit S(int& r) : a{ int{ 1 } }, b{ r } {}\n"
" int a, &b;\n"
"};";
ASSERT_EQUALS("1: struct S {\n"
"2: explicit S ( int & r@1 ) : a@2 { int { 1 } } , b@3 { r@1 } { }\n"
"3: int a@2 ; int & b@3 ;\n"
"4: } ;\n",
tokenize(code11));
const char code12[] = "template<typename... T>\n" // # 13070
" struct S1 : T... {\n"
" constexpr S1(const T& ... p) : T{ p } {}\n"
"};\n"
"namespace p { struct S2 {}; }\n"
"struct S3 {\n"
" S3() {}\n"
" bool f(p::S2& c);\n"
"};\n";
ASSERT_EQUALS("1: template < typename ... T >\n"
"2: struct S1 : T ... {\n"
"3: constexpr S1 ( const T & ... p@1 ) : T { p@1 } { }\n"
"4: } ;\n"
"5: namespace p { struct S2 { } ; }\n"
"6: struct S3 {\n"
"7: S3 ( ) { }\n"
"8: bool f ( p :: S2 & c@2 ) ;\n"
"9: } ;\n",
tokenize(code12));
const char code13[] = "template <typename... T>\n" // #13088
"struct B {};\n"
"template <typename... T>\n"
"struct D : B<T>... {\n"
" template <typename... P>\n"
" D(P&&... p) : B<T>(std::forward<P>(p))... {}\n"
"};\n"
"template <typename... T>\n"
"struct S {\n"
" D<T...> d;\n"
"};\n";
ASSERT_EQUALS("1: template < typename ... T >\n"
"2: struct B { } ;\n"
"3: template < typename ... T >\n"
"4: struct D : B < T > ... {\n"
"5: template < typename ... P >\n"
"6: D ( P && ... p@1 ) : B < T > ( std :: forward < P > ( p@1 ) ) ... { }\n"
"7: } ;\n"
"8: template < typename ... T >\n"
"9: struct S {\n"
"10: D < T ... > d@2 ;\n"
"11: } ;\n",
tokenize(code13));
}
void varid_initListWithBaseTemplate() {
const char code1[] = "class A : B<C,D> {\n"
" A() : B<C,D>(), x(0) {}\n"
" int x;\n"
"};";
ASSERT_EQUALS("1: class A : B < C , D > {\n"
"2: A ( ) : B < C , D > ( ) , x@1 ( 0 ) { }\n"
"3: int x@1 ;\n"
"4: } ;\n",
tokenize(code1));
const char code2[] = "class A : B<C,D> {\n"
" A(int x) : x(x) {}\n"
" int x;\n"
"};";
ASSERT_EQUALS("1: class A : B < C , D > {\n"
"2: A ( int x@1 ) : x@2 ( x@1 ) { }\n"
"3: int x@2 ;\n"
"4: } ;\n",
tokenize(code2));
const char code3[] = "class A : B<C,D> {\n"
" A(int x);\n"
" int x;\n"
"};\n"
"A::A(int x) : x(x) {}";
ASSERT_EQUALS("1: class A : B < C , D > {\n"
"2: A ( int x@1 ) ;\n"
"3: int x@2 ;\n"
"4: } ;\n"
"5: A :: A ( int x@3 ) : x@2 ( x@3 ) { }\n",
tokenize(code3));
const char code4[] = "struct A : B<C,D> {\n"
" int x;\n"
" A(int x) : x(x) {}\n"
"};\n";
ASSERT_EQUALS("1: struct A : B < C , D > {\n"
"2: int x@1 ;\n"
"3: A ( int x@2 ) : x@1 ( x@2 ) { }\n"
"4: } ;\n",
tokenize(code4));
const char code5[] = "class BCLass : public Ticket<void> {\n"
" BCLass();\n"
" PClass* member;\n"
"};\n"
"BCLass::BCLass() : Ticket<void>() {\n"
" member = 0;\n"
"}";
ASSERT_EQUALS("1: class BCLass : public Ticket < void > {\n"
"2: BCLass ( ) ;\n"
"3: PClass * member@1 ;\n"
"4: } ;\n"
"5: BCLass :: BCLass ( ) : Ticket < void > ( ) {\n"
"6: member@1 = 0 ;\n"
"7: }\n",
tokenize(code5));
}
void varid_initListWithScope() {
const char code1[] = "class A : public B::C {\n"
" A() : B::C(), x(0) {}\n"
" int x;\n"
"};";
ASSERT_EQUALS("1: class A : public B :: C {\n"
"2: A ( ) : B :: C ( ) , x@1 ( 0 ) { }\n"
"3: int x@1 ;\n"
"4: } ;\n",
tokenize(code1));
}
void varid_operator() {
{
const std::string actual = tokenize(
"class Foo\n"
"{\n"
"public:\n"
" void operator=(const Foo &);\n"
"};");
const char expected[] = "1: class Foo\n"
"2: {\n"
"3: public:\n"
"4: void operator= ( const Foo & ) ;\n"
"5: } ;\n";
ASSERT_EQUALS(expected, actual);
}
{
const std::string actual = tokenize(
"struct Foo {\n"
" void * operator new [](int);\n"
"};");
const char expected[] = "1: struct Foo {\n"
"2: void * operatornew[] ( int ) ;\n"
"3: } ;\n";
ASSERT_EQUALS(expected, actual);
}
}
void varid_throw() { // ticket #1723
const std::string actual = tokenize(
"UserDefinedException* pe = new UserDefinedException();\n"
"throw pe;");
const char expected[] = "1: UserDefinedException * pe@1 ; pe@1 = new UserDefinedException ( ) ;\n"
"2: throw pe@1 ;\n";
ASSERT_EQUALS(expected, actual);
}
void varid_unknown_macro() {
// #2638 - unknown macro
const char code[] = "void f() {\n"
" int a[10];\n"
" AAA\n"
" a[0] = 0;\n"
"}";
const char expected[] = "1: void f ( ) {\n"
"2: int a@1 [ 10 ] ;\n"
"3: AAA\n"
"4: a@1 [ 0 ] = 0 ;\n"
"5: }\n";
ASSERT_EQUALS(expected, tokenize(code, false));
}
void varid_using() {
// #3648
const char code[] = "using std::size_t;";
const char expected[] = "1: using unsigned long ;\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void varid_catch() {
const char code[] = "void f() {\n"
" try { dostuff(); }\n"
" catch (exception &e) { }\n"
"}";
const char expected[] = "1: void f ( ) {\n"
"2: try { dostuff ( ) ; }\n"
"3: catch ( exception & e@1 ) { }\n"
"4: }\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void varid_functionPrototypeTemplate() {
ASSERT_EQUALS("1: function < void ( ) > fptr@1 ;\n", tokenize("function<void(void)> fptr;"));
}
void varid_templatePtr() {
ASSERT_EQUALS("1: std :: map < int , FooTemplate < int > * > dummy_member@1 [ 1 ] ;\n", tokenize("std::map<int, FooTemplate<int>*> dummy_member[1];"));
}
void varid_templateNamespaceFuncPtr() {
ASSERT_EQUALS("1: KeyListT < float , & NIFFile :: getFloat > mKeyList@1 [ 4 ] ;\n", tokenize("KeyListT<float, &NIFFile::getFloat> mKeyList[4];"));
}
void varid_templateArray() {
ASSERT_EQUALS("1: VertexArrayIterator < float [ 2 ] > attrPos@1 ; attrPos@1 = m_AttributePos . GetIterator < float [ 2 ] > ( ) ;\n",
tokenize("VertexArrayIterator<float[2]> attrPos = m_AttributePos.GetIterator<float[2]>();"));
}
void varid_templateParameter() {
{
const char code[] = "const int X = 0;\n" // #7046 set varid for "X": std::array<int,X> Y;
"std::array<int,X> Y;\n";
ASSERT_EQUALS("1: const int X@1 = 0 ;\n"
"2: std :: array < int , X@1 > Y@2 ;\n",
tokenize(code));
}
{
const char code[] = "std::optional<N::Foo<A>> Foo;\n"; // #11003
ASSERT_EQUALS("1: std :: optional < N :: Foo < A > > Foo@1 ;\n",
tokenize(code));
}
}
void varid_templateParameterFunctionPointer() {
{
const char code[] = "template <class, void (*F)()>\n"
"struct a;\n";
ASSERT_EQUALS("1: template < class , void ( * F ) ( ) >\n"
"2: struct a ;\n",
tokenize(code));
}
}
void varid_templateUsing() { // #5781 #7273
const char code[] = "template<class T> using X = Y<T,4>;\n"
"X<int> x;";
ASSERT_EQUALS("2: Y < int , 4 > x@1 ;\n",
tokenize(code));
}
void varid_templateSpecializationFinal() {
const char code[] = "template <typename T>\n"
"struct S;\n"
"template <>\n"
"struct S<void> final {};\n";
ASSERT_EQUALS("4: struct S<void> ;\n"
"1: template < typename T >\n"
"2: struct S ;\n"
"3:\n"
"4: struct S<void> { } ;\n",
tokenize(code));
}
void varid_not_template_in_condition() {
const char code1[] = "void f() { if (x<a||x>b); }";
ASSERT_EQUALS("1: void f ( ) { if ( x < a || x > b ) { ; } }\n", tokenize(code1));
const char code2[] = "void f() { if (1+x<a||x>b); }";
ASSERT_EQUALS("1: void f ( ) { if ( 1 + x < a || x > b ) { ; } }\n", tokenize(code2));
const char code3[] = "void f() { if (x<a||x>b+1); }";
ASSERT_EQUALS("1: void f ( ) { if ( x < a || x > b + 1 ) { ; } }\n", tokenize(code3));
const char code4[] = "void f() { if ((x==13) && (x<a||x>b)); }";
ASSERT_EQUALS("1: void f ( ) { if ( ( x == 13 ) && ( x < a || x > b ) ) { ; } }\n", tokenize(code4));
}
void varid_cppcast() {
ASSERT_EQUALS("1: const_cast < int * > ( code ) [ 0 ] = 0 ;\n",
tokenize("const_cast<int *>(code)[0] = 0;"));
ASSERT_EQUALS("1: dynamic_cast < int * > ( code ) [ 0 ] = 0 ;\n",
tokenize("dynamic_cast<int *>(code)[0] = 0;"));
ASSERT_EQUALS("1: reinterpret_cast < int * > ( code ) [ 0 ] = 0 ;\n",
tokenize("reinterpret_cast<int *>(code)[0] = 0;"));
ASSERT_EQUALS("1: static_cast < int * > ( code ) [ 0 ] = 0 ;\n",
tokenize("static_cast<int *>(code)[0] = 0;"));
}
void varid_variadicFunc() {
ASSERT_EQUALS("1: int foo ( ... ) ;\n", tokenize("int foo(...);"));
}
void varid_typename() {
ASSERT_EQUALS("1: template < int d , class A , class B > struct S { } ;\n", tokenize("template<int d, class A, class B> struct S {};"));
ASSERT_EQUALS("1: template < int d , typename A , typename B > struct S { } ;\n", tokenize("template<int d, typename A, typename B> struct S {};"));
ASSERT_EQUALS("1: A a@1 ;\n", tokenize("typename A a;"));
}
void varid_rvalueref() {
ASSERT_EQUALS("1: int && a@1 ;\n", tokenize("int&& a;"));
ASSERT_EQUALS("1: void foo ( int && a@1 ) { }\n", tokenize("void foo(int&& a) {}"));
ASSERT_EQUALS("1: class C {\n"
"2: C ( int && a@1 ) ;\n"
"3: } ;\n",
tokenize("class C {\n"
" C(int&& a);\n"
"};"));
ASSERT_EQUALS("1: void foo ( int && ) ;\n", tokenize("void foo(int&&);"));
}
void varid_arrayFuncPar() {
ASSERT_EQUALS("1: void check ( const char fname@1 [ ] = 0 ) { }\n", tokenize("void check( const char fname[] = 0) { }"));
}
void varid_sizeofPassed() {
ASSERT_EQUALS("1: void which_test ( ) {\n"
"2: const char * argv@1 [ 2 ] = { \"./test_runner\" , \"TestClass\" } ;\n"
"3: options args@2 ( sizeof ( argv@1 ) / sizeof ( argv@1 [ 0 ] ) , argv@1 ) ;\n"
"4: args@2 . which_test ( ) ;\n"
"5: }\n",
tokenize("void which_test() {\n"
" const char* argv[] = { \"./test_runner\", \"TestClass\" };\n"
" options args(sizeof argv / sizeof argv[0], argv);\n"
" args.which_test();\n"
"}"));
}
void varid_classInFunction() {
ASSERT_EQUALS("1: void AddSuppression ( ) {\n"
"2: class QErrorLogger {\n"
"3: void reportErr ( ErrorLogger :: ErrorMessage & msg@1 ) {\n"
"4: }\n"
"5: } ;\n"
"6: }\n",
tokenize("void AddSuppression() {\n"
" class QErrorLogger {\n"
" void reportErr(ErrorLogger::ErrorMessage &msg) {\n"
" }\n"
" };\n"
"}"));
}
void varid_pointerToArray() {
ASSERT_EQUALS("1: int ( * a1@1 ) [ 10 ] ;\n"
"2: void f1 ( ) {\n"
"3: int ( * a2@2 ) [ 10 ] ;\n"
"4: int ( & a3@3 ) [ 10 ] ;\n"
"5: }\n"
"6: struct A {\n"
"7: int ( & a4@4 ) [ 10 ] ;\n"
"8: int f2 ( int i@5 ) { return a4@4 [ i@5 ] ; }\n"
"9: int f3 ( int ( & a5@6 ) [ 10 ] , int i@7 ) { return a5@6 [ i@7 ] ; }\n"
"10: } ;\n"
"11: int f4 ( int ( & a6@8 ) [ 10 ] , int i@9 ) { return a6@8 [ i@9 ] ; }\n",
tokenize("int (*a1)[10];\n" // pointer to array of 10 ints
"void f1() {\n"
" int(*a2)[10];\n"
" int(&a3)[10];\n"
"}\n"
"struct A {\n"
" int(&a4)[10];\n"
" int f2(int i) { return a4[i]; }\n"
" int f3(int(&a5)[10], int i) { return a5[i]; }\n"
"};\n"
"int f4(int(&a6)[10], int i) { return a6[i]; }"));
}
void varid_cpp11initialization() {
ASSERT_EQUALS("1: int i@1 { 1 } ;\n"
"2: std :: vector < int > vec@2 { 1 , 2 , 3 } ;\n"
"3: namespace n { int z@3 ; } ;\n"
"4: int & j@4 { i@1 } ;\n"
"5: int k@5 { 1 } ; int l@6 { 2 } ;\n",
tokenize("int i{1};\n"
"std::vector<int> vec{1, 2, 3};\n"
"namespace n { int z; };\n"
"int& j{i};\n"
"int k{1}, l{2};"));
// #6030
ASSERT_EQUALS("1: struct S3 : public S1 , public S2 { } ;\n",
tokenize("struct S3 : public S1, public S2 { };"));
// #6058
ASSERT_EQUALS("1: class Scope { } ;\n",
tokenize("class CPPCHECKLIB Scope { };"));
// #6073 #6253
ASSERT_EQUALS("1: class A : public B , public C :: D , public E < F > :: G < H > {\n"
"2: int i@1 ;\n"
"3: A ( int i@2 ) : B { i@2 } , C :: D { i@2 } , E < F > :: G < H > { i@2 } , i@1 { i@2 } {\n"
"4: int j@3 { i@2 } ;\n"
"5: }\n"
"6: } ;\n",
tokenize("class A: public B, public C::D, public E<F>::G<H> {\n"
" int i;\n"
" A(int i): B{i}, C::D{i}, E<F>::G<H>{i} ,i{i} {\n"
" int j{i};\n"
" }\n"
"};"));
}
void varid_inheritedMembers() {
ASSERT_EQUALS("1: class A {\n"
"2: int a@1 ;\n"
"3: } ;\n"
"4: class B : public A {\n"
"5: void f ( ) ;\n"
"6: } ;\n"
"7: void B :: f ( ) {\n"
"8: a@1 = 0 ;\n"
"9: }\n",
tokenize("class A {\n"
" int a;\n"
"};\n"
"class B : public A {\n"
" void f();\n"
"};\n"
"void B::f() {\n"
" a = 0;\n"
"}"));
ASSERT_EQUALS("1: class A {\n"
"2: int a@1 ;\n"
"3: } ;\n"
"4: class B : A {\n"
"5: void f ( ) ;\n"
"6: } ;\n"
"7: void B :: f ( ) {\n"
"8: a@1 = 0 ;\n"
"9: }\n",
tokenize("class A {\n"
" int a;\n"
"};\n"
"class B : A {\n"
" void f();\n"
"};\n"
"void B::f() {\n"
" a = 0;\n"
"}"));
ASSERT_EQUALS("1: class A {\n"
"2: int a@1 ;\n"
"3: } ;\n"
"4: class B : protected B , public A {\n"
"5: void f ( ) ;\n"
"6: } ;\n"
"7: void B :: f ( ) {\n"
"8: a@1 = 0 ;\n"
"9: }\n",
tokenize("class A {\n"
" int a;\n"
"};\n"
"class B : protected B, public A {\n"
" void f();\n"
"};\n"
"void B::f() {\n"
" a = 0;\n"
"}"));
ASSERT_EQUALS("1: class A {\n"
"2: int a@1 ;\n"
"3: } ;\n"
"4: class B : public A {\n"
"5: void f ( ) {\n"
"6: a@1 = 0 ;\n"
"7: }\n"
"8: } ;\n",
tokenize("class A {\n"
" int a;\n"
"};\n"
"class B : public A {\n"
" void f() {\n"
" a = 0;\n"
" }\n"
"};"));
}
void varid_header() {
ASSERT_EQUALS("1: class A@1 ;\n"
"2: struct B {\n"
"3: void setData ( const A@1 & a ) ;\n"
"4: } ;\n",
tokenizeHeader("class A;\n"
"struct B {\n"
" void setData(const A & a);\n"
"}; ", "test.h"));
ASSERT_EQUALS("1: class A ;\n"
"2: struct B {\n"
"3: void setData ( const A & a@1 ) ;\n"
"4: } ;\n",
tokenizeHeader("class A;\n"
"struct B {\n"
" void setData(const A & a);\n"
"}; ", "test.hpp"));
ASSERT_EQUALS("1: void f ( )\n"
"2: {\n"
"3: int class@1 ;\n"
"4: }\n",
tokenizeHeader("void f()\n"
"{\n"
" int class;\n"
"}", "test.h"));
}
void varid_rangeBasedFor() {
ASSERT_EQUALS("1: void reset ( Foo array@1 ) {\n"
"2: for ( auto & e@2 : array@1 ) {\n"
"3: foo ( e@2 ) ; }\n"
"4: } ;\n",
tokenize("void reset(Foo array) {\n"
" for (auto& e : array)\n"
" foo(e);\n"
"};"));
ASSERT_EQUALS("1: void reset ( Foo array@1 ) {\n"
"2: for ( auto e@2 : array@1 ) {\n"
"3: foo ( e@2 ) ; }\n"
"4: } ;\n",
tokenize("void reset(Foo array) {\n"
" for (auto e : array)\n"
" foo(e);\n"
"};"));
// Labels are no variables
ASSERT_EQUALS("1: void foo ( ) {\n"
"2: switch ( event . key . keysym . sym ) {\n"
"3: case SDLK_LEFT : ;\n"
"4: break ;\n"
"5: case SDLK_RIGHT : ;\n"
"6: delta = 1 ;\n"
"7: break ;\n"
"8: }\n"
"9: }\n",
tokenize("void foo() {\n"
" switch (event.key.keysym.sym) {\n"
" case SDLK_LEFT:\n"
" break;\n"
" case SDLK_RIGHT:\n"
" delta = 1;\n"
" break;\n"
" }\n"
"}", false));
ASSERT_EQUALS("1: int * f ( ) {\n" // #11838
"2: int * label@1 ; label@1 = 0 ;\n"
"3: label : ;\n"
"4: return label@1 ;\n"
"5: }\n",
tokenize("int* f() {\n"
" int* label = 0;\n"
"label:\n"
" return label;\n"
"}"));
}
void varid_structinit() { // #6406
ASSERT_EQUALS("1: void foo ( ) {\n"
"2: struct ABC abc@1 ; abc@1 = { . a@2 = 0 , . b@3 = 1 } ;\n"
"3: }\n",
tokenize("void foo() {\n"
" struct ABC abc = {.a=0,.b=1};\n"
"}"));
ASSERT_EQUALS("1: void foo ( ) {\n"
"2: struct ABC abc@1 ; abc@1 = { . a@2 = abc@1 . a@2 , . b@3 = abc@1 . b@3 } ;\n"
"3: }\n",
tokenize("void foo() {\n"
" struct ABC abc = {.a=abc.a,.b=abc.b};\n"
"}"));
ASSERT_EQUALS("1: void foo ( ) {\n"
"2: struct ABC abc@1 ; abc@1 = { . a@2 { abc@1 . a@2 } , . b@3 = { abc@1 . b@3 } } ;\n"
"3: }\n",
tokenize("void foo() {\n"
" struct ABC abc = {.a { abc.a },.b= { abc.b } };\n"
"}"));
ASSERT_EQUALS("1: struct T { int a@1 ; } ;\n" // #13123
"2: void f ( int a@2 ) {\n"
"3: struct T t@3 ; t@3 = { . a@4 = 1 } ;\n"
"4: }\n",
tokenize("struct T { int a; };\n"
"void f(int a) {\n"
" struct T t = { .a = 1 };\n"
"}\n"));
ASSERT_EQUALS("1: struct S { int x@1 ; } ;\n" // TODO: set some varid for designated initializer?
"2: void f0 ( S s@2 ) ;\n"
"3: void f1 ( int n@3 ) {\n"
"4: if ( int x@4 = n@3 ) {\n"
"5: f0 ( S { . x = x@4 } ) ;\n"
"6: }\n"
"7: }\n",
tokenize("struct S { int x; };\n"
"void f0(S s);\n"
"void f1(int n) {\n"
" if (int x = n) {\n"
" f0(S{ .x = x });\n"
" }\n"
"}\n"));
}
void varid_arrayinit() {
// #7579 - no variable declaration in rhs
ASSERT_EQUALS("1: void foo ( int * a@1 ) { int b@2 [ 1 ] = { x * a@1 [ 0 ] } ; }\n", tokenize("void foo(int*a) { int b[] = { x*a[0] }; }"));
// #12402
ASSERT_EQUALS("1: void f ( ) { void ( * p@1 [ 1 ] ) ( int ) = { [ ] ( int i@2 ) { } } ; }\n", tokenize("void f() { void (*p[1])(int) = { [](int i) {} }; }"));
}
void varid_lambda_arg() {
// #8664
{
const char code[] = "static void func(int ec) {\n"
" func2([](const std::error_code& ec) { return ec; });\n"
"}";
const char exp[] = "1: static void func ( int ec@1 ) {\n"
"2: func2 ( [ ] ( const std :: error_code & ec@2 ) { return ec@2 ; } ) ;\n"
"3: }\n";
ASSERT_EQUALS(exp, tokenize(code));
}
{
const char code[] = "static void func(int ec) {\n"
" func2([](int x, const std::error_code& ec) { return x + ec; });\n"
"}";
const char exp[] = "1: static void func ( int ec@1 ) {\n"
"2: func2 ( [ ] ( int x@2 , const std :: error_code & ec@3 ) { return x@2 + ec@3 ; } ) ;\n"
"3: }\n";
ASSERT_EQUALS(exp, tokenize(code));
}
// #9384
{
const char code[] = "auto g = [](const std::string& s) -> std::string { return {}; };\n";
const char exp[] = "1: auto g@1 ; g@1 = [ ] ( const std :: string & s@2 ) . std :: string { return { } ; } ;\n";
ASSERT_EQUALS(exp, tokenize(code));
}
{
const char code[] = "auto g = [](std::function<void()> p) {};\n";
const char exp[] = "1: auto g@1 ; g@1 = [ ] ( std :: function < void ( ) > p@2 ) { } ;\n";
ASSERT_EQUALS(exp, tokenize(code));
}
// # 10849
{
const char code[] = "class T {};\n"
"auto g = [](const T* t) -> int {\n"
" const T* u{}, *v{};\n"
" return 0;\n"
"};\n";
const char exp[] = "1: class T { } ;\n"
"2: auto g@1 ; g@1 = [ ] ( const T * t@2 ) . int {\n"
"3: const T * u@3 { } ; const T * v@4 { } ;\n"
"4: return 0 ;\n"
"5: } ;\n";
ASSERT_EQUALS(exp, tokenize(code));
}
// # 11332
{
const char code[] = "auto a() {\n"
" return [](int, int b) {};\n"
"}\n";
const char exp[] = "1: auto a ( ) {\n"
"2: return [ ] ( int , int b@1 ) { } ;\n"
"3: }\n";
ASSERT_EQUALS(exp, tokenize(code));
}
}
void varid_lambda_mutable() {
// #8957
{
const char code[] = "static void func() {\n"
" auto x = []() mutable {};\n"
" dostuff(x);\n"
"}";
const char exp[] = "1: static void func ( ) {\n"
"2: auto x@1 ; x@1 = [ ] ( ) mutable { } ;\n"
"3: dostuff ( x@1 ) ;\n"
"4: }\n";
ASSERT_EQUALS(exp, tokenize(code));
}
// #9384
{
const char code[] = "auto g = [](int i) mutable {};\n";
const char exp[] = "1: auto g@1 ; g@1 = [ ] ( int i@2 ) mutable { } ;\n";
ASSERT_EQUALS(exp, tokenize(code));
}
}
void varid_trailing_return1() { // #8889
const char code1[] = "struct Fred {\n"
" auto foo(const Fred & other) -> Fred &;\n"
" auto bar(const Fred & other) -> Fred & {\n"
" return *this;\n"
" }\n"
"};\n"
"auto Fred::foo(const Fred & other) -> Fred & {\n"
" return *this;\n"
"}";
const char exp1[] = "1: struct Fred {\n"
"2: auto foo ( const Fred & other@1 ) . Fred & ;\n"
"3: auto bar ( const Fred & other@2 ) . Fred & {\n"
"4: return * this ;\n"
"5: }\n"
"6: } ;\n"
"7: auto Fred :: foo ( const Fred & other@3 ) . Fred & {\n"
"8: return * this ;\n"
"9: }\n";
ASSERT_EQUALS(exp1, tokenize(code1));
}
void varid_trailing_return2() { // #9066
const char code1[] = "auto func(int arg) -> bar::quux {}";
const char exp1[] = "1: auto func ( int arg@1 ) . bar :: quux { }\n";
ASSERT_EQUALS(exp1, tokenize(code1));
}
void varid_trailing_return3() { // #11423
const char code[] = "void f(int a, int b) {\n"
" auto g = [](int& a, const int b) -> void {};\n"
" auto h = [&a, &b]() { std::swap(a, b); };\n"
"}\n";
const char exp[] = "1: void f ( int a@1 , int b@2 ) {\n"
"2: auto g@3 ; g@3 = [ ] ( int & a@4 , const int b@5 ) . void { } ;\n"
"3: auto h@6 ; h@6 = [ & a@1 , & b@2 ] ( ) { std :: swap ( a@1 , b@2 ) ; } ;\n"
"4: }\n";
ASSERT_EQUALS(exp, tokenize(code));
}
void varid_parameter_pack() { // #9383
const char code1[] = "template <typename... Rest>\n"
"void func(Rest... parameters) {\n"
" foo(parameters...);\n"
"}\n";
const char exp1[] = "1: template < typename ... Rest >\n"
"2: void func ( Rest ... parameters@1 ) {\n"
"3: foo ( parameters@1 ... ) ;\n"
"4: }\n";
ASSERT_EQUALS(exp1, tokenize(code1));
}
void varid_for_auto_cpp17() {
const char code[] = "void f() {\n"
" for (auto [x,y,z]: xyz) {\n"
" x+y+z;\n"
" }\n"
" x+y+z;\n"
"}";
const char exp1[] = "1: void f ( ) {\n"
"2: for ( auto [ x@1 , y@2 , z@3 ] : xyz ) {\n"
"3: x@1 + y@2 + z@3 ;\n"
"4: }\n"
"5: x + y + z ;\n"
"6: }\n";
ASSERT_EQUALS(exp1, tokenize(code));
}
void varid_not() { // #9689 'not x'
const char code1[] = "void foo(int x) const {\n"
" if (not x) {}\n"
"}";
const char exp1[] = "1: void foo ( int x@1 ) const {\n"
"2: if ( ! x@1 ) { }\n"
"3: }\n";
ASSERT_EQUALS(exp1, tokenize(code1));
}
void varid_declInIfCondition() {
// if
ASSERT_EQUALS("1: void f ( int x@1 ) {\n"
"2: if ( int x@2 = 0 ) { x@2 ; }\n"
"3: x@1 ;\n"
"4: }\n",
tokenize("void f(int x) {\n"
" if (int x = 0) { x; }\n"
" x;\n"
"}"));
// if, else
ASSERT_EQUALS("1: void f ( int x@1 ) {\n"
"2: if ( int x@2 = 0 ) { x@2 ; }\n"
"3: else { x@2 ; }\n"
"4: x@1 ;\n"
"5: }\n",
tokenize("void f(int x) {\n"
" if (int x = 0) { x; }\n"
" else { x; }\n"
" x;\n"
"}"));
// if, else if
ASSERT_EQUALS("1: void f ( int x@1 ) {\n"
"2: if ( int x@2 = 0 ) { x@2 ; }\n"
"3: else { if ( void * x@3 = & x@3 ) { x@3 ; } }\n"
"4: x@1 ;\n"
"5: }\n",
tokenize("void f(int x) {\n"
" if (int x = 0) x;\n"
" else if (void* x = &x) x;\n"
" x;\n"
"}"));
// if, else if, else
ASSERT_EQUALS("1: void f ( int x@1 ) {\n"
"2: if ( int x@2 = 0 ) { x@2 ; }\n"
"3: else { if ( void * x@3 = & x@3 ) { x@3 ; }\n"
"4: else { x@3 ; } }\n"
"5: x@1 ;\n"
"6: }\n",
tokenize("void f(int x) {\n"
" if (int x = 0) x;\n"
" else if (void* x = &x) x;\n"
" else x;\n"
" x;\n"
"}"));
ASSERT_EQUALS("1: const char * f ( int * ) ;\n" // #12924
"2: void g ( int i@1 ) {\n"
"3: if ( f ( & i@1 ) [ 0 ] == 'm' ) { }\n"
"4: }\n",
tokenize("const char *f(int*);\n"
"void g(int i) {\n"
" if (f(&i)[0] == 'm') {}\n"
"}\n", false));
}
void varid_globalScope() {
const char code1[] = "int a[5];\n"
"namespace Z { struct B { int a[5]; } b; }\n"
"void f() {\n"
" int a[5];\n"
" memset(a, 123, 5);\n"
" memset(::a, 123, 5);\n"
" memset(Z::b.a, 123, 5);\n"
" memset(::Z::b.a, 123, 5);\n"
"}";
const char exp1[] = "1: int a@1 [ 5 ] ;\n"
"2: namespace Z { struct B { int a@2 [ 5 ] ; } ; struct B b@3 ; }\n"
"3: void f ( ) {\n"
"4: int a@4 [ 5 ] ;\n"
"5: memset ( a@4 , 123 , 5 ) ;\n"
"6: memset ( :: a@1 , 123 , 5 ) ;\n"
"7: memset ( Z :: b@3 . a , 123 , 5 ) ;\n"
"8: memset ( :: Z :: b@3 . a , 123 , 5 ) ;\n"
"9: }\n";
ASSERT_EQUALS(exp1, tokenize(code1));
}
void varid_function_pointer_args() {
const char code1[] = "void foo() {\n"
" char *text;\n"
" void (*cb)(char* text);\n"
"}\n";
ASSERT_EQUALS("1: void foo ( ) {\n"
"2: char * text@1 ;\n"
"3: void ( * cb@2 ) ( char * ) ;\n"
"4: }\n", tokenize(code1));
const char code2[] = "void foo() {\n"
" char *text;\n"
" void (*f)(int (*arg)(char* text));\n"
"}\n";
ASSERT_EQUALS("1: void foo ( ) {\n"
"2: char * text@1 ;\n"
"3: void ( * f@2 ) ( int ( * arg ) ( char * ) ) ;\n"
"4: }\n", tokenize(code2));
const char code3[] = "void f (void (*g) (int i, IN int n)) {}\n";
ASSERT_EQUALS("1: void f ( void ( * g@1 ) ( int , IN int ) ) { }\n", tokenize(code3));
}
void varid_alignas() {
const char code[] = "extern alignas(16) int x;\n"
"alignas(16) int x;";
const char expected[] = "1: extern alignas ( 16 ) int x@1 ;\n"
"2: alignas ( 16 ) int x@2 ;\n";
ASSERT_EQUALS(expected, tokenize(code, false));
}
void varidclass1() {
const std::string actual = tokenize(
"class Fred\n"
"{\n"
"private:\n"
" int i;\n"
"\n"
" void foo1();\n"
" void foo2()\n"
" {\n"
" ++i;\n"
" }\n"
"}\n"
"\n"
"Fred::foo1()\n"
"{\n"
" i = 0;\n"
"}");
const char expected[] = "1: class Fred\n"
"2: {\n"
"3: private:\n"
"4: int i@1 ;\n"
"5:\n"
"6: void foo1 ( ) ;\n"
"7: void foo2 ( )\n"
"8: {\n"
"9: ++ i@1 ;\n"
"10: }\n"
"11: }\n"
"12:\n"
"13: Fred :: foo1 ( )\n"
"14: {\n"
"15: i@1 = 0 ;\n"
"16: }\n";
ASSERT_EQUALS(expected, actual);
}
void varidclass2() {
const std::string actual = tokenize(
"class Fred\n"
"{ void f(); };\n"
"\n"
"void A::foo1()\n"
"{\n"
" int i = 0;\n"
"}\n"
"\n"
"void Fred::f()\n"
"{\n"
" i = 0;\n"
"}");
const char expected[] = "1: class Fred\n"
"2: { void f ( ) ; } ;\n"
"3:\n"
"4: void A :: foo1 ( )\n"
"5: {\n"
"6: int i@1 ; i@1 = 0 ;\n"
"7: }\n"
"8:\n"
"9: void Fred :: f ( )\n"
"10: {\n"
"11: i = 0 ;\n"
"12: }\n";
ASSERT_EQUALS(expected, actual);
}
void varidclass3() {
const std::string actual = tokenize(
"class Fred\n"
"{ int i; void f(); };\n"
"\n"
"void Fred::f()\n"
"{\n"
" i = 0;\n"
"}\n"
"\n"
"void A::f()\n"
"{\n"
" i = 0;\n"
"}");
const char expected[] = "1: class Fred\n"
"2: { int i@1 ; void f ( ) ; } ;\n"
"3:\n"
"4: void Fred :: f ( )\n"
"5: {\n"
"6: i@1 = 0 ;\n"
"7: }\n"
"8:\n"
"9: void A :: f ( )\n"
"10: {\n"
"11: i = 0 ;\n"
"12: }\n";
ASSERT_EQUALS(expected, actual);
}
void varidclass4() {
const std::string actual = tokenize(
"class Fred\n"
"{ int i; void f(); };\n"
"\n"
"void Fred::f()\n"
"{\n"
" if (i) { }\n"
" i = 0;\n"
"}");
const char expected[] = "1: class Fred\n"
"2: { int i@1 ; void f ( ) ; } ;\n"
"3:\n"
"4: void Fred :: f ( )\n"
"5: {\n"
"6: if ( i@1 ) { }\n"
"7: i@1 = 0 ;\n"
"8: }\n";
ASSERT_EQUALS(expected, actual);
}
void varidclass5() {
const std::string actual = tokenize(
"class A { };\n"
"class B\n"
"{\n"
" A *a;\n"
" B() : a(new A)\n"
" { }\n"
"};");
const char expected[] = "1: class A { } ;\n"
"2: class B\n"
"3: {\n"
"4: A * a@1 ;\n"
"5: B ( ) : a@1 ( new A )\n"
"6: { }\n"
"7: } ;\n";
ASSERT_EQUALS(expected, actual);
}
void varidclass6() {
const std::string actual = tokenize(
"class A\n"
"{\n"
" public:\n"
" static char buf[20];\n"
"};\n"
"char A::buf[20];\n"
"int main()\n"
"{\n"
" char buf[2];\n"
" A::buf[10] = 0;\n"
"}");
const char expected[] = "1: class A\n"
"2: {\n"
"3: public:\n"
"4: static char buf@1 [ 20 ] ;\n"
"5: } ;\n"
"6: char A :: buf@1 [ 20 ] ;\n"
"7: int main ( )\n"
"8: {\n"
"9: char buf@2 [ 2 ] ;\n"
"10: A :: buf@1 [ 10 ] = 0 ;\n"
"11: }\n";
ASSERT_EQUALS(expected, actual);
}
void varidclass7() {
const std::string actual = tokenize(
"int main()\n"
"{\n"
" char buf[2];\n"
" A::buf[10] = 0;\n"
"}");
const char expected[] = "1: int main ( )\n"
"2: {\n"
"3: char buf@1 [ 2 ] ;\n"
"4: A :: buf [ 10 ] = 0 ;\n"
"5: }\n";
ASSERT_EQUALS(expected, actual);
}
void varidclass8() {
const char code[] ="class Fred {\n"
"public:\n"
" void foo(int d) {\n"
" int i = bar(x * d);\n"
" }\n"
" int x;\n"
"}\n";
const char expected[] = "1: class Fred {\n"
"2: public:\n"
"3: void foo ( int d@1 ) {\n"
"4: int i@2 ; i@2 = bar ( x@3 * d@1 ) ;\n"
"5: }\n"
"6: int x@3 ;\n"
"7: }\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void varidclass9() {
const char code[] ="typedef char Str[10];"
"class A {\n"
"public:\n"
" void f(Str &cl);\n"
" void g(Str cl);\n"
"}\n"
"void Fred::f(Str &cl) {\n"
" sizeof(cl);\n"
"}";
const char expected[] = "1: class A {\n"
"2: public:\n"
"3: void f ( char ( & cl@1 ) [ 10 ] ) ;\n"
"4: void g ( char cl@2 [ 10 ] ) ;\n"
"5: }\n"
"6: void Fred :: f ( char ( & cl@3 ) [ 10 ] ) {\n"
"7: sizeof ( cl@3 ) ;\n"
"8: }\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void varidclass10() {
const char code[] ="class A {\n"
" void f() {\n"
" a = 3;\n"
" }\n"
" int a;\n"
"};\n";
const char expected[] = "1: class A {\n"
"2: void f ( ) {\n"
"3: a@1 = 3 ;\n"
"4: }\n"
"5: int a@1 ;\n"
"6: } ;\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void varidclass11() {
const char code[] ="class Fred {\n"
" int a;\n"
" void f();\n"
"};\n"
"class Wilma {\n"
" int a;\n"
" void f();\n"
"};\n"
"void Fred::f() { a = 0; }\n"
"void Wilma::f() { a = 0; }\n";
const char expected[] = "1: class Fred {\n"
"2: int a@1 ;\n"
"3: void f ( ) ;\n"
"4: } ;\n"
"5: class Wilma {\n"
"6: int a@2 ;\n"
"7: void f ( ) ;\n"
"8: } ;\n"
"9: void Fred :: f ( ) { a@1 = 0 ; }\n"
"10: void Wilma :: f ( ) { a@2 = 0 ; }\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void varidclass12() {
const char code[] ="class Fred {\n"
" int a;\n"
" void f() { Fred::a = 0; }\n"
"};\n";
const char expected[] = "1: class Fred {\n"
"2: int a@1 ;\n"
"3: void f ( ) { Fred :: a@1 = 0 ; }\n"
"4: } ;\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void varidclass13() {
const char code[] ="class Fred {\n"
" int a;\n"
" void f() { Foo::Fred::a = 0; }\n"
"};\n";
const char expected[] = "1: class Fred {\n"
"2: int a@1 ;\n"
"3: void f ( ) { Foo :: Fred :: a = 0 ; }\n"
"4: } ;\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void varidclass14() {
// don't give friend classes varid
{
const char code[] ="class A {\n"
"friend class B;\n"
"}";
const char expected[] = "1: class A {\n"
"2: friend class B ;\n"
"3: }\n";
ASSERT_EQUALS(expected, tokenize(code));
}
{
const char code[] ="class A {\n"
"private: friend class B;\n"
"}";
const char expected[] = "1: class A {\n"
"2: private: friend class B ;\n"
"3: }\n";
ASSERT_EQUALS(expected, tokenize(code));
}
}
void varidclass15() {
const char code[] = "class A {\n"
" int a;\n"
" int b;\n"
" A();\n"
"};\n"
"A::A() : a(0) { b = 1; }";
const char expected[] = "1: class A {\n"
"2: int a@1 ;\n"
"3: int b@2 ;\n"
"4: A ( ) ;\n"
"5: } ;\n"
"6: A :: A ( ) : a@1 ( 0 ) { b@2 = 1 ; }\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void varidclass16() {
const char code[] = "struct A;\n"
"typedef bool (A::* FuncPtr)();\n"
"struct A {\n"
" FuncPtr pFun;\n"
" void setPFun(int mode);\n"
" bool funcNorm();\n"
"};\n"
"void A::setPFun(int mode) {\n"
" pFun = &A::funcNorm;\n"
"}";
const char expected[] = "1: struct A ;\n"
"2:\n"
"3: struct A {\n"
"4: bool ( * pFun@1 ) ( ) ;\n"
"5: void setPFun ( int mode@2 ) ;\n"
"6: bool funcNorm ( ) ;\n"
"7: } ;\n"
"8: void A :: setPFun ( int mode@3 ) {\n"
"9: pFun@1 = & A :: funcNorm ;\n"
"10: }\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void varidclass17() {
const char code[] = "class A: public B, public C::D {\n"
" int i;\n"
" A(int i): B(i), C::D(i), i(i) {\n"
" int j(i);\n"
" }\n"
"};";
const char expected[] = "1: class A : public B , public C :: D {\n"
"2: int i@1 ;\n"
"3: A ( int i@2 ) : B ( i@2 ) , C :: D ( i@2 ) , i@1 ( i@2 ) {\n"
"4: int j@3 ; j@3 = i@2 ;\n"
"5: }\n"
"6: } ;\n";
ASSERT_EQUALS(expected, tokenize(code));
const char code2[] = "struct S {\n" // #11411
" std::vector<int> v;\n"
" int i;\n"
" S(int i) : v({ 0 }), i(i) {}\n"
"};";
const char expected2[] = "1: struct S {\n"
"2: std :: vector < int > v@1 ;\n"
"3: int i@2 ;\n"
"4: S ( int i@3 ) : v@1 ( { 0 } ) , i@2 ( i@3 ) { }\n"
"5: } ;\n";
ASSERT_EQUALS(expected2, tokenize(code2));
}
void varidclass18() {
const char code[] = "class A {\n"
" int a;\n"
" int b;\n"
" A();\n"
"};\n"
"A::A() : a{0} { b = 1; }";
const char expected[] = "1: class A {\n"
"2: int a@1 ;\n"
"3: int b@2 ;\n"
"4: A ( ) ;\n"
"5: } ;\n"
"6: A :: A ( ) : a@1 { 0 } { b@2 = 1 ; }\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void varidclass19() {
const char code[] = "class A : public ::B {\n"
" int a;\n"
" A();\n"
"};\n"
"A::A() : ::B(), a(0) {}";
const char expected[] = "1: class A : public :: B {\n"
"2: int a@1 ;\n"
"3: A ( ) ;\n"
"4: } ;\n"
"5: A :: A ( ) : :: B ( ) , a@1 ( 0 ) { }\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void varidclass20() { // #7578: int (*p)[2]
const char code[] = "struct S {\n"
" int (*p)[2];\n"
" S();\n"
"};\n"
"S::S() { p[0] = 0; }";
const char expected[] = "1: struct S {\n"
"2: int ( * p@1 ) [ 2 ] ;\n"
"3: S ( ) ;\n"
"4: } ;\n"
"5: S :: S ( ) { p@1 [ 0 ] = 0 ; }\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void varidenum1() {
const char code[] = "const int eStart = 6;\n"
"enum myEnum {\n"
" A = eStart\n"
"};\n";
const char expected[] = "1: const int eStart@1 = 6 ;\n"
"2: enum myEnum {\n"
"3: A = eStart@1\n"
"4: } ;\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void varidenum2() {
const char code[] = "const int eStart = 6;\n"
"enum myEnum {\n"
" A = f(eStart)\n"
"};\n";
const char expected[] = "1: const int eStart@1 = 6 ;\n"
"2: enum myEnum {\n"
"3: A = f ( eStart@1 )\n"
"4: } ;\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void varidenum3() {
const char code[] = "const int eStart = 6;\n"
"enum myEnum {\n"
" A = f(eStart, x)\n"
"};\n";
const char expected[] = "1: const int eStart@1 = 6 ;\n"
"2: enum myEnum {\n"
"3: A = f ( eStart@1 , x )\n"
"4: } ;\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void varidenum4() {
const char code[] = "const int eStart = 6;\n"
"enum myEnum {\n"
" A = f(x, eStart)\n"
"};\n";
const char expected[] = "1: const int eStart@1 = 6 ;\n"
"2: enum myEnum {\n"
"3: A = f ( x , eStart@1 )\n"
"4: } ;\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void varidenum5() {
const char code[] = "const int eStart = 6;\n"
"enum myEnum {\n"
" A = f(x, eStart, y)\n"
"};\n";
const char expected[] = "1: const int eStart@1 = 6 ;\n"
"2: enum myEnum {\n"
"3: A = f ( x , eStart@1 , y )\n"
"4: } ;\n";
const char current[] = "1: const int eStart@1 = 6 ;\n"
"2: enum myEnum {\n"
"3: A = f ( x , eStart , y )\n"
"4: } ;\n";
TODO_ASSERT_EQUALS(expected, current, tokenize(code));
}
void varidenum6() { // #9180
const char code[] = "const int IDL1 = 13;\n"
"enum class E { IDL1 = 16, };\n";
const char expected[] = "1: const int IDL1@1 = 13 ;\n"
"2: enum class E { IDL1 = 16 , } ;\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void varidenum7() { // #8991
const char code[] = "namespace N1 { const int c = 42; }\n"
"namespace N2 { const int c = 24; }\n"
"struct S {\n"
" enum { v1 = N1::c, v2 = N2::c };\n"
"};\n";
const char expected[] = "1: namespace N1 { const int c@1 = 42 ; }\n"
"2: namespace N2 { const int c@2 = 24 ; }\n"
"3: struct S {\n"
"4: enum Anonymous0 { v1 = N1 :: c@1 , v2 = N2 :: c@2 } ;\n"
"5: } ;\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void varid_classnameshaddowsvariablename() {
const char code[] = "class Data;\n"
"void strange_declarated(const Data& Data);\n"
"void handleData(const Data& data) {\n"
" strange_declarated(data);\n"
"}\n";
const char expected[] = "1: class Data ;\n"
"2: void strange_declarated ( const Data & Data@1 ) ;\n"
"3: void handleData ( const Data & data@2 ) {\n"
"4: strange_declarated ( data@2 ) ;\n"
"5: }\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void varid_classnametemplate() {
const char code[] = "template <typename T>\n"
"struct BBB {\n"
" struct inner;\n"
"};\n"
"\n"
"template <typename T>\n"
"struct BBB<T>::inner {\n"
" inner(int x);\n"
" int x;\n"
"};\n"
"\n"
"template <typename T>\n"
"BBB<T>::inner::inner(int x): x(x) {}\n";
const char expected[] = "1: template < typename T >\n"
"2: struct BBB {\n"
"3: struct inner ;\n"
"4: } ;\n"
"5:\n"
"6: template < typename T >\n"
"7: struct BBB < T > :: inner {\n"
"8: inner ( int x@1 ) ;\n"
"9: int x@2 ;\n"
"10: } ;\n"
"11:\n"
"12: template < typename T >\n"
"13: BBB < T > :: inner :: inner ( int x@3 ) : x@2 ( x@3 ) { }\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void varidnamespace1() {
const char code[] = "namespace A {\n"
" char buf[20];\n"
"}\n"
"int main() {\n"
" return foo(A::buf);\n"
"}";
const char expected[] = "1: namespace A {\n"
"2: char buf@1 [ 20 ] ;\n"
"3: }\n"
"4: int main ( ) {\n"
"5: return foo ( A :: buf@1 ) ;\n"
"6: }\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void varidnamespace2() {
const char code[] = "namespace A {\n"
" namespace B {\n"
" char buf[20];\n"
" }\n"
"}\n"
"int main() {\n"
" return foo(A::B::buf);\n"
"}";
const char expected[] = "1: namespace A {\n"
"2: namespace B {\n"
"3: char buf@1 [ 20 ] ;\n"
"4: }\n"
"5: }\n"
"6: int main ( ) {\n"
"7: return foo ( A :: B :: buf@1 ) ;\n"
"8: }\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void usingNamespace1() {
const char code[] = "namespace NS {\n"
" class A { int x; void dostuff(); };\n"
"}\n"
"using namespace NS;\n"
"void A::dostuff() { x = 0; }\n";
const char expected[] = "1: namespace NS {\n"
"2: class A { int x@1 ; void dostuff ( ) ; } ;\n"
"3: }\n"
"4: using namespace NS ;\n"
"5: void A :: dostuff ( ) { x@1 = 0 ; }\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void usingNamespace2() {
const char code[] = "class A { int x; void dostuff(); };\n"
"using namespace NS;\n"
"void A::dostuff() { x = 0; }\n";
const char expected[] = "1: class A { int x@1 ; void dostuff ( ) ; } ;\n"
"2: using namespace NS ;\n"
"3: void A :: dostuff ( ) { x@1 = 0 ; }\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void usingNamespace3() {
const char code[] = "namespace A {\n"
" namespace B {\n"
" class C {\n"
" double m;\n"
" C();\n"
" };\n"
" }\n"
"}\n"
"using namespace A::B;\n"
"C::C() : m(42) {}";
const char expected[] = "1: namespace A {\n"
"2: namespace B {\n"
"3: class C {\n"
"4: double m@1 ;\n"
"5: C ( ) ;\n"
"6: } ;\n"
"7: }\n"
"8: }\n"
"9: using namespace A :: B ;\n"
"10: C :: C ( ) : m@1 ( 42 ) { }\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void setVarIdStructMembers1() {
const char code[] = "void f(Foo foo)\n"
"{\n"
" foo.size = 0;\n"
" return ((uint8_t)(foo).size);\n"
"}";
const char expected[] = "1: void f ( Foo foo@1 )\n"
"2: {\n"
"3: foo@1 . size@2 = 0 ;\n"
"4: return ( ( uint8_t ) ( foo@1 ) . size@2 ) ;\n"
"5: }\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void decltype1() {
const char code[] = "void foo(int x, decltype(A::b) *p);";
const char expected[] = "1: void foo ( int x@1 , decltype ( A :: b ) * p@2 ) ;\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void decltype2() {
const char code[] = "int x; decltype(x) y;";
const char expected[] = "1: int x@1 ; decltype ( x@1 ) y@2 ;\n";
ASSERT_EQUALS(expected, tokenize(code));
}
void exprid1() {
const std::string actual = tokenizeExpr(
"struct A {\n"
" int x, y;\n"
"};\n"
"int f(A a, A b) {\n"
" int x = a.x + b.x;\n"
" int y = b.x + a.x;\n"
" return x + y + a.y + b.y;\n"
"}\n");
const char expected[] =
"1: struct A {\n"
"2: int x ; int y ;\n"
"3: } ;\n"
"4: int f ( A a , A b ) {\n"
"5: int x@5 ; x@5 =@UNIQUE a@3 .@11 x@6 +@13 b@4 .@12 x@7 ;\n"
"6: int y@8 ; y@8 =@UNIQUE b@4 .@12 x@7 +@13 a@3 .@11 x@6 ;\n"
"7: return x@5 +@UNIQUE y@8 +@UNIQUE a@3 .@UNIQUE y@9 +@UNIQUE b@4 .@UNIQUE y@10 ;\n"
"8: }\n";
ASSERT_EQUALS(expected, actual);
}
void exprid2() {
const std::string actual = tokenizeExpr( // #11739
"struct S { std::unique_ptr<int> u; };\n"
"auto f = [](const S& s) -> std::unique_ptr<int> {\n"
" if (auto p = s.u.get())\n"
" return std::make_unique<int>(*p);\n"
" return nullptr;\n"
"};\n");
const char expected[] = "1: struct S { std :: unique_ptr < int > u ; } ;\n"
"2: auto f ; f = [ ] ( const S & s ) . std :: unique_ptr < int > {\n"
"3: if ( auto p@4 =@UNIQUE s@3 .@UNIQUE u@5 .@UNIQUE get (@UNIQUE ) ) {\n"
"4: return std ::@UNIQUE make_unique < int > (@UNIQUE *@UNIQUE p@4 ) ; }\n"
"5: return nullptr ;\n"
"6: } ;\n";
ASSERT_EQUALS(expected, actual);
}
void exprid3() {
const char code[] = "void f(bool b, int y) {\n"
" if (b && y > 0) {}\n"
" while (b && y > 0) {}\n"
"}\n";
const char expected[] = "1: void f ( bool b , int y ) {\n"
"2: if ( b@1 &&@5 y@2 >@4 0 ) { }\n"
"3: while ( b@1 &&@5 y@2 >@4 0 ) { }\n"
"4: }\n";
ASSERT_EQUALS(expected, tokenizeExpr(code));
}
void exprid4() {
// expanded macro..
const char code[] = "#define ADD(x,y) x+y\n"
"int f(int a, int b) {\n"
" return ADD(a,b) + ADD(a,b);\n"
"}\n";
const char expected[] = "2: int f ( int a , int b ) {\n"
"3: return a@1 $+@UNIQUE b@2 +@UNIQUE a@1 $+@UNIQUE b@2 ;\n"
"4: }\n";
ASSERT_EQUALS(expected, tokenizeExpr(code));
}
void exprid5() {
// references..
const char code[] = "int foo(int a) {\n"
" int& r = a;\n"
" return (a+a)*(r+r);\n"
"}\n";
const char expected[] = "1: int foo ( int a ) {\n"
"2: int & r@2 =@UNIQUE a@1 ;\n"
"3: return ( a@1 +@4 a@1 ) *@UNIQUE ( r@2 +@4 r@2 ) ;\n"
"4: }\n";
ASSERT_EQUALS(expected, tokenizeExpr(code));
}
void exprid6() {
// ++ and -- should have UNIQUE exprid
const char code[] = "void foo(int *a) {\n"
" *a++ = 0;\n"
" if (*a++ == 32) {}\n"
"}\n";
const char expected[] = "1: void foo ( int * a ) {\n"
"2: *@UNIQUE a@1 ++@UNIQUE = 0 ;\n"
"3: if ( *@UNIQUE a@1 ++@UNIQUE ==@UNIQUE 32 ) { }\n"
"4: }\n";
ASSERT_EQUALS(expected, tokenizeExpr(code));
}
void exprid7() {
// different casts
const char code[] = "void foo(int a) {\n"
" if ((char)a == (short)a) {}\n"
" if ((char)a == (short)a) {}\n"
"}\n";
const char expected[] = "1: void foo ( int a ) {\n"
"2: if ( (@2 char ) a@1 ==@4 (@3 short ) a@1 ) { }\n"
"3: if ( (@2 char ) a@1 ==@4 (@3 short ) a@1 ) { }\n"
"4: }\n";
ASSERT_EQUALS(expected, tokenizeExpr(code));
}
void exprid8() {
const char code[] = "void f() {\n" // #12249
" std::string s;\n"
" (((s += \"--\") += std::string()) += \"=\");\n"
"}\n";
const char expected[] = "1: void f ( ) {\n"
"2: std ::@UNIQUE string s@1 ;\n"
"3: ( ( s@1 +=@UNIQUE \"--\"@UNIQUE ) +=@UNIQUE std ::@UNIQUE string (@UNIQUE ) ) +=@UNIQUE \"=\"@UNIQUE ;\n"
"4: }\n";
ASSERT_EQUALS(expected, tokenizeExpr(code));
const char code2[] = "struct S { std::function<void()>* p; };\n"
"S f() { return S{ std::make_unique<std::function<void()>>([]() {}).release()}; }";
const char expected2[] = "1: struct S { std :: function < void ( ) > * p ; } ;\n"
"2: S f ( ) { return S@UNIQUE {@UNIQUE std ::@UNIQUE make_unique < std :: function < void ( ) > > (@UNIQUE [ ] ( ) { } ) .@UNIQUE release (@UNIQUE ) } ; }\n";
ASSERT_EQUALS(expected2, tokenizeExpr(code2));
const char code3[] = "struct S { int* p; };\n"
"S f() { return S{ std::make_unique<int>([]() { return 4; }()).release()}; }\n";
const char expected3[] = "1: struct S { int * p ; } ;\n"
"2: S f ( ) { return S@UNIQUE {@UNIQUE std ::@UNIQUE make_unique < int > (@UNIQUE [ ] ( ) { return 4 ; } ( ) ) .@UNIQUE release (@UNIQUE ) } ; }\n";
ASSERT_EQUALS(expected3, tokenizeExpr(code3));
const char code4[] = "std::unique_ptr<int> g(int i) { return std::make_unique<int>(i); }\n"
"void h(int*);\n"
"void f() {\n"
" h(g({}).get());\n"
"}\n";
const char expected4[] = "1: std :: unique_ptr < int > g ( int i ) { return std ::@UNIQUE make_unique < int > (@UNIQUE i@1 ) ; }\n"
"2: void h ( int * ) ;\n"
"3: void f ( ) {\n"
"4: h (@UNIQUE g (@UNIQUE { } ) .@UNIQUE get (@UNIQUE ) ) ;\n"
"5: }\n";
ASSERT_EQUALS(expected4, tokenizeExpr(code4));
const char code5[] = "int* g(std::map<int, std::unique_ptr<int>>& m) {\n"
" return m[{0}].get();\n"
"}\n";
const char expected5[] = "1: int * g ( std :: map < int , std :: unique_ptr < int > > & m ) {\n"
"2: return m@1 [@UNIQUE { 0 } ] .@UNIQUE get (@UNIQUE ) ;\n"
"3: }\n";
ASSERT_EQUALS(expected5, tokenizeExpr(code5));
}
void exprid9()
{
const char code[] = "void f(const std::type_info& type) {\n" // #12340
" if (type == typeid(unsigned int)) {}\n"
" else if (type == typeid(int)) {}\n"
"}\n";
const char expected[] = "1: void f ( const std :: type_info & type ) {\n"
"2: if ( type@1 ==@UNIQUE typeid (@UNIQUE unsigned int@UNIQUE ) ) { }\n"
"3: else { if ( type@1 ==@UNIQUE typeid (@UNIQUE int@UNIQUE ) ) { } }\n"
"4: }\n";
ASSERT_EQUALS(expected, tokenizeExpr(code));
}
void exprid10()
{
const char code[] = "void f(const std::string& p) {\n" // #12350
" std::string s;\n"
" ((s = \"abc\") += p) += \"def\";\n"
"}\n";
const char expected[] = "1: void f ( const std :: string & p ) {\n"
"2: std ::@UNIQUE string s@2 ;\n"
"3: ( ( s@2 =@UNIQUE \"abc\" ) +=@UNIQUE p@1 ) +=@UNIQUE \"def\"@UNIQUE ;\n"
"4: }\n";
ASSERT_EQUALS(expected, tokenizeExpr(code));
}
void exprid11()
{
const char code[] = "struct S { void f(); };\n" // #12713
"int g(int, S*);\n"
"int h(void (*)(), S*);\n"
"void S::f() {\n"
" std::make_unique<int>(g({}, this)).release();\n"
" std::make_unique<int>(h([]() {}, this)).release();\n"
"}\n";
const char* exp = "1: struct S { void f ( ) ; } ;\n"
"2: int g ( int , S * ) ;\n"
"3: int h ( void ( * ) ( ) , S * ) ;\n"
"4: void S :: f ( ) {\n"
"5: std ::@UNIQUE make_unique < int > (@UNIQUE g (@UNIQUE { } ,@6 this ) ) .@UNIQUE release (@UNIQUE ) ;\n"
"6: std ::@UNIQUE make_unique < int > (@UNIQUE h (@UNIQUE [ ] ( ) { } ,@6 this ) ) .@UNIQUE release (@UNIQUE ) ;\n"
"7: }\n";
ASSERT_EQUALS(exp, tokenizeExpr(code));
}
void exprid12()
{
const char code[] = "struct S { std::unique_ptr<int> p; };\n" // #12765
"namespace N {\n"
" struct T { void (*f)(S*); };\n"
" const T t = {\n"
" [](S* s) { s->p.release(); }\n"
" };\n"
"}\n";
const char* exp = "1: struct S { std :: unique_ptr < int > p ; } ;\n"
"2: namespace N {\n"
"3: struct T { void ( * f@2 ) ( S * ) ; } ;\n"
"4: const T t@3 = {\n"
"5: [ ] ( S * s@4 ) { s@4 .@UNIQUE p@5 .@UNIQUE release (@UNIQUE ) ; }\n"
"6: } ;\n"
"7: }\n";
ASSERT_EQUALS(exp, tokenizeExpr(code));
}
void exprid13()
{
const char code[] = "struct S { int s; };\n" // #11488
"struct T { struct S s; };\n"
"struct U { struct T t; };\n"
"void f() {\n"
" struct U u = { .t = { .s = { .s = 1 } } };\n"
"}\n";
const char* exp = "1: struct S { int s ; } ;\n"
"2: struct T { struct S s ; } ;\n"
"3: struct U { struct T t ; } ;\n"
"4: void f ( ) {\n"
"5: struct U u@4 ; u@4 = { .@UNIQUE t@5 = { . s = { . s = 1 } } } ;\n"
"6: }\n";
ASSERT_EQUALS(exp, tokenizeExpr(code));
}
void structuredBindings() {
const char code[] = "int foo() { auto [x,y] = xy(); return x+y; }";
ASSERT_EQUALS("1: int foo ( ) { auto [ x@1 , y@2 ] = xy ( ) ; return x@1 + y@2 ; }\n",
tokenize(code));
}
};
REGISTER_TEST(TestVarID)
| null |
985 | cpp | cppcheck | testleakautovar.cpp | test/testleakautovar.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "checkleakautovar.h"
#include "fixture.h"
#include "helpers.h"
#include "settings.h"
#include "tokenize.h"
#include <cstddef>
#include <string>
#include <vector>
class TestLeakAutoVar : public TestFixture {
public:
TestLeakAutoVar() : TestFixture("TestLeakAutoVar") {}
private:
Settings settings;
void run() override {
settings = settingsBuilder(settings).library("std.cfg").build();
// Assign
TEST_CASE(assign1);
TEST_CASE(assign2);
TEST_CASE(assign3);
TEST_CASE(assign4);
TEST_CASE(assign5);
TEST_CASE(assign6);
TEST_CASE(assign7);
TEST_CASE(assign8);
TEST_CASE(assign9);
TEST_CASE(assign10);
TEST_CASE(assign11); // #3942: x = a(b(p));
TEST_CASE(assign12); // #4236: FP. bar(&x);
TEST_CASE(assign13); // #4237: FP. char*&ref=p; p=malloc(10); free(ref);
TEST_CASE(assign14);
TEST_CASE(assign15);
TEST_CASE(assign16);
TEST_CASE(assign17); // #9047
TEST_CASE(assign18);
TEST_CASE(assign19);
TEST_CASE(assign20); // #9187
TEST_CASE(assign21); // #10186
TEST_CASE(assign22); // #9139
TEST_CASE(assign23);
TEST_CASE(assign24); // #7440
TEST_CASE(assign25);
TEST_CASE(assign26);
TEST_CASE(memcpy1); // #11542
TEST_CASE(memcpy2);
TEST_CASE(isAutoDealloc);
TEST_CASE(realloc1);
TEST_CASE(realloc2);
TEST_CASE(realloc3);
TEST_CASE(realloc4);
TEST_CASE(realloc5); // #9292, #9990
TEST_CASE(freopen1);
TEST_CASE(freopen2);
TEST_CASE(deallocuse1);
TEST_CASE(deallocuse3);
TEST_CASE(deallocuse4);
TEST_CASE(deallocuse5); // #4018: FP. free(p), p = 0;
TEST_CASE(deallocuse6); // #4034: FP. x = p = f();
TEST_CASE(deallocuse7); // #6467, #6469, #6473
TEST_CASE(deallocuse8); // #1765
TEST_CASE(deallocuse9); // #9781
TEST_CASE(deallocuse10);
TEST_CASE(deallocuse11); // #8302
TEST_CASE(deallocuse12);
TEST_CASE(deallocuse13);
TEST_CASE(deallocuse14);
TEST_CASE(deallocuse15);
TEST_CASE(deallocuse16); // #8109: delete with comma operator
TEST_CASE(doublefree1);
TEST_CASE(doublefree2);
TEST_CASE(doublefree3); // #4914
TEST_CASE(doublefree4); // #5451 - FP when exit is called
TEST_CASE(doublefree5); // #5522
TEST_CASE(doublefree6); // #7685
TEST_CASE(doublefree7);
TEST_CASE(doublefree8);
TEST_CASE(doublefree9);
TEST_CASE(doublefree10); // #8706
TEST_CASE(doublefree11);
TEST_CASE(doublefree12); // #10502
TEST_CASE(doublefree13); // #11008
TEST_CASE(doublefree14); // #9708
TEST_CASE(doublefree15);
TEST_CASE(doublefree16);
TEST_CASE(doublefree17); // #8109: delete with comma operator
// exit
TEST_CASE(exit1);
TEST_CASE(exit2);
TEST_CASE(exit3);
TEST_CASE(exit4);
// handling function calls
TEST_CASE(functioncall1);
// goto
TEST_CASE(goto1);
TEST_CASE(goto2);
TEST_CASE(goto3); // #11431
// if/else
TEST_CASE(ifelse1);
TEST_CASE(ifelse2);
TEST_CASE(ifelse3);
TEST_CASE(ifelse4);
TEST_CASE(ifelse5);
TEST_CASE(ifelse6); // #3370
TEST_CASE(ifelse7); // #5576 - if (fd < 0)
TEST_CASE(ifelse8); // #5747 - if (fd == -1)
TEST_CASE(ifelse9); // #5273 - if (X(p==NULL, 0))
TEST_CASE(ifelse10); // #8794 - if (!(x!=NULL))
TEST_CASE(ifelse11); // #8365 - if (NULL == (p = malloc(4)))
TEST_CASE(ifelse12); // #8340 - if ((*p = malloc(4)) == NULL)
TEST_CASE(ifelse13); // #8392
TEST_CASE(ifelse14); // #9130 - if (x == (char*)NULL)
TEST_CASE(ifelse15); // #9206 - if (global_ptr = malloc(1))
TEST_CASE(ifelse16); // #9635 - if (p = malloc(4), p == NULL)
TEST_CASE(ifelse17); // if (!!(!p))
TEST_CASE(ifelse18);
TEST_CASE(ifelse19);
TEST_CASE(ifelse20); // #10182
TEST_CASE(ifelse21);
TEST_CASE(ifelse22); // #10187
TEST_CASE(ifelse23); // #5473
TEST_CASE(ifelse24); // #1733
TEST_CASE(ifelse25); // #9966
TEST_CASE(ifelse26);
TEST_CASE(ifelse27);
TEST_CASE(ifelse28); // #11038
TEST_CASE(ifelse29);
// switch
TEST_CASE(switch1);
// loops
TEST_CASE(loop1);
TEST_CASE(loop2);
// mismatching allocation/deallocation
TEST_CASE(mismatchAllocDealloc);
TEST_CASE(smartPointerDeleter);
TEST_CASE(smartPointerRelease);
// Execution reaches a 'return'
TEST_CASE(return1);
TEST_CASE(return2);
TEST_CASE(return3);
TEST_CASE(return4);
TEST_CASE(return5);
TEST_CASE(return6); // #8282 return {p, p}
TEST_CASE(return7); // #9343 return (uint8_t*)x
TEST_CASE(return8);
TEST_CASE(return9);
TEST_CASE(return10);
TEST_CASE(return11); // #13098
// General tests: variable type, allocation type, etc
TEST_CASE(test1);
TEST_CASE(test2);
TEST_CASE(test3); // #3954 - reference pointer
TEST_CASE(test4); // #5923 - static pointer
TEST_CASE(test5); // unknown type
// Execution reaches a 'throw'
TEST_CASE(throw1);
TEST_CASE(throw2);
// Possible leak => Further configuration is needed for complete analysis
TEST_CASE(configuration1);
TEST_CASE(configuration2);
TEST_CASE(configuration3);
TEST_CASE(configuration4);
TEST_CASE(configuration5);
TEST_CASE(configuration6);
TEST_CASE(ptrptr);
TEST_CASE(nestedAllocation);
TEST_CASE(testKeywords); // #6767
TEST_CASE(inlineFunction); // #3989
TEST_CASE(smartPtrInContainer); // #8262
TEST_CASE(functionCallCastConfig); // #9652
TEST_CASE(functionCallLeakIgnoreConfig); // #7923
}
#define check(...) check_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
void check_(const char* file, int line, const char (&code)[size], bool cpp = false, const Settings *s = nullptr) {
const Settings settings1 = settingsBuilder(s ? *s : settings).checkLibrary().build();
// Tokenize..
SimpleTokenizer tokenizer(settings1, *this);
ASSERT_LOC(tokenizer.tokenize(code, cpp), file, line);
// Check for leaks..
runChecks<CheckLeakAutoVar>(tokenizer, this);
}
template<size_t size>
void check_(const char* file, int line, const char (&code)[size], const Settings & s) {
const Settings settings0 = settingsBuilder(s).checkLibrary().build();
// Tokenize..
SimpleTokenizer tokenizer(settings0, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
// Check for leaks..
runChecks<CheckLeakAutoVar>(tokenizer, this);
}
void assign1() {
check("void f() {\n"
" char *p = malloc(10);\n"
" p = NULL;\n"
" free(p);\n"
"}");
ASSERT_EQUALS("[test.c:3]: (error) Memory leak: p\n", errout_str());
}
void assign2() {
check("void f() {\n"
" char *p = malloc(10);\n"
" char *q = p;\n"
" free(q);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void assign3() {
check("void f() {\n"
" char *p = malloc(10);\n"
" char *q = p + 1;\n"
" free(q - 1);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void assign4() {
check("void f() {\n"
" char *a = malloc(10);\n"
" a += 10;\n"
" free(a - 10);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void assign5() {
check("void foo()\n"
"{\n"
" char *p = new char[100];\n"
" list += p;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void assign6() { // #2806 - FP when there is redundant assignment
check("void foo() {\n"
" char *p = malloc(10);\n"
" p = strcpy(p,q);\n"
" free(p);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void assign7() {
check("void foo(struct str *d) {\n"
" struct str *p = malloc(10);\n"
" d->p = p;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void assign8() { // linux list
check("void foo(struct str *d) {\n"
" struct str *p = malloc(10);\n"
" d->p = &p->x;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void assign9() {
check("void foo() {\n"
" char *p = x();\n"
" free(p);\n"
" p = NULL;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void assign10() {
check("void foo() {\n"
" char *p;\n"
" if (x) { p = malloc(10); }\n"
" if (!x) { p = NULL; }\n"
" free(p);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void assign11() { // #3942 - FP for x = a(b(p));
check("void f() {\n"
" char *p = malloc(10);\n"
" x = a(b(p));\n"
"}");
ASSERT_EQUALS("[test.c:4]: (information) --check-library: Function b() should have <use>/<leak-ignore> configuration\n", errout_str());
}
void assign12() { // #4236: FP. bar(&x)
check("void f() {\n"
" char *p = malloc(10);\n"
" free(p);\n"
" bar(&p);\n"
" free(p);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void assign13() { // #4237: FP. char *&ref=p; p=malloc(10); free(ref);
check("void f() {\n"
" char *p;\n"
" char * &ref = p;\n"
" p = malloc(10);\n"
" free(ref);\n"
"}", /*cpp*/ true);
TODO_ASSERT_EQUALS("", "[test.cpp:6]: (error) Memory leak: p\n", errout_str());
}
void assign14() {
check("void f(int x) {\n"
" char *p;\n"
" if (x && (p = malloc(10))) { }"
"}");
ASSERT_EQUALS("[test.c:3]: (error) Memory leak: p\n", errout_str());
check("void f(int x) {\n"
" char *p;\n"
" if (x && (p = new char[10])) { }"
"}", true);
ASSERT_EQUALS("[test.cpp:3]: (error) Memory leak: p\n", errout_str());
}
void assign15() {
// #8120
check("void f() {\n"
" baz *p;\n"
" p = malloc(sizeof *p);\n"
" free(p);\n"
" p = malloc(sizeof *p);\n"
" free(p);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void assign16() {
check("void f() {\n"
" char *p = malloc(10);\n"
" free(p);\n"
" if (p=dostuff()) *p = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void assign17() { // #9047
check("void f() {\n"
" char *p = (char*)malloc(10);\n"
"}");
ASSERT_EQUALS("[test.c:3]: (error) Memory leak: p\n", errout_str());
check("void f() {\n"
" char *p = (char*)(int*)malloc(10);\n"
"}");
ASSERT_EQUALS("[test.c:3]: (error) Memory leak: p\n", errout_str());
}
void assign18() {
check("void f(int x) {\n"
" char *p;\n"
" if (x && (p = (char*)malloc(10))) { }"
"}");
ASSERT_EQUALS("[test.c:3]: (error) Memory leak: p\n", errout_str());
check("void f(int x) {\n"
" char *p;\n"
" if (x && (p = (char*)(int*)malloc(10))) { }"
"}");
ASSERT_EQUALS("[test.c:3]: (error) Memory leak: p\n", errout_str());
}
void assign19() {
check("void f() {\n"
" char *p = malloc(10);\n"
" free((void*)p);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void assign20() { // #9187
check("void f() {\n"
" char *p = static_cast<int>(malloc(10));\n"
"}", true);
ASSERT_EQUALS("[test.cpp:3]: (error) Memory leak: p\n", errout_str());
}
void assign21() {
check("void f(int **x) {\n" // #10186
" void *p = malloc(10);\n"
" *x = (int*)p;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("struct S { int i; };\n" // #10996
"void f() {\n"
" S* s = new S();\n"
" (void)s;\n"
"}", true);
ASSERT_EQUALS("[test.cpp:5]: (error) Memory leak: s\n", errout_str());
}
void assign22() { // #9139
const Settings s = settingsBuilder().library("posix.cfg").build();
check("void f(char tempFileName[256]) {\n"
" const int fd = socket(AF_INET, SOCK_PACKET, 0 );\n"
"}", true, &s);
ASSERT_EQUALS("[test.cpp:3]: (error) Resource leak: fd\n", errout_str());
check("void f() {\n"
" const void * const p = malloc(10);\n"
"}", true);
ASSERT_EQUALS("[test.cpp:3]: (error) Memory leak: p\n", errout_str());
}
void assign23() {
const Settings s = settingsBuilder().library("posix.cfg").build();
check("void f() {\n"
" int n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11, n12, n13, n14;\n"
" *&n1 = open(\"xx.log\", O_RDONLY);\n"
" *&(n2) = open(\"xx.log\", O_RDONLY);\n"
" *(&n3) = open(\"xx.log\", O_RDONLY);\n"
" *&*&n4 = open(\"xx.log\", O_RDONLY);\n"
" *&*&*&(n5) = open(\"xx.log\", O_RDONLY);\n"
" *&*&(*&n6) = open(\"xx.log\", O_RDONLY);\n"
" *&*(&*&n7) = open(\"xx.log\", O_RDONLY);\n"
" *(&*&n8) = open(\"xx.log\", O_RDONLY);\n"
" *&(*&*&(*&n9)) = open(\"xx.log\", O_RDONLY);\n"
" (n10) = open(\"xx.log\", O_RDONLY);\n"
" ((n11)) = open(\"xx.log\", O_RDONLY);\n"
" ((*&n12)) = open(\"xx.log\", O_RDONLY);\n"
" *(&(*&n13)) = open(\"xx.log\", O_RDONLY);\n"
" ((*&(*&n14))) = open(\"xx.log\", O_RDONLY);\n"
"}\n", true, &s);
ASSERT_EQUALS("[test.cpp:17]: (error) Resource leak: n1\n"
"[test.cpp:17]: (error) Resource leak: n2\n"
"[test.cpp:17]: (error) Resource leak: n3\n"
"[test.cpp:17]: (error) Resource leak: n4\n"
"[test.cpp:17]: (error) Resource leak: n5\n"
"[test.cpp:17]: (error) Resource leak: n6\n"
"[test.cpp:17]: (error) Resource leak: n7\n"
"[test.cpp:17]: (error) Resource leak: n8\n"
"[test.cpp:17]: (error) Resource leak: n9\n"
"[test.cpp:17]: (error) Resource leak: n10\n"
"[test.cpp:17]: (error) Resource leak: n11\n"
"[test.cpp:17]: (error) Resource leak: n12\n"
"[test.cpp:17]: (error) Resource leak: n13\n"
"[test.cpp:17]: (error) Resource leak: n14\n",
errout_str());
}
void assign24() {
check("void f() {\n" // #7440
" char* data = new char[100];\n"
" char** dataPtr = &data;\n"
" delete[] *dataPtr;\n"
"}\n", true);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" char* data = new char[100];\n"
" char** dataPtr = &data;\n"
" printf(\"test\");\n"
" delete[] *dataPtr;\n"
"}\n", true);
ASSERT_EQUALS("", errout_str());
check("void f() {\n" // #9279
" int* p = new int;\n"
" *p = 42;\n"
" g();\n"
"}\n", /*cpp*/ true);
ASSERT_EQUALS("[test.cpp:4]: (information) --check-library: Function g() should have <noreturn> configuration\n",
errout_str());
check("void g();\n"
"void f() {\n"
" int* p = new int;\n"
" *p = 42;\n"
" g();\n"
"}\n", /*cpp*/ true);
ASSERT_EQUALS("[test.cpp:6]: (error) Memory leak: p\n", errout_str());
check("void g() {}\n"
"void f() {\n"
" int* p = new int;\n"
" *p = 42;\n"
" g();\n"
"}\n", /*cpp*/ true);
ASSERT_EQUALS("[test.cpp:6]: (error) Memory leak: p\n", errout_str());
check("[[noreturn]] void g();\n"
"void f() {\n"
" int* p = new int;\n"
" *p = 42;\n"
" g();\n"
"}\n", /*cpp*/ true);
ASSERT_EQUALS("", errout_str());
check("void g() { exit(1); }\n"
"void f() {\n"
" int* p = new int;\n"
" *p = 42;\n"
" g();\n"
"}\n", /*cpp*/ true);
ASSERT_EQUALS("", errout_str());
check("void g() {}\n" // #10517
"void f() {\n"
" char* p = malloc(10);\n"
" g();\n"
"}\n");
ASSERT_EQUALS("[test.c:5]: (error) Memory leak: p\n", errout_str());
}
void assign25() {
check("void f() {\n" // #11796
" int* p{ new int };\n"
" int* q(new int);\n"
"}", true);
ASSERT_EQUALS("[test.cpp:4]: (error) Memory leak: p\n"
"[test.cpp:4]: (error) Memory leak: q\n",
errout_str());
check("struct S : B {\n" // #12239
" void f();\n"
" void g();\n"
"};\n"
"void S::f() {\n"
" FD* fd(new FD(this));\n"
" fd->exec();\n"
"}\n"
"void S::g() {\n"
" FD* fd{ new FD(this) };\n"
" fd->exec();\n"
"}\n", true);
ASSERT_EQUALS("", errout_str());
check("struct C {\n" // #12327
" char* m_p;\n"
" C(char* p) : m_p(p) {}\n"
"};\n"
"std::list<C> gli;\n"
"void f() {\n"
" std::list<C> li;\n"
" char* p = new char[1];\n"
" C c(p);\n"
" li.push_back(c);\n"
" C c2(li.front());\n"
" delete[] c2.m_p;\n"
"}\n"
"void g() {\n"
" char* p = new char[1];\n"
" C c(p);\n"
" gli.push_back(c);\n"
"}\n"
"void h() {\n"
" std::list<C> li;\n"
" char* p = new char[1];\n"
" C c(p);\n"
" li.push_back(c);\n"
" delete[] li.front().m_p;\n"
"}\n", true);
ASSERT_EQUALS("", errout_str());
check("struct S {\n" // #12890
" int** p;\n"
" S() {\n"
" p = std::malloc(sizeof(int*));\n"
" p[0] = new int;\n"
" }\n"
" ~S() {\n"
" delete p[0];\n"
" std::free(p);\n"
" }\n"
"};\n", true);
ASSERT_EQUALS("", errout_str());
}
void assign26() {
check("void f(int*& x) {\n" // #8235
" int* p = (int*)malloc(10);\n"
" x = p ? p : nullptr;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("void f(int*& x) {\n"
" int* p = (int*)malloc(10);\n"
" x = p != nullptr ? p : nullptr;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
}
void memcpy1() { // #11542
const Settings s = settingsBuilder().library("std.cfg").build();
check("void f(char** old, char* value) {\n"
" char *str = strdup(value);\n"
" memcpy(old, &str, sizeof(char*));\n"
"}\n", &s);
ASSERT_EQUALS("", errout_str());
}
void memcpy2() {
const Settings s = settingsBuilder().library("std.cfg").build();
check("void f(char* old, char* value, size_t len) {\n"
" char *str = strdup(value);\n"
" memcpy(old, str, len);\n"
"}\n", &s);
ASSERT_EQUALS("[test.cpp:4]: (error) Memory leak: str\n", errout_str());
}
void isAutoDealloc() {
check("void f() {\n"
" char *p = new char[100];"
"}", true);
ASSERT_EQUALS("[test.cpp:2]: (error) Memory leak: p\n", errout_str());
check("void f() {\n"
" Fred *fred = new Fred;"
"}", true);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" std::string *str = new std::string;"
"}", true);
ASSERT_EQUALS("[test.cpp:2]: (error) Memory leak: str\n", errout_str());
check("class TestType {\n" // #9028
"public:\n"
" char ca[12];\n"
"};\n"
"void f() {\n"
" TestType *tt = new TestType();\n"
"}", true);
ASSERT_EQUALS("[test.cpp:7]: (error) Memory leak: tt\n", errout_str());
check("void f(Bar& b) {\n" // #7622
" char* data = new char[10];\n"
" b = Bar(*new Foo(data));\n"
"}", /*cpp*/ true);
ASSERT_EQUALS("[test.cpp:4]: (information) --check-library: Function Foo() should have <use>/<leak-ignore> configuration\n", errout_str());
check("class B {};\n"
" class D : public B {};\n"
" void g() {\n"
" auto d = new D();\n"
" if (d) {}\n"
"}", /*cpp*/ true);
ASSERT_EQUALS("[test.cpp:6]: (error) Memory leak: d\n", errout_str());
check("struct S {\n" // #12354
" int i{};\n"
" void f();\n"
"};\n"
"void f(S* p, bool b) {\n"
" if (b)\n"
" p = new S();\n"
" p->f();\n"
"}", /*cpp*/ true);
ASSERT_EQUALS("[test.cpp:9]: (error) Memory leak: p\n", errout_str());
}
void realloc1() {
check("void f() {\n"
" void *p = malloc(10);\n"
" void *q = realloc(p, 20);\n"
" free(q)\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void realloc2() {
check("void f() {\n"
" void *p = malloc(10);\n"
" void *q = realloc(p, 20);\n"
"}");
ASSERT_EQUALS("[test.c:4]: (error) Memory leak: q\n", errout_str());
}
void realloc3() {
check("void f() {\n"
" char *p = malloc(10);\n"
" char *q = (char*) realloc(p, 20);\n"
"}");
ASSERT_EQUALS("[test.c:4]: (error) Memory leak: q\n", errout_str());
}
void realloc4() {
check("void f(void *p) {\n"
" void * q = realloc(p, 10);\n"
" if (q == NULL)\n"
" return;\n"
"}");
ASSERT_EQUALS("[test.c:5]: (error) Memory leak: q\n", errout_str());
}
void realloc5() {
// #9292
check("void * f(void * ptr, size_t size) {\n"
" void *datap = realloc(ptr, size);\n"
" if (size && !datap)\n"
" free(ptr);\n"
" return datap;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #9990
check("void f() {\n"
" void * p1 = malloc(10);\n"
" if (!p1)\n"
" return;\n"
" void * p2 = realloc(p1, 42);\n"
" if (!p2) {\n"
" free(p1);\n"
" return;\n"
" }\n"
" free(p2);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void freopen1() {
check("void f() {\n"
" void *p = fopen(name,a);\n"
" void *q = freopen(name, b, p);\n"
" fclose(q)\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void freopen2() {
check("void f() {\n"
" void *p = fopen(name,a);\n"
" void *q = freopen(name, b, p);\n"
"}");
ASSERT_EQUALS("[test.c:4]: (error) Resource leak: q\n", errout_str());
}
void deallocuse1() {
check("void f(char *p) {\n"
" free(p);\n"
" *p = 0;\n"
"}");
ASSERT_EQUALS("[test.c:3]: (error) Dereferencing 'p' after it is deallocated / released\n", errout_str());
check("void f(char *p) {\n"
" free(p);\n"
" char c = *p;\n"
"}");
ASSERT_EQUALS("[test.c:3]: (error) Dereferencing 'p' after it is deallocated / released\n", errout_str());
}
void deallocuse3() {
check("void f(struct str *p) {\n"
" free(p);\n"
" p = p->next;\n"
"}");
ASSERT_EQUALS("[test.c:3]: (error) Dereferencing 'p' after it is deallocated / released\n", errout_str());
}
void deallocuse4() {
check("void f(char *p) {\n"
" free(p);\n"
" return p;\n"
"}");
ASSERT_EQUALS("[test.c:2] -> [test.c:3]: (error) Returning/dereferencing 'p' after it is deallocated / released\n", errout_str());
check("void f(char *p) {\n"
" if (!p) free(p);\n"
" return p;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(char *p) {\n"
" if (!p) delete p;\n"
" return p;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("void f(char *p) {\n"
" if (!p) delete [] p;\n"
" return p;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("void f(void* p) {\n"
" if (a) {\n"
" free(p);\n"
" return;\n"
" }\n"
" g(p);\n"
" return;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void deallocuse5() { // #4018
check("void f(char *p) {\n"
" free(p), p = 0;\n"
" *p = 0;\n" // <- Make sure pointer info is reset. It is NOT a freed pointer dereference
"}");
ASSERT_EQUALS("", errout_str());
}
void deallocuse6() { // #4034
check("void f(char *p) {\n"
" free(p);\n"
" x = p = foo();\n" // <- p is not dereferenced
"}");
ASSERT_EQUALS("", errout_str());
}
void deallocuse7() { // #6467, #6469, #6473, #6648
check("struct Foo { int* ptr; };\n"
"void f(Foo* foo) {\n"
" delete foo->ptr;\n"
" foo->ptr = new Foo;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("struct Foo { int* ptr; };\n"
"void f(Foo* foo) {\n"
" delete foo->ptr;\n"
" x = *foo->ptr;\n"
"}", true);
TODO_ASSERT_EQUALS("[test.cpp:4]: (error) Dereferencing 'ptr' after it is deallocated / released\n", "", errout_str());
check("void parse() {\n"
" struct Buf {\n"
" Buf(uint32_t len) : m_buf(new uint8_t[len]) {}\n"
" ~Buf() { delete[]m_buf; }\n"
" uint8_t *m_buf;\n"
" };\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("struct Foo {\n"
" Foo();\n"
" Foo* ptr;\n"
" void func();\n"
"};\n"
"void bar(Foo* foo) {\n"
" delete foo->ptr;\n"
" foo->ptr = new Foo;\n"
" foo->ptr->func();\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("void foo(void (*conv)(char**)) {\n"
" char * ptr=(char*)malloc(42);\n"
" free(ptr);\n"
" (*conv)(&ptr);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void deallocuse8() { // #1765
check("void f() {\n"
" int *ptr = new int;\n"
" delete(ptr);\n"
" *ptr = 0;\n"
"}", true);
ASSERT_EQUALS("[test.cpp:4]: (error) Dereferencing 'ptr' after it is deallocated / released\n", errout_str());
}
void deallocuse9() {
check("void f(Type* p) {\n" // #9781
" std::shared_ptr<Type> sp(p);\n"
" bool b = p->foo();\n"
" return b;\n"
"}\n", /*cpp*/ true);
ASSERT_EQUALS("", errout_str());
check("struct A {\n" // #8635
" std::vector<std::unique_ptr<A>> array_;\n"
" A* foo() {\n"
" A* a = new A();\n"
" array_.push_back(std::unique_ptr<A>(a));\n"
" return a;\n"
" }\n"
"};\n", /*cpp*/ true);
ASSERT_EQUALS("", errout_str());
check("int g(int *p) {\n" // #9838
" std::unique_ptr<int> temp(p);\n"
" return DoSomething(p);\n"
"}\n"
"int f() {\n"
" return g(new int(3));\n"
"}\n", /*cpp*/ true);
ASSERT_EQUALS("", errout_str());
}
void deallocuse10() {
check("void f(char* p) {\n"
" free(p);\n"
" p[0] = 10;\n"
"}\n");
ASSERT_EQUALS("[test.c:3]: (error) Dereferencing 'p' after it is deallocated / released\n", errout_str());
check("int f(int* p) {\n"
" free(p);\n"
" return p[1];\n"
"}\n");
ASSERT_EQUALS("[test.c:2] -> [test.c:3]: (error) Returning/dereferencing 'p' after it is deallocated / released\n", errout_str());
}
void deallocuse11() { // #8302
check("int f() {\n"
" int *array = new int[42];\n"
" delete [] array;\n"
" return array[1];" // <<
"}", true);
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (error) Returning/dereferencing 'array' after it is deallocated / released\n", errout_str());
check("int f() {\n"
" int *array = (int*)malloc(40);\n"
" free(array);\n"
" return array[1];" // <<
"}");
ASSERT_EQUALS("[test.c:3] -> [test.c:4]: (error) Returning/dereferencing 'array' after it is deallocated / released\n", errout_str());
}
void deallocuse12() {
check("struct foo { int x; }\n"
"void f1(struct foo *f) {\n"
" free(f);\n"
"}\n"
"void f2(struct foo *f, int *out) {\n"
" *out = f->x;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void deallocuse13() {
check("void f() {\n" // #9695
" auto* a = new int[2];\n"
" delete[] a;\n"
" a[1] = 0;\n"
" auto* b = static_cast<int*>(malloc(8));\n"
" free(b);\n"
" b[1] = 0;\n"
"}\n", true);
ASSERT_EQUALS("[test.cpp:4]: (error) Dereferencing 'a' after it is deallocated / released\n"
"[test.cpp:7]: (error) Dereferencing 'b' after it is deallocated / released\n",
errout_str());
}
void deallocuse14() {
check("struct S { void f(); };\n" // #10905
"void g() {\n"
" S* s = new S;\n"
" delete s;\n"
" s->f();\n"
"}\n", true);
ASSERT_EQUALS("[test.cpp:5]: (error) Dereferencing 's' after it is deallocated / released\n",
errout_str());
check("void f() {\n"
" int *p = (int*)malloc(4);\n"
" free(p);\n"
" if (*p == 5) {}\n"
"}\n");
ASSERT_EQUALS("[test.c:4]: (error) Dereferencing 'p' after it is deallocated / released\n",
errout_str());
check("int g(int);\n"
"void f(int* p) {\n"
" free(p);\n"
" g(*p);\n"
"}\n"
"int h(int* p) {\n"
" free(p);\n"
" return g(*p);\n"
"}\n");
ASSERT_EQUALS("[test.c:4]: (error) Dereferencing 'p' after it is deallocated / released\n"
"[test.c:7] -> [test.c:8]: (error) Returning/dereferencing 'p' after it is deallocated / released\n",
errout_str());
check("int g(int);\n"
"void f(int* p) {\n"
" free(p);\n"
" g(1 + *p);\n"
"}\n"
"int h(int* p) {\n"
" free(p);\n"
" return g(1 + *p);\n"
"}\n");
ASSERT_EQUALS("[test.c:4]: (error) Dereferencing 'p' after it is deallocated / released\n"
"[test.c:7] -> [test.c:8]: (error) Returning/dereferencing 'p' after it is deallocated / released\n",
errout_str());
check("int g(int, int);\n"
"void f(int* p) {\n"
" free(p);\n"
" g(0, 1 + *p);\n"
"}\n"
"int h(int* p) {\n"
" free(p);\n"
" return g(0, 1 + *p);\n"
"}\n");
ASSERT_EQUALS("[test.c:4]: (error) Dereferencing 'p' after it is deallocated / released\n"
"[test.c:7] -> [test.c:8]: (error) Returning/dereferencing 'p' after it is deallocated / released\n",
errout_str());
check("void f() {\n"
" FOREACH(callables, ());\n"
"}\n");
ASSERT_EQUALS("[test.c:2]: (information) --check-library: Function FOREACH() should have <noreturn> configuration\n", errout_str()); // don't crash
check("int f() {\n" // #12321
" std::invoke([](int i) {\n"
" int* p = (int*)malloc(4);\n"
" *p = 0;\n"
" if (i) {\n"
" free(p);\n"
" return;\n"
" }\n"
" free(p);\n"
" }, 1);\n"
" return 0;\n"
"}\n", /*cpp*/ true);
ASSERT_EQUALS("", errout_str());
}
void deallocuse15() {
check("bool FileExists(const char* filename) {\n" // #12490
" FILE* f = fopen(filename, \"rb\");\n"
" if (f) fclose(f);\n"
" return f;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("bool f() {\n" // #12590
" FILE* fd = fopen(\"/foo/bar\", \"w\");\n"
" if (fd == nullptr)\n"
" return false;\n"
" return fclose(fd) == 0;\n"
"}\n", /*cpp*/ true);
ASSERT_EQUALS("", errout_str());
check("int f(const char* fileName) {\n" // #13136
" FILE* h = fopen(fileName, \"rb\");\n"
" if (fseek(h, 0L, SEEK_END) == -1)\n"
" fclose(h);\n"
" int i = ftell(h);\n"
" return i;\n"
"}\n");
ASSERT_EQUALS("[test.c:5]: (error) Dereferencing 'h' after it is deallocated / released\n", errout_str());
}
void deallocuse16() {
check("void f() {\n"
" int *a = nullptr;\n"
" int *c = new int;\n"
" delete (a, c);\n"
" *c = 10;\n"
"}\n", true);
ASSERT_EQUALS("[test.cpp:5]: (error) Dereferencing 'c' after it is deallocated / released\n", errout_str());
}
void doublefree1() { // #3895
check("void f(char *p) {\n"
" if (x)\n"
" free(p);\n"
" else\n"
" p = 0;\n"
" free(p);\n"
"}");
ASSERT_EQUALS("[test.c:3] -> [test.c:6]: (error) Memory pointed to by 'p' is freed twice.\n", errout_str());
check(
"void foo(char *p) {\n"
" free(p);\n"
" free(p);\n"
"}");
ASSERT_EQUALS("[test.c:2] -> [test.c:3]: (error) Memory pointed to by 'p' is freed twice.\n", errout_str());
check(
"void foo(char *p, char *r) {\n"
" free(p);\n"
" free(r);\n"
"}");
ASSERT_EQUALS("", errout_str());
check(
"void foo() {\n"
" free(p);\n"
" free(r);\n"
"}");
ASSERT_EQUALS("", errout_str());
check(
"void foo(char *p) {\n"
" if (x < 3) free(p);\n"
" else { if (x > 9) free(p); }\n"
"}");
ASSERT_EQUALS("", errout_str());
check(
"void foo(char *p) {\n"
" free(p);\n"
" getNext(&p);\n"
" free(p);\n"
"}");
ASSERT_EQUALS("", errout_str());
check(
"void foo(char *p) {\n"
" free(p);\n"
" bar();\n"
" free(p);\n"
"}");
ASSERT_EQUALS("[test.c:2] -> [test.c:4]: (error) Memory pointed to by 'p' is freed twice.\n", errout_str());
check(
"void foo(char *p) {\n"
" free(p);\n"
" printf(\"Freed memory at location %x\", p);\n"
" free(p);\n"
"}");
ASSERT_EQUALS("[test.c:3]: (error) Dereferencing 'p' after it is deallocated / released\n"
"[test.c:2] -> [test.c:4]: (error) Memory pointed to by 'p' is freed twice.\n",
errout_str());
check(
"void foo(FILE *p) {\n"
" fclose(p);\n"
" fclose(p);\n"
"}");
ASSERT_EQUALS("[test.c:2] -> [test.c:3]: (error) Resource handle 'p' freed twice.\n", errout_str());
check(
"void foo(FILE *p, FILE *r) {\n"
" fclose(p);\n"
" fclose(r);\n"
"}");
ASSERT_EQUALS("", errout_str());
check(
"void foo(FILE *p) {\n"
" if (x < 3) fclose(p);\n"
" else { if (x > 9) fclose(p); }\n"
"}");
ASSERT_EQUALS("", errout_str());
check(
"void foo(FILE *p) {\n"
" fclose(p);\n"
" gethandle(&p);\n"
" fclose(p);\n"
"}");
ASSERT_EQUALS("", errout_str());
check(
"void foo(FILE *p) {\n"
" fclose(p);\n"
" gethandle();\n"
" fclose(p);\n"
"}");
ASSERT_EQUALS("[test.c:2] -> [test.c:4]: (error) Resource handle 'p' freed twice.\n", errout_str());
check(
"void foo(Data* p) {\n"
" free(p->a);\n"
" free(p->b);\n"
"}");
ASSERT_EQUALS("", errout_str());
check(
"void f() {\n"
" char *p; p = malloc(100);\n"
" if (x) {\n"
" free(p);\n"
" exit();\n"
" }\n"
" free(p);\n"
"}");
ASSERT_EQUALS("", errout_str());
check(
"void f() {\n"
" char *p; p = malloc(100);\n"
" if (x) {\n"
" free(p);\n"
" x = 0;\n"
" }\n"
" free(p);\n"
"}");
ASSERT_EQUALS("[test.c:4] -> [test.c:7]: (error) Memory pointed to by 'p' is freed twice.\n", errout_str());
check(
"void f() {\n"
" char *p; p = do_something();\n"
" free(p);\n"
" p = do_something();\n"
" free(p);\n"
"}");
ASSERT_EQUALS("", errout_str());
check(
"void foo(char *p) {\n"
" delete p;\n"
" delete p;\n"
"}", true);
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (error) Memory pointed to by 'p' is freed twice.\n", errout_str());
check(
"void foo(char *p, char *r) {\n"
" delete p;\n"
" delete r;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check(
"void foo(P p) {\n"
" delete p.x;\n"
" delete p;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check(
"void foo(char **p) {\n"
" delete p[0];\n"
" delete p[1];\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check(
"void foo(char *p) {\n"
" delete p;\n"
" getNext(&p);\n"
" delete p;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check(
"void foo(char *p) {\n"
" delete p;\n"
" bar();\n"
" delete p;\n"
"}", true);
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:4]: (error) Memory pointed to by 'p' is freed twice.\n", errout_str());
check(
"void foo(char *p) {\n"
" delete[] p;\n"
" delete[] p;\n"
"}", true);
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (error) Memory pointed to by 'p' is freed twice.\n", errout_str());
check(
"void foo(char *p, char *r) {\n"
" delete[] p;\n"
" delete[] r;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check(
"void foo(char *p) {\n"
" delete[] p;\n"
" getNext(&p);\n"
" delete[] p;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check(
"void foo(char *p) {\n"
" delete[] p;\n"
" bar();\n"
" delete[] p;\n"
"}", true);
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:4]: (error) Memory pointed to by 'p' is freed twice.\n", errout_str());
check(
"LineMarker::~LineMarker() {\n"
" delete pxpm;\n"
"}\n"
"LineMarker &LineMarker::operator=(const LineMarker &) {\n"
" delete pxpm;\n"
" pxpm = NULL;\n"
" return *this;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check(
"void foo()\n"
"{\n"
" int* ptr; ptr = NULL;\n"
" try\n"
" {\n"
" ptr = new int(4);\n"
" }\n"
" catch(...)\n"
" {\n"
" delete ptr;\n"
" throw;\n"
" }\n"
" delete ptr;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check(
"int foo()\n"
"{\n"
" int* a; a = new int;\n"
" bool doDelete; doDelete = true;\n"
" if (a != 0)\n"
" {\n"
" doDelete = false;\n"
" delete a;\n"
" }\n"
" if(doDelete)\n"
" delete a;\n"
" return 0;\n"
"}", true);
TODO_ASSERT_EQUALS("", "[test.cpp:8] -> [test.cpp:11]: (error) Memory pointed to by 'a' is freed twice.\n", errout_str());
check(
"void foo(int y)\n"
"{\n"
" char * x; x = NULL;\n"
" while(true) {\n"
" x = new char[100];\n"
" if (y++ > 100)\n"
" break;\n"
" delete[] x;\n"
" }\n"
" delete[] x;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check(
"void foo(int y)\n"
"{\n"
" char * x; x = NULL;\n"
" for (int i = 0; i < 10000; i++) {\n"
" x = new char[100];\n"
" delete[] x;\n"
" }\n"
" delete[] x;\n"
"}", true);
TODO_ASSERT_EQUALS("[test.cpp:8]: (error) Memory pointed to by 'x' is freed twice.\n", "", errout_str());
check(
"void foo(int y)\n"
"{\n"
" char * x; x = NULL;\n"
" while (isRunning()) {\n"
" x = new char[100];\n"
" delete[] x;\n"
" }\n"
" delete[] x;\n"
"}", true);
TODO_ASSERT_EQUALS("[test.cpp:8]: (error) Memory pointed to by 'x' is freed twice.\n", "", errout_str());
check(
"void foo(int y)\n"
"{\n"
" char * x; x = NULL;\n"
" while (isRunning()) {\n"
" x = malloc(100);\n"
" free(x);\n"
" }\n"
" free(x);\n"
"}");
TODO_ASSERT_EQUALS("[test.c:8]: (error) Memory pointed to by 'x' is freed twice.\n", "", errout_str());
check(
"void foo(int y)\n"
"{\n"
" char * x; x = NULL;\n"
" for (;;) {\n"
" x = new char[100];\n"
" if (y++ > 100)\n"
" break;\n"
" delete[] x;\n"
" }\n"
" delete[] x;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check(
"void foo(int y)\n"
"{\n"
" char * x; x = NULL;\n"
" do {\n"
" x = new char[100];\n"
" if (y++ > 100)\n"
" break;\n"
" delete[] x;\n"
" } while (true);\n"
" delete[] x;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check(
"void f()\n"
"{\n"
" char *p; p = 0;\n"
" if (x < 100) {\n"
" p = malloc(10);\n"
" free(p);\n"
" }\n"
" free(p);\n"
"}");
ASSERT_EQUALS("[test.c:6] -> [test.c:8]: (error) Memory pointed to by 'p' is freed twice.\n", errout_str());
check(
"void MyFunction()\n"
"{\n"
" char* data; data = new char[100];\n"
" try\n"
" {\n"
" }\n"
" catch(err)\n"
" {\n"
" delete[] data;\n"
" MyThrow(err);\n"
" }\n"
" delete[] data;\n"
"}\n"
"void MyThrow(err)\n"
"{\n"
" throw(err);\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check(
"void MyFunction()\n"
"{\n"
" char* data; data = new char[100];\n"
" try\n"
" {\n"
" }\n"
" catch(err)\n"
" {\n"
" delete[] data;\n"
" MyExit(err);\n"
" }\n"
" delete[] data;\n"
"}\n"
"void MyExit(err)\n"
"{\n"
" exit(err);\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check( // #6252
"struct Wrapper {\n"
" Thing* m_thing;\n"
" Wrapper() : m_thing(0) {\n"
" }\n"
" ~Wrapper() {\n"
" delete m_thing;\n"
" }\n"
" void changeThing() {\n"
" delete m_thing;\n"
" m_thing = new Thing;\n"
" }\n"
"};", true);
ASSERT_EQUALS("", errout_str());
// #7401
check("void pCodeLabelDestruct(pCode *pc) {\n"
" free(PCL(pc)->label);\n"
" free(pc);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void doublefree2() { // #3891
check("void *f(int a) {\n"
" char *p = malloc(10);\n"
" if (a == 2) { free(p); return ((void*)1); }\n"
" free(p);\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void doublefree3() { // #4914
check("void foo() {\n"
" bool done = false;\n"
" do {\n"
" char *bar = malloc(10)\n"
" if(condition()) {\n"
" free(bar);\n"
" continue;\n"
" }\n"
" done = true;\n"
" free(bar)\n"
" } while(!done);\n"
" return;"
"}"
);
ASSERT_EQUALS("", errout_str());
}
void doublefree4() {
check("void f(char *p) {\n" // #5451 - exit
" if (x) {\n"
" free(p);\n"
" exit(1);\n"
" }\n"
" free(p);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(void* p, int i) {\n" // #11391
" if (i)\n"
" goto cleanup;\n"
" free(p);\n"
" exit(0);\n"
"cleanup:\n"
" free(p);\n"
" exit(1);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void doublefree5() { // #5522
check("void f(char *p) {\n"
" free(p);\n"
" x = (q == p);\n"
" free(p);\n"
"}");
ASSERT_EQUALS("[test.c:2] -> [test.c:4]: (error) Memory pointed to by 'p' is freed twice.\n", errout_str());
}
void doublefree6() { // #7685
check("void do_wordexp(FILE *f) {\n"
" free(getword(f));\n"
" fclose(f);\n"
"}", /*cpp=*/ false);
ASSERT_EQUALS("", errout_str());
}
void doublefree7() {
check("void f(char *p, int x) {\n"
" free(p);\n"
" if (x && (p = malloc(10)))\n"
" free(p);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(char *p, int x) {\n"
" delete[] p;\n"
" if (x && (p = new char[10]))\n"
" delete[] p;\n"
"}", /*cpp*/ true);
ASSERT_EQUALS("", errout_str());
}
void doublefree8() {
check("void f() {\n"
" int * i = new int;\n"
" std::unique_ptr<int> x(i);\n"
" delete i;\n"
"}\n", true);
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (error) Memory pointed to by 'i' is freed twice.\n", errout_str());
check("void f() {\n"
" int * i = new int;\n"
" delete i;\n"
" std::unique_ptr<int> x(i);\n"
"}\n", true);
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (error) Memory pointed to by 'i' is freed twice.\n", errout_str());
check("void f() {\n"
" int * i = new int;\n"
" std::unique_ptr<int> x{i};\n"
" delete i;\n"
"}\n", true);
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (error) Memory pointed to by 'i' is freed twice.\n", errout_str());
check("void f() {\n"
" int * i = new int;\n"
" std::shared_ptr<int> x(i);\n"
" delete i;\n"
"}\n", true);
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (error) Memory pointed to by 'i' is freed twice.\n", errout_str());
check("void f() {\n"
" int * i = new int;\n"
" std::shared_ptr<int> x{i};\n"
" delete i;\n"
"}\n", true);
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (error) Memory pointed to by 'i' is freed twice.\n", errout_str());
// Check for use-after-free FP
check("void f() {\n"
" int * i = new int;\n"
" std::shared_ptr<int> x{i};\n"
" *i = 123;\n"
"}\n", true);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int * i = new int[1];\n"
" std::unique_ptr<int[]> x(i);\n"
" delete i;\n"
"}\n", true);
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (error) Memory pointed to by 'i' is freed twice.\n", errout_str());
check("using namespace std;\n" // #9708
"void f() {\n"
" int* i = new int;\n"
" unique_ptr<int> x(i);\n"
" delete i;\n"
"}\n", true);
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:5]: (error) Memory pointed to by 'i' is freed twice.\n", errout_str());
}
void doublefree9() {
check("struct foo {\n"
" int* get(int) { return new int(); }\n"
"};\n"
"void f(foo* b) {\n"
" std::unique_ptr<int> x(b->get(0));\n"
" std::unique_ptr<int> y(b->get(1));\n"
"}\n", true);
ASSERT_EQUALS("", errout_str());
}
void doublefree10() {
check("void f(char* s) {\n"
" char *p = malloc(strlen(s));\n"
" if (p != NULL) {\n"
" strcat(p, s);\n"
" if (strlen(s) != 10)\n"
" free(p); p = NULL;\n"
" }\n"
" if (p != NULL)\n"
" free(p);\n"
"}\n", true);
ASSERT_EQUALS("", errout_str());
check("void f(char* s) {\n"
" char *p = malloc(strlen(s));\n"
" if (p != NULL) {\n"
" strcat(p, s);\n"
" if (strlen(s) != 10)\n"
" free(p), p = NULL;\n"
" }\n"
" if (p != NULL)\n"
" free(p);\n"
"}\n", true);
ASSERT_EQUALS("", errout_str());
}
void doublefree11() {
check("void f() {\n"
" void * p = malloc(5);\n"
" void * q = realloc(p, 10);\n"
" if (q == NULL) {\n"
" free(p);\n"
" return;\n"
" }\n"
" free(p);\n"
" if (q == NULL)\n"
" return;\n"
" free(q);\n"
"}");
ASSERT_EQUALS("[test.c:3] -> [test.c:8]: (error) Memory pointed to by 'p' is freed twice.\n", errout_str());
}
void doublefree12() { // #10502
check("int f(FILE *fp, const bool b) {\n"
" if (b)\n"
" return fclose(fp);\n"
" fclose(fp);\n"
" return 0;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void doublefree13() { // #11008
check("struct buf_t { void* ptr; };\n"
"void f() {\n"
" struct buf_t buf;\n"
" if ((buf.ptr = malloc(10)) == NULL)\n"
" return;\n"
" free(buf.ptr);\n"
" if ((buf.ptr = malloc(10)) == NULL)\n"
" return;\n"
" free(buf.ptr);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void doublefree14() { // #9708
check("using namespace std;\n"
" \n"
"int main()\n"
"{\n"
" int *i = new int;\n"
" unique_ptr<int> x(i);\n"
" delete i;\n"
"}", true);
ASSERT_EQUALS("[test.cpp:6] -> [test.cpp:7]: (error) Memory pointed to by 'i' is freed twice.\n", errout_str());
check("using namespace std;\n"
" \n"
"int main()\n"
"{\n"
" int *i = new int;\n"
" unique_ptr<int> x(i);\n"
"}", true);
ASSERT_EQUALS("", errout_str());
}
void doublefree15() { // #11966
check("void f(FILE* fp) {\n"
" static_cast<void>(fclose(fp));\n"
"}", true);
ASSERT_EQUALS("", errout_str());
}
void doublefree16() { // #12236
check("void f() {\n"
" FILE* f = fopen(\"abc\", \"r\");\n"
" decltype(fclose(f)) y;\n"
" y = fclose(f);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" FILE *fp = fopen(\"abc\", \"r\");\n"
" if (({\n"
" __typeof__(fclose(fp)) r;\n"
" r = (fclose(fp));\n"
" r;\n"
" })) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void doublefree17() {
check("void f() {\n"
" int *a = nullptr;\n"
" int *b = nullptr;\n"
" int *c = new int;\n"
" delete (a, c);\n"
" delete (b, c);\n"
"}\n", true);
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:6]: (error) Memory pointed to by 'c' is freed twice.\n", errout_str());
}
void exit1() {
check("void f() {\n"
" char *p = malloc(10);\n"
" exit(0);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void exit2() {
check("void f() {\n"
" char *p = malloc(10);\n"
" fatal_error();\n"
"}");
ASSERT_EQUALS("[test.c:3]: (information) --check-library: Function fatal_error() should have <noreturn> configuration\n",
errout_str());
}
void exit3() {
check("void f() {\n"
" char *p = malloc(100);\n"
" if (x) {\n"
" free(p);\n"
" ::exit(0);\n"
" }"
" free(p);\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" char *p = malloc(100);\n"
" if (x) {\n"
" free(p);\n"
" std::exit(0);\n"
" }"
" free(p);\n"
"}", true);
ASSERT_EQUALS("", errout_str());
}
void exit4() {
check("void __attribute__((__noreturn__)) (*func_notret)(void);\n"
"int main(int argc) {\n"
" void* ptr = malloc(1000);\n"
" if (argc == 1) {\n"
" free(ptr);\n"
" func_notret();\n"
" }\n"
" free(ptr);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void functioncall1() {
check("void f(struct S *p) {\n"
" p->x = malloc(10);\n"
" free(p->x);\n"
" p->x = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(s_t s) {\n" // #11061
" s->p = (char*)malloc(10);\n"
" free((void*)s->p);\n"
" s->p = NULL;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
const Settings s = settingsBuilder().library("std.cfg").build();
check("struct S {};\n"
"void f(int i, std::vector<std::unique_ptr<S>> &v) {\n"
" if (i < 1) {\n"
" auto s = new S;\n"
" v.push_back(std::unique_ptr<S>(s));\n"
" }\n"
"}\n", /*cpp*/ true, &s);
ASSERT_EQUALS("", errout_str()); // don't crash
check("void g(size_t len) {\n" // #12365
" char* b = new char[len + 1]{};\n"
" std::string str = std::string(b);\n"
"}", /*cpp*/ true, &s);
ASSERT_EQUALS("[test.cpp:4]: (error) Memory leak: b\n", errout_str());
}
void goto1() {
check("static void f() {\n"
" int err = -ENOMEM;\n"
" char *reg = malloc(100);\n"
" if (err) {\n"
" free(reg);\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void goto2() { // #4231
check("static char * f() {\n"
"x:\n"
" char *p = malloc(100);\n"
" if (err) {\n"
" free(p);\n"
" goto x;\n"
" }\n"
" return p;\n" // no error since there is a goto
"}");
ASSERT_EQUALS("", errout_str());
}
void goto3() { // #11431
check("void f() {\n"
" int* p = (int*)malloc(2);\n"
" if (!p) {\n"
" p = (int*)malloc(1);\n"
" if (!p)\n"
" goto err;\n"
" }\n"
" free(p);\n"
"err:\n"
" (void)0;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void ifelse1() {
check("int f() {\n"
" char *p = NULL;\n"
" if (x) { p = malloc(10); }\n"
" else { return 0; }\n"
" free(p);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void ifelse2() {
check("int f() {\n"
" char *p = NULL;\n"
" if (x) { p = malloc(10); }\n"
" else { return 0; }\n"
"}");
ASSERT_EQUALS("[test.c:5]: (error) Memory leak: p\n", errout_str());
}
void ifelse3() {
check("void f() {\n"
" char *p = malloc(10);\n"
" if (!p) { return; }\n"
" free(p);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("char * f(size_t size) {"
" void *p = malloc(1);"
" if (!p && size != 0)"
" return NULL;"
" return p;"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" char *p = malloc(10);\n"
" if (p) { } else { return; }\n"
" free(p);\n"
"}");
ASSERT_EQUALS("", errout_str());
// #3866 - UNLIKELY
check("void f() {\n"
" char *p = malloc(10);\n"
" if (UNLIKELY(!p)) { return; }\n"
" free(p);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void ifelse4() {
check("void f(int x) {\n"
" char *p;\n"
" if (x) { p = malloc(10); }\n"
" if (x) { free(p); }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
" char *p;\n"
" if (x) { p = malloc(10); }\n"
" if (!x) { return; }\n"
" free(p);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void ifelse5() {
check("void f() {\n"
" char *p = malloc(10);\n"
" if (!p && x) { p = malloc(10); }\n"
" free(p);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void ifelse6() { // #3370
check("void f(int x) {\n"
" int *a = malloc(20);\n"
" if (x)\n"
" free(a);\n"
" else\n"
" a = 0;\n"
"}");
ASSERT_EQUALS("[test.c:6]: (error) Memory leak: a\n", errout_str());
}
void ifelse7() { // #5576
check("void f() {\n"
" int x = malloc(20);\n"
" if (x < 0)\n" // assume negative value indicates its unallocated
" return;\n"
" free(x);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void ifelse8() { // #5747
check("int f() {\n"
" int fd = socket(AF_INET, SOCK_PACKET, 0 );\n"
" if (fd == -1)\n"
" return -1;\n"
" return fd;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f() {\n"
" int fd = socket(AF_INET, SOCK_PACKET, 0 );\n"
" if (fd != -1)\n"
" return fd;\n"
" return -1;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void ifelse9() { // #5273
check("void f() {\n"
" char *p = malloc(100);\n"
" if (dostuff(p==NULL,0))\n"
" return;\n"
" free(p);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void ifelse10() { // #8794
check("void f() {\n"
" void *x = malloc(1U);\n"
" if (!(x != NULL))\n"
" return;\n"
" free(x);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void ifelse11() { // #8365
check("void f() {\n"
" void *p;\n"
" if (NULL == (p = malloc(4)))\n"
" return;\n"
" free(p);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void ifelse12() { // #8340
check("void f(char **p) {\n"
" if ((*p = malloc(4)) == NULL)\n"
" return;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void ifelse13() { // #8392
check("int f(int fd, const char *mode) {\n"
" char *path;\n"
" if (fd == -1 || (path = (char *)malloc(10)) == NULL)\n"
" return 1;\n"
" free(path);\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f(int fd, const char *mode) {\n"
" char *path;\n"
" if ((path = (char *)malloc(10)) == NULL || fd == -1)\n"
" return 1;\n" // <- memory leak
" free(path);\n"
" return 0;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:4] memory leak", "", errout_str());
}
void ifelse14() { // #9130
check("char* f() {\n"
" char* buf = malloc(10);\n"
" if (buf == (char*)NULL)\n"
" return NULL;\n"
" return buf;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void ifelse15() { // #9206
check("struct SSS { int a; };\n"
"SSS* global_ptr;\n"
"void test_alloc() {\n"
" if ( global_ptr = new SSS()) {}\n"
" return;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("FILE* hFile;\n"
"int openFile( void ) {\n"
" if ((hFile = fopen(\"1.txt\", \"wb\" )) == NULL) return 0;\n"
" return 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void ifelse16() { // #9635
check("void f(void) {\n"
" char *p;\n"
" if(p = malloc(4), p == NULL)\n"
" return;\n"
" free(p);\n"
" return;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(void) {\n"
" char *p, q;\n"
" if(p = malloc(4), q = 1, p == NULL)\n"
" return;\n"
" free(p);\n"
" return;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void ifelse17() {
check("int *f() {\n"
" int *p = realloc(nullptr, 10);\n"
" if (!p)\n"
" return NULL;\n"
" return p;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int *f() {\n"
" int *p = realloc(nullptr, 10);\n"
" if (!!(!p))\n"
" return NULL;\n"
" return p;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void ifelse18() {
check("void f() {\n"
" void * p = malloc(10);\n"
" void * q = realloc(p, 20);\n"
" if (q == 0)\n"
" return;\n"
" free(q);\n"
"}");
ASSERT_EQUALS("[test.c:5]: (error) Memory leak: p\n", errout_str());
check("void f() {\n"
" void * p = malloc(10);\n"
" void * q = realloc(p, 20);\n"
" if (q != 0) {\n"
" free(q);\n"
" return;\n"
" } else\n"
" return;\n"
"}");
ASSERT_EQUALS("[test.c:8]: (error) Memory leak: p\n", errout_str());
}
void ifelse19() {
check("void f() {\n"
" static char * a;\n"
" char * b = realloc(a, 10);\n"
" if (!b)\n"
" return;\n"
" a = b;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void ifelse20() {
check("void f() {\n"
" if (x > 0)\n"
" void * p1 = malloc(5);\n"
" else\n"
" void * p2 = malloc(2);\n"
" return;\n"
"}");
ASSERT_EQUALS("[test.c:3]: (error) Memory leak: p1\n"
"[test.c:5]: (error) Memory leak: p2\n", errout_str());
check("void f() {\n"
" if (x > 0)\n"
" void * p1 = malloc(5);\n"
" else\n"
" void * p2 = malloc(2);\n"
"}");
ASSERT_EQUALS("[test.c:3]: (error) Memory leak: p1\n"
"[test.c:5]: (error) Memory leak: p2\n", errout_str());
}
void ifelse21() {
check("void f() {\n"
" if (y) {\n"
" void * p;\n"
" if (x > 0)\n"
" p = malloc(5);\n"
" }\n"
" return;\n"
"}");
ASSERT_EQUALS("[test.c:6]: (error) Memory leak: p\n", errout_str());
}
void ifelse22() { // #10187
check("int f(const char * pathname, int flags) {\n"
" int fd = socket(pathname, flags);\n"
" if (fd >= 0)\n"
" return fd;\n"
" return -1;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f(const char * pathname, int flags) {\n"
" int fd = socket(pathname, flags);\n"
" if (fd <= -1)\n"
" return -1;\n"
" return fd;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void ifelse23() { // #5473
check("void f() {\n"
" if (FILE* fp = fopen(\"x\", \"r\")) {}\n"
"}\n");
ASSERT_EQUALS("[test.c:2]: (error) Resource leak: fp\n", errout_str());
}
void ifelse24() { // #1733
const Settings s = settingsBuilder().library("std.cfg").library("posix.cfg").build();
check("void f() {\n"
" char* temp = strdup(\"temp.txt\");\n"
" FILE* fp;\n"
" if (NULL == x || NULL == (fp = fopen(temp, \"rt\")))\n"
" return;\n"
"}\n", s);
ASSERT_EQUALS("[test.cpp:5]: (error) Memory leak: temp\n"
"[test.cpp:6]: (error) Memory leak: temp\n"
"[test.cpp:6]: (error) Resource leak: fp\n",
errout_str());
check("FILE* f() {\n"
" char* temp = strdup(\"temp.txt\");\n"
" FILE* fp = fopen(temp, \"rt\");\n"
" return fp;\n"
"}\n", s);
ASSERT_EQUALS("[test.cpp:4]: (error) Memory leak: temp\n", errout_str());
check("FILE* f() {\n"
" char* temp = strdup(\"temp.txt\");\n"
" FILE* fp = NULL;\n"
" fopen_s(&fp, temp, \"rt\");\n"
" return fp;\n"
"}\n", s);
ASSERT_EQUALS("[test.cpp:5]: (error) Memory leak: temp\n", errout_str());
check("void f() {\n"
" char* temp = strdup(\"temp.txt\");\n"
" FILE* fp = fopen(\"a.txt\", \"rb\");\n"
" if (fp)\n"
" freopen(temp, \"rt\", fp);\n"
"}\n", s);
ASSERT_EQUALS("[test.cpp:6]: (error) Memory leak: temp\n"
"[test.cpp:6]: (error) Resource leak: fp\n",
errout_str());
check("FILE* f() {\n"
" char* temp = strdup(\"temp.txt\");\n"
" return fopen(temp, \"rt\");\n"
"}\n", s);
TODO_ASSERT_EQUALS("[test.cpp:3]: (error) Memory leak: temp\n", "", errout_str());
}
void ifelse25() { // #9966
check("void f() {\n"
" void *p, *p2;\n"
" if((p2 = p = malloc(10)) == NULL)\n"
" return;\n"
" (void)p;\n"
" free(p2);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void ifelse26() { // don't crash
check("union tidi {\n"
" long long ti;\n"
" unsigned int di[2];\n"
"};\n"
"void f(long long val) {\n"
" if (val == ({ union tidi d = {.di = {0x0, 0x80000000}}; d.ti; })) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void ifelse27() {
check("struct key { void* p; };\n"
"int f(struct key** handle) {\n"
" struct key* key;\n"
" if (!(key = calloc(1, sizeof(*key))))\n"
" return 0;\n"
" if (!(key->p = malloc(4))) {\n"
" free(key);\n"
" return 0;\n"
" }\n"
" *handle = key;\n"
" return 1;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void ifelse28() { // #11038
check("char * f(void) {\n"
" char *buf = (char*)malloc(42*sizeof(char));\n"
" char *temp;\n"
" if ((temp = (char*)realloc(buf, 16)) != NULL)\n"
" { buf = temp; }\n"
" return buf;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void ifelse29() { // #13296
check("struct S {\n"
" typedef int (S::* func_t)(int) const;\n"
" void f(func_t pfn);\n"
" int g(int) const;\n"
"};\n"
"void S::f(func_t pfn) {\n"
" if (pfn == (func_t)&S::g) {}\n"
"}\n", true);
ASSERT_EQUALS("", errout_str()); // don't crash
}
void switch1() {
check("void f() {\n"
" char *p = 0;\n"
" switch (x) {\n"
" case 123: p = malloc(100); break;\n"
" default: return;\n"
" }\n"
" free(p);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void loop1() {
// test the handling of { }
check("void f() {\n"
" char *p;\n"
" for (i=0;i<5;i++) { }\n"
" if (x) { free(p) }\n"
" else { a = p; }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void loop2() {
check("void f() {\n" // #11786
" int* p = (int*)malloc(sizeof(int));\n"
" if (1) {\n"
" while (0) {}\n"
" free(p);\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(node **p) {\n"
" node* n = *p;\n"
" if (n->left == NULL) {\n"
" *p = n->right;\n"
" free(n);\n"
" }\n"
" else if (n->right == NULL) {\n"
" *p = n->left;\n"
" free(n);\n"
" }\n"
" else {\n"
" for (int i = 0; i < 4; ++i) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void mismatchAllocDealloc() {
check("void f() {\n"
" FILE*f=fopen(fname,a);\n"
" free(f);\n"
"}");
ASSERT_EQUALS("[test.c:2] -> [test.c:3]: (error) Mismatching allocation and deallocation: f\n", errout_str());
check("void f() {\n"
" FILE*f=fopen(fname,a);\n"
" free((void*)f);\n"
"}");
ASSERT_EQUALS("[test.c:2] -> [test.c:3]: (error) Mismatching allocation and deallocation: f\n", errout_str());
check("void f() {\n"
" char *cPtr = new char[100];\n"
" delete[] cPtr;\n"
" cPtr = new char[100]('x');\n"
" delete[] cPtr;\n"
" cPtr = new char[100];\n"
" delete cPtr;\n"
"}", true);
ASSERT_EQUALS("[test.cpp:6] -> [test.cpp:7]: (error) Mismatching allocation and deallocation: cPtr\n", errout_str());
check("void f() {\n"
" char *cPtr = new char[100];\n"
" free(cPtr);\n"
"}", true);
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (error) Mismatching allocation and deallocation: cPtr\n", errout_str());
check("void f() {\n"
" char *cPtr = new (buf) char[100];\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int * i = new int[1];\n"
" std::unique_ptr<int> x(i);\n"
"}\n", true);
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (error) Mismatching allocation and deallocation: i\n", errout_str());
check("void f() {\n"
" int * i = new int;\n"
" std::unique_ptr<int[]> x(i);\n"
"}\n", true);
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (error) Mismatching allocation and deallocation: i\n", errout_str());
check("void f() {\n"
" void* a = malloc(1);\n"
" void* b = freopen(f, p, a);\n"
" free(b);\n"
"}");
ASSERT_EQUALS("[test.c:2] -> [test.c:3]: (error) Mismatching allocation and deallocation: a\n"
"[test.c:3] -> [test.c:4]: (error) Mismatching allocation and deallocation: b\n", errout_str());
check("void f() {\n"
" void* a;\n"
" void* b = realloc(a, 10);\n"
" free(b);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int * i = new int;\n"
" int * j = realloc(i, 2 * sizeof(int));\n"
" delete[] j;\n"
"}", true);
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (error) Mismatching allocation and deallocation: i\n"
"[test.cpp:3] -> [test.cpp:4]: (error) Mismatching allocation and deallocation: j\n", errout_str());
check("static void deleter(int* p) { free(p); }\n" // #11392
"void f() {\n"
" if (int* p = static_cast<int*>(malloc(4))) {\n"
" std::unique_ptr<int, decltype(&deleter)> guard(p, &deleter);\n"
" }\n"
"}\n", true);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" if (int* p = static_cast<int*>(malloc(4))) {\n"
" std::unique_ptr<int, decltype(&deleter)> guard(p, &deleter);\n"
" }\n"
"}\n", true);
ASSERT_EQUALS("", errout_str());
check("void f(int i) {\n"
" int* a = new int[i] {};\n"
" delete[] a;\n"
"}\n", /*cpp*/ true);
ASSERT_EQUALS("", errout_str());
}
void smartPointerDeleter() {
check("void f() {\n"
" FILE*f=fopen(fname,a);\n"
" std::unique_ptr<FILE> fp{f};\n"
"}", true);
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (error) Mismatching allocation and deallocation: f\n", errout_str());
check("void f() {\n"
" FILE*f=fopen(fname,a);\n"
" std::unique_ptr<FILE, decltype(&fclose)> fp{f, &fclose};\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" FILE*f=fopen(fname,a);\n"
" std::shared_ptr<FILE> fp{f, &fclose};\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("struct deleter { void operator()(FILE* f) { fclose(f); }};\n"
"void f() {\n"
" FILE*f=fopen(fname,a);\n"
" std::unique_ptr<FILE, deleter> fp{f};\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("int * create();\n"
"void destroy(int * x);\n"
"void f() {\n"
" int x * = create()\n"
" std::unique_ptr<int, decltype(&destroy)> xp{x, &destroy()};\n"
"}\n", true);
ASSERT_EQUALS("", errout_str());
check("int * create();\n"
"void destroy(int * x);\n"
"void f() {\n"
" int x * = create()\n"
" std::unique_ptr<int, decltype(&destroy)> xp(x, &destroy());\n"
"}\n", true);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" FILE*f=fopen(fname,a);\n"
" std::shared_ptr<FILE> fp{f, [](FILE* x) { fclose(x); }};\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" FILE*f=fopen(fname,a);\n"
" std::shared_ptr<FILE> fp{f, +[](FILE* x) { fclose(x); }};\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" FILE*f=fopen(fname,a);\n"
" std::shared_ptr<FILE> fp{f, [](FILE* x) { free(f); }};\n"
"}", true);
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (error) Mismatching allocation and deallocation: f\n", errout_str());
check("void f() {\n"
" FILE*f=fopen(fname,a);\n"
" std::shared_ptr<FILE> fp{f, [](FILE* x) {}};\n"
"}", true);
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (error) Mismatching allocation and deallocation: f\n", errout_str());
check("class C;\n"
"void f() {\n"
" C* c = new C{};\n"
" std::shared_ptr<C> a{c, [](C*) {}};\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("class C;\n"
"void f() {\n"
" C* c = new C{};\n"
" std::shared_ptr<C> a{c, [](C* x) { delete x; }};\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("struct DirDeleter {\n" // #12544
" void operator()(DIR* d) { ::closedir(d); }\n"
"};\n"
"void openDir(DIR* dir) {\n"
" std::shared_ptr<DIR> dp(dir, DirDeleter());\n"
"}\n", true);
ASSERT_EQUALS("[test.cpp:2]: (information) --check-library: Function closedir() should have <noreturn> configuration\n", errout_str()); // don't crash
}
void smartPointerRelease() {
check("void f() {\n"
" int * i = new int;\n"
" std::unique_ptr<int> x(i);\n"
" x.release();\n"
" delete i;\n"
"}\n", true);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int * i = new int;\n"
" std::unique_ptr<int> x(i);\n"
" x.release();\n"
"}\n", true);
ASSERT_EQUALS("[test.cpp:5]: (error) Memory leak: i\n", errout_str());
}
void return1() {
check("int f() {\n"
" char *p = malloc(100);\n"
" return 123;\n"
"}");
ASSERT_EQUALS("[test.c:3]: (error) Memory leak: p\n", errout_str());
}
void return2() {
check("char *f() {\n"
" char *p = malloc(100);\n"
" return p;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void return3() {
check("struct dev * f() {\n"
" struct ABC *abc = malloc(100);\n"
" return &abc->dev;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void return4() { // ticket #3862
// avoid false positives
check("void f(char *p, int x) {\n"
" if (x==12) {\n"
" free(p);\n"
" throw 1;\n"
" }\n"
" free(p);\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("void f(char *p, int x) {\n"
" if (x==12) {\n"
" delete p;\n"
" throw 1;\n"
" }\n"
" delete p;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("void f(char *p, int x) {\n"
" if (x==12) {\n"
" delete [] p;\n"
" throw 1;\n"
" }\n"
" delete [] p;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
}
void return5() { // ticket #6397 - conditional allocation/deallocation and conditional return
// avoid false positives
check("void f(int *p, int x) {\n"
" if (x != 0) {\n"
" free(p);\n"
" }\n"
" if (x != 0) {\n"
" return;\n"
" }\n"
" *p = 0;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
}
void return6() { // #8282
check("std::pair<char*, char*> f(size_t n) {\n"
" char* p = (char* )malloc(n);\n"
" return {p, p};\n"
"}", true);
ASSERT_EQUALS("", errout_str());
}
void return7() { // #9343
check("uint8_t *f() {\n"
" void *x = malloc(1);\n"
" return (uint8_t *)x;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("uint8_t f() {\n"
" void *x = malloc(1);\n"
" return (uint8_t)x;\n"
"}", true);
ASSERT_EQUALS("[test.cpp:3]: (error) Memory leak: x\n", errout_str());
check("void** f() {\n"
" void *x = malloc(1);\n"
" return (void**)x;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("void* f() {\n"
" void *x = malloc(1);\n"
" return (long long)x;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("void* f() {\n"
" void *x = malloc(1);\n"
" return (void*)(short)x;\n"
"}", true);
ASSERT_EQUALS("[test.cpp:3]: (error) Memory leak: x\n", errout_str());
check("void* f() {\n"
" void *x = malloc(1);\n"
" return (mytype)x;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("void* f() {\n" // Do not crash
" void *x = malloc(1);\n"
" return (mytype)y;\n"
"}", true);
ASSERT_EQUALS("[test.cpp:3]: (error) Memory leak: x\n", errout_str());
}
void return8() {
check("void* f() {\n"
" void *x = malloc(1);\n"
" return (x);\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("void* f() {\n"
" void *x = malloc(1);\n"
" return ((x));\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("void* f() {\n"
" void *x = malloc(1);\n"
" return ((((x))));\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("char* f() {\n"
" void *x = malloc(1);\n"
" return (char*)(x);\n"
"}", true);
ASSERT_EQUALS("", errout_str());
}
void return9() {
check("void* f() {\n"
" void *x = malloc (sizeof (struct alloc));\n"
" return x + sizeof (struct alloc);\n"
"}", true);
ASSERT_EQUALS("", errout_str());
}
void return10() {
check("char f() {\n" // #11758
" char* p = (char*)malloc(1);\n"
" p[0] = 'x';\n"
" return p[0];\n"
"}");
ASSERT_EQUALS("[test.c:4]: (error) Memory leak: p\n", errout_str());
check("struct S { int f(); };\n" // #11746
"int g() {\n"
" S* s = new S;\n"
" delete s;\n"
" return s->f();\n"
"}", true);
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:5]: (error) Returning/dereferencing 's' after it is deallocated / released\n", errout_str());
check("int f() {\n"
" int* p = new int(3);\n"
" delete p;\n"
" return *p;\n"
"}", true);
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (error) Returning/dereferencing 'p' after it is deallocated / released\n", errout_str());
}
void return11() { // #13098
check("char malloc_memleak(void) {\n"
" bool flag = false;\n"
" char *ptr = malloc(10);\n"
" if (flag) {\n"
" free(ptr);\n"
" }\n"
" return 'a';\n"
"}\n", true);
ASSERT_EQUALS("[test.cpp:7]: (error) Memory leak: ptr\n", errout_str());
check("char malloc_memleak(void) {\n"
" bool flag = false;\n"
" char *ptr = malloc(10);\n"
" if (flag) {\n"
" free(ptr);\n"
" }\n"
" return 'a';\n"
"}\n", false);
ASSERT_EQUALS("[test.c:7]: (error) Memory leak: ptr\n", errout_str());
}
void test1() {
check("void f(double*&p) {\n" // 3809
" p = malloc(0x100);\n"
"}", /*cpp*/ true);
ASSERT_EQUALS("", errout_str());
check("void f(int*& p) {\n" // #4400
" p = (int*)malloc(4);\n"
" p = (int*)malloc(4);\n"
"}\n", /*cpp*/ true);
ASSERT_EQUALS("[test.cpp:3]: (error) Memory leak: p\n", errout_str());
check("void f() {\n"
" int* p = (int*)malloc(4);\n"
" int*& r = p;\n"
" r = (int*)malloc(4);\n"
"}\n", /*cpp*/ true);
TODO_ASSERT_EQUALS("[test.cpp:4]: (error) Memory leak: p\n", "", errout_str());
check("void f() {\n"
" int* p = (int*)malloc(4);\n"
" int*& r = p;\n"
" free(r);\n"
" p = (int*)malloc(4);\n"
"}\n", /*cpp*/ true);
TODO_ASSERT_EQUALS("", "[test.cpp:6]: (error) Memory leak: p\n", errout_str());
}
void test2() { // 3899
check("struct Fred {\n"
" char *p;\n"
" void f1() { free(p); }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void test3() { // 3954 - reference pointer
check("void f() {\n"
" char *&p = x();\n"
" p = malloc(10);\n"
"};", /*cpp*/ true);
ASSERT_EQUALS("", errout_str());
}
void test4() { // 5923 - static pointer
check("void f() {\n"
" static char *p;\n"
" if (!p) p = malloc(10);\n"
" if (x) { free(p); p = 0; }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void test5() { // unknown type
check("void f() { Fred *p = malloc(10); }", true);
ASSERT_EQUALS("[test.cpp:1]: (error) Memory leak: p\n", errout_str());
check("void f() { Fred *p = malloc(10); }", false);
ASSERT_EQUALS("[test.c:1]: (error) Memory leak: p\n", errout_str());
check("void f() { Fred *p = new Fred; }", true);
ASSERT_EQUALS("", errout_str());
check("void f() { Fred fred = malloc(10); }", true);
ASSERT_EQUALS("", errout_str());
}
void throw1() { // 3987 - Execution reach a 'throw'
check("void f() {\n"
" char *p = malloc(10);\n"
" throw 123;\n"
"}", true);
ASSERT_EQUALS("[test.cpp:3]: (error) Memory leak: p\n", errout_str());
check("void f() {\n"
" char *p;\n"
" try {\n"
" p = malloc(10);\n"
" throw 123;\n"
" } catch (...) { }\n"
" free(p);\n"
"}", true);
ASSERT_EQUALS("", errout_str());
}
void throw2() { // do not miss ::NS::Except()
check("namespace NS {\n"
" class Except {\n"
" };\n"
"}\n"
"void foo(int i)\n"
"{\n"
" int *pi = new int;\n"
" if (i == 42) {\n"
" delete pi;\n"
" throw ::NS::Except();\n"
" }\n"
" delete pi;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
}
void configuration1() {
// Possible leak => configuration is required for complete analysis
// The user should be able to "white list" and "black list" functions.
// possible leak. If the function 'x' deallocates the pointer or
// takes the address, there is no leak.
check("void f() {\n"
" char *p = malloc(10);\n"
" x(p);\n"
"}");
ASSERT_EQUALS("[test.c:3]: (information) --check-library: Function x() should have <noreturn> configuration\n"
"[test.c:4]: (information) --check-library: Function x() should have <use>/<leak-ignore> configuration\n",
errout_str());
check("void cb();\n" // #11190, #11523
"void f() {\n"
" cb();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void configuration2() {
// possible leak. If the function 'x' deallocates the pointer or
// takes the address, there is no leak.
check("void f() {\n"
" char *p = malloc(10);\n"
" x(&p);\n"
"}");
ASSERT_EQUALS("[test.c:3]: (information) --check-library: Function x() should have <noreturn> configuration\n"
"[test.c:4]: (information) --check-library: Function x() should have <use>/<leak-ignore> configuration\n",
errout_str());
}
void configuration3() {
{
const char code[] = "void f() {\n"
" char *p = malloc(10);\n"
" if (set_data(p)) { }\n"
"}";
check(code);
ASSERT_EQUALS("[test.c:4]: (information) --check-library: Function set_data() should have <use>/<leak-ignore> configuration\n", errout_str());
check(code, true);
ASSERT_EQUALS("[test.cpp:4]: (information) --check-library: Function set_data() should have <use>/<leak-ignore> configuration\n", errout_str());
}
{
const char code[] = "void f() {\n"
" char *p = malloc(10);\n"
" if (set_data(p)) { return; }\n"
"}";
check(code);
ASSERT_EQUALS("[test.c:3]: (information) --check-library: Function set_data() should have <use>/<leak-ignore> configuration\n"
"[test.c:4]: (information) --check-library: Function set_data() should have <use>/<leak-ignore> configuration\n"
, errout_str());
check(code, true);
ASSERT_EQUALS("[test.cpp:3]: (information) --check-library: Function set_data() should have <use>/<leak-ignore> configuration\n"
"[test.cpp:4]: (information) --check-library: Function set_data() should have <use>/<leak-ignore> configuration\n"
, errout_str());
}
}
void configuration4() {
check("void f() {\n"
" char *p = malloc(10);\n"
" int ret = set_data(p);\n"
" return ret;\n"
"}");
ASSERT_EQUALS("[test.c:4]: (information) --check-library: Function set_data() should have <use>/<leak-ignore> configuration\n", errout_str());
}
void configuration5() {
check("void f() {\n"
" int(i);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" static_assert(1 == sizeof(char), \"test\");\n"
"}\n", /*cpp*/ true);
ASSERT_EQUALS("", errout_str());
check("namespace pal {\n" // #11237
" struct AutoTimer {};\n"
"}\n"
"int main() {\n"
" pal::AutoTimer();\n"
"}\n", /*cpp*/ true);
ASSERT_EQUALS("", errout_str());
check("struct AutoTimer {};\n"
"int main() {\n"
" AutoTimer();\n"
"}\n", /*cpp*/ true);
ASSERT_EQUALS("", errout_str());
check("void f() {\n" // #8666
" asm(\"assembler code\");\n"
" asm volatile(\"assembler code\");\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f() {\n" // #11239
" asm goto(\"assembler code\");\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" FILE* p = fopen(\"abc.txt\", \"r\");\n"
" if (fclose(p) != 0) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct S;\n"
"void f(int a, int b, S*& p) {\n"
" if (a == -1) {\n"
" FILE* file = fopen(\"abc.txt\", \"r\");\n"
" }\n"
" if (b) {\n"
" void* buf = malloc(10);\n"
" p = reinterpret_cast<S*>(buf);\n"
" }\n"
"}\n", /*cpp*/ true);
ASSERT_EQUALS("[test.cpp:5]: (error) Resource leak: file\n", errout_str());
}
void configuration6() {
check("void f() {}\n" // #11198
"void g() {\n"
" f();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(std::function<void()> cb) {\n" // #11189
" cb();\n"
"}\n"
"void g(void (*cb)()) {\n"
" cb();\n"
"}\n", /*cpp*/ true);
ASSERT_EQUALS("", errout_str());
}
void ptrptr() {
check("void f() {\n"
" char **p = malloc(10);\n"
"}");
ASSERT_EQUALS("[test.c:3]: (error) Memory leak: p\n", errout_str());
}
void nestedAllocation() {
check("void QueueDSMCCPacket(unsigned char *data, int length) {\n"
" unsigned char *dataCopy = malloc(length * sizeof(unsigned char));\n"
" m_dsmccQueue.enqueue(new DSMCCPacket(dataCopy));\n"
"}", true);
ASSERT_EQUALS("[test.cpp:4]: (information) --check-library: Function DSMCCPacket() should have <use>/<leak-ignore> configuration\n", errout_str());
check("void QueueDSMCCPacket(unsigned char *data, int length) {\n"
" unsigned char *dataCopy = malloc(length * sizeof(unsigned char));\n"
" m_dsmccQueue.enqueue(new DSMCCPacket(somethingunrelated));\n"
"}", true);
ASSERT_EQUALS("[test.cpp:4]: (error) Memory leak: dataCopy\n", errout_str());
check("void f() {\n"
" char *buf = new char[1000];\n"
" clist.push_back(new (std::nothrow) C(buf));\n"
"}", true);
ASSERT_EQUALS("[test.cpp:4]: (information) --check-library: Function C() should have <use>/<leak-ignore> configuration\n", errout_str());
}
void testKeywords() {
check("int main(int argc, char **argv) {\n"
" double *new = malloc(1*sizeof(double));\n"
" free(new);\n"
" return 0;\n"
"}", false);
ASSERT_EQUALS("", errout_str());
}
void inlineFunction() {
check("int test() {\n"
" char *c;\n"
" int ret() {\n"
" free(c);\n"
" return 0;\n"
" }\n"
" c = malloc(128);\n"
" return ret();\n"
"}");
ASSERT_EQUALS("", errout_str());
}
// #8262
void smartPtrInContainer() {
check("std::list< std::shared_ptr<int> > mList;\n"
"void test(){\n"
" int *pt = new int(1);\n"
" mList.push_back(std::shared_ptr<int>(pt));\n"
"}\n",
true
);
ASSERT_EQUALS("", errout_str());
}
void functionCallCastConfig() { // #9652
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def format=\"2\">\n"
" <function name=\"free_func\">\n"
" <noreturn>false</noreturn>\n"
" <arg nr=\"1\">\n"
" <not-uninit/>\n"
" </arg>\n"
" <arg nr=\"2\">\n"
" <not-uninit/>\n"
" </arg>\n"
" </function>\n"
"</def>";
const Settings settingsFunctionCall = settingsBuilder(settings).libraryxml(xmldata, sizeof(xmldata)).build();
check("void test_func()\n"
"{\n"
" char * buf = malloc(4);\n"
" free_func((void *)(1), buf);\n"
"}", settingsFunctionCall);
ASSERT_EQUALS("[test.cpp:5]: (information) --check-library: Function free_func() should have <use>/<leak-ignore> configuration\n", errout_str());
check("void g(void*);\n"
"void h(int, void*);\n"
"void f1() {\n"
" int* p = new int;\n"
" g(static_cast<void*>(p));\n"
"}\n"
"void f2() {\n"
" int* p = new int;\n"
" h(1, static_cast<void*>(p));\n"
"}\n", /*cpp*/ true);
ASSERT_EQUALS("[test.cpp:6]: (information) --check-library: Function g() should have <use>/<leak-ignore> configuration\n"
"[test.cpp:10]: (information) --check-library: Function h() should have <use>/<leak-ignore> configuration\n",
errout_str());
}
void functionCallLeakIgnoreConfig() { // #7923
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def format=\"2\">\n"
" <function name=\"SomeClass::someMethod\">\n"
" <leak-ignore/>\n"
" <noreturn>false</noreturn>\n"
" <arg nr=\"1\" direction=\"in\"/>\n"
" </function>\n"
"</def>\n";
const Settings settingsLeakIgnore = settingsBuilder().libraryxml(xmldata, sizeof(xmldata)).build();
check("void f() {\n"
" double* a = new double[1024];\n"
" SomeClass::someMethod(a);\n"
"}\n", settingsLeakIgnore);
ASSERT_EQUALS("[test.cpp:4]: (error) Memory leak: a\n", errout_str());
check("void bar(int* p) {\n"
" if (p)\n"
" free(p);\n"
"}\n"
"void f() {\n"
" int* p = malloc(4);\n"
" bar(p);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(int n) {\n"
" char* p = new char[n];\n"
" v.push_back(p);\n"
"}\n", /*cpp*/ true);
ASSERT_EQUALS("[test.cpp:4]: (information) --check-library: Function unknown::push_back() should have <use>/<leak-ignore> configuration\n", errout_str());
}
};
REGISTER_TEST(TestLeakAutoVar)
class TestLeakAutoVarRecursiveCountLimit : public TestFixture {
public:
TestLeakAutoVarRecursiveCountLimit() : TestFixture("TestLeakAutoVarRecursiveCountLimit") {}
private:
const Settings settings = settingsBuilder().library("std.cfg").checkLibrary().build();
#define checkP(...) checkP_(__FILE__, __LINE__, __VA_ARGS__)
void checkP_(const char* file, int line, const char code[], bool cpp = false) {
std::vector<std::string> files(1, cpp?"test.cpp":"test.c");
Tokenizer tokenizer(settings, *this);
PreprocessorHelper::preprocess(code, files, tokenizer, *this);
// Tokenizer..
ASSERT_LOC(tokenizer.simplifyTokens1(""), file, line);
// Check for leaks..
runChecks<CheckLeakAutoVar>(tokenizer, this);
}
void run() override {
TEST_CASE(recursiveCountLimit); // #5872 #6157 #9097
}
void recursiveCountLimit() { // #5872 #6157 #9097
ASSERT_THROW_INTERNAL_EQUALS(checkP("#define ONE else if (0) { }\n"
"#define TEN ONE ONE ONE ONE ONE ONE ONE ONE ONE ONE\n"
"#define HUN TEN TEN TEN TEN TEN TEN TEN TEN TEN TEN\n"
"#define THOU HUN HUN HUN HUN HUN HUN HUN HUN HUN HUN\n"
"void foo() {\n"
" if (0) { }\n"
" THOU THOU\n"
"}"), LIMIT, "Internal limit: CheckLeakAutoVar::checkScope() Maximum recursive count of 1000 reached.");
ASSERT_NO_THROW(checkP("#define ONE if (0) { }\n"
"#define TEN ONE ONE ONE ONE ONE ONE ONE ONE ONE ONE\n"
"#define HUN TEN TEN TEN TEN TEN TEN TEN TEN TEN TEN\n"
"#define THOU HUN HUN HUN HUN HUN HUN HUN HUN HUN HUN\n"
"void foo() {\n"
" if (0) { }\n"
" THOU THOU\n"
"}"));
}
};
#if !defined(__MINGW32__)
// TODO: this crashes with a stack overflow for MinGW in the CI
REGISTER_TEST(TestLeakAutoVarRecursiveCountLimit)
#endif
class TestLeakAutoVarStrcpy : public TestFixture {
public:
TestLeakAutoVarStrcpy() : TestFixture("TestLeakAutoVarStrcpy") {}
private:
const Settings settings = settingsBuilder().library("std.cfg").checkLibrary().build();
template<size_t size>
void check_(const char* file, int line, const char (&code)[size]) {
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
// Check for leaks..
runChecks<CheckLeakAutoVar>(tokenizer, this);
}
void run() override {
TEST_CASE(returnedValue); // #9298
TEST_CASE(deallocuse2);
TEST_CASE(fclose_false_positive); // #9575
TEST_CASE(strcpy_false_negative);
TEST_CASE(doubleFree);
TEST_CASE(memleak_std_string);
}
void returnedValue() { // #9298
check("char *m;\n"
"void strcpy_returnedvalue(const char* str)\n"
"{\n"
" char* ptr = new char[strlen(str)+1];\n"
" m = strcpy(ptr, str);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void deallocuse2() {
check("void f(char *p) {\n"
" free(p);\n"
" strcpy(a, p);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Dereferencing 'p' after it is deallocated / released\n", errout_str());
check("void f(char *p, const char *q) {\n" // #11665
" free(p);\n"
" strcpy(p, q);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Dereferencing 'p' after it is deallocated / released\n",
errout_str());
check("void f(char *p) {\n" // #3041 - assigning pointer when it's used
" free(p);\n"
" strcpy(a, p=b());\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void fclose_false_positive() { // #9575
check("int f(FILE *fp) { return fclose(fp); }");
ASSERT_EQUALS("", errout_str());
}
void strcpy_false_negative() { // #12289
check("void f() {\n"
" char* buf = new char[12];\n"
" strcpy(buf, \"123\");\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (error) Memory leak: buf\n", errout_str());
}
void doubleFree() {
check("void f(char* p) {\n"
" free(p);\n"
" printf(\"%s\", p = strdup(\"abc\"));\n"
" free(p);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void memleak_std_string() {
check("struct S {\n" // #12354
" std::string s;\n"
" void f();\n"
"};\n"
"void f(S* p, bool b) {\n"
" if (b)\n"
" p = new S();\n"
" p->f();\n"
"}");
ASSERT_EQUALS("[test.cpp:9]: (error) Memory leak: p\n", errout_str());
check("class B { std::string s; };\n" // #12062
"class D : public B {};\n"
"void g() {\n"
" auto d = new D();\n"
" if (d) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:6]: (error) Memory leak: d\n", errout_str());
}
};
REGISTER_TEST(TestLeakAutoVarStrcpy)
class TestLeakAutoVarWindows : public TestFixture {
public:
TestLeakAutoVarWindows() : TestFixture("TestLeakAutoVarWindows") {}
private:
const Settings settings = settingsBuilder().library("windows.cfg").build();
template<size_t size>
void check_(const char* file, int line, const char (&code)[size]) {
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code, false), file, line);
// Check for leaks..
runChecks<CheckLeakAutoVar>(tokenizer, this);
}
void run() override {
TEST_CASE(heapDoubleFree);
}
void heapDoubleFree() {
check("void f() {"
" HANDLE MyHeap = HeapCreate(0, 0, 0);"
" int *a = HeapAlloc(MyHeap, 0, sizeof(int));"
" int *b = HeapAlloc(MyHeap, 0, sizeof(int));"
" HeapFree(MyHeap, 0, a);"
" HeapFree(MyHeap, 0, b);"
" HeapDestroy(MyHeap);"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {"
" int *a = HeapAlloc(GetProcessHeap(), 0, sizeof(int));"
" int *b = HeapAlloc(GetProcessHeap(), 0, sizeof(int));"
" HeapFree(GetProcessHeap(), 0, a);"
" HeapFree(GetProcessHeap(), 0, b);"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {"
" HANDLE MyHeap = HeapCreate(0, 0, 0);"
" int *a = HeapAlloc(MyHeap, 0, sizeof(int));"
" int *b = HeapAlloc(MyHeap, 0, sizeof(int));"
" HeapFree(MyHeap, 0, a);"
" HeapDestroy(MyHeap);"
"}");
ASSERT_EQUALS("[test.c:1]: (error) Memory leak: b\n", errout_str());
check("void f() {"
" HANDLE MyHeap = HeapCreate(0, 0, 0);"
" int *a = HeapAlloc(MyHeap, 0, sizeof(int));"
" int *b = HeapAlloc(MyHeap, 0, sizeof(int));"
" HeapFree(MyHeap, 0, a);"
" HeapFree(MyHeap, 0, b);"
"}");
ASSERT_EQUALS("[test.c:1]: (error) Resource leak: MyHeap\n", errout_str());
check("void f() {"
" HANDLE MyHeap = HeapCreate(0, 0, 0);"
" int *a = HeapAlloc(MyHeap, 0, sizeof(int));"
" int *b = HeapAlloc(MyHeap, 0, sizeof(int));"
" HeapFree(MyHeap, 0, a);"
"}");
ASSERT_EQUALS("[test.c:1]: (error) Resource leak: MyHeap\n"
"[test.c:1]: (error) Memory leak: b\n",
errout_str());
}
};
REGISTER_TEST(TestLeakAutoVarWindows)
class TestLeakAutoVarPosix : public TestFixture {
public:
TestLeakAutoVarPosix() : TestFixture("TestLeakAutoVarPosix") {}
private:
const Settings settings = settingsBuilder().library("std.cfg").library("posix.cfg").build();
template<size_t size>
void check_(const char* file, int line, const char (&code)[size]) {
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
// Check for leaks..
runChecks<CheckLeakAutoVar>(tokenizer, this);
}
void run() override {
TEST_CASE(memleak_getline);
TEST_CASE(deallocuse_fdopen);
TEST_CASE(doublefree_fdopen); // #12781
TEST_CASE(memleak_open); // #13356
}
void memleak_getline() {
check("void f(std::ifstream &is) {\n" // #12297
" std::string str;\n"
" if (getline(is, str, 'x').good()) {};\n"
" if (!getline(is, str, 'x').good()) {};\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void deallocuse_fdopen() {
check("struct FileCloser {\n" // #13126
" void operator()(std::FILE * ptr) const {\n"
" std::fclose(ptr);\n"
" }\n"
"};\n"
"void f(char* fileName) {\n"
" std::unique_ptr<std::FILE, FileCloser> out;\n"
" int fd = mkstemps(fileName, 4);\n"
" if (fd != -1)\n"
" out.reset(fdopen(fd, \"w\"));\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void doublefree_fdopen() { // #12781
check("void foo(void) {\n"
" int fd;\n"
" FILE *stream;\n"
" fd = open(\"/foo\", O_RDONLY);\n"
" if (fd == -1) return;\n"
" stream = fdopen(fd, \"r\");\n"
" if (!stream) {\n"
" close(fd);\n"
" return;\n"
" }\n"
" fclose(stream);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void memleak_open() { // #13356
check("int f() {\n"
" int fd = open(\"abc \", O_RDONLY);\n"
" if (fd > -1) {\n"
" return fd;\n"
" }\n"
" return -1;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
};
REGISTER_TEST(TestLeakAutoVarPosix)
| null |
986 | cpp | cppcheck | testthreadexecutor.cpp | test/testthreadexecutor.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "redirect.h"
#include "settings.h"
#include "filesettings.h"
#include "fixture.h"
#include "helpers.h"
#include "suppressions.h"
#include "threadexecutor.h"
#include "timer.h"
#include <cstdlib>
#include <list>
#include <memory>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
class TestThreadExecutorBase : public TestFixture {
public:
TestThreadExecutorBase(const char * const name, bool useFS) : TestFixture(name), useFS(useFS) {}
private:
/*const*/ Settings settings = settingsBuilder().library("std.cfg").build();
bool useFS;
std::string fprefix() const
{
if (useFS)
return "threadfs";
return "thread";
}
struct CheckOptions
{
CheckOptions() = default;
bool quiet = true;
SHOWTIME_MODES showtime = SHOWTIME_MODES::SHOWTIME_NONE;
const char* plistOutput = nullptr;
std::vector<std::string> filesList;
bool clangTidy = false;
bool executeCommandCalled = false;
std::string exe;
std::vector<std::string> args;
};
/**
* Execute check using n jobs for y files which are have
* identical data, given within data.
*/
void check(unsigned int jobs, int files, int result, const std::string &data, const CheckOptions& opt = make_default_obj{}) {
std::list<FileSettings> fileSettings;
std::list<FileWithDetails> filelist;
if (opt.filesList.empty()) {
for (int i = 1; i <= files; ++i) {
std::string f_s = fprefix() + "_" + std::to_string(i) + ".cpp";
filelist.emplace_back(f_s, data.size());
if (useFS) {
fileSettings.emplace_back(std::move(f_s), data.size());
}
}
}
else {
for (const auto& f : opt.filesList)
{
filelist.emplace_back(f, data.size());
if (useFS) {
fileSettings.emplace_back(f, data.size());
}
}
}
/*const*/ Settings s = settings;
s.jobs = jobs;
s.showtime = opt.showtime;
s.quiet = opt.quiet;
if (opt.plistOutput)
s.plistOutput = opt.plistOutput;
s.clangTidy = opt.clangTidy;
bool executeCommandCalled = false;
std::string exe;
std::vector<std::string> args;
// NOLINTNEXTLINE(performance-unnecessary-value-param)
auto executeFn = [&executeCommandCalled, &exe, &args](std::string e,std::vector<std::string> a,std::string,std::string&){
executeCommandCalled = true;
exe = std::move(e);
args = std::move(a);
return EXIT_SUCCESS;
};
std::vector<std::unique_ptr<ScopedFile>> scopedfiles;
scopedfiles.reserve(filelist.size());
for (std::list<FileWithDetails>::const_iterator i = filelist.cbegin(); i != filelist.cend(); ++i)
scopedfiles.emplace_back(new ScopedFile(i->path(), data));
// clear files list so only fileSettings are used
if (useFS)
filelist.clear();
ThreadExecutor executor(filelist, fileSettings, s, s.supprs.nomsg, *this, executeFn);
ASSERT_EQUALS(result, executor.check());
ASSERT_EQUALS(opt.executeCommandCalled, executeCommandCalled);
ASSERT_EQUALS(opt.exe, exe);
ASSERT_EQUALS(opt.args.size(), args.size());
for (std::size_t i = 0; i < args.size(); ++i)
{
ASSERT_EQUALS(opt.args[i], args[i]);
}
}
void run() override {
TEST_CASE(deadlock_with_many_errors);
TEST_CASE(many_threads);
TEST_CASE(many_threads_showtime);
TEST_CASE(many_threads_plist);
TEST_CASE(no_errors_more_files);
TEST_CASE(no_errors_less_files);
TEST_CASE(no_errors_equal_amount_files);
TEST_CASE(one_error_less_files);
TEST_CASE(one_error_several_files);
TEST_CASE(clangTidy);
TEST_CASE(showtime_top5_file);
TEST_CASE(showtime_top5_summary);
TEST_CASE(showtime_file);
TEST_CASE(showtime_summary);
TEST_CASE(showtime_file_total);
TEST_CASE(suppress_error_library);
TEST_CASE(unique_errors);
}
void deadlock_with_many_errors() {
std::ostringstream oss;
oss << "int main()\n"
<< "{\n";
const int num_err = 1;
for (int i = 0; i < num_err; i++) {
oss << " {int i = *((int*)0);}\n";
}
oss << " return 0;\n"
<< "}\n";
const int num_files = 3;
check(2, num_files, num_files, oss.str());
ASSERT_EQUALS(1LL * num_err * num_files, cppcheck::count_all_of(errout_str(), "(error) Null pointer dereference: (int*)0"));
}
void many_threads() {
const int num_files = 100;
check(16, num_files, num_files,
"int main()\n"
"{\n"
" int i = *((int*)0);\n"
" return 0;\n"
"}");
ASSERT_EQUALS(num_files, cppcheck::count_all_of(errout_str(), "(error) Null pointer dereference: (int*)0"));
}
// #11249 - reports TSAN errors - only applies to threads not processes though
void many_threads_showtime() {
SUPPRESS;
check(16, 100, 100,
"int main()\n"
"{\n"
" int i = *((int*)0);\n"
" return 0;\n"
"}", dinit(CheckOptions, $.showtime = SHOWTIME_MODES::SHOWTIME_SUMMARY));
// we are not interested in the results - so just consume them
ignore_errout();
}
void many_threads_plist() {
const std::string plistOutput = "plist_" + fprefix() + "/";
ScopedFile plistFile("dummy", "", plistOutput);
check(16, 100, 100,
"int main()\n"
"{\n"
" int i = *((int*)0);\n"
" return 0;\n"
"}", dinit(CheckOptions, $.plistOutput = plistOutput.c_str()));
// we are not interested in the results - so just consume them
ignore_errout();
}
void no_errors_more_files() {
check(2, 3, 0,
"int main()\n"
"{\n"
" return 0;\n"
"}");
}
void no_errors_less_files() {
check(2, 1, 0,
"int main()\n"
"{\n"
" return 0;\n"
"}");
}
void no_errors_equal_amount_files() {
check(2, 2, 0,
"int main()\n"
"{\n"
" return 0;\n"
"}");
}
void one_error_less_files() {
check(2, 1, 1,
"int main()\n"
"{\n"
" {int i = *((int*)0);}\n"
" return 0;\n"
"}");
ASSERT_EQUALS("[" + fprefix() + "_1.cpp:3]: (error) Null pointer dereference: (int*)0\n", errout_str());
}
void one_error_several_files() {
const int num_files = 20;
check(2, num_files, num_files,
"int main()\n"
"{\n"
" {int i = *((int*)0);}\n"
" return 0;\n"
"}");
ASSERT_EQUALS(num_files, cppcheck::count_all_of(errout_str(), "(error) Null pointer dereference: (int*)0"));
}
void clangTidy() {
// TODO: we currently only invoke it with ImportProject::FileSettings
if (!useFS)
return;
#ifdef _WIN32
constexpr char exe[] = "clang-tidy.exe";
#else
constexpr char exe[] = "clang-tidy";
#endif
const std::string file = fprefix() + "_1.cpp";
check(2, 1, 0,
"int main()\n"
"{\n"
" return 0;\n"
"}",
dinit(CheckOptions,
$.quiet = false,
$.clangTidy = true,
$.executeCommandCalled = true,
$.exe = exe,
$.args = {"-quiet", "-checks=*,-clang-analyzer-*,-llvm*", file, "--"}));
ASSERT_EQUALS("Checking " + file + " ...\n", output_str());
}
// TODO: provide data which actually shows values above 0
// TODO: should this be logged only once like summary?
void showtime_top5_file() {
REDIRECT; // should not cause TSAN failures as the showtime logging is synchronized
check(2, 2, 0,
"int main() {}",
dinit(CheckOptions,
$.showtime = SHOWTIME_MODES::SHOWTIME_TOP5_FILE));
// for each file: top5 results + overall + empty line
const std::string output_s = GET_REDIRECT_OUTPUT;
// for each file: top5 results + overall + empty line
ASSERT_EQUALS((5 + 1 + 1) * 2LL, cppcheck::count_all_of(output_s, '\n'));
}
void showtime_top5_summary() {
REDIRECT;
check(2, 2, 0,
"int main() {}",
dinit(CheckOptions,
$.showtime = SHOWTIME_MODES::SHOWTIME_TOP5_SUMMARY));
const std::string output_s = GET_REDIRECT_OUTPUT;
// once: top5 results + overall + empty line
ASSERT_EQUALS(5 + 1 + 1, cppcheck::count_all_of(output_s, '\n'));
// should only report the top5 once
ASSERT(output_s.find("1 result(s)") == std::string::npos);
ASSERT(output_s.find("2 result(s)") != std::string::npos);
}
void showtime_file() {
REDIRECT; // should not cause TSAN failures as the showtime logging is synchronized
check(2, 2, 0,
"int main() {}",
dinit(CheckOptions,
$.showtime = SHOWTIME_MODES::SHOWTIME_FILE));
const std::string output_s = GET_REDIRECT_OUTPUT;
ASSERT_EQUALS(2, cppcheck::count_all_of(output_s, "Overall time:"));
}
void showtime_summary() {
REDIRECT; // should not cause TSAN failures as the showtime logging is synchronized
check(2, 2, 0,
"int main() {}",
dinit(CheckOptions,
$.showtime = SHOWTIME_MODES::SHOWTIME_SUMMARY));
const std::string output_s = GET_REDIRECT_OUTPUT;
// should only report the actual summary once
ASSERT(output_s.find("1 result(s)") == std::string::npos);
ASSERT(output_s.find("2 result(s)") != std::string::npos);
}
void showtime_file_total() {
REDIRECT; // should not cause TSAN failures as the showtime logging is synchronized
check(2, 2, 0,
"int main() {}",
dinit(CheckOptions,
$.showtime = SHOWTIME_MODES::SHOWTIME_FILE_TOTAL));
const std::string output_s = GET_REDIRECT_OUTPUT;
ASSERT(output_s.find("Check time: " + fprefix() + "_1.cpp: ") != std::string::npos);
ASSERT(output_s.find("Check time: " + fprefix() + "_2.cpp: ") != std::string::npos);
}
void suppress_error_library() {
SUPPRESS;
const Settings settingsOld = settings;
const char xmldata[] = R"(<def format="2"><markup ext=".cpp" reporterrors="false"/></def>)";
settings = settingsBuilder().libraryxml(xmldata, sizeof(xmldata)).build();
check(2, 1, 0,
"int main()\n"
"{\n"
" int i = *((int*)0);\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
settings = settingsOld;
}
void unique_errors() {
SUPPRESS;
ScopedFile inc_h(fprefix() + ".h",
"inline void f()\n"
"{\n"
" (void)*((int*)0);\n"
"}");
check(2, 2, 2,
"#include \"" + inc_h.name() +"\"");
// this is made unique by the executor
ASSERT_EQUALS("[" + inc_h.name() + ":3]: (error) Null pointer dereference: (int*)0\n", errout_str());
}
// TODO: test whole program analysis
};
class TestThreadExecutorFiles : public TestThreadExecutorBase {
public:
TestThreadExecutorFiles() : TestThreadExecutorBase("TestThreadExecutorFiles", false) {}
};
class TestThreadExecutorFS : public TestThreadExecutorBase {
public:
TestThreadExecutorFS() : TestThreadExecutorBase("TestThreadExecutorFS", true) {}
};
REGISTER_TEST(TestThreadExecutorFiles)
REGISTER_TEST(TestThreadExecutorFS)
| null |
987 | cpp | cppcheck | testunusedfunctions.cpp | test/testunusedfunctions.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "checkunusedfunctions.h"
#include "errortypes.h"
#include "fixture.h"
#include "helpers.h"
#include "platform.h"
#include "settings.h"
#include "tokenize.h"
#include "tokenlist.h"
#include <cstddef>
#include <sstream>
#include <string>
class TestUnusedFunctions : public TestFixture {
public:
TestUnusedFunctions() : TestFixture("TestUnusedFunctions") {}
private:
const Settings settings = settingsBuilder().severity(Severity::style).build();
void run() override {
TEST_CASE(incondition);
TEST_CASE(return1);
TEST_CASE(return2);
TEST_CASE(return3);
TEST_CASE(callback1);
TEST_CASE(callback2);
TEST_CASE(else1);
TEST_CASE(functionpointer);
TEST_CASE(template1);
TEST_CASE(template2);
TEST_CASE(template3);
TEST_CASE(template4); // #9805
TEST_CASE(template5);
TEST_CASE(template6); // #10475 crash
TEST_CASE(template7); // #9766 crash
TEST_CASE(template8);
TEST_CASE(template9);
TEST_CASE(template10);
TEST_CASE(throwIsNotAFunction);
TEST_CASE(unusedError);
TEST_CASE(unusedMain);
TEST_CASE(initializationIsNotAFunction);
TEST_CASE(operator1); // #3195
TEST_CASE(operator2); // #7974
TEST_CASE(returnRef);
TEST_CASE(attribute); // #3471 - FP __attribute__(constructor)
TEST_CASE(initializer_list);
TEST_CASE(member_function_ternary);
TEST_CASE(boost);
TEST_CASE(enumValues);
TEST_CASE(recursive);
TEST_CASE(multipleFiles); // same function name in multiple files
TEST_CASE(lineNumber); // Ticket 3059
TEST_CASE(ignore_declaration); // ignore declaration
TEST_CASE(operatorOverload);
TEST_CASE(entrypointsWin);
TEST_CASE(entrypointsWinU);
TEST_CASE(entrypointsUnix);
TEST_CASE(includes);
TEST_CASE(virtualFunc);
TEST_CASE(parensInit);
TEST_CASE(typeInCast);
TEST_CASE(attributeCleanup);
}
#define check(...) check_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
void check_(const char* file, int line, const char (&code)[size], Platform::Type platform = Platform::Type::Native, const Settings *s = nullptr) {
const Settings settings1 = settingsBuilder(s ? *s : settings).platform(platform).build();
// Tokenize..
SimpleTokenizer tokenizer(settings1, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
// Check for unused functions..
CheckUnusedFunctions checkUnusedFunctions;
checkUnusedFunctions.parseTokens(tokenizer, settings1);
(checkUnusedFunctions.check)(settings1, *this); // TODO: check result
}
// TODO: get rid of this
void check_(const char* file, int line, const std::string& code ) {
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
// Check for unused functions..
CheckUnusedFunctions checkUnusedFunctions;
checkUnusedFunctions.parseTokens(tokenizer, settings);
(checkUnusedFunctions.check)(settings, *this); // TODO: check result
}
void incondition() {
check("int f1()\n"
"{\n"
" if (f1())\n"
" { }\n"
"}");
ASSERT_EQUALS("[test.cpp:1]: (style) The function 'f1' is never used.\n", errout_str());
}
void return1() {
check("int f1()\n"
"{\n"
" return f1();\n"
"}");
ASSERT_EQUALS("[test.cpp:1]: (style) The function 'f1' is never used.\n", errout_str());
}
void return2() {
check("char * foo()\n"
"{\n"
" return foo();\n"
"}");
ASSERT_EQUALS("[test.cpp:1]: (style) The function 'foo' is never used.\n", errout_str());
}
void return3() {
check("typedef void (*VoidFunc)();\n" // #9602
"void sayHello() {\n"
" printf(\"Hello World\\n\");\n"
"}\n"
"VoidFunc getEventHandler() {\n"
" return sayHello;\n"
"}\n"
"void indirectHello() {\n"
" VoidFunc handler = getEventHandler();\n"
" handler();\n"
"}\n"
"int main() {\n"
" indirectHello();\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void callback1() {
check("void f1()\n"
"{\n"
" void (*f)() = cond ? f1 : NULL;\n"
"}");
ASSERT_EQUALS("[test.cpp:1]: (style) The function 'f1' is never used.\n", errout_str());
}
void callback2() { // #8677
check("class C {\n"
"public:\n"
" void callback();\n"
" void start();\n"
"};\n"
"\n"
"void C::callback() {}\n" // <- not unused
"\n"
"void C::start() { ev.set<C, &C::callback>(this); }");
ASSERT_EQUALS("[test.cpp:9]: (style) The function 'start' is never used.\n", errout_str());
}
void else1() {
check("void f1()\n"
"{\n"
" if (cond) ;\n"
" else f1();\n"
"}");
ASSERT_EQUALS("[test.cpp:1]: (style) The function 'f1' is never used.\n", errout_str());
}
void functionpointer() {
check("void foo() { }\n"
"int main() {\n"
" f(&foo);\n"
" return 0\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo() { }\n"
"int main() {\n"
" f(&::foo);\n"
" return 0\n"
"}");
ASSERT_EQUALS("", errout_str());
check("namespace abc {\n"
" void foo() { }\n"
"};\n"
"int main() {\n"
" f(&abc::foo);\n"
" return 0\n"
"}");
ASSERT_EQUALS("", errout_str());
check("namespace abc {\n"
" void foo() { }\n"
"};\n"
"int main() {\n"
" f = &abc::foo;\n"
" return 0\n"
"}");
ASSERT_EQUALS("", errout_str());
check("namespace abc {\n"
" void foo() { }\n"
"};\n"
"int main() {\n"
" f = &::abc::foo;\n"
" return 0\n"
"}");
ASSERT_EQUALS("", errout_str());
check("namespace abc {\n" // #3875
" void foo() { }\n"
"};\n"
"int main() {\n"
" f(abc::foo);\n"
" return 0\n"
"}");
ASSERT_EQUALS("", errout_str());
check("template <class T> T f()\n" // #13117
"{\n"
" return T(1);\n"
"}\n"
"int main(void)\n"
"{\n"
" auto *ptr = &f<int>;\n"
" return ptr();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void template1() {
check("template<class T> void foo() { }\n"
"\n"
"int main()\n"
"{\n"
" foo<int>();\n"
" return 0\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void template2() {
check("void f() { }\n"
"\n"
"template<class T> void g()\n"
"{\n"
" f();\n"
"}\n"
"\n"
"void h() { g<int>(); h(); }");
ASSERT_EQUALS("[test.cpp:8]: (style) The function 'h' is never used.\n", errout_str());
}
void template3() { // #4701
check("class X {\n"
"public:\n"
" void bar() { foo<int>(0); }\n"
"private:\n"
" template<typename T> void foo( T t ) const;\n"
"};\n"
"template<typename T> void X::foo( T t ) const { }");
ASSERT_EQUALS("[test.cpp:3]: (style) The function 'bar' is never used.\n", errout_str());
}
void template4() { // #9805
check("struct A {\n"
" int a = 0;\n"
" void f() { a = 1; }\n"
" template <typename T, typename... Args> auto call(const Args &... args) -> T {\n"
" a = 2;\n"
" return T{};\n"
" }\n"
"};\n"
"\n"
"struct B : public A {\n"
" void test() {\n"
" f();\n"
" call<int>(1, 2, 3);\n"
" test();\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:11]: (style) The function 'test' is never used.\n", errout_str());
}
void template5() { // #9220
check("void f(){}\n"
"\n"
"typedef void(*Filter)();\n"
"\n"
"template <Filter fun>\n"
"void g() { fun(); }\n"
"\n"
"int main() { g<f>(); return 0;}");
ASSERT_EQUALS("", errout_str());
}
void template6() { // #10475
check("template<template<typename...> class Ref, typename... Args>\n"
"struct Foo<Ref<Args...>, Ref> : std::true_type {};\n");
ASSERT_EQUALS("", errout_str());
}
void template7()
{ // #9766
check("void f() {\n"
" std::array<std::array<double,3>,3> array;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:1]: (style) The function 'f' is never used.\n", errout_str());
}
void template8() { // #11485
check("struct S {\n"
" template<typename T>\n"
" void tf(const T&) { }\n"
"};\n");
ASSERT_EQUALS("[test.cpp:3]: (style) The function 'tf' is never used.\n", errout_str());
check("struct C {\n"
" template<typename T>\n"
" void tf(const T&) { }\n"
"};\n"
"int main() {\n"
" C c;\n"
" c.tf(1.5);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct C {\n"
" template<typename T>\n"
" void tf(const T&) { }\n"
"};\n"
"int main() {\n"
" C c;\n"
" c.tf<int>(1);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void template9() {
check("template<class T>\n" // #7739
"void f(T const& t) {}\n"
"template<class T>\n"
"void g(T const& t) {\n"
" f(t);\n"
"}\n"
"template<>\n"
"void f<double>(double const& d) {}\n"
"int main() {\n"
" g(2);\n"
" g(3.14);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("template <typename T> T f(T);\n" // #9222
"template <typename T> T f(T i) { return i; }\n"
"template int f<int>(int);\n"
"int main() { return f(int(2)); }\n");
ASSERT_EQUALS("", errout_str());
}
void template10() {
check("template<typename T>\n" // #12013, don't crash
"struct S {\n"
" static const int digits = std::numeric_limits<T>::digits;\n"
" using type = std::conditional<digits < 32, std::int32_t, std::int64_t>::type;\n"
"};\n");
ASSERT_EQUALS("", errout_str());
}
void throwIsNotAFunction() {
check("struct A {void f() const throw () {}}; int main() {A a; a.f();}");
ASSERT_EQUALS("", errout_str());
}
void unusedError() {
check("void foo() {}\n"
"int main()");
ASSERT_EQUALS("[test.cpp:1]: (style) The function 'foo' is never used.\n", errout_str());
check("void foo() const {}\n"
"int main()");
ASSERT_EQUALS("[test.cpp:1]: (style) The function 'foo' is never used.\n", errout_str());
check("void foo() const throw() {}\n"
"int main()");
ASSERT_EQUALS("[test.cpp:1]: (style) The function 'foo' is never used.\n", errout_str());
check("void foo() throw() {}\n"
"int main()");
ASSERT_EQUALS("[test.cpp:1]: (style) The function 'foo' is never used.\n", errout_str());
}
void unusedMain() {
check("int main() { }");
ASSERT_EQUALS("", errout_str());
}
void initializationIsNotAFunction() {
check("struct B: N::A {\n"
" B(): N::A() {};\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void operator1() {
check("struct Foo { void operator()(int a) {} };");
ASSERT_EQUALS("", errout_str());
check("struct Foo { operator std::string(int a) {} };");
ASSERT_EQUALS("", errout_str());
}
void operator2() { // #7974
check("bool operator==(const data_t& a, const data_t& b) {\n"
" return (a.fd == b.fd);\n"
"}\n"
"bool operator==(const event& a, const event& b) {\n"
" return ((a.events == b.events) && (a.data == b.data));\n"
"}\n"
"int main(event a, event b) {\n"
" return a == b;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void returnRef() {
check("int& foo() {return x;}");
ASSERT_EQUALS("[test.cpp:1]: (style) The function 'foo' is never used.\n", errout_str());
}
void attribute() { // #3471 - FP __attribute__((constructor))
check("void __attribute__((constructor)) f() {}");
ASSERT_EQUALS("", errout_str());
check("void __attribute__((constructor(1000))) f() {}");
ASSERT_EQUALS("", errout_str());
check("void __attribute__((destructor)) f() {}");
ASSERT_EQUALS("", errout_str());
check("void __attribute__((destructor(1000))) f() {}");
ASSERT_EQUALS("", errout_str());
// alternate syntax
check("__attribute__((constructor)) void f() {}");
ASSERT_EQUALS("", errout_str());
check("__attribute__((constructor(1000))) void f() {}");
ASSERT_EQUALS("", errout_str());
check("__attribute__((destructor)) void f() {}");
ASSERT_EQUALS("", errout_str());
check("__attribute__((destructor(1000))) void f() {}");
ASSERT_EQUALS("", errout_str());
// alternate syntax
check("void f() __attribute__((constructor));\n"
"void f() { }");
ASSERT_EQUALS("", errout_str());
check("void f() __attribute__((constructor(1000)));\n"
"void f() { }");
ASSERT_EQUALS("", errout_str());
check("void f() __attribute__((destructor));\n"
"void f() { }");
ASSERT_EQUALS("", errout_str());
check("void f() __attribute__((destructor(1000)));\n"
"void f() { }");
ASSERT_EQUALS("", errout_str());
// Don't crash on wrong syntax
check("int x __attribute__((constructor));\n"
"int y __attribute__((destructor));");
// #10661
check("extern \"C\" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t dataSize) { return 0; }\n");
ASSERT_EQUALS("", errout_str());
check("[[maybe_unused]] void f() {}\n" // #13268
"__attribute__((unused)) void g() {}\n");
ASSERT_EQUALS("", errout_str());
}
void initializer_list() {
check("int foo() { return 0; }\n"
"struct A {\n"
" A() : m_i(foo())\n"
" {}\n"
"int m_i;\n"
"};");
ASSERT_EQUALS("", errout_str());
// #8580
check("int foo() { return 12345; }\n"
"int bar(std::function<int()> func) { return func(); }\n"
"\n"
"class A {\n"
"public:\n"
" A() : a(bar([] { return foo(); })) {}\n"
" const int a;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void member_function_ternary() {
check("struct Foo {\n"
" void F1() {}\n"
" void F2() {}\n"
"};\n"
"int main(int argc, char *argv[]) {\n"
" Foo foo;\n"
" void (Foo::*ptr)();\n"
" ptr = (argc > 1 && !strcmp(argv[1], \"F2\")) ? &Foo::F2 : &Foo::F1;\n"
" (foo.*ptr)();\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void boost() {
check("static void _xy(const char *b, const char *e) {}\n"
"void f() {\n"
" parse(line, blanks_p >> ident[&_xy] >> blanks_p >> eol_p).full;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) The function 'f' is never used.\n", errout_str());
}
void enumValues() { // #11486
check("enum E1 { Break1 };\n"
"struct S {\n"
" enum class E { Break };\n"
" void Break() {}\n"
" void Break1() {}\n"
"};\n");
ASSERT_EQUALS("[test.cpp:4]: (style) The function 'Break' is never used.\n"
"[test.cpp:5]: (style) The function 'Break1' is never used.\n",
errout_str());
check("struct S {\n" // #12899
" void f() {}\n"
"};\n"
"enum E { f };\n"
"int main() {\n"
" E e{ f };\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) The function 'f' is never used.\n", errout_str());
}
void recursive() {
check("void f() {\n" // #8159
" f();\n"
"}\n");
ASSERT_EQUALS("[test.cpp:1]: (style) The function 'f' is never used.\n",
errout_str());
}
void multipleFiles() {
CheckUnusedFunctions c;
const char code[] = "static void f() { }";
for (int i = 1; i <= 2; ++i) {
const std::string fname = "test" + std::to_string(i) + ".cpp";
Tokenizer tokenizer(settings, *this);
std::istringstream istr(code);
ASSERT(tokenizer.list.createTokens(istr, fname));
ASSERT(tokenizer.simplifyTokens1(""));
c.parseTokens(tokenizer, settings);
}
// Check for unused functions..
(c.check)(settings, *this); // TODO: check result
ASSERT_EQUALS("[test1.cpp:1]: (style) The function 'f' is never used.\n", errout_str());
}
void lineNumber() {
check("void foo();\n"
"void bar() {}\n"
"int main() {}");
ASSERT_EQUALS("[test.cpp:2]: (style) The function 'bar' is never used.\n", errout_str());
}
void ignore_declaration() {
check("void f();\n"
"void f() {}");
ASSERT_EQUALS("[test.cpp:2]: (style) The function 'f' is never used.\n", errout_str());
check("void f(void) {}\n"
"void (*list[])(void) = {f};");
ASSERT_EQUALS("", errout_str());
}
void operatorOverload() {
check("class A {\n"
"private:\n"
" friend std::ostream & operator<<(std::ostream &, const A&);\n"
"};\n"
"std::ostream & operator<<(std::ostream &os, const A&) {\n"
" os << \"This is class A\";\n"
"}");
ASSERT_EQUALS("", errout_str());
check("class A{};\n"
"A operator + (const A &, const A &){ return A(); }\n"
"A operator - (const A &, const A &){ return A(); }\n"
"A operator * (const A &, const A &){ return A(); }\n"
"A operator / (const A &, const A &){ return A(); }\n"
"A operator % (const A &, const A &){ return A(); }\n"
"A operator & (const A &, const A &){ return A(); }\n"
"A operator | (const A &, const A &){ return A(); }\n"
"A operator ~ (const A &){ return A(); }\n"
"A operator ! (const A &){ return A(); }\n"
"bool operator < (const A &, const A &){ return true; }\n"
"bool operator > (const A &, const A &){ return true; }\n"
"A operator += (const A &, const A &){ return A(); }\n"
"A operator -= (const A &, const A &){ return A(); }\n"
"A operator *= (const A &, const A &){ return A(); }\n"
"A operator /= (const A &, const A &){ return A(); }\n"
"A operator %= (const A &, const A &){ return A(); }\n"
"A operator &= (const A &, const A &){ return A(); }\n"
"A operator ^= (const A &, const A &){ return A(); }\n"
"A operator |= (const A &, const A &){ return A(); }\n"
"A operator << (const A &, const int){ return A(); }\n"
"A operator >> (const A &, const int){ return A(); }\n"
"A operator <<= (const A &, const int){ return A(); }\n"
"A operator >>= (const A &, const int){ return A(); }\n"
"bool operator == (const A &, const A &){ return true; }\n"
"bool operator != (const A &, const A &){ return true; }\n"
"bool operator <= (const A &, const A &){ return true; }\n"
"bool operator >= (const A &, const A &){ return true; }\n"
"A operator && (const A &, const int){ return A(); }\n"
"A operator || (const A &, const int){ return A(); }\n"
"A operator ++ (const A &, const int){ return A(); }\n"
"A operator ++ (const A &){ return A(); }\n"
"A operator -- (const A &, const int){ return A(); }\n"
"A operator -- (const A &){ return A(); }\n"
"A operator , (const A &, const A &){ return A(); }");
ASSERT_EQUALS("", errout_str());
check("class A {\n"
"public:\n"
" static void * operator new(std::size_t);\n"
" static void * operator new[](std::size_t);\n"
"};\n"
"void * A::operator new(std::size_t s) {\n"
" return malloc(s);\n"
"}\n"
"void * A::operator new[](std::size_t s) {\n"
" return malloc(s);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void entrypointsWin() {
check("int WinMain() { }");
ASSERT_EQUALS("[test.cpp:1]: (style) The function 'WinMain' is never used.\n", errout_str());
check("int _tmain() { }");
ASSERT_EQUALS("[test.cpp:1]: (style) The function '_tmain' is never used.\n", errout_str());
const Settings s = settingsBuilder(settings).library("windows.cfg").build();
check("int WinMain() { }", Platform::Type::Native, &s);
ASSERT_EQUALS("", errout_str());
check("int _tmain() { }", Platform::Type::Native, &s);
ASSERT_EQUALS("", errout_str());
}
void entrypointsWinU() {
check("int wWinMain() { }");
ASSERT_EQUALS("[test.cpp:1]: (style) The function 'wWinMain' is never used.\n", errout_str());
check("int _tmain() { }");
ASSERT_EQUALS("[test.cpp:1]: (style) The function '_tmain' is never used.\n", errout_str());
const Settings s = settingsBuilder(settings).library("windows.cfg").build();
check("int wWinMain() { }", Platform::Type::Native, &s);
ASSERT_EQUALS("", errout_str());
check("int _tmain() { }", Platform::Type::Native, &s);
ASSERT_EQUALS("", errout_str());
}
void entrypointsUnix() {
check("int _init() { }\n"
"int _fini() { }\n");
ASSERT_EQUALS("[test.cpp:1]: (style) The function '_init' is never used.\n"
"[test.cpp:2]: (style) The function '_fini' is never used.\n", errout_str());
const Settings s = settingsBuilder(settings).library("gnu.cfg").build();
check("int _init() { }\n"
"int _fini() { }\n", Platform::Type::Native, &s);
ASSERT_EQUALS("", errout_str());
}
// TODO: fails because the location information is not be preserved by PreprocessorHelper::getcode()
void includes()
{
// #11483
const char inc[] = "class A {\n"
"public:\n"
" void f() {}\n"
"};";
const char code[] = R"(#include "test.h")";
ScopedFile header("test.h", inc);
const std::string processed = PreprocessorHelper::getcode(settings, *this, code, "", "test.cpp");
check(processed);
TODO_ASSERT_EQUALS("[test.h:3]: (style) The function 'f' is never used.\n", "[test.cpp:3]: (style) The function 'f' is never used.\n", errout_str());
}
void virtualFunc()
{
check("struct D : public B {\n" // #10660
" virtual void f() {}\n"
" void g() override {}\n"
" void h() final {}\n"
"};\n");
ASSERT_EQUALS("", errout_str());
check("struct B {\n"
" virtual void f() = 0;\n"
" void g();\n"
"};\n"
"struct D : B {\n"
" void f() override {}\n"
"};\n"
"int main() {\n"
" D d;\n"
" d.g();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void parensInit()
{
check("struct S {\n" // #12898
" void url() {}\n"
"};\n"
"int main() {\n"
" const int url(0);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) The function 'url' is never used.\n", errout_str());
}
void typeInCast()
{
check("struct S {\n" // #12901
" void Type() {}\n"
"};\n"
"int main() {\n"
" struct Type {} t;\n"
" Type t2{ (Type)t };\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) The function 'Type' is never used.\n", errout_str());
}
void attributeCleanup()
{
check("void clean(void *ptr) {}\n"
"int main() {\n"
" void * __attribute__((cleanup(clean))) p;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
};
REGISTER_TEST(TestUnusedFunctions)
| null |
988 | cpp | cppcheck | testtimer.cpp | test/testtimer.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2023 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "fixture.h"
#include "timer.h"
#include <cmath>
#include <ctime>
class TestTimer : public TestFixture {
public:
TestTimer() : TestFixture("TestTimer") {}
private:
void run() override {
TEST_CASE(result);
}
void result() const {
TimerResultsData t1;
t1.mClocks = ~(std::clock_t)0;
ASSERT(t1.seconds() > 100.0);
t1.mClocks = CLOCKS_PER_SEC * 5 / 2;
ASSERT(std::fabs(t1.seconds()-2.5) < 0.01);
}
};
REGISTER_TEST(TestTimer)
| null |
989 | cpp | cppcheck | testfunctions.cpp | test/testfunctions.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "checkfunctions.h"
#include "errortypes.h"
#include "fixture.h"
#include "helpers.h"
#include "settings.h"
#include "standards.h"
#include <cstddef>
#include <string>
class TestFunctions : public TestFixture {
public:
TestFunctions() : TestFixture("TestFunctions") {}
private:
const Settings settings = settingsBuilder().severity(Severity::style).severity(Severity::warning).severity(Severity::performance).severity(Severity::portability).
certainty(Certainty::inconclusive).c(Standards::C11).cpp(Standards::CPP11).library("std.cfg").library("posix.cfg").build();
void run() override {
// Prohibited functions
TEST_CASE(prohibitedFunctions_posix);
TEST_CASE(prohibitedFunctions_index);
TEST_CASE(prohibitedFunctions_qt_index); // FP when using the Qt function 'index'?
TEST_CASE(prohibitedFunctions_rindex);
TEST_CASE(prohibitedFunctions_var); // no false positives for variables
TEST_CASE(prohibitedFunctions_gets); // dangerous function
TEST_CASE(prohibitedFunctions_alloca);
TEST_CASE(prohibitedFunctions_declaredFunction); // declared function ticket #3121
TEST_CASE(prohibitedFunctions_std_gets); // test std::gets
TEST_CASE(prohibitedFunctions_multiple); // multiple use of obsolete functions
TEST_CASE(prohibitedFunctions_c_declaration); // c declared function
TEST_CASE(prohibitedFunctions_functionWithBody); // function with body
TEST_CASE(prohibitedFunctions_crypt); // Non-reentrant function
TEST_CASE(prohibitedFunctions_namespaceHandling);
// Invalid function usage
TEST_CASE(invalidFunctionUsage1);
TEST_CASE(invalidFunctionUsageStrings);
// Invalid function argument
TEST_CASE(invalidFunctionArg1);
// Math function usage
TEST_CASE(mathfunctionCall_fmod);
TEST_CASE(mathfunctionCall_sqrt);
TEST_CASE(mathfunctionCall_log);
TEST_CASE(mathfunctionCall_acos);
TEST_CASE(mathfunctionCall_asin);
TEST_CASE(mathfunctionCall_pow);
TEST_CASE(mathfunctionCall_atan2);
TEST_CASE(mathfunctionCall_precision);
// Ignored return value
TEST_CASE(checkIgnoredReturnValue);
TEST_CASE(checkIgnoredErrorCode);
// memset..
TEST_CASE(memsetZeroBytes);
TEST_CASE(memsetInvalid2ndParam);
// missing "return"
TEST_CASE(checkMissingReturn1);
TEST_CASE(checkMissingReturn2); // #11798
TEST_CASE(checkMissingReturn3);
TEST_CASE(checkMissingReturn4);
TEST_CASE(checkMissingReturn5);
TEST_CASE(checkMissingReturn6); // #13180
// std::move for locar variable
TEST_CASE(returnLocalStdMove1);
TEST_CASE(returnLocalStdMove2);
TEST_CASE(returnLocalStdMove3);
TEST_CASE(returnLocalStdMove4);
TEST_CASE(returnLocalStdMove5);
TEST_CASE(negativeMemoryAllocationSizeError); // #389
TEST_CASE(checkLibraryMatchFunctions);
TEST_CASE(checkUseStandardLibrary1);
TEST_CASE(checkUseStandardLibrary2);
TEST_CASE(checkUseStandardLibrary3);
TEST_CASE(checkUseStandardLibrary4);
TEST_CASE(checkUseStandardLibrary5);
TEST_CASE(checkUseStandardLibrary6);
TEST_CASE(checkUseStandardLibrary7);
TEST_CASE(checkUseStandardLibrary8);
TEST_CASE(checkUseStandardLibrary9);
TEST_CASE(checkUseStandardLibrary10);
TEST_CASE(checkUseStandardLibrary11);
TEST_CASE(checkUseStandardLibrary12);
TEST_CASE(checkUseStandardLibrary13);
TEST_CASE(checkUseStandardLibrary14);
}
#define check(...) check_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
void check_(const char* file, int line, const char (&code)[size], bool cpp = true, const Settings* settings_ = nullptr) {
if (!settings_)
settings_ = &settings;
// Tokenize..
SimpleTokenizer tokenizer(*settings_, *this);
ASSERT_LOC(tokenizer.tokenize(code, cpp), file, line);
runChecks<CheckFunctions>(tokenizer, this);
}
void prohibitedFunctions_posix() {
check("void f()\n"
"{\n"
" bsd_signal(SIGABRT, SIG_IGN);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Obsolescent function 'bsd_signal' called. It is recommended to use 'sigaction' instead.\n", errout_str());
check("int f()\n"
"{\n"
" int bsd_signal(0);\n"
" return bsd_signal;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f()\n"
"{\n"
" struct hostent *hp;\n"
" if(!hp = gethostbyname(\"127.0.0.1\")) {\n"
" exit(1);\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Obsolescent function 'gethostbyname' called. It is recommended to use 'getaddrinfo' instead.\n", errout_str());
check("void f()\n"
"{\n"
" long addr;\n"
" addr = inet_addr(\"127.0.0.1\");\n"
" if(!hp = gethostbyaddr((char *) &addr, sizeof(addr), AF_INET)) {\n"
" exit(1);\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (style) Obsolescent function 'gethostbyaddr' called. It is recommended to use 'getnameinfo' instead.\n", errout_str());
check("void f()\n"
"{\n"
" usleep( 1000 );\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Obsolescent function 'usleep' called. It is recommended to use 'nanosleep' or 'setitimer' instead.\n", errout_str());
}
void prohibitedFunctions_index() {
check("namespace n1 {\n"
" int index(){ return 1; };\n"
"}\n"
"int main()\n"
"{\n"
" n1::index();\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("std::size_t f()\n"
"{\n"
" std::size_t index(0);\n"
" index++;\n"
" return index;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f()\n"
"{\n"
" return this->index();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f()\n"
"{\n"
" int index( 0 );\n"
"}");
ASSERT_EQUALS("", errout_str());
check("const char f()\n"
"{\n"
" const char var[6] = \"index\";\n"
" const char i = index(var, 0);\n"
" return i;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Obsolescent function 'index' called. It is recommended to use 'strchr' instead.\n",
errout_str());
}
void prohibitedFunctions_qt_index() {
check("void TDataModel::forceRowRefresh(int row) {\n"
" emit dataChanged(index(row, 0), index(row, columnCount() - 1));\n"
"}");
ASSERT_EQUALS(
"[test.cpp:2]: (style) Obsolescent function 'index' called. It is recommended to use 'strchr' instead.\n"
"[test.cpp:2]: (style) Obsolescent function 'index' called. It is recommended to use 'strchr' instead.\n", // duplicate
errout_str());
}
void prohibitedFunctions_rindex() {
check("void f()\n"
"{\n"
" int rindex( 0 );\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f()\n"
"{\n"
" const char var[7] = \"rindex\";\n"
" print(rindex(var, 0));\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Obsolescent function 'rindex' called. It is recommended to use 'strrchr' instead.\n", errout_str());
}
void prohibitedFunctions_var() {
check("class Fred {\n"
"public:\n"
" Fred() : index(0) { }\n"
" int index;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void prohibitedFunctions_gets() {
check("void f()\n"
"{\n"
" char *x = gets(a);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Obsolete function 'gets' called. It is recommended to use 'fgets' or 'gets_s' instead.\n", errout_str());
check("void f()\n"
"{\n"
" foo(x, gets(a));\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Obsolete function 'gets' called. It is recommended to use 'fgets' or 'gets_s' instead.\n", errout_str());
}
void prohibitedFunctions_alloca() {
check("void f()\n"
"{\n"
" char *x = alloca(10);\n"
"}"); // #4382 - there are no VLAs in C++
ASSERT_EQUALS("[test.cpp:3]: (warning) Obsolete function 'alloca' called.\n", errout_str());
check("void f()\n"
"{\n"
" char *x = alloca(10);\n"
"}", false);
ASSERT_EQUALS("[test.c:3]: (warning) Obsolete function 'alloca' called. In C99 and later it is recommended to use a variable length array instead.\n", errout_str());
const Settings s = settingsBuilder(settings).c(Standards::C89).cpp(Standards::CPP03).build();
check("void f()\n"
"{\n"
" char *x = alloca(10);\n"
"}", true, &s); // #4382 - there are no VLAs in C++
ASSERT_EQUALS("", errout_str());
check("void f()\n"
"{\n"
" char *x = alloca(10);\n"
"}", false, &s); // #7558 - no alternative to alloca in C89
ASSERT_EQUALS("", errout_str());
check("void f()\n"
"{\n"
" char *x = alloca(10);\n"
"}", false, &s);
ASSERT_EQUALS("", errout_str());
}
// ticket #3121
void prohibitedFunctions_declaredFunction() {
check("int ftime ( int a )\n"
"{\n"
" return a;\n"
"}\n"
"int main ()\n"
"{\n"
" int b ; b = ftime ( 1 ) ;\n"
" return 0 ;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
// test std::gets
void prohibitedFunctions_std_gets() {
check("void f(char * str)\n"
"{\n"
" char *x = std::gets(str);\n"
" char *y = gets(str);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Obsolete function 'gets' called. It is recommended to use 'fgets' or 'gets_s' instead.\n"
"[test.cpp:4]: (warning) Obsolete function 'gets' called. It is recommended to use 'fgets' or 'gets_s' instead.\n", errout_str());
}
// multiple use
void prohibitedFunctions_multiple() {
check("void f(char * str)\n"
"{\n"
" char *x = std::gets(str);\n"
" usleep( 1000 );\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Obsolete function 'gets' called. It is recommended to use 'fgets' or 'gets_s' instead.\n"
"[test.cpp:4]: (style) Obsolescent function 'usleep' called. It is recommended to use 'nanosleep' or 'setitimer' instead.\n", errout_str());
}
void prohibitedFunctions_c_declaration() {
check("char * gets ( char * c ) ;\n"
"int main ()\n"
"{\n"
" char s [ 10 ] ;\n"
" gets ( s ) ;\n"
" return 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (warning) Obsolete function 'gets' called. It is recommended to use 'fgets' or 'gets_s' instead.\n", errout_str());
check("int getcontext(ucontext_t *ucp);\n"
"void f (ucontext_t *ucp)\n"
"{\n"
" getcontext ( ucp ) ;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (portability) Obsolescent function 'getcontext' called. Applications are recommended to be rewritten to use POSIX threads.\n", errout_str());
}
void prohibitedFunctions_functionWithBody() {
check("char * gets ( char * c ) { return c; }\n"
"int main ()\n"
"{\n"
" char s [ 10 ] ;\n"
" gets ( s ) ;\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void prohibitedFunctions_crypt() {
check("void f(char *pwd)\n"
"{\n"
" char *cpwd;"
" crypt(pwd, cpwd);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Return value of function crypt() is not used.\n"
"[test.cpp:3]: (portability) Non reentrant function 'crypt' called. For threadsafe applications it is recommended to use the reentrant replacement function 'crypt_r'.\n", errout_str());
check("void f()\n"
"{\n"
" char *pwd = getpass(\"Password:\");"
" char *cpwd;"
" crypt(pwd, cpwd);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Return value of function crypt() is not used.\n"
"[test.cpp:3]: (portability) Non reentrant function 'crypt' called. For threadsafe applications it is recommended to use the reentrant replacement function 'crypt_r'.\n", errout_str());
check("int f()\n"
"{\n"
" int crypt = 0;"
" return crypt;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void prohibitedFunctions_namespaceHandling() {
check("void f()\n"
"{\n"
" time_t t = 0;"
" auto lt = std::localtime(&t);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (portability) Non reentrant function 'localtime' called. For threadsafe applications it is recommended to use the reentrant replacement function 'localtime_r'.\n", errout_str());
// Passed as function argument
check("void f()\n"
"{\n"
" printf(\"Magic guess: %d\", getpwent());\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (portability) Non reentrant function 'getpwent' called. For threadsafe applications it is recommended to use the reentrant replacement function 'getpwent_r'.\n", errout_str());
// Pass return value
check("void f()\n"
"{\n"
" time_t t = 0;"
" struct tm *foo = localtime(&t);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (portability) Non reentrant function 'localtime' called. For threadsafe applications it is recommended to use the reentrant replacement function 'localtime_r'.\n", errout_str());
// Access via global namespace
check("void f()\n"
"{\n"
" ::getpwent();\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Return value of function ::getpwent() is not used.\n"
"[test.cpp:3]: (portability) Non reentrant function 'getpwent' called. For threadsafe applications it is recommended to use the reentrant replacement function 'getpwent_r'.\n", errout_str());
// Be quiet on function definitions
check("int getpwent()\n"
"{\n"
" return 123;\n"
"}");
ASSERT_EQUALS("", errout_str());
// Be quiet on other namespaces
check("void f()\n"
"{\n"
" foobar::getpwent();\n"
"}");
ASSERT_EQUALS("", errout_str());
// Be quiet on class member functions
check("void f()\n"
"{\n"
" foobar.getpwent();\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void invalidFunctionUsage1() {
check("void f() { memset(a,b,sizeof(a)!=12); }");
ASSERT_EQUALS("[test.cpp:1]: (error) Invalid memset() argument nr 3. A non-boolean value is required.\n", errout_str());
check("void f() { memset(a,b,sizeof(a)!=0); }");
ASSERT_EQUALS("[test.cpp:1]: (error) Invalid memset() argument nr 3. A non-boolean value is required.\n", errout_str());
check("void f() { memset(a,b,!c); }");
ASSERT_EQUALS("[test.cpp:1]: (error) Invalid memset() argument nr 3. A non-boolean value is required.\n", errout_str());
// Ticket #6990
check("void f(bool c) { memset(a,b,c); }");
ASSERT_EQUALS("[test.cpp:1]: (error) Invalid memset() argument nr 3. A non-boolean value is required.\n", errout_str());
check("void f() { memset(a,b,true); }");
ASSERT_EQUALS("[test.cpp:1]: (error) Invalid memset() argument nr 3. A non-boolean value is required.\n", errout_str());
// Ticket #6588 (c mode)
check("void record(char* buf, int n) {\n"
" memset(buf, 0, n < 255);\n" /* KO */
" memset(buf, 0, n < 255 ? n : 255);\n" /* OK */
"}", false);
ASSERT_EQUALS("[test.c:2]: (error) Invalid memset() argument nr 3. A non-boolean value is required.\n", errout_str());
// Ticket #6588 (c++ mode)
check("void record(char* buf, int n) {\n"
" memset(buf, 0, n < 255);\n" /* KO */
" memset(buf, 0, n < 255 ? n : 255);\n" /* OK */
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Invalid memset() argument nr 3. A non-boolean value is required.\n", errout_str());
check("int boolArgZeroIsInvalidButOneIsValid(int a, int param) {\n"
" return div(a, param > 0);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Invalid div() argument nr 2. The value is 0 or 1 (boolean) but the valid values are ':-1,1:'.\n", errout_str());
check("void boolArgZeroIsValidButOneIsInvalid(int param) {\n"
" strtol(a, b, param > 0);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Invalid strtol() argument nr 3. The value is 0 or 1 (boolean) but the valid values are '0,2:36'.\n", errout_str());
check("void f() { strtol(a,b,1); }");
ASSERT_EQUALS("[test.cpp:1]: (error) Invalid strtol() argument nr 3. The value is 1 but the valid values are '0,2:36'.\n", errout_str());
check("void f() { strtol(a,b,10); }");
ASSERT_EQUALS("", errout_str());
check("void f(std::vector<int>& v) {\n" // #10754
" int N = -1;\n"
" for (long i = 0; i < g(); i++)\n"
" N = h(N);\n"
" v.resize(N);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5]: (warning) Invalid v.resize() argument nr 1. The value is -1 but the valid values are '0:'.\n", errout_str());
check("void f(std::vector<int>& v, int N) {\n"
" if (N < -1)\n"
" return;\n"
" v.resize(N);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:4]: (warning) Either the condition 'N<-1' is redundant or v.resize() argument nr 1 can have invalid value. The value is -1 but the valid values are '0:'.\n",
errout_str());
check("void f(std::vector<int>& v, int N) {\n"
" if (N == -1) {}\n"
" v.resize(N);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (warning) Either the condition 'N==-1' is redundant or v.resize() argument nr 1 can have invalid value. The value is -1 but the valid values are '0:'.\n",
errout_str());
check("void f(std::vector<int>& v, int N, bool b) {\n"
" if (b)\n"
" N = -1;\n"
" v.resize(N);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (warning) Invalid v.resize() argument nr 1. The value is -1 but the valid values are '0:'.\n",
errout_str());
check("void f(std::vector<int>& v) {\n"
" int N = -1;\n"
" v.resize(N);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Invalid v.resize() argument nr 1. The value is -1 but the valid values are '0:'.\n",
errout_str());
}
void invalidFunctionUsageStrings() {
check("size_t f() { char x = 'x'; return strlen(&x); }");
ASSERT_EQUALS("[test.cpp:1]: (error) Invalid strlen() argument nr 1. A nul-terminated string is required.\n", errout_str());
check("size_t f() { return strlen(&x); }");
ASSERT_EQUALS("", errout_str());
check("size_t f(char x) { return strlen(&x); }");
ASSERT_EQUALS("[test.cpp:1]: (error) Invalid strlen() argument nr 1. A nul-terminated string is required.\n", errout_str());
check("size_t f() { char x = '\\0'; return strlen(&x); }");
ASSERT_EQUALS("", errout_str());
check("size_t f() {\n"
" char x;\n"
" if (y)\n"
" x = '\\0';\n"
" else\n"
" x = 'a';\n"
" return strlen(&x);\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (error) Invalid strlen() argument nr 1. A nul-terminated string is required.\n", errout_str());
check("int f() { char x = '\\0'; return strcmp(\"Hello world\", &x); }");
ASSERT_EQUALS("", errout_str());
check("int f() { char x = 'x'; return strcmp(\"Hello world\", &x); }");
ASSERT_EQUALS("[test.cpp:1]: (error) Invalid strcmp() argument nr 2. A nul-terminated string is required.\n", errout_str());
check("size_t f(char x) { char * y = &x; return strlen(y); }");
TODO_ASSERT_EQUALS("[test.cpp:1]: (error) Invalid strlen() argument nr 1. A nul-terminated string is required.\n", "", errout_str());
check("size_t f(char x) { char * y = &x; char *z = y; return strlen(z); }");
TODO_ASSERT_EQUALS("[test.cpp:1]: (error) Invalid strlen() argument nr 1. A nul-terminated string is required.\n", "", errout_str());
check("size_t f() { char x = 'x'; char * y = &x; char *z = y; return strlen(z); }");
TODO_ASSERT_EQUALS("[test.cpp:1]: (error) Invalid strlen() argument nr 1. A nul-terminated string is required.\n", "", errout_str());
check("size_t f() { char x = '\\0'; char * y = &x; char *z = y; return strlen(z); }");
ASSERT_EQUALS("", errout_str());
check("size_t f() { char x[] = \"Hello world\"; return strlen(x); }");
ASSERT_EQUALS("", errout_str());
check("size_t f(char x[]) { return strlen(x); }");
ASSERT_EQUALS("", errout_str());
check("int f(char x, char y) { return strcmp(&x, &y); }");
ASSERT_EQUALS("[test.cpp:1]: (error) Invalid strcmp() argument nr 1. A nul-terminated string is required.\n"
"[test.cpp:1]: (error) Invalid strcmp() argument nr 2. A nul-terminated string is required.\n", errout_str());
check("size_t f() { char x[] = \"Hello world\"; return strlen(&x[0]); }");
ASSERT_EQUALS("", errout_str());
check("size_t f() { char* x = \"Hello world\"; return strlen(&x[0]); }");
ASSERT_EQUALS("", errout_str());
check("struct S {\n"
" char x;\n"
"};\n"
"size_t f() {\n"
" S s1 = {0};\n"
" S s2;\n;"
" s2.x = 'x';\n"
" size_t l1 = strlen(&s1.x);\n"
" size_t l2 = strlen(&s2.x);\n"
" return l1 + l2;\n"
"}");
ASSERT_EQUALS("[test.cpp:8]: (error) Invalid strlen() argument nr 1. A nul-terminated string is required.\n"
"[test.cpp:9]: (error) Invalid strlen() argument nr 1. A nul-terminated string is required.\n", errout_str());
check("const char x = 'x'; size_t f() { return strlen(&x); }");
ASSERT_EQUALS("[test.cpp:1]: (error) Invalid strlen() argument nr 1. A nul-terminated string is required.\n", errout_str());
check("struct someStruct {\n"
" union {\n"
" struct {\n"
" uint16_t nr;\n"
" uint8_t d[40];\n"
" } data;\n"
" char buf[42];\n"
" } x;\n"
"};\n"
"int f(struct someStruct * const tp, const int k)\n"
"{\n"
" return strcmp(&tp->x.buf[k], \"needle\");\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct someStruct {\n"
" char buf[42];\n"
"};\n"
"int f(struct someStruct * const tp, const int k)\n"
"{\n"
" return strcmp(&tp->buf[k], \"needle\");\n"
"}");
ASSERT_EQUALS("", errout_str());
check("const char x = 'x'; size_t f() { char y = x; return strlen(&y); }");
ASSERT_EQUALS("[test.cpp:1]: (error) Invalid strlen() argument nr 1. A nul-terminated string is required.\n", errout_str());
check("const char x = '\\0'; size_t f() { return strlen(&x); }");
ASSERT_EQUALS("", errout_str());
check("const char x = '\\0'; size_t f() { char y = x; return strlen(&y); }");
ASSERT_EQUALS("", errout_str());
check("size_t f() {\n"
" char * a = \"Hello world\";\n"
" char ** b = &a;\n"
" return strlen(&b[0][0]);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("size_t f() {\n"
" char ca[] = \"asdf\";\n"
" return strlen((char*) &ca);\n"
"}");
ASSERT_EQUALS("", errout_str());
// #5225
check("int main(void)\n"
"{\n"
" char str[80] = \"hello worl\";\n"
" char d = 'd';\n"
" strcat(str, &d);\n"
" puts(str);\n"
" return 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (error) Invalid strcat() argument nr 2. A nul-terminated string is required.\n", errout_str());
check("FILE* f(void) {\n"
" const char fileName[1] = { \'x\' };\n"
" return fopen(fileName, \"r\"); \n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Invalid fopen() argument nr 1. A nul-terminated string is required.\n", errout_str());
check("FILE* f(void) {\n"
" const char fileName[2] = { \'x\', \'y\' };\n"
" return fopen(fileName, \"r\"); \n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Invalid fopen() argument nr 1. A nul-terminated string is required.\n", errout_str());
check("FILE* f(void) {\n"
" const char fileName[3] = { \'x\', \'y\' ,\'\\0\' };\n"
" return fopen(fileName, \"r\"); \n"
"}");
ASSERT_EQUALS("", errout_str());
check("FILE* f(void) {\n"
" const char fileName[3] = { \'x\', \'\\0\' ,\'y\' };\n"
" return fopen(fileName, \"r\"); \n"
"}");
ASSERT_EQUALS("", errout_str());
check("FILE* f(void) {\n"
" const char fileName[3] = { \'x\', \'y\' };\n" // implicit '\0' added at the end
" return fopen(fileName, \"r\"); \n"
"}");
ASSERT_EQUALS("", errout_str());
check("FILE* f(void) {\n"
" const char fileName[] = { \'\\0\' };\n"
" return fopen(fileName, \"r\"); \n"
"}");
ASSERT_EQUALS("", errout_str());
check("FILE* f(void) {\n"
" const char fileName[] = { \'0\' + 42 };\n" // no size is explicitly defined, no implicit '\0' is added
" return fopen(fileName, \"r\"); \n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Invalid fopen() argument nr 1. A nul-terminated string is required.\n", errout_str());
check("FILE* f(void) {\n"
" const char fileName[] = { \'0\' + 42, \'x\' };\n" // no size is explicitly defined, no implicit '\0' is added
" return fopen(fileName, \"r\"); \n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Invalid fopen() argument nr 1. A nul-terminated string is required.\n", errout_str());
check("FILE* f(void) {\n"
" const char fileName[2] = { \'0\' + 42 };\n" // implicitly '\0' added at the end because size is set to 2
" return fopen(fileName, \"r\"); \n"
"}");
ASSERT_EQUALS("", errout_str());
check("FILE* f(void) {\n"
" const char fileName[] = { };\n"
" return fopen(fileName, \"r\"); \n"
"}");
ASSERT_EQUALS("", errout_str());
check("void scanMetaTypes()\n" // don't crash
"{\n"
" QVector<int> metaTypes;\n"
" for (int mtId = 0; mtId <= QMetaType::User; ++mtId) {\n"
" const auto name = QMetaType::typeName(mtId);\n"
" if (strstr(name, \"GammaRay::\") != name)\n"
" metaTypes.push_back(mtId);\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f() {\n"
" const char c[3] = \"abc\";\n"
" return strlen(c);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Invalid strlen() argument nr 1. A nul-terminated string is required.\n", errout_str());
check("int f() {\n"
" const wchar_t c[3] = L\"abc\";\n"
" return wcslen(c);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Invalid wcslen() argument nr 1. A nul-terminated string is required.\n", errout_str());
check("void f(char* dest) {\n"
" char if_name[(IF_NAMESIZE > 21 ? IF_NAMESIZE : 21) + 1] = \"%\";\n"
" strcat(dest, if_name);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("int f() {\n"
" const char c[3] = \"ab\\0\";\n"
" return strlen(c);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(int n) {\n" // #11179
" char s[8] = \" \";\n"
" n = (n + 1) % 100;\n"
" sprintf(s, \"lwip%02d\", n);\n"
" s[strlen(s)] = ' ';\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("size_t f() { wchar_t x = L'x'; return wcslen(&x); }");
ASSERT_EQUALS("[test.cpp:1]: (error) Invalid wcslen() argument nr 1. A nul-terminated string is required.\n", errout_str());
check("void f() { char a[10] = \"1234567890\"; puts(a); }", false); // #1770
ASSERT_EQUALS("[test.c:1]: (error) Invalid puts() argument nr 1. A nul-terminated string is required.\n", errout_str());
}
void invalidFunctionArg1() {
const Settings settingsUnix32 = settingsBuilder(settings).platform(Platform::Unix32).build();
check("int main() {\n"
" char tgt[7];\n"
" char src[7+1] = \"7777777\";\n"
" if (sizeof tgt <= sizeof src) {\n"
" memmove(&tgt, &src, sizeof tgt);\n"
" } else {\n"
" memmove(&tgt, &src, sizeof src);\n"
" memset(&tgt + sizeof src, ' ', sizeof tgt - sizeof src);\n"
" }\n"
"}\n", false, &settingsUnix32);
ASSERT_EQUALS("", errout_str());
}
void mathfunctionCall_sqrt() {
// sqrt, sqrtf, sqrtl
check("void foo()\n"
"{\n"
" std::cout << sqrt(-1) << std::endl;\n"
" std::cout << sqrtf(-1) << std::endl;\n"
" std::cout << sqrtl(-1) << std::endl;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Invalid sqrt() argument nr 1. The value is -1 but the valid values are '0.0:'.\n"
"[test.cpp:4]: (error) Invalid sqrtf() argument nr 1. The value is -1 but the valid values are '0.0:'.\n"
"[test.cpp:5]: (error) Invalid sqrtl() argument nr 1. The value is -1 but the valid values are '0.0:'.\n", errout_str());
// implementation-defined behaviour for "finite values of x<0" only:
check("void foo()\n"
"{\n"
" std::cout << sqrt(-0.) << std::endl;\n"
" std::cout << sqrtf(-0.) << std::endl;\n"
" std::cout << sqrtl(-0.) << std::endl;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo()\n"
"{\n"
" std::cout << sqrt(1) << std::endl;\n"
" std::cout << sqrtf(1) << std::endl;\n"
" std::cout << sqrtl(1) << std::endl;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void mathfunctionCall_log() {
// log,log10,logf,logl,log10f,log10l,log2,log2f,log2l,log1p,log1pf,log1pl
check("void foo()\n"
"{\n"
" std::cout << log(-2) << std::endl;\n"
" std::cout << logf(-2) << std::endl;\n"
" std::cout << logl(-2) << std::endl;\n"
" std::cout << log10(-2) << std::endl;\n"
" std::cout << log10f(-2) << std::endl;\n"
" std::cout << log10l(-2) << std::endl;\n"
" std::cout << log2(-2) << std::endl;\n"
" std::cout << log2f(-2) << std::endl;\n"
" std::cout << log2l(-2) << std::endl;\n"
" std::cout << log1p(-3) << std::endl;\n"
" std::cout << log1pf(-3) << std::endl;\n"
" std::cout << log1pl(-3) << std::endl;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Invalid log() argument nr 1. The value is -2 but the valid values are '4.94066e-324:'.\n"
"[test.cpp:4]: (error) Invalid logf() argument nr 1. The value is -2 but the valid values are '1.4013e-45:'.\n"
"[test.cpp:5]: (error) Invalid logl() argument nr 1. The value is -2 but the valid values are '4.94066e-324:'.\n"
"[test.cpp:6]: (error) Invalid log10() argument nr 1. The value is -2 but the valid values are '4.94066e-324:'.\n"
"[test.cpp:7]: (error) Invalid log10f() argument nr 1. The value is -2 but the valid values are '1.4013e-45:'.\n"
"[test.cpp:8]: (error) Invalid log10l() argument nr 1. The value is -2 but the valid values are '4.94066e-324:'.\n"
"[test.cpp:9]: (error) Invalid log2() argument nr 1. The value is -2 but the valid values are '4.94066e-324:'.\n"
"[test.cpp:10]: (error) Invalid log2f() argument nr 1. The value is -2 but the valid values are '1.4013e-45:'.\n"
"[test.cpp:11]: (error) Invalid log2l() argument nr 1. The value is -2 but the valid values are '4.94066e-324:'.\n"
"[test.cpp:3]: (warning) Passing value -2 to log() leads to implementation-defined result.\n"
"[test.cpp:4]: (warning) Passing value -2 to logf() leads to implementation-defined result.\n"
"[test.cpp:5]: (warning) Passing value -2 to logl() leads to implementation-defined result.\n"
"[test.cpp:6]: (warning) Passing value -2 to log10() leads to implementation-defined result.\n"
"[test.cpp:7]: (warning) Passing value -2 to log10f() leads to implementation-defined result.\n"
"[test.cpp:8]: (warning) Passing value -2 to log10l() leads to implementation-defined result.\n"
"[test.cpp:9]: (warning) Passing value -2 to log2() leads to implementation-defined result.\n"
"[test.cpp:10]: (warning) Passing value -2 to log2f() leads to implementation-defined result.\n"
"[test.cpp:11]: (warning) Passing value -2 to log2l() leads to implementation-defined result.\n"
"[test.cpp:12]: (warning) Passing value -3 to log1p() leads to implementation-defined result.\n"
"[test.cpp:13]: (warning) Passing value -3 to log1pf() leads to implementation-defined result.\n"
"[test.cpp:14]: (warning) Passing value -3 to log1pl() leads to implementation-defined result.\n", errout_str());
check("void foo()\n"
"{\n"
" std::cout << log(-1) << std::endl;\n"
" std::cout << logf(-1) << std::endl;\n"
" std::cout << logl(-1) << std::endl;\n"
" std::cout << log10(-1) << std::endl;\n"
" std::cout << log10f(-1) << std::endl;\n"
" std::cout << log10l(-1) << std::endl;\n"
" std::cout << log2(-1) << std::endl;\n"
" std::cout << log2f(-1) << std::endl;\n"
" std::cout << log2l(-1) << std::endl;\n"
" std::cout << log1p(-2) << std::endl;\n"
" std::cout << log1pf(-2) << std::endl;\n"
" std::cout << log1pl(-2) << std::endl;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Invalid log() argument nr 1. The value is -1 but the valid values are '4.94066e-324:'.\n"
"[test.cpp:4]: (error) Invalid logf() argument nr 1. The value is -1 but the valid values are '1.4013e-45:'.\n"
"[test.cpp:5]: (error) Invalid logl() argument nr 1. The value is -1 but the valid values are '4.94066e-324:'.\n"
"[test.cpp:6]: (error) Invalid log10() argument nr 1. The value is -1 but the valid values are '4.94066e-324:'.\n"
"[test.cpp:7]: (error) Invalid log10f() argument nr 1. The value is -1 but the valid values are '1.4013e-45:'.\n"
"[test.cpp:8]: (error) Invalid log10l() argument nr 1. The value is -1 but the valid values are '4.94066e-324:'.\n"
"[test.cpp:9]: (error) Invalid log2() argument nr 1. The value is -1 but the valid values are '4.94066e-324:'.\n"
"[test.cpp:10]: (error) Invalid log2f() argument nr 1. The value is -1 but the valid values are '1.4013e-45:'.\n"
"[test.cpp:11]: (error) Invalid log2l() argument nr 1. The value is -1 but the valid values are '4.94066e-324:'.\n"
"[test.cpp:3]: (warning) Passing value -1 to log() leads to implementation-defined result.\n"
"[test.cpp:4]: (warning) Passing value -1 to logf() leads to implementation-defined result.\n"
"[test.cpp:5]: (warning) Passing value -1 to logl() leads to implementation-defined result.\n"
"[test.cpp:6]: (warning) Passing value -1 to log10() leads to implementation-defined result.\n"
"[test.cpp:7]: (warning) Passing value -1 to log10f() leads to implementation-defined result.\n"
"[test.cpp:8]: (warning) Passing value -1 to log10l() leads to implementation-defined result.\n"
"[test.cpp:9]: (warning) Passing value -1 to log2() leads to implementation-defined result.\n"
"[test.cpp:10]: (warning) Passing value -1 to log2f() leads to implementation-defined result.\n"
"[test.cpp:11]: (warning) Passing value -1 to log2l() leads to implementation-defined result.\n"
"[test.cpp:12]: (warning) Passing value -2 to log1p() leads to implementation-defined result.\n"
"[test.cpp:13]: (warning) Passing value -2 to log1pf() leads to implementation-defined result.\n"
"[test.cpp:14]: (warning) Passing value -2 to log1pl() leads to implementation-defined result.\n", errout_str());
check("void foo()\n"
"{\n"
" std::cout << log(-1.0) << std::endl;\n"
" std::cout << logf(-1.0) << std::endl;\n"
" std::cout << logl(-1.0) << std::endl;\n"
" std::cout << log10(-1.0) << std::endl;\n"
" std::cout << log10f(-1.0) << std::endl;\n"
" std::cout << log10l(-1.0) << std::endl;\n"
" std::cout << log2(-1.0) << std::endl;\n"
" std::cout << log2f(-1.0) << std::endl;\n"
" std::cout << log2l(-1.0) << std::endl;\n"
" std::cout << log1p(-2.0) << std::endl;\n"
" std::cout << log1pf(-2.0) << std::endl;\n"
" std::cout << log1pl(-2.0) << std::endl;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Invalid log() argument nr 1. The value is -1 but the valid values are '4.94066e-324:'.\n"
"[test.cpp:4]: (error) Invalid logf() argument nr 1. The value is -1 but the valid values are '1.4013e-45:'.\n"
"[test.cpp:5]: (error) Invalid logl() argument nr 1. The value is -1 but the valid values are '4.94066e-324:'.\n"
"[test.cpp:6]: (error) Invalid log10() argument nr 1. The value is -1 but the valid values are '4.94066e-324:'.\n"
"[test.cpp:7]: (error) Invalid log10f() argument nr 1. The value is -1 but the valid values are '1.4013e-45:'.\n"
"[test.cpp:8]: (error) Invalid log10l() argument nr 1. The value is -1 but the valid values are '4.94066e-324:'.\n"
"[test.cpp:9]: (error) Invalid log2() argument nr 1. The value is -1 but the valid values are '4.94066e-324:'.\n"
"[test.cpp:10]: (error) Invalid log2f() argument nr 1. The value is -1 but the valid values are '1.4013e-45:'.\n"
"[test.cpp:11]: (error) Invalid log2l() argument nr 1. The value is -1 but the valid values are '4.94066e-324:'.\n"
"[test.cpp:3]: (warning) Passing value -1.0 to log() leads to implementation-defined result.\n"
"[test.cpp:4]: (warning) Passing value -1.0 to logf() leads to implementation-defined result.\n"
"[test.cpp:5]: (warning) Passing value -1.0 to logl() leads to implementation-defined result.\n"
"[test.cpp:6]: (warning) Passing value -1.0 to log10() leads to implementation-defined result.\n"
"[test.cpp:7]: (warning) Passing value -1.0 to log10f() leads to implementation-defined result.\n"
"[test.cpp:8]: (warning) Passing value -1.0 to log10l() leads to implementation-defined result.\n"
"[test.cpp:9]: (warning) Passing value -1.0 to log2() leads to implementation-defined result.\n"
"[test.cpp:10]: (warning) Passing value -1.0 to log2f() leads to implementation-defined result.\n"
"[test.cpp:11]: (warning) Passing value -1.0 to log2l() leads to implementation-defined result.\n"
"[test.cpp:12]: (warning) Passing value -2.0 to log1p() leads to implementation-defined result.\n"
"[test.cpp:13]: (warning) Passing value -2.0 to log1pf() leads to implementation-defined result.\n"
"[test.cpp:14]: (warning) Passing value -2.0 to log1pl() leads to implementation-defined result.\n", errout_str());
check("void foo()\n"
"{\n"
" std::cout << log(-0.1) << std::endl;\n"
" std::cout << logf(-0.1) << std::endl;\n"
" std::cout << logl(-0.1) << std::endl;\n"
" std::cout << log10(-0.1) << std::endl;\n"
" std::cout << log10f(-0.1) << std::endl;\n"
" std::cout << log10l(-0.1) << std::endl;\n"
" std::cout << log2(-0.1) << std::endl;\n"
" std::cout << log2f(-0.1) << std::endl;\n"
" std::cout << log2l(-0.1) << std::endl;\n"
" std::cout << log1p(-1.1) << std::endl;\n"
" std::cout << log1pf(-1.1) << std::endl;\n"
" std::cout << log1pl(-1.1) << std::endl;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Invalid log() argument nr 1. The value is -0.1 but the valid values are '4.94066e-324:'.\n"
"[test.cpp:4]: (error) Invalid logf() argument nr 1. The value is -0.1 but the valid values are '1.4013e-45:'.\n"
"[test.cpp:5]: (error) Invalid logl() argument nr 1. The value is -0.1 but the valid values are '4.94066e-324:'.\n"
"[test.cpp:6]: (error) Invalid log10() argument nr 1. The value is -0.1 but the valid values are '4.94066e-324:'.\n"
"[test.cpp:7]: (error) Invalid log10f() argument nr 1. The value is -0.1 but the valid values are '1.4013e-45:'.\n"
"[test.cpp:8]: (error) Invalid log10l() argument nr 1. The value is -0.1 but the valid values are '4.94066e-324:'.\n"
"[test.cpp:9]: (error) Invalid log2() argument nr 1. The value is -0.1 but the valid values are '4.94066e-324:'.\n"
"[test.cpp:10]: (error) Invalid log2f() argument nr 1. The value is -0.1 but the valid values are '1.4013e-45:'.\n"
"[test.cpp:11]: (error) Invalid log2l() argument nr 1. The value is -0.1 but the valid values are '4.94066e-324:'.\n"
"[test.cpp:3]: (warning) Passing value -0.1 to log() leads to implementation-defined result.\n"
"[test.cpp:4]: (warning) Passing value -0.1 to logf() leads to implementation-defined result.\n"
"[test.cpp:5]: (warning) Passing value -0.1 to logl() leads to implementation-defined result.\n"
"[test.cpp:6]: (warning) Passing value -0.1 to log10() leads to implementation-defined result.\n"
"[test.cpp:7]: (warning) Passing value -0.1 to log10f() leads to implementation-defined result.\n"
"[test.cpp:8]: (warning) Passing value -0.1 to log10l() leads to implementation-defined result.\n"
"[test.cpp:9]: (warning) Passing value -0.1 to log2() leads to implementation-defined result.\n"
"[test.cpp:10]: (warning) Passing value -0.1 to log2f() leads to implementation-defined result.\n"
"[test.cpp:11]: (warning) Passing value -0.1 to log2l() leads to implementation-defined result.\n"
"[test.cpp:12]: (warning) Passing value -1.1 to log1p() leads to implementation-defined result.\n"
"[test.cpp:13]: (warning) Passing value -1.1 to log1pf() leads to implementation-defined result.\n"
"[test.cpp:14]: (warning) Passing value -1.1 to log1pl() leads to implementation-defined result.\n", errout_str());
check("void foo()\n"
"{\n"
" std::cout << log(0) << std::endl;\n"
" std::cout << logf(0.) << std::endl;\n"
" std::cout << logl(0.0) << std::endl;\n"
" std::cout << log10(0.0) << std::endl;\n"
" std::cout << log10f(0) << std::endl;\n"
" std::cout << log10l(0.) << std::endl;\n"
" std::cout << log2(0.) << std::endl;\n"
" std::cout << log2f(0.0) << std::endl;\n"
" std::cout << log2l(0) << std::endl;\n"
" std::cout << log1p(-1.) << std::endl;\n"
" std::cout << log1pf(-1.0) << std::endl;\n"
" std::cout << log1pl(-1) << std::endl;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Invalid log() argument nr 1. The value is 0 but the valid values are '4.94066e-324:'.\n"
"[test.cpp:4]: (error) Invalid logf() argument nr 1. The value is 0 but the valid values are '1.4013e-45:'.\n"
"[test.cpp:5]: (error) Invalid logl() argument nr 1. The value is 0 but the valid values are '4.94066e-324:'.\n"
"[test.cpp:6]: (error) Invalid log10() argument nr 1. The value is 0 but the valid values are '4.94066e-324:'.\n"
"[test.cpp:7]: (error) Invalid log10f() argument nr 1. The value is 0 but the valid values are '1.4013e-45:'.\n"
"[test.cpp:8]: (error) Invalid log10l() argument nr 1. The value is 0 but the valid values are '4.94066e-324:'.\n"
"[test.cpp:9]: (error) Invalid log2() argument nr 1. The value is 0 but the valid values are '4.94066e-324:'.\n"
"[test.cpp:10]: (error) Invalid log2f() argument nr 1. The value is 0 but the valid values are '1.4013e-45:'.\n"
"[test.cpp:11]: (error) Invalid log2l() argument nr 1. The value is 0 but the valid values are '4.94066e-324:'.\n"
"[test.cpp:3]: (warning) Passing value 0 to log() leads to implementation-defined result.\n"
"[test.cpp:4]: (warning) Passing value 0. to logf() leads to implementation-defined result.\n"
"[test.cpp:5]: (warning) Passing value 0.0 to logl() leads to implementation-defined result.\n"
"[test.cpp:6]: (warning) Passing value 0.0 to log10() leads to implementation-defined result.\n"
"[test.cpp:7]: (warning) Passing value 0 to log10f() leads to implementation-defined result.\n"
"[test.cpp:8]: (warning) Passing value 0. to log10l() leads to implementation-defined result.\n"
"[test.cpp:9]: (warning) Passing value 0. to log2() leads to implementation-defined result.\n"
"[test.cpp:10]: (warning) Passing value 0.0 to log2f() leads to implementation-defined result.\n"
"[test.cpp:11]: (warning) Passing value 0 to log2l() leads to implementation-defined result.\n"
"[test.cpp:12]: (warning) Passing value -1. to log1p() leads to implementation-defined result.\n"
"[test.cpp:13]: (warning) Passing value -1.0 to log1pf() leads to implementation-defined result.\n"
"[test.cpp:14]: (warning) Passing value -1 to log1pl() leads to implementation-defined result.\n", errout_str());
check("void foo()\n"
"{\n"
" std::cout << log(1E-3) << std::endl;\n"
" std::cout << logf(1E-3) << std::endl;\n"
" std::cout << logl(1E-3) << std::endl;\n"
" std::cout << log10(1E-3) << std::endl;\n"
" std::cout << log10f(1E-3) << std::endl;\n"
" std::cout << log10l(1E-3) << std::endl;\n"
" std::cout << log2(1E-3) << std::endl;\n"
" std::cout << log2f(1E-3) << std::endl;\n"
" std::cout << log2l(1E-3) << std::endl;\n"
" std::cout << log1p(-1+1E-3) << std::endl;\n"
" std::cout << log1pf(-1+1E-3) << std::endl;\n"
" std::cout << log1pl(-1+1E-3) << std::endl;\n"
" std::cout << log(1.0E-3) << std::endl;\n"
" std::cout << logf(1.0E-3) << std::endl;\n"
" std::cout << logl(1.0E-3) << std::endl;\n"
" std::cout << log10(1.0E-3) << std::endl;\n"
" std::cout << log10f(1.0E-3) << std::endl;\n"
" std::cout << log10l(1.0E-3) << std::endl;\n"
" std::cout << log2(1.0E-3) << std::endl;\n"
" std::cout << log2f(1.0E-3) << std::endl;\n"
" std::cout << log2l(1.0E-3) << std::endl;\n"
" std::cout << log1p(-1+1.0E-3) << std::endl;\n"
" std::cout << log1pf(-1+1.0E-3) << std::endl;\n"
" std::cout << log1pl(-1+1.0E-3) << std::endl;\n"
" std::cout << log(1.0E+3) << std::endl;\n"
" std::cout << logf(1.0E+3) << std::endl;\n"
" std::cout << logl(1.0E+3) << std::endl;\n"
" std::cout << log10(1.0E+3) << std::endl;\n"
" std::cout << log10f(1.0E+3) << std::endl;\n"
" std::cout << log10l(1.0E+3) << std::endl;\n"
" std::cout << log2(1.0E+3) << std::endl;\n"
" std::cout << log2f(1.0E+3) << std::endl;\n"
" std::cout << log2l(1.0E+3) << std::endl;\n"
" std::cout << log1p(1.0E+3) << std::endl;\n"
" std::cout << log1pf(1.0E+3) << std::endl;\n"
" std::cout << log1pl(1.0E+3) << std::endl;\n"
" std::cout << log(2.0) << std::endl;\n"
" std::cout << logf(2.0) << std::endl;\n"
" std::cout << logf(2.0f) << std::endl;\n"
" std::cout << log10(2.0) << std::endl;\n"
" std::cout << log10f(2.0) << std::endl;\n"
" std::cout << log10f(2.0f) << std::endl;\n"
" std::cout << log2(2.0) << std::endl;\n"
" std::cout << log2f(2.0) << std::endl;\n"
" std::cout << log2f(2.0f) << std::endl;\n"
" std::cout << log1p(2.0) << std::endl;\n"
" std::cout << log1pf(2.0) << std::endl;\n"
" std::cout << log1pf(2.0f) << std::endl;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo()\n"
"{\n"
" std::string *log(0);\n"
"}");
ASSERT_EQUALS("", errout_str());
// #3473 - no warning if "log" is a variable
check("Fred::Fred() : log(0) { }");
ASSERT_EQUALS("", errout_str());
// #5748
check("void f() { foo.log(0); }");
ASSERT_EQUALS("", errout_str());
}
void mathfunctionCall_acos() {
// acos, acosf, acosl
check("void foo()\n"
"{\n"
" return acos(-1) \n"
" + acos(0.1) \n"
" + acos(0.0001) \n"
" + acos(0.01) \n"
" + acos(1.0E-1) \n"
" + acos(-1.0E-1) \n"
" + acos(+1.0E-1) \n"
" + acos(0.1E-1) \n"
" + acos(+0.1E-1) \n"
" + acos(-0.1E-1) \n"
" + acosf(-1) \n"
" + acosf(0.1) \n"
" + acosf(0.0001) \n"
" + acosf(0.01) \n"
" + acosf(1.0E-1) \n"
" + acosf(-1.0E-1) \n"
" + acosf(+1.0E-1) \n"
" + acosf(0.1E-1) \n"
" + acosf(+0.1E-1) \n"
" + acosf(-0.1E-1) \n"
" + acosl(-1) \n"
" + acosl(0.1) \n"
" + acosl(0.0001) \n"
" + acosl(0.01) \n"
" + acosl(1.0E-1) \n"
" + acosl(-1.0E-1) \n"
" + acosl(+1.0E-1) \n"
" + acosl(0.1E-1) \n"
" + acosl(+0.1E-1) \n"
" + acosl(-0.1E-1);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo()\n"
"{\n"
" std::cout << acos(1.1) << std::endl;\n"
" std::cout << acosf(1.1) << std::endl;\n"
" std::cout << acosl(1.1) << std::endl;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Invalid acos() argument nr 1. The value is 1.1 but the valid values are '-1.0:1.0'.\n"
"[test.cpp:4]: (error) Invalid acosf() argument nr 1. The value is 1.1 but the valid values are '-1.0:1.0'.\n"
"[test.cpp:5]: (error) Invalid acosl() argument nr 1. The value is 1.1 but the valid values are '-1.0:1.0'.\n", errout_str());
check("void foo()\n"
"{\n"
" std::cout << acos(-1.1) << std::endl;\n"
" std::cout << acosf(-1.1) << std::endl;\n"
" std::cout << acosl(-1.1) << std::endl;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Invalid acos() argument nr 1. The value is -1.1 but the valid values are '-1.0:1.0'.\n"
"[test.cpp:4]: (error) Invalid acosf() argument nr 1. The value is -1.1 but the valid values are '-1.0:1.0'.\n"
"[test.cpp:5]: (error) Invalid acosl() argument nr 1. The value is -1.1 but the valid values are '-1.0:1.0'.\n", errout_str());
}
void mathfunctionCall_asin() {
// asin, asinf, asinl
check("void foo()\n"
"{\n"
" return asin(1) \n"
" + asin(-1) \n"
" + asin(0.1) \n"
" + asin(0.0001) \n"
" + asin(0.01) \n"
" + asin(1.0E-1) \n"
" + asin(-1.0E-1) \n"
" + asin(+1.0E-1) \n"
" + asin(0.1E-1) \n"
" + asin(+0.1E-1) \n"
" + asin(-0.1E-1) \n"
" + asinf(1) \n"
" + asinf(-1) \n"
" + asinf(0.1) \n"
" + asinf(0.0001) \n"
" + asinf(0.01) \n"
" + asinf(1.0E-1) \n"
" + asinf(-1.0E-1) \n"
" + asinf(+1.0E-1) \n"
" + asinf(0.1E-1) \n"
" + asinf(+0.1E-1) \n"
" + asinf(-0.1E-1) \n"
" + asinl(1) \n"
" + asinl(-1) \n"
" + asinl(0.1) \n"
" + asinl(0.0001) \n"
" + asinl(0.01) \n"
" + asinl(1.0E-1) \n"
" + asinl(-1.0E-1) \n"
" + asinl(+1.0E-1) \n"
" + asinl(0.1E-1) \n"
" + asinl(+0.1E-1) \n"
" + asinl(-0.1E-1);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo()\n"
"{\n"
" std::cout << asin(1.1) << std::endl;\n"
" std::cout << asinf(1.1) << std::endl;\n"
" std::cout << asinl(1.1) << std::endl;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Invalid asin() argument nr 1. The value is 1.1 but the valid values are '-1.0:1.0'.\n"
"[test.cpp:4]: (error) Invalid asinf() argument nr 1. The value is 1.1 but the valid values are '-1.0:1.0'.\n"
"[test.cpp:5]: (error) Invalid asinl() argument nr 1. The value is 1.1 but the valid values are '-1.0:1.0'.\n", errout_str());
check("void foo()\n"
"{\n"
" std::cout << asin(-1.1) << std::endl;\n"
" std::cout << asinf(-1.1) << std::endl;\n"
" std::cout << asinl(-1.1) << std::endl;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Invalid asin() argument nr 1. The value is -1.1 but the valid values are '-1.0:1.0'.\n"
"[test.cpp:4]: (error) Invalid asinf() argument nr 1. The value is -1.1 but the valid values are '-1.0:1.0'.\n"
"[test.cpp:5]: (error) Invalid asinl() argument nr 1. The value is -1.1 but the valid values are '-1.0:1.0'.\n", errout_str());
}
void mathfunctionCall_pow() {
// pow, powf, powl
check("void foo()\n"
"{\n"
" std::cout << pow(0,-10) << std::endl;\n"
" std::cout << powf(0,-10) << std::endl;\n"
" std::cout << powl(0,-10) << std::endl;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Passing values 0 and -10 to pow() leads to implementation-defined result.\n"
"[test.cpp:4]: (warning) Passing values 0 and -10 to powf() leads to implementation-defined result.\n"
"[test.cpp:5]: (warning) Passing values 0 and -10 to powl() leads to implementation-defined result.\n", errout_str());
check("void foo()\n"
"{\n"
" std::cout << pow(0,10) << std::endl;\n"
" std::cout << powf(0,10) << std::endl;\n"
" std::cout << powl(0,10) << std::endl;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void mathfunctionCall_atan2() {
// atan2
check("void foo()\n"
"{\n"
" std::cout << atan2(1,1) ;\n"
" std::cout << atan2(-1,-1) ;\n"
" std::cout << atan2(0.1,1) ;\n"
" std::cout << atan2(0.0001,100) ;\n"
" std::cout << atan2(0.0,1e-1) ;\n"
" std::cout << atan2(1.0E-1,-3) ;\n"
" std::cout << atan2(-1.0E-1,+2) ;\n"
" std::cout << atan2(+1.0E-1,0) ;\n"
" std::cout << atan2(0.1E-1,3) ;\n"
" std::cout << atan2(+0.1E-1,1) ;\n"
" std::cout << atan2(-0.1E-1,8) ;\n"
" std::cout << atan2f(1,1) ;\n"
" std::cout << atan2f(-1,-1) ;\n"
" std::cout << atan2f(0.1,1) ;\n"
" std::cout << atan2f(0.0001,100) ;\n"
" std::cout << atan2f(0.0,1e-1) ;\n"
" std::cout << atan2f(1.0E-1,-3) ;\n"
" std::cout << atan2f(-1.0E-1,+2) ;\n"
" std::cout << atan2f(+1.0E-1,0) ;\n"
" std::cout << atan2f(0.1E-1,3) ;\n"
" std::cout << atan2f(+0.1E-1,1) ;\n"
" std::cout << atan2f(-0.1E-1,8) ;\n"
" std::cout << atan2l(1,1) ;\n"
" std::cout << atan2l(-1,-1) ;\n"
" std::cout << atan2l(0.1,1) ;\n"
" std::cout << atan2l(0.0001,100) ;\n"
" std::cout << atan2l(0.0,1e-1) ;\n"
" std::cout << atan2l(1.0E-1,-3) ;\n"
" std::cout << atan2l(-1.0E-1,+2) ;\n"
" std::cout << atan2l(+1.0E-1,0) ;\n"
" std::cout << atan2l(0.1E-1,3) ;\n"
" std::cout << atan2l(+0.1E-1,1) ;\n"
" std::cout << atan2l(-0.1E-1,8) ;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo()\n"
"{\n"
" std::cout << atan2(0,0) << std::endl;\n"
" std::cout << atan2f(0,0) << std::endl;\n"
" std::cout << atan2l(0,0) << std::endl;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Passing values 0 and 0 to atan2() leads to implementation-defined result.\n"
"[test.cpp:4]: (warning) Passing values 0 and 0 to atan2f() leads to implementation-defined result.\n"
"[test.cpp:5]: (warning) Passing values 0 and 0 to atan2l() leads to implementation-defined result.\n", errout_str());
}
void mathfunctionCall_fmod() {
// fmod, fmodl, fmodf
check("void foo()\n"
"{\n"
" std::cout << fmod(1.0,0) << std::endl;\n"
" std::cout << fmodf(1.0,0) << std::endl;\n"
" std::cout << fmodl(1.0,0) << std::endl;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Invalid fmod() argument nr 2. The value is 0 but the valid values are '!0.0'.\n"
"[test.cpp:4]: (error) Invalid fmodf() argument nr 2. The value is 0 but the valid values are '!0.0'.\n"
"[test.cpp:5]: (error) Invalid fmodl() argument nr 2. The value is 0 but the valid values are '!0.0'.\n"
"[test.cpp:3]: (warning) Passing values 1.0 and 0 to fmod() leads to implementation-defined result.\n"
"[test.cpp:4]: (warning) Passing values 1.0 and 0 to fmodf() leads to implementation-defined result.\n"
"[test.cpp:5]: (warning) Passing values 1.0 and 0 to fmodl() leads to implementation-defined result.\n", errout_str());
check("void foo()\n"
"{\n"
" std::cout << fmod(1.0,1) << std::endl;\n"
" std::cout << fmodf(1.0,1) << std::endl;\n"
" std::cout << fmodl(1.0,1) << std::endl;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void mathfunctionCall_precision() {
check("void foo() {\n"
" print(exp(x) - 1);\n"
" print(log(1 + x));\n"
" print(1 - erf(x));\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Expression 'exp(x) - 1' can be replaced by 'expm1(x)' to avoid loss of precision.\n"
"[test.cpp:3]: (style) Expression 'log(1 + x)' can be replaced by 'log1p(x)' to avoid loss of precision.\n"
"[test.cpp:4]: (style) Expression '1 - erf(x)' can be replaced by 'erfc(x)' to avoid loss of precision.\n", errout_str());
check("void foo() {\n"
" print(exp(x) - 1.0);\n"
" print(log(1.0 + x));\n"
" print(1.0 - erf(x));\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Expression 'exp(x) - 1' can be replaced by 'expm1(x)' to avoid loss of precision.\n"
"[test.cpp:3]: (style) Expression 'log(1 + x)' can be replaced by 'log1p(x)' to avoid loss of precision.\n"
"[test.cpp:4]: (style) Expression '1 - erf(x)' can be replaced by 'erfc(x)' to avoid loss of precision.\n", errout_str());
check("void foo() {\n"
" print(exp(3 + x*f(a)) - 1);\n"
" print(log(x*4 + 1));\n"
" print(1 - erf(34*x + f(x) - c));\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Expression 'exp(x) - 1' can be replaced by 'expm1(x)' to avoid loss of precision.\n"
"[test.cpp:3]: (style) Expression 'log(1 + x)' can be replaced by 'log1p(x)' to avoid loss of precision.\n"
"[test.cpp:4]: (style) Expression '1 - erf(x)' can be replaced by 'erfc(x)' to avoid loss of precision.\n", errout_str());
check("void foo() {\n"
" print(2*exp(x) - 1);\n"
" print(1 - erf(x)/2.0);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void checkIgnoredReturnValue() {
constexpr char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def version=\"2\">\n"
" <function name=\"mystrcmp,foo::mystrcmp\">\n"
" <use-retval/>\n"
" <arg nr=\"1\"/>\n"
" <arg nr=\"2\"/>\n"
" </function>\n"
"</def>";
const Settings settings2 = settingsBuilder().severity(Severity::warning).libraryxml(xmldata, sizeof(xmldata)).build();
check("void foo() {\n"
" mystrcmp(a, b);\n"
"}", true, &settings2);
ASSERT_EQUALS("[test.cpp:2]: (warning) Return value of function mystrcmp() is not used.\n", errout_str());
check("void foo() {\n"
" foo::mystrcmp(a, b);\n"
"}", true, &settings2);
ASSERT_EQUALS("[test.cpp:2]: (warning) Return value of function foo::mystrcmp() is not used.\n", errout_str());
check("void f() {\n"
" foo x;\n"
" x.mystrcmp(a, b);\n"
"}", true, &settings2);
ASSERT_EQUALS("[test.cpp:3]: (warning) Return value of function x.mystrcmp() is not used.\n", errout_str());
check("bool mystrcmp(char* a, char* b);\n" // cppcheck sees a custom strcmp definition, but it returns a value. Assume it is the one specified in the library.
"void foo() {\n"
" mystrcmp(a, b);\n"
"}", true, &settings2);
ASSERT_EQUALS("[test.cpp:3]: (warning) Return value of function mystrcmp() is not used.\n", errout_str());
check("void mystrcmp(char* a, char* b);\n" // cppcheck sees a custom strcmp definition which returns void!
"void foo() {\n"
" mystrcmp(a, b);\n"
"}", true, &settings2);
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" class mystrcmp { mystrcmp() {} };\n" // strcmp is a constructor definition here
"}", true, &settings2);
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" return mystrcmp(a, b);\n"
"}", true, &settings2);
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" return foo::mystrcmp(a, b);\n"
"}", true, &settings2);
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" if(mystrcmp(a, b));\n"
"}", true, &settings2);
ASSERT_EQUALS("", errout_str());
check("void foo() {\n"
" bool b = mystrcmp(a, b);\n"
"}", true, &settings2);
ASSERT_EQUALS("", errout_str());
// #6194
check("void foo() {\n"
" MyStrCmp mystrcmp(x, y);\n"
"}", true, &settings2);
ASSERT_EQUALS("", errout_str());
// #6197
check("void foo() {\n"
" abc::def.mystrcmp(a,b);\n"
"}", true, &settings2);
ASSERT_EQUALS("", errout_str());
// #6233
check("int main() {\n"
" auto lambda = [](double value) {\n"
" double rounded = floor(value + 0.5);\n"
" printf(\"Rounded value = %f\\n\", rounded);\n"
" };\n"
" lambda(13.3);\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #6669
check("void foo(size_t size) {\n"
" void * res{malloc(size)};\n"
"}");
ASSERT_EQUALS("", errout_str());
// #7447
check("void foo() {\n"
" int x{mystrcmp(a,b)};\n"
"}", true, &settings2);
ASSERT_EQUALS("", errout_str());
// #7905
check("void foo() {\n"
" int x({mystrcmp(a,b)});\n"
"}", true, &settings2);
ASSERT_EQUALS("", errout_str());
check("void foo() {\n" // don't crash
" DEBUG(123)(mystrcmp(a,b))(fd);\n"
"}", false, &settings2);
check("struct teststruct {\n"
" int testfunc1() __attribute__ ((warn_unused_result)) { return 1; }\n"
" [[nodiscard]] int testfunc2() { return 1; }\n"
" void foo() { testfunc1(); testfunc2(); }\n"
"};\n"
"int main() {\n"
" teststruct TestStruct1;\n"
" TestStruct1.testfunc1();\n"
" TestStruct1.testfunc2();\n"
" return 0;\n"
"}", true, &settings2);
ASSERT_EQUALS("[test.cpp:4]: (warning) Return value of function testfunc1() is not used.\n"
"[test.cpp:4]: (warning) Return value of function testfunc2() is not used.\n"
"[test.cpp:8]: (warning) Return value of function TestStruct1.testfunc1() is not used.\n"
"[test.cpp:9]: (warning) Return value of function TestStruct1.testfunc2() is not used.\n", errout_str());
// #9006
check("template <typename... a> uint8_t b(std::tuple<uint8_t> d) {\n"
" std::tuple<a...> c{std::move(d)};\n"
" return std::get<0>(c);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct A { int x; };\n"
"template <class... Ts>\n"
"A f(int x, Ts... xs) {\n"
" return {std::move(x), static_cast<int>(xs)...};\n"
"}\n"
"A g() { return f(1); }");
ASSERT_EQUALS("", errout_str());
// #8412 - unused operator result
check("void foo() {\n"
" !mystrcmp(a, b);\n"
"}", true, &settings2);
ASSERT_EQUALS("[test.cpp:2]: (warning) Return value of function mystrcmp() is not used.\n", errout_str());
check("void f(std::vector<int*> v) {\n"
" delete *v.begin();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("int __attribute__((pure)) p_foo(int);\n" // #12697
"int __attribute__((const)) c_foo(int);\n"
"void f() {\n"
" p_foo(0);\n"
" c_foo(0);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (warning) Return value of function p_foo() is not used.\n"
"[test.cpp:5]: (warning) Return value of function c_foo() is not used.\n",
errout_str());
}
void checkIgnoredErrorCode() {
const char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def version=\"2\">\n"
" <function name=\"mystrcmp\">\n"
" <use-retval type=\"error-code\"/>\n"
" <arg nr=\"1\"/>\n"
" <arg nr=\"2\"/>\n"
" </function>\n"
"</def>";
const Settings settings2 = settingsBuilder().severity(Severity::style).libraryxml(xmldata, sizeof(xmldata)).build();
check("void foo() {\n"
" mystrcmp(a, b);\n"
"}", true, &settings2);
ASSERT_EQUALS("[test.cpp:2]: (style) Error code from the return value of function mystrcmp() is not used.\n", errout_str());
}
void memsetZeroBytes() {
check("void f() {\n"
" memset(p, 10, 0x0);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) memset() called to fill 0 bytes.\n", errout_str());
check("void f() {\n"
" memset(p, sizeof(p), 0);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) memset() called to fill 0 bytes.\n", errout_str());
check("void f() {\n"
" memset(p, sizeof(p), i);\n"
"}");
ASSERT_EQUALS("", errout_str());
// #6269 false positives in case of overloaded standard library functions
check("class c {\n"
" void memset( int i );\n"
" void f( void ) {\n"
" memset( 0 );\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
// #7285
check("void f() {\n"
" memset(&tm, sizeof(tm), 0);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) memset() called to fill 0 bytes.\n", errout_str());
}
void memsetInvalid2ndParam() {
check("void f() {\n"
" int* is = new int[10];\n"
" memset(is, 1.0f, 40);\n"
" int* is2 = new int[10];\n"
" memset(is2, 0.1f, 40);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (portability) The 2nd memset() argument '1.0f' is a float, its representation is implementation defined.\n"
"[test.cpp:5]: (portability) The 2nd memset() argument '0.1f' is a float, its representation is implementation defined.\n", errout_str());
check("void f() {\n"
" int* is = new int[10];\n"
" float g = computeG();\n"
" memset(is, g, 40);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (portability) The 2nd memset() argument 'g' is a float, its representation is implementation defined.\n", errout_str());
check("void f() {\n"
" int* is = new int[10];\n"
" memset(is, 0.0f, 40);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n" // FP
" float x = 2.3f;\n"
" memset(a, (x?64:0), 40);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" short ss[] = {1, 2};\n"
" memset(ss, 256, 4);\n"
" short ss2[2];\n"
" memset(ss2, -129, 4);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) The 2nd memset() argument '256' doesn't fit into an 'unsigned char'.\n"
"[test.cpp:5]: (warning) The 2nd memset() argument '-129' doesn't fit into an 'unsigned char'.\n", errout_str());
check("void f() {\n"
" int is[10];\n"
" memset(is, 0xEE, 40);\n"
" unsigned char* cs = malloc(256);\n"
" memset(cs, -1, 256);\n"
" short* ss[30];\n"
" memset(ss, -128, 60);\n"
" char cs2[30];\n"
" memset(cs2, 255, 30);\n"
" char cs3[30];\n"
" memset(cs3, 0, 30);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int is[10];\n"
" const int i = g();\n"
" memset(is, 1.0f + i, 40);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (portability) The 2nd memset() argument '1.0f+i' is a float, its representation is implementation defined.\n", errout_str());
}
void checkMissingReturn1() {
check("int f() {}");
ASSERT_EQUALS("[test.cpp:1]: (error) Found an exit path from function with non-void return type that has missing return statement\n", errout_str());
{
const char code[] = "int main(void) {}";
{
const Settings s = settingsBuilder().c(Standards::C89).build();
check(code, false, &s); // c code (c89)
ASSERT_EQUALS("[test.c:1]: (error) Found an exit path from function with non-void return type that has missing return statement\n", errout_str());
}
{
const Settings s = settingsBuilder().c(Standards::C99).build();
check(code, false, &s); // c code (c99)
ASSERT_EQUALS("", errout_str());
check(code, true, &s); // c++ code
ASSERT_EQUALS("", errout_str());
}
}
check("F(A,B) { x=1; }");
ASSERT_EQUALS("", errout_str());
check("auto foo4() -> void {}");
ASSERT_EQUALS("", errout_str());
check("void STDCALL foo() {}");
ASSERT_EQUALS("", errout_str());
check("void operator=(int y) { x=y; }");
ASSERT_EQUALS("", errout_str());
check("int f() {\n"
"back:\n"
" return 0;\n"
"ng:\n"
" x=y;\n"
" goto back;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// unreachable code..
check("int foo(int x) {\n"
" return 1;\n"
" (void)x;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int foo(int x) {\n"
" if (x) goto out;\n"
" return 1;\n"
"out:\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Found an exit path from function with non-void return type that has missing return statement\n", errout_str());
// switch
check("int f() {\n"
" switch (x) {\n"
" case 1: break;\n" // <- error
" case 2: return 1;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Found an exit path from function with non-void return type that has missing return statement\n", errout_str());
check("int f() {\n"
" switch (x) {\n"
" case 1: return 2; break;\n"
" default: return 1;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool test(unsigned char v1, int v2) {\n"
" switch (v1) {\n"
" case 0:\n"
" switch (v2) {\n"
" case 48000:\n"
" break;\n"
" }\n"
" return false;\n"
" default:\n"
" return true;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// if/else
check("int f(int x) {\n"
" if (x) {\n"
" return 1;\n"
" }\n" // <- error (missing else)
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Found an exit path from function with non-void return type that has missing return statement\n", errout_str());
check("int f(int x) {\n"
" if (x) {\n"
" ;\n" // <- error
" } else {\n"
" return 1;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Found an exit path from function with non-void return type that has missing return statement\n", errout_str());
check("int f() {\n"
" if (!0) {\n"
" return 1;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f() {\n"
" if (!0) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Found an exit path from function with non-void return type that has missing return statement\n", errout_str());
// loop
check("int f(int x) {\n"
" while (1) {\n"
" dostuff();\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// return {..}
check("std::pair<int, int> typeDecl(int tok) {\n"
" if (!tok)\n"
" return {};\n"
" else\n"
" return {1, 2};\n"
"}");
ASSERT_EQUALS("", errout_str());
// noreturn function
check("int f(int x) { exit(0); }");
ASSERT_EQUALS("", errout_str());
check("int f(int x) { assert(0); }");
ASSERT_EQUALS("", errout_str());
check("int f(int x) { if (x) return 1; else return bar({1}, {}); }");
ASSERT_EQUALS("", errout_str());
check("auto f() -> void {}"); // #10342
ASSERT_EQUALS("", errout_str());
check("struct S1 {\n" // #7433
" S1& operator=(const S1& r) { if (this != &r) { i = r.i; } }\n"
" int i;\n"
"};\n"
"struct S2 {\n"
" S2& operator=(const S2& s) { if (this != &s) { j = s.j; } return *this; }\n"
" int j;\n"
"};\n"
"struct S3 {\n"
" S3& operator=(const S3& t) { if (this != &t) { k = t.k; return *this; } }\n"
" int k;\n"
"};\n");
ASSERT_EQUALS("[test.cpp:2]: (error) Found an exit path from function with non-void return type that has missing return statement\n"
"[test.cpp:10]: (error) Found an exit path from function with non-void return type that has missing return statement\n",
errout_str());
// #11171
check("std::enable_if_t<sizeof(uint64_t) == 8> f() {}");
ASSERT_EQUALS("", errout_str());
check("std::enable_if_t<sizeof(uint64_t) == 8, int> f() {}");
ASSERT_EQUALS(
"[test.cpp:1]: (error) Found an exit path from function with non-void return type that has missing return statement\n",
errout_str());
check("template<class T> std::enable_if_t<std::is_same<T, int>{}, int> f(T) {}");
ASSERT_EQUALS(
"[test.cpp:1]: (error) Found an exit path from function with non-void return type that has missing return statement\n",
errout_str());
check("template<class T> std::enable_if_t<std::is_same<T, int>{}> f(T) {}");
ASSERT_EQUALS("", errout_str());
check("typename std::enable_if<sizeof(uint64_t) == 8>::type f() {}");
ASSERT_EQUALS("", errout_str());
check("typename std::enable_if<sizeof(uint64_t) == 8, int>::type f() {}");
ASSERT_EQUALS(
"[test.cpp:1]: (error) Found an exit path from function with non-void return type that has missing return statement\n",
errout_str());
check("template<class T> typename std::enable_if<std::is_same<T, int>{}, int>::type f(T) {}");
ASSERT_EQUALS(
"[test.cpp:1]: (error) Found an exit path from function with non-void return type that has missing return statement\n",
errout_str());
check("template<class T> typename std::enable_if<std::is_same<T, int>{}>::type f(T) {}");
ASSERT_EQUALS("", errout_str());
check("struct S {\n"
" [[noreturn]] void f();\n"
" int g() { this->f(); }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
check("struct S { [[noreturn]] void f(); };\n"
"int g(S& s) { s.f(); }\n");
ASSERT_EQUALS("", errout_str());
}
void checkMissingReturn2() { // #11798
check("int f(bool const a) {\n"
" switch (a) {\n"
" case true:\n"
" return 1;\n"
" case false:\n"
" return 2;\n"
" }\n"
"}\n"
"int main(int argc, char* argv[])\n"
"{\n"
" auto const b= f(true);\n"
" auto const c= f(false);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void checkMissingReturn3() {
check("enum Enum {\n"
" A,\n"
" B,\n"
" C,\n"
"};\n"
"int f(Enum e) {\n"
" switch (e) {\n"
" case A:\n"
" return 1;\n"
" case B:\n"
" return 2;\n"
" case C:\n"
" return 2;\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void checkMissingReturn4() {
check("enum Enum {\n"
" A,\n"
" B,\n"
" C,\n"
"};\n"
"int f(Enum e) {\n"
" switch (e) {\n"
" case A:\n"
" return 1;\n"
" case B:\n"
" return 2;\n"
" }\n"
"}\n");
ASSERT_EQUALS("[test.cpp:7]: (error) Found an exit path from function with non-void return type that has missing return statement\n", errout_str());
}
void checkMissingReturn5() {
check("enum Enum {\n"
" A,\n"
" B,\n"
" C,\n"
"};\n"
"int f(Enum e, bool b) {\n"
" switch (e) {\n"
" case A:\n"
" return 1;\n"
" case B:\n"
" return 2;\n"
" case C:\n"
" switch (b) {\n"
" case true:\n"
" return 3;\n"
" case false:\n"
" return 4;\n"
" }\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void checkMissingReturn6() {// #13180
check("int foo(void)\n"
"{\n"
" i = readData();\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Found an exit path from function with non-void return type that has missing return statement\n", errout_str());
}
// NRVO check
void returnLocalStdMove1() {
check("struct A{}; A f() { A var; return std::move(var); }");
ASSERT_EQUALS("[test.cpp:1]: (performance) Using std::move for returning object by-value from function will affect copy elision optimization."
" More: https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rf-return-move-local\n", errout_str());
}
// RVO, C++03 ctor style
void returnLocalStdMove2() {
check("struct A{}; A f() { return std::move( A() ); }");
ASSERT_EQUALS("[test.cpp:1]: (performance) Using std::move for returning object by-value from function will affect copy elision optimization."
" More: https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rf-return-move-local\n", errout_str());
}
// RVO, new ctor style
void returnLocalStdMove3() {
check("struct A{}; A f() { return std::move(A{}); }");
ASSERT_EQUALS("[test.cpp:1]: (performance) Using std::move for returning object by-value from function will affect copy elision optimization."
" More: https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rf-return-move-local\n", errout_str());
}
// Function argument
void returnLocalStdMove4() {
check("struct A{}; A f(A a) { return std::move(A{}); }");
ASSERT_EQUALS("[test.cpp:1]: (performance) Using std::move for returning object by-value from function will affect copy elision optimization."
" More: https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rf-return-move-local\n", errout_str());
}
void returnLocalStdMove5() {
check("struct A{} a; A f1() { return std::move(a); }\n"
"A f2() { volatile A var; return std::move(var); }");
ASSERT_EQUALS("", errout_str());
check("struct S { std::string msg{ \"abc\" }; };\n"
"std::unique_ptr<S> get(std::vector<std::unique_ptr<S>>& v) {\n"
" return std::move(v.front());\n"
"}\n"
"int main() {\n"
" std::vector<std::unique_ptr<S>> v;\n"
" v.emplace_back(std::make_unique<S>());\n"
" auto p = get(v);\n"
" std::cout << p->msg;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("std::string&& f() {\n" // #11881
" std::string s;\n"
" return std::move(s);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void negativeMemoryAllocationSizeError() { // #389
check("void f() {\n"
" int *a;\n"
" a = malloc( -10 );\n"
" free(a);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Invalid malloc() argument nr 1. The value is -10 but the valid values are '0:'.\n", errout_str());
check("void f() {\n"
" int *a;\n"
" a = alloca( -10 );\n"
" free(a);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Obsolete function 'alloca' called.\n"
"[test.cpp:3]: (error) Invalid alloca() argument nr 1. The value is -10 but the valid values are '0:'.\n", errout_str());
}
void checkLibraryMatchFunctions() {
/*const*/ Settings s = settingsBuilder(settings).checkLibrary().debugwarnings().build();
s.daca = true;
check("void f() {\n"
" lib_func();"
"}", true, &s);
ASSERT_EQUALS("[test.cpp:2]: (information) --check-library: There is no matching configuration for function lib_func()\n", errout_str());
check("void f(void* v) {\n"
" lib_func(v);"
"}", true, &s);
ASSERT_EQUALS("[test.cpp:2]: (information) --check-library: There is no matching configuration for function lib_func()\n", errout_str());
// #10105
check("class TestFixture {\n"
"protected:\n"
" bool prepareTest(const char testname[]);\n"
"};\n"
"\n"
"class TestMemleak : private TestFixture {\n"
" void run() {\n"
" do { prepareTest(\"testFunctionReturnType\"); } while (false);\n"
" }\n"
"\n"
" void testFunctionReturnType() {\n"
" }\n"
"};", true, &s);
ASSERT_EQUALS("", errout_str());
// #11183
check("#include <string>\n"
"\n"
"extern void cb(const std::string&);\n"
"\n"
"void f() {\n"
" cb(std::string(\"\"));\n"
"}", true, &s);
TODO_ASSERT_EQUALS("", "[test.cpp:6]: (information) --check-library: There is no matching configuration for function cb()\n", errout_str());
// #7375
check("void f() {\n"
" struct S { int i; char c; };\n"
" size_t s = sizeof(S);\n"
" static_assert(s == 9);\n"
"}\n", true, &s);
ASSERT_EQUALS("", errout_str());
check("void f(char) {}\n"
"void g() {\n"
" f(int8_t(1));\n"
"}\n", true, &s);
ASSERT_EQUALS("", errout_str());
check("void f(std::uint64_t& u) {\n"
" u = std::uint32_t(u) * std::uint64_t(100);\n"
"}\n", true, &s);
ASSERT_EQUALS("", errout_str());
check("void f() { throw(1); }\n", true, &s); // #8958
ASSERT_EQUALS("", errout_str());
check("using namespace std;\n"
"void f() { throw range_error(\"abc\"); }\n", true, &s);
ASSERT_EQUALS("", errout_str());
check("class C {\n" // #9002
"public:\n"
" static int f() { return 1; }\n"
"};\n"
"void g() { C::f(); }\n", true, &s);
ASSERT_EQUALS("", errout_str());
check("void f(const std::vector<std::string>& v) {\n" // #11223
" for (const auto& s : v)\n"
" s.find(\"\");\n"
"}\n", true, &s);
ASSERT_EQUALS("[test.cpp:3]: (warning) Return value of function s.find() is not used.\n", errout_str());
check("void f() {\n"
" auto* p = new std::vector<int>(5);\n"
" p->push_back(1);\n"
" auto* q = new std::vector<int>{ 5, 7 };\n"
" q->push_back(1);\n"
" auto* r = new std::vector<int>;\n"
" r->push_back(1);\n"
"}\n", true, &s);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" auto p = std::make_shared<std::vector<int>>();\n"
" p->push_back(1);\n"
"}\n", true, &s);
ASSERT_EQUALS("", errout_str());
check("void f(std::vector<std::vector<int>>& v) {\n"
" auto it = v.begin();\n"
" it->push_back(1);\n"
"}\n", true, &s);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" auto v = std::vector<int>{};\n"
" v.push_back(1);\n"
" auto w = std::vector<int>{ 1, 2, 3 };\n"
" w.push_back(1);\n"
" auto x = std::vector<int>(1);\n"
" x.push_back(1);\n"
"}\n", true, &s);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" auto p(std::make_shared<std::vector<int>>());\n"
" p->push_back(1);\n"
" auto q{ std::make_shared<std::vector<int>>{} };\n"
" q->push_back(1);\n"
"}\n", true, &s);
TODO_ASSERT_EQUALS("",
"[test.cpp:2]: (debug) auto token with no type.\n"
"[test.cpp:4]: (debug) auto token with no type.\n"
"[test.cpp:3]: (information) --check-library: There is no matching configuration for function auto::push_back()\n"
"[test.cpp:5]: (information) --check-library: There is no matching configuration for function auto::push_back()\n",
errout_str());
check("struct F { void g(int); };\n"
"void f(std::list<F>& l) {\n"
" std::list<F>::iterator it;\n"
" for (it = l.begin(); it != l.end(); ++it)\n"
" it->g(0);\n"
"}\n", true, &s);
ASSERT_EQUALS("", filter_valueflow(errout_str()));
check("auto f() {\n"
" return std::runtime_error(\"abc\");\n"
"}\n", true, &s);
TODO_ASSERT_EQUALS("",
"[test.cpp:1]: (debug) auto token with no type.\n",
errout_str());
check("struct S {\n" // #11543
" S() {}\n"
" std::vector<std::shared_ptr<S>> v;\n"
" void f(int i) const;\n"
"};\n"
"void S::f(int i) const {\n"
" for (const std::shared_ptr<S>& c : v)\n"
" c->f(i);\n"
"}\n", true, &s);
ASSERT_EQUALS("", errout_str());
check("namespace N {\n"
" struct S { static const std::set<std::string> s; };\n"
"}\n"
"void f() {\n"
" const auto& t = N::S::s;\n"
" if (t.find(\"abc\") != t.end()) {}\n"
"}\n", true, &s);
ASSERT_EQUALS("", filter_valueflow(errout_str()));
check("void f(std::vector<std::unordered_map<int, std::unordered_set<int>>>& v, int i, int j) {\n"
" auto& s = v[i][j];\n"
" s.insert(0);\n"
"}\n", true, &s);
ASSERT_EQUALS("", errout_str());
check("int f(const std::vector<std::string>& v, int i, char c) {\n"
" const auto& s = v[i];\n"
" return s.find(c);\n"
"}\n", true, &s);
ASSERT_EQUALS("", errout_str());
check("void f() {\n" // #11604
" int (*g)() = nullptr;\n"
"}\n", true, &s);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" INT (*g)() = nullptr;\n"
"}\n", true, &s);
ASSERT_EQUALS("", errout_str());
check("struct T;\n"
"std::shared_ptr<T> get();\n"
"void f(int i) {\n"
" auto p = get();\n"
" p->h(i);\n"
" p.reset(nullptr);\n"
"}\n", true, &s);
ASSERT_EQUALS("[test.cpp:5]: (information) --check-library: There is no matching configuration for function T::h()\n",
errout_str());
check("struct S : std::vector<int> {\n"
" void f(int i) { push_back(i); }\n"
"};\n", true, &s);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" auto g = []() -> std::string { return \"abc\"; };\n"
" auto s = g();\n"
" if (s.at(0)) {}\n"
" auto h{ []() -> std::string { return \"xyz\"; } };\n"
" auto t = h();\n"
" if (t.at(0)) {}\n"
"};\n", true, &s);
ASSERT_EQUALS("", filter_valueflow(errout_str()));
check("::std::string f(const char* c) {\n" // #12365
" return ::std::string(c);\n"
"}\n", true, &s);
ASSERT_EQUALS("", errout_str());
check("template <typename T>\n"
"struct S : public std::vector<T> {\n"
" void resize(size_t n) { std::vector<T>::resize(n); }\n"
"};\n", true, &s);
ASSERT_EQUALS("", errout_str());
check("struct P {\n" // #13105
" bool g(int i) const;\n"
" std::shared_ptr<std::map<int, int>> m;\n"
"};\n"
"bool P::g(int i) const {\n"
" auto it = m->find(i);\n"
" const bool b = it != m->end();\n"
" return b;\n"
"}\n", true, &s);
TODO_ASSERT_EQUALS("", "[test.cpp:6]: (debug) auto token with no type.\n", errout_str());
}
void checkUseStandardLibrary1() {
check("void f(void* dest, void const* src, const size_t count) {\n"
" size_t i;\n"
" for (i = 0; count > i; ++i)\n"
" (reinterpret_cast<uint8_t*>(dest))[i] = (reinterpret_cast<const uint8_t*>(src))[i];\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (style) Consider using std::memcpy instead of loop.\n", errout_str());
}
void checkUseStandardLibrary2() {
check("void f(void* dest, void const* src, const size_t count) {\n"
" for (size_t i = 0; i < count; i++) {\n"
" (reinterpret_cast<uint8_t*>(dest))[i] = (reinterpret_cast<const uint8_t*>(src))[i];\n"
"}}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) Consider using std::memcpy instead of loop.\n", errout_str());
}
void checkUseStandardLibrary3() {
check("void f(void* dst, const void* src, const size_t count) {\n"
" size_t i;\n"
" for (i = 0; count > i; i++)\n"
" ((char*)dst)[i] = ((const char*)src)[i];\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (style) Consider using std::memcpy instead of loop.\n", errout_str());
}
void checkUseStandardLibrary4() {
check("void f(void* dst, void* src, const size_t size) {\n"
" for (size_t i = 0; i < size; i += 1) {\n"
" ((int8_t*)dst)[i] = ((int8_t*)src)[i];\n"
"}}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) Consider using std::memcpy instead of loop.\n", errout_str());
}
// different indexes
void checkUseStandardLibrary5() {
check("void f(void* dst, void* src, const size_t size, const size_t from_idx) {\n"
" for (size_t i = 0; i < size; ++i) {\n"
" ((int8_t*)dst)[i] = ((int8_t*)src)[from_idx];\n"
"}}\n");
ASSERT_EQUALS("", errout_str());
}
// unknown count
void checkUseStandardLibrary6() {
check("void f(void* dst, void* src, const size_t size) {\n"
" for (size_t i = 0; ((int8_t*)src)[i] != 0; ++i) {\n"
" ((int8_t*)dst)[i] = ((int8_t*)src)[i];\n"
"}}\n");
ASSERT_EQUALS("", errout_str());
}
// increment with 2
void checkUseStandardLibrary7() {
check("void f(void* dst, void* src, const size_t size) {\n"
" for (size_t i = 0; i < size; i += 2) {\n"
" ((int8_t*)dst)[i] = ((int8_t*)src)[i];\n"
"}}\n");
ASSERT_EQUALS("", errout_str());
}
// right argument of assignment could be static_cast, functional cast, c-style and implicit cast
// functional cast case not covered
void checkUseStandardLibrary8() {
check("void f(void* dest, const size_t count) {\n"
" size_t i;\n"
" for (i = 0; i < count; ++i)\n"
" (reinterpret_cast<int8_t*>(dest))[i] = static_cast<const int8_t>(0);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (style) Consider using std::memset instead of loop.\n", errout_str());
}
void checkUseStandardLibrary9() {
check("void f(void* dest, const size_t count) {\n"
" for (size_t i = 0; i < count; i++) {\n"
" (reinterpret_cast<uint8_t*>(dest))[i] = (static_cast<const uint8_t>(0));\n"
"}}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) Consider using std::memset instead of loop.\n", errout_str());
}
void checkUseStandardLibrary10() {
check("void f(void* dst, const size_t size) {\n"
" size_t i;\n"
" for (i = 0; i < size; i++)\n"
" ((char*)dst)[i] = (const char)0;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (style) Consider using std::memset instead of loop.\n", errout_str());
}
void checkUseStandardLibrary11() {
check("void f(void* dst, const size_t size) {\n"
" for (size_t i = 0; i < size; i += 1) {\n"
" ((int8_t*)dst)[i] = ((int8_t)0);\n"
"}}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) Consider using std::memset instead of loop.\n", errout_str());
}
void checkUseStandardLibrary12() {
check("void f(void* dst, const size_t size) {\n"
" for (size_t i = 0; i < size; i += 1) {\n"
" ((int8_t*)dst)[i] = 42;\n"
"}}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) Consider using std::memset instead of loop.\n", errout_str());
}
void checkUseStandardLibrary13() {
check("void f(void* dest, const size_t count) {\n"
" for (size_t i = 0; i < count; i++) {\n"
" reinterpret_cast<unsigned char*>(dest)[i] = '0';\n"
"}}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) Consider using std::memset instead of loop.\n", errout_str());
}
void checkUseStandardLibrary14() {
check("void f(void* dest) {\n"
" for (size_t i = 0; i < sizeof(int)*(15 + 42/2 - 7); i++) {\n"
" reinterpret_cast<unsigned char*>(dest)[i] = '0';\n"
"}}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) Consider using std::memset instead of loop.\n", errout_str());
}
};
REGISTER_TEST(TestFunctions)
| null |
990 | cpp | cppcheck | testtokenlist.cpp | test/testtokenlist.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "settings.h"
#include "fixture.h"
#include "helpers.h"
#include "platform.h"
#include "preprocessor.h"
#include "standards.h"
#include "token.h"
#include "tokenlist.h"
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>
#include <simplecpp.h>
class TestTokenList : public TestFixture {
public:
TestTokenList() : TestFixture("TestTokenList") {
settings.enforcedLang = Standards::Language::C;
}
private:
/*const*/ Settings settings;
void run() override {
TEST_CASE(testaddtoken1);
TEST_CASE(testaddtoken2);
TEST_CASE(inc);
TEST_CASE(isKeyword);
TEST_CASE(notokens);
TEST_CASE(ast1);
}
// inspired by #5895
void testaddtoken1() const {
const std::string code = "0x89504e470d0a1a0a";
TokenList tokenlist(&settings);
tokenlist.addtoken(code, 1, 1, false);
ASSERT_EQUALS("0x89504e470d0a1a0a", tokenlist.front()->str());
}
void testaddtoken2() const {
const std::string code = "0xF0000000";
/*const*/ Settings settings1 = settings;
settings1.platform.int_bit = 32;
TokenList tokenlist(&settings1);
tokenlist.addtoken(code, 1, 1, false);
ASSERT_EQUALS("0xF0000000", tokenlist.front()->str());
}
void inc() const {
const char code[] = "a++1;1++b;";
const SimpleTokenList tokenlist(code);
ASSERT(Token::simpleMatch(tokenlist.front(), "a + + 1 ; 1 + + b ;"));
}
void isKeyword() const {
const char code[] = "for a int delete true";
{
const SimpleTokenList tokenlist(code, Standards::Language::C);
ASSERT_EQUALS(true, tokenlist.front()->isKeyword());
ASSERT_EQUALS(true, tokenlist.front()->isControlFlowKeyword());
ASSERT_EQUALS(false, tokenlist.front()->next()->isKeyword());
ASSERT_EQUALS(false, tokenlist.front()->next()->isControlFlowKeyword());
ASSERT_EQUALS(false, tokenlist.front()->tokAt(2)->isKeyword());
ASSERT_EQUALS(true, tokenlist.front()->tokAt(2)->tokType() == Token::eType);
ASSERT_EQUALS(false, tokenlist.front()->tokAt(2)->isControlFlowKeyword());
ASSERT_EQUALS(false, tokenlist.front()->tokAt(3)->isKeyword());
ASSERT_EQUALS(false, tokenlist.front()->tokAt(3)->isControlFlowKeyword());
ASSERT_EQUALS(false, tokenlist.front()->tokAt(4)->isKeyword());
ASSERT_EQUALS(true, tokenlist.front()->tokAt(4)->isLiteral());
ASSERT_EQUALS(false, tokenlist.front()->tokAt(4)->isControlFlowKeyword());
}
{
const SimpleTokenList tokenlist(code);
ASSERT_EQUALS(true, tokenlist.front()->isKeyword());
ASSERT_EQUALS(true, tokenlist.front()->isControlFlowKeyword());
ASSERT_EQUALS(false, tokenlist.front()->next()->isKeyword());
ASSERT_EQUALS(false, tokenlist.front()->next()->isControlFlowKeyword());
ASSERT_EQUALS(false, tokenlist.front()->tokAt(2)->isKeyword());
ASSERT_EQUALS(true, tokenlist.front()->tokAt(2)->tokType() == Token::eType);
ASSERT_EQUALS(false, tokenlist.front()->tokAt(2)->isControlFlowKeyword());
ASSERT_EQUALS(true, tokenlist.front()->tokAt(3)->isKeyword());
ASSERT_EQUALS(false, tokenlist.front()->tokAt(3)->isControlFlowKeyword());
ASSERT_EQUALS(false, tokenlist.front()->tokAt(4)->isKeyword());
ASSERT_EQUALS(true, tokenlist.front()->tokAt(4)->isLiteral());
ASSERT_EQUALS(false, tokenlist.front()->tokAt(4)->isControlFlowKeyword());
}
{
const char code2[] = "_Generic"; // C11 keyword
const SimpleTokenList tokenlist(code2); // default settings use latest standard
ASSERT_EQUALS(false, tokenlist.front()->isKeyword());
}
{
const char code2[] = "_Generic"; // C11 keyword
const SimpleTokenList tokenlist(code2, Standards::Language::C); // default settings use latest standard
ASSERT_EQUALS(true, tokenlist.front()->isKeyword());
}
{
const char code2[] = "_Generic"; // C11 keyword
const Settings s = settingsBuilder().c(Standards::C89).build();
TokenList tokenlist(&s);
std::istringstream istr(code2);
ASSERT(tokenlist.createTokens(istr, "a.c"));
ASSERT_EQUALS(false, tokenlist.front()->isKeyword());
}
{
const char code2[] = "co_return"; // C++20 keyword
const SimpleTokenList tokenlist(code2); // default settings use latest standard
ASSERT_EQUALS(true, tokenlist.front()->isKeyword());
}
{
const char code2[] = "co_return"; // C++20 keyword
const SimpleTokenList tokenlist(code2, Standards::Language::C); // default settings use latest standard
ASSERT_EQUALS(false, tokenlist.front()->isKeyword());
}
{
const char code2[] = "noexcept"; // C++11 keyword
const Settings s = settingsBuilder().cpp(Standards::CPP03).build();
TokenList tokenlist(&s);
std::istringstream istr(code2);
ASSERT(tokenlist.createTokens(istr, "a.cpp"));
ASSERT_EQUALS(false, tokenlist.front()->isKeyword());
}
}
void notokens() {
// analyzing /usr/include/poll.h caused Path::identify() to be called with an empty filename from
// TokenList::determineCppC() because there are no tokens
const char code[] = "#include <sys/poll.h>";
std::istringstream istr(code);
std::vector<std::string> files;
simplecpp::TokenList tokens1(istr, files, "poll.h", nullptr);
Preprocessor preprocessor(settingsDefault, *this);
simplecpp::TokenList tokensP = preprocessor.preprocess(tokens1, "", files, true);
TokenList tokenlist(&settingsDefault);
tokenlist.createTokens(std::move(tokensP)); // do not assert
}
void ast1() const {
const std::string s = "('Release|x64' == 'Release|x64');";
TokenList tokenlist(&settings);
std::istringstream istr(s);
ASSERT(tokenlist.createTokens(istr, Standards::Language::C));
// TODO: put this logic in TokenList
// generate links
{
std::stack<Token*> lpar;
for (Token* tok2 = tokenlist.front(); tok2; tok2 = tok2->next()) {
if (tok2->str() == "(")
lpar.push(tok2);
else if (tok2->str() == ")") {
if (lpar.empty())
break;
Token::createMutualLinks(lpar.top(), tok2);
lpar.pop();
}
}
}
tokenlist.createAst(); // do not crash
}
};
REGISTER_TEST(TestTokenList)
| null |
991 | cpp | cppcheck | testtokenrange.cpp | test/testtokenrange.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "fixture.h"
#include "helpers.h"
#include "token.h"
#include "tokenrange.h"
#include "symboldatabase.h"
#include <algorithm>
#include <iterator>
#include <list>
#include <sstream>
#include <string>
class TestTokenRange : public TestFixture {
public:
TestTokenRange() : TestFixture("TestTokenRange") {}
private:
void run() override {
TEST_CASE(enumerationToEnd);
TEST_CASE(untilHelperToEnd);
TEST_CASE(untilHelperPartWay);
TEST_CASE(partialEnumeration);
TEST_CASE(scopeExample);
TEST_CASE(exampleAlgorithms);
}
static std::string testTokenRange(ConstTokenRange range, const Token* start, const Token* end) {
auto tokenToString = [](const Token* t) {
return t ? t->str() : "<null>";
};
int index = 0;
const Token* expected = start;
for (const Token* t : range) {
if (expected != t) {
std::ostringstream message;
message << "Failed to match token " << tokenToString(expected) << " at position " << index << ". Got " << tokenToString(t) << " instead";
return message.str();
}
index++;
expected = expected->next();
}
if (expected != end) {
std::ostringstream message;
message << "Failed to terminate on " << tokenToString(end) << ". Instead terminated on " << tokenToString(expected) << " at position " << index << ".";
return message.str();
}
return "";
}
void enumerationToEnd() const {
const char code[] = "void a(){} void main(){ if(true){a();} }";
const SimpleTokenList tokenList(code);
ASSERT_EQUALS("", testTokenRange(ConstTokenRange{ tokenList.front(), nullptr }, tokenList.front(), nullptr));
}
void untilHelperToEnd() const {
const char code[] = "void a(){} void main(){ if(true){a();} }";
const SimpleTokenList tokenList(code);
ASSERT_EQUALS("", testTokenRange(tokenList.front()->until(nullptr), tokenList.front(), nullptr));
}
void untilHelperPartWay() const {
const char code[] = "void a(){} void main(){ if(true){a();} }";
const SimpleTokenList tokenList(code);
const Token* start = tokenList.front()->tokAt(4);
const Token* end = start->tokAt(8);
ASSERT_EQUALS("", testTokenRange(start->until(end), start, end));
}
void partialEnumeration() const {
const char code[] = "void a(){} void main(){ if(true){a();} }";
const SimpleTokenList tokenList(code);
const Token* start = tokenList.front()->tokAt(4);
const Token* end = tokenList.front()->tokAt(10);
ASSERT_EQUALS("", testTokenRange(ConstTokenRange{ start, end }, start, end));
}
void scopeExample() {
SimpleTokenizer tokenizer(settingsDefault, *this);
const char code[] = "void a(){} void main(){ if(true){a();} }";
ASSERT(tokenizer.tokenize(code));
const SymbolDatabase* sd = tokenizer.getSymbolDatabase();
const Scope& scope = *std::next(sd->scopeList.cbegin(), 3); //The scope of the if block
std::string contents;
for (const Token* t : ConstTokenRange{ scope.bodyStart->next(), scope.bodyEnd }) {
contents += t->str();
}
ASSERT_EQUALS("a();", contents);
}
void exampleAlgorithms() const {
const char code[] = "void a(){} void main(){ if(true){a();} }";
const SimpleTokenList tokenList(code);
ConstTokenRange range{ tokenList.front(), nullptr };
ASSERT_EQUALS(true, std::all_of(range.begin(), range.end(), [](const Token*) {
return true;
}));
ASSERT_EQUALS(true, std::any_of(range.begin(), range.end(), [](const Token* t) {
return t->str() == "true";
}));
ASSERT_EQUALS("true", (*std::find_if(range.begin(), range.end(), [](const Token* t) {
return t->str() == "true";
}))->str());
ASSERT_EQUALS(3, std::count_if(range.begin(), range.end(), [](const Token* t) {
return t->str() == "{";
}));
}
};
REGISTER_TEST(TestTokenRange)
| null |
992 | cpp | cppcheck | testcheck.cpp | test/testcheck.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2023 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "check.h"
#include "fixture.h"
#include <list>
#include <string>
class TestCheck : public TestFixture {
public:
TestCheck() : TestFixture("TestCheck") {}
private:
void run() override {
TEST_CASE(instancesSorted);
TEST_CASE(classInfoFormat);
}
void instancesSorted() const {
for (std::list<Check *>::const_iterator i = Check::instances().cbegin(); i != Check::instances().cend(); ++i) {
std::list<Check *>::const_iterator j = i;
++j;
if (j != Check::instances().cend()) {
ASSERT_EQUALS(true, (*i)->name() < (*j)->name());
}
}
}
void classInfoFormat() const {
for (std::list<Check *>::const_iterator i = Check::instances().cbegin(); i != Check::instances().cend(); ++i) {
const std::string info = (*i)->classInfo();
if (!info.empty()) {
ASSERT('\n' != info[0]); // No \n in the beginning
ASSERT('\n' == info.back()); // \n at end
if (info.size() > 1)
ASSERT('\n' != info[info.length()-2]); // Only one \n at end
}
}
}
};
REGISTER_TEST(TestCheck)
| null |
993 | cpp | cppcheck | testexceptionsafety.cpp | test/testexceptionsafety.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "checkexceptionsafety.h"
#include "errortypes.h"
#include "fixture.h"
#include "helpers.h"
#include "settings.h"
#include <cstddef>
class TestExceptionSafety : public TestFixture {
public:
TestExceptionSafety() : TestFixture("TestExceptionSafety") {}
private:
/*const*/ Settings settings;
void run() override {
settings.severity.fill();
TEST_CASE(destructors);
TEST_CASE(deallocThrow1);
TEST_CASE(deallocThrow2);
TEST_CASE(deallocThrow3);
TEST_CASE(rethrowCopy1);
TEST_CASE(rethrowCopy2);
TEST_CASE(rethrowCopy3);
TEST_CASE(rethrowCopy4);
TEST_CASE(rethrowCopy5);
TEST_CASE(catchExceptionByValue);
TEST_CASE(noexceptThrow);
TEST_CASE(nothrowThrow);
TEST_CASE(unhandledExceptionSpecification1); // #4800
TEST_CASE(unhandledExceptionSpecification2);
TEST_CASE(unhandledExceptionSpecification3);
TEST_CASE(nothrowAttributeThrow);
TEST_CASE(nothrowAttributeThrow2); // #5703
TEST_CASE(nothrowDeclspecThrow);
TEST_CASE(rethrowNoCurrentException1);
TEST_CASE(rethrowNoCurrentException2);
TEST_CASE(rethrowNoCurrentException3);
}
#define check(...) check_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
void check_(const char* file, int line, const char (&code)[size], bool inconclusive = false, const Settings *s = nullptr) {
const Settings settings1 = settingsBuilder(s ? *s : settings).certainty(Certainty::inconclusive, inconclusive).build();
// Tokenize..
SimpleTokenizer tokenizer(settings1, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
// Check char variable usage..
runChecks<CheckExceptionSafety>(tokenizer, this);
}
void destructors() {
check("class x {\n"
" ~x() {\n"
" throw e;\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (warning) Class x is not safe, destructor throws exception\n"
"[test.cpp:3]: (error) Exception thrown in function declared not to throw exceptions.\n", errout_str());
check("class x {\n"
" ~x();\n"
"};\n"
"x::~x() {\n"
" throw e;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (warning) Class x is not safe, destructor throws exception\n"
"[test.cpp:5]: (error) Exception thrown in function declared not to throw exceptions.\n", errout_str());
// #3858 - throwing exception in try block in destructor.
check("class x {\n"
" ~x() {\n"
" try {\n"
" throw e;\n"
" } catch (...) {\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("class x {\n"
" ~x() {\n"
" if(!std::uncaught_exception()) {\n"
" throw e;\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Exception thrown in function declared not to throw exceptions.\n", errout_str());
// #11031 should not warn when noexcept false
check("class A {\n"
"public:\n"
" ~A() noexcept(false) {\n"
" throw 30;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void deallocThrow1() {
check("int * p;\n"
"void f(int x) {\n"
" delete p;\n"
" if (x)\n"
" throw 123;\n"
" p = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (warning) Exception thrown in invalid state, 'p' points at deallocated memory.\n", errout_str());
check("void f() {\n"
" static int* p = foo;\n"
" delete p;\n"
" if (foo)\n"
" throw 1;\n"
" p = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (warning) Exception thrown in invalid state, 'p' points at deallocated memory.\n", errout_str());
}
void deallocThrow2() {
check("void f() {\n"
" int* p = 0;\n"
" delete p;\n"
" if (foo)\n"
" throw 1;\n"
" p = new int;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" static int* p = 0;\n"
" delete p;\n"
" reset(p);\n"
" throw 1;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
}
void deallocThrow3() {
check("void f() {\n"
" static int* p = 0;\n"
" delete p;\n"
" throw 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" static int* p = 0;\n"
" delete p;\n"
" throw 1;\n"
"}", true);
ASSERT_EQUALS("[test.cpp:4]: (warning) Exception thrown in invalid state, 'p' points at deallocated memory.\n", errout_str());
}
void rethrowCopy1() {
check("void f() {\n"
" try\n"
" {\n"
" foo();\n"
" }\n"
" catch(const exception& err)\n"
" {\n"
" throw err;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:8]: (style) Throwing a copy of the caught exception instead of rethrowing the original exception.\n", errout_str());
}
void rethrowCopy2() {
check("void f() {\n"
" try\n"
" {\n"
" foo();\n"
" }\n"
" catch(exception& err)\n"
" {\n"
" throw err;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:8]: (style) Throwing a copy of the caught exception instead of rethrowing the original exception.\n", errout_str());
}
void rethrowCopy3() {
check("void f() {\n"
" try {\n"
" foo();\n"
" }\n"
" catch(std::runtime_error& err) {\n"
" throw err;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (style) Throwing a copy of the caught exception instead of rethrowing the original exception.\n", errout_str());
}
void rethrowCopy4() {
check("void f() {\n"
" try\n"
" {\n"
" foo();\n"
" }\n"
" catch(const exception& err)\n"
" {\n"
" exception err2;\n"
" throw err2;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void rethrowCopy5() {
check("void f() {\n"
" try {\n"
" foo();\n"
" }\n"
" catch(const exception& outer) {\n"
" try {\n"
" foo(outer);\n"
" }\n"
" catch(const exception& inner) {\n"
" throw inner;\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:10]: (style) Throwing a copy of the caught exception instead of rethrowing the original exception.\n", errout_str());
check("void f() {\n"
" try {\n"
" foo();\n"
" }\n"
" catch(const exception& outer) {\n"
" try {\n"
" foo(outer);\n"
" }\n"
" catch(const exception& inner) {\n"
" throw outer;\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void catchExceptionByValue() {
check("void f() {\n"
" try {\n"
" bar();\n"
" }\n"
" catch( ::std::exception err) {\n"
" foo(err);\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (style) Exception should be caught by reference.\n", errout_str());
check("void f() {\n"
" try {\n"
" bar();\n"
" }\n"
" catch(const exception err) {\n"
" foo(err);\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (style) Exception should be caught by reference.\n", errout_str());
check("void f() {\n"
" try {\n"
" bar();\n"
" }\n"
" catch( ::std::exception& err) {\n"
" foo(err);\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" try {\n"
" bar();\n"
" }\n"
" catch(exception* err) {\n"
" foo(err);\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" try {\n"
" bar();\n"
" }\n"
" catch(const exception& err) {\n"
" foo(err);\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" try {\n"
" bar();\n"
" }\n"
" catch(int err) {\n"
" foo(err);\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" try {\n"
" bar();\n"
" }\n"
" catch(exception* const err) {\n"
" foo(err);\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void noexceptThrow() {
check("void func1() noexcept(false) { try {} catch(...) {;} throw 1; }\n"
"void func2() noexcept { throw 1; }\n"
"void func3() noexcept(true) { throw 1; }\n"
"void func4() noexcept(false) { throw 1; }\n"
"void func5() noexcept(true) { func1(); }\n"
"void func6() noexcept(false) { func1(); }");
ASSERT_EQUALS("[test.cpp:2]: (error) Exception thrown in function declared not to throw exceptions.\n"
"[test.cpp:3]: (error) Exception thrown in function declared not to throw exceptions.\n"
"[test.cpp:5]: (error) Exception thrown in function declared not to throw exceptions.\n", errout_str());
// avoid false positives
check("const char *func() noexcept { return 0; }\n"
"const char *func1() noexcept { try { throw 1; } catch(...) {} return 0; }");
ASSERT_EQUALS("", errout_str());
}
void nothrowThrow() {
check("void func1() throw(int) { try {;} catch(...) { throw 1; } ; }\n"
"void func2() throw() { throw 1; }\n"
"void func3() throw(int) { throw 1; }\n"
"void func4() throw() { func1(); }\n"
"void func5() throw(int) { func1(); }");
ASSERT_EQUALS("[test.cpp:2]: (error) Exception thrown in function declared not to throw exceptions.\n"
"[test.cpp:4]: (error) Exception thrown in function declared not to throw exceptions.\n", errout_str());
// avoid false positives
check("const char *func() throw() { return 0; }");
ASSERT_EQUALS("", errout_str());
// #11691: FP throwInNoexceptFunction with if constexpr in template
check("template<bool IsNoThrow>\n"
"static void foo(size_t Size) noexcept(IsNoThrow) {\n"
" if constexpr (!IsNoThrow) {\n"
" throw std::bad_alloc();\n"
" }\n"
"}\n"
"foo<true>(123);\n");
ASSERT_EQUALS("", errout_str());
}
void unhandledExceptionSpecification1() { // #4800
check("void myThrowingFoo() throw(MyException) {\n"
" throw MyException();\n"
"}\n"
"void myNonCatchingFoo() {\n"
" myThrowingFoo();\n"
"}\n"
"void myCatchingFoo() {\n"
" try {\n"
" myThrowingFoo();\n"
" } catch(MyException &) {}\n"
"}\n", true);
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:1]: (style, inconclusive) Unhandled exception specification when calling function myThrowingFoo().\n", errout_str());
}
void unhandledExceptionSpecification2() {
check("void f() const throw (std::runtime_error);\n"
"int main()\n"
"{\n"
" f();\n"
"}\n", true);
ASSERT_EQUALS("", errout_str());
}
void unhandledExceptionSpecification3() {
const char code[] = "void f() const throw (std::runtime_error);\n"
"int _init() {\n"
" f();\n"
"}\n"
"int _fini() {\n"
" f();\n"
"}\n"
"int main()\n"
"{\n"
" f();\n"
"}\n";
check(code, true);
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:1]: (style, inconclusive) Unhandled exception specification when calling function f().\n"
"[test.cpp:6] -> [test.cpp:1]: (style, inconclusive) Unhandled exception specification when calling function f().\n", errout_str());
const Settings s = settingsBuilder().library("gnu.cfg").build();
check(code, true, &s);
ASSERT_EQUALS("", errout_str());
}
void nothrowAttributeThrow() {
check("void func1() throw(int) { throw 1; }\n"
"void func2() __attribute((nothrow)); void func2() { throw 1; }\n"
"void func3() __attribute((nothrow)); void func3() { func1(); }");
ASSERT_EQUALS("[test.cpp:2]: (error) Exception thrown in function declared not to throw exceptions.\n"
"[test.cpp:3]: (error) Exception thrown in function declared not to throw exceptions.\n", errout_str());
// avoid false positives
check("const char *func() __attribute((nothrow)); void func1() { return 0; }");
ASSERT_EQUALS("", errout_str());
}
void nothrowAttributeThrow2() {
check("class foo {\n"
" void copyMemberValues() throw () {\n"
" copyMemberValues();\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void nothrowDeclspecThrow() {
check("void func1() throw(int) { throw 1; }\n"
"void __declspec(nothrow) func2() { throw 1; }\n"
"void __declspec(nothrow) func3() { func1(); }");
ASSERT_EQUALS("[test.cpp:2]: (error) Exception thrown in function declared not to throw exceptions.\n"
"[test.cpp:3]: (error) Exception thrown in function declared not to throw exceptions.\n", errout_str());
// avoid false positives
check("const char *func() __attribute((nothrow)); void func1() { return 0; }");
ASSERT_EQUALS("", errout_str());
}
void rethrowNoCurrentException1() {
check("void func1(const bool flag) { try{ if(!flag) throw; } catch (int&) { ; } }");
ASSERT_EQUALS("[test.cpp:1]: (error) Rethrowing current exception with 'throw;', it seems there is no current exception to rethrow."
" If there is no current exception this calls std::terminate(). More: https://isocpp.org/wiki/faq/exceptions#throw-without-an-object\n", errout_str());
}
void rethrowNoCurrentException2() {
check("void func1() { try{ ; } catch (...) { ; } throw; }");
ASSERT_EQUALS("[test.cpp:1]: (error) Rethrowing current exception with 'throw;', it seems there is no current exception to rethrow."
" If there is no current exception this calls std::terminate(). More: https://isocpp.org/wiki/faq/exceptions#throw-without-an-object\n", errout_str());
}
void rethrowNoCurrentException3() {
check("void on_error() { try { throw; } catch (const int &) { ; } catch (...) { ; } }\n" // exception dispatcher idiom
"void func2() { try{ ; } catch (const int&) { throw; } ; }\n"
"void func3() { throw 0; }");
ASSERT_EQUALS("", errout_str());
}
};
REGISTER_TEST(TestExceptionSafety)
| null |
994 | cpp | cppcheck | testgarbage.cpp | test/testgarbage.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "check.h"
#include "errortypes.h"
#include "fixture.h"
#include "helpers.h"
#include "settings.h"
#include "token.h"
#include <cstddef>
#include <list>
#include <string>
class TestGarbage : public TestFixture {
public:
TestGarbage() : TestFixture("TestGarbage") {}
private:
/*const*/ Settings settings = settingsBuilder().debugwarnings().build();
void run() override {
settings.severity.fill();
settings.certainty.fill();
// don't freak out when the syntax is wrong
TEST_CASE(final_class_x);
TEST_CASE(wrong_syntax1);
TEST_CASE(wrong_syntax2);
TEST_CASE(wrong_syntax3); // #3544
TEST_CASE(wrong_syntax4); // #3618
TEST_CASE(wrong_syntax_if_macro); // #2518 - if MACRO()
TEST_CASE(wrong_syntax_class_x_y); // #3585 - class x y { };
TEST_CASE(wrong_syntax_anonymous_struct);
TEST_CASE(syntax_case_default);
TEST_CASE(garbageCode1);
TEST_CASE(garbageCode2); // #4300
TEST_CASE(garbageCode3); // #4869
TEST_CASE(garbageCode4); // #4887
TEST_CASE(garbageCode5); // #5168
TEST_CASE(garbageCode6); // #5214
TEST_CASE(garbageCode7);
TEST_CASE(garbageCode8); // #5511
TEST_CASE(garbageCode9); // #5604
TEST_CASE(garbageCode10); // #6127
TEST_CASE(garbageCode12);
TEST_CASE(garbageCode13); // #2607
TEST_CASE(garbageCode15); // #5203
TEST_CASE(garbageCode16);
TEST_CASE(garbageCode17);
TEST_CASE(garbageCode18);
TEST_CASE(garbageCode20);
TEST_CASE(garbageCode21);
TEST_CASE(garbageCode22);
TEST_CASE(garbageCode23);
TEST_CASE(garbageCode24); // #6361
TEST_CASE(garbageCode25);
TEST_CASE(garbageCode26);
TEST_CASE(garbageCode27);
TEST_CASE(garbageCode28);
TEST_CASE(garbageCode30); // #5867
TEST_CASE(garbageCode31); // #6539
TEST_CASE(garbageCode33); // #6613
TEST_CASE(garbageCode34); // #6626
TEST_CASE(garbageCode35); // #2604
TEST_CASE(garbageCode36); // #6334
TEST_CASE(garbageCode37); // #5166
TEST_CASE(garbageCode38); // #6666
TEST_CASE(garbageCode40); // #6620
TEST_CASE(garbageCode41); // #6685
TEST_CASE(garbageCode42); // #5760
TEST_CASE(garbageCode43); // #6703
TEST_CASE(garbageCode44); // #6704
TEST_CASE(garbageCode45); // #6608
TEST_CASE(garbageCode46); // #6705
TEST_CASE(garbageCode47); // #6706
TEST_CASE(garbageCode48); // #6712
TEST_CASE(garbageCode49); // #6715
TEST_CASE(garbageCode51); // #6719
TEST_CASE(garbageCode53); // #6721
TEST_CASE(garbageCode54); // #6722
TEST_CASE(garbageCode55); // #6724
TEST_CASE(garbageCode56); // #6713
TEST_CASE(garbageCode57); // #6733
TEST_CASE(garbageCode58); // #6732
TEST_CASE(garbageCode59); // #6735
TEST_CASE(garbageCode60); // #6736
TEST_CASE(garbageCode61);
TEST_CASE(garbageCode63);
TEST_CASE(garbageCode64);
TEST_CASE(garbageCode65);
TEST_CASE(garbageCode66);
TEST_CASE(garbageCode68);
TEST_CASE(garbageCode69);
TEST_CASE(garbageCode70);
TEST_CASE(garbageCode71);
TEST_CASE(garbageCode72);
TEST_CASE(garbageCode73);
TEST_CASE(garbageCode74);
TEST_CASE(garbageCode76);
TEST_CASE(garbageCode77);
TEST_CASE(garbageCode78);
TEST_CASE(garbageCode79);
TEST_CASE(garbageCode80);
TEST_CASE(garbageCode81);
TEST_CASE(garbageCode82);
TEST_CASE(garbageCode83);
TEST_CASE(garbageCode84);
TEST_CASE(garbageCode85);
TEST_CASE(garbageCode86);
TEST_CASE(garbageCode87);
TEST_CASE(garbageCode88);
TEST_CASE(garbageCode90);
TEST_CASE(garbageCode91);
TEST_CASE(garbageCode92);
TEST_CASE(garbageCode94);
TEST_CASE(garbageCode95);
TEST_CASE(garbageCode96);
TEST_CASE(garbageCode97);
TEST_CASE(garbageCode98);
TEST_CASE(garbageCode99);
TEST_CASE(garbageCode100);
TEST_CASE(garbageCode101); // #6835
TEST_CASE(garbageCode102); // #6846
TEST_CASE(garbageCode103); // #6824
TEST_CASE(garbageCode104); // #6847
TEST_CASE(garbageCode105); // #6859
TEST_CASE(garbageCode106);
TEST_CASE(garbageCode107);
TEST_CASE(garbageCode108);
TEST_CASE(garbageCode109);
TEST_CASE(garbageCode110);
TEST_CASE(garbageCode111);
TEST_CASE(garbageCode112);
TEST_CASE(garbageCode114); // #2118
TEST_CASE(garbageCode115); // #5506
TEST_CASE(garbageCode116); // #5356
TEST_CASE(garbageCode117); // #6121
TEST_CASE(garbageCode118); // #5600
TEST_CASE(garbageCode119); // #5598
TEST_CASE(garbageCode120); // #4927
TEST_CASE(garbageCode121); // #2585
TEST_CASE(garbageCode122); // #6303
TEST_CASE(garbageCode123);
TEST_CASE(garbageCode125); // 6782, 6834
TEST_CASE(garbageCode126); // #6997
TEST_CASE(garbageCode127); // #6667
TEST_CASE(garbageCode128); // #7018
TEST_CASE(garbageCode129); // #7020
TEST_CASE(garbageCode130); // #7021
TEST_CASE(garbageCode131); // #7023
TEST_CASE(garbageCode132); // #7022
TEST_CASE(garbageCode133);
TEST_CASE(garbageCode134);
TEST_CASE(garbageCode135); // #4994
TEST_CASE(garbageCode136); // #7033
TEST_CASE(garbageCode137); // #7034
TEST_CASE(garbageCode138); // #6660
TEST_CASE(garbageCode139); // #6659
TEST_CASE(garbageCode140); // #7035
TEST_CASE(garbageCode141); // #7043
TEST_CASE(garbageCode142); // #7050
TEST_CASE(garbageCode143); // #6922
TEST_CASE(garbageCode144); // #6865
TEST_CASE(garbageCode146); // #7081
TEST_CASE(garbageCode147); // #7082
TEST_CASE(garbageCode148); // #7090
TEST_CASE(garbageCode149); // #7085
TEST_CASE(garbageCode150); // #7089
TEST_CASE(garbageCode151); // #4911
TEST_CASE(garbageCode152); // travis after 9c7271a5
TEST_CASE(garbageCode153);
TEST_CASE(garbageCode154); // #7112
TEST_CASE(garbageCode156); // #7120
TEST_CASE(garbageCode157); // #7131
TEST_CASE(garbageCode158); // #3238
TEST_CASE(garbageCode159); // #7119
TEST_CASE(garbageCode160); // #7190
TEST_CASE(garbageCode161); // #7200
TEST_CASE(garbageCode162); // #7208
TEST_CASE(garbageCode163); // #7228
TEST_CASE(garbageCode164); // #7234
TEST_CASE(garbageCode165); // #7235
TEST_CASE(garbageCode167); // #7237
TEST_CASE(garbageCode168); // #7246
TEST_CASE(garbageCode169); // #6731
TEST_CASE(garbageCode170);
TEST_CASE(garbageCode171);
TEST_CASE(garbageCode172);
TEST_CASE(garbageCode173); // #6781
TEST_CASE(garbageCode174); // #7356
TEST_CASE(garbageCode175);
TEST_CASE(garbageCode176); // #7527
TEST_CASE(garbageCode181);
TEST_CASE(garbageCode182); // #4195
TEST_CASE(garbageCode183); // #7505
TEST_CASE(garbageCode184); // #7699
TEST_CASE(garbageCode185); // #6011
TEST_CASE(garbageCode186); // #8151
TEST_CASE(garbageCode187);
TEST_CASE(garbageCode188);
TEST_CASE(garbageCode189); // #8317
TEST_CASE(garbageCode190); // #8307
TEST_CASE(garbageCode191); // #8333
TEST_CASE(garbageCode192); // #8386 (segmentation fault)
TEST_CASE(garbageCode193); // #8740
TEST_CASE(garbageCode194); // #8384
TEST_CASE(garbageCode195); // #8709
TEST_CASE(garbageCode196); // #8265
TEST_CASE(garbageCode197); // #8385
TEST_CASE(garbageCode198); // #8383
TEST_CASE(garbageCode199); // #8752
TEST_CASE(garbageCode200); // #8757
TEST_CASE(garbageCode201); // #8873
TEST_CASE(garbageCode202); // #8907
TEST_CASE(garbageCode203); // #8972
TEST_CASE(garbageCode204);
TEST_CASE(garbageCode205);
TEST_CASE(garbageCode206);
TEST_CASE(garbageCode207); // #8750
TEST_CASE(garbageCode208); // #8753
TEST_CASE(garbageCode209); // #8756
TEST_CASE(garbageCode210); // #8762
TEST_CASE(garbageCode211); // #8764
TEST_CASE(garbageCode212); // #8765
TEST_CASE(garbageCode213); // #8758
TEST_CASE(garbageCode214);
TEST_CASE(garbageCode215); // daca@home script with extension .c
TEST_CASE(garbageCode216); // #7884
TEST_CASE(garbageCode217); // #10011
TEST_CASE(garbageCode218); // #8763
TEST_CASE(garbageCode219); // #10101
TEST_CASE(garbageCode220); // #6832
TEST_CASE(garbageCode221);
TEST_CASE(garbageCode222); // #10763
TEST_CASE(garbageCode223); // #11639
TEST_CASE(garbageCode224);
TEST_CASE(garbageCode225);
TEST_CASE(garbageCode226);
TEST_CASE(garbageCode227);
TEST_CASE(garbageCodeFuzzerClientMode1); // test cases created with the fuzzer client, mode 1
TEST_CASE(garbageValueFlow);
TEST_CASE(garbageSymbolDatabase);
TEST_CASE(garbageAST);
TEST_CASE(templateSimplifierCrashes);
TEST_CASE(syntaxErrorFirstToken); // Make sure syntax errors are detected and reported
TEST_CASE(syntaxErrorLastToken); // Make sure syntax errors are detected and reported
TEST_CASE(syntaxErrorCase);
TEST_CASE(syntaxErrorFuzzerCliType1);
TEST_CASE(cliCode);
TEST_CASE(enumTrailingComma);
TEST_CASE(nonGarbageCode1); // #8346
}
#define checkCodeInternal(code, filename) checkCodeInternal_(code, filename, __FILE__, __LINE__)
template<size_t size>
std::string checkCode(const char (&code)[size], bool cpp = true) {
// double the tests - run each example as C as well as C++
// run alternate check first. It should only ensure stability - so we catch exceptions here.
try {
(void)checkCodeInternal(code, !cpp);
} catch (const InternalError&) {}
return checkCodeInternal(code, cpp);
}
template<size_t size>
std::string checkCodeInternal_(const char (&code)[size], bool cpp, const char* file, int line) {
// tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code, cpp), file, line);
// call all "runChecks" in all registered Check classes
for (auto it = Check::instances().cbegin(); it != Check::instances().cend(); ++it) {
(*it)->runChecks(tokenizer, this);
}
return tokenizer.tokens()->stringifyList(false, false, false, true, false, nullptr, nullptr);
}
#define getSyntaxError(code) getSyntaxError_(code, __FILE__, __LINE__)
template<size_t size>
std::string getSyntaxError_(const char (&code)[size], const char* file, int line) {
SimpleTokenizer tokenizer(settings, *this);
try {
ASSERT_LOC(tokenizer.tokenize(code), file, line);
} catch (InternalError& e) {
if (e.id != "syntaxError")
return "";
return "[test.cpp:" + std::to_string(e.token->linenr()) + "] " + e.errorMessage;
}
return "";
}
void final_class_x() {
const char code[] = "class __declspec(dllexport) x final { };";
SimpleTokenizer tokenizer(settings, *this);
ASSERT(tokenizer.tokenize(code));
ASSERT_EQUALS("", errout_str());
}
void wrong_syntax1() {
{
const char code[] ="TR(kvmpio, PROTO(int rw), ARGS(rw), TP_(aa->rw;))";
ASSERT_THROW_INTERNAL(checkCode(code), UNKNOWN_MACRO);
ASSERT_EQUALS("", errout_str());
}
{
const char code[] ="struct A { template<int> struct { }; };";
ASSERT_THROW_INTERNAL(checkCode(code), SYNTAX);
}
{
const char code[] ="enum ABC { A,B, typedef enum { C } };";
ASSERT_THROW_INTERNAL(checkCode(code), SYNTAX);
}
}
void wrong_syntax2() { // #3504
const char code[] = "void f() {\n"
" X<int> x;\n"
" Y<int, int, int, int, int, char> y;\n"
"}\n"
"\n"
"void G( template <typename T> class (j) ) {}";
// don't segfault..
ASSERT_THROW_INTERNAL(checkCode(code), SYNTAX);
ignore_errout(); // we are not interested in the output
}
void wrong_syntax3() { // #3544
const char code[] = "X #define\n"
"{\n"
" (\n"
" for( #endif typedef typedef cb[N] )\n"
" ca[N]; = cb[i]\n"
" )\n"
"}";
SimpleTokenizer tokenizer(settings, *this);
try {
ASSERT(tokenizer.tokenize(code));
assertThrowFail(__FILE__, __LINE__);
} catch (InternalError& e) {
ASSERT_EQUALS("syntax error", e.errorMessage);
ASSERT_EQUALS("syntaxError", e.id);
ASSERT_EQUALS(4, e.token->linenr());
}
}
void wrong_syntax4() { // #3618
const char code[] = "typedef void (x) (int); return x&";
ASSERT_THROW_INTERNAL(checkCode(code), SYNTAX);
}
void wrong_syntax_if_macro() {
// #2518 #4171
ASSERT_THROW_INTERNAL(checkCode("void f() { if MACRO(); }"), SYNTAX);
// #4668 - note there is no semicolon after MACRO()
ASSERT_THROW_INTERNAL(checkCode("void f() { if (x) MACRO() {} }"), SYNTAX);
// #4810 - note there is no semicolon after MACRO()
ASSERT_THROW_INTERNAL(checkCode("void f() { if (x) MACRO() else ; }"), SYNTAX);
}
void wrong_syntax_class_x_y() {
// #3585
const char code[] = "class x y { };";
{
SimpleTokenizer tokenizer(settings, *this);
ASSERT(tokenizer.tokenize(code, false));
ASSERT_EQUALS("", errout_str());
}
{
SimpleTokenizer tokenizer(settings, *this);
ASSERT(tokenizer.tokenize(code));
ASSERT_EQUALS("[test.cpp:1]: (information) The code 'class x y {' is not handled. You can use -I or --include to add handling of this code.\n", errout_str());
}
}
void wrong_syntax_anonymous_struct() {
ASSERT_THROW_INTERNAL(checkCode("struct { int x; } = {0};"), SYNTAX);
ASSERT_THROW_INTERNAL(checkCode("struct { int x; } * = {0};"), SYNTAX);
}
void syntax_case_default() {
ASSERT_THROW_INTERNAL(checkCode("void f() {switch (n) { case: z(); break;}}"), SYNTAX);
ASSERT_THROW_INTERNAL(checkCode("void f() {switch (n) { case;: z(); break;}}"), SYNTAX);
ASSERT_THROW_INTERNAL(checkCode("void f() {switch (n) { case {}: z(); break;}}"), SYNTAX);
ASSERT_THROW_INTERNAL(checkCode("void f() {switch (n) { case 0?{1}:{2} : z(); break;}}"), SYNTAX);
ASSERT_THROW_INTERNAL(checkCode("void f() {switch (n) { case 0?1;:{2} : z(); break;}}"), SYNTAX);
ASSERT_THROW_INTERNAL(checkCode("void f() {switch (n) { case 0?(1?{3:4}):2 : z(); break;}}"), AST);
//ticket #4234
ASSERT_THROW_INTERNAL(checkCode("( ) { switch break ; { switch ( x ) { case } y break ; : } }"), SYNTAX);
//ticket #4267
ASSERT_THROW_INTERNAL(checkCode("f ( ) { switch break; { switch ( x ) { case } case break; -6: ( ) ; } }"), SYNTAX);
// Missing semicolon
ASSERT_THROW_INTERNAL(checkCode("void foo () { switch(0) case 0 : default : }"), SYNTAX);
}
void garbageCode1() {
(void)checkCode("struct x foo_t; foo_t typedef y;");
}
void garbageCode2() { //#4300 (segmentation fault)
TODO_ASSERT_THROW(checkCode("enum { D = 1 struct { } ; } s.b = D;"), InternalError);
}
void garbageCode3() { //#4849 (segmentation fault in Tokenizer::simplifyStructDecl (invalid code))
TODO_ASSERT_THROW(checkCode("enum { D = 2 s ; struct y { x } ; } { s.a = C ; s.b = D ; }"), InternalError);
}
void garbageCode4() { // #4887
ASSERT_THROW_INTERNAL(checkCode("void f ( ) { = a ; if ( 1 ) if = ( 0 ) ; }"), SYNTAX);
}
void garbageCode5() { // #5168 (segmentation fault)
ASSERT_THROW_INTERNAL(checkCode("( asm : ; void : );"), SYNTAX);
}
void garbageCode6() { // #5214
ASSERT_THROW_INTERNAL(checkCode("int b = ( 0 ? ? ) 1 : 0 ;"), SYNTAX);
ASSERT_THROW_INTERNAL(checkCode("int a = int b = ( 0 ? ? ) 1 : 0 ;"), SYNTAX);
}
void garbageCode7() {
ASSERT_THROW_INTERNAL(checkCode("1 (int j) { return return (c) * sizeof } y[1];"), SYNTAX);
ASSERT_THROW_INTERNAL(checkCode("foo(Args&&...) fn void = { } auto template<typename... bar(Args&&...)"), SYNTAX);
}
void garbageCode8() { // #5604
TODO_ASSERT_THROW(checkCode("{ enum struct : };"), InternalError);
TODO_ASSERT_THROW(checkCode("int ScopedEnum{ template<typename T> { { e = T::error }; };\n"
"ScopedEnum1<int> se1; { enum class E : T { e = 0 = e ScopedEnum2<void*> struct UnscopedEnum3 { T{ e = 4 }; };\n"
"arr[(int) E::e]; }; UnscopedEnum3<int> e2 = f()\n"
"{ { e = e1; T::error } int test1 ue2; g() { enum class E { e = T::error }; return E::e; } int test2 = }\n"
"namespace UnscopedEnum { template<typename T> struct UnscopedEnum1 { E{ e = T::error }; }; UnscopedEnum1<int> { enum E : { e = 0 }; };\n"
"UnscopedEnum2<void*> ue3; template<typename T> struct UnscopedEnum3 { enum { }; }; int arr[E::e]; };\n"
"UnscopedEnum3<int> namespace template<typename T> int f() { enum E { e }; T::error }; return (int) E(); } int test1 int g() { enum E { e = E };\n"
"E::e; } int test2 = g<int>(); }"), InternalError);
}
void garbageCode9() {
TODO_ASSERT_THROW(checkCode("enum { e = { } } ( ) { { enum { } } } { e } "), InternalError);
}
void garbageCode10() { // #6127
ASSERT_THROW_INTERNAL(checkCode("for( rl=reslist; rl!=NULL; rl=rl->next )"), SYNTAX);
}
void garbageCode12() { // do not crash
(void)checkCode("{ g; S (void) { struct } { } int &g; }");
ignore_errout(); // we do not care about the output
}
void garbageCode13() { // Ticket #2607 - crash
(void)checkCode("struct C {} {} x");
}
void garbageCode15() { // Ticket #5203
ASSERT_THROW_INTERNAL(checkCode("int f ( int* r ) { { int s[2] ; f ( s ) ; if ( ) } }"), SYNTAX);
}
void garbageCode16() { // #6080 (segmentation fault)
(void)checkCode("{ } A() { delete }"); // #6080
ignore_errout(); // we do not care about the output
}
void garbageCode17() {
ASSERT_THROW_INTERNAL(checkCode("void h(int l) {\n"
" while\n" // Don't crash (#3870)
"}"), SYNTAX);
}
void garbageCode18() {
ASSERT_THROW_INTERNAL(checkCode("switch(){case}"), SYNTAX);
}
void garbageCode20() {
// #3953 (valgrind errors on garbage code)
ASSERT_EQUALS("void f ( 0 * ) ;", checkCode("void f ( 0 * ) ;"));
}
void garbageCode21() {
// Ticket #3486 - Don't crash garbage code
ASSERT_THROW_INTERNAL(checkCode("void f()\n"
"{\n"
" (\n"
" x;\n"
" int a, a2, a2*x; if () ;\n"
" )\n"
"}"), SYNTAX);
}
void garbageCode22() {
// Ticket #3480 - Don't crash garbage code
ASSERT_THROW_INTERNAL(checkCode("int f()\n"
"{\n"
" return if\n"
"}"), SYNTAX);
}
void garbageCode23() {
//garbage code : don't crash (#3481)
ASSERT_THROW_INTERNAL_EQUALS(checkCode("{\n"
" if (1) = x\n"
" else abort s[2]\n"
"}"),
SYNTAX,
"syntax error");
}
void garbageCode24() {
// don't crash (example from #6361)
ASSERT_THROW_INTERNAL(checkCode("float buffer[64];\n"
"main (void)\n"
"{\n"
" char *cptr;\n"
" cptr = (char *)buffer;\n"
" cptr += (-(long int) buffer & (16 * sizeof (float) - 1));\n"
"}\n"), SYNTAX);
ignore_errout(); // we do not care about the output
}
void garbageCode25() {
// Ticket #2386 - Segmentation fault upon strange syntax
ASSERT_THROW_INTERNAL(checkCode("void f() {\n"
" switch ( x ) {\n"
" case struct Tree : break;\n"
" }\n"
"}"), SYNTAX);
ignore_errout(); // we do not care about the output
}
void garbageCode26() {
// See tickets #2518 #2555 #4171
ASSERT_THROW_INTERNAL(checkCode("void f() {\n"
" switch MAKEWORD(1)\n"
" {\n"
" case 0:\n"
" return;\n"
" }\n"
"}"), SYNTAX);
}
void garbageCode27() {
ASSERT_THROW_INTERNAL(checkCode("int f() {\n"
" return if\n"
"}"), SYNTAX);
}
void garbageCode28() { // #5702 (segmentation fault)
// 5702
(void)checkCode("struct R1 {\n"
" int a;\n"
" R1 () : a { }\n"
"};");
ignore_errout(); // we do not care about the output
}
void garbageCode30() {
// simply survive - a syntax error would be even better (#5867)
(void)checkCode("void f(int x) {\n"
" x = 42\n"
"}");
ignore_errout(); // we do not care about the output
}
void garbageCode31() {
ASSERT_THROW_INTERNAL(checkCode("typedef struct{}x[([],)]typedef e y;(y,x 0){}"), SYNTAX);
}
void garbageCode33() { // #6613 (segmentation fault)
(void)checkCode("main(()B{});");
}
// Bug #6626 crash: Token::astOperand2() const ( do while )
void garbageCode34() {
const char code[] = "void foo(void) {\n"
" do\n"
" while (0);\n"
"}";
ASSERT_THROW_INTERNAL(checkCode(code), SYNTAX);
}
void garbageCode35() {
// ticket #2604 segmentation fault
ASSERT_THROW_INTERNAL(checkCode("sizeof <= A"), AST);
}
void garbageCode36() { // #6334
ASSERT_THROW_INTERNAL(checkCode("{ } < class template < > , { = } ; class... >\n"
"struct Y { }\n"
"class Types { }\n"
"( X < int > \"uses template\" ) ( < ( ) \"uses ;"
"( int int ::primary \"uses template\" ) int double \"uses )"
"::primary , \"uses template\" ;\n"), SYNTAX);
}
void garbageCode37() {
// #5166 segmentation fault (invalid code) in lib/checkother.cpp:329 ( void * f { } void b ( ) { * f } )
(void)checkCode("void * f { } void b ( ) { * f }");
ignore_errout(); // we do not care about the output
}
void garbageCode38() { // Ticket #6666 (segmentation fault)
(void)checkCode("{ f2 { } } void f3 () { delete[] } { }");
ignore_errout(); // we do not care about the output
}
void garbageCode40() { // #6620 (segmentation fault)
(void)checkCode("{ ( ) () { virtual } ; { } E } A { : { } ( ) } * const ( ) const { }");
// test doesn't seem to work on any platform: ASSERT_THROW(checkCode("{ ( ) () { virtual } ; { } E } A { : { } ( ) } * const ( ) const { }", "test.c"), InternalError);
}
void garbageCode41() { // #6685 (segmentation fault)
(void)checkCode(" { } { return } *malloc(__SIZE_TYPE__ size); *memcpy(void n); static * const () { memcpy (*slot, 3); } { (); } { }");
}
void garbageCode42() { // #5760 (segmentation fault)
(void)checkCode("{ } * const ( ) { }");
}
void garbageCode43() { // #6703 (segmentation fault)
(void)checkCode("int { }; struct A<void> a = { }");
}
void garbageCode44() { // #6704
ASSERT_THROW_INTERNAL(checkCode("{ { }; }; { class A : }; public typedef b;"), SYNTAX);
}
void garbageCode45() { // #6608
ASSERT_THROW_INTERNAL(checkCode("struct true template < > { = } > struct Types \"s\" ; static_assert < int > ;"), SYNTAX);
}
void garbageCode46() { // #6705 (segmentation fault)
(void)checkCode(" { bar(char *x); void foo (int ...) { struct } va_list ap; va_start(ap, size); va_arg(ap, (d)); }");
ignore_errout(); // we do not care about the output
}
void garbageCode47() { // #6706 (segmentation fault)
(void)checkCode(" { { }; }; * new private: B: B;");
}
void garbageCode48() { // #6712 (segmentation fault)
ASSERT_THROW_INTERNAL(checkCode(" { d\" ) d ...\" } int main ( ) { ( ) catch ( A a ) { { } catch ( ) \"\" } }"), SYNTAX);
}
void garbageCode49() { // #6715
ASSERT_THROW_INTERNAL(checkCode(" ( ( ) ) { } ( { ( __builtin_va_arg_pack ( ) ) ; } ) { ( int { ( ) ( ( ) ) } ( ) { } ( ) ) += ( ) }"), AST);
}
void garbageCode51() { // #6719
ASSERT_THROW_INTERNAL(checkCode(" (const \"C\" ...); struct base { int f2; base (int arg1, int arg2); }; global_base(0x55, 0xff); { ((global_base.f1 0x55) (global_base.f2 0xff)) { } } base::base(int arg1, int arg2) { f2 = }"), SYNTAX);
}
void garbageCode53() { // #6721
ASSERT_THROW_INTERNAL(checkCode("{ { } }; void foo (struct int i) { x->b[i] = = }"), SYNTAX);
}
void garbageCode54() { // #6722
ASSERT_THROW_INTERNAL(checkCode("{ typedef long ((pf) p) (); }"), SYNTAX);
}
void garbageCode55() { // #6724
ASSERT_THROW_INTERNAL(checkCode("() __attribute__((constructor)); { } { }"), SYNTAX);
}
void garbageCode56() { // #6713
ASSERT_THROW_INTERNAL(checkCode("void foo() { int a = 0; int b = ???; }"), AST);
}
void garbageCode57() { // #6731
ASSERT_THROW_INTERNAL(checkCode("{ } if () try { } catch (...) B::~B { }"), SYNTAX);
}
void garbageCode58() { // #6732, #6762
ASSERT_THROW_INTERNAL(checkCode("{ }> {= ~A()^{} }P { }"), SYNTAX);
ASSERT_THROW_INTERNAL(checkCode("{= ~A()^{} }P { } { }> is"), SYNTAX);
}
void garbageCode59() { // #6735
ASSERT_THROW_INTERNAL(checkCode("{ { } }; char font8x8[256][8]"), SYNTAX);
}
void garbageCode60() { // #6736
ASSERT_THROW_INTERNAL(checkCode("{ } { } typedef int int_array[]; int_array &right ="), SYNTAX);
}
void garbageCode61() { // #6737
ASSERT_THROW_INTERNAL(checkCode("{ (const U&) }; { }; { }; struct U : virtual public"), SYNTAX);
}
void garbageCode63() { // #6739
ASSERT_THROW_INTERNAL(checkCode("{ } { } typedef int u_array[]; typedef u_array &u_array_ref; (u_array_ref arg) { } u_array_ref u_array_ref_gbl_obj0"), SYNTAX);
}
void garbageCode64() { // #6740
ASSERT_THROW_INTERNAL(checkCode("{ } foo(void (*bar)(void))"), SYNTAX);
}
void garbageCode65() { // #6741 (segmentation fault)
// TODO write some syntax error
(void)checkCode("{ } { } typedef int u_array[]; typedef u_array &u_array_ref; (u_array_ref arg) { } u_array_ref");
}
void garbageCode66() { // #6742
ASSERT_THROW_INTERNAL(checkCode("{ { } }; { { } }; { }; class bar : public virtual"), SYNTAX);
}
void garbageCode68() { // #6745 (segmentation fault)
(void)checkCode("(int a[3]); typedef void (*fp) (void); fp");
}
void garbageCode69() { // #6746
ASSERT_THROW_INTERNAL(checkCode("{ (make_mess, aux); } typedef void F(void); aux(void (*x)()) { } (void (*y)()) { } F*"), SYNTAX);
}
void garbageCode70() { // #6747
ASSERT_THROW_INTERNAL(checkCode("{ } __attribute__((constructor)) void"), SYNTAX);
}
void garbageCode71() { // #6748
ASSERT_THROW_INTERNAL(checkCode("( ) { } typedef void noattr_t ( ) ; noattr_t __attribute__ ( )"), SYNTAX);
}
void garbageCode72() { // #6749
ASSERT_THROW_INTERNAL(checkCode("{ } { } typedef void voidfn(void); <voidfn&"), SYNTAX);
}
void garbageCode73() { // #6750
ASSERT_THROW_INTERNAL(checkCode("typedef int IRT[2]; IRT&"), SYNTAX);
}
void garbageCode74() { // #6751
ASSERT_THROW_INTERNAL(checkCode("_lenraw(const char* digits) { } typedef decltype(sizeof(0)) { } operator"), SYNTAX);
}
void garbageCode76() { // #6754
ASSERT_THROW_INTERNAL(checkCode(" ( ) ( ) { ( ) [ ] } TEST ( ) { ( _broadcast_f32x4 ) ( ) ( ) ( ) ( ) if ( ) ( ) ; } E mask = ( ) [ ] ( ) res1.x ="), SYNTAX);
}
void garbageCode77() { // #6755
ASSERT_THROW_INTERNAL(checkCode("void foo (int **p) { { { };>= } } unsigned *d = (b b--) --*d"), SYNTAX);
}
void garbageCode78() { // #6756
ASSERT_THROW_INTERNAL(checkCode("( ) { [ ] } ( ) { } const_array_of_int ( ) { } typedef int A [ ] [ ] ; A a = { { } { } }"), SYNTAX);
ignore_errout(); // we do not care about the output
}
void garbageCode79() { // #6757
ASSERT_THROW_INTERNAL(checkCode("{ } { } typedef void ( func_type ) ( ) ; func_type & ( )"), SYNTAX);
}
void garbageCode80() { // #6759
ASSERT_THROW_INTERNAL(checkCode("( ) { ; ( ) ; ( * ) [ ] ; [ ] = ( ( ) ( ) h ) ! ( ( ) ) } { ; } { } head heads [ ] = ; = & heads [ 2 ]"), SYNTAX);
}
void garbageCode81() { // #6760
ASSERT_THROW_INTERNAL(checkCode("{ } [ ] { ( ) } { } typedef void ( *fptr1 ) ( ) const"), SYNTAX);
}
void garbageCode82() { // #6761
ASSERT_THROW_INTERNAL(checkCode("p(\"Hello \" 14) _yn(const size_t) typedef bool pfunk (*pfunk)(const size_t)"), SYNTAX);
}
void garbageCode83() { // #6771
ASSERT_THROW_INTERNAL(checkCode("namespace A { class } class A { friend C ; } { } ;"), SYNTAX);
}
void garbageCode84() { // #6780
ASSERT_THROW_INTERNAL(checkCode("int main ( [ ] ) { " " [ ] ; int i = 0 ; do { } ; } ( [ ] ) { }"), SYNTAX); // do not crash
}
void garbageCode85() { // #6784 (segmentation fault)
(void)checkCode("{ } { } typedef void ( *VoidFunc() ) ( ) ; VoidFunc"); // do not crash
}
void garbageCode86() { // #6785
ASSERT_THROW_INTERNAL(checkCode("{ } typedef char ( *( X ) ( void) , char ) ;"), SYNTAX); // do not crash
}
void garbageCode87() { // #6788
ASSERT_THROW_INTERNAL(checkCode("((X (128))) (int a) { v[ = {} (x 42) a] += }"), SYNTAX); // do not crash
}
void garbageCode88() { // #6786
ASSERT_THROW_INTERNAL(checkCode("( ) { ( 0 ) { ( ) } } g ( ) { i( ( false ?) ( ) : 1 ) ; } ;"), SYNTAX); // do not crash
}
void garbageCode90() { // #6790
ASSERT_THROW_INTERNAL(checkCode("{ } { } typedef int u_array [[ ] ; typedef u_array & u_array_ref] ( ) { } u_array_ref_gbl_obj0"), SYNTAX); // do not crash
}
void garbageCode91() { // #6791
ASSERT_THROW_INTERNAL(checkCode("typedef __attribute__((vector_size (16))) { return[ (v2df){ } ;] }"), SYNTAX); // throw syntax error
}
void garbageCode92() { // #6792
ASSERT_THROW_INTERNAL(checkCode("template < typename _Tp ( ( ) ; _Tp ) , decltype > { } { ( ) ( ) }"), SYNTAX); // do not crash
}
void garbageCode94() { // #6803
//checkCode("typedef long __m256i __attribute__ ( ( ( ) ) )[ ; ( ) { } typedef __m256i __attribute__ ( ( ( ) ) ) < ] ( ) { ; }");
ASSERT_THROW_INTERNAL(checkCode("typedef long __m256i __attribute__ ( ( ( ) ) )[ ; ( ) { } typedef __m256i __attribute__ ( ( ( ) ) ) < ] ( ) { ; }"), SYNTAX);
}
void garbageCode95() { // #6804
ASSERT_THROW_INTERNAL(checkCode("{ } x x ; { } h h [ ] ( ) ( ) { struct x ( x ) ; int __attribute__ ( ) f ( ) { h - > first = & x ; struct x * n = h - > first ; ( ) n > } }"), AST); // do not crash
}
void garbageCode96() { // #6807
ASSERT_THROW_INTERNAL(checkCode("typedef J J[ ; typedef ( ) ( ) { ; } typedef J J ;] ( ) ( J cx ) { n } ;"), SYNTAX); // throw syntax error
}
void garbageCode97() { // #6808
ASSERT_THROW_INTERNAL(checkCode("namespace A {> } class A{ { }} class A : T< ;"), SYNTAX);
}
void garbageCode98() { // #6838
ASSERT_THROW_INTERNAL(checkCode("for (cocon To::ta@Taaaaaforconst oken aaaaaaaaaaaa5Dl()\n"
"const unsigned in;\n"
"fon *tok = f);.s(Token i = d-)L;"), SYNTAX);
}
void garbageCode99() { // #6726
ASSERT_THROW_INTERNAL_EQUALS(checkCode("{ xs :: i(:) ! ! x/5 ! !\n"
"i, :: a :: b integer, } foo2(x) :: j(:)\n"
"b type(*), d(:), a x :: end d(..), foo end\n"
"foo4 b d(..), a a x type(*), b foo2 b"), SYNTAX, "syntax error");
}
void garbageCode100() { // #6840
ASSERT_THROW_INTERNAL(checkCode("( ) { ( i< ) } int foo ( ) { int i ; ( for ( i => 1 ) ; ) }"), SYNTAX);
}
void garbageCode101() { // #6835
// Reported case
ASSERT_THROW_INTERNAL(checkCode("template < class , =( , int) X = 1 > struct A { } ( ) { = } [ { } ] ( ) { A < void > 0 }"), SYNTAX);
// Reduced case
ASSERT_THROW_INTERNAL(checkCode("template < class =( , ) X = 1> struct A {}; A<void> a;"), SYNTAX);
}
void garbageCode102() { // #6846 (segmentation fault)
(void)checkCode("struct Object { ( ) ; Object & operator= ( Object ) { ( ) { } if ( this != & b ) } }");
ignore_errout(); // we do not care about the output
}
void garbageCode103() { // #6824
ASSERT_THROW_INTERNAL(checkCode("a f(r) int * r; { { int s[2]; [f(s); if () ] } }"), SYNTAX);
}
void garbageCode104() { // #6847
ASSERT_THROW_INTERNAL(checkCode("template < Types > struct S {> ( S < ) S >} { ( ) { } } ( ) { return S < void > ( ) } { ( )> >} { ( ) { } } ( ) { ( ) }"), SYNTAX);
}
void garbageCode105() { // #6859
ASSERT_THROW_INTERNAL(checkCode("void foo (int i) { int a , for (a 1; a( < 4; a++) if (a) (b b++) (b);) n++; }"), SYNTAX);
}
void garbageCode106() { // #6880
ASSERT_THROW_INTERNAL(checkCode("[ ] typedef typedef b_array b_array_ref [ ; ] ( ) b_array_ref b_array_ref_gbl_obj0 { ; { b_array_ref b_array_ref_gbl_obj0 } }"), SYNTAX);
}
void garbageCode107() { // #6881
TODO_ASSERT_THROW(checkCode("enum { val = 1{ }; { const} }; { } Bar { const int A = val const } ;"), InternalError);
}
void garbageCode108() { // #6895 "segmentation fault (invalid code) in CheckCondition::isOppositeCond"
ASSERT_THROW_INTERNAL(checkCode("A( ) { } bool f( ) { ( ) F; ( ) { ( == ) if ( !=< || ( !A( ) && r[2] ) ) ( !A( ) ) ( ) } }"), SYNTAX);
}
void garbageCode109() { // #6900 "segmentation fault (invalid code) in CheckStl::runSimplifiedChecks"
(void)checkCode("( *const<> (( ) ) { } ( *const ( ) ( ) ) { } ( * const<> ( size_t )) ) { } ( * const ( ) ( ) ) { }");
}
void garbageCode110() { // #6902 "segmentation fault (invalid code) in CheckStl::string_c_str"
ASSERT_THROW_INTERNAL(checkCode("( *const<> ( size_t ) ; foo ) { } * ( *const ( size_t ) ( ) ;> foo )< { }"), SYNTAX);
}
void garbageCode111() { // #6907
TODO_ASSERT_THROW(checkCode("enum { FOO = 1( ,) } {{ FOO }} ;"), InternalError);
}
void garbageCode112() { // #6909
TODO_ASSERT_THROW(checkCode("enum { FOO = ( , ) } {{ }}>> enum { FOO< = ( ) } { { } } ;"), InternalError);
}
void garbageCode114() { // #2118
ASSERT_NO_THROW(checkCode("Q_GLOBAL_STATIC_WITH_INITIALIZER(Qt4NodeStaticData, qt4NodeStaticData, {\n"
" for (unsigned i = 0 ; i < count; i++) {\n"
" }\n"
"});"));
}
void garbageCode115() { // #5506
ASSERT_THROW_INTERNAL(checkCode("A template < int { int = -1 ; } template < int N > struct B { int [ A < N > :: zero ] ; } ; B < 0 > b ;"), UNKNOWN_MACRO);
}
void garbageCode116() { // #5356
ASSERT_THROW_INTERNAL(checkCode("struct template<int { = }; > struct B { }; B < 0 > b;"), SYNTAX);
}
void garbageCode117() { // #6121
TODO_ASSERT_THROW(checkCode("enum E { f = {} };\n"
"int a = f;"), InternalError);
}
void garbageCode118() { // #5600 - missing include causes invalid enum
ASSERT_THROW_INTERNAL(checkCode("enum {\n"
" NUM_OPCODES =\n"
// #include "definition"
"};\n"
"struct bytecode {};\n"
"jv jq_next() { opcode = ((opcode) +NUM_OPCODES);\n"
"}"), SYNTAX);
}
void garbageCode119() { // #5598 (segmentation fault)
(void)checkCode("{ { void foo() { struct }; template <typename> struct S { Used x; void bar() } auto f = [this] { }; } };");
ignore_errout(); // we do not care about the output
}
void garbageCode120() { // #4927 (segmentation fault)
(void)checkCode("int main() {\n"
" return 0\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void garbageCode121() { // #2585
ASSERT_THROW_INTERNAL(checkCode("abcdef?" "?<"
"123456?" "?>"
"+?" "?="), SYNTAX);
}
void garbageCode122() { // #6303 (segmentation fault)
(void)checkCode("void foo() {\n"
"char *a = malloc(10);\n"
"a[0]\n"
"}");
ignore_errout(); // we do not care about the output
}
void garbageCode123() {
(void)checkCode("namespace pr16989 {\n"
" class C {\n"
" C tpl_mem(T *) { return }\n"
" };\n"
"}");
ignore_errout(); // we do not care about the output
}
void garbageCode125() {
ASSERT_THROW_INTERNAL(checkCode("{ T struct B : T valueA_AA ; } T : [ T > ( ) { B } template < T > struct A < > : ] { ( ) { return valueA_AC struct { : } } b A < int > AC ( ) a_aa.M ; ( ) ( ) }"), SYNTAX);
ASSERT_THROW_INTERNAL(checkCode("template < Types > struct S :{ ( S < ) S >} { ( ) { } } ( ) { return S < void > ( ) }"),
SYNTAX);
}
void garbageCode126() {
ASSERT_THROW_INTERNAL(checkCode("{ } float __ieee754_sinhf ( float x ) { float t , , do { gf_u ( jx ) { } ( 0 ) return ; ( ) { } t } ( 0x42b17180 ) { } }"),
SYNTAX);
}
void garbageCode127() { // #6667 (segmentation fault)
(void)checkCode("extern \"C\" int printf(const char* fmt, ...);\n"
"class A {\n"
"public:\n"
" int Var;\n"
" A(int arg) { Var = arg; }\n"
" ~A() { printf(\"A d'tor\\n\"); }\n"
"};\n"
" const A& foo(const A& arg) { return arg; }\n"
" foo(A(12)).Var");
ignore_errout(); // we do not care about the output
}
void garbageCode128() {
TODO_ASSERT_THROW(checkCode("enum { FOO = ( , ) } {{ }} enum {{ FOO << = } ( ) } {{ }} ;"),
InternalError);
}
void garbageCode129() {
ASSERT_THROW_INTERNAL(checkCode("operator - ( { } typedef typename x ; ( ) ) { ( { { ( ( ) ) } ( { } ) } ) }"),
SYNTAX);
}
void garbageCode130() {
TODO_ASSERT_THROW(checkCode("enum { FOO = ( , ){ } { { } } { { FOO} = } ( ) } { { } } enumL\" ( enumL\" { { FOO } ( ) } { { } } ;"),
InternalError);
}
void garbageCode131() {
ASSERT_THROW_INTERNAL(checkCode("( void ) { ( ) } ( ) / { ( ) }"), SYNTAX);
// actually the invalid code should trigger an syntax error...
}
void garbageCode132() { // #7022
ASSERT_THROW_INTERNAL(checkCode("() () { } { () () ({}) i() } void i(void(*ptr) ()) { ptr(!) () }"), SYNTAX);
}
void garbageCode133() {
ASSERT_THROW_INTERNAL(checkCode("void f() {{}"), SYNTAX);
ASSERT_THROW_INTERNAL(checkCode("void f()) {}"), SYNTAX);
ASSERT_THROW_INTERNAL(checkCode("void f()\n"
"{\n"
" foo(;\n"
"}\n"), SYNTAX);
ASSERT_THROW_INTERNAL(checkCode("void f()\n"
"{\n"
" for(;;){ foo();\n"
"}\n"), SYNTAX);
ASSERT_THROW_INTERNAL(checkCode("void f()\n"
"{\n"
" a[10;\n"
"}\n"), SYNTAX);
{
const char code[] = "{\n"
" a(\n" // <- error
"}\n"
"{\n"
" b());\n"
"}\n";
ASSERT_EQUALS("[test.cpp:2] Unmatched '('. Configuration: ''.", getSyntaxError(code));
}
{
const char code[] = "void f() {\n"
" int x = 3) + 0;\n" // <- error: unmatched )
"}\n";
ASSERT_EQUALS("[test.cpp:2] Unmatched ')'. Configuration: ''.", getSyntaxError(code));
}
{
const char code[] = "void f() {\n"
" int x = (3] + 0;\n" // <- error: unmatched ]
"}\n";
ASSERT_EQUALS("[test.cpp:2] Unmatched ']'. Configuration: ''.", getSyntaxError(code));
}
{
const char code[] = "void f() {\n" // <- error: unmatched {
" {\n"
"}\n";
ASSERT_EQUALS("[test.cpp:1] Unmatched '{'. Configuration: ''.", getSyntaxError(code));
}
}
void garbageCode134() {
// Ticket #5605, #5759, #5762, #5774, #5823, #6059
ASSERT_THROW_INTERNAL(checkCode("foo() template<typename T1 = T2 = typename = unused, T5 = = unused> struct tuple Args> tuple<Args...> { } main() { foo<int,int,int,int,int,int>(); }"), SYNTAX);
ASSERT_THROW_INTERNAL(checkCode("( ) template < T1 = typename = unused> struct Args { } main ( ) { foo < int > ( ) ; }"), SYNTAX);
ASSERT_THROW_INTERNAL(checkCode("() template < T = typename = x > struct a {} { f <int> () }"), SYNTAX);
ASSERT_THROW_INTERNAL(checkCode("template < T = typename = > struct a { f <int> }"), SYNTAX);
(void)checkCode("struct S { int i, j; }; "
"template<int S::*p, typename U> struct X {}; "
"X<&S::i, int> x = X<&S::i, int>(); "
"X<&S::j, int> y = X<&S::j, int>();");
ignore_errout(); // we are not interested in the output
(void)checkCode("template <typename T> struct A {}; "
"template <> struct A<void> {}; "
"void foo(const void* f = 0) {}");
(void)checkCode("template<typename... T> struct A { "
" static const int s = 0; "
"}; "
"A<int> a;");
(void)checkCode("template<class T, class U> class A {}; "
"template<class T = A<int, int> > class B {}; "
"template<class T = B<int> > class C { "
" C() : _a(0), _b(0) {} "
" int _a, _b; "
"};");
(void)checkCode("template<class... T> struct A { "
" static int i; "
"}; "
"void f() { A<int>::i = 0; }");
ignore_errout(); // we are not interested in the output
}
void garbageCode135() { // #4994 (segmentation fault)
(void)checkCode("long f () {\n"
" return a >> extern\n"
"}\n"
"long a = 1 ;\n"
"long b = 2 ;");
ignore_errout(); // we are not interested in the output
}
void garbageCode136() { // #7033
ASSERT_THROW_INTERNAL(checkCode("{ } () { void f() { node_t * n; for (; -n) {} } } { }"),
SYNTAX);
}
void garbageCode137() { // #7034
ASSERT_THROW_INTERNAL(checkCode("\" \" typedef signed char f; \" \"; void a() { f * s = () &[]; (; ) (; ) }"), SYNTAX);
}
void garbageCode138() { // #6660 (segmentation fault)
(void)checkCode("CS_PLUGIN_NAMESPACE_BEGIN(csparser)\n"
"{\n"
" struct foo\n"
" {\n"
" union\n"
" {};\n"
" } halo;\n"
"}\n"
"CS_PLUGIN_NAMESPACE_END(csparser)");
ignore_errout(); // we are not interested in the output
}
void garbageCode139() { // #6659 heap user after free: kernel: sm750_accel.c
ASSERT_THROW_INTERNAL(checkCode("void hw_copyarea() {\n"
" de_ctrl = (nDirection == RIGHT_TO_LEFT) ?\n"
" ( (0 & ~(((1 << (1 - (0 ? DE_CONTROL_DIRECTION))) - 1) << (0 ? DE_CONTROL_DIRECTION))) )\n"
" : 42;\n"
"}"), SYNTAX);
}
void garbageCode140() { // #7035
ASSERT_THROW_INTERNAL(checkCode("int foo(int align) { int off(= 0 % align; return off) ? \\ align - off : 0; \\ }"), SYNTAX);
}
void garbageCode141() { // #7043
TODO_ASSERT_THROW(checkCode("enum { X = << { X } } enum { X = X } = X ;"), InternalError);
}
void garbageCode142() { // #7050
ASSERT_THROW_INTERNAL(checkCode("{ } ( ) { void mapGraphs ( ) { node_t * n ; for (!oid n ) { } } } { }"), SYNTAX);
}
void garbageCode143() { // #6922
ASSERT_THROW_INTERNAL(checkCode("void neoProgramShadowRegs() {\n"
" int i;\n"
" Bool noProgramShadowRegs;\n"
" if (noProgramShadowRegs) {\n"
" } else {\n"
" switch (nPtr->NeoPanelWidth) {\n"
" case 1280:\n"
" VGAwCR(0x64,0x?? );\n"
" }\n"
" }\n"
"}"), AST);
}
void garbageCode144() { // #6865
ASSERT_THROW_INTERNAL(checkCode("template < typename > struct A { } ; template < typename > struct A < INVALID > : A < int[ > { }] ;"), SYNTAX);
}
void garbageCode146() { // #7081
ASSERT_THROW_INTERNAL(checkCode("void foo() {\n"
" ? std::cout << pow((, 1) << std::endl;\n"
" double <ip = NUO ip) << std::end;\n"
"}"), SYNTAX);
}
void garbageCode147() { // #7082
ASSERT_THROW_INTERNAL(checkCode("free(3();\n"
"$ vWrongAllocp1) test1<int, -!>() ^ {\n"
" int *p<ynew int[n];\n"
" delete[]p;\n"
" int *p1 = (int*)malloc(n*sizeof(int));\n"
" free(p1);\n"
"}\n"
"void est2() {\n"
" for (int ui = 0; ui < 1z; ui++)\n"
" ;\n"
"}"), SYNTAX);
ASSERT_THROW_INTERNAL(checkCode("; void f ^ { return } int main ( ) { }"), SYNTAX); // #4941
}
void garbageCode148() { // #7090
ASSERT_THROW_INTERNAL(checkCode("void f_1() {\n"
" typedef S0 b[][1][1] != 0\n"
"};\n"
"b[K][0] S0 b[][1][1] != 4{ 0 };\n"
"b[0][0]"), UNKNOWN_MACRO);
}
void garbageCode149() { // #7085 (segmentation fault)
(void)checkCode("int main() {\n"
" for (j = 0; j < 1; j)\n"
" j6;\n"
"}");
ignore_errout(); // we do not care about the output
}
void garbageCode150() { // #7089
ASSERT_THROW_INTERNAL(checkCode("class A {\n"
" pl vFoo() {\n"
" A::\n"
" };\n"
" A::\n"
"}\n"), SYNTAX);
}
void garbageCode151() { // #4911 - bad simplification => don't crash
(void)checkCode("void f() {\n"
" int a;\n"
" do { a=do_something() } while (a);\n"
"}");
}
void garbageCode152() { // happened in travis, originally from llvm clang code (segmentation fault)
const char code[] = "template <bool foo = std::value &&>\n"
"static std::string foo(char *Bla) {\n"
" while (Bla[1] && Bla[1] != ',') }\n";
(void)checkCode(code);
ignore_errout(); // we are not interested in the output
}
void garbageCode153() {
TODO_ASSERT_THROW(checkCode("enum { X = << { X } } { X X } enum { X = << { ( X ) } } { } X */"), InternalError);
}
void garbageCode154() { // #7112 (segmentation fault)
(void)checkCode("\"abc\"[];");
}
void garbageCode156() { // #7120
ASSERT_THROW_INTERNAL(checkCode("struct {}a; d f() { c ? : } {}a.p"), AST);
}
void garbageCode157() { // #7131
ASSERT_THROW_INTERNAL(checkCode("namespace std {\n"
" template < typename >\n"
" void swap();\n"
"}"
"template std::swap\n"), SYNTAX);
}
void garbageCode158() { // #3238 (segmentation fault)
(void)checkCode("__FBSDID(\"...\");");
}
void garbageCode159() { // #7119
ASSERT_THROW_INTERNAL(checkCode("({}typedef typename x;typename x!){({{}()})}"), SYNTAX);
}
void garbageCode160() { // #7190
ASSERT_THROW_INTERNAL(checkCode("f(a,b,c,d)float [ a[],d;int ] b[],c;{} "), SYNTAX); // don't hang
}
void garbageCodeFuzzerClientMode1() {
ASSERT_THROW_INTERNAL(checkCode("void f() { x= name2 & name3 name2 = | 0.1 , | 0.1 , | 0.1 name4 <= >( ); }"), SYNTAX);
ASSERT_THROW_INTERNAL(checkCode("void f() { x = , * [ | + 0xff | > 0xff]; }"), SYNTAX);
ASSERT_THROW_INTERNAL(checkCode("void f() { x = , | 0xff , 0.1 < ; }"), SYNTAX);
ASSERT_THROW_INTERNAL(checkCode("void f() { x = [ 1 || ] ; }"), SYNTAX);
ASSERT_THROW_INTERNAL(checkCode("void f1() { x = name6 1 || ? name3 [ ( 1 || +) ] ; }"), SYNTAX);
}
void garbageValueFlow() {
{ // #6089
const char code[] = "{} int foo(struct, x1, struct x2, x3, int, x5, x6, x7)\n"
"{\n"
" (foo(s, , 2, , , 5, , 7)) abort()\n"
"}\n";
ASSERT_THROW_INTERNAL(checkCode(code), SYNTAX);
}
{ // 6122 survive garbage code
const char code[] = "; { int i ; for ( i = 0 ; = 123 ; ) - ; }";
ASSERT_THROW_INTERNAL(checkCode(code), SYNTAX);
}
{
const char code[] = "void f1() { for (int n = 0 n < 10 n++); }";
ASSERT_THROW_INTERNAL(checkCode(code), SYNTAX);
}
}
void garbageSymbolDatabase() {
(void)checkCode("void f( { u = 1 ; } ) { }");
ASSERT_THROW_INTERNAL(checkCode("{ }; void namespace A::f; { g() { int } }"), SYNTAX);
ASSERT_THROW_INTERNAL(checkCode("class Foo {}; class Bar : public Foo"), SYNTAX);
// #5663 (segmentation fault)
(void)checkCode("YY_DECL { switch (yy_act) {\n"
" case 65: YY_BREAK\n"
" case YY_STATE_EOF(block):\n"
" yyterminate();\n"
"} }");
ignore_errout(); // we are not interested in the output
}
void garbageAST() {
ASSERT_THROW_INTERNAL(checkCode("N 1024 float a[N], b[N + 3], c[N]; void N; (void) i;\n"
"int #define for (i = avx_test i < c[i]; i++)\n"
"b[i + 3] = a[i] * {}"), SYNTAX); // Don't hang (#5787)
(void)checkCode("START_SECTION([EXTRA](bool isValid(const String &filename)))"); // Don't crash (#5991)
// #8352
ASSERT_THROW_INTERNAL(checkCode("else return % name5 name2 - =name1 return enum | { - name3 1 enum != >= 1 >= ++ { { || "
"{ return return { | { - name3 1 enum != >= 1 >= ++ { name6 | ; ++}}}}}}}"), SYNTAX);
ASSERT_THROW_INTERNAL(checkCode("else return % name5 name2 - =name1 return enum | { - name3 1 enum != >= 1 >= ++ { { || "
"{ return return { | { - name3 1 enum != >= 1 >= ++ { { || ; ++}}}}}}}}"), SYNTAX);
}
void templateSimplifierCrashes() {
(void)checkCode( // #5950 (segmentation fault)
"struct A {\n"
" template <class T> operator T*();\n"
"};\n"
"\n"
"template <> A::operator char*(){ return 0; } // specialization\n"
"\n"
"int main() {\n"
" A a;\n"
" int *ip = a.operator int*();\n"
"}\n"
"\n"
"namespace PR5742 {\n"
" template <class T> struct A { };\n"
" struct S {\n"
" template <class T> operator T();\n"
" } s;\n"
" void f() {\n"
" s.operator A<A<int> >();\n"
" }\n"
"}");
ASSERT_NO_THROW(checkCode( // #6034
"template<template<typename...> class T, typename... Args>\n"
"struct foo<T<Args...> > {\n"
" const bool value = true;\n"
"};\n"
"\n"
"template<int I>\n"
"struct int_\n"
"{};\n"
"\n"
"int main() {\n"
" foo<int_<0> >::value;\n"
"}"));
(void)checkCode( // #6117 (segmentation fault)
"template <typename ...> struct something_like_tuple\n"
"{};\n"
"template <typename, typename> struct is_last {\n"
" static const bool value = false;\n"
"};\n"
"template <typename T, template <typename ...> class Tuple, typename ... Head>\n"
"struct is_last<T, Tuple<Head ..., T>>\n"
"{\n"
" static const bool value = true;\n"
"};\n"
"\n"
"#define SA(X) static_assert (X, #X)\n"
"\n"
"typedef something_like_tuple<char, int, float> something_like_tuple_t;\n"
"SA ((is_last<float, something_like_tuple_t>::value == false));\n"
"SA ((is_last<int, something_like_tuple_t>::value == false));");
ignore_errout(); // we are not interested in the output
(void)checkCode( // #6225 (use-after-free)
"template <typename...>\n"
"void templ_fun_with_ty_pack() {}\n"
"\n"
"namespace PR20047 {\n"
" template <typename T>\n"
" struct A {};\n"
" using AliasA = A<T>;\n"
"}");
// #3449
ASSERT_EQUALS("template < typename T > struct A ;\n"
"struct B { template < typename T > struct C } ;\n"
"{ } ;",
checkCode("template<typename T> struct A;\n"
"struct B { template<typename T> struct C };\n"
"{};"));
}
void garbageCode161() {
//7200
ASSERT_THROW_INTERNAL(checkCode("{ }{ if () try { } catch (...)} B : : ~B { }"), SYNTAX);
}
void garbageCode162() {
//7208
ASSERT_THROW_INTERNAL(checkCode("return << >> x return << >> x ", false), SYNTAX);
}
void garbageCode163() {
//7228
ASSERT_THROW_INTERNAL(checkCode("typedef s f[](){typedef d h(;f)}", false), SYNTAX);
}
void garbageCode164() {
//7234
ASSERT_THROW_INTERNAL(checkCode("class d{k p;}(){d::d():B<()}"), SYNTAX);
}
void garbageCode165() {
//7235
ASSERT_THROW_INTERNAL(checkCode("for(;..)", false),SYNTAX);
}
void garbageCode167() {
//7237
ASSERT_THROW_INTERNAL(checkCode("class D00i000{:D00i000::}i"),SYNTAX);
}
void garbageCode168() {
// #7246 (segmentation fault)
(void)checkCode("long foo(void) { return *bar; }", false);
ignore_errout(); // we do not care about the output
}
void garbageCode169() {
// 6713
ASSERT_THROW_INTERNAL(checkCode("( ) { ( ) ; { return } switch ( ) i\n"
"set case break ; default: ( ) }", false), SYNTAX);
}
void garbageCode170() {
// 7255
ASSERT_THROW_INTERNAL(checkCode("d i(){{f*s=typeid(()0,)}}", false), SYNTAX);
}
void garbageCode171() {
// 7270
ASSERT_THROW_INTERNAL(checkCode("(){case()?():}:", false), SYNTAX);
}
void garbageCode172() {
// #7357
ASSERT_THROW_INTERNAL(checkCode("p<e T=l[<]<>>,"), SYNTAX);
}
void garbageCode173() {
// #6781 heap corruption ; TemplateSimplifier::simplifyTemplateInstantiations
ASSERT_THROW_INTERNAL(checkCode(" template < Types > struct S : >( S < ...Types... > S <) > { ( ) { } } ( ) { return S < void > ( ) }"), SYNTAX);
}
void garbageCode174() { // #7356
ASSERT_THROW_INTERNAL(checkCode("{r e() { w*constD = (())D = cast< }}"), SYNTAX);
}
void garbageCode175() { // #7027
ASSERT_THROW_INTERNAL(checkCode("int f() {\n"
" int i , j;\n"
" for ( i = t3 , i < t1 ; i++ )\n"
" for ( j = 0 ; j < = j++ )\n"
" return t1 ,\n"
"}"), SYNTAX);
}
void garbageCode176() { // #7257 (segmentation fault)
(void)checkCode("class t { { struct } enum class f : unsigned { q } b ; operator= ( T ) { switch ( b ) { case f::q: } } { assert ( b ) ; } } { ; & ( t ) ( f::t ) ; } ;");
ignore_errout(); // we are not interested in the output
}
void garbageCode181() {
ASSERT_THROW_INTERNAL(checkCode("int test() { int +; }"), SYNTAX);
}
// #4195 - segfault for "enum { int f ( ) { return = } r = f ( ) ; }"
void garbageCode182() {
ASSERT_THROW_INTERNAL(checkCode("enum { int f ( ) { return = } r = f ( ) ; }"), SYNTAX);
}
// #7505 - segfault
void garbageCode183() {
ASSERT_THROW_INTERNAL(checkCode("= { int } enum return { r = f() f(); }"), SYNTAX);
}
void garbageCode184() { // #7699
ASSERT_THROW_INTERNAL(checkCode("unsigned int AquaSalSystem::GetDisplayScreenCount() {\n"
" NSArray* pScreens = [NSScreen screens];\n"
" return pScreens ? [pScreens count] : 1;\n"
"}"), SYNTAX);
}
void garbageCode185() { // #6011 crash in libreoffice failure to create proper AST
(void)checkCode(
"namespace binfilter\n"
"{\n"
" BOOL EnhWMFReader::ReadEnhWMF()\n"
" {\n"
" pOut->CreateObject( nIndex, GDI_BRUSH, new WinMtfFillStyle( ReadColor(), ( nStyle == BS_HOLLOW ) ? TRUE : FALSE ) );\n"
" return bStatus;\n"
" };\n"
"}");
ignore_errout(); // we are not interested in the output
}
// #8151 - segfault due to incorrect template syntax
void garbageCode186() {
ASSERT_THROW_INTERNAL(checkCode("A<B<><>C"), SYNTAX);
}
void garbageCode187() { // # 8152 - segfault in handling
const char inp[] = "0|\0|0>;\n";
ASSERT_THROW_INTERNAL(checkCode(inp), SYNTAX);
(void)checkCode("template<class T> struct S : A< B<T> || C<T> > {};"); // No syntax error: #8390
(void)checkCode("static_assert(A<x> || B<x>, ab);");
}
void garbageCode188() { // #8255
ASSERT_THROW_INTERNAL(checkCode("{z r(){(){for(;<(x);){if(0==0)}}}}"), SYNTAX);
}
void garbageCode189() { // #8317 (segmentation fault)
(void)checkCode("t&n(){()()[](){()}}$");
}
void garbageCode190() { // #8307
ASSERT_THROW_INTERNAL(checkCode("void foo() {\n"
" int i;\n"
" i *= 0;\n"
" !i <;\n"
"}"),
AST);
}
void garbageCode191() { // #8333
ASSERT_THROW_INTERNAL(checkCode("struct A { int f(const); };"), SYNTAX);
ASSERT_THROW_INTERNAL(checkCode("struct A { int f(int, const, char); };"), SYNTAX);
ASSERT_THROW_INTERNAL(checkCode("struct A { int f(struct); };"), SYNTAX);
// The following code is valid and should not trigger any error
ASSERT_NO_THROW(checkCode("struct A { int f ( char ) ; } ;"));
}
void garbageCode192() { // #8386 (segmentation fault)
ASSERT_THROW_INTERNAL(checkCode("{(()[((0||0xf||))]0[])}"), SYNTAX);
}
// #8740
void garbageCode193() {
ASSERT_THROW_INTERNAL(checkCode("d f(){!=[]&&0()!=0}"), SYNTAX);
}
// #8384
void garbageCode194() {
ASSERT_THROW_INTERNAL(checkCode("{((()))(return 1||);}"), SYNTAX);
}
// #8709 - no garbage but to avoid stability regression (segmentation fault)
void garbageCode195() {
(void)checkCode("a b;\n"
"void c() {\n"
" switch (d) { case b:; }\n"
" double e(b);\n"
" if(e <= 0) {}\n"
"}");
ignore_errout(); // we do not care about the output
}
// #8265
void garbageCode196() {
ASSERT_THROW_INTERNAL(checkCode("0|,0<<V"), SYNTAX);
ASSERT_THROW_INTERNAL(checkCode(";|4|<0;"), SYNTAX);
}
// #8385
void garbageCode197() {
ASSERT_THROW_INTERNAL(checkCode("(){e break,{(case)|{e:[()]}}}"), SYNTAX);
}
// #8383
void garbageCode198() {
ASSERT_THROW_INTERNAL(checkCode("void f(){\n"
"x= ={(continue continue { ( struct continue { ( ++ name5 name5 ) ( name5 name5 n\n"
"ame5 ( name5 struct ( name5 name5 < ) ) ( default ) { name4 != name5 name5 name5\n"
" ( name5 name5 name5 ( { 1 >= void { ( ()) } 1 name3 return >= >= ( ) >= name5 (\n"
" name5 name6 :nam00 [ ()])}))})})})};\n"
"}"), SYNTAX);
}
// #8752 (segmentation fault)
void garbageCode199() {
ASSERT_THROW_INTERNAL(checkCode("d f(){e n00e0[]n00e0&" "0+f=0}"), SYNTAX);
}
// #8757
void garbageCode200() {
ASSERT_THROW_INTERNAL(checkCode("(){e break,{(case)!{e:[]}}}"), SYNTAX);
}
// #8873
void garbageCode201() {
ASSERT_THROW_INTERNAL(checkCode("void f() { std::string s=\"abc\"; return s + }"), SYNTAX);
}
// #8907
void garbageCode202() {
ASSERT_THROW_INTERNAL(checkCode("void f() { UNKNOWN_MACRO(return); }"), UNKNOWN_MACRO);
ASSERT_THROW_INTERNAL(checkCode("void f() { UNKNOWN_MACRO(throw); }"), UNKNOWN_MACRO);
ignore_errout();
}
void garbageCode203() { // #8972 (segmentation fault)
ASSERT_THROW_INTERNAL(checkCode("{ > () {} }"), SYNTAX);
(void)checkCode("template <> a > ::b();");
}
void garbageCode204() {
ASSERT_THROW_INTERNAL(checkCode("template <a, = b<>()> c; template <a> a as() {} as<c<>>();"), SYNTAX);
}
void garbageCode205() {
ASSERT_THROW_INTERNAL(checkCode("class CodeSnippetsEvent : public wxCommandEvent {\n"
"public :\n"
" CodeSnippetsEvent ( wxEventType commandType = wxEventType , int id = 0 ) ;\n"
" CodeSnippetsEvent ( const CodeSnippetsEvent & event ) ;\n"
"virtual wxEvent * Clone ( ) const { return new CodeSnippetsEvent ( * this ) ; }\n"
"private :\n"
" int m_SnippetID ;\n"
"} ;\n"
"const wxEventType wxEVT_CODESNIPPETS_GETFILELINKS = wxNewEventType ( )\n"
"CodeSnippetsEvent :: CodeSnippetsEvent ( wxEventType commandType , int id )\n"
": wxCommandEvent ( commandType , id ) {\n"
"}\n"
"CodeSnippetsEvent :: CodeSnippetsEvent ( const CodeSnippetsEvent & Event )\n"
": wxCommandEvent ( Event )\n"
", m_SnippetID ( 0 ) {\n"
"}"),
INTERNAL);
}
void garbageCode206() {
ASSERT_EQUALS("[test.cpp:1] syntax error: operator", getSyntaxError("void foo() { for (auto operator new : int); }"));
ASSERT_EQUALS("[test.cpp:1] syntax error", getSyntaxError("void foo() { for (a operator== :) }"));
}
void garbageCode207() { // #8750
ASSERT_THROW_INTERNAL(checkCode("d f(){(.n00e0(return%n00e0''('')));}"), SYNTAX);
}
void garbageCode208() { // #8753
ASSERT_THROW_INTERNAL(checkCode("d f(){(for(((((0{t b;((((((((()))))))))}))))))}"), SYNTAX);
}
void garbageCode209() { // #8756
ASSERT_THROW_INTERNAL(checkCode("{(- -##0xf/-1 0)[]}"), SYNTAX);
}
void garbageCode210() { // #8762
ASSERT_THROW_INTERNAL(checkCode("{typedef typedef c n00e0[]c000(;n00e0&c000)}"), SYNTAX);
}
void garbageCode211() { // #8764
ASSERT_THROW_INTERNAL(checkCode("{typedef f typedef[]({typedef e e,>;typedef(((typedef<typedef|)))})}"), SYNTAX);
}
void garbageCode212() { // #8765
ASSERT_THROW_INTERNAL(checkCode("{(){}[]typedef r n00e0[](((n00e0 0((;()))))){(0 typedef n00e0 bre00 n00e0())}[]();typedef n n00e0()[],(bre00)}"), SYNTAX);
}
void garbageCode213() { // #8758
ASSERT_THROW_INTERNAL(checkCode("{\"\"[(1||)];}"), SYNTAX);
}
void garbageCode214() { // segmentation fault
(void)checkCode("THIS FILE CONTAINS VARIOUS TEXT");
}
void garbageCode215() { // daca@home script with extension .c
ASSERT_THROW_INTERNAL(checkCode("a = [1,2,3];"), SYNTAX);
}
void garbageCode216() { // #7884 (out-of-memory)
(void)checkCode("template<typename> struct A {};\n"
"template<typename...T> struct A<T::T...> {}; \n"
"A<int> a;");
}
void garbageCode217() { // #10011
ASSERT_THROW_INTERNAL(checkCode("void f() {\n"
" auto p;\n"
" if (g(p)) {}\n"
" assert();\n"
"}"), AST);
}
void garbageCode218() { // #8763
ASSERT_THROW_INTERNAL(checkCode("d f(){t n0000 const[]n0000+0!=n0000,(0)}"), SYNTAX);
}
void garbageCode219() { // #10101
(void)checkCode("typedef void (*func) (addr) ;\n"
"void bar(void) {\n"
" func f;\n"
" f & = (func)42;\n"
"}\n"); // don't crash
ignore_errout(); // we are not interested in the output
}
void garbageCode220() { // #6832
ASSERT_THROW_INTERNAL(checkCode("(){(){{()}}return;{switch()0 case(){}break;l:()}}\n"), SYNTAX); // don't crash
}
void garbageCode221() {
ASSERT_THROW_INTERNAL(checkCode("struct A<0<;\n"), SYNTAX); // don't crash
}
void garbageCode222() { // #10763
ASSERT_THROW_INTERNAL(checkCode("template<template<class>\n"), SYNTAX); // don't crash
}
void garbageCode223() { // #11639
ASSERT_THROW_INTERNAL(checkCode("struct{}*"), SYNTAX); // don't crash
}
void garbageCode224() {
ASSERT_THROW_INTERNAL(checkCode("void f(){ auto* b = dynamic_cast<const }"), SYNTAX); // don't crash
ASSERT_EQUALS("", errout_str());
ASSERT_THROW_INTERNAL(checkCode("void f(){ auto* b = dynamic_cast x; }"), SYNTAX);
ignore_errout();
}
void garbageCode225() {
ASSERT_THROW_INTERNAL(checkCode("int n() { c * s0, 0 s0 = c(sizeof = ) }"), SYNTAX);
ASSERT_THROW_INTERNAL(checkCode("int n() { c * s0, 0 s0 = c(sizeof |= ) }"), SYNTAX);
}
void garbageCode226() {
ASSERT_THROW_INTERNAL(checkCode("int a() { (b((c)`)) } {}"), SYNTAX); // #11638
ASSERT_THROW_INTERNAL(checkCode("int a() { (b((c)\\)) } {}"), SYNTAX);
ASSERT_THROW_INTERNAL(checkCode("int a() { (b((c)@)) } {}"), SYNTAX);
}
void garbageCode227() { // #12615
ASSERT_NO_THROW(checkCode("f(&S::operator=);"));
}
void syntaxErrorFirstToken() {
ASSERT_THROW_INTERNAL(checkCode("&operator(){[]};"), SYNTAX); // #7818
ASSERT_THROW_INTERNAL(checkCode("*(*const<> (size_t); foo) { } *(*const (size_t)() ; foo) { }"), SYNTAX); // #6858
ASSERT_THROW_INTERNAL(checkCode(">{ x while (y) z int = }"), SYNTAX); // #4175
ASSERT_THROW_INTERNAL(checkCode("&p(!{}e x){({(0?:?){({})}()})}"), SYNTAX); // #7118
ASSERT_THROW_INTERNAL(checkCode("<class T> { struct { typename D4:typename Base<T*> }; };"), SYNTAX); // #3533
ASSERT_THROW_INTERNAL(checkCode(" > template < . > struct Y < T > { = } ;\n"), SYNTAX); // #6108
}
void syntaxErrorLastToken() {
ASSERT_THROW_INTERNAL(checkCode("int *"), SYNTAX); // #7821
ASSERT_THROW_INTERNAL(checkCode("x[y]"), SYNTAX); // #2986
ASSERT_THROW_INTERNAL(checkCode("( ) &"), SYNTAX);
ASSERT_THROW_INTERNAL(checkCode("|| #if #define <="), SYNTAX); // #2601
ASSERT_THROW_INTERNAL(checkCode("f::y:y : <x::"), SYNTAX); // #6613
ASSERT_THROW_INTERNAL(checkCode("a \"b\" not_eq \"c\""), SYNTAX); // #6720
ASSERT_THROW_INTERNAL(checkCode("(int arg2) { } { } typedef void (func_type) (int, int); typedef func_type&"), SYNTAX); // #6738
ASSERT_THROW_INTERNAL(checkCode("&g[0]; { (g[0] 0) } =", false), SYNTAX); // #6744
ASSERT_THROW_INTERNAL(checkCode("{ { void foo() { struct }; { }; } }; struct S { } f =", false), SYNTAX); // #6753
ASSERT_THROW_INTERNAL(checkCode("{ { ( ) } P ( ) ^ { } { } { } ( ) } 0"), SYNTAX); // #6772
ASSERT_THROW_INTERNAL(checkCode("+---+"), SYNTAX); // #6948
ASSERT_THROW_INTERNAL(checkCode("template<>\n"), SYNTAX);
ASSERT_THROW_INTERNAL(checkCode("++4++ + + E++++++++++ + ch " "tp.oed5[.]"), SYNTAX); // #7074
ASSERT_THROW_INTERNAL(checkCode("d a(){f s=0()8[]s?():0}*()?:0", false), SYNTAX); // #7236
ASSERT_THROW_INTERNAL(checkCode("!2 : #h2 ?:", false), SYNTAX); // #7769
ASSERT_THROW_INTERNAL(checkCode("--"), SYNTAX);
ASSERT_THROW_INTERNAL(checkCode("volatile true , test < test < #ifdef __ppc__ true ,"), SYNTAX); // #4169
ASSERT_THROW_INTERNAL(checkCode("a,b--\n"), SYNTAX); // #2847
ASSERT_THROW_INTERNAL(checkCode("x a[0] ="), SYNTAX); // #2682
ASSERT_THROW_INTERNAL(checkCode("auto_ptr<x>\n"), SYNTAX); // #2967
ASSERT_THROW_INTERNAL(checkCode("char a[1]\n"), SYNTAX); // #2865
ASSERT_THROW_INTERNAL(checkCode("<><<"), SYNTAX); // #2612
ASSERT_THROW_INTERNAL(checkCode("z<y<x>"), SYNTAX); // #2831
ASSERT_THROW_INTERNAL(checkCode("><,f<i,"), SYNTAX); // #2835
ASSERT_THROW_INTERNAL(checkCode("0; (a) < (a)"), SYNTAX); // #2875
ASSERT_THROW_INTERNAL(checkCode(" ( * const ( size_t ) ; foo )"), SYNTAX); // #6135
ASSERT_THROW_INTERNAL(checkCode("({ (); strcat(strcat(() ()) ()) })"), SYNTAX); // #6686
ASSERT_THROW_INTERNAL(checkCode("%: return ; ()"), SYNTAX); // #3441
ASSERT_THROW_INTERNAL(checkCode("__attribute__((destructor)) void"), SYNTAX); // #7816
ASSERT_THROW_INTERNAL(checkCode("1 *p = const"), SYNTAX); // #3512
ASSERT_THROW_INTERNAL(checkCode("sizeof"), SYNTAX); // #2599
ASSERT_THROW_INTERNAL(checkCode(" enum struct"), SYNTAX); // #6718
ASSERT_THROW_INTERNAL(checkCode("{(){(())}}r&const"), SYNTAX); // #7321
ASSERT_THROW_INTERNAL(checkCode("int"), SYNTAX);
ASSERT_THROW_INTERNAL(checkCode("struct A :\n"), SYNTAX); // #2591
ASSERT_THROW_INTERNAL(checkCode("{} const const\n"), SYNTAX); // #2637
ASSERT_THROW_INTERNAL(checkCode("re2c: error: line 14, column 4: can only difference char sets"), SYNTAX);
// ASSERT_THROW( , InternalError)
}
void syntaxErrorCase() {
// case must be inside switch block
ASSERT_THROW_INTERNAL(checkCode("void f() { switch (a) {}; case 1: }"), SYNTAX); // #8184
ASSERT_THROW_INTERNAL(checkCode("struct V : { public case {} ; struct U : U void { V *f (int x) (x) } }"), SYNTAX); // #5120
ASSERT_THROW_INTERNAL(checkCode("void f() { 0 0; }"), SYNTAX);
ASSERT_THROW_INTERNAL(checkCode("void f() { true 0; }"), SYNTAX);
ASSERT_THROW_INTERNAL(checkCode("void f() { 'a' 0; }"), SYNTAX);
ASSERT_THROW_INTERNAL(checkCode("void f() { 1 \"\"; }"), SYNTAX);
}
void syntaxErrorFuzzerCliType1() {
ASSERT_THROW_INTERNAL(checkCode("void f(){x=0,return return''[]()}"), SYNTAX);
ASSERT_THROW_INTERNAL(checkCode("void f(){x='0'++'0'(return)[];}"), SYNTAX); // #9063
(void)checkCode("void f(){*(int *)42=0;}"); // no syntax error
ignore_errout(); // we are not interested in the output
ASSERT_THROW_INTERNAL(checkCode("void f() { x= 'x' > typedef name5 | ( , ;){ } (); }"), SYNTAX); // #9067
ASSERT_THROW_INTERNAL(checkCode("void f() { x= {}( ) ( 'x')[ ] (); }"), SYNTAX); // #9068
ASSERT_THROW_INTERNAL(checkCode("void f() { x= y{ } name5 y[ ] + y ^ name5 ^ name5 for ( ( y y y && y y y && name5 ++ int )); }"), SYNTAX); // #9069
}
void cliCode() {
// #8913
ASSERT_NO_THROW(checkCode(
"public ref class LibCecSharp : public CecCallbackMethods {\n"
"array<CecAdapter ^> ^ FindAdapters(String ^ path) {}\n"
"bool GetDeviceInformation(String ^ port, LibCECConfiguration ^configuration, uint32_t timeoutMs) {\n"
"bool bReturn(false);\n"
"}\n"
"};"));
ignore_errout(); // we are not interested in the output
}
void enumTrailingComma() {
ASSERT_THROW_INTERNAL(checkCode("enum ssl_shutdown_t {ssl_shutdown_none = 0,ssl_shutdown_close_notify = , } ;"), SYNTAX); // #8079
}
void nonGarbageCode1() {
ASSERT_NO_THROW(checkCode("template <class T> class List {\n"
"public:\n"
" List();\n"
" virtual ~List();\n"
" template< class Predicate > u_int DeleteIf( const Predicate &pred );\n"
"};\n"
"template< class T >\n"
"template< class Predicate > int\n"
"List<T>::DeleteIf( const Predicate &pred )\n"
"{}"));
ignore_errout(); // we are not interested in the output
// #8749
ASSERT_NO_THROW(checkCode(
"struct A {\n"
" void operator+=(A&) && = delete;\n"
"};"));
// #8788
ASSERT_NO_THROW(checkCode(
"struct foo;\n"
"void f() {\n"
" auto fn = []() -> foo* { return new foo(); };\n"
"}"));
ignore_errout(); // we do not care about the output
}
};
REGISTER_TEST(TestGarbage)
| null |
995 | cpp | cppcheck | testunusedvar.cpp | test/testunusedvar.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "checkunusedvar.h"
#include "errortypes.h"
#include "fixture.h"
#include "helpers.h"
#include "preprocessor.h"
#include "settings.h"
#include "standards.h"
#include "tokenize.h"
#include <list>
#include <string>
#include <vector>
class TestUnusedVar : public TestFixture {
public:
TestUnusedVar() : TestFixture("TestUnusedVar") {}
private:
const Settings settings = settingsBuilder().severity(Severity::style).checkLibrary().library("std.cfg").build();
void run() override {
TEST_CASE(isRecordTypeWithoutSideEffects);
TEST_CASE(cleanFunction);
TEST_CASE(emptyclass); // #5355 - False positive: Variable is not assigned a value.
TEST_CASE(emptystruct); // #5355 - False positive: Variable is not assigned a value.
TEST_CASE(structmember1);
TEST_CASE(structmember2);
TEST_CASE(structmember3);
TEST_CASE(structmember4);
TEST_CASE(structmember5);
TEST_CASE(structmember6);
TEST_CASE(structmember7);
TEST_CASE(structmember8);
TEST_CASE(structmember9); // #2017 - struct is inherited
TEST_CASE(structmember_extern); // No false positives for extern structs
TEST_CASE(structmember10);
TEST_CASE(structmember11); // #4168 - initialization with {} / passed by address to unknown function
TEST_CASE(structmember12); // #7179 - FP unused structmember
TEST_CASE(structmember13); // #3088 - __attribute__((packed))
TEST_CASE(structmember14); // #6508 - (struct x){1,2,..}
TEST_CASE(structmember15); // #3088 - #pragma pack(1)
TEST_CASE(structmember_sizeof);
TEST_CASE(structmember16); // #10485
TEST_CASE(structmember17); // #10591
TEST_CASE(structmember18); // #10684
TEST_CASE(structmember19); // #10826, #10848, #10852
TEST_CASE(structmember20); // #10737
TEST_CASE(structmember21); // #4759
TEST_CASE(structmember22); // #11016
TEST_CASE(structmember23);
TEST_CASE(structmember24); // #10847
TEST_CASE(structmember25);
TEST_CASE(structmember26); // #13345
TEST_CASE(structmember27); // #13367
TEST_CASE(structmember_macro);
TEST_CASE(classmember);
TEST_CASE(localvar1);
TEST_CASE(localvar2);
TEST_CASE(localvar3);
TEST_CASE(localvar4);
TEST_CASE(localvar5);
TEST_CASE(localvar6);
TEST_CASE(localvar8);
TEST_CASE(localvar9); // ticket #1605
TEST_CASE(localvar10);
TEST_CASE(localvar11);
TEST_CASE(localvar12);
TEST_CASE(localvar13); // ticket #1640
TEST_CASE(localvar14); // ticket #5
TEST_CASE(localvar15);
TEST_CASE(localvar16); // ticket #1709
TEST_CASE(localvar17); // ticket #1720
TEST_CASE(localvar18); // ticket #1723
TEST_CASE(localvar19); // ticket #1776
TEST_CASE(localvar20); // ticket #1799
TEST_CASE(localvar21); // ticket #1807
TEST_CASE(localvar22); // ticket #1811
TEST_CASE(localvar23); // ticket #1808
TEST_CASE(localvar24); // ticket #1803
TEST_CASE(localvar25); // ticket #1729
TEST_CASE(localvar26); // ticket #1894
TEST_CASE(localvar27); // ticket #2160
TEST_CASE(localvar28); // ticket #2205
TEST_CASE(localvar29); // ticket #2206 (array initialization)
TEST_CASE(localvar30);
TEST_CASE(localvar31); // ticket #2286
TEST_CASE(localvar32); // ticket #2330
TEST_CASE(localvar33); // ticket #2346
TEST_CASE(localvar34); // ticket #2368
TEST_CASE(localvar35); // ticket #2535
TEST_CASE(localvar36); // ticket #2805
TEST_CASE(localvar37); // ticket #3078
TEST_CASE(localvar38);
TEST_CASE(localvar39); // ticket #3454
TEST_CASE(localvar40); // ticket #3473
TEST_CASE(localvar41); // ticket #3603
TEST_CASE(localvar42); // ticket #3742
TEST_CASE(localvar43); // ticket #3602
TEST_CASE(localvar44); // ticket #4020
TEST_CASE(localvar45); // ticket #4899
TEST_CASE(localvar46); // ticket #5491 (C++11 style initialization)
TEST_CASE(localvar47); // ticket #6603
TEST_CASE(localvar48); // ticket #6954
TEST_CASE(localvar49); // ticket #7594
TEST_CASE(localvar50); // ticket #6261 : dostuff(cond ? buf1 : buf2)
TEST_CASE(localvar51); // ticket #8128 - FN : tok = tok->next();
TEST_CASE(localvar52);
TEST_CASE(localvar53); // continue
TEST_CASE(localvar54); // ast, {}
TEST_CASE(localvar55);
TEST_CASE(localvar56);
TEST_CASE(localvar57); // #8974 - increment
TEST_CASE(localvar58); // #9901 - increment false positive
TEST_CASE(localvar59); // #9737
TEST_CASE(localvar60);
TEST_CASE(localvar61); // #9407
TEST_CASE(localvar62); // #10824
TEST_CASE(localvar63); // #6928
TEST_CASE(localvar64); // #9997
TEST_CASE(localvar65); // #9876, #10006
TEST_CASE(localvar66); // #11143
TEST_CASE(localvar67); // #9946
TEST_CASE(localvar68);
TEST_CASE(localvar69);
TEST_CASE(localvar70);
TEST_CASE(localvar71);
TEST_CASE(localvarloops); // loops
TEST_CASE(localvaralias1);
TEST_CASE(localvaralias2); // ticket #1637
TEST_CASE(localvaralias3); // ticket #1639
TEST_CASE(localvaralias4); // ticket #1643
TEST_CASE(localvaralias5); // ticket #1647
TEST_CASE(localvaralias6); // ticket #1729
TEST_CASE(localvaralias7); // ticket #1732
TEST_CASE(localvaralias8);
TEST_CASE(localvaralias9); // ticket #1996
TEST_CASE(localvaralias10); // ticket #2004
TEST_CASE(localvaralias11); // ticket #4423 - iterator
TEST_CASE(localvaralias12); // ticket #4394
TEST_CASE(localvaralias13); // ticket #4487
TEST_CASE(localvaralias14); // ticket #5619
TEST_CASE(localvaralias15); // ticket #6315
TEST_CASE(localvaralias16);
TEST_CASE(localvaralias17); // ticket #8911
TEST_CASE(localvaralias18); // ticket #9234 - iterator
TEST_CASE(localvaralias19); // ticket #9828
TEST_CASE(localvaralias20); // ticket #10966
TEST_CASE(localvaralias21);
TEST_CASE(localvaralias22);
TEST_CASE(localvaralias23);
TEST_CASE(localvarasm);
TEST_CASE(localvarstatic);
TEST_CASE(localvarextern);
TEST_CASE(localvardynamic1);
TEST_CASE(localvardynamic2); // ticket #2904
TEST_CASE(localvardynamic3); // ticket #3467
TEST_CASE(localvararray1); // ticket #2780
TEST_CASE(localvararray2); // ticket #3438
TEST_CASE(localvararray3); // ticket #3980
TEST_CASE(localvararray4); // ticket #4839
TEST_CASE(localvararray5); // ticket #7092
TEST_CASE(localvararray6);
TEST_CASE(localvarstring1);
TEST_CASE(localvarstring2); // ticket #2929
TEST_CASE(localvarconst1);
TEST_CASE(localvarconst2);
TEST_CASE(localvarreturn); // ticket #9167
TEST_CASE(localvarmaybeunused);
TEST_CASE(localvarthrow); // ticket #3687
TEST_CASE(localVarStd);
TEST_CASE(localVarClass);
TEST_CASE(localVarSmartPtr);
// Don't give false positives for variables in structs/unions
TEST_CASE(localvarStruct1);
TEST_CASE(localvarStruct2);
TEST_CASE(localvarStruct3);
TEST_CASE(localvarStruct5);
TEST_CASE(localvarStruct6);
TEST_CASE(localvarStruct7);
TEST_CASE(localvarStruct8);
TEST_CASE(localvarStruct9);
TEST_CASE(localvarStruct10);
TEST_CASE(localvarStruct11); // 10095
TEST_CASE(localvarStruct12); // #10495
TEST_CASE(localvarStruct13); // #10398
TEST_CASE(localvarStruct14);
TEST_CASE(localvarStructArray);
TEST_CASE(localvarUnion1);
TEST_CASE(localvarOp); // Usage with arithmetic operators
TEST_CASE(localvarInvert); // Usage with inverted variable
TEST_CASE(localvarIf); // Usage in if
TEST_CASE(localvarIfElse); // return tmp1 ? tmp2 : tmp3;
TEST_CASE(localvarDeclaredInIf);
TEST_CASE(localvarOpAssign); // a |= b;
TEST_CASE(localvarFor); // for ( ; var; )
TEST_CASE(localvarForEach); // #4155 - BOOST_FOREACH, hlist_for_each, etc
TEST_CASE(localvarShift1); // 1 >> var
TEST_CASE(localvarShift3); // x << y
TEST_CASE(localvarCast);
TEST_CASE(localvarClass);
TEST_CASE(localvarUnused);
TEST_CASE(localvarFunction); // ticket #1799
TEST_CASE(localvarIfNOT); // #3104 - if ( NOT var )
TEST_CASE(localvarAnd); // #3672
TEST_CASE(localvarSwitch); // #3744 - false positive when localvar is used in switch
TEST_CASE(localvarNULL); // #4203 - Setting NULL value is not redundant - it is safe
TEST_CASE(localvarUnusedGoto); // #4447, #4558 goto
TEST_CASE(localvarRangeBasedFor); // #7075
TEST_CASE(localvarAssignInWhile);
TEST_CASE(localvarTemplate); // #4955 - variable is used as template parameter
TEST_CASE(localvarFuncPtr); // #7194
TEST_CASE(localvarAddr); // #7477
TEST_CASE(localvarDelete);
TEST_CASE(localvarLambda); // #8941, #8948
TEST_CASE(localvarStructuredBinding); // #10368
TEST_CASE(localvarCppInitialization);
TEST_CASE(localvarCpp11Initialization);
TEST_CASE(chainedAssignment); // #5466
TEST_CASE(crash1);
TEST_CASE(crash2);
TEST_CASE(crash3);
TEST_CASE(usingNamespace); // #4585
TEST_CASE(lambdaFunction); // #5078
TEST_CASE(namespaces); // #7557
TEST_CASE(bracesInitCpp11);// #7895 - "int var{123}" initialization
TEST_CASE(argument);
TEST_CASE(argumentClass);
TEST_CASE(escapeAlias); // #9150
TEST_CASE(volatileData); // #9280
TEST_CASE(globalData);
}
#define functionVariableUsage(...) functionVariableUsage_(__FILE__, __LINE__, __VA_ARGS__)
#define checkStructMemberUsage(...) checkStructMemberUsage_(__FILE__, __LINE__, __VA_ARGS__)
void checkStructMemberUsage_(const char* file, int line, const char code[], const std::list<Directive>* directives = nullptr, const Settings *s = nullptr) {
const Settings *settings1 = s ? s : &settings;
// Tokenize..
SimpleTokenizer tokenizer(*settings1, *this);
if (directives)
tokenizer.setDirectives(*directives);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
// Check for unused variables..
CheckUnusedVar checkUnusedVar(&tokenizer, settings1, this);
(checkUnusedVar.checkStructMemberUsage)();
}
#define checkStructMemberUsageP(...) checkStructMemberUsageP_(__FILE__, __LINE__, __VA_ARGS__)
void checkStructMemberUsageP_(const char* file, int line, const char code[]) {
std::vector<std::string> files(1, "test.cpp");
Tokenizer tokenizer(settings, *this);
PreprocessorHelper::preprocess(code, files, tokenizer, *this);
// Tokenizer..
ASSERT_LOC(tokenizer.simplifyTokens1(""), file, line);
// Check for unused variables..
CheckUnusedVar checkUnusedVar(&tokenizer, &settings, this);
(checkUnusedVar.checkStructMemberUsage)();
}
#define checkFunctionVariableUsageP(...) checkFunctionVariableUsageP_(__FILE__, __LINE__, __VA_ARGS__)
void checkFunctionVariableUsageP_(const char* file, int line, const char code[], const char* filename = "test.cpp") {
std::vector<std::string> files(1, filename);
Tokenizer tokenizer(settings, *this);
PreprocessorHelper::preprocess(code, files, tokenizer, *this);
// Tokenizer..
ASSERT_LOC(tokenizer.simplifyTokens1(""), file, line);
// Check for unused variables..
CheckUnusedVar checkUnusedVar(&tokenizer, &settings, this);
(checkUnusedVar.checkFunctionVariableUsage)();
}
void isRecordTypeWithoutSideEffects() {
functionVariableUsage(
"class A {};\n"
"void f() {\n"
" A a;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Unused variable: a\n", errout_str());
functionVariableUsage(
"class A {};\n"
"class B {\n"
"public:\n"
" A a;\n"
"};\n"
"void f() {\n"
" B b;\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (style) Unused variable: b\n", errout_str());
functionVariableUsage(
"class C {\n"
"public:\n"
" C() = default;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (style) Unused variable: c\n", errout_str());
functionVariableUsage(
"class D {\n"
"public:\n"
" D() {}\n"
"};\n"
"void f() {\n"
" D d;\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (style) Unused variable: d\n", errout_str());
functionVariableUsage(
"class E {\n"
"public:\n"
" uint32_t u{1};\n"
"};\n"
"void f() {\n"
" E e;\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (style) Unused variable: e\n", errout_str());
functionVariableUsage(
"class F {\n"
"public:\n"
" F() : x(0) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" F f;\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (style) Unused variable: f\n", errout_str());
functionVariableUsage(
"class F {\n"
"public:\n"
" F() : x{0} {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" F f;\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (style) Unused variable: f\n", errout_str());
functionVariableUsage(
"int y = 0;\n"
"class F {\n"
"public:\n"
" F() : x(y) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" F f;\n"
"}");
ASSERT_EQUALS("[test.cpp:8]: (style) Unused variable: f\n", errout_str());
functionVariableUsage(
"int y = 0;"
"class F {\n"
"public:\n"
" F() : x(++y) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" F f;\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (style) Unused variable: f\n", errout_str());
functionVariableUsage(
"int y = 0;"
"class F {\n"
"public:\n"
" F() : x(--y) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" F f;\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (style) Unused variable: f\n", errout_str());
functionVariableUsage(
"int y = 0;"
"class F {\n"
"public:\n"
" F() : x(y+=1) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" F f;\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (style) Unused variable: f\n", errout_str());
functionVariableUsage(
"int y = 0;"
"class F {\n"
"public:\n"
" F() : x(y-=1) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" F f;\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (style) Unused variable: f\n", errout_str());
// non-empty constructor
functionVariableUsage(
"class F {\n"
"public:\n"
" F() {\n"
" int i = 0;\n"
" (void) i;"
" }\n"
"};\n"
"void f() {\n"
" F f;\n"
"}");
TODO_ASSERT_EQUALS("error", "", errout_str());
// constructor with hidden definition
functionVariableUsage(
"class B {\n"
"public:\n"
" B();\n"
"};\n"
"class A {\n"
" B* b = new B;\n"
"};\n"
"int main() {\n"
" A a;\n"
"}");
ASSERT_EQUALS("", errout_str());
// side-effect variable
functionVariableUsage(
"class F {\n"
"public:\n"
" F() {\n"
" int i = 0;\n"
" (void) i;"
" }\n"
"};\n"
"class G {\n"
"public:\n"
" F f;\n"
"};\n"
"void f() {\n"
" G g;\n"
"}");
ASSERT_EQUALS("", errout_str());
// side-effect variable in initialization list
functionVariableUsage(
"class F {\n"
"public:\n"
" F() {\n"
" int i = 0;\n"
" (void) i;"
" }\n"
"};\n"
"class G {\n"
"public:\n"
" G() : f(F()) {}\n"
" F f;"
"};\n"
"void f() {\n"
" G g;\n"
"}");
ASSERT_EQUALS("", errout_str());
// unknown variable type
functionVariableUsage(
"class H {\n"
"public:\n"
" unknown_type u{1};\n"
"};\n"
"void f() {\n"
" H h;\n"
"}");
ASSERT_EQUALS("", errout_str());
// unknown variable type in initialization list
functionVariableUsage(
"class H {\n"
"public:\n"
" H() : x{0}, u(1) {}\n"
" int x;"
" unknown_type u;\n"
"};\n"
"void f() {\n"
" H h;\n"
"}");
ASSERT_EQUALS("", errout_str());
// unknown variable type used for initialization
functionVariableUsage(
"unknown_type y = 0;\n"
"class F {\n"
"public:\n"
" F() : x(y) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" F f;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage(
"int sideEffectFunc();\n"
"class F {\n"
"public:\n"
" F() : x(sideEffectFunc()) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" F f;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage(
"class F {\n"
"public:\n"
" F() : x(++unknownValue) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" F f;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage(
"class F {\n"
"public:\n"
" F() : x(--unknownValue) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" F f;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage(
"class F {\n"
"public:\n"
" F() : x(unknownValue+=1) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" F f;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage(
"class F {\n"
"public:\n"
" F() : x(unknownValue-=1) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" F f;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage(
"struct S {\n"
" static void f() { std::cout << \"f()\"; }\n"
" ~S() { f(); }\n"
"};\n"
"void g() {\n"
" S s;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
functionVariableUsage( // #11109
"class D { public: D(); };\n"
"class E { public: ~E(); };\n"
"class F {\n"
"public:\n"
" F();\n"
" ~F();\n"
"};\n"
"void f() {\n"
" D d;\n"
" E e;\n"
" F f;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void cleanFunction() {
// unknown function
functionVariableUsage(
"class F {\n"
"public:\n"
" F() : x(func()) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" F f;\n"
"}");
ASSERT_EQUALS("", errout_str());
// function forward declaration
functionVariableUsage(
"int func();\n"
"class C {\n"
"public:\n"
" C() : x(func()) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("", errout_str());
// return literal
functionVariableUsage(
"int func() { return 1; }\n"
"class C {\n"
"public:\n"
" C() : x(func()) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("[test.cpp:8]: (style) Unused variable: c\n", errout_str());
// return variable without side effects
functionVariableUsage(
"int func() {\n"
" int x = 1;\n"
" return x;\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func()) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("[test.cpp:11]: (style) Unused variable: c\n", errout_str());
// return variable with side effects
functionVariableUsage(
"int func() {\n"
" unknown_type x = 1;\n"
" return x;\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func()) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("", errout_str());
// return unknown variable
functionVariableUsage(
"int func() {\n"
" return unknown_var;\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func()) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("", errout_str());
// return variable is global, but not changed
functionVariableUsage(
"int x = 1;\n"
"int func() {\n"
" return x;\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func()) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("[test.cpp:11]: (style) Unused variable: c\n", errout_str());
// changing global variable in return
functionVariableUsage(
"int x = 1;\n"
"int func() {\n"
" return x++;\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func()) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("", errout_str());
// changing global variable in function body
functionVariableUsage(
"int x = 1;\n"
"int func() {\n"
" x++;\n"
" return 1;\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func()) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage(
"int x = 1;\n"
"int func() {\n"
" --x;\n"
" return 1;\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func()) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage(
"int x = 1;\n"
"int func() {\n"
" x += 2;\n"
" return 1;\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func()) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage(
"int x = 1;\n"
"int func() {\n"
" x = 2;\n"
" return 1;\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func()) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("", errout_str());
// global variable use in function body without change
functionVariableUsage(
"int global = 1;\n"
"int func() {\n"
" int x = global + 1;\n"
" return x;\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func()) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("[test.cpp:12]: (style) Unused variable: c\n", errout_str());
// changing global array variable in function body
functionVariableUsage(
"int x[] = {0, 1, 3};\n"
"int func() {\n"
" x[0] = 4;\n"
" return 1;\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func()) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage(
"int x[] = {0, 1, 3};\n"
"int func() {\n"
" *x = 2;\n"
" return 1;\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func()) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage(
"int x[] = {0, 1, 3};\n"
"int func() {\n"
" *(x) = 2;\n"
" return 1;\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func()) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("", errout_str());
// pointer arithmetic on global array
functionVariableUsage(
"int x[] = {0, 1, 3};\n"
"int func() {\n"
" *(x + 1) = 2;\n"
" return 1;\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func()) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage(
"int x[][] = {{0, 1}, {2, 3}};\n"
"int func() {\n"
" *((x + 1) + 1) = 4;\n"
" return 1;\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func()) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage(
"int x[] = {0, 1, 3};\n"
"int func() {\n"
" int local = *(x + 1);\n"
" (void) local;\n"
" return 1;\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func()) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("[test.cpp:13]: (style) Unused variable: c\n", errout_str());
functionVariableUsage(
"int x[] = {0, 1, 3};\n"
"int func() {\n"
" int* local = x + 2;\n"
" (void) local;\n"
" return 1;\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func()) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("[test.cpp:13]: (style) Unused variable: c\n", errout_str());
functionVariableUsage(
"int x[] = {0, 1, 3};\n"
"int func() {\n"
" int* local = x + 2;\n"
" return *local;\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func()) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage(
"int x[] = {0, 1, 3};\n"
"int func() {\n"
" return *(x + 1);\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func()) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("", errout_str());
// changing local variable
functionVariableUsage(
"int func() {\n"
" int x = 1;\n"
" x = 2;\n"
" x++;\n"
" return x;\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func()) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("[test.cpp:13]: (style) Unused variable: c\n", errout_str());
// variable of user-defined class without side effects
functionVariableUsage(
"class A {};\n"
"A func() {\n"
" A a;\n"
" return a;\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func()) {}\n"
" A x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("[test.cpp:12]: (style) Unused variable: c\n", errout_str());
// variable of user-defined class with side effects
functionVariableUsage(
"class A {\n"
"public:\n"
" unknown_type u{1};\n"
"};\n"
"int func() {\n"
" A a;\n"
" return 1;\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func()) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("", errout_str());
// unknown type variable
functionVariableUsage(
"int func() {\n"
" unknown_type a;\n"
" return 1;\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func()) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("", errout_str());
// nested clean function call
functionVariableUsage(
"int another_func() { return 1;}\n"
"int func() {\n"
" another_func();\n"
" return 1;\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func()) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("[test.cpp:12]: (style) Unused variable: c\n", errout_str());
// nested side-effects function call
functionVariableUsage(
"int global = 1;"
"int another_func() {\n"
" global++;\n"
" return global;}\n"
"int func() {\n"
" another_func();\n"
" return 1;\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func()) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("", errout_str());
// unknown nested function
functionVariableUsage(
"int func() {\n"
" unknown_func();\n"
" return 1;\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func()) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("", errout_str());
// clean function recursion
functionVariableUsage(
"int func(int i) {\n"
" if (i != 2) {\n"
" func(i++);\n"
" return 2;\n"
" }\n"
" return i;\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func(0)) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("[test.cpp:14]: (style) Unused variable: c\n", errout_str());
// indirect clean function recursion
functionVariableUsage(
"void another_func() {\n"
" func(0);\n"
"}\n"
"int func(int i) {\n"
" if (i != 2) {\n"
" another_func();\n"
" return 2;\n"
" }\n"
" return i;\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func(0)) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("[test.cpp:17]: (style) Unused variable: c\n", errout_str());
// side-effect function recursion
functionVariableUsage(
"int global = 1;\n"
"int func(int i) {\n"
" if (i != 2) {\n"
" global++;\n"
" func(i++);\n"
" return 2;\n"
" }\n"
" return i;\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func(0)) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("", errout_str());
// multiple returns (side-effect & clean)
functionVariableUsage(
"int func(int i) {\n"
" if (i == 0) { return 0;}\n"
" else { return unknownSideEffectFunction(); }\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func(0)) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("", errout_str());
// multiple clean returns
functionVariableUsage(
"int func(int i) {\n"
" if (i == 0) { return 0;}\n"
" else { return i; }\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func(0)) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("[test.cpp:11]: (style) Unused variable: c\n", errout_str());
// multiple side-effect returns
functionVariableUsage(
"int func(int i) {\n"
" if (i == 0) { return unknownSideEffectFunction();}\n"
" else { return unknown_var; }\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func(0)) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("", errout_str());
// argument return
functionVariableUsage(
"int func(int i) {\n"
" return i;\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func(0)) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("[test.cpp:10]: (style) Unused variable: c\n", errout_str());
// global variable modifying through function argument
functionVariableUsage(
"char buf[10];\n"
"int func(char* p) {\n"
" *p = 0;\n"
" return 1;\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func(buf)) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("", errout_str());
// global variable modifying through local pointer
functionVariableUsage(
"int global = 1;\n"
"int func() {\n"
" int* p = &global;\n"
" *p = 0;\n"
" return 1;\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func()) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("", errout_str());
// global variable assigning to local pointer, but not modifying
functionVariableUsage(
"int global = 1;\n"
"int func() {\n"
" int* p = &global;\n"
" (void) p;\n"
" return 1;\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func()) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("[test.cpp:13]: (style) Unused variable: c\n", errout_str());
// global struct variable modification
functionVariableUsage(
"struct S { int x; } s;\n"
"int func() {\n"
" s.x = 1;\n"
" return 1;\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func()) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("", errout_str());
// global struct variable without modification
functionVariableUsage(
"struct S { int x; } s;\n"
"int func() {\n"
" int y = s.x + 1;\n"
" return y;\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func()) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("[test.cpp:12]: (style) Unused variable: c\n", errout_str());
// global pointer to struct variable modification
functionVariableUsage(
"struct S { int x; };\n"
"struct S* s = new(struct S);\n"
"int func() {\n"
" s->x = 1;\n"
" return 1;\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func()) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("", errout_str());
// global pointer to struct variable without modification
functionVariableUsage(
"struct S { int x; };\n"
"struct S* s = new(struct S);\n"
"int func() {\n"
" int y = s->x + 1;\n"
" return y;\n"
"}\n"
"class C {\n"
"public:\n"
" C() : x(func()) {}\n"
" int x;\n"
"};\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("[test.cpp:13]: (style) Unused variable: c\n", errout_str());
}
// #5355 - False positive: Variable is not assigned a value.
void emptyclass() {
functionVariableUsage("class Carla {\n"
"};\n"
"class Fred : Carla {\n"
"};\n"
"void foo() {\n"
" Fred fred;\n"
" throw fred;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
// #5355 - False positive: Variable is not assigned a value.
void emptystruct() {
functionVariableUsage("struct Fred {\n"
"};\n"
"void foo() {\n"
" Fred fred;\n"
" throw fred;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void structmember1() {
checkStructMemberUsage("struct abc\n"
"{\n"
" int a;\n"
" int b;\n"
" int c;\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (style) struct member 'abc::a' is never used.\n"
"[test.cpp:4]: (style) struct member 'abc::b' is never used.\n"
"[test.cpp:5]: (style) struct member 'abc::c' is never used.\n", errout_str());
checkStructMemberUsage("union abc\n"
"{\n"
" int a;\n"
" int b;\n"
" int c;\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (style) union member 'abc::a' is never used.\n"
"[test.cpp:4]: (style) union member 'abc::b' is never used.\n"
"[test.cpp:5]: (style) union member 'abc::c' is never used.\n", errout_str());
}
void structmember2() {
checkStructMemberUsage("struct ABC\n"
"{\n"
" int a;\n"
" int b;\n"
" int c;\n"
"};\n"
"\n"
"void foo()\n"
"{\n"
" struct ABC abc;\n"
" int a = abc.a;\n"
" int b = abc.b;\n"
" int c = abc.c;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void structmember3() {
checkStructMemberUsage("struct ABC\n"
"{\n"
" int a;\n"
" int b;\n"
" int c;\n"
"};\n"
"\n"
"static struct ABC abc[] = { {1, 2, 3} };\n"
"\n"
"void foo()\n"
"{\n"
" int a = abc[0].a;\n"
" int b = abc[0].b;\n"
" int c = abc[0].c;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void structmember4() {
checkStructMemberUsage("struct ABC\n"
"{\n"
" const int a;\n"
"};\n"
"\n"
"void foo()\n"
"{\n"
" ABC abc;\n"
" if (abc.a == 2);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void structmember5() {
checkStructMemberUsage("struct AB\n"
"{\n"
" int a;\n"
" int b;\n"
" void reset()\n"
" {\n"
" a = 1;\n"
" b = 2;\n"
" }\n"
"};\n"
"\n"
"void foo()\n"
"{\n"
" struct AB ab;\n"
" ab.reset();\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void structmember6() {
checkStructMemberUsage("struct AB\n"
"{\n"
" int a;\n"
" int b;\n"
"};\n"
"\n"
"void foo(char *buf)\n"
"{\n"
" struct AB *ab = (struct AB *)&buf[10];\n"
"}");
ASSERT_EQUALS("", errout_str());
checkStructMemberUsage("struct AB\n"
"{\n"
" int a;\n"
" int b;\n"
"};\n"
"\n"
"void foo(char *buf)\n"
"{\n"
" struct AB *ab = (AB *)&buf[10];\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void structmember7() {
checkStructMemberUsage("struct AB\n"
"{\n"
" int a;\n"
" int b;\n"
"};\n"
"\n"
"void foo(struct AB *ab)\n"
"{\n"
" ab->a = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) struct member 'AB::b' is never used.\n", errout_str());
checkStructMemberUsage("struct AB\n"
"{\n"
" int a;\n"
" int b;\n"
"};\n"
"\n"
"void foo(struct AB _shuge *ab)\n"
"{\n"
" ab->a = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) struct member 'AB::b' is never used.\n", errout_str());
}
void structmember8() {
checkStructMemberUsage("struct AB\n"
"{\n"
" int a;\n"
" int b;\n"
"};\n"
"\n"
"void foo(char *ab)\n"
"{\n"
" ((AB *)ab)->b = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void structmember9() {
checkStructMemberUsage("struct base {\n"
" int a;\n"
"};\n"
"\n"
"struct derived : public base {"
"}");
ASSERT_EQUALS("", errout_str());
}
void structmember10() {
// Fred may have some useful side-effects
checkStructMemberUsage("struct abc {\n"
" Fred fred;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void structmember11() { // #4168
checkStructMemberUsage("struct abc { int x; };\n"
"struct abc s = {0};\n"
"void f() { do_something(&s); }");
ASSERT_EQUALS("", errout_str());
checkStructMemberUsage("struct abc { int x; };\n"
"struct abc s = {0};\n"
"void f() { }");
TODO_ASSERT_EQUALS("abc::x is not used", "", errout_str());
}
void structmember12() { // #7179
checkStructMemberUsage("#include <stdio.h>\n"
"struct\n"
"{\n"
" union\n"
" {\n"
" struct\n"
" {\n"
" int a;\n"
" } struct1;\n"
" };\n"
"} var = {0};\n"
"int main(int argc, char *argv[])\n"
"{\n"
" printf(\"var.struct1.a = %d\", var.struct1.a);\n"
" return 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void structmember13() { // #3088 - struct members required by hardware
checkStructMemberUsage("struct S {\n"
" int x;\n"
"} __attribute__((packed));");
ASSERT_EQUALS("", errout_str());
}
void structmember14() { // #6508
checkStructMemberUsage("struct bstr { char *bstart; size_t len; };\n"
"struct bstr bstr0(void) {\n"
" return (struct bstr){\"hello\",6};\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void structmember15() { // #3088
std::list<Directive> directives;
directives.emplace_back("test.cpp", 1, "#pragma pack(1)");
checkStructMemberUsage("\nstruct Foo { int x; int y; };", &directives);
ASSERT_EQUALS("", errout_str());
}
void structmember_extern() {
// extern struct => no false positive
checkStructMemberUsage("extern struct AB\n"
"{\n"
" int a;\n"
" int b;\n"
"} ab;\n"
"\n"
"void foo()\n"
"{\n"
" ab.b = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
// global linkage => no false positive
checkStructMemberUsage("struct AB\n"
"{\n"
" int a;\n"
" int b;\n"
"} ab;\n"
"\n"
"void foo()\n"
"{\n"
" ab.b = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
// static linkage => error message
checkStructMemberUsage("static struct AB\n"
"{\n"
" int a;\n"
" int b;\n"
"} ab;\n"
"\n"
"void foo()\n"
"{\n"
" ab.b = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) struct member 'AB::a' is never used.\n", errout_str());
checkStructMemberUsage("struct A\n"
"{\n"
" static const int a = 0;\n"
"};\n"
"\n"
"int foo()\n"
"{\n"
" return A::a;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void structmember_sizeof() {
checkStructMemberUsage("struct Header {\n"
" uint8_t message_type;\n"
"}\n"
"\n"
"input.skip(sizeof(Header));");
ASSERT_EQUALS("", errout_str());
checkStructMemberUsage("struct Header {\n"
" uint8_t message_type;\n"
"}\n"
"\n"
"input.skip(sizeof(struct Header));");
ASSERT_EQUALS("", errout_str());
checkStructMemberUsage("struct S { int a, b, c; };\n" // #6561
"int f(FILE * fp) {\n"
" S s;\n"
" ::fread(&s, sizeof(S), 1, fp);\n"
" return s.b;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void structmember16() {
checkStructMemberUsage("struct S {\n"
" static const int N = 128;\n" // <- used
" char E[N];\n" // <- not used
"};\n");
ASSERT_EQUALS("[test.cpp:3]: (style) struct member 'S::E' is never used.\n", errout_str());
}
void structmember17() { // #10591
checkStructMemberUsage("struct tagT { int i; };\n"
"void f() {\n"
" struct tagT t{};\n"
" t.i = 0;\n" // <- used
" g(t);\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkStructMemberUsage("typedef struct tagT { int i; } typeT;\n"
"void f() {\n"
" struct typeT t{};\n"
" t.i = 0;\n" // <- used
" g(t);\n"
"};\n");
ASSERT_EQUALS("", errout_str());
checkStructMemberUsage("struct T { int i; };\n"
"void f() {\n"
" struct T t{};\n"
" t.i = 0;\n" // <- used
" g(t);\n"
"};\n");
ASSERT_EQUALS("", errout_str()); // due to removeMacroInClassDef()
}
void structmember18() { // #10684
checkStructMemberUsage("struct S { uint8_t padding[500]; };\n"
"static S s = { 0 };\n"
"uint8_t f() {\n"
" uint8_t* p = (uint8_t*)&s;\n"
" return p[10];\n"
"};\n");
ASSERT_EQUALS("[test.cpp:1]: (style) struct member 'S::padding' is never used.\n", errout_str());
checkStructMemberUsage("struct S { uint8_t padding[500]; };\n"
"uint8_t f(const S& s) {\n"
" std::cout << &s;\n"
" auto p = reinterpret_cast<const uint8_t*>(&s);\n"
" return p[10];\n"
"};\n");
ASSERT_EQUALS("[test.cpp:1]: (style) struct member 'S::padding' is never used.\n", errout_str());
checkStructMemberUsage("struct S { int i, j; };\n" // #11577
"void f(S s) {\n"
" void* p = (void*)&s;\n"
" if (s.i) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:1]: (style) struct member 'S::j' is never used.\n", errout_str());
}
void structmember19() {
checkStructMemberUsage("class C {};\n" // #10826
"struct S {\n"
" char* p;\n"
" std::string str;\n"
" C c;\n"
"};\n"
"void f(S* s) {}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) struct member 'S::p' is never used.\n"
"[test.cpp:4]: (style) struct member 'S::str' is never used.\n"
"[test.cpp:5]: (style) struct member 'S::c' is never used.\n",
errout_str());
checkStructMemberUsage("class C {};\n"
"struct S {\n"
" char* p;\n"
" std::string str;\n"
" C c;\n"
"};\n"
"void f(S& s) {}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) struct member 'S::p' is never used.\n"
"[test.cpp:4]: (style) struct member 'S::str' is never used.\n"
"[test.cpp:5]: (style) struct member 'S::c' is never used.\n",
errout_str());
checkStructMemberUsage("struct S {\n" // #10848
" struct T {\n"
" int i;\n"
" } t[2];\n"
"};\n"
"S s[1];\n"
"int f() {\n"
" return s[0].t[1].i;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkStructMemberUsage("struct S { int a; };\n"
"struct T { S s; };\n"
"int f(const T** tp) {\n"
" return tp[0]->s.a;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkStructMemberUsage("struct S { int a; };\n"
"int f(const S* sp) {\n"
" return (*sp).a; \n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkStructMemberUsage("struct S { int a; };\n"
"int f(const S** spp) {\n"
" return spp[0]->a;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkStructMemberUsage("struct S { int a; };\n"
"int f(const S** spp) {\n"
" return spp[0][0].a;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkStructMemberUsage("struct S { int a; };\n"
"int f(const S* sp) {\n"
" return sp[0].a;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkStructMemberUsage("struct S { int a; };\n"
"int f(const S* sp) {\n"
" return sp->a;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkStructMemberUsage("typedef struct { int i; } A;\n"
"typedef struct { std::vector<A> v; } B;\n"
"const A& f(const std::vector<const B*>& b, int idx) {\n"
" const A& a = b[0]->v[idx];\n"
" return a;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:1]: (style) struct member 'A::i' is never used.\n",
errout_str());
/*const*/ Settings s = settings;
s.enforcedLang = Standards::Language::C;
checkStructMemberUsage("struct A {\n" // #10852
" struct B {\n"
" int x;\n"
" } b;\n"
"} a;\n"
"void f() {\n"
" struct B* pb = &a.b;\n"
" pb->x = 1;\n"
"}\n", nullptr, &s);
ASSERT_EQUALS("", errout_str());
checkStructMemberUsage("union U {\n"
" struct A {\n"
" struct B {\n"
" int x;\n"
" } b;\n"
" } a;\n"
" struct C {\n"
" short s[2];\n"
" } c;\n"
"} u;\n"
"void f() {\n"
" struct B* pb = &u.a.b;\n"
" pb->x = 1;\n"
" struct C* pc = &u.c;\n"
" pc->s[0] = 1;\n"
"}\n", nullptr, &s);
ASSERT_EQUALS("", errout_str());
}
void structmember20() { // #10737
checkStructMemberUsage("void f() {\n"
" {\n"
" }\n"
" {\n"
" struct S { int a; };\n"
" S s{};\n"
" {\n"
" if (s.a) {}\n"
" }\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void structmember21() { // #4759
checkStructMemberUsage("class C {\n"
"public:\n"
" int f() { return 0; }\n"
"};\n"
"C c;\n"
"int g() {\n"
" return c.f();\n"
"}\n"
"struct S {\n"
" int f;\n"
"};\n");
ASSERT_EQUALS("[test.cpp:10]: (style) struct member 'S::f' is never used.\n", errout_str());
checkStructMemberUsage("struct A { int i; };\n"
"struct B { struct A* pA; };");
ASSERT_EQUALS("[test.cpp:1]: (style) struct member 'A::i' is never used.\n"
"[test.cpp:2]: (style) struct member 'B::pA' is never used.\n",
errout_str());
}
void structmember22() { // #11016
checkStructMemberUsage("struct A { bool b; };\n"
"void f(const std::vector<A>& v) {\n"
" std::vector<A>::const_iterator it = b.begin();\n"
" if (it->b) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void structmember23() {
checkStructMemberUsage("namespace N {\n"
" struct S { std::string s; };\n"
"}\n"
"std::string f() {\n"
" std::map<int, N::S> m = { { 0, { \"abc\" } } };\n"
" return m[0].s;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void structmember24() { // #10847
checkStructMemberUsage("struct S { std::map<int, S*> m; };\n"
"std::map<int, S*> u;\n"
"std::map<int, S*>::iterator f() {\n"
" return u.find(0)->second->m.begin();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkStructMemberUsage("struct S { int i; };\n"
"void f() {\n"
" std::map<int, S> m = { { 0, S() } };\n"
" m[0].i = 1;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkStructMemberUsage("struct S { bool b; };\n"
"std::vector<S> v;\n"
"bool f() {\n"
" return v.begin()->b;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkStructMemberUsage("int f(int s) {\n" // #10587
" const struct S { int a, b; } Map[] = { { 0, 1 }, { 2, 3 } };\n"
" auto it = std::find_if(std::begin(Map), std::end(Map), [&](const auto& m) { return s == m.a; });\n"
" if (it != std::end(Map))\n"
" return it->b;\n"
" return 0;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkStructMemberUsage("int f(int s) {\n"
" const struct S { int a, b; } Map[] = { { 0, 1 }, { 2, 3 } };\n"
" for (auto&& m : Map)\n"
" if (m.a == s)\n"
" return m.b;\n"
" return 0;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkStructMemberUsage("struct R { bool b{ false }; };\n" // #11539
"void f(std::optional<R> r) {\n"
" if (r.has_value())\n"
" std::cout << r->b;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void structmember25() {
checkStructMemberUsage("struct S {\n" // #12485
" S* p;\n"
" int i;\n"
"};\n"
"struct T {\n"
" S s;\n"
" int j;\n"
"};\n");
ASSERT_EQUALS("[test.cpp:2]: (style) struct member 'S::p' is never used.\n"
"[test.cpp:3]: (style) struct member 'S::i' is never used.\n"
"[test.cpp:6]: (style) struct member 'T::s' is never used.\n"
"[test.cpp:7]: (style) struct member 'T::j' is never used.\n",
errout_str());
}
void structmember26() { // #13345
checkStructMemberUsage("struct foobar {\n"
" char unused;\n"
"};\n"
"size_t offset_unused = offsetof(struct foobar, unused);\n");
ASSERT_EQUALS("", errout_str());
}
void structmember27() { // #13367
checkStructMemberUsage("typedef struct pathNode_s {\n"
" struct pathNode_s* next;\n"
"} pathNode_t;\n"
"void f() {\n"
" x<pathNode_t, offsetof( pathNode_t, next )> y;\n"
"}\n");
ASSERT_EQUALS("", // don't crash
errout_str());
}
void structmember_macro() {
checkStructMemberUsageP("#define S(n) struct n { int a, b, c; };\n"
"S(unused);\n");
ASSERT_EQUALS("", errout_str());
}
void classmember() {
checkStructMemberUsage("class C {\n"
" int i{};\n"
"};\n");
ASSERT_EQUALS("[test.cpp:2]: (style) class member 'C::i' is never used.\n", errout_str());
checkStructMemberUsage("class C {\n"
" int i{}, j{};\n"
"public:\n"
" int& get() { return i; }\n"
"};\n");
ASSERT_EQUALS("[test.cpp:2]: (style) class member 'C::j' is never used.\n", errout_str());
checkStructMemberUsage("class C {\n"
"private:\n"
" int i;\n"
"};\n"
"class D : public C {};\n");
ASSERT_EQUALS("[test.cpp:3]: (style) class member 'C::i' is never used.\n", errout_str());
checkStructMemberUsage("class C {\n"
"public:\n"
" int i;\n"
"};\n"
"class D : C {};\n");
ASSERT_EQUALS("[test.cpp:3]: (style) class member 'C::i' is never used.\n", errout_str());
checkStructMemberUsage("class C {\n"
"public:\n"
" int i;\n"
"};\n"
"class D : public C {};\n");
ASSERT_EQUALS("", errout_str());
}
void functionVariableUsage_(const char* file, int line, const char code[], bool cpp = true) {
// Tokenize..
SimpleTokenizer tokenizer(settings, *this);
ASSERT_LOC(tokenizer.tokenize(code, cpp), file, line);
// Check for unused variables..
CheckUnusedVar checkUnusedVar(&tokenizer, &settings, this);
checkUnusedVar.checkFunctionVariableUsage();
}
void localvar1() {
// extracttests.disable
functionVariableUsage("void foo()\n"
"{\n"
" int i = 0;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3]: (style) Variable 'i' is assigned a value that is never used.\n"
"[test.cpp:3]: (style) Variable 'i' is assigned a value that is never used.\n", // duplicate
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int i(0);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'i' is assigned a value that is never used.\n", errout_str());
// if a is undefined then Cppcheck can't determine if "int i(a)" is a
// * variable declaration
// * function declaration
functionVariableUsage("void foo()\n"
"{\n"
" int i(a);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'i' is assigned a value that is never used.\n", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int j = 0;\n"
" int i(j);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Variable 'i' is assigned a value that is never used.\n", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int j = 0;\n"
" int & i = j;\n"
" x(j);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Variable 'i' is assigned a value that is never used.\n", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int j = 0;\n"
" const int & i = j;\n"
" x(j);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Variable 'i' is assigned a value that is never used.\n", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int j = 0;\n"
" int & i(j);\n"
" x(j);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Variable 'i' is assigned a value that is never used.\n", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int j = 0;\n"
" const int & i(j);\n"
" x(j);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Variable 'i' is assigned a value that is never used.\n", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int * j = Data;\n"
" int * i(j);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Variable 'i' is assigned a value that is never used.\n", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int * j = Data;\n"
" const int * i(j);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Variable 'i' is assigned a value that is never used.\n", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" bool i = false;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3]: (style) Variable 'i' is assigned a value that is never used.\n"
"[test.cpp:3]: (style) Variable 'i' is assigned a value that is never used.\n", // duplicate
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" bool i = true;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3]: (style) Variable 'i' is assigned a value that is never used.\n"
"[test.cpp:3]: (style) Variable 'i' is assigned a value that is never used.\n", // duplicate
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" char *i;\n"
" i = fgets();\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Variable 'i' is assigned a value that is never used.\n", errout_str());
// undefined variables are not reported because they may be classes with constructors
functionVariableUsage("undefined foo()\n"
"{\n"
" undefined i = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (information) --check-library: Provide <type-checks><unusedvar> configuration for undefined\n", errout_str());
functionVariableUsage("undefined foo()\n"
"{\n"
" undefined i = 0;\n"
"}\n",
false);
ASSERT_EQUALS(
"[test.c:3]: (style) Variable 'i' is assigned a value that is never used.\n"
"[test.c:3]: (style) Variable 'i' is assigned a value that is never used.\n", // duplicate
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int i = undefined;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3]: (style) Variable 'i' is assigned a value that is never used.\n"
"[test.cpp:3]: (style) Variable 'i' is assigned a value that is never used.\n", // duplicate
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int * i = Data;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3]: (style) Variable 'i' is assigned a value that is never used.\n"
"[test.cpp:3]: (style) Variable 'i' is assigned a value that is never used.\n", // duplicate
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" void * i = Data;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3]: (style) Variable 'i' is assigned a value that is never used.\n"
"[test.cpp:3]: (style) Variable 'i' is assigned a value that is never used.\n", // duplicate
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" const void * i = Data;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3]: (style) Variable 'i' is assigned a value that is never used.\n"
"[test.cpp:3]: (style) Variable 'i' is assigned a value that is never used.\n", // duplicate
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" struct S * i = DATA;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3]: (style) Variable 'i' is assigned a value that is never used.\n"
"[test.cpp:3]: (style) Variable 'i' is assigned a value that is never used.\n", // duplicate
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" const struct S * i = DATA;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3]: (style) Variable 'i' is assigned a value that is never used.\n"
"[test.cpp:3]: (style) Variable 'i' is assigned a value that is never used.\n", // duplicate
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" struct S & i = j;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'i' is assigned a value that is never used.\n", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" const struct S & i = j;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'i' is assigned a value that is never used.\n", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" undefined * i = X;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3]: (style) Variable 'i' is assigned a value that is never used.\n"
"[test.cpp:3]: (style) Variable 'i' is assigned a value that is never used.\n", // duplicate
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int i = 0;\n"
" int j = i;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:4]: (style) Variable 'j' is assigned a value that is never used.\n"
"[test.cpp:4]: (style) Variable 'j' is assigned a value that is never used.\n", // duplicate
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int i[10] = { 0 };\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'i' is assigned a value that is never used.\n", errout_str());
functionVariableUsage("void foo(int n)\n"
"{\n"
" int i[n] = { 0 };\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'i' is assigned a value that is never used.\n", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" char i[10] = \"123456789\";\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'i' is assigned a value that is never used.\n", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" char *i = \"123456789\";\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3]: (style) Variable 'i' is assigned a value that is never used.\n"
"[test.cpp:3]: (style) Variable 'i' is assigned a value that is never used.\n", // duplicate
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int i = 0;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3]: (style) Variable 'i' is assigned a value that is never used.\n"
"[test.cpp:3]: (style) Variable 'i' is assigned a value that is never used.\n", // duplicate
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int i = 0,code=10;\n"
" for(i = 0; i < 10; i++) {\n"
" std::cout<<code<<std::endl;\n"
" code += 2;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int i = 0,code=10,d=10;\n"
" for(i = 0; i < 10; i++) {\n"
" std::cout<<code<<std::endl;\n"
" code += 2;\n"
" d = code;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'd' is assigned a value that is never used.\n"
"[test.cpp:7]: (style) Variable 'd' is assigned a value that is never used.\n",
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int i = 0,code=10,d=10;\n"
" for(i = 0; i < 10; i++) {\n"
" std::cout<<code<<std::endl;\n"
" code += 2;\n"
" g(d);\n"
" d = code;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int i = 0,code=10,d=10;\n"
" for(i = 0; i < 10; i++) {\n"
" std::cout<<code<<std::endl;\n"
" code += 2;\n"
" if (i == 3) {\n"
" return d;\n"
" }\n"
" d = code;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int i = 0,a=10,b=20;\n"
" for(i = 0; i < 10; i++) {\n"
" std::cout<<a<<std::endl;\n"
" int tmp=a;\n"
" a=b;\n"
" b=tmp;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int code=10;\n"
" while(code < 20) {\n"
" std::cout<<code<<std::endl;\n"
" code += 2;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int code=10,d=10;\n"
" while(code < 20) {\n"
" std::cout<<code<<std::endl;\n"
" code += 2;\n"
" d += code;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'd' is assigned a value that is never used.\n"
"[test.cpp:7]: (style) Variable 'd' is assigned a value that is never used.\n", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int code=10,d=10;\n"
" while(code < 20) {\n"
" std::cout<<code<<std::endl;\n"
" code += 2;\n"
" g(d);\n"
" d += code;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int code=10,d=10;\n"
" while(code < 20) {\n"
" std::cout<<code<<std::endl;\n"
" code += 2;\n"
" if (i == 3) {\n"
" return d;\n"
" }\n"
" d += code;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int a=10,b=20;\n"
" while(a != 30) {\n"
" std::cout<<a<<std::endl;\n"
" int tmp=a;\n"
" a=b;\n"
" b=tmp;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int code=10;\n"
" do {\n"
" std::cout<<code<<std::endl;\n"
" code += 2;\n"
" } while(code < 20);\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int code=10,d=10;\n"
" do {\n"
" std::cout<<code<<std::endl;\n"
" code += 2;\n"
" d += code;\n"
" } while(code < 20);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'd' is assigned a value that is never used.\n"
"[test.cpp:7]: (style) Variable 'd' is assigned a value that is never used.\n", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int code=10,d=10;\n"
" do {\n"
" std::cout<<code<<std::endl;\n"
" code += 2;\n"
" g(d);\n"
" d += code;\n"
" } while(code < 20);\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int code=10,d=10;\n"
" do {\n"
" std::cout<<code<<std::endl;\n"
" code += 2;\n"
" if (i == 3) {\n"
" return d;\n"
" }\n"
" d += code;\n"
" } while(code < 20);\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int a=10,b=20;\n"
" do {\n"
" std::cout<<a<<std::endl;\n"
" int tmp=a;\n"
" a=b;\n"
" b=tmp;\n"
" } while( a!=30 );\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int code=10;\n"
" for(int i=0; i < 10; i++) {\n"
" if(true) {\n"
" std::cout<<code<<std::endl;\n"
" code += 2;\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int code=10;\n"
" for(int i=0; i < 10; i++) {\n"
" if(true) {\n"
" std::cout<<code<<std::endl;\n"
" }\n"
" code += 2;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int code=10;\n"
" while(code < 20) {\n"
" if(true) {\n"
" std::cout<<code<<std::endl;\n"
" code += 2;\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int code=10;\n"
" do {\n"
" if(true) {\n"
" std::cout<<code<<std::endl;\n"
" code += 2;\n"
" }\n"
" } while(code < 20);\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo(int j = 0) {\n" // #5985 - default function parameters should not affect checking results
" int i = 0;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:2]: (style) Variable 'i' is assigned a value that is never used.\n"
"[test.cpp:2]: (style) Variable 'i' is assigned a value that is never used.\n", // duplicate
errout_str());
// extracttests.enable
}
void localvar2() {
// extracttests.disable: uninitialized variables and stuff
functionVariableUsage("int foo()\n"
"{\n"
" int i;\n"
" return i;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'i' is not assigned a value.\n", errout_str());
functionVariableUsage("bool foo()\n"
"{\n"
" bool i;\n"
" return i;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'i' is not assigned a value.\n", errout_str());
// undefined variables are not reported because they may be classes with constructors
functionVariableUsage("undefined foo()\n"
"{\n"
" undefined i;\n"
" return i;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("undefined foo()\n"
"{\n"
" undefined i;\n"
" return i;\n"
"}\n",
false);
ASSERT_EQUALS("[test.c:3]: (style) Variable 'i' is not assigned a value.\n", errout_str());
functionVariableUsage("undefined *foo()\n"
"{\n"
" undefined * i;\n"
" return i;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'i' is not assigned a value.\n", errout_str());
functionVariableUsage("int *foo()\n"
"{\n"
" int * i;\n"
" return i;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'i' is not assigned a value.\n", errout_str());
functionVariableUsage("const int *foo()\n"
"{\n"
" const int * i;\n"
" return i;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'i' is not assigned a value.\n", errout_str());
functionVariableUsage("struct S *foo()\n"
"{\n"
" struct S * i;\n"
" return i;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'i' is not assigned a value.\n", errout_str());
functionVariableUsage("const struct S *foo()\n"
"{\n"
" const struct S * i;\n"
" return i;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'i' is not assigned a value.\n", errout_str());
// assume f() can write a
functionVariableUsage("void foo()\n"
"{\n"
" int a[10];\n"
" f(a[0]);\n"
"}");
ASSERT_EQUALS("", errout_str());
// assume f() can write a
functionVariableUsage("void foo()\n"
"{\n"
" int a[10];\n"
" f(a[0], 0);\n"
"}");
ASSERT_EQUALS("", errout_str());
// assume f() can write a
functionVariableUsage("void foo()\n"
"{\n"
" int a[10];\n"
" f(0, a[0]);\n"
"}");
ASSERT_EQUALS("", errout_str());
// assume f() can write a
functionVariableUsage("void foo()\n"
"{\n"
" int a[10];\n"
" f(0, a[0], 0);\n"
"}");
ASSERT_EQUALS("", errout_str());
// f() can not write a (not supported yet)
functionVariableUsage("void f(const int & i) { }\n"
"void foo()\n"
"{\n"
" int a[10];\n"
" f(a[0]);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:4]: (style) Variable 'a' is not assigned a value.\n",
"", errout_str());
// f() writes a
functionVariableUsage("void f(int & i) { }\n"
"void foo()\n"
"{\n"
" int a[10];\n"
" f(a[0]);\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void f(int * i);\n"
"void foo()\n"
"{\n"
" int a[10];\n"
" f(a+1);\n"
"}");
ASSERT_EQUALS("", errout_str());
// extracttests.enable
}
void localvar3() {
functionVariableUsage("void foo(int abc)\n"
"{\n"
" int i;\n"
" if ( abc )\n"
" ;\n"
" else i = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (style) Variable 'i' is assigned a value that is never used.\n", errout_str());
}
void localvar4() {
functionVariableUsage("void foo()\n"
"{\n"
" int i = 0;\n"
" f(i);\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int i = 0;\n"
" f(&i);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvar5() {
functionVariableUsage("void foo()\n"
"{\n"
" int a = 0;\n"
" b = (char)a;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvar6() {
functionVariableUsage("void foo() {\n"
" int b[10];\n"
" for (int i=0;i<10;++i)\n"
" b[i] = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Variable 'b[i]' is assigned a value that is never used.\n", errout_str());
functionVariableUsage("void foo() {\n"
" int a = 0;\n"
" int b[10];\n"
" for (int i=0;i<10;++i)\n"
" b[i] = ++a;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (style) Variable 'b[i]' is assigned a value that is never used.\n", errout_str());
functionVariableUsage("void foo() {\n"
" int b[10];\n"
" for (int i=0;i<10;++i)\n"
" *(b+i) = 0;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:4]: (style) Variable '*(b+i)' is assigned a value that is never used.\n", "", errout_str());
functionVariableUsage("void f() {\n" // #11832, #11923
" int b;\n"
" *(&b) = 0;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable '*(&b)' is assigned a value that is never used.\n", errout_str());
}
void localvar8() {
functionVariableUsage("void foo()\n"
"{\n"
" int i;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Unused variable: i\n", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int i[2];\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Unused variable: i\n", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" void * i;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Unused variable: i\n", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" const void * i;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Unused variable: i\n", errout_str());
// extracttests.start: struct A {int x;};
functionVariableUsage("void foo()\n"
"{\n"
" A * i;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Unused variable: i\n", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" struct A * i;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Unused variable: i\n", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" const struct A * i;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Unused variable: i\n", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int * i[2];\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:3]: (style) Unused variable: i\n", "", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" const int * i[2];\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:3]: (style) Unused variable: i\n", "", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" void * i[2];\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:3]: (style) Unused variable: i\n", "", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" const void * i[2];\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:3]: (style) Unused variable: i\n", "", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" struct A * i[2];\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:3]: (style) Unused variable: i\n", "", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" const struct A * i[2];\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:3]: (style) Unused variable: i\n", "", errout_str());
functionVariableUsage("void foo(int n)\n"
"{\n"
" int i[n];\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Unused variable: i\n", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int i = 0;\n"
" int &j = i;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Variable 'j' is assigned a value that is never used.\n"
"[test.cpp:3]: (style) Variable 'i' is assigned a value that is never used.\n",
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int i;\n"
" int &j = i;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Variable 'j' is assigned a value that is never used.\n"
"[test.cpp:3]: (style) Unused variable: i\n", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int i;\n"
" int &j = i;\n"
" j = 0;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:5]: (style) Variable 'i' is assigned a value that is never used.\n",
"",
errout_str());
functionVariableUsage("double foo()\n"
"{\n"
" double i = 0.0;\n"
" const double j = i;\n"
" return j;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" A * i;\n"
" i->f();\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" char * i;\n"
" if (i);\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" char * i = 0;\n"
" if (i);\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" char * i = new char[10];\n"
" if (i);\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" char *i;\n"
" f(i);\n"
"}");
functionVariableUsage("int a;\n"
"void foo()\n"
"{\n"
" return &a;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int a[10];\n"
"void foo()\n"
"{\n"
" int *p = a;\n"
" for (int i = 0; i < 10; i++)\n"
" p[i] = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int a[10];\n"
"void foo()\n"
"{\n"
" int *p = &a[0];\n"
" for (int i = 0; i < 10; i++)\n"
" p[i] = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int a[10];\n"
" int x;\n"
" a[0] = 0;\n"
" x = a[0];\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (style) Variable 'x' is assigned a value that is never used.\n", errout_str());
// extracttests.start: int f();
functionVariableUsage("void foo()\n"
"{\n"
" int a, b, c;\n"
" a = b = c = f();\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Variable 'a' is assigned a value that is never used.\n"
"[test.cpp:4]: (style) Variable 'b' is assigned a value that is never used.\n"
"[test.cpp:4]: (style) Variable 'c' is assigned a value that is never used.\n",
errout_str());
functionVariableUsage("int * foo()\n"
"{\n"
" return &undefined[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvar9() {
// ticket #1605
functionVariableUsage("void foo()\n"
"{\n"
" int a[10];\n"
" for (int i = 0; i < 10; )\n"
" a[i++] = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (style) Variable 'a[i++]' is assigned a value that is never used.\n", errout_str());
}
void localvar10() {
functionVariableUsage("void foo(int x)\n"
"{\n"
" int i;\n"
" if (x) {\n"
" int i;\n"
" } else {\n"
" int i;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Unused variable: i\n"
"[test.cpp:5]: (style) Unused variable: i\n"
"[test.cpp:7]: (style) Unused variable: i\n", errout_str());
functionVariableUsage("void foo(int x)\n"
"{\n"
" int i;\n"
" if (x)\n"
" int i;\n"
" else\n"
" int i;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Unused variable: i\n"
"[test.cpp:5]: (style) Unused variable: i\n"
"[test.cpp:7]: (style) Unused variable: i\n", errout_str());
functionVariableUsage("void foo(int x)\n"
"{\n"
" int i;\n"
" if (x) {\n"
" int i;\n"
" } else {\n"
" int i = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:7]: (style) Variable 'i' is assigned a value that is never used.\n"
"[test.cpp:3]: (style) Unused variable: i\n"
"[test.cpp:5]: (style) Unused variable: i\n"
"[test.cpp:7]: (style) Variable 'i' is assigned a value that is never used.\n", // duplicate
errout_str());
functionVariableUsage("void foo(int x)\n"
"{\n"
" int i;\n"
" if (x) {\n"
" int i;\n"
" } else {\n"
" int i;\n"
" }\n"
" i = 1;\n"
"}");
ASSERT_EQUALS("[test.cpp:9]: (style) Variable 'i' is assigned a value that is never used.\n"
"[test.cpp:5]: (style) Unused variable: i\n"
"[test.cpp:7]: (style) Unused variable: i\n", errout_str());
}
void localvar11() {
functionVariableUsage("void foo(int x)\n"
"{\n"
" int a = 0;\n"
" if (x == 1)\n"
" {\n"
" a = 123;\n" // redundant assignment
" return;\n"
" }\n"
" x = a;\n" // redundant assignment
"}");
ASSERT_EQUALS("[test.cpp:6]: (style) Variable 'a' is assigned a value that is never used.\n"
"[test.cpp:9]: (style) Variable 'x' is assigned a value that is never used.\n", errout_str());
// The variable 'a' is initialized. But the initialized value is
// never used. It is only initialized for security reasons.
functionVariableUsage("void foo(int x)\n"
"{\n"
" int a = 0;\n"
" if (x == 1)\n"
" a = 123;\n"
" else if (x == 2)\n"
" a = 456;\n"
" else\n"
" return;\n"
" x = a;\n"
"}");
ASSERT_EQUALS("[test.cpp:10]: (style) Variable 'x' is assigned a value that is never used.\n", errout_str());
}
void localvar12() {
// ticket #1574
functionVariableUsage("void foo()\n"
"{\n"
" int a, b, c, d, e, f;\n"
" a = b = c = d = e = f = 15;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:4]: (style) Variable 'a' is assigned a value that is never used.\n"
"[test.cpp:4]: (style) Variable 'b' is assigned a value that is never used.\n"
"[test.cpp:4]: (style) Variable 'c' is assigned a value that is never used.\n"
"[test.cpp:4]: (style) Variable 'd' is assigned a value that is never used.\n"
"[test.cpp:4]: (style) Variable 'e' is assigned a value that is never used.\n"
"[test.cpp:4]: (style) Variable 'f' is assigned a value that is never used.\n",
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int a, b, c = 0;\n"
" a = b = c;\n"
"\n"
"}");
TODO_ASSERT_EQUALS(
"[test.cpp:4]: (style) Variable 'a' is assigned a value that is never used.\n"
"[test.cpp:4]: (style) Variable 'b' is assigned a value that is never used.\n"
"[test.cpp:3]: (style) Variable 'c' is assigned a value that is never used.\n",
"[test.cpp:4]: (style) Variable 'a' is assigned a value that is never used.\n"
"[test.cpp:4]: (style) Variable 'b' is assigned a value that is never used.\n",
errout_str());
}
void localvar13() { // ticket #1640
// extracttests.start: struct OBJECT { int ySize; };
functionVariableUsage("void foo( OBJECT *obj )\n"
"{\n"
" int x;\n"
" x = obj->ySize / 8;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Variable 'x' is assigned a value that is never used.\n", errout_str());
}
void localvar14() {
// ticket #5
functionVariableUsage("void foo()\n"
"{\n"
" int a[10];\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Unused variable: a\n", errout_str());
}
void localvar15() {
functionVariableUsage("int foo()\n"
"{\n"
" int a = 5;\n"
" int b[a];\n"
" b[0] = 0;\n"
" return b[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int foo()\n"
"{\n"
" int a = 5;\n"
" int * b[a];\n"
" b[0] = &c;\n"
" return *b[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int * foo()\n"
"{\n"
" int a = 5;\n"
" const int * b[a];\n"
" b[0] = &c;\n"
" return b[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("struct B * foo()\n"
"{\n"
" int a = 5;\n"
" struct B * b[a];\n"
" b[0] = &c;\n"
" return b[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("const struct B * foo()\n"
"{\n"
" int a = 5;\n"
" const struct B * b[a];\n"
" b[0] = &c;\n"
" return b[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvar16() { // ticket #1709
functionVariableUsage("void foo()\n"
"{\n"
" char buf[5];\n"
" char *ptr = buf;\n"
" *(ptr++) = 0;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:5]: (style) Variable 'buf' is assigned a value that is never used.\n", "", errout_str());
// #3910
functionVariableUsage("void foo() {\n"
" char buf[5];\n"
" char *data[2];\n"
" data[0] = buf;\n"
" do_something(data);\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo() {\n"
" char buf1[5];\n"
" char buf2[5];\n"
" char *data[2];\n"
" data[0] = buf1;\n"
" data[1] = buf2;\n"
" do_something(data);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvar17() { // ticket #1720
// extracttests.disable
// Don't crash when checking the code below!
functionVariableUsage("void foo()\n"
"{\n"
" struct DATA *data = DATA;\n"
" char *k = data->req;\n"
" char *ptr;\n"
" char *line_start;\n"
" ptr = data->buffer;\n"
" line_start = ptr;\n"
" data->info = k;\n"
" line_start = ptr;\n"
"}");
ASSERT_EQUALS("[test.cpp:10]: (style) Variable 'line_start' is assigned a value that is never used.\n", errout_str());
// extracttests.enable
}
void localvar18() { // ticket #1723
functionVariableUsage("A::A(int iValue) {\n"
" UserDefinedException* pe = new UserDefinedException();\n"
" throw pe;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvar19() { // ticket #1776
functionVariableUsage("void foo() {\n"
" int a[10];\n"
" int c;\n"
" c = *(a);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Variable 'c' is assigned a value that is never used.\n"
"[test.cpp:2]: (style) Variable 'a' is not assigned a value.\n", errout_str());
}
void localvar20() { // ticket #1799
functionVariableUsage("void foo()\n"
"{\n"
" char c1 = 'c';\n"
" char c2[] = { c1 };\n"
" a(c2);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvar21() { // ticket #1807
functionVariableUsage("void foo()\n"
"{\n"
" char buffer[1024];\n"
" bar((void *)buffer);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvar22() { // ticket #1811
functionVariableUsage("int foo(int u, int v)\n"
"{\n"
" int h, i;\n"
" h = 0 ? u : v;\n"
" i = 1 ? u : v;\n"
" return h + i;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvar23() { // ticket #1808
functionVariableUsage("int foo(int c)\n"
"{\n"
" int a;\n"
" int b[10];\n"
" a = b[c] = 0;\n"
" return a;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (style) Variable 'b[c]' is assigned a value that is never used.\n", errout_str());
}
void localvar24() { // ticket #1803
functionVariableUsage("class MyException\n"
"{\n"
" virtual void raise() const\n"
" {\n"
" throw *this;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvar25() { // ticket #1729
functionVariableUsage("int main() {\n"
" int ppos = 1;\n"
" int pneg = 0;\n"
" const char*edge = ppos? \" +\" : pneg ? \" -\" : \"\";\n"
" printf(\"This should be a '+' -> %s\\n\", edge);\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvar26() { // ticket #1894
functionVariableUsage("int main() {\n"
" const Fred &fred = getfred();\n"
" int *p = fred.x();\n"
" *p = 0;"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvar27() { // ticket #2160
functionVariableUsage("void f(struct s *ptr) {\n"
" int param = 1;\n"
" ptr->param = param++;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'param' is assigned a value that is never used.\n", errout_str());
}
void localvar28() { // ticket #2205
functionVariableUsage("void f(char* buffer, int value) {\n"
" char* pos = buffer;\n"
" int size = value;\n"
" *(int*)pos = size;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvar29() { // ticket #2206
functionVariableUsage("void f() {\n"
" float s_ranges[] = { 0, 256 };\n"
" float* ranges[] = { s_ranges };\n"
" cout << ranges[0][0];\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvar30() { // ticket #2264
functionVariableUsage("void f() {\n"
" Engine *engine = e;\n"
" x->engine = engine->clone();\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvar31() { // ticket #2286
functionVariableUsage("void f() {\n"
" int x = 0;\n"
" a.x = x - b;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvar32() {
// ticket #2330 - fstream >> x
functionVariableUsage("void f() {\n"
" int x;\n"
" fstream &f = getfile();\n"
" f >> x;\n"
"}");
ASSERT_EQUALS("", errout_str());
// ticket #4596 - if (c >>= x) {}
functionVariableUsage("void f(int x) {\n"
" C c;\n" // possibly some stream class
" if (c >>= x) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (information) --check-library: Provide <type-checks><unusedvar> configuration for C\n", errout_str());
functionVariableUsage("void f(int x) {\n"
" C c;\n"
" if (c >>= x) {}\n"
"}", false);
ASSERT_EQUALS("[test.c:3]: (style) Variable 'c' is assigned a value that is never used.\n", errout_str());
functionVariableUsage("void f() {\n"
" int x, y;\n"
" std::cin >> x >> y;\n"
"}");
ASSERT_EQUALS("", errout_str());
// ticket #8494
functionVariableUsage("void f(C c) {\n"
" int x;\n"
" c & x;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvar33() { // ticket #2345
functionVariableUsage("void f() {\n"
" Abc* abc = getabc();\n"
" while (0 != (abc = abc->next())) {\n"
" ++nOldNum;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvar34() { // ticket #2368
functionVariableUsage("void f() {\n"
" int i = 0;\n"
" if (false) {\n"
" } else {\n"
" j -= i;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvar35() { // ticket #2535
functionVariableUsage("void f() {\n"
" int a, b;\n"
" x(1,a,b);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvar36() { // ticket #2805
functionVariableUsage("int f() {\n"
" int a, b;\n"
" a = 2 * (b = 3);\n"
" return a + b;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int f() {\n" // ticket #4318
" int a,b;\n"
" x(a, b=2);\n" // <- if param2 is passed-by-reference then b might be used in x
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int foo() {\n" // ticket #6147
" int a = 0;\n"
" bar(a=a+2);\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int foo() {\n" // ticket #6147
" int a = 0;\n"
" bar(a=2);\n"
"}");
TODO_ASSERT_EQUALS("error", "", errout_str());
functionVariableUsage("void bar(int);\n"
"int foo() {\n"
" int a = 0;\n"
" bar(a=a+2);\n"
"}");
TODO_ASSERT_EQUALS("error", "", errout_str());
}
void localvar37() { // ticket #3078
functionVariableUsage("void f() {\n"
" int a = 2;\n"
" ints.at(a) = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvar38() {
functionVariableUsage("std::string f() {\n"
" const char code[] = \"foo\";\n"
" const std::string s1(sizeof_(code));\n"
" const std::string s2 = sizeof_(code);\n"
" return(s1+s2);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvar39() {
functionVariableUsage("void f() {\n"
" int a = 1;\n"
" foo(x*a);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvar40() {
functionVariableUsage("int f() {\n"
" int a = 1;\n"
" return x & a;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvar41() {
// #3603 - false positive 'x is assigned a value that is never used'
functionVariableUsage("int f() {\n"
" int x = 1;\n"
" int y = FOO::VALUE * x;\n"
" return y;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvar42() { // #3742
functionVariableUsage("float g_float = 1;\n"
"extern void SomeTestFunc(float);\n"
"void MyFuncError()\n"
"{\n"
" const float floatA = 2.2f;\n"
" const float floatTot = g_float * floatA;\n"
" SomeTestFunc(floatTot);\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("float g_float = 1;\n"
"extern void SomeTestFunc(float);\n"
"void MyFuncNoError()\n"
"{\n"
" const float floatB = 2.2f;\n"
" const float floatTot = floatB * g_float;\n"
" SomeTestFunc(floatTot);\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("float g_float = 1;\n"
"extern void SomeTestFunc(float);\n"
"void MyFuncNoError2()\n"
"{\n"
" const float floatC = 2.2f;\n"
" float floatTot = g_float * floatC;\n"
" SomeTestFunc(floatTot);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvar43() { // ticket #3602 (false positive)
functionVariableUsage("void bar()\n"
"{\n"
" int * piArray = NULL;\n"
" unsigned int uiArrayLength = 2048;\n"
" unsigned int uiIndex;\n"
"\n"
" try\n"
" {\n"
" piArray = new int[uiArrayLength];\n" // Allocate memory
" }\n"
" catch (...)\n"
" {\n"
" SOME_MACRO\n"
" delete [] piArray;\n"
" return;\n"
" }\n"
" for (uiIndex = 0; uiIndex < uiArrayLength; uiIndex++)\n"
" {\n"
" piArray[uiIndex] = -1234;\n"
" }\n"
" delete [] piArray;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int f() {\n" // #9877
" const std::vector<int> x = get();\n"
" MACRO(2U, x.size())\n"
" int i = 0;\n"
" return i;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvar44() { // #4020 - FP
functionVariableUsage("void func() {\n"
" int *sp_mem[2] = { global1, global2 };\n"
" sp_mem[0][3] = 123;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvar45() { // #4899 - FP
functionVariableUsage("int func() {\n"
" int a = 123;\n"
" int b = (short)-a;;\n"
" return b;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvar46() { // #5491/#5494/#6301
functionVariableUsage("int func() {\n"
" int i = 0;\n"
" int j{i};\n"
" return j;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void f(bool b, bool c, double& r) {\n"
" double d{};\n"
" if (b) {\n"
" d = g();\n"
" r += d;\n"
" }\n"
" if (c) {\n"
" d = h();\n"
" r += d;\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int func() {\n"
" std::mutex m;\n"
" std::unique_lock<std::mutex> l{ m };\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int func() {\n"
" std::shared_lock<std::shared_timed_mutex> lock( m );\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void f() {\n" // #10490
" std::shared_lock lock = GetLock();\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void f() {\n"
" auto&& g = std::lock_guard<std::mutex> { mutex };\n"
"}\n");
TODO_ASSERT_EQUALS("", "[test.cpp:2]: (style) Variable 'g' is assigned a value that is never used.\n", errout_str());
functionVariableUsage("void f() {\n"
" auto a = RAII();\n"
" auto b { RAII() };\n"
"}\n");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("struct RAIIWrapper {\n" // #10894
" RAIIWrapper();\n"
" ~RAIIWrapper();\n"
"};\n"
"static void foo() {\n"
" auto const guard = RAIIWrapper();\n"
" auto const& guard2 = RAIIWrapper();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void localvar47() { // #6603
// extracttests.disable
functionVariableUsage("void f() {\n"
" int (SfxUndoManager::*retrieveCount)(bool) const\n"
" = (flag) ? &SfxUndoManager::foo : &SfxUndoManager::bar;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'retrieveCount' is assigned a value that is never used.\n", errout_str());
// extracttests.enable
}
void localvar48() { // #6954
functionVariableUsage("void foo() {\n"
" long (*pKoeff)[256] = new long[9][256];\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvar49() { // #7594
functionVariableUsage("class A {\n"
" public:\n"
" typedef enum { ID1,ID2,ID3 } Id_t;\n"
" typedef struct {Id_t id; std::string a; } x_t;\n"
" std::vector<x_t> m_vec;\n"
" std::vector<x_t> Get(void);\n"
" void DoSomething();\n"
"};\n"
"std::vector<A::x_t> A::Get(void) {\n"
" return m_vec;\n"
"}\n"
"const std::string Bar() {\n"
" return \"x\";\n"
"}\n"
"void A::DoSomething(void) {\n"
" const std::string x = Bar();\n" // <- warning
"}");
ASSERT_EQUALS(
"[test.cpp:16]: (style) Variable 'x' is assigned a value that is never used.\n"
"[test.cpp:16]: (style) Variable 'x' is assigned a value that is never used.\n", // duplicate
errout_str());
}
void localvar50() { // #6261, #6542
// #6261 - ternary operator in function call
functionVariableUsage("void foo() {\n"
" char buf1[10];\n"
" dostuff(cond?buf1:buf2);\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo() {\n"
" char buf1[10];\n"
" dostuff(cond?buf2:buf1);\n"
"}");
ASSERT_EQUALS("", errout_str());
// #6542 - ternary operator
functionVariableUsage("void foo(int c) {\n"
" char buf1[10], buf2[10];\n"
" char *p = c ? buf1 : buf2;\n"
" dostuff(p);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvar51() { // #8128 FN
// extracttests.start: struct Token { const Token* next() const; }; const Token* nameToken();
functionVariableUsage("void foo(const Token *var) {\n"
" const Token *tok = nameToken();\n"
" tok = tok->next();\n" // read+write
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'tok' is assigned a value that is never used.\n", errout_str());
functionVariableUsage("void foo() {\n"
" int x = 4;\n"
" x = 15 + x;\n" // read+write
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'x' is assigned a value that is never used.\n", errout_str());
}
void localvar52() {
functionVariableUsage("void foo() {\n"
" std::vector<int> data;\n"
" data[2] = 32;\n"
" return data;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvar53() {
functionVariableUsage("void foo(int a, int loop) {\n"
" bool x = false;\n"
" while (loop) {\n"
" if (a) {\n"
" x = true;\n" // unused value
" continue;\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Variable 'x' is assigned a value that is never used.\n", errout_str());
functionVariableUsage("void foo(int a, int loop) {\n"
" bool x = false;\n"
" while (loop) {\n"
" if (a) {\n"
" x = true;\n"
" continue;\n"
" }\n"
" }\n"
" return x;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvar54() {
functionVariableUsage("Padding fun() {\n"
" Distance d = DISTANCE;\n"
" return (Padding){ d, d, d, d };\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvar55() {
functionVariableUsage("void f(int mode) {\n"
" int x = 0;\n" // <- redundant assignment
"\n"
" for (int i = 0; i < 10; i++) {\n"
" if (mode == 0x04)\n"
" x = 0;\n" // <- redundant assignment
" if (mode == 0x0f) {\n"
" x = address;\n"
" data[x] = 0;\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Variable 'x' is assigned a value that is never used.\n"
"[test.cpp:6]: (style) Variable 'x' is assigned a value that is never used.\n",
errout_str());
}
void localvar56() {
functionVariableUsage("void f()\n"
"{\n"
" int x = 31;\n"
" mask[x] |= 123;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvar57() {
functionVariableUsage("void f()\n"
"{\n"
" int x = 0;\n"
" x++;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Variable 'x' is assigned a value that is never used.\n", errout_str());
}
void localvar58() { // #9901 - increment false positive
functionVariableUsage("void f() {\n"
" int x = 0;\n"
" if (--x > 0) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void f() {\n"
" int x = 0;\n"
" if (x-- > 0) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'x' is assigned a value that is never used.\n", errout_str());
}
void localvar59() { // #9737
functionVariableUsage("Response foo() {\n"
" const std::vector<char> cmanifest = z;\n"
" return {.a = cmanifest, .b =0};\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvar60() {
functionVariableUsage("void Scale(double scale) {\n" // #10531
" for (int i = 0; i < m_points.size(); ++i) {\n"
" auto& p = m_points[i];\n"
" p += scale;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo(int c[]) {\n" // #10597
" int& cc = c[0];\n"
" cc &= ~0xff;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void localvar61() { // #9407
functionVariableUsage("void g(int& i);\n"
"void f() {\n"
" int var = 0;\n"
" g(var);\n"
" var = 2;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5]: (style) Variable 'var' is assigned a value that is never used.\n", errout_str());
}
void localvar62() {
functionVariableUsage("void f() {\n" // #10824
" S* s = nullptr;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Variable 's' is assigned a value that is never used.\n", errout_str());
functionVariableUsage("void f() {\n"
" S* s{};\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Variable 's' is assigned a value that is never used.\n", errout_str());
functionVariableUsage("int f() {\n"
" int i = 0, j = 1;\n"
" return i;\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:2]: (style) Variable 'j' is assigned a value that is never used.\n"
"[test.cpp:2]: (style) Variable 'j' is assigned a value that is never used.\n", // duplicate
errout_str());
functionVariableUsage("int f() {\n"
" int i = 0, j = 1;\n"
" return j;\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:2]: (style) Variable 'i' is assigned a value that is never used.\n"
"[test.cpp:2]: (style) Variable 'i' is assigned a value that is never used.\n", // duplicate
errout_str());
functionVariableUsage("void f() {\n" // #10846
" int i = 1; while (i) { i = g(); }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void localvar63() { // #6928
functionVariableUsage("void f(void) {\n"
" int x=3;\n" // <- set but not used
" goto y;\n"
" y:return;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Variable 'x' is assigned a value that is never used.\n", errout_str());
}
void localvar64() { // #9997
functionVariableUsage("class S {\n"
" ~S();\n"
" S* f();\n"
" S* g(int);\n"
"};\n"
"void h(S* s, bool b) {\n"
" S* p = nullptr;\n"
" S* q = nullptr;\n"
" if (b) {\n"
" p = s;\n"
" q = s->f()->g(-2);\n"
" }\n"
" else\n"
" q = s;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:10]: (style) Variable 'p' is assigned a value that is never used.\n"
"[test.cpp:11]: (style) Variable 'q' is assigned a value that is never used.\n"
"[test.cpp:14]: (style) Variable 'q' is assigned a value that is never used.\n",
errout_str());
}
void localvar65() {
functionVariableUsage("bool b();\n" // #9876
"void f() {\n"
" for (;;) {\n"
" const T* t = tok->next()->link()->next();\n"
" if (!b())\n"
" continue;\n"
" }\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (style) Variable 't' is assigned a value that is never used.\n", errout_str());
functionVariableUsage("void f() {\n" // #10006
" std::string s = \"\";\n"
" try {}\n"
" catch (...) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Variable 's' is assigned a value that is never used.\n", errout_str());
}
void localvar66() { // #11143
functionVariableUsage("void f() {\n"
" double phi = 42.0;\n"
" std::cout << pow(sin(phi), 2) + pow(cos(phi), 2) << std::endl;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void localvar67() { // #9946
functionVariableUsage("struct B {\n"
" virtual ~B() {}\n"
" bool operator() () const { return true; }\n"
" virtual bool f() const = 0;\n"
"};\n"
"class D : B {\n"
"public:\n"
" bool f() const override { return false; }\n"
"};\n"
"void f1() {\n"
" const D d1;\n"
" d1.f();\n"
"}\n"
"void f2() {\n"
" const D d2;\n"
" d2();\n"
" B() {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void localvar68() {
checkFunctionVariableUsageP("#define X0 int x = 0\n"
"void f() { X0; }\n");
ASSERT_EQUALS("", errout_str());
checkFunctionVariableUsageP("#define X0 int (*x)(int) = 0\n"
"void f() { X0; }\n");
ASSERT_EQUALS("", errout_str());
}
void localvar69() {
functionVariableUsage("int g();\n" // #11063
"int h(int);\n"
"int f() {\n"
" int i = g();\n"
" return (::h)(i);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void localvar70() {
functionVariableUsage("struct S { int i = 0; };\n" // #12176
"void f(S s) {\n"
" S s1;\n"
" if (s == s1) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void localvar71() {
functionVariableUsage("struct A { explicit A(int i); };\n" // #12363
"void f() { A a(0); }\n");
ASSERT_EQUALS("", errout_str());
}
void localvarloops() {
// loops
functionVariableUsage("void fun(int c) {\n"
" int x;\n"
" while (c) { x=10; }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'x' is assigned a value that is never used.\n", errout_str());
functionVariableUsage("void dostuff(int x);\n"
"void fun(int y, int c) {\n"
" int x = 1;\n"
" while (c) {\n"
" dostuff(x);\n"
" if (y) { x=10; break; }\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (style) Variable 'x' is assigned a value that is never used.\n", errout_str());
functionVariableUsage("void dostuff(int &x);\n"
"void fun() {\n"
" int x = 1;\n"
" while (c) {\n"
" dostuff(x);\n"
" if (y) { x=10; break; }\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (style) Variable 'x' is assigned a value that is never used.\n", errout_str());
functionVariableUsage("void fun() {\n"
" int x = 0;\n"
" while (c) {\n"
" dostuff(x);\n"
" x = 10;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void fun() {\n"
" int x = 0;\n"
" while (x < 10) { x = x + 1; }\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void fun()\n"
"{\n"
" int status = 0;\n"
" for (ind = 0; ((ind < nrArgs) && (status < 10)); ind++)\n"
" status = x;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void f()\n"
"{\n"
" int sum = 0U;\n"
" for (i = 0U; i < 2U; i++)\n"
" sum += 123;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'sum' is assigned a value that is never used.\n"
"[test.cpp:5]: (style) Variable 'sum' is assigned a value that is never used.\n", errout_str());
functionVariableUsage("void f(int c) {\n" // #7908
" int b = 0;\n"
" while (g()) {\n"
" int a = c;\n"
" b = a;\n"
" if (a == 4)\n"
" a = 5;\n"
" }\n"
" h(b);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:7]: (style) Variable 'a' is assigned a value that is never used.\n", errout_str());
functionVariableUsage("void f(const std::vector<int>& v) {\n"
" while (g()) {\n"
" const std::vector<int>& v2 = h();\n"
" if (std::vector<int>{ 1, 2, 3 }.size() > v2.size()) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void f(const std::vector<int>& v) {\n"
" while (g()) {\n"
" const std::vector<int>& v2 = h();\n"
" if (std::vector<int>({ 1, 2, 3 }).size() > v2.size()) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void f(const std::string &c) {\n"
" std::string s = str();\n"
" if (s[0] == '>')\n"
" s[0] = '<';\n"
" if (s == c) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void f(bool b) {\n"
" std::map<std::string, std::vector<std::string>> m;\n"
" if (b) {\n"
" const std::string n = g();\n"
" std::vector<std::string> c = h();\n"
" m[n] = c;\n"
" }\n"
" j(m);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("struct S { int i; };\n"
"S f(S s, bool b) {\n"
" if (b)\n"
" s.i = 1;\n"
" return s;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void localvaralias1() {
functionVariableUsage("void foo()\n"
"{\n"
" int a;\n"
" int *b = &a;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Variable 'b' is assigned a value that is never used.\n"
"[test.cpp:3]: (style) Unused variable: a\n"
"[test.cpp:4]: (style) Variable 'b' is assigned a value that is never used.\n", // duplicate
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int a[10];\n"
" int *b = a;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Variable 'b' is assigned a value that is never used.\n"
"[test.cpp:3]: (style) Unused variable: a\n"
"[test.cpp:4]: (style) Variable 'b' is assigned a value that is never used.\n", // duplicate
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int a;\n"
" int *b = &a;\n"
" *b = 0;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:5]: (style) Variable 'a' is assigned a value that is never used.\n",
"",
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int a;\n"
" char *b = (char *)&a;\n"
" *b = 0;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:5]: (style) Variable 'a' is assigned a value that is never used.\n",
"",
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int a;\n"
" char *b = (char *)(&a);\n"
" *b = 0;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:5]: (style) Variable 'a' is assigned a value that is never used.\n",
"",
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int a;\n"
" const char *b = (const char *)&a;\n"
" *b = 0;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:5]: (style) Variable 'a' is assigned a value that is never used.\n",
"",
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int a;\n"
" const char *b = (const char *)(&a);\n"
" *b = 0;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:5]: (style) Variable 'a' is assigned a value that is never used.\n",
"",
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int a;\n"
" char *b = static_cast<char *>(&a);\n"
" *b = 0;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:5]: (style) Variable 'a' is assigned a value that is never used.\n",
"",
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int a;\n"
" const char *b = static_cast<const char *>(&a);\n"
" *b = 0;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:5]: (style) Variable 'a' is assigned a value that is never used.\n",
"",
errout_str());
// a is not a local variable and b is aliased to it
functionVariableUsage("int a;\n"
"void foo()\n"
"{\n"
" int *b = &a;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:4]: (style) Variable 'b' is assigned a value that is never used.\n"
"[test.cpp:4]: (style) Variable 'b' is assigned a value that is never used.\n", // duplicate
errout_str());
// a is not a local variable and b is aliased to it
functionVariableUsage("void foo(int a)\n"
"{\n"
" int *b = &a;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3]: (style) Variable 'b' is assigned a value that is never used.\n"
"[test.cpp:3]: (style) Variable 'b' is assigned a value that is never used.\n", // duplicate
errout_str());
// a is not a local variable and b is aliased to it
functionVariableUsage("class A\n"
"{\n"
" int a;\n"
" void foo()\n"
" {\n"
" int *b = &a;\n"
" }\n"
"};");
ASSERT_EQUALS(
"[test.cpp:6]: (style) Variable 'b' is assigned a value that is never used.\n"
"[test.cpp:6]: (style) Variable 'b' is assigned a value that is never used.\n", // duplicate
errout_str());
functionVariableUsage("int a;\n"
"void foo()\n"
"{\n"
" int *b = &a;\n"
" *b = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo(int a)\n"
"{\n"
" int *b = &a;\n"
" *b = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("class A\n"
"{\n"
" int a;\n"
" void foo()\n"
" {\n"
" int *b = &a;\n"
" *b = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int a[10];\n"
" int *b = a;\n"
" *b = 0;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:5]: (style) Variable 'a' is assigned a value that is never used.\n",
"",
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int a[10];\n"
" char *b = (char *)a;\n"
" *b = 0;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:5]: (style) Variable 'a' is assigned a value that is never used.\n",
"",
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int a[10];\n"
" char *b = (char *)(a);\n"
" *b = 0;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:5]: (style) Variable 'a' is assigned a value that is never used.\n",
"",
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int a[10];\n"
" const char *b = (const char *)a;\n"
" *b = 0;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:5]: (style) Variable 'a' is assigned a value that is never used.\n",
"",
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int a[10];\n"
" const char *b = (const char *)(a);\n"
" *b = 0;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:5]: (style) Variable 'a' is assigned a value that is never used.\n",
"",
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int a[10];\n"
" char *b = static_cast<char *>(a);\n"
" *b = 0;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:5]: (style) Variable 'a' is assigned a value that is never used.\n",
"",
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int a[10];\n"
" const char *b = static_cast<const char *>(a);\n"
" *b = 0;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:5]: (style) Variable 'a' is assigned a value that is never used.\n",
"",
errout_str());
functionVariableUsage("int a[10];\n"
"void foo()\n"
"{\n"
" int *b = a;\n"
" *b = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int a[10];\n"
"void foo()\n"
"{\n"
" int *b = a;\n"
" int *c = b;\n"
" *c = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int *b = a;\n"
" int *c = b;\n"
" *c = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int *b = a;\n"
" int *c = b;\n"
" *c = b[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
// extracttests.start: int a[10];
functionVariableUsage("void foo()\n"
"{\n"
" int *b = a;\n"
" int c = b[0];\n"
" x(c);\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int *b = a;\n"
" int c = b[0];\n"
" x(c);\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int a[10];\n"
"void foo()\n"
"{\n"
" int *b = &a[0];\n"
" a[0] = b[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int *b = &a[0];\n"
" a[0] = b[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int *b = a;\n"
" a[0] = b[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo(int a[10])\n"
"{\n"
" int *b = a;\n"
" *b = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("class A\n"
"{\n"
" int a[10];\n"
" void foo()\n"
" {\n"
" int *b = a;\n"
" *b = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int a[10];\n"
" int *b = a;\n"
" int *c = b;\n"
" *c = 0;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:6]: (style) Variable 'a' is assigned a value that is never used.\n",
"",
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int a[10];\n"
" int b[10];\n"
" int *c = a;\n"
" int *d = b;\n"
" *d = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (style) Variable 'c' is assigned a value that is never used.\n"
"[test.cpp:3]: (style) Unused variable: a\n"
"[test.cpp:5]: (style) Variable 'c' is assigned a value that is never used.\n", // duplicate
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int a[10];\n"
" int b[10];\n"
" int *c = a;\n"
" c = b;\n"
" *c = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Unused variable: a\n"
"",
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int a[10];\n"
" int b[10];\n"
" int *c = a;\n"
" c = b;\n"
" *c = 0;\n"
" c = a;\n"
" *c = 0;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:9]: (style) Variable 'a' is assigned a value that is never used.\n"
"[test.cpp:7]: (style) Variable 'b' is assigned a value that is never used.\n",
"",
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int a[10], * b = a + 10;\n"
" b[-10] = 1;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:4]: (style) Variable 'b[-10]' is assigned a value that is never used.\n",
"",
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int a[10], * b = a + 10;\n"
" b[-10] = 0;\n"
" int * c = b - 10;\n"
"}");
TODO_ASSERT_EQUALS(
"[test.cpp:4]: (style) Variable 'a' is assigned a value that is never used.\n",
"[test.cpp:5]: (style) Variable 'c' is assigned a value that is never used.\n"
"[test.cpp:5]: (style) Variable 'c' is assigned a value that is never used.\n", // duplicate
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int a[10], * b = a + 10;\n"
" int * c = b - 10;\n"
" c[1] = 3;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:5]: (style) Variable 'c[1]' is assigned a value that is never used.\n",
"",
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" int a[10], * b = a + 10;\n"
" int * c = b - 10;\n"
" c[1] = c[0];\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:5]: (style) Variable 'c[1]' is assigned a value that is never used.\n",
"",
errout_str());
functionVariableUsage("void foo() {\n" // #4022 - FP (a is assigned a value that is never used)
" int a[2], *b[2];\n"
" a[0] = 123;\n"
" b[0] = &a[0];\n"
" int *d = b[0];\n"
" return *d;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo() {\n" // #4022 - FP (a is assigned a value that is never used)
" entry a[2], *b[2];\n"
" a[0].value = 123;\n"
" b[0] = &a[0];\n"
" int d = b[0].value;\n"
" return d;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("struct S { char c[100]; };\n"
"void foo()\n"
"{\n"
" char a[100];\n"
" struct S * s = (struct S *)a;\n"
" s->c[0] = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("struct S { char c[100]; };\n"
"void foo()\n"
"{\n"
" char a[100];\n"
" struct S * s = (struct S *)a;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (style) Variable 's' is assigned a value that is never used.\n"
"[test.cpp:4]: (style) Unused variable: a\n"
"[test.cpp:5]: (style) Variable 's' is assigned a value that is never used.\n", // duplicate
errout_str());
functionVariableUsage("struct S { char c[100]; };\n"
"void foo()\n"
"{\n"
" char a[100];\n"
" const struct S * s = (const struct S *)a;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (style) Variable 's' is assigned a value that is never used.\n"
"[test.cpp:4]: (style) Unused variable: a\n"
"[test.cpp:5]: (style) Variable 's' is assigned a value that is never used.\n", // duplicate
errout_str());
functionVariableUsage("struct S { char c[100]; };\n"
"void foo()\n"
"{\n"
" char a[100];\n"
" struct S * s = static_cast<struct S *>(a);\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (style) Variable 's' is assigned a value that is never used.\n"
"[test.cpp:4]: (style) Unused variable: a\n"
"[test.cpp:5]: (style) Variable 's' is assigned a value that is never used.\n", // duplicate
errout_str());
functionVariableUsage("struct S { char c[100]; };\n"
"void foo()\n"
"{\n"
" char a[100];\n"
" const struct S * s = static_cast<const struct S *>(a);\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (style) Variable 's' is assigned a value that is never used.\n"
"[test.cpp:4]: (style) Unused variable: a\n"
"[test.cpp:5]: (style) Variable 's' is assigned a value that is never used.\n", // duplicate
errout_str());
functionVariableUsage("int a[10];\n"
"void foo()\n"
"{\n"
" int b[10];\n"
" int c[10];\n"
" int *d;\n"
" d = b;\n"
" d = a;\n"
" d = c;\n"
" *d = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Unused variable: b\n",
errout_str());
functionVariableUsage("int a[10];\n"
"void foo()\n"
"{\n"
" int b[10];\n"
" int c[10];\n"
" int *d;\n"
" d = b; *d = 0;\n"
" d = a; *d = 0;\n"
" d = c; *d = 0;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:7]: (style) Variable 'b' is assigned a value that is never used.\n"
"[test.cpp:9]: (style) Variable 'c' is assigned a value that is never used.\n",
"",
errout_str());
}
void localvaralias2() { // ticket 1637
functionVariableUsage("void foo()\n"
"{\n"
" int * a;\n"
" x(a);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvaralias3() { // ticket 1639
functionVariableUsage("void foo()\n"
"{\n"
" BROWSEINFO info;\n"
" char szDisplayName[MAX_PATH];\n"
" info.pszDisplayName = szDisplayName;\n"
" SHBrowseForFolder(&info);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvaralias4() { // ticket 1643
functionVariableUsage("struct AB { int a; int b; } ab;\n"
"void foo()\n"
"{\n"
" int * a = &ab.a;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:4]: (style) Variable 'a' is assigned a value that is never used.\n"
"[test.cpp:4]: (style) Variable 'a' is assigned a value that is never used.\n", // duplicate
errout_str());
functionVariableUsage("struct AB { int a; int b; } ab;\n"
"void foo()\n"
"{\n"
" int * a = &ab.a;\n"
" *a = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("struct AB { int a; int b; };\n"
"void foo()\n"
"{\n"
" struct AB ab;\n"
" int * a = &ab.a;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (style) Variable 'a' is assigned a value that is never used.\n"
"[test.cpp:4]: (style) Variable 'ab' is not assigned a value.\n"
"[test.cpp:5]: (style) Variable 'a' is assigned a value that is never used.\n", // duplicate
errout_str());
functionVariableUsage("struct AB { int a; int b; };\n"
"void foo()\n"
"{\n"
" struct AB ab;\n"
" int * a = &ab.a;\n"
" *a = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvaralias5() { // ticket 1647
functionVariableUsage("char foo()\n"
"{\n"
" char buf[8];\n"
" char *p = &buf[0];\n"
" *p++ = 0;\n"
" return buf[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("char foo()\n"
"{\n"
" char buf[8];\n"
" char *p = &buf[1];\n"
" *p-- = 0;\n"
" return buf[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("char foo()\n"
"{\n"
" char buf[8];\n"
" char *p = &buf[0];\n"
" *++p = 0;\n"
" return buf[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("char foo()\n"
"{\n"
" char buf[8];\n"
" char *p = &buf[1];\n"
" *--p = 0;\n"
" return buf[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvaralias6() { // ticket 1729
// extracttests.start: int a(); void b(const char *);
functionVariableUsage("void foo()\n"
"{\n"
" char buf[8];\n"
" char *srcdata;\n"
" if (a()) {\n"
" buf[0] = 1;\n"
" srcdata = buf;\n"
" } else {\n"
" srcdata = vdata;\n"
" }\n"
" b(srcdata);\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" char buf[8];\n"
" char *srcdata;\n"
" if (a()) {\n"
" buf[0] = 1;\n"
" srcdata = buf;\n"
" srcdata = vdata;\n"
" }\n"
" b(srcdata);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:6]: (style) Variable 'buf' is assigned a value that is never used.\n",
"",
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" char buf[8];\n"
" char *srcdata;\n"
" if (a()) {\n"
" buf[0] = 1;\n"
" srcdata = buf;\n"
" }\n"
" srcdata = vdata;\n"
" b(srcdata);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:6]: (style) Variable 'buf' is assigned a value that is never used.\n",
"",
errout_str());
functionVariableUsage("void foo(char *vdata)\n"
"{\n"
" char buf[8];\n"
" char *srcdata;\n"
" if (a()) {\n"
" srcdata = buf;\n"
" }\n"
" srcdata = vdata;\n"
" b(srcdata);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Unused variable: buf\n", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" char buf[8];\n"
" char *srcdata;\n"
" if (a()) {\n"
" srcdata = vdata;\n"
" }\n"
" srcdata = buf;\n"
" b(srcdata);\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" char buf[8];\n"
" char *srcdata;\n"
" char vdata[8];\n"
" if (a()) {\n"
" buf[0] = 1;\n"
" srcdata = buf;\n"
" } else {\n"
" srcdata = vdata;\n"
" }\n"
" b(srcdata);\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" char buf[8];\n"
" char *srcdata;\n"
" char vdata[8];\n"
" if (a()) {\n"
" buf[0] = 1;\n"
" srcdata = buf;\n"
" srcdata = vdata;\n"
" }\n"
" b(srcdata);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:7]: (style) Variable 'buf' is assigned a value that is never used.\n",
"",
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" char buf[8];\n"
" char *srcdata;\n"
" char vdata[8];\n"
" if (a()) {\n"
" buf[0] = 1;\n"
" srcdata = buf;\n"
" }\n"
" srcdata = vdata;\n"
" b(srcdata);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:7]: (style) Variable 'buf' is assigned a value that is never used.\n",
"",
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" char buf[8];\n"
" char *srcdata;\n"
" char vdata[8];\n"
" if (a()) {\n"
" srcdata = buf;\n"
" }\n"
" srcdata = vdata;\n"
" b(srcdata);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Unused variable: buf\n", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" char buf[8];\n"
" char *srcdata;\n"
" char vdata[8];\n"
" if (a()) {\n"
" srcdata = vdata;\n"
" }\n"
" srcdata = buf;\n"
" b(srcdata);\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (style) Unused variable: vdata\n", errout_str());
}
void localvaralias7() { // ticket 1732
functionVariableUsage("void foo()\n"
"{\n"
" char *c[10];\n"
" char **cp;\n"
" cp = c;\n"
" *cp = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvaralias8() {
functionVariableUsage("void foo()\n"
"{\n"
" char b1[8];\n"
" char b2[8];\n"
" char b3[8];\n"
" char b4[8];\n"
" char *pb;\n"
" if (a == 1)\n"
" pb = b1;\n"
" else if (a == 2)\n"
" pb = b2;\n"
" else if (a == 3)\n"
" pb = b3;\n"
" else\n"
" pb = b4;\n"
" b(pb);\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" char b1[8];\n"
" char b2[8];\n"
" char b3[8];\n"
" char b4[8];\n"
" char *pb;\n"
" if (a == 1)\n"
" pb = b1;\n"
" else if (a == 2)\n"
" pb = b2;\n"
" else if (a == 3)\n"
" pb = b3;\n"
" else {\n"
" pb = b1;\n"
" pb = b4;\n"
" }\n"
" b(pb);\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" char b1[8];\n"
" char b2[8];\n"
" char b3[8];\n"
" char b4[8];\n"
" char *pb;\n"
" if (a == 1)\n"
" pb = b1;\n"
" else if (a == 2)\n"
" pb = b2;\n"
" else if (a == 3)\n"
" pb = b3;\n"
" else {\n"
" pb = b1;\n"
" pb = b2;\n"
" pb = b3;\n"
" pb = b4;\n"
" }\n"
" b(pb);\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" char b1[8];\n"
" char b2[8];\n"
" char b3[8];\n"
" char b4[8];\n"
" char *pb;\n"
" if (a == 1)\n"
" pb = b1;\n"
" else if (a == 2)\n"
" pb = b2;\n"
" else if (a == 3)\n"
" pb = b3;\n"
" pb = b4;\n"
" b(pb);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Unused variable: b1\n"
"[test.cpp:4]: (style) Unused variable: b2\n"
"[test.cpp:5]: (style) Unused variable: b3\n", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" char b1[8];\n"
" char b2[8];\n"
" char b3[8];\n"
" char b4[8];\n"
" char *pb;\n"
" if (a == 1)\n"
" pb = b1;\n"
" else {\n"
" if (a == 2)\n"
" pb = b2;\n"
" else {\n"
" if (a == 3)\n"
" pb = b3;\n"
" else\n"
" pb = b4;\n"
" }\n"
" }\n"
" b(pb);\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" char b1[8];\n"
" char b2[8];\n"
" char b3[8];\n"
" char b4[8];\n"
" char *pb;\n"
" if (a == 1)\n"
" pb = b1;\n"
" else {\n"
" if (a == 2)\n"
" pb = b2;\n"
" else {\n"
" if (a == 3)\n"
" pb = b3;\n"
" else {\n"
" pb = b1;\n"
" pb = b4;\n"
" }\n"
" }\n"
" }\n"
" b(pb);\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" char b1[8];\n"
" char b2[8];\n"
" char b3[8];\n"
" char b4[8];\n"
" char *pb;\n"
" if (a == 1)\n"
" pb = b1;\n"
" else {\n"
" if (a == 2)\n"
" pb = b2;\n"
" else {\n"
" if (a == 3)\n"
" pb = b3;\n"
" else {\n"
" pb = b1;\n"
" pb = b2;\n"
" pb = b3;\n"
" pb = b4;\n"
" }\n"
" }\n"
" }\n"
" b(pb);\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" char b1[8];\n"
" char b2[8];\n"
" char b3[8];\n"
" char b4[8];\n"
" char *pb;\n"
" if (a == 1)\n"
" pb = b1;\n"
" else {\n"
" if (a == 2)\n"
" pb = b2;\n"
" else {\n"
" if (a == 3)\n"
" pb = b3;\n"
" }\n"
" }\n"
" pb = b4;\n"
" b(pb);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Unused variable: b1\n"
"[test.cpp:4]: (style) Unused variable: b2\n"
"[test.cpp:5]: (style) Unused variable: b3\n", errout_str());
}
void localvaralias9() { // ticket 1996
functionVariableUsage("void foo()\n"
"{\n"
" Foo foo;\n"
" Foo &ref = foo;\n"
" ref[0] = 123;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvaralias10() { // ticket 2004
functionVariableUsage("void foo(Foo &foo)\n"
"{\n"
" Foo &ref = foo;\n"
" int *x = &ref.x();\n"
" *x = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvaralias11() { // #4423 - iterator
functionVariableUsage("void f(Foo &foo) {\n"
" std::set<int>::iterator x = foo.dostuff();\n"
" *(x) = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvaralias12() { // #4394
functionVariableUsage("void f(void) {\n"
" int a[4];\n"
" int *b = (int*)((int*)a+1);\n"
" x(b);\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int f(void) {\n" // #4628
" int x=1,y;\n"
" y = (x * a) / 100;\n"
" return y;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvaralias13() { // #4487
functionVariableUsage("void f(char *p) {\n"
" char a[4];\n"
" p = a;\n"
" strcpy(p, \"x\");\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void f(char *p) {\n"
" char a[4];\n"
" p = a;\n"
" strcpy(p, \"x\");\n"
"}");
TODO_ASSERT_EQUALS("a is assigned value that is never used", "", errout_str());
}
void localvaralias14() { // #5619
functionVariableUsage("char * dostuff(char *p);\n"
"void f() {\n"
" char a[4], *p=a;\n"
" p = dostuff(p);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Variable 'p' is assigned a value that is never used.\n", errout_str());
functionVariableUsage("char * dostuff(char *&p);\n"
"void f() {\n"
" char a[4], *p=a;\n"
" p = dostuff(p);\n"
"}");
ASSERT_EQUALS("", errout_str()); // TODO: we can warn in this special case; variable is local and there are no function calls after the assignment
functionVariableUsage("void f() {\n"
" char a[4], *p=a;\n"
" p = dostuff(p);\n"
"}");
ASSERT_EQUALS("", errout_str()); // TODO: we can warn in this special case; variable is local and there are no function calls after the assignment
}
void localvaralias15() { // #6315
functionVariableUsage("void f() {\n"
" int x=3;\n"
" int *p = &x;\n"
" int *p2[1] = {p};\n"
" dostuff(p2);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvaralias16() {
functionVariableUsage("void f() {\n"
" auto x = dostuff();\n"
" p = x;\n"
" x->data[0] = 9;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvaralias17() {
functionVariableUsage("void f() {\n"
" int x;\n"
" unknown_type p = &x;\n"
" *p = 9;\n"
"}", false);
ASSERT_EQUALS("", errout_str());
}
void localvaralias18() {
functionVariableUsage("void add( std::vector< std::pair< int, double > >& v)\n"
"{\n"
" std::vector< std::pair< int, double > >::iterator it;\n"
" for ( it = v.begin(); it != v.end(); ++it )\n"
" {\n"
" if ( x )\n"
" {\n"
" ( *it ).second = 0;\n"
" break;\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvaralias19() { // #9828
functionVariableUsage("void f() {\n"
" bool b0{}, b1{};\n"
" struct {\n"
" bool* pb;\n"
" int val;\n"
" } Map[] = { {&b0, 0}, {&b1, 1} };\n"
" b0 = true;\n"
" for (auto & m : Map)\n"
" if (m.pb && *m.pb)\n"
" m.val = 1;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void localvaralias20() { // #10966
functionVariableUsage("struct A {};\n"
"A g();\n"
"void f() {\n"
" const auto& a = g();\n"
" const auto& b = a;\n"
" const auto&& c = g();\n"
" auto&& d = c;\n"
"}\n");
TODO_ASSERT_EQUALS("[test.cpp:5]: (style) Variable 'b' is assigned a value that is never used.\n"
"[test.cpp:7]: (style) Variable 'd' is assigned a value that is never used.\n",
"[test.cpp:7]: (style) Variable 'd' is assigned a value that is never used.\n",
errout_str());
}
void localvaralias21() { // #11728
functionVariableUsage("void f(int i) {\n"
" bool b = true;\n"
" bool* p = &b;\n"
" int j{};\n"
" if (i)\n"
" b = false;\n"
" if (*p) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (style) Variable 'j' is assigned a value that is never used.\n", errout_str());
}
void localvaralias22() { // #11139
functionVariableUsage("int f() {\n"
" int x[1], *p = x;\n"
" x[0] = 42;\n"
" return *p;\n"
"}\n"
"int g() {\n"
" int x[1], *p{ x };\n"
" x[0] = 42;\n"
" return *p;\n"
"}\n"
"int h() {\n"
" int x[1], *p(x);\n"
" x[0] = 42;\n"
" return *p;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void localvaralias23() { // #11817
functionVariableUsage("void f(int& r, bool a, bool b) {\n"
" int& e = r;\n"
" if (a)\n"
" e = 42;\n"
" else if (b)\n"
" e = 1;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void localvarasm() {
functionVariableUsage("void foo(int &b)\n"
"{\n"
" int a;\n"
" asm();\n"
" b = a;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvarStruct1() {
functionVariableUsage("void foo()\n"
"{\n"
" static const struct{ int x, y, w, h; } bounds = {1,2,3,4};\n"
" return bounds.x + bounds.y + bounds.w + bounds.h;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvarStruct2() {
functionVariableUsage("void foo()\n"
"{\n"
" struct ABC { int a, b, c; };\n"
" struct ABC abc = { 1, 2, 3 };\n"
"}");
ASSERT_EQUALS(
"[test.cpp:4]: (style) Variable 'abc' is assigned a value that is never used.\n"
"[test.cpp:4]: (style) Variable 'abc' is assigned a value that is never used.\n", // duplicate
errout_str());
}
void localvarStruct3() {
functionVariableUsage("void foo()\n"
"{\n"
" int a = 10;\n"
" union { struct { unsigned char x; }; unsigned char z; };\n"
" do {\n"
" func();\n"
" } while(a--);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:4]: (style) Unused variable: x\n"
"[test.cpp:4]: (style) Unused variable: z\n", "", errout_str());
}
void localvarStruct5() {
// extracttests.disable
functionVariableUsage("int foo() {\n"
" A a;\n"
" return a.i;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int foo() {\n"
" A a;\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int foo() {\n"
" A a;\n"
" return 0;\n"
"}\n",
false);
ASSERT_EQUALS("[test.c:2]: (style) Unused variable: a\n", errout_str());
// extracttests.enable
functionVariableUsage("struct A { int i; };\n"
"int foo() {\n"
" A a;\n"
" return a.i;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("struct A { int i; };\n"
"int foo() {\n"
" A a;\n"
" a.i = 0;\n"
" return 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Variable 'a.i' is assigned a value that is never used.\n", errout_str());
functionVariableUsage("struct A { int i; };\n"
"int foo() {\n"
" A a = { 0 };\n"
" return 0;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3]: (style) Variable 'a' is assigned a value that is never used.\n"
"[test.cpp:3]: (style) Variable 'a' is assigned a value that is never used.\n", // duplicate
errout_str());
// extracttests.disable
functionVariableUsage("class A { int i; };\n"
"int foo() {\n"
" A a = { 0 };\n"
" return 0;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3]: (style) Variable 'a' is assigned a value that is never used.\n"
"[test.cpp:3]: (style) Variable 'a' is assigned a value that is never used.\n", // duplicate
errout_str());
// extracttests.enable
functionVariableUsage("class A { int i; public: A(); { } };\n"
"int foo() {\n"
" A a;\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("struct A { int i; };\n"
"int foo() {\n"
" A a;\n"
" return 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Unused variable: a\n", errout_str());
functionVariableUsage("class A { int i; };\n"
"int foo() {\n"
" A a;\n"
" return 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Unused variable: a\n", errout_str());
functionVariableUsage("class A { int i; public: A(); { } };\n"
"int foo() {\n"
" A a;\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("class A { unknown i; };\n"
"int foo() {\n"
" A a;\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("class A : public Fred { int i; };\n"
"int foo() {\n"
" A a;\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("class Fred {char c;};\n"
"class A : public Fred { int i; };\n"
"int foo() {\n"
" A a;\n"
" return 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Unused variable: a\n", errout_str());
}
void localvarStruct6() {
functionVariableUsage("class Type { };\n"
"class A {\n"
"public:\n"
" Type & get() { return t; }\n"
"private:\n"
" Type t;\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void localvarStruct7() {
functionVariableUsage("struct IMAPARG {\n"
" void *text;\n"
"};\n"
"\n"
"void fun() {\n"
" IMAPARG *args, aatt;\n"
" args = &aatt;\n"
" aatt.text = tmp;\n"
" dostuff(args);\n"
"}");
ASSERT_EQUALS("", errout_str());
// extracttests.start: void dostuff(int*);
functionVariableUsage("struct ARG {\n"
" int a;\n"
" int b;\n"
"};\n"
"\n"
"void fun() {\n"
" ARG aatt;\n"
" int *p = &aatt.b;\n"
" aatt.a = 123;\n"
" dostuff(p);\n"
"}");
ASSERT_EQUALS("[test.cpp:9]: (style) Variable 'aatt.a' is assigned a value that is never used.\n", errout_str());
functionVariableUsage("struct AB {\n"
" int a;\n"
" int b;\n"
"};\n"
"\n"
"void fun() {\n"
" AB ab;\n"
" int &a = ab.a;\n"
" ab.a = 123;\n"
" dostuff(a);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvarStruct8() {
functionVariableUsage("struct s {\n"
" union {\n"
" struct {\n"
" int fld1 : 16;\n"
" int fld2 : 16;\n"
" };\n"
" int raw;\n"
" };\n"
"};\n"
"\n"
"void foo() {\n"
" struct s test;\n"
" test.raw = 0x100;\n"
" dostuff(test.fld1, test.fld2);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvarStruct9() {
functionVariableUsage("struct XY { int x; int y; };\n"
"\n"
"void foo() {\n"
" struct XY xy(get());\n"
" return xy.x + xy.y;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvarStruct10() { // #6766
functionVariableUsage("struct S { int x; };\n"
"\n"
"void foo(const struct S s2) {\n"
" struct S s;\n"
" s.x = 3;\n"
" memcpy (&s, &s2, sizeof (S));\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (style) Variable 's.x' is assigned a value that is never used.\n", errout_str());
}
void localvarStruct11() { // #10095
functionVariableUsage("struct Point { int x; int y; };\n"
"Point scale(Point *p);\n"
"\n"
"int foo() {\n"
" Point p;\n"
" p.x = 42;\n"
" return scale(&p).y;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvarStruct12() { // #10495
functionVariableUsage("struct S { bool& Ref(); };\n"
"\n"
"void Set() {\n"
" S s;\n"
" s.Ref() = true;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvarStruct13() { // #10398
functionVariableUsage("int f() {\n"
" std::vector<std::string> Mode;\n"
" Info Block = {\n"
" {\n"
" { &Mode },\n"
" { &Level }\n"
" }\n"
" };\n"
" Mode.resize(N);\n"
" for (int i = 0; i < N; ++i)\n"
" Mode[i] = \"abc\";\n"
" return Save(&Block);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void localvarStruct14() { // #12142
functionVariableUsage("struct S { int i; };\n"
"int f() {\n"
" S s;\n"
" int S::* p = &S::i;\n"
" s.*p = 123;\n"
" return s.i;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void localvarStructArray() {
// extracttests.start: struct X {int a;};
// #3633 - detect that struct array is assigned a value
functionVariableUsage("void f() {\n"
" struct X x[10];\n"
" x[0].a = 5;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'x[0].a' is assigned a value that is never used.\n", errout_str());
}
void localvarUnion1() {
// #9707
functionVariableUsage("static short read(FILE *fp) {\n"
" typedef union { short s; unsigned char c[2]; } u;\n"
" u x;\n"
" x.c[0] = fgetuc(fp);\n"
" x.c[1] = fgetuc(fp);\n"
" return x.s;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvarOp() {
constexpr char op[] = "+-*/%&|^";
for (const char *p = op; *p; ++p) {
std::string code("int main()\n"
"{\n"
" int tmp = 10;\n"
" return 123 " + std::string(1, *p) + " tmp;\n"
"}");
functionVariableUsage(code.c_str());
ASSERT_EQUALS("", errout_str());
}
}
void localvarInvert() {
functionVariableUsage("int main()\n"
"{\n"
" int tmp = 10;\n"
" return ~tmp;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvarIf() {
functionVariableUsage("int main()\n"
"{\n"
" int tmp = 10;\n"
" if ( tmp )\n"
" return 1;\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("bool argsMatch(const Token *first, const Token *second) {\n" // #6145
" if (first->str() == \")\")\n"
" return true;\n"
" else if (first->next()->str() == \"=\")\n"
" first = first->nextArgument();\n"
" else if (second->next()->str() == \"=\") {\n"
" second = second->nextArgument();\n"
" if (second)\n"
" second = second->tokAt(-2);\n"
" if (!first || !second) {\n"
" return !first && !second;\n"
" }\n"
" }\n"
" return false;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5]: (style) Variable 'first' is assigned a value that is never used.\n", errout_str());
}
void localvarIfElse() {
functionVariableUsage("int foo()\n"
"{\n"
" int tmp1 = 1;\n"
" int tmp2 = 2;\n"
" int tmp3 = 3;\n"
" return tmp1 ? tmp2 : tmp3;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvarDeclaredInIf() {
functionVariableUsage("int foo(int x)\n"
"{\n"
" if (int y = x % 2)\n"
" return 2;\n"
" else\n"
" return 1;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:3]: (style) Variable 'y' is assigned a value that is never used.\n"
"[test.cpp:3]: (style) Variable 'y' is assigned a value that is never used.\n", // duplicate
errout_str());
functionVariableUsage("int foo(int x)\n"
"{\n"
" if (int y = x % 2)\n"
" return y;\n"
" else\n"
" return 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int foo(int x)\n"
"{\n"
" if (int y = x % 2)\n"
" return 2;\n"
" else\n"
" return y;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int f(int i) {\n" // #11788
" if (int x = i) {\n"
" return x;\n"
" }\n"
" else {\n"
" x = 12;\n"
" return x;\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void f(int i) {\n"
" if (int x = i) {\n"
" while (x < 100) {\n"
" if (x % 2 == 0) {\n"
" x += 3;\n"
" }\n"
" else if (x % 3 == 0) {\n"
" x += 5;\n"
" }\n"
" else {\n"
" x += 7;\n"
" }\n"
" x += 6;\n"
" }\n"
" return x;\n"
" }\n"
" return i;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void localvarOpAssign() {
functionVariableUsage("void foo()\n"
"{\n"
" int a = 1;\n"
" int b = 2;\n"
" a |= b;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'a' is assigned a value that is never used.\n"
"[test.cpp:5]: (style) Variable 'a' is assigned a value that is never used.\n", errout_str());
functionVariableUsage("void foo() {\n"
" int a = 1;\n"
" (b).x += a;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo() {\n"
" int a=1, b[10];\n"
" b[0] = x;\n"
" a += b[0];\n"
" return a;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void f(int *start, int *stop) {\n"
" int length = *start - *stop;\n"
" if (length < 10000)\n"
" length = 10000;\n"
" *stop -= length;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void f(int a) {\n"
" int x = 3;\n"
" a &= ~x;\n"
" return a;\n"
"}");
ASSERT_EQUALS("", errout_str());
// extracttests.disable
functionVariableUsage("void f() {\n" // unknown class => library configuration is needed
" Fred fred;\n"
" int *a; a = b;\n"
" fred += a;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (information) --check-library: Provide <type-checks><unusedvar> configuration for Fred\n", errout_str());
// extracttests.enable
functionVariableUsage("void f(std::pair<int,int> x) {\n"
" std::pair<int,int> fred;\n" // class with library configuration
" fred = x;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'fred' is assigned a value that is never used.\n", errout_str());
}
void localvarFor() {
functionVariableUsage("void foo()\n"
"{\n"
" int a = 1;\n"
" for (;a;);\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo() {\n"
" for (int i = 0; (pci = cdi_list_get(pciDevices, i)); i++)\n"
" {}\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvarForEach() { // #4155 - foreach
functionVariableUsage("void foo() {\n"
" int i = -1;\n"
" int a[] = {1,2,3};\n"
" FOREACH_X (int x, a) {\n"
" if (i==x) return x;\n"
" i = x;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// #5154 - MSVC 'for each'
functionVariableUsage("void f() {\n"
" std::map<int,int> ints;\n"
" ints[0]= 1;\n"
" for each(std::pair<int,int> i in ints) { x += i.first; }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvarShift1() {
functionVariableUsage("int foo()\n"
"{\n"
" int var = 1;\n"
" return 1 >> var;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvarShift3() { // #3509
functionVariableUsage("int foo()\n"
"{\n"
" QList<int *> ints;\n"
" ints << 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int foo() {\n" // #4320
" int x;\n"
" x << 1;\n"
" return x;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvarCast() {
functionVariableUsage("int foo()\n"
"{\n"
" int a = 1;\n"
" int b = static_cast<int>(a);\n"
" return b;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvarClass() {
functionVariableUsage("int foo()\n"
"{\n"
" class B : public A {\n"
" int a;\n"
" int f() { return a; }\n"
" } b;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvarUnused() {
functionVariableUsage("int foo()\n"
"{\n"
" bool test __attribute__((unused));\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int foo()\n"
"{\n"
" bool test __attribute__((unused)) = true;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int foo()\n"
"{\n"
" bool __attribute__((unused)) test;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int foo()\n"
"{\n"
" bool __attribute__((unused)) test = true;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int foo()\n"
"{\n"
" bool test __attribute__((used));\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int foo()\n"
"{\n"
" bool __attribute__((used)) test;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int foo()\n"
"{\n"
" char a[1] __attribute__((unused));\n"
" char b[1][2] __attribute__((unused));\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvarFunction() {
functionVariableUsage("void check_dlsym(void*& h)\n"
"{\n"
" typedef void (*function_type) (void);\n"
" function_type fn;\n"
" fn = reinterpret_cast<function_type>(dlsym(h, \"try_allocation\"));\n"
" fn();\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvarstatic() {
functionVariableUsage("void foo()\n"
"{\n"
" static int i;\n"
" static const int ci;\n"
" static std::string s;\n"
" static const std::string cs;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Unused variable: i\n"
"[test.cpp:4]: (style) Unused variable: ci\n"
"[test.cpp:5]: (style) Unused variable: s\n"
"[test.cpp:6]: (style) Unused variable: cs\n",
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" static int i = 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'i' is assigned a value that is never used.\n",
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" static int i(0);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'i' is assigned a value that is never used.\n",
"",
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" static int j = 0;\n"
" static int i(j);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:4]: (style) Variable 'i' is assigned a value that is never used.\n",
"",
errout_str());
functionVariableUsage("int * foo(int x)\n"
"{\n"
" static int a[] = { 3, 4, 5, 6 };\n"
" static int b[] = { 4, 5, 6, 7 };\n"
" static int c[] = { 5, 6, 7, 8 };\n"
" b[1] = 1;\n"
" return x ? a : c;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:6]: (style) Variable 'b' is assigned a value that is never used.\n",
"",
errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" static int i = 0;\n"
" if(i < foo())\n"
" i += 5;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo() {\n"
" static int x = 0;\n"
" print(x);\n"
" if(x > 5)\n"
" x = 0;\n"
" else\n"
" x++;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo(int value) {\n"
" static int array[16] = {0};\n"
" if(array[value]) {}\n"
" array[value] = 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int fun() {\n" // #11310
" static int k;\n"
" k++;\n"
" return k;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int& f() {\n" // #12935
" static int i;\n"
" return i;\n"
"}\n"
"int* g() {\n"
" static int j;\n"
" return &j;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void localvarextern() {
functionVariableUsage("void foo() {\n"
" extern int i;\n"
" i = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvardynamic1() {
functionVariableUsage("void foo()\n"
"{\n"
" void* ptr = malloc(16);\n"
" free(ptr);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'ptr' is allocated memory that is never used.\n", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" char* ptr = new char[16];\n"
" delete[] ptr;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'ptr' is allocated memory that is never used.\n", errout_str());
// extracttests.disable
functionVariableUsage("void foo()\n"
"{\n"
" char* ptr = new ( nothrow ) char[16];\n"
" delete[] ptr;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'ptr' is allocated memory that is never used.\n", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" char* ptr = new ( std::nothrow ) char[16];\n"
" delete[] ptr;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'ptr' is allocated memory that is never used.\n", errout_str());
// extracttests.enable
functionVariableUsage("void foo()\n"
"{\n"
" char* ptr = new char;\n"
" delete ptr;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'ptr' is allocated memory that is never used.\n", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" void* ptr = malloc(16);\n"
" ptr[0] = 123;\n"
" free(ptr);\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" char* ptr = new char[16];\n"
" ptr[0] = 123;\n"
" delete[] ptr;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" Fred* fred = new Fred;\n"
" std::cout << \"test\" << std::endl;\n"
" delete fred;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("struct Fred { int a; };\n"
"void foo()\n"
"{\n"
" Fred* fred = new Fred;\n"
" std::cout << \"test\" << std::endl;\n"
" delete fred;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Variable 'fred' is allocated memory that is never used.\n", errout_str());
functionVariableUsage("struct Fred { int a; Fred() : a(0) {} };\n"
"void foo()\n"
"{\n"
" Fred* fred = new Fred;\n"
" std::cout << \"test\" << std::endl;\n"
" delete fred;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Variable 'fred' is allocated memory that is never used.\n", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" Fred* fred = malloc(sizeof(Fred));\n"
" std::cout << \"test\" << std::endl;\n"
" free(fred);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'fred' is allocated memory that is never used.\n", errout_str());
functionVariableUsage("void foo()\n"
"{\n"
" char* ptr = names[i];\n"
" delete[] ptr;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvardynamic2() {
functionVariableUsage("struct Fred { int i; };\n"
"void foo()\n"
"{\n"
" Fred* ptr = (Fred*)malloc(sizeof(Fred));\n"
" free(ptr);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Variable 'ptr' is allocated memory that is never used.\n", errout_str());
functionVariableUsage("struct Fred { int i; };\n"
"void foo()\n"
"{\n"
" Fred* ptr = (Fred*)malloc(sizeof(Fred));\n"
" ptr->i = 0;\n"
" free(ptr);\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("struct Fred { int i; };\n"
"void foo()\n"
"{\n"
" struct Fred* ptr = (Fred*)malloc(sizeof(Fred));\n"
" free(ptr);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Variable 'ptr' is allocated memory that is never used.\n", errout_str());
functionVariableUsage("struct Fred { int i; };\n"
"void foo()\n"
"{\n"
" struct Fred* ptr = (Fred*)malloc(sizeof(Fred));\n"
" ptr->i = 0;\n"
" free(ptr);\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("struct Fred { int i; };\n"
"void foo()\n"
"{\n"
" Fred* ptr = new Fred();\n"
" delete ptr;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Variable 'ptr' is allocated memory that is never used.\n", errout_str());
// extracttests.disable
functionVariableUsage("struct Fred { int i; };\n"
"void foo()\n"
"{\n"
" Fred* ptr = new (nothrow ) Fred();\n"
" delete ptr;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Variable 'ptr' is allocated memory that is never used.\n", errout_str());
functionVariableUsage("struct Fred { int i; };\n"
"void foo()\n"
"{\n"
" Fred* ptr = new (std::nothrow) Fred();\n"
" delete ptr;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Variable 'ptr' is allocated memory that is never used.\n", errout_str());
// extracttests.enable
functionVariableUsage("struct Fred { int i; };\n"
"void foo()\n"
"{\n"
" Fred* ptr = new Fred();\n"
" ptr->i = 0;\n"
" delete ptr;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("struct Fred { int i; };\n"
"void foo()\n"
"{\n"
" struct Fred* ptr = new Fred();\n"
" delete ptr;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Variable 'ptr' is allocated memory that is never used.\n", errout_str());
functionVariableUsage("struct Fred { int i; };\n"
"void foo()\n"
"{\n"
" struct Fred* ptr = new Fred();\n"
" ptr->i = 0;\n"
" free(ptr);\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("class Fred { public: int i; };\n"
"void foo()\n"
"{\n"
" Fred* ptr = (Fred*)malloc(sizeof(Fred));\n"
" free(ptr);\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Variable 'ptr' is allocated memory that is never used.\n", errout_str());
functionVariableUsage("class Fred { public: int i; };\n"
"void foo()\n"
"{\n"
" Fred* ptr = (Fred*)malloc(sizeof(Fred));\n"
" ptr->i = 0;\n"
" free(ptr);\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("class Fred { public: int i; };\n"
"void foo()\n"
"{\n"
" Fred* ptr = new Fred();\n"
" delete ptr;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Variable 'ptr' is allocated memory that is never used.\n", errout_str());
functionVariableUsage("class Fred { public: int i; };\n"
"void foo()\n"
"{\n"
" Fred* ptr = new Fred();\n"
" ptr->i = 0;\n"
" delete ptr;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvardynamic3() {
// Ticket #3467 - False positive that 'data' is not assigned a value
functionVariableUsage("void foo() {\n"
" int* data = new int[100];\n"
" int* p = data;\n"
" for ( int i = 0; i < 10; ++i )\n"
" p++;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:5]: (style) Variable 'p' is modified but its new value is never used.\n",
"",
errout_str());
}
void localvararray1() {
functionVariableUsage("void foo() {\n"
" int p[5];\n"
" *p = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvararray2() {
functionVariableUsage("int foo() {\n"
" int p[5][5];\n"
" p[0][0] = 0;\n"
" return p[0][0];\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvararray3() {
functionVariableUsage("int foo() {\n"
" int p[5][5];\n"
" *((int*)p[0]) = 0;\n"
" return p[0][0];\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvararray4() {
functionVariableUsage("void foo() {\n"
" int p[1];\n"
" int *pp[0];\n"
" p[0] = 1;\n"
" *pp[0] = p[0];\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvararray5() {
functionVariableUsage("int foo() {\n"
" int p[5][5];\n"
" dostuff(*p);\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int foo() {\n"
" int p[5];\n"
" dostuff(*p);\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int foo() {\n"
" int p[5][5][5];\n"
" dostuff(**p);\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void f() {\n" // #11872
" char v[1][2];\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Unused variable: v\n", errout_str());
}
void localvararray6() {
functionVariableUsage("struct S { int* p; };\n" // #11012
"void g(struct S* ps);\n"
"void f() {\n"
" int i[2];\n"
" struct S s = { i };\n"
" g(&s);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void localvarstring1() { // ticket #1597
functionVariableUsage("void foo() {\n"
" std::string s;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Unused variable: s\n", errout_str());
functionVariableUsage("void foo() {\n"
" std::string s;\n"
" s = \"foo\";\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 's' is assigned a value that is never used.\n", errout_str());
functionVariableUsage("void foo() {\n"
" std::string s = \"foo\";\n"
"}");
ASSERT_EQUALS(
"[test.cpp:2]: (style) Variable 's' is assigned a value that is never used.\n"
"[test.cpp:2]: (style) Variable 's' is assigned a value that is never used.\n", // duplicate
errout_str());
functionVariableUsage("void foo() {\n" // #8901
" const std::string s = \"foo\";\n"
"}");
ASSERT_EQUALS(
"[test.cpp:2]: (style) Variable 's' is assigned a value that is never used.\n"
"[test.cpp:2]: (style) Variable 's' is assigned a value that is never used.\n", // duplicate
errout_str());
functionVariableUsage("std::string foo() {\n"
" std::string s;\n" // Class instances are initialized. Assignment is not necessary
" return s;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("std::string foo() {\n"
" std::string s = \"foo\";\n"
" return s;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void f() {\n"
" std::string s(\"foo\");\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Variable 's' is assigned a value that is never used.\n", errout_str());
functionVariableUsage("void f() {\n"
" std::string s{ \"foo\" };\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Variable 's' is assigned a value that is never used.\n", errout_str());
}
void localvarstring2() { // ticket #2929
functionVariableUsage("void foo() {\n"
" std::string s;\n"
" int i;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Unused variable: s\n"
"[test.cpp:3]: (style) Unused variable: i\n", errout_str());
}
void localvarconst1() {
functionVariableUsage("void foo() {\n"
" const bool b = true;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:2]: (style) Variable 'b' is assigned a value that is never used.\n"
"[test.cpp:2]: (style) Variable 'b' is assigned a value that is never used.\n", // duplicate
errout_str());
}
void localvarconst2() {
functionVariableUsage("void foo() {\n"
" const int N = 10;\n"
" struct X { int x[N]; };\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvarreturn() { // ticket #9167
functionVariableUsage("void foo() {\n"
" const int MyInt = 1;\n"
" class bar {\n"
" public:\n"
" bool operator()(const int &uIndexA, const int &uIndexB) const {\n"
" return true;\n"
" }\n"
" bar() {}\n"
" };\n"
" return MyInt;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvarmaybeunused() {
functionVariableUsage("int main() {\n"
" [[maybe_unused]] int x;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("[[nodiscard]] int getX() { return 4; }\n"
"int main() {\n"
" [[maybe_unused]] int x = getX();\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("[[nodiscard]] int getX() { return 4; }\n"
"int main() {\n"
" [[maybe_unused]] int x = getX();\n"
" x = getX();\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("[[nodiscard]] int getX() { return 4; }\n"
"int main() {\n"
" [[maybe_unused]] int x = getX();\n"
" x = getX();\n"
" std::cout << x;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int main() {\n"
" [[maybe_unused]] const int x = getX();\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int main() {\n"
" [[maybe_unused]] const int& x = getX();\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int main() {\n"
" [[maybe_unused]] const int* x = getX();\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int main() {\n"
" [[maybe_unused]] int& x = getX();\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int main() {\n"
" [[maybe_unused]] int* x = getX();\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int main() {\n"
" [[maybe_unused]] auto x = getX();\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int main() {\n"
" [[maybe_unused]] auto&& x = getX();\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int main() {\n"
" [[maybe_unused]] int x[] = getX();\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int main() {\n"
" [[maybe_unused]] constexpr volatile static int x = 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("[[maybe_unused]] inline int x = 1;");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int main() {\n"
" [[maybe_unused]] [[anotherattribute]] const int* = 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int main() {\n"
" [[maybe_unused]] char a[1];\n"
" [[maybe_unused]] char b[1][2];\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvarthrow() { // ticket #3687
functionVariableUsage("void foo() {\n"
" try {}"
" catch(Foo& bar) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localVarStd() {
// extracttests.start: struct MyClass {int x;}; std::string foo();
functionVariableUsage("void f() {\n"
" std::string x = foo();\n"
"}");
ASSERT_EQUALS(
"[test.cpp:2]: (style) Variable 'x' is assigned a value that is never used.\n"
"[test.cpp:2]: (style) Variable 'x' is assigned a value that is never used.\n", // duplicate
errout_str());
functionVariableUsage("void f() {\n"
" std::vector<int> x;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Unused variable: x\n", errout_str());
functionVariableUsage("void f() {\n"
" std::vector<int> x(100);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Variable 'x' is assigned a value that is never used.\n", errout_str());
functionVariableUsage("void f() {\n"
" std::vector<MyClass> x;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Unused variable: x\n", errout_str());
functionVariableUsage("void f() {\n"
" std::lock_guard<MyClass> lock(mutex_);\n" // Has a side-effect #4385
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void f() {\n"
" pLocker = std::shared_ptr<jfxLocker>(new jfxLocker(m_lock, true));\n" // Could have side-effects (#4355)
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void f() {\n"
" std::mutex m;\n"
" std::unique_lock<std::mutex> lock(m);\n" // #4624
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void f() {\n" // #7732
" const std::pair<std::string, std::string> p(\"a\", \"b\");\n"
" std::pair<std::string, std::string> q{\"a\", \"b\" };\n"
" auto r = std::pair<std::string, std::string>(\"a\", \"b\");\n"
" auto s = std::pair<std::string, std::string>{ \"a\", \"b\" };\n"
"}\n");
TODO_ASSERT_EQUALS("[test.cpp:2]: (style) Variable 'p' is assigned a value that is never used.\n"
"[test.cpp:3]: (style) Variable 'q' is assigned a value that is never used.\n"
"[test.cpp:4]: (style) Variable 'r' is assigned a value that is never used.\n"
"[test.cpp:5]: (style) Variable 's' is assigned a value that is never used.\n",
"[test.cpp:2]: (style) Variable 'p' is assigned a value that is never used.\n"
"[test.cpp:3]: (style) Variable 'q' is assigned a value that is never used.\n",
errout_str());
functionVariableUsage("void f(std::span<int> s) {\n" // #11545
" s[0] = 0;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("struct S {\n"
" std::mutex m;\n"
" void f();\n"
"};\n"
"void S::f() {\n"
" const ::std::lock_guard g(m);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void f(const std::string& str, int i) {\n" // #11879
" const std::string s = str;\n"
" switch (i) {\n"
" default:\n"
" break;\n"
" }\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Variable 's' is assigned a value that is never used.\n", errout_str());
}
void localVarClass() {
functionVariableUsage("void f() {\n"
" Fred f;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("class C { int x; };\n"
"void f() {\n"
" C c;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Unused variable: c\n", errout_str());
functionVariableUsage("class ExampleClass\n" // #10000
"{\n"
"public:\n"
" ExampleClass(int xScale, int yScale, int x, int y)\n"
" : XScale(xScale)\n"
" , YScale(yScale)\n"
" , X(x)\n"
" , Y(y)\n"
" {\n"
" }\n"
" \n"
" int XScale;\n"
" int YScale;\n"
" int X;\n"
" int Y;\n"
"};\n"
" \n"
"void foo()\n"
"{\n"
" ExampleClass ex(1, 2, 3, 4);\n"
"}");
ASSERT_EQUALS("[test.cpp:20]: (style) Variable 'ex' is assigned a value that is never used.\n", errout_str());
functionVariableUsage("class C { public: C(int); ~C(); };\n"
"void f() {\n"
" C c(12);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localVarSmartPtr() {
// handling of smart pointers (#9680)
functionVariableUsage("static int s_i = 0;\n"
"\n"
"class A {\n"
"public:\n"
" ~A() {\n"
" ++s_i;\n"
" }\n"
"};\n"
"\n"
"static void func() {\n"
" auto a = std::make_shared<A>();\n"
" auto a2 = std::unique_ptr<A>(new A());\n"
"}\n");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("class A {\n"
"public:\n"
" std::string x;\n"
"};\n"
"\n"
"static void func() {\n"
" auto a = std::make_shared<A>();\n"
" auto a2 = std::unique_ptr<A>(new A());\n"
"}\n");
ASSERT_EQUALS("[test.cpp:7]: (style) Variable 'a' is assigned a value that is never used.\n"
"[test.cpp:8]: (style) Variable 'a2' is assigned a value that is never used.\n", // duplicate
errout_str());
functionVariableUsage("void g();\n" // #11094
"void f() {\n"
" auto p = std::make_unique<S>();\n"
" p = nullptr;\n"
" g();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int f(int *p) {\n" // #10703
" std::unique_ptr<int> up(p);\n"
" return *p;\n"
"}\n"
"int g(int* p) {\n"
" auto up = std::unique_ptr<int>(p);\n"
" return *p;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("struct S { S(); };\n" // #11108
"void f(std::unique_ptr<S> p) {\n"
" p = nullptr;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
// ticket #3104 - false positive when variable is read with "if (NOT var)"
void localvarIfNOT() {
functionVariableUsage("void f() {\n"
" bool x = foo();\n"
" if (NOT x) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvarAnd() { // #3672
functionVariableUsage("int main() {\n"
" unsigned flag = 0x1 << i;\n"
" if (m_errorflags & flag) {\n"
" return 1;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvarSwitch() { // #3744 - false positive when used in switch
functionVariableUsage("const char *f(int x) {\n"
" const char a[] = \"abc\";\n"
" const char def[] = \"def\";\n"
" const char *ptr;\n"
" switch(x) {\n"
" case 1: ptr=a; break;\n"
" default: ptr=def; break;\n"
" }\n"
" return ptr;\n"
"}");
ASSERT_EQUALS("", errout_str()); // Don't write an error that "a" is not used
functionVariableUsage("void x() {\n"
" unsigned char* pcOctet = NULL;\n"
" float fValeur;\n"
" switch (pnodeCurrent->left.pnode->usLen) {\n"
" case 4:\n"
" fValeur = (float)pevalDataLeft->data.fd;\n"
" pcOctet = (unsigned char*)&fValeur;\n"
" break;\n"
" case 8:\n"
" pcOctet = (unsigned char*)&pevalDataLeft->data.fd;\n"
" break;\n"
" }\n"
" for (iIndice = 1; iIndice <= (pnodeCurrent->usLen / 2); iIndice++) {\n"
" *pcData = gacHexChar[(*pcOctet >> 4) & 0x0F];\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str()); // Don't write an error that "fValeur" is not used
}
void localvarNULL() { // #4203 - Setting NULL value is not redundant - it is safe
functionVariableUsage("void f() {\n"
" char *p = malloc(100);\n"
" foo(p);\n"
" free(p);\n"
" p = NULL;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void f(Foo *p) {\n"
" free(p);\n"
" p = (Foo *)NULL;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void f() {\n" // #11079
" std::string s1{ nullptr };\n"
" std::string s2{ NULL };\n"
" std::string s4(nullptr);\n"
" std::string s5(NULL);\n"
"}\n"
"struct A { A(void*) {} };\n"
"static void g() {\n"
" A a1{ nullptr };\n"
" A a2{ NULL };\n"
" A a4(nullptr);\n"
" A a5(NULL);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Variable 's1' is assigned a value that is never used.\n"
"[test.cpp:3]: (style) Variable 's2' is assigned a value that is never used.\n"
"[test.cpp:4]: (style) Variable 's4' is assigned a value that is never used.\n"
"[test.cpp:5]: (style) Variable 's5' is assigned a value that is never used.\n"
"[test.cpp:9]: (style) Variable 'a1' is assigned a value that is never used.\n"
"[test.cpp:10]: (style) Variable 'a2' is assigned a value that is never used.\n"
"[test.cpp:11]: (style) Variable 'a4' is assigned a value that is never used.\n"
"[test.cpp:12]: (style) Variable 'a5' is assigned a value that is never used.\n",
errout_str());
}
void localvarUnusedGoto() {
// #4447
functionVariableUsage("bool f(const int &i) {\n"
" int X = i;\n"
"label:\n"
" if ( X == 0 ) {\n"
" X -= 101;\n"
" return true;\n"
" }\n"
" if ( X < 1001 ) {\n"
" X += 1;\n"
" goto label;\n"
" }\n"
" return false;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (style) Variable 'X' is assigned a value that is never used.\n", errout_str());
// #4558
functionVariableUsage("int f() {\n"
" int i,j=0;\n"
" start:\n"
" i=j;\n"
" i++;\n"
" j=i;\n"
" if (i<3)\n"
" goto start;\n"
" return i;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvarLambda() {
functionVariableUsage("int foo() {\n"
" auto f = []{return 1};\n"
" return f();\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int foo() {\n"
" auto f = []{return 1};\n"
" auto g = []{return 1};\n"
" return f() + g();\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void foo(std::vector<int>& v) {\n"
" int n = 0;\n"
" std::generate(v.begin(), v.end(), [&n] {\n"
" int r = n;\n"
" n += 2;\n"
" return r;\n"
" });\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int f() {\n" // #8433
" float a;\n"
" auto lambda = []() {};\n"
" return 0;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Unused variable: a\n", errout_str());
functionVariableUsage("void f() {\n" // #9823
" auto cb = []() {\n"
" int i;\n"
" };\n"
" (void)cb;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) Unused variable: i\n", errout_str());
functionVariableUsage("void f() {\n" // #9822
" int i;\n"
" auto cb = []() {\n"
" int i;\n"
" };\n"
" (void)cb;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Unused variable: i\n"
"[test.cpp:4]: (style) Unused variable: i\n",
errout_str());
}
void localvarStructuredBinding() {
functionVariableUsage("void f() {\n" // #10368
" std::map<int, double> m;\n"
" m[2] = 2.0;\n"
" for (auto& [k, v] : m) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void localvarCppInitialization() {
functionVariableUsage("void foo() {\n"
" int buf[6];\n"
" Data data(buf);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (information) --check-library: Provide <type-checks><unusedvar> configuration for Data\n", errout_str());
}
void localvarCpp11Initialization() {
// #6160
functionVariableUsage("void foo() {\n"
" int myNewValue{ 3u };\n"
" myManager.theDummyTable.addRow(UnsignedIndexValue{ myNewValue }, DummyRowData{ false });\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void f() {\n"
" std::list<std::list<int>>::value_type a{ 1, 2, 3, 4 };\n"
"}\n");
TODO_ASSERT_EQUALS("", "[test.cpp:2]: (information) --check-library: Provide <type-checks><unusedvar> configuration for std::list::value_type\n", errout_str());
functionVariableUsage("void f(int* p) {\n"
" int* q{ p };\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Variable 'q' is assigned a value that is never used.\n", errout_str());
}
void localvarRangeBasedFor() {
// #7075
functionVariableUsage("void reset() {\n"
" for (auto & e : array)\n"
" e = 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvarAssignInWhile() {
functionVariableUsage("void foo() {\n"
" int a = 0;\n"
" do {\n"
" dostuff(a);\n"
" } while((a += x) < 30);\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int foo() {\n"
" int var = 1;\n"
" while (var = var >> 1) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvarTemplate() {
functionVariableUsage("template<int A> void f() {}\n"
"void foo() {\n"
" const int x = 0;\n"
" f<x>();\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void f() {\n"
" constexpr std::size_t ArraySize(5);\n"
" std::array<int, ArraySize> X; X.dostuff();\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void f() {\n" // #10686
" std::array<int, 1> a;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Unused variable: a\n", errout_str());
functionVariableUsage("class A {};\n" // #9471
" namespace std {\n"
" template<>\n"
" struct hash<A> {};\n"
"}\n"
"char f() {\n"
" std::string hash = \"-\";\n"
" return hash[0];\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void localvarFuncPtr() {
functionVariableUsage("int main() {\n"
" void(*funcPtr)(void)(x);\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:2]: (style) Variable 'funcPtr' is assigned a value never used.\n", "", errout_str());
functionVariableUsage("int main() {\n"
" void(*funcPtr)(void);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Unused variable: funcPtr\n", errout_str());
functionVariableUsage("int main() {\n"
" void(*funcPtr)(void)(x);\n"
" funcPtr();\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("int main() {\n"
" void(*funcPtr)(void) = x;\n"
" funcPtr();\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvarAddr() { // #7747
functionVariableUsage("void f() {\n"
" int x = 0;\n"
" dostuff(&x);\n"
" x = 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void f() {\n"
" int x = 0;\n"
" dostuff(std::ref(x));\n"
" x = 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void localvarDelete() { // #8339
functionVariableUsage("void reassign(char*& data, int size)"
"{"
" char* buf = new char[size];"
""
" char* tmp = data;"
" data = buf;"
" buf = tmp;"
""
" delete [] buf;"
"}");
ASSERT_EQUALS("", errout_str());
}
void chainedAssignment() {
// #5466
functionVariableUsage("void NotUsed(double* pdD, int n) {\n"
" double sum = 0.0;\n"
" for (int i = 0; i<n; ++i)\n"
" pdD[i] = (sum += pdD[i]);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void crash1() {
functionVariableUsage("SAL_WNODEPRECATED_DECLARATIONS_PUSH\n"
"void convertToTokenArray() {\n"
"}\n"
"SAL_WNODEPRECATED_DECLARATIONS_POP"); // #4033
}
void crash2() {
functionVariableUsage("template<unsigned dim>\n"
"struct Y: Y<dim-1> { };\n"
"template<>\n"
"struct Y<0> {};\n"
"void f() {\n"
" Y y;\n"
"}"); // #4695
}
void crash3() {
functionVariableUsage("void f(int a, int b, const int* p) {\n" // #12531
" const int* s[] = { p, p + 1, p + 2 };\n"
" a = *(s[a] + b);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'a' is assigned a value that is never used.\n", errout_str());
}
void usingNamespace() {
functionVariableUsage("int foo() {\n"
" using namespace ::com::sun::star::i18n;\n"
" bool b = false;\n"
" int j = 0;\n"
" for (int i = 0; i < 3; i++) {\n"
" if (!b) {\n"
" j = 3;\n"
" b = true;\n"
" }\n"
" }\n"
" return j;\n"
"}"); // #4585
ASSERT_EQUALS("", errout_str());
}
void lambdaFunction() {
// #7026
functionVariableUsage("void f() {\n"
" bool first = true;\n"
"\n"
" auto do_something = [&first]() {\n"
" if (first) {\n"
" first = false;\n"
" } else {\n"
" dostuff();\n"
" }\n"
" };\n"
" do_something();\n"
" do_something();\n"
"}");
ASSERT_EQUALS("", errout_str());
// #4956 - assignment in for_each
functionVariableUsage("void f(std::vector<int> ints) {\n"
" int x = 0;\n"
" std::for_each(ints.begin(), ints.end(), [&x](int i){ dostuff(x); x = i; });\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage("void f(std::vector<int> ints) {\n"
" int x = 0;\n"
" std::for_each(ints.begin(), ints.end(), [&x](int i){ x += i; });\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'x' is assigned a value that is never used.\n", "", errout_str());
functionVariableUsage("int f(const std::vector<int>& v) {\n"
" auto it = std::find_if(v.begin(), v.end(), [&](int i) { return i > 0 && i < 7; });\n"
" std::unordered_map<std::string, std::vector<int*>> exprs;\n"
" return *it;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Unused variable: exprs\n", errout_str());
}
void namespaces() { // #7557
functionVariableUsage("namespace t { namespace g {\n"
" typedef std::pair<BoostBox, size_t> value;\n"
"} }\n"
"namespace t { namespace g {} }\n"
"namespace t {\n"
" inline double getTime() const {\n"
" iterator it=find();\n"
" double& value=it->second.values[index];\n"
" if(isnan(value)) {\n"
" value=get();\n"
" }\n"
" return value;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void bracesInitCpp11() {
functionVariableUsage(
"int fun() {\n"
" static int fpUnread{0};\n"
" const int var{fpUnread++};\n"
" return var;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void argument() {
functionVariableUsage(
"void fun(Value value) {\n"
" value[10] = 123;\n"
"}");
ASSERT_EQUALS("", errout_str());
functionVariableUsage(
"void fun(std::string s) {\n"
" s[10] = 123;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Variable 's[10]' is assigned a value that is never used.\n", errout_str());
functionVariableUsage(
"void fun(short data[2]) {\n"
" data[2] = 1;\n"
"}"
);
ASSERT_EQUALS("", errout_str());
// Unknown argument type
functionVariableUsage(
"void A::b(Date& result) {"
" result = 12;\n"
"}"
);
ASSERT_EQUALS("", errout_str());
{
// #8914
functionVariableUsage( // assume unknown argument type is reference
"void fun(Date result) {"
" result.x = 12;\n"
"}"
);
ASSERT_EQUALS("", errout_str());
functionVariableUsage( // there is no reference type in C
"void fun(Date result) {"
" result.x = 12;\n"
"}",
false
);
ASSERT_EQUALS("[test.c:1]: (style) Variable 'result.x' is assigned a value that is never used.\n", errout_str());
functionVariableUsage(
"struct Date { int x; };\n"
"void fun(Date result) {"
" result.x = 12;\n"
"}"
);
ASSERT_EQUALS("[test.cpp:2]: (style) Variable 'result.x' is assigned a value that is never used.\n", errout_str());
}
// Unknown struct type
functionVariableUsage(
"void fun() {"
" struct FOO foo;\n"
" foo.x = 123;\n"
"}"
);
ASSERT_EQUALS("[test.cpp:2]: (style) Variable 'foo.x' is assigned a value that is never used.\n", errout_str());
}
void argumentClass() {
functionVariableUsage(
"void foo(std::insert_iterator<C> it) {\n"
" it = 123;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void escapeAlias() {
functionVariableUsage(
"struct A {\n"
" std::map<int, int> m;\n"
" void f(int key, int number) {\n"
" auto pos = m.find(key);\n"
" if (pos == m.end())\n"
" m.insert(std::map<int, int>::value_type(key, number));\n"
" else\n"
" (*pos).second = number;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void volatileData() {
functionVariableUsage(
"struct Data { unsigned int n; };\n"
"int main() {\n"
" (*(volatile struct Data*)0x4200).n = 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void globalData() {
// #10276
functionVariableUsage(
"void f(void) {\n"
" ((uint8_t *) (uint16_t)0x1000)[0] = 0x42;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
};
REGISTER_TEST(TestUnusedVar)
| null |
996 | cpp | cppcheck | teststandards.cpp | test/teststandards.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "fixture.h"
#include "standards.h"
class TestStandards : public TestFixture {
public:
TestStandards() : TestFixture("TestStandards") {}
private:
void run() override {
TEST_CASE(set);
TEST_CASE(setCPPAlias);
TEST_CASE(setCAlias);
TEST_CASE(getC);
TEST_CASE(getCPP);
TEST_CASE(setStd);
}
void set() const {
Standards stds;
ASSERT_EQUALS_ENUM(Standards::CLatest, stds.c);
ASSERT_EQUALS("", stds.stdValueC);
ASSERT_EQUALS_ENUM(Standards::CPPLatest, stds.cpp);
ASSERT_EQUALS("", stds.stdValueCPP);
ASSERT_EQUALS(true, stds.setC("c99"));
ASSERT_EQUALS_ENUM(Standards::C99, stds.c);
ASSERT_EQUALS("c99", stds.stdValueC);
ASSERT_EQUALS_ENUM(Standards::CPPLatest, stds.cpp);
ASSERT_EQUALS("", stds.stdValueCPP);
ASSERT_EQUALS(true, stds.setC("c11"));
ASSERT_EQUALS_ENUM(Standards::C11, stds.c);
ASSERT_EQUALS("c11", stds.stdValueC);
ASSERT_EQUALS_ENUM(Standards::CPPLatest, stds.cpp);
ASSERT_EQUALS("", stds.stdValueCPP);
ASSERT_EQUALS(true, stds.setCPP("c++11"));
ASSERT_EQUALS_ENUM(Standards::C11, stds.c);
ASSERT_EQUALS("c11", stds.stdValueC);
ASSERT_EQUALS_ENUM(Standards::CPP11, stds.cpp);
ASSERT_EQUALS("c++11", stds.stdValueCPP);
ASSERT_EQUALS(true, stds.setCPP("c++23"));
ASSERT_EQUALS_ENUM(Standards::C11, stds.c);
ASSERT_EQUALS("c11", stds.stdValueC);
ASSERT_EQUALS_ENUM(Standards::CPP23, stds.cpp);
ASSERT_EQUALS("c++23", stds.stdValueCPP);
ASSERT_EQUALS(false, stds.setC("c77"));
ASSERT_EQUALS_ENUM(Standards::C11, stds.c);
ASSERT_EQUALS("c11", stds.stdValueC);
ASSERT_EQUALS_ENUM(Standards::CPP23, stds.cpp);
ASSERT_EQUALS("c++23", stds.stdValueCPP);
ASSERT_EQUALS(false, stds.setCPP("c+77"));
ASSERT_EQUALS_ENUM(Standards::C11, stds.c);
ASSERT_EQUALS("c11", stds.stdValueC);
ASSERT_EQUALS_ENUM(Standards::CPP23, stds.cpp);
ASSERT_EQUALS("c++23", stds.stdValueCPP);
ASSERT_EQUALS(false, stds.setC("C23"));
ASSERT_EQUALS_ENUM(Standards::C11, stds.c);
ASSERT_EQUALS("c11", stds.stdValueC);
ASSERT_EQUALS_ENUM(Standards::CPP23, stds.cpp);
ASSERT_EQUALS("c++23", stds.stdValueCPP);
ASSERT_EQUALS(false, stds.setCPP("C++11"));
ASSERT_EQUALS_ENUM(Standards::C11, stds.c);
ASSERT_EQUALS("c11", stds.stdValueC);
ASSERT_EQUALS_ENUM(Standards::CPP23, stds.cpp);
ASSERT_EQUALS("c++23", stds.stdValueCPP);
}
void setCPPAlias() const {
Standards stds;
ASSERT_EQUALS(true, stds.setCPP("gnu++11"));
ASSERT_EQUALS_ENUM(Standards::CLatest, stds.c);
ASSERT_EQUALS("", stds.stdValueC);
ASSERT_EQUALS_ENUM(Standards::CPP11, stds.cpp);
ASSERT_EQUALS("gnu++11", stds.stdValueCPP);
}
void setCAlias() const {
Standards stds;
ASSERT_EQUALS(true, stds.setC("gnu17"));
ASSERT_EQUALS_ENUM(Standards::C17, stds.c);
ASSERT_EQUALS("gnu17", stds.stdValueC);
ASSERT_EQUALS_ENUM(Standards::CPPLatest, stds.cpp);
ASSERT_EQUALS("", stds.stdValueCPP);
}
void getC() const {
ASSERT_EQUALS_ENUM(Standards::C99, Standards::getC("c99"));
ASSERT_EQUALS_ENUM(Standards::C11, Standards::getC("c11"));
ASSERT_EQUALS_ENUM(Standards::C17, Standards::getC("gnu17"));
ASSERT_EQUALS_ENUM(Standards::C11, Standards::getC("iso9899:2011"));
ASSERT_EQUALS_ENUM(Standards::CLatest, Standards::getC(""));
ASSERT_EQUALS_ENUM(Standards::CLatest, Standards::getC("c77"));
ASSERT_EQUALS_ENUM(Standards::CLatest, Standards::getC("C99"));
}
void getCPP() const {
ASSERT_EQUALS_ENUM(Standards::CPP11, Standards::getCPP("c++11"));
ASSERT_EQUALS_ENUM(Standards::CPP23, Standards::getCPP("c++23"));
ASSERT_EQUALS_ENUM(Standards::CPP23, Standards::getCPP("gnu++23"));
ASSERT_EQUALS_ENUM(Standards::CPPLatest, Standards::getCPP(""));
ASSERT_EQUALS_ENUM(Standards::CPPLatest, Standards::getCPP("c++77"));
ASSERT_EQUALS_ENUM(Standards::CPPLatest, Standards::getCPP("C++11"));
}
void setStd() const {
Standards stds;
ASSERT(stds.setStd("c11"));
ASSERT(stds.setStd("c++11"));
ASSERT(stds.setStd("gnu11"));
ASSERT(stds.setStd("gnu++17"));
ASSERT(stds.setStd("iso9899:2011"));
ASSERT(!stds.setStd("C++11"));
ASSERT(!stds.setStd("Gnu++11"));
}
};
REGISTER_TEST(TestStandards)
| null |
997 | cpp | cppcheck | testcondition.cpp | test/testcondition.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "checkcondition.h"
#include "errortypes.h"
#include "fixture.h"
#include "helpers.h"
#include "platform.h"
#include "settings.h"
#include "tokenize.h"
#include <cstddef>
#include <limits>
#include <string>
#include <vector>
class TestCondition : public TestFixture {
public:
TestCondition() : TestFixture("TestCondition") {}
private:
const Settings settings0 = settingsBuilder().library("qt.cfg").library("std.cfg").severity(Severity::style).severity(Severity::warning).build();
/*const*/ Settings settings1 = settingsBuilder().severity(Severity::style).severity(Severity::warning).build();
void run() override {
const char cfg[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <function name=\"bar\"> <pure/> </function>\n"
"</def>";
settings1 = settingsBuilder(settings1).libraryxml(cfg, sizeof(cfg)).build();
TEST_CASE(assignAndCompare); // assignment and comparison don't match
TEST_CASE(mismatchingBitAnd); // overlapping bitmasks
TEST_CASE(comparison); // CheckCondition::comparison test cases
TEST_CASE(multicompare); // mismatching comparisons
TEST_CASE(overlappingElseIfCondition); // overlapping conditions in if and else-if
TEST_CASE(oppositeElseIfCondition); // opposite conditions in if and else-if
TEST_CASE(checkBadBitmaskCheck);
TEST_CASE(incorrectLogicOperator1);
TEST_CASE(incorrectLogicOperator2);
TEST_CASE(incorrectLogicOperator3);
TEST_CASE(incorrectLogicOperator4);
TEST_CASE(incorrectLogicOperator5); // complex expressions
TEST_CASE(incorrectLogicOperator6); // char literals
TEST_CASE(incorrectLogicOperator7); // opposite expressions: (expr || !expr)
TEST_CASE(incorrectLogicOperator8); // !
TEST_CASE(incorrectLogicOperator9);
TEST_CASE(incorrectLogicOperator10); // enum
TEST_CASE(incorrectLogicOperator11);
TEST_CASE(incorrectLogicOperator12);
TEST_CASE(incorrectLogicOperator13);
TEST_CASE(incorrectLogicOperator14);
TEST_CASE(incorrectLogicOperator15);
TEST_CASE(incorrectLogicOperator16); // #10070
TEST_CASE(incorrectLogicOperator17);
TEST_CASE(secondAlwaysTrueFalseWhenFirstTrueError);
TEST_CASE(incorrectLogicOp_condSwapping);
TEST_CASE(testBug5895);
TEST_CASE(testBug5309);
TEST_CASE(modulo);
TEST_CASE(oppositeInnerCondition);
TEST_CASE(oppositeInnerConditionPointers);
TEST_CASE(oppositeInnerConditionClass);
TEST_CASE(oppositeInnerConditionUndeclaredVariable);
TEST_CASE(oppositeInnerConditionAlias);
TEST_CASE(oppositeInnerCondition2);
TEST_CASE(oppositeInnerCondition3);
TEST_CASE(oppositeInnerConditionAnd);
TEST_CASE(oppositeInnerConditionOr);
TEST_CASE(oppositeInnerConditionEmpty);
TEST_CASE(oppositeInnerConditionFollowVar);
TEST_CASE(identicalInnerCondition);
TEST_CASE(identicalConditionAfterEarlyExit);
TEST_CASE(innerConditionModified);
TEST_CASE(clarifyCondition1); // if (a = b() < 0)
TEST_CASE(clarifyCondition2); // if (a & b == c)
TEST_CASE(clarifyCondition3); // if (! a & b)
TEST_CASE(clarifyCondition4); // ticket #3110
TEST_CASE(clarifyCondition5); // #3609 CWinTraits<WS_CHILD|WS_VISIBLE>..
TEST_CASE(clarifyCondition6); // #3818
TEST_CASE(clarifyCondition7);
TEST_CASE(clarifyCondition8);
TEST_CASE(alwaysTrue);
TEST_CASE(alwaysTrueSymbolic);
TEST_CASE(alwaysTrueInfer);
TEST_CASE(alwaysTrueContainer);
TEST_CASE(alwaysTrueLoop);
TEST_CASE(alwaysTrueTryCatch);
TEST_CASE(multiConditionAlwaysTrue);
TEST_CASE(duplicateCondition);
TEST_CASE(checkInvalidTestForOverflow);
TEST_CASE(checkConditionIsAlwaysTrueOrFalseInsideIfWhile);
TEST_CASE(alwaysTrueFalseInLogicalOperators);
TEST_CASE(pointerAdditionResultNotNull);
TEST_CASE(duplicateConditionalAssign);
TEST_CASE(checkAssignmentInCondition);
TEST_CASE(compareOutOfTypeRange);
TEST_CASE(knownConditionCast); // #9976
TEST_CASE(knownConditionIncrementLoop); // #9808
TEST_CASE(knownConditionAfterBailout); // #12526
TEST_CASE(knownConditionIncDecOperator);
}
#define check(...) check_(__FILE__, __LINE__, __VA_ARGS__)
void check_(const char* file, int line, const char code[], const Settings &settings, const char* filename = "test.cpp") {
std::vector<std::string> files(1, filename);
Tokenizer tokenizer(settings, *this);
PreprocessorHelper::preprocess(code, files, tokenizer, *this);
// Tokenizer..
ASSERT_LOC(tokenizer.simplifyTokens1(""), file, line);
// Run checks..
runChecks<CheckCondition>(tokenizer, this);
}
void check_(const char* file, int line, const char code[], const char* filename = "test.cpp", bool inconclusive = false) {
const Settings settings = settingsBuilder(settings0).certainty(Certainty::inconclusive, inconclusive).build();
check_(file, line, code, settings, filename);
}
#define checkP(...) checkP_(__FILE__, __LINE__, __VA_ARGS__)
void checkP_(const char* file, int line, const char code[], const char* filename = "test.cpp")
{
const Settings settings = settingsBuilder(settings0).severity(Severity::performance).certainty(Certainty::inconclusive).build();
std::vector<std::string> files(1, filename);
Tokenizer tokenizer(settings, *this);
PreprocessorHelper::preprocess(code, files, tokenizer, *this);
// Tokenizer..
ASSERT_LOC(tokenizer.simplifyTokens1(""), file, line);
// Run checks..
runChecks<CheckCondition>(tokenizer, this);
}
void assignAndCompare() {
// &
check("void foo(int x)\n"
"{\n"
" int y = x & 4;\n"
" if (y == 3);\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (style) Mismatching assignment and comparison, comparison 'y==3' is always false.\n", errout_str());
check("void foo(int x)\n"
"{\n"
" int y = x & 4;\n"
" if (y != 3);\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (style) Mismatching assignment and comparison, comparison 'y!=3' is always true.\n", errout_str());
// |
check("void foo(int x) {\n"
" int y = x | 0x14;\n"
" if (y == 0x710);\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) Mismatching assignment and comparison, comparison 'y==0x710' is always false.\n", errout_str());
check("void foo(int x) {\n"
" int y = x | 0x14;\n"
" if (y == 0x71f);\n"
"}");
ASSERT_EQUALS("", errout_str());
// various simple assignments
check("void foo(int x) {\n"
" int y = (x+1) | 1;\n"
" if (y == 2);\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) Mismatching assignment and comparison, comparison 'y==2' is always false.\n", errout_str());
check("void foo() {\n"
" int y = 1 | x();\n"
" if (y == 2);\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) Mismatching assignment and comparison, comparison 'y==2' is always false.\n", errout_str());
// multiple conditions
check("void foo(int x) {\n"
" int y = x & 4;\n"
" if ((y == 3) && (z == 1));\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) Mismatching assignment and comparison, comparison 'y==3' is always false.\n", errout_str());
check("void foo(int x) {\n"
" int y = x & 4;\n"
" if ((x==123) || ((y == 3) && (z == 1)));\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) Mismatching assignment and comparison, comparison 'y==3' is always false.\n", errout_str());
check("void f(int x) {\n"
" int y = x & 7;\n"
" if (setvalue(&y) && y != 8);\n"
"}");
ASSERT_EQUALS("", errout_str());
// recursive checking into scopes
check("void f(int x) {\n"
" int y = x & 7;\n"
" if (z) y=0;\n"
" else { if (y==8); }\n" // always false
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:4]: (style) Mismatching assignment and comparison, comparison 'y==8' is always false.\n", errout_str());
// while
check("void f(int x) {\n"
" int y = x & 7;\n"
" while (y==8);\n" // local variable => always false
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) Mismatching assignment and comparison, comparison 'y==8' is always false.\n", errout_str());
check("void f(int x) {\n"
" extern int y; y = x & 7;\n"
" while (y==8);\n" // non-local variable => no error
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
" int a = 100;\n"
" while (x) {\n"
" int y = 16 | a;\n"
" while (y != 0) y--;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void g(int x);\n"
"void f(int x) {\n"
" int a = 100;\n"
" while (x) {\n"
" int y = 16 | a;\n"
" while (y != 0) g(y);\n"
" }\n"
"}");
ASSERT_EQUALS(
"[test.cpp:5] -> [test.cpp:6]: (style) Mismatching assignment and comparison, comparison 'y!=0' is always true.\n",
errout_str());
check("void g(int &x);\n"
"void f(int x) {\n"
" int a = 100;\n"
" while (x) {\n"
" int y = 16 | a;\n"
" while (y != 0) g(y);\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// calling function
check("void f(int x) {\n"
" int y = x & 7;\n"
" do_something();\n"
" if (y==8);\n" // local variable => always false
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:4]: (style) Mismatching assignment and comparison, comparison 'y==8' is always false.\n", errout_str());
check("void f(int x) {\n"
" int y = x & 7;\n"
" do_something(&y);\n" // passing variable => no error
" if (y==8);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void do_something(int);\n"
"void f(int x) {\n"
" int y = x & 7;\n"
" do_something(y);\n"
" if (y==8);\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:5]: (style) Mismatching assignment and comparison, comparison 'y==8' is always false.\n", errout_str());
check("void f(int x) {\n"
" extern int y; y = x & 7;\n"
" do_something();\n"
" if (y==8);\n" // non-local variable => no error
"}");
ASSERT_EQUALS("", errout_str());
// #4434 : false positive: ?:
check("void f(int x) {\n"
" x = x & 1;\n"
" x = x & 1 ? 1 : -1;\n"
" if(x != -1) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
// #4735
check("void f() {\n"
" int x = *(char*)&0x12345678;\n"
" if (x==18) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
// bailout: no variable info
check("void foo(int x) {\n"
" y = 2 | x;\n" // y not declared => no error
" if(y == 1) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
// bailout: negative number
check("void foo(int x) {\n"
" int y = -2 | x;\n" // negative number => no error
" if (y==1) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
// bailout: pass variable to function
check("void foo(int x) {\n"
" int y = 2 | x;\n"
" bar(&y);\n" // pass variable to function => no error
" if (y==1) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
// no crash on unary operator& (#5643)
// #11610
check("SdrObject* ApplyGraphicToObject() {\n"
" if (&rHitObject) {}\n"
" else if (rHitObject.IsClosedObj() && !&rHitObject) { }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Condition '&rHitObject' is always true\n"
"[test.cpp:3]: (style) Condition '!&rHitObject' is always false\n",
errout_str());
// #5695: increment
check("void f(int a0, int n) {\n"
" int c = a0 & 3;\n"
" for (int a = 0; a < n; a++) {\n"
" c++;\n"
" if (c == 4)\n"
" c = 0;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int a) {\n" // #6662
" int x = a & 1;\n"
" while (x <= 4) {\n"
" if (x != 5) {}\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:4]: (style) Mismatching assignment and comparison, comparison 'x!=5' is always true.\n", errout_str());
check("void f(int a) {\n" // #6662
" int x = a & 1;\n"
" while ((x += 4) < 10) {\n"
" if (x != 5) {}\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int x = 100;\n"
" while (x) {\n"
" g(x);\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void g(int x);\n"
"void f() {\n"
" int x = 100;\n"
" while (x) {\n"
" g(x);\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Condition 'x' is always true\n", errout_str());
check("void g(int & x);\n"
"void f() {\n"
" int x = 100;\n"
" while (x) {\n"
" g(x);\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void mismatchingBitAnd() {
check("void f(int a) {\n"
" int b = a & 0xf0;\n"
" b &= 1;\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) Mismatching bitmasks. Result is always 0 (X = Y & 0xf0; Z = X & 0x1; => Z=0).\n", errout_str());
check("void f(int a) {\n"
" int b = a & 0xf0;\n"
" int c = b & 1;\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) Mismatching bitmasks. Result is always 0 (X = Y & 0xf0; Z = X & 0x1; => Z=0).\n", errout_str());
check("void f(int a) {\n"
" int b = a;"
" switch (x) {\n"
" case 1: b &= 1; break;\n"
" case 2: b &= 2; break;\n"
" };\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void comparison() {
// CheckCondition::comparison test cases
// '=='
check("void f(int a) {\n assert( (a & 0x07) == 8U );\n}");
ASSERT_EQUALS("[test.cpp:2]: (style) Expression '(X & 0x7) == 0x8' is always false.\n",errout_str());
check("void f(int a) {\n assert( (a & b & 4 & c ) == 3 );\n}");
ASSERT_EQUALS("[test.cpp:2]: (style) Expression '(X & 0x4) == 0x3' is always false.\n", errout_str());
check("void f(int a) {\n assert( (a | 0x07) == 8U );\n}");
ASSERT_EQUALS("[test.cpp:2]: (style) Expression '(X | 0x7) == 0x8' is always false.\n",errout_str());
check("void f(int a) {\n assert( (a & 0x07) == 7U );\n}");
ASSERT_EQUALS("", errout_str());
check("void f(int a) {\n assert( (a | 0x01) == -15 );\n}");
ASSERT_EQUALS("", errout_str());
// '!='
check("void f(int a) {\n assert( (a & 0x07) != 8U );\n}");
ASSERT_EQUALS("[test.cpp:2]: (style) Expression '(X & 0x7) != 0x8' is always true.\n",errout_str());
check("void f(int a) {\n assert( (a | 0x07) != 8U );\n}");
ASSERT_EQUALS("[test.cpp:2]: (style) Expression '(X | 0x7) != 0x8' is always true.\n",errout_str());
check("void f(int a) {\n assert( (a & 0x07) != 7U );\n}");
ASSERT_EQUALS("", errout_str());
check("void f(int a) {\n assert( (a | 0x07) != 7U );\n}");
ASSERT_EQUALS("", errout_str());
// '>='
check("void f(int a) {\n assert( (a & 0x07) >= 8U );\n}");
ASSERT_EQUALS("[test.cpp:2]: (style) Expression '(X & 0x7) >= 0x8' is always false.\n",errout_str());
check("void f(unsigned int a) {\n assert( (a | 0x7) >= 7U );\n}");
ASSERT_EQUALS("[test.cpp:2]: (style) Expression '(X | 0x7) >= 0x7' is always true.\n",errout_str());
check("void f(int a) {\n assert( (a & 0x07) >= 7U );\n}");
ASSERT_EQUALS("",errout_str());
check("void f(int a) {\n assert( (a | 0x07) >= 8U );\n}");
ASSERT_EQUALS("",errout_str()); //correct for negative 'a'
// '>'
check("void f(int a) {\n assert( (a & 0x07) > 7U );\n}");
ASSERT_EQUALS("[test.cpp:2]: (style) Expression '(X & 0x7) > 0x7' is always false.\n",errout_str());
check("void f(unsigned int a) {\n assert( (a | 0x7) > 6U );\n}");
ASSERT_EQUALS("[test.cpp:2]: (style) Expression '(X | 0x7) > 0x6' is always true.\n",errout_str());
check("void f(int a) {\n assert( (a & 0x07) > 6U );\n}");
ASSERT_EQUALS("",errout_str());
check("void f(int a) {\n assert( (a | 0x07) > 7U );\n}");
ASSERT_EQUALS("",errout_str()); //correct for negative 'a'
// '<='
check("void f(int a) {\n assert( (a & 0x07) <= 7U );\n}");
ASSERT_EQUALS("[test.cpp:2]: (style) Expression '(X & 0x7) <= 0x7' is always true.\n",errout_str());
check("void f(unsigned int a) {\n assert( (a | 0x08) <= 7U );\n}");
ASSERT_EQUALS("[test.cpp:2]: (style) Expression '(X | 0x8) <= 0x7' is always false.\n",errout_str());
check("void f(int a) {\n assert( (a & 0x07) <= 6U );\n}");
ASSERT_EQUALS("",errout_str());
check("void f(int a) {\n assert( (a | 0x08) <= 7U );\n}");
ASSERT_EQUALS("",errout_str()); //correct for negative 'a'
// '<'
check("void f(int a) {\n assert( (a & 0x07) < 8U );\n}");
ASSERT_EQUALS("[test.cpp:2]: (style) Expression '(X & 0x7) < 0x8' is always true.\n",errout_str());
check("void f(unsigned int a) {\n assert( (a | 0x07) < 7U );\n}");
ASSERT_EQUALS("[test.cpp:2]: (style) Expression '(X | 0x7) < 0x7' is always false.\n",errout_str());
check("void f(int a) {\n assert( (a & 0x07) < 3U );\n}");
ASSERT_EQUALS("",errout_str());
check("void f(int a) {\n assert( (a | 0x07) < 7U );\n}");
ASSERT_EQUALS("",errout_str()); //correct for negative 'a'
check("void f(int i) {\n" // #11998
" if ((i & 0x100) == 0x200) {}\n"
" if (0x200 == (i & 0x100)) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) The if condition is the same as the previous if condition\n"
"[test.cpp:2]: (style) Expression '(X & 0x100) == 0x200' is always false.\n"
"[test.cpp:3]: (style) Expression '(X & 0x100) == 0x200' is always false.\n",
errout_str());
checkP("#define MACRO1 (0x0010)\n" // #13222
"#define MACRO2 (0x0020)\n"
"#define MACRO_ALL (MACRO1 | MACRO2)\n"
"void f() {\n"
" if (MACRO_ALL == 0) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
checkP("void f(int i, int j) {\n" // #13360
" int X = 0x10;\n"
" if ((i & 0xff00) == X) {}\n"
" if (X == (j & 0xff00)) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) Expression '(X & 0xff00) == 0x10' is always false.\n"
"[test.cpp:4]: (style) Expression '(X & 0xff00) == 0x10' is always false.\n",
errout_str());
}
#define checkPureFunction(code) checkPureFunction_(code, __FILE__, __LINE__)
void multicompare() {
check("void foo(int x)\n"
"{\n"
" if (x & 7);\n"
" else { if (x == 1); }\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Expression is always false because 'else if' condition matches previous condition at line 3.\n", errout_str());
check("void foo(int x)\n"
"{\n"
" if (x & 7);\n"
" else { if (x & 1); }\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Expression is always false because 'else if' condition matches previous condition at line 3.\n", errout_str());
check("extern int bar() __attribute__((pure));\n"
"void foo(int x)\n"
"{\n"
" if ( bar() >1 && b) {}\n"
" else if (bar() >1 && b) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (style) Expression is always false because 'else if' condition matches previous condition at line 4.\n", errout_str());
checkPureFunction("extern int bar();\n"
"void foo(int x)\n"
"{\n"
" if ( bar() >1 && b) {}\n"
" else if (bar() >1 && b) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (style) Expression is always false because 'else if' condition matches previous condition at line 4.\n", errout_str());
// 7284
check("void foo() {\n"
" if (a) {}\n"
" else if (!!a) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Expression is always false because 'else if' condition matches previous condition at line 2.\n", errout_str());
// #11059
check("int f();\n"
"void g() {\n"
" int i = f();\n"
" if (i == 3) {}\n"
" else if ((i = f()) == 5) {}\n"
" else if (i == 3) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("int f();\n"
"void g() {\n"
" int i = f();\n"
" if (i == 3) {}\n"
" else if ((i = f()) == 5) {}\n"
" else if (i != 3) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
template<size_t size>
void checkPureFunction_(const char (&code)[size], const char* file, int line) {
// Tokenize..
SimpleTokenizer tokenizer(settings1, *this);
ASSERT_LOC(tokenizer.tokenize(code), file, line);
runChecks<CheckCondition>(tokenizer, this);
}
void overlappingElseIfCondition() {
check("void f(int a, int &b) {\n"
" if (a) { b = 1; }\n"
" else { if (a) { b = 2; } }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Expression is always false because 'else if' condition matches previous condition at line 2.\n", errout_str());
check("void f(int a, int &b) {\n"
" if (a) { b = 1; }\n"
" else { if (a) { b = 2; } }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Expression is always false because 'else if' condition matches previous condition at line 2.\n", errout_str());
check("void f(int a, int &b) {\n"
" if (a == 1) { b = 1; }\n"
" else { if (a == 2) { b = 2; }\n"
" else { if (a == 1) { b = 3; } } }\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Expression is always false because 'else if' condition matches previous condition at line 2.\n", errout_str());
check("void f(int a, int &b) {\n"
" if (a == 1) { b = 1; }\n"
" else { if (a == 2) { b = 2; }\n"
" else { if (a == 2) { b = 3; } } }\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Expression is always false because 'else if' condition matches previous condition at line 3.\n", errout_str());
check("void f(int a, int &b) {\n"
" if (a++) { b = 1; }\n"
" else { if (a++) { b = 2; }\n"
" else { if (a++) { b = 3; } } }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int a, int &b) {\n"
" if (!strtok(NULL, \" \")) { b = 1; }\n"
" else { if (!strtok(NULL, \" \")) { b = 2; } }\n"
"}");
ASSERT_EQUALS("", errout_str());
{
check("void f(Class &c) {\n"
" if (c.dostuff() == 3) {}\n"
" else { if (c.dostuff() == 3) {} }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(const Class &c) {\n"
" if (c.dostuff() == 3) {}\n"
" else { if (c.dostuff() == 3) {} }\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Expression is always false because 'else if' condition matches previous condition at line 2.\n", errout_str());
}
check("void f(int a, int &b) {\n"
" x = x / 2;\n"
" if (x < 100) { b = 1; }\n"
" else { x = x / 2; if (x < 100) { b = 2; } }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int i) {\n"
" if(i == 0x02e2000000 || i == 0xa0c6000000)\n"
" foo(i);\n"
"}");
ASSERT_EQUALS("", errout_str());
// ticket 3689 ( avoid false positive )
check("int fitInt(long long int nValue){\n"
" if( nValue < 0x7fffffffLL )\n"
" {\n"
" return 32;\n"
" }\n"
" if( nValue < 0x7fffffffffffLL )\n"
" {\n"
" return 48;\n"
" }\n"
" else {\n"
" if( nValue < 0x7fffffffffffffffLL )\n"
" {\n"
" return 64;\n"
" } else\n"
" {\n"
" return -1;\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(WIDGET *widget) {\n"
" if (dynamic_cast<BUTTON*>(widget)){}\n"
" else if (dynamic_cast<LABEL*>(widget)){}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("class B { virtual void v() {} };\n" // #11037
"class D1 : public B {};\n"
"class D2 : public B {};\n"
"void f(const std::shared_ptr<B>&p) {\n"
" const auto d1 = dynamic_cast<D1*>(p.get());\n"
" const auto d2 = dynamic_cast<D2*>(p.get());\n"
" if (d1) {}\n"
" else if (d2) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n" // #6482
" if (x & 1) {}\n"
" else if (x == 0) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
" if (x & 15) {}\n"
" else if (x == 40) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Expression is always false because 'else if' condition matches previous condition at line 2.\n", errout_str());
check("void f(int x) {\n"
" if (x == sizeof(double)) {}\n"
" else { if (x == sizeof(long double)) {} }"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
" if (x & 0x08) {}\n"
" else if (x & 0xF8) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
" if (x & 0xF8) {}\n"
" else if (x & 0x08) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Expression is always false because 'else if' condition matches previous condition at line 2.\n", errout_str());
check("void f(bool a, bool b) {\n"
" if(a && b){}\n"
" else if( !!b && !!a){}\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Expression is always false because 'else if' condition matches previous condition at line 2.\n", errout_str());
check("void f(bool a, bool b) {\n"
" if(a && b){}\n"
" else if( !!b && a){}\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Expression is always false because 'else if' condition matches previous condition at line 2.\n", errout_str());
check("void f(bool a, bool b) {\n"
" if(a && b){}\n"
" else if( b && !!a){}\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Expression is always false because 'else if' condition matches previous condition at line 2.\n", errout_str());
check("void f(bool a, bool b) {\n"
" if(a && b){}\n"
" else if( b && !(!a)){}\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Expression is always false because 'else if' condition matches previous condition at line 2.\n", errout_str());
check("void f(bool a, bool b) {\n"
" if(a && b){}\n"
" else if( !!b && !(!a)){}\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Expression is always false because 'else if' condition matches previous condition at line 2.\n", errout_str());
check("void f(bool a, bool b) {\n"
" if(a && b){}\n"
" else if( !!(b) && !!(a+b)){}\n"
"}");
ASSERT_EQUALS("", errout_str());
// #8168
check("enum MaskValues\n"
"{\n"
" Value1 = 0x00000001,\n"
" Value2 = 0x00000002\n"
"};\n"
"void TestFunction(int value) {\n"
" if ( value & (int)Value1 ) {}\n"
" else if ( value & (int)Value2 ) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(size_t x) {\n"
" if (x == sizeof(int)) {}\n"
" else { if (x == sizeof(long))} {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(size_t x) {\n"
" if (x == sizeof(long)) {}\n"
" else { if (x == sizeof(long long))} {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void oppositeElseIfCondition() {
setMultiline();
check("void f(int x) {\n"
" if (x) {}\n"
" else if (!x) {}\n"
"}");
ASSERT_EQUALS("test.cpp:3:style:Expression is always true because 'else if' condition is opposite to previous condition at line 2.\n"
"test.cpp:2:note:first condition\n"
"test.cpp:3:note:else if condition is opposite to first condition\n", errout_str());
check("void f(int x) {\n"
" int y = x;\n"
" if (x) {}\n"
" else if (!y) {}\n"
"}");
ASSERT_EQUALS("test.cpp:4:style:Expression is always true because 'else if' condition is opposite to previous condition at line 3.\n"
"test.cpp:2:note:'y' is assigned value 'x' here.\n"
"test.cpp:3:note:first condition\n"
"test.cpp:4:note:else if condition is opposite to first condition\n", errout_str());
}
void checkBadBitmaskCheck() {
check("bool f(int x) {\n"
" bool b = x | 0x02;\n"
" return b;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Result of operator '|' is always true if one operand is non-zero. Did you intend to use '&'?\n", errout_str());
check("bool f(int x) {\n"
" bool b = 0x02 | x;\n"
" return b;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Result of operator '|' is always true if one operand is non-zero. Did you intend to use '&'?\n", errout_str());
check("int f(int x) {\n"
" int b = x | 0x02;\n"
" return b;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool f(int x) {\n"
" bool b = x & 0x02;\n"
" return b;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool f(int x) {\n"
" if(x | 0x02)\n"
" return b;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Result of operator '|' is always true if one operand is non-zero. Did you intend to use '&'?\n", errout_str());
check("bool f(int x) {\n"
" int y = 0x1;\n"
" if(b) y = 0;\n"
" if(x | y)\n"
" return b;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool f(int x) {\n"
" foo(a && (x | 0x02));\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Result of operator '|' is always true if one operand is non-zero. Did you intend to use '&'?\n", errout_str());
check("int f(int x) {\n"
" return (x | 0x02) ? 0 : 5;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Result of operator '|' is always true if one operand is non-zero. Did you intend to use '&'?\n", errout_str());
check("int f(int x) {\n"
" return x ? (x | 0x02) : 5;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool f(int x) {\n"
" return x | 0x02;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Result of operator '|' is always true if one operand is non-zero. Did you intend to use '&'?\n", errout_str());
check("bool f(int x) {\n"
" if (x) {\n"
" return x | 0x02;\n"
" }\n"
" return 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Result of operator '|' is always true if one operand is non-zero. Did you intend to use '&'?\n", errout_str());
check("const bool f(int x) {\n"
" return x | 0x02;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Result of operator '|' is always true if one operand is non-zero. Did you intend to use '&'?\n", errout_str());
check("struct F {\n"
" static const bool f(int x) {\n"
" return x | 0x02;\n"
" }\n"
"};");
ASSERT_EQUALS("[test.cpp:3]: (warning) Result of operator '|' is always true if one operand is non-zero. Did you intend to use '&'?\n", errout_str());
check("struct F {\n"
" typedef bool b_t;\n"
"};\n"
"F::b_t f(int x) {\n"
" return x | 0x02;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (warning) Result of operator '|' is always true if one operand is non-zero. Did you intend to use '&'?\n", errout_str());
check("int f(int x) {\n"
" return x | 0x02;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void create_rop_masks_4( rop_mask_bits *bits) {\n"
"DWORD mask_offset;\n"
"BYTE *and_bits = bits->and;\n"
"rop_mask *rop_mask;\n"
"and_bits[mask_offset] |= (rop_mask->and & 0x0f);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(unsigned a, unsigned b) {\n"
" unsigned cmd1 = b & 0x0F;\n"
" if (cmd1 | a) {\n"
" if (b == 0x0C) {}\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int i) {\n" // #11082
" int j = 0;\n"
" if (i | j) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) Operator '|' with one operand equal to zero is redundant.\n", errout_str());
check("#define EIGHTTOIS(x) (((x) << 8) | (x))\n"
"int f() {\n"
" return EIGHTTOIS(0);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("#define O_RDONLY 0\n"
"void f(const char* s, int* pFd) {\n"
" *pFd = open(s, O_RDONLY | O_BINARY, 0);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("const int FEATURE_BITS = x |\n"
"#if FOO_ENABLED\n"
" FEATURE_FOO |\n"
"#endif\n"
"#if BAR_ENABLED\n"
" FEATURE_BAR |\n"
"#endif\n"
" 0;");
ASSERT_EQUALS("", errout_str());
check("enum precedence { PC0, UNARY };\n"
"int x = PC0 | UNARY;\n"
"int y = UNARY | PC0;\n");
ASSERT_EQUALS("", errout_str());
check("#define MASK 0\n"
"#define SHIFT 1\n"
"int x = 1 | (MASK << SHIFT);\n");
ASSERT_EQUALS("", errout_str());
}
void incorrectLogicOperator1() {
check("void f(int x) {\n"
" if ((x != 1) || (x != 3))\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical disjunction always evaluates to true: x != 1 || x != 3.\n", errout_str());
check("void f(int x) {\n"
" if (1 != x || 3 != x)\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical disjunction always evaluates to true: x != 1 || x != 3.\n", errout_str());
check("void f(int x) {\n"
" if (x<0 && !x) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical conjunction always evaluates to false: x < 0 && !x.\n", errout_str());
check("void f(int x) {\n"
" if (x==0 && x) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical conjunction always evaluates to false: x == 0 && x.\n", errout_str());
check("void f(int x) {\n" // ast..
" if (y == 1 && x == 1 && x == 7) { }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical conjunction always evaluates to false: x == 1 && x == 7.\n", errout_str());
check("void f(int x, int y) {\n"
" if (x != 1 || y != 1)\n"
" a++;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x, int y) {\n"
" if ((y == 1) && (x != 1) || (x != 3))\n"
" a++;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x, int y) {\n"
" if ((x != 1) || (x != 3) && (y == 1))\n"
" a++;\n"
"}"
);
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:2]: (style) Condition 'x!=3' is always true\n", errout_str());
check("void f(int x) {\n"
" if ((x != 1) && (x != 3))\n"
" a++;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
" if ((x == 1) || (x == 3))\n"
" a++;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x, int y) {\n"
" if ((x != 1) || (y != 3))\n"
" a++;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x, int y) {\n"
" if ((x != hotdog) || (y != hotdog))\n"
" a++;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x, int y) {\n"
" if ((x != 5) || (y != 5))\n"
" a++;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
" if ((x != 5) || (x != 6))\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical disjunction always evaluates to true: x != 5 || x != 6.\n", errout_str());
check("void f(unsigned int a, unsigned int b, unsigned int c) {\n"
" if((a != b) || (c != b) || (c != a))\n"
" {\n"
" return true;\n"
" }\n"
" return false;\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:2]: (style) Condition 'c!=a' is always false\n", errout_str());
}
void incorrectLogicOperator2() {
check("void f(float x) {\n"
" if ((x == 1) && (x == 1.0))\n"
" a++;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
" if ((x == 1) && (x == 0x00000001))\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:2]: (style) Condition 'x==0x00000001' is always true\n", errout_str());
check("void f(int x) {\n"
" if (x == 1 && x == 3)\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical conjunction always evaluates to false: x == 1 && x == 3.\n", errout_str());
check("void f(int x) {\n"
" if (x == 1.0 && x == 3.0)\n"
" a++;\n"
"}");
ASSERT_EQUALS("", errout_str()); // float comparisons with == and != are not checked right now - such comparison is a bad idea
check("void f(float x) {\n"
" if (x == 1 && x == 1.0)\n"
" a++;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void bar(float f) {\n" // #5246
" if ((f > 0) && (f < 1)) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
" if (x < 1 && x > 1)\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical conjunction always evaluates to false: x < 1 && x > 1.\n", errout_str());
check("void f(int x) {\n"
" if (x < 1.0 && x > 1.0)\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical conjunction always evaluates to false: x < 1.0 && x > 1.0.\n", errout_str());
check("void f(int x) {\n"
" if (x < 1 && x > 1.0)\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical conjunction always evaluates to false: x < 1 && x > 1.0.\n", errout_str());
check("void f(int x) {\n"
" if (x >= 1.0 && x <= 1.001)\n"
" a++;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
" if (x < 1 && x > 3)\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical conjunction always evaluates to false: x < 1 && x > 3.\n", errout_str());
check("void f(float x) {\n"
" if (x < 1.0 && x > 3.0)\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical conjunction always evaluates to false: x < 1.0 && x > 3.0.\n", errout_str());
check("void f(int x) {\n"
" if (1 > x && 3 < x)\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical conjunction always evaluates to false: x < 1 && x > 3.\n", errout_str());
check("void f(int x) {\n"
" if (x < 3 && x > 1)\n"
" a++;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
" if (x > 3 || x < 10)\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical disjunction always evaluates to true: x > 3 || x < 10.\n", errout_str());
check("void f(int x) {\n"
" if (x >= 3 || x <= 10)\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical disjunction always evaluates to true: x >= 3 || x <= 10.\n", errout_str());
check("void f(int x) {\n"
" if (x >= 3 || x < 10)\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical disjunction always evaluates to true: x >= 3 || x < 10.\n", errout_str());
check("void f(int x) {\n"
" if (x > 3 || x <= 10)\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical disjunction always evaluates to true: x > 3 || x <= 10.\n", errout_str());
check("void f(int x) {\n"
" if (x > 3 || x < 3)\n"
" a++;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
" if (x >= 3 || x <= 3)\n"
" a++;\n"
"}"
);
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical disjunction always evaluates to true: x >= 3 || x <= 3.\n", errout_str());
check("void f(int x) {\n"
" if (x >= 3 || x < 3)\n"
" a++;\n"
"}"
);
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical disjunction always evaluates to true: x >= 3 || x < 3.\n", errout_str());
check("void f(int x) {\n"
" if (x > 3 || x <= 3)\n"
" a++;\n"
"}"
);
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical disjunction always evaluates to true: x > 3 || x <= 3.\n", errout_str());
check("void f(int x) {\n"
" if((x==3) && (x!=4))\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Redundant condition: The condition 'x != 4' is redundant since 'x == 3' is sufficient.\n", errout_str());
check("void f(const std::string &s) {\n" // #8860
" const std::size_t p = s.find(\"42\");\n"
" const std::size_t * const ptr = &p;\n"
" if(p != std::string::npos && p == 0 && *ptr != 1){;}\n"
"}");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:4]: (style) Condition '*ptr!=1' is always true\n", errout_str());
check("void f(int x) {\n"
" if ((x!=4) && (x==3))\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Redundant condition: The condition 'x != 4' is redundant since 'x == 3' is sufficient.\n", errout_str());
check("void f(int x) {\n"
" if ((x==3) || (x!=4))\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Redundant condition: The condition 'x == 3' is redundant since 'x != 4' is sufficient.\n", errout_str());
check("void f(int x) {\n"
" if ((x!=4) || (x==3))\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Redundant condition: The condition 'x == 3' is redundant since 'x != 4' is sufficient.\n", errout_str());
check("void f(int x) {\n"
" if ((x==3) && (x!=3))\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical conjunction always evaluates to false: x == 3 && x != 3.\n", errout_str());
check("void f(int x) {\n"
" if ((x==6) || (x!=6))\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical disjunction always evaluates to true: x == 6 || x != 6.\n", errout_str());
check("void f(int x) {\n"
" if (x > 10 || x < 3)\n"
" a++;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
" if (x > 5 && x == 1)\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical conjunction always evaluates to false: x > 5 && x == 1.\n", errout_str());
check("void f(int x) {\n"
" if (x > 5 && x == 6)\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Redundant condition: The condition 'x > 5' is redundant since 'x == 6' is sufficient.\n", errout_str());
// #3419
check("void f() {\n"
" if ( &q != &a && &q != &b ) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
// #3676
check("void f(int m_x2, int w, int x) {\n"
" if (x + w - 1 > m_x2 || m_x2 < 0 )\n"
" m_x2 = x + w - 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(float x) {\n" // x+1 => x
" if (x <= 1.0e20 && x >= -1.0e20) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(float x) {\n" // x+1 => x
" if (x >= 1.0e20 && x <= 1.0e21) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(float x) {\n" // x+1 => x
" if (x <= -1.0e20 && x >= -1.0e21) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void incorrectLogicOperator3() {
check("void f(int x, bool& b) {\n"
" b = x > 5 && x == 1;\n"
" c = x < 1 && x == 3;\n"
" d = x >= 5 && x == 1;\n"
" e = x <= 1 && x == 3;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical conjunction always evaluates to false: x > 5 && x == 1.\n"
"[test.cpp:3]: (warning) Logical conjunction always evaluates to false: x < 1 && x == 3.\n"
"[test.cpp:4]: (warning) Logical conjunction always evaluates to false: x >= 5 && x == 1.\n"
"[test.cpp:5]: (warning) Logical conjunction always evaluates to false: x <= 1 && x == 3.\n", errout_str());
}
void incorrectLogicOperator4() {
check("#define ZERO 0\n"
"void f(int x) {\n"
" if (x && x != ZERO) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int N) {\n" // #9789
" T a[20] = { 0 };\n"
" for (int i = 0; i < N; ++i) {\n"
" if (0 < a[i] && a[i] < 1) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void incorrectLogicOperator5() { // complex expressions
check("void f(int x) {\n"
" if (x+3 > 2 || x+3 < 10) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical disjunction always evaluates to true: x+3 > 2 || x+3 < 10.\n", errout_str());
}
void incorrectLogicOperator6() { // char literals
check("void f(char x) {\n"
" if (x == '1' || x == '2') {}\n"
"}", "test.cpp", true);
ASSERT_EQUALS("", errout_str());
check("void f(char x) {\n"
" if (x == '1' && x == '2') {}\n"
"}", "test.cpp", true);
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical conjunction always evaluates to false: x == '1' && x == '2'.\n", errout_str());
check("int f(char c) {\n"
" return (c >= 'a' && c <= 'z');\n"
"}", "test.cpp", true);
ASSERT_EQUALS("", errout_str());
check("int f(char c) {\n"
" return (c <= 'a' && c >= 'z');\n"
"}", "test.cpp", true);
ASSERT_EQUALS("[test.cpp:2]: (warning, inconclusive) Logical conjunction always evaluates to false: c <= 'a' && c >= 'z'.\n", errout_str());
check("int f(char c) {\n"
" return (c <= 'a' && c >= 'z');\n"
"}", "test.cpp", false);
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:2]: (style) Return value 'c>='z'' is always false\n", errout_str());
}
void incorrectLogicOperator7() { // opposite expressions
check("void f(int i) {\n"
" if (i || !i) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical disjunction always evaluates to true: i || !(i).\n", errout_str());
check("void f(int a, int b) {\n"
" if (a>b || a<=b) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical disjunction always evaluates to true: a > b || a <= b.\n", errout_str());
check("void f(int a, int b) {\n"
" if (a>b || a<b) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
// #6064 False positive incorrectLogicOperator - invalid assumption about template type?
check("template<typename T> T icdf( const T uniform ) {\n"
" if ((0<uniform) && (uniform<1))\n"
" {}\n"
"}");
ASSERT_EQUALS("", errout_str());
// #6081 False positive: incorrectLogicOperator, with close negative comparisons
check("double neg = -1.0 - 1.0e-13;\n"
"void foo() {\n"
" if ((neg < -1.0) && (neg > -1.0 - 1.0e-12))\n"
" return;\n"
" else\n"
" return;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void incorrectLogicOperator8() { // opposite expressions
check("void f(int i) {\n"
" if (!(i!=10) && !(i!=20)) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical conjunction always evaluates to false: !(i != 10) && !(i != 20).\n", errout_str());
}
void incorrectLogicOperator9() { // #6069 "False positive incorrectLogicOperator due to dynamic_cast"
check("class MyType;\n"
"class OtherType;\n"
"void foo (OtherType* obj) {\n"
" assert((!obj) || dynamic_cast<MyType*>(obj));\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void incorrectLogicOperator10() { // #7794 - enum
check("typedef enum { A, B } Type_t;\n"
"void f(Type_t t) {\n"
" if ((t == A) && (t == B))\n"
" {}\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Logical conjunction always evaluates to false: t == 0 && t == 1.\n", errout_str());
}
void incorrectLogicOperator11() {
check("void foo(int i, const int n) { if ( i < n && i == n ) {} }");
ASSERT_EQUALS("[test.cpp:1]: (warning) Logical conjunction always evaluates to false: i < n && i == n.\n", errout_str());
check("void foo(int i, const int n) { if ( i > n && i == n ) {} }");
ASSERT_EQUALS("[test.cpp:1]: (warning) Logical conjunction always evaluates to false: i > n && i == n.\n", errout_str());
check("void foo(int i, const int n) { if ( i == n && i > n ) {} }");
ASSERT_EQUALS("[test.cpp:1]: (warning) Logical conjunction always evaluates to false: i == n && i > n.\n", errout_str());
check("void foo(int i, const int n) { if ( i == n && i < n ) {} }");
ASSERT_EQUALS("[test.cpp:1]: (warning) Logical conjunction always evaluates to false: i == n && i < n.\n", errout_str());
}
void incorrectLogicOperator12() { // #8696
check("struct A {\n"
" void f() const;\n"
"};\n"
"void foo(A a, A b) {\n"
" A x = b;\n"
" A y = b;\n"
" y.f();\n"
" if (a > x && a < y)\n"
" return;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:5] -> [test.cpp:6] -> [test.cpp:8]: (warning) Logical conjunction always evaluates to false: a > x && a < y.\n",
errout_str());
check("struct A {\n"
" void f();\n"
"};\n"
"void foo(A a, A b) {\n"
" A x = b;\n"
" A y = b;\n"
" y.f();\n"
" if (a > x && a < y)\n"
" return;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(A a, A b) {\n"
" A x = b;\n"
" A y = b;\n"
" y.f();\n"
" if (a > x && a < y)\n"
" return;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(A a, A b) {\n"
" const A x = b;\n"
" const A y = b;\n"
" y.f();\n"
" if (a > x && a < y)\n"
" return;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:2] -> [test.cpp:3] -> [test.cpp:5]: (warning) Logical conjunction always evaluates to false: a > x && a < y.\n",
errout_str());
check("struct A {\n"
" void f() const;\n"
"};\n"
"void foo(A a) {\n"
" A x = a;\n"
" A y = a;\n"
" y.f();\n"
" if (a > x && a < y)\n"
" return;\n"
"}");
ASSERT_EQUALS("[test.cpp:8]: (style) Condition 'a>x' is always false\n"
"[test.cpp:8]: (style) Condition 'a<y' is always false\n",
errout_str());
check("struct A {\n"
" void f();\n"
"};\n"
"void foo(A a) {\n"
" A x = a;\n"
" A y = a;\n"
" y.f();\n"
" if (a > x && a < y)\n"
" return;\n"
"}");
ASSERT_EQUALS("[test.cpp:8]: (style) Condition 'a>x' is always false\n", errout_str());
check("void foo(A a) {\n"
" A x = a;\n"
" A y = a;\n"
" y.f();\n"
" if (a > x && a < y)\n"
" return;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (style) Condition 'a>x' is always false\n", errout_str());
check("void foo(A a) {\n"
" const A x = a;\n"
" const A y = a;\n"
" y.f();\n"
" if (a > x && a < y)\n"
" return;\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (style) Condition 'a>x' is always false\n"
"[test.cpp:5]: (style) Condition 'a<y' is always false\n",
errout_str());
}
void incorrectLogicOperator13() {
// 8780
check("void f(const int &v) {\n"
" const int x=v;\n"
" if ((v == 1) && (x == 2)) {;}\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (warning) Logical conjunction always evaluates to false: v == 1 && x == 2.\n", errout_str());
check("void f2(const int *v) {\n"
" const int *x=v;\n"
" if ((*v == 1) && (*x == 2)) {;}\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (warning) Logical conjunction always evaluates to false: *(v) == 1 && *(x) == 2.\n", errout_str());
}
void incorrectLogicOperator14() {
check("static const std ::string h;\n"
"class i {\n"
"public:\n"
" struct j {\n"
" std ::string k;\n"
" std ::string l;\n"
" };\n"
" struct a {\n"
" enum { m = 1 };\n"
" };\n"
"} b;\n"
"namespace n {\n"
"class c;\n"
"}\n"
"struct o {\n"
" enum { p, d, q, r };\n"
" enum { e, f };\n"
"\n"
"public:\n"
" class j {\n"
" public:\n"
" class s {\n"
" std ::string a;\n"
" };\n"
" };\n"
"};\n"
"namespace n {\n"
"class b;\n"
"}\n"
"namespace aa {\n"
"class d {\n"
"public:\n"
" char t;\n"
" enum {} u;\n"
"};\n"
"} // namespace aa\n"
"namespace aa {\n"
"struct e {};\n"
"} // namespace aa\n"
"class a;\n"
"class w {\n"
"public:\n"
" enum { x };\n"
" struct {\n"
" } y;\n"
" std ::string z;\n"
"};\n"
"class ab {\n"
" friend class c;\n"
"\n"
"public:\n"
" class ac {\n"
" void e(const ac &v) const;\n"
" };\n"
"};\n"
"class f;\n"
"class ad {\n"
" friend class e;\n"
" enum { e, ae, ag, ah, ai, aj, ak, a, b };\n"
" class c {};\n"
" class d {\n"
" enum am { f, an, ao, ap, aq, ar, b, as, at, c, au };\n"
" enum av { aw, ax, ay, az, e, ba, bb, bc, bd, a };\n"
" struct b {\n"
" am action;\n"
" av c;\n"
" };\n"
" };\n"
" class e {\n"
" public:\n"
" std ::string e;\n"
" class f {\n"
" } f;\n"
" class be {\n"
" public:\n"
" };\n"
" std ::vector<be> bf;\n"
" enum { bg, b } c;\n"
" };\n"
" struct bh {\n"
" std ::map<int, d> b;\n"
" };\n"
" std ::map<std ::string, bh> bi;\n"
" struct {\n"
" int b;\n"
" char bj;\n"
" } bk;\n"
" class a {\n"
" public:\n"
" std ::set<std ::string> b;\n"
" };\n"
"};\n"
"class bl;\n"
"class al;\n"
"class bm;\n"
"class f;\n"
"class b;\n"
"class bn;\n"
"namespace bo {\n"
"class bp {\n"
"public:\n"
" typedef std ::pair<const f *, std ::string> bq;\n"
" typedef std ::list<bq> br;\n"
"};\n"
"const bo ::bp *dg(const f *a, const al *b);\n"
"} // namespace bo\n"
"const bn *dh(const f *d, bo ::bp ::br &bs);\n"
"class f {\n"
"public:\n"
" struct bt {};\n"
" std ::vector<a> f;\n"
"};\n"
"class bu;\n"
"class a;\n"
"class c;\n"
"struct bv {};\n"
"class af {\n"
"private:\n"
"public:\n"
" enum { b, d, e, f, c, bw };\n"
" void a(int c);\n"
" af *bx() const;\n"
"};\n"
"namespace by {\n"
"class b;\n"
"}\n"
"class b {\n"
"public:\n"
" bool d, c;\n"
"};\n"
"class bz;\n"
"class f;\n"
"class ca {\n"
" friend class b;\n"
"\n"
"public:\n"
" const bm *cb() const { return cc; }\n"
" f *d(f *e, bool f) const;\n"
" int e() { return ++cd; }\n"
" bl *const c;\n"
" bm *cc;\n"
" std ::map<std ::string, int> ce;\n"
" int cd;\n"
" bz *a;\n"
"};\n"
"namespace n {\n"
"class c;\n"
"class d;\n"
"} // namespace n\n"
"class cf {\n"
"public:\n"
" explicit cf(const std ::string &aname);\n"
" cf(const std ::string &aname, const ca *cg, const al *ch, bl *ci)\n"
" : cj(cg), ck(ch), cl(ci), cn(aname) {}\n"
"\n"
"protected:\n"
" const ca *const cj;\n"
" const al *const ck;\n"
" bl *const cl;\n"
" const std ::string cn;\n"
"};\n"
"class cm : public cf {\n"
"public:\n"
" void cp();\n"
" std ::string d() const;\n"
"};\n"
"struct co {\n"
" co();\n"
" const bu *a;\n"
" enum f {};\n"
" enum {\n"
" b = (1 << 0),\n"
" c = (1 << 1),\n"
" };\n"
" void d(bool e);\n"
"};\n"
"class bu {\n"
" friend class e;\n"
"\n"
"public:\n"
" struct f {};\n"
" enum { d, cr, cq, ct, cs, e, a, b, c, dd, cu, cv, cw, cx, cy, cz, da };\n"
" const f *db;\n"
" const af *dc;\n"
"} f{};\n"
"class bm {\n"
"public:\n"
" std ::list<bu> df;\n"
" std ::vector<const bu *> de;\n"
" mutable std ::set<std ::string> f;\n"
"};\n"
"void cm ::cp() {\n"
" const bm *a = cj->cb();\n"
" for (const bu *b : a->de)\n"
" for (af *c = b->dc->bx();;) {\n"
" af *d = c;\n"
" af *e = c;\n"
" bool f(d);\n"
" bool g(e);\n"
" if (f && g)\n"
" ;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:200] -> [test.cpp:200]: (style) Condition 'g' is always true\n", errout_str());
}
void incorrectLogicOperator15() {
// 10022
check("struct PipeRoute {\n"
" std::deque<int> points;\n"
" std::deque<int> estimates;\n"
"};\n"
"void CleanPipeRoutes(std::map<int, PipeRoute*>& pipeRoutes) {\n"
" for (auto it = pipeRoutes.begin(); it != pipeRoutes.end(); ) {\n"
" PipeRoute* curRoute = it->second;\n"
" if (curRoute->points.empty() && curRoute->estimates.size() != 2)\n"
" {\n"
" delete curRoute;\n"
" it = pipeRoutes.erase(it);\n"
" }\n"
" else\n"
" {\n"
" ++it;\n"
" }\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void incorrectLogicOperator16() { // #10070
check("void foo(void* p) {\n"
" if (!p || p == -1) { }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void incorrectLogicOperator17() { // #12471
check("struct R {\n"
" void set() { i = 1; }\n"
" int get() const { return i; }\n"
" int i;\n"
"};\n"
"struct P {\n"
" void f();\n"
" R* r;\n"
"};\n"
"void P::f() {\n"
" int a = r->get();\n"
" r->set();\n"
" if (a == 0 && r->get()) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void secondAlwaysTrueFalseWhenFirstTrueError() {
check("void f(void) {\n" // #8892
" const char c[1] = { \'x\' }; \n"
" if(c[0] == \'x\'){;}\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Condition 'c[0]=='x'' is always true\n", errout_str());
check("void f(int x) {\n"
" if (x > 5 && x != 1)\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Redundant condition: The condition 'x != 1' is redundant since 'x > 5' is sufficient.\n", errout_str());
check("void f(int x) {\n"
" if (x > 5 && x != 6)\n"
" a++;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
" if ((x > 5) && (x != 1))\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Redundant condition: The condition 'x != 1' is redundant since 'x > 5' is sufficient.\n", errout_str());
check("void f(int x) {\n"
" if ((x > 5) && (x != 6))\n"
" a++;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x, bool& b) {\n"
" b = x > 3 || x == 4;\n"
" c = x < 5 || x == 4;\n"
" d = x >= 3 || x == 4;\n"
" e = x <= 5 || x == 4;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Redundant condition: The condition 'x == 4' is redundant since 'x > 3' is sufficient.\n"
"[test.cpp:3]: (style) Redundant condition: The condition 'x == 4' is redundant since 'x < 5' is sufficient.\n"
"[test.cpp:4]: (style) Redundant condition: The condition 'x == 4' is redundant since 'x >= 3' is sufficient.\n"
"[test.cpp:5]: (style) Redundant condition: The condition 'x == 4' is redundant since 'x <= 5' is sufficient.\n",
errout_str());
check("void f(int x, bool& b) {\n"
" b = x > 5 || x != 1;\n"
" c = x < 1 || x != 3;\n"
" d = x >= 5 || x != 1;\n"
" e = x <= 1 || x != 3;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Redundant condition: The condition 'x > 5' is redundant since 'x != 1' is sufficient.\n"
"[test.cpp:3]: (style) Redundant condition: The condition 'x < 1' is redundant since 'x != 3' is sufficient.\n"
"[test.cpp:4]: (style) Redundant condition: The condition 'x >= 5' is redundant since 'x != 1' is sufficient.\n"
"[test.cpp:5]: (style) Redundant condition: The condition 'x <= 1' is redundant since 'x != 3' is sufficient.\n",
errout_str());
check("void f(int x, bool& b) {\n"
" b = x > 6 && x > 5;\n"
" c = x > 5 || x > 6;\n"
" d = x < 6 && x < 5;\n"
" e = x < 5 || x < 6;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Redundant condition: The condition 'x > 5' is redundant since 'x > 6' is sufficient.\n"
"[test.cpp:3]: (style) Redundant condition: The condition 'x > 6' is redundant since 'x > 5' is sufficient.\n"
"[test.cpp:4]: (style) Redundant condition: The condition 'x < 6' is redundant since 'x < 5' is sufficient.\n"
"[test.cpp:5]: (style) Redundant condition: The condition 'x < 5' is redundant since 'x < 6' is sufficient.\n",
errout_str());
check("void f(double x, bool& b) {\n"
" b = x > 6.5 && x > 5.5;\n"
" c = x > 5.5 || x > 6.5;\n"
" d = x < 6.5 && x < 5.5;\n"
" e = x < 5.5 || x < 6.5;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Redundant condition: The condition 'x > 5.5' is redundant since 'x > 6.5' is sufficient.\n"
"[test.cpp:3]: (style) Redundant condition: The condition 'x > 6.5' is redundant since 'x > 5.5' is sufficient.\n"
"[test.cpp:4]: (style) Redundant condition: The condition 'x < 6.5' is redundant since 'x < 5.5' is sufficient.\n"
"[test.cpp:5]: (style) Redundant condition: The condition 'x < 5.5' is redundant since 'x < 6.5' is sufficient.\n",
errout_str());
check("void f(const char *p) {\n" // #10320
" if (!p || !*p || *p != 'x') {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Redundant condition: The condition '!*p' is redundant since '*p != 'x'' is sufficient.\n",
errout_str());
}
void incorrectLogicOp_condSwapping() {
check("void f(int x) {\n"
" if (x < 1 && x > 3)\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical conjunction always evaluates to false: x < 1 && x > 3.\n", errout_str());
check("void f(int x) {\n"
" if (1 > x && x > 3)\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical conjunction always evaluates to false: x < 1 && x > 3.\n", errout_str());
check("void f(int x) {\n"
" if (x < 1 && 3 < x)\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical conjunction always evaluates to false: x < 1 && x > 3.\n", errout_str());
check("void f(int x) {\n"
" if (1 > x && 3 < x)\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical conjunction always evaluates to false: x < 1 && x > 3.\n", errout_str());
check("void f(int x) {\n"
" if (x > 3 && x < 1)\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical conjunction always evaluates to false: x > 3 && x < 1.\n", errout_str());
check("void f(int x) {\n"
" if (3 < x && x < 1)\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical conjunction always evaluates to false: x > 3 && x < 1.\n", errout_str());
check("void f(int x) {\n"
" if (x > 3 && 1 > x)\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical conjunction always evaluates to false: x > 3 && x < 1.\n", errout_str());
check("void f(int x) {\n"
" if (3 < x && 1 > x)\n"
" a++;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical conjunction always evaluates to false: x > 3 && x < 1.\n", errout_str());
}
void modulo() {
check("bool f(bool& b1, bool& b2, bool& b3) {\n"
" b1 = a % 5 == 4;\n"
" b2 = a % c == 100000;\n"
" b3 = a % 5 == c;\n"
" return a % 5 == 5-p;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool f(bool& b1, bool& b2, bool& b3, bool& b4, bool& b5) {\n"
" b1 = a % 5 < 5;\n"
" b2 = a % 5 <= 5;\n"
" b3 = a % 5 == 5;\n"
" b4 = a % 5 != 5;\n"
" b5 = a % 5 >= 5;\n"
" return a % 5 > 5;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:2]: (warning) Comparison of modulo result is predetermined, because it is always less than 5.\n"
"[test.cpp:3]: (warning) Comparison of modulo result is predetermined, because it is always less than 5.\n"
"[test.cpp:4]: (warning) Comparison of modulo result is predetermined, because it is always less than 5.\n"
"[test.cpp:5]: (warning) Comparison of modulo result is predetermined, because it is always less than 5.\n"
"[test.cpp:6]: (warning) Comparison of modulo result is predetermined, because it is always less than 5.\n"
"[test.cpp:7]: (warning) Comparison of modulo result is predetermined, because it is always less than 5.\n",
errout_str());
check("void f(bool& b1, bool& b2) {\n"
" b1 = bar() % 5 < 889;\n"
" if(x[593] % 5 <= 5)\n"
" b2 = x.a % 5 == 5;\n"
"}");
ASSERT_EQUALS(
"[test.cpp:2]: (warning) Comparison of modulo result is predetermined, because it is always less than 5.\n"
"[test.cpp:3]: (warning) Comparison of modulo result is predetermined, because it is always less than 5.\n"
"[test.cpp:4]: (warning) Comparison of modulo result is predetermined, because it is always less than 5.\n",
errout_str());
check("void f() {\n"
" if (a % 2 + b % 2 == 2)\n"
" foo();\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void oppositeInnerCondition() {
check("void foo(int a, int b) {\n"
" if(a==b)\n"
" if(a!=b)\n"
" cout << a;\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (warning) Opposite inner 'if' condition leads to a dead code block.\n", errout_str());
check("bool foo(int a, int b) {\n"
" if(a==b)\n"
" return a!=b;\n"
" return false;\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (warning) Opposite inner 'return' condition leads to a dead code block.\n", errout_str());
check("void foo(int a, int b) {\n"
" if(a==b)\n"
" if(b!=a)\n"
" cout << a;\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (warning) Opposite inner 'if' condition leads to a dead code block.\n", errout_str());
check("void foo(int a) {\n"
" if(a >= 50) {\n"
" if(a < 50)\n"
" cout << a;\n"
" else\n"
" cout << 100;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (warning) Opposite inner 'if' condition leads to a dead code block.\n", errout_str());
// #4186
check("void foo(int a) {\n"
" if(a >= 50) {\n"
" if(a > 50)\n"
" cout << a;\n"
" else\n"
" cout << 100;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// 4170
check("class foo {\n"
" void bar() {\n"
" if (tok == '(') {\n"
" next();\n"
" if (tok == ',') {\n"
" next();\n"
" if (tok != ',') {\n"
" op->reg2 = asm_parse_reg();\n"
" }\n"
" skip(',');\n"
" }\n"
" }\n"
" }\n"
" void next();\n"
" const char *tok;\n"
"};");
ASSERT_EQUALS("", errout_str());
check("void foo(int i)\n"
"{\n"
" if(i > 5) {\n"
" i = bar();\n"
" if(i < 5) {\n"
" cout << a;\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(int& i) {\n"
" i=6;\n"
"}\n"
"void bar(int i) {\n"
" if(i>5) {\n"
" foo(i);\n"
" if(i<5) {\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(int& i);\n"
"void bar() {\n"
" int i; i = func();\n"
" if(i>5) {\n"
" foo(i);\n"
" if(i<5) {\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(int i);\n"
"void bar(int i) {\n"
" if(i>5) {\n"
" foo(i);\n"
" if(i<5) {\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:5]: (warning) Opposite inner 'if' condition leads to a dead code block.\n", errout_str());
check("void foo(const int &i);\n"
"void bar(int i) {\n"
" if(i>5) {\n"
" foo(i);\n"
" if(i<5) {\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:5]: (warning) Opposite inner 'if' condition leads to a dead code block.\n", errout_str());
check("void foo(int i);\n"
"void bar() {\n"
" int i; i = func();\n"
" if(i>5) {\n"
" foo(i);\n"
" if(i<5) {\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:6]: (warning) Opposite inner 'if' condition leads to a dead code block.\n", errout_str());
check("class C { void f(int &i) const; };\n" // #7028 - variable is changed by const method
"void foo(C c, int i) {\n"
" if (i==5) {\n"
" c.f(i);\n"
" if (i != 5) {}\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// see linux revision 1f80c0cc
check("int generic_write_sync(int,int,int);\n"
"\n"
"void cifs_writev(int i) {\n"
" int rc = __generic_file_aio_write();\n"
" if (rc > 0){\n"
" err = generic_write_sync(file, iocb->ki_pos - rc, rc);\n"
" if(rc < 0) {\n" // <- condition is always false
" err = rc;\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:7]: (warning) Opposite inner 'if' condition leads to a dead code block.\n", errout_str());
// #5874 - array
check("void testOppositeConditions2() {\n"
" int array[2] = { 0, 0 };\n"
" if (array[0] < 2) {\n"
" array[0] += 5;\n"
" if (array[0] > 2) {}\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// #6227 - FP caused by simplifications of casts and known variables
check("void foo(A *a) {\n"
" if(a) {\n"
" B *b = dynamic_cast<B*>(a);\n"
" if(!b) {}\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(int a) {\n"
" if(a) {\n"
" int b = a;\n"
" if(!b) {}\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:2] -> [test.cpp:4]: (warning) Opposite inner 'if' condition leads to a dead code block.\n", errout_str());
check("void foo(unsigned u) {\n"
" if (u != 0) {\n"
" for (int i=0; i<32; i++) {\n"
" if (u == 0) {}\n" // <- don't warn
" u = x;\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// #8186
check("void f() {\n"
" for (int i=0;i<4;i++) {\n"
" if (i==5) {}\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (warning) Opposite inner 'if' condition leads to a dead code block.\n", errout_str());
// #8938
check("void Delete(SS_CELLCOORD upperleft) {\n"
" if ((upperleft.Col == -1) && (upperleft.Row == -1)) {\n"
" GetActiveCell(&(upperleft.Col), &(upperleft.Row));\n"
" if (upperleft.Row == -1) {}\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// #9702
check("struct A {\n"
" void DoTest() {\n"
" if (!IsSet()) {\n"
" m_value = true;\n"
" if (IsSet());\n"
" }\n"
" }\n"
" bool IsSet() const { return m_value; }\n"
" bool m_value = false;\n"
"};");
ASSERT_EQUALS("", errout_str());
// #12725
check("bool f(bool b) {\n"
" if (b)\n"
" return !b;\n"
" b = g();\n"
" return b;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) Return value '!b' is always false\n", errout_str());
}
void oppositeInnerConditionPointers() {
check("void f(struct ABC *abc) {\n"
" struct AB *ab = abc->ab;\n"
" if (ab->a == 123){\n"
" do_something(abc);\n" // might change ab->a
" if (ab->a != 123) {\n"
" err = rc;\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void Fred::f() {\n" // daca: ace
" if (this->next_ == map_man_->table_) {\n"
" this->next_ = n;\n"
" if (this->next_ != map_man_->table_) {}\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void test(float *f) {\n" // #7405
" if(*f>10) {\n"
" (*f) += 0.1f;\n"
" if(*f<10) {}\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int * f(int * x, int * y) {\n"
" if(!x) return x;\n"
" return y;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void oppositeInnerConditionClass() {
// #6095 - calling member function that might change the state
check("void f() {\n"
" const Fred fred;\n" // <- fred is const, warn
" if (fred.isValid()) {\n"
" fred.dostuff();\n"
" if (!fred.isValid()) {}\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:5]: (warning) Opposite inner 'if' condition leads to a dead code block.\n", errout_str());
check("class Fred { public: bool isValid() const; void dostuff() const; };\n"
"void f() {\n"
" Fred fred;\n"
" if (fred.isValid()) {\n"
" fred.dostuff();\n" // <- dostuff() is const, warn
" if (!fred.isValid()) {}\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:6]: (warning) Opposite inner 'if' condition leads to a dead code block.\n", errout_str());
check("void f() {\n"
" Fred fred;\n"
" if (fred.isValid()) {\n"
" fred.dostuff();\n"
" if (!fred.isValid()) {}\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// #6385 "crash in Variable::getFlag()"
check("class TranslationHandler {\n"
"QTranslator *mTranslator;\n"
"void SetLanguage() {\n"
" if (mTranslator) {\n"
" qApp->removeTranslator(mTranslator);\n"
" }\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str()); // just don't crash...
check("bool f(std::ofstream &CFileStream) {\n" // #8198
" if(!CFileStream.good()) { return; }\n"
" CFileStream << \"abc\";\n"
" if (!CFileStream.good()) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void oppositeInnerConditionUndeclaredVariable() {
// #5731 - fp when undeclared variable is used
check("void f() {\n"
" if (x == -1){\n"
" x = do_something();\n"
" if (x != -1) {}\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// #5750 - another fp when undeclared variable is used
check("void f() {\n"
" if (r < w){\n"
" r += 3;\n"
" if (r > w) {}\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// #6574 - another fp when undeclared variable is used
check("void foo() {\n"
" if(i) {\n"
" i++;\n"
" if(!i) {}\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// undeclared array
check("void f(int x) {\n"
" if (a[x] > 0) {\n"
" a[x] -= dt;\n"
" if (a[x] < 0) {}\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// #6313 - false positive: opposite conditions in nested if blocks when condition changed
check("void Foo::Bar() {\n"
" if(var){\n"
" --var;\n"
" if(!var){}\n"
" else {}\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// daca hyphy
check("bool f() {\n"
" if (rec.lLength==0) {\n"
" rec.Delete(i);\n"
" if (rec.lLength!=0) {}\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void oppositeInnerConditionAlias() {
check("void f() {\n"
" struct S s;\n"
" bool hasFailed = false;\n"
" s.status = &hasFailed;\n"
"\n"
" if (! hasFailed) {\n"
" doStuff(&s);\n"
" if (hasFailed) {}\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (style) Condition '!hasFailed' is always true\n", errout_str());
}
void oppositeInnerCondition2() {
// first comparison: <
check("void f(int x) {\n"
"\n"
" if (x<4) {\n"
" if (x==5) {}\n" // <- Warning
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (warning) Opposite inner 'if' condition leads to a dead code block.\n",
errout_str());
check("void f(int x) {\n"
"\n"
" if (x<4) {\n"
" if (x!=5) {}\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (style) Condition 'x!=5' is always true\n", errout_str());
check("void f(int x) {\n"
"\n"
" if (x<4) {\n"
" if (x>5) {}\n" // <- Warning
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (warning) Opposite inner 'if' condition leads to a dead code block.\n",
errout_str());
check("void f(int x) {\n"
"\n"
" if (x<4) {\n"
" if (x>=5) {}\n" // <- Warning
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (warning) Opposite inner 'if' condition leads to a dead code block.\n",
errout_str());
check("void f(int x) {\n"
"\n"
" if (x<4) {\n"
" if (x<5) {}\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (style) Condition 'x<5' is always true\n", errout_str());
check("void f(int x) {\n"
"\n"
" if (x<4) {\n"
" if (x<=5) {}\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (style) Condition 'x<=5' is always true\n", errout_str());
check("void f(int x) {\n"
"\n"
" if (x<5) {\n"
" if (x==4) {}\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
"\n"
" if (x<5) {\n"
" if (x!=4) {}\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
"\n"
" if (x<5) {\n"
" if (x!=6) {}\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (style) Condition 'x!=6' is always true\n", errout_str());
check("void f(int x) {\n"
"\n"
" if (x<5) {\n"
" if (x>4) {}\n" // <- Warning
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (style) Condition 'x>4' is always false\n", errout_str());
check("void f(int x) {\n"
"\n"
" if (x<5) {\n"
" if (x>=4) {}\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
"\n"
" if (x<5) {\n"
" if (x<4) {}\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
"\n"
" if (x<5) {\n"
" if (x<=4) {}\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (style) Condition 'x<=4' is always true\n", errout_str());
// first comparison: >
check("void f(int x) {\n"
"\n"
" if (x>4) {\n"
" if (x==5) {}\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
"\n"
" if (x>4) {\n"
" if (x>5) {}\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
"\n"
" if (x>4) {\n"
" if (x>=5) {}\n" // <- Warning
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (style) Condition 'x>=5' is always true\n", errout_str());
check("void f(int x) {\n"
"\n"
" if (x>4) {\n"
" if (x<5) {}\n" // <- Warning
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (style) Condition 'x<5' is always false\n", errout_str());
check("void f(int x) {\n"
"\n"
" if (x>4) {\n"
" if (x<=5) {}\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
"\n"
" if (x>5) {\n"
" if (x==4) {}\n" // <- Warning
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (warning) Opposite inner 'if' condition leads to a dead code block.\n",
errout_str());
check("void f(int x) {\n"
"\n"
" if (x>5) {\n"
" if (x>4) {}\n" // <- Warning
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (style) Condition 'x>4' is always true\n", errout_str());
check("void f(int x) {\n"
"\n"
" if (x>5) {\n"
" if (x>=4) {}\n" // <- Warning
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (style) Condition 'x>=4' is always true\n", errout_str());
check("void f(int x) {\n"
"\n"
" if (x>5) {\n"
" if (x<4) {}\n" // <- Warning
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (warning) Opposite inner 'if' condition leads to a dead code block.\n",
errout_str());
check("void f(int x) {\n"
"\n"
" if (x>5) {\n"
" if (x<=4) {}\n" // <- Warning
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (warning) Opposite inner 'if' condition leads to a dead code block.\n",
errout_str());
check("void f(int x) {\n"
" if (x < 4) {\n"
" if (10 < x) {}\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (warning) Opposite inner 'if' condition leads to a dead code block.\n", errout_str());
}
void oppositeInnerCondition3() {
check("void f3(char c) { if(c=='x') if(c=='y') {}}");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:1]: (warning) Opposite inner 'if' condition leads to a dead code block.\n", errout_str());
check("void f4(char *p) { if(*p=='x') if(*p=='y') {}}");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:1]: (warning) Opposite inner 'if' condition leads to a dead code block.\n", errout_str());
check("void f5(const char * const p) { if(*p=='x') if(*p=='y') {}}");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:1]: (warning) Opposite inner 'if' condition leads to a dead code block.\n", errout_str());
check("void f5(const char * const p) { if('x'==*p) if('y'==*p) {}}");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:1]: (warning) Opposite inner 'if' condition leads to a dead code block.\n", errout_str());
check("void f6(char * const p) { if(*p=='x') if(*p=='y') {}}");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:1]: (warning) Opposite inner 'if' condition leads to a dead code block.\n", errout_str());
check("void f7(const char * p) { if(*p=='x') if(*p=='y') {}}");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:1]: (warning) Opposite inner 'if' condition leads to a dead code block.\n", errout_str());
check("void f8(int i) { if(i==4) if(i==2) {}}");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:1]: (warning) Opposite inner 'if' condition leads to a dead code block.\n", errout_str());
check("void f9(int *p) { if (*p==4) if(*p==2) {}}");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:1]: (warning) Opposite inner 'if' condition leads to a dead code block.\n", errout_str());
check("void f10(int * const p) { if (*p==4) if(*p==2) {}}");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:1]: (warning) Opposite inner 'if' condition leads to a dead code block.\n", errout_str());
check("void f11(const int *p) { if (*p==4) if(*p==2) {}}");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:1]: (warning) Opposite inner 'if' condition leads to a dead code block.\n", errout_str());
check("void f12(const int * const p) { if (*p==4) if(*p==2) {}}");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:1]: (warning) Opposite inner 'if' condition leads to a dead code block.\n", errout_str());
check("struct foo {\n"
" int a;\n"
" int b;\n"
"};\n"
"void f(foo x) { if(x.a==4) if(x.b==2) {}}");
ASSERT_EQUALS("", errout_str());
check("struct foo {\n"
" int a;\n"
" int b;\n"
"};\n"
"void f(foo x) { if(x.a==4) if(x.b==4) {}}");
ASSERT_EQUALS("", errout_str());
check("void f3(char a, char b) { if(a==b) if(a==0) {}}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) { if (x == 1) if (x != 1) {} }");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:1]: (warning) Opposite inner 'if' condition leads to a dead code block.\n", errout_str());
}
void oppositeInnerConditionAnd() {
check("void f(int x) {\n"
" if (a>3 && x > 100) {\n"
" if (x < 10) {}\n"
" }"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (warning) Opposite inner 'if' condition leads to a dead code block.\n", errout_str());
check("void f(bool x, const int a, const int b) {\n"
" if(x && a < b)\n"
" if( x && a > b){}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (warning) Opposite inner 'if' condition leads to a dead code block.\n", errout_str());
}
void oppositeInnerConditionOr()
{
check("void f(int x) {\n"
" if (x == 1 || x == 2) {\n"
" if (x == 3) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (warning) Opposite inner 'if' condition leads to a dead code block.\n",
errout_str());
check("void f(int x) {\n"
" if (x == 1 || x == 2) {\n"
" if (x == 1) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
" if (x == 1 || x == 2) {\n"
" if (x == 2) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(std::string x) {\n"
" if (x == \"1\" || x == \"2\") {\n"
" if (x == \"1\") {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
" if (x < 1 || x > 3) {\n"
" if (x == 3) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (warning) Opposite inner 'if' condition leads to a dead code block.\n",
errout_str());
}
void oppositeInnerConditionEmpty() {
check("void f1(const std::string &s) { if(s.size() > 42) if(s.empty()) {}}");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:1]: (warning) Opposite inner 'if' condition leads to a dead code block.\n", errout_str());
check("void f1(const std::string &s) { if(s.size() > 0) if(s.empty()) {}}");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:1]: (warning) Opposite inner 'if' condition leads to a dead code block.\n", errout_str());
check("void f1(const std::string &s) { if(s.size() < 0) if(s.empty()) {}} "); // <- CheckOther reports: checking if unsigned expression is less than zero
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:1]: (style) Condition 's.empty()' is always false\n", errout_str());
check("void f1(const std::string &s) { if(s.empty()) if(s.size() > 42) {}}");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:1]: (warning) Opposite inner 'if' condition leads to a dead code block.\n", errout_str());
check("template<class T> void f1(const T &s) { if(s.size() > 42) if(s.empty()) {}}");
ASSERT_EQUALS("", errout_str()); //We don't know the type of T so we don't know the relationship between size() and empty(). e.g. s might be a 50 tonne truck with nothing in it.
check("void f2(const std::wstring &s) { if(s.empty()) if(s.size() > 42) {}}");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:1]: (warning) Opposite inner 'if' condition leads to a dead code block.\n", errout_str());
check("void f1(QString s) { if(s.isEmpty()) if(s.length() > 42) {}}");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:1]: (warning) Opposite inner 'if' condition leads to a dead code block.\n", errout_str());
check("void f1(const std::string &s, bool b) { if(s.empty() || ((s.size() == 1) && b)) {}}");
ASSERT_EQUALS("", errout_str());
check("void f1(const std::string &x, const std::string &y) { if(x.size() > 42) if(y.empty()) {}}");
ASSERT_EQUALS("", errout_str());
check("void f1(const std::string &x, const std::string &y) { if(y.empty()) if(x.size() > 42) {}}");
ASSERT_EQUALS("", errout_str());
check("void f1(const std::string v[10]) { if(v[0].size() > 42) if(v[1].empty()) {}}");
ASSERT_EQUALS("", errout_str());
check("void f1(const std::string &s) { if(s.size() <= 1) if(s.empty()) {}}");
ASSERT_EQUALS("", errout_str());
check("void f1(const std::string &s) { if(s.size() <= 2) if(s.empty()) {}}");
ASSERT_EQUALS("", errout_str());
check("void f1(const std::string &s) { if(s.size() < 2) if(s.empty()) {}}");
ASSERT_EQUALS("", errout_str());
check("void f1(const std::string &s) { if(s.size() >= 0) if(s.empty()) {}} "); // CheckOther says: Unsigned expression 's.size()' can't be negative so it is unnecessary to test it. [unsignedPositive]
ASSERT_EQUALS("", errout_str());
// TODO: These are identical condition since size cannot be negative
check("void f1(const std::string &s) { if(s.size() <= 0) if(s.empty()) {}}");
ASSERT_EQUALS("", errout_str());
// TODO: These are identical condition since size cannot be negative
check("void f1(const std::string &s) { if(s.size() < 1) if(s.empty()) {}}");
ASSERT_EQUALS("", errout_str());
}
void oppositeInnerConditionFollowVar() {
check("struct X {\n"
" void f() {\n"
" const int flag = get();\n"
" if (flag) {\n"
" bar();\n"
" if (!get()) {}\n"
" }\n"
" }\n"
" void bar();\n"
" int get() const;\n"
"};");
ASSERT_EQUALS("", errout_str());
check("struct CD {\n"
" bool state;\n"
" void foo() {\n"
" const bool flag = this->get();\n"
" if (flag) {\n"
" this->bar();\n"
" if (!this->get()) return;\n"
" }\n"
" }\n"
" bool get() const;\n"
" void bar();\n"
"};\n");
ASSERT_EQUALS("", errout_str());
check("class C {\n"
"public:\n"
" bool f() const { return x > 0; }\n"
" void g();\n"
" int x = 0;\n"
"};\n"
"\n"
"void C::g() {\n"
" bool b = f();\n"
" x += 1;\n"
" if (!b && f()) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(double d) {\n"
" if (d != 0) {\n"
" int i = d;\n"
" if (i == 0) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void identicalInnerCondition() {
check("void f1(int a, int b) { if(a==b) if(a==b) {}}");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:1]: (warning) Identical inner 'if' condition is always true.\n", errout_str());
check("void f2(int a, int b) { if(a!=b) if(a!=b) {}}");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:1]: (warning) Identical inner 'if' condition is always true.\n", errout_str());
// #6645 false negative: condition is always false
check("void f(bool a, bool b) {\n"
" if(a && b) {\n"
" if(a) {}\n"
" else {}\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (warning) Identical inner 'if' condition is always true.\n", errout_str());
check("bool f(int a, int b) {\n"
" if(a == b) { return a == b; }\n"
" return false;\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:2]: (warning) Identical inner 'return' condition is always true.\n", errout_str());
check("bool f(bool a) {\n"
" if(a) { return a; }\n"
" return false;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int* f(int* a, int * b) {\n"
" if(a) { return a; }\n"
" return b;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int* f(std::shared_ptr<int> a, std::shared_ptr<int> b) {\n"
" if(a.get()) { return a.get(); }\n"
" return b.get();\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct A { int * x; };\n"
"int* f(A a, int * b) {\n"
" if(a.x) { return a.x; }\n"
" return b;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" uint32_t value;\n"
" get_value(&value);\n"
" int opt_function_capable = (value >> 28) & 1;\n"
" if (opt_function_capable) {\n"
" value = 0;\n"
" get_value (&value);\n"
" if ((value >> 28) & 1) {}\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
checkP("#define TYPE_1 \"a\"\n" // #13202
"#define TYPE_2 \"b\"\n"
"#define TYPE_3 \"c\"\n"
"void f(const std::string& s) {\n"
" if (s == TYPE_1) {}\n"
" else if (s == TYPE_2 || s == TYPE_3) {\n"
" if (s == TYPE_2) {}\n"
" else if (s == TYPE_3) {}\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void identicalConditionAfterEarlyExit() {
check("void f(int x) {\n" // #8137
" if (x > 100) { return; }\n"
" if (x > 100) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (warning) Identical condition 'x>100', second condition is always false\n", errout_str());
check("bool f(int x) {\n"
" if (x > 100) { return false; }\n"
" return x > 100;\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (warning) Identical condition and return expression 'x>100', return value is always false\n", errout_str());
check("void f(int x) {\n"
" if (x > 100) { return; }\n"
" if (x > 100 || y > 100) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (warning) Identical condition 'x>100', second condition is always false\n", errout_str());
check("void f(int x) {\n"
" if (x > 100) { return; }\n"
" if (x > 100 && y > 100) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (warning) Identical condition 'x>100', second condition is always false\n", errout_str());
check("void f(int x) {\n"
" if (x > 100) { return; }\n"
" if (abc) {}\n"
" if (x > 100) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:4]: (warning) Identical condition 'x>100', second condition is always false\n", errout_str());
check("void f(int x) {\n"
" if (x > 100) { return; }\n"
" while (abc) { y = x; }\n"
" if (x > 100) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:4]: (warning) Identical condition 'x>100', second condition is always false\n", errout_str());
ASSERT_THROW_INTERNAL(check("void f(int x) {\n" // #8217 - crash for incomplete code
" if (x > 100) { return; }\n"
" X(do);\n"
" if (x > 100) {}\n"
"}"),
SYNTAX);
check("void f(const int *i) {\n"
" if (!i) return;\n"
" if (!num1tok) { *num1 = *num2; }\n"
" if (!i) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:4]: (warning) Identical condition '!i', second condition is always false\n", errout_str());
check("void C::f(Tree &coreTree) {\n" // daca
" if(!coreTree.build())\n"
" return;\n"
" coreTree.dostuff();\n"
" if(!coreTree.build()) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct C { void f(const Tree &coreTree); };\n"
"void C::f(const Tree &coreTree) {\n"
" if(!coreTree.build())\n"
" return;\n"
" coreTree.dostuff();\n"
" if(!coreTree.build()) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:6]: (warning) Identical condition '!coreTree.build()', second condition is always false\n", errout_str());
check("void f(int x) {\n" // daca: labplot
" switch(type) {\n"
" case 1:\n"
" if (x == 0) return 1;\n"
" else return 2;\n"
" case 2:\n"
" if (x == 0) return 3;\n"
" else return 4;\n"
" }\n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("static int failed = 0;\n"
"void f() {\n"
" if (failed) return;\n"
" checkBuffer();\n"
" if (failed) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
// daca icu
check("void f(const uint32_t *section, int32_t start) {\n"
" if(10<=section[start]) { return; }\n"
" if(++start<100 && 10<=section[start]) { }\n"
"}");
ASSERT_EQUALS("", errout_str());
// daca iqtree
check("void readNCBITree(std::istream &in) {\n"
" char ch;\n"
" in >> ch;\n"
" if (ch != '|') return;\n"
" in >> ch;\n"
" if (ch != '|') {}\n"
"}");
ASSERT_EQUALS("", errout_str());
// #8924
check("struct A {\n"
" void f() {\n"
" if (this->FileIndex >= 0) return;\n"
" this->FileIndex = 1 ;\n"
" if (this->FileIndex < 0) return;\n"
" }\n"
" int FileIndex;\n"
"};");
ASSERT_EQUALS("[test.cpp:5]: (style) Condition 'this->FileIndex<0' is always false\n", errout_str());
// #8858 - #if
check("short Do() {\n"
" short ret = bar1();\n"
" if ( ret )\n"
" return ret;\n"
"#ifdef FEATURE\n"
" ret = bar2();\n"
"#endif\n"
" return ret;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #10456
check("int f() {\n"
" int i = 0;\n"
" auto f = [&](bool b) { if (b) ++i; };\n"
" if (i) return i;\n"
" f(true);\n"
" if (i) return i;\n"
" return 0;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #11478
check("struct S {\n"
" void run();\n"
" bool b = false;\n"
" const std::function<void(S&)> f;\n"
"};\n"
"void S::run() {\n"
" while (true) {\n"
" if (b)\n"
" return;\n"
" f(*this);\n"
" if (b)\n"
" return;\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void innerConditionModified() {
check("void f(int x, int y) {\n"
" if (x == 0) {\n"
" x += y;\n"
" if (x == 0) {}\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
" if (x == 0) {\n"
" x += y;\n"
" if (x == 1) {}\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int * x, int * y) {\n"
" if (x[*y] == 0) {\n"
" (*y)++;\n"
" if (x[*y] == 0) {}\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
// clarify conditions with = and comparison
void clarifyCondition1() {
check("void f() {\n"
" if (x = b() < 0) {}\n" // don't simplify and verify this code
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Suspicious condition (assignment + comparison); Clarify expression with parentheses.\n", errout_str());
check("void f(int i) {\n"
" for (i = 0; i < 10; i++) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" x = a<int>(); if (x) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" if (x = b < 0 ? 1 : 2) {}\n" // don't simplify and verify this code
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int y = rand(), z = rand();\n"
" if (y || (!y && z));\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Redundant condition: !y. 'y || (!y && z)' is equivalent to 'y || z'\n", errout_str());
check("void f() {\n"
" int y = rand(), z = rand();\n"
" if (y || !y && z);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Redundant condition: !y. 'y || (!y && z)' is equivalent to 'y || z'\n", errout_str());
check("void f() {\n"
" if (!a || a && b) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Redundant condition: a. '!a || (a && b)' is equivalent to '!a || b'\n", errout_str());
check("void f(const Token *tok) {\n"
" if (!tok->next()->function() ||\n"
" (tok->next()->function() && tok->next()->function()->isConstructor()));\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Redundant condition: tok->next()->function(). '!A || (A && B)' is equivalent to '!A || B'\n", errout_str());
check("void f() {\n"
" if (!tok->next()->function() ||\n"
" (!tok->next()->function() && tok->next()->function()->isConstructor()));\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" if (!tok->next()->function() ||\n"
" (!tok2->next()->function() && tok->next()->function()->isConstructor()));\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(const Token *tok) {\n"
" if (!tok->next(1)->function(1) ||\n"
" (tok->next(1)->function(1) && tok->next(1)->function(1)->isConstructor()));\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Redundant condition: tok->next(1)->function(1). '!A || (A && B)' is equivalent to '!A || B'\n", errout_str());
check("void f() {\n"
" if (!tok->next()->function(1) ||\n"
" (tok->next()->function(2) && tok->next()->function()->isConstructor()));\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int y = rand(), z = rand();\n"
" if (y==0 || y!=0 && z);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Redundant condition: y!=0. 'y==0 || (y!=0 && z)' is equivalent to 'y==0 || z'\n", errout_str());
check("void f() {\n"
" if (x>0 || (x<0 && y)) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
// Test Token::expressionString, TODO move this test
check("void f() {\n"
" if (!dead || (dead && (*it).ticks > 0)) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Redundant condition: dead. '!dead || (dead && (*it).ticks>0)' is equivalent to '!dead || (*it).ticks>0'\n", errout_str());
check("void f() {\n"
" if (!x || (x && (2>(y-1)))) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Redundant condition: x. '!x || (x && 2>(y-1))' is equivalent to '!x || 2>(y-1)'\n", errout_str());
check("void f(bool a, bool b) {\n"
" if (a || (a && b)) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Redundant condition: a. 'a || (a && b)' is equivalent to 'a'\n", errout_str());
check("void f(bool a, bool b) {\n"
" if (a && (a || b)) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Redundant condition: a. 'a && (a || b)' is equivalent to 'a'\n", errout_str());
}
// clarify conditions with bitwise operator and comparison
void clarifyCondition2() {
check("void f() {\n"
" if (x & 3 == 2) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Suspicious condition (bitwise operator + comparison); Clarify expression with parentheses.\n"
"[test.cpp:2]: (style) Boolean result is used in bitwise operation. Clarify expression with parentheses.\n"
"[test.cpp:2]: (style) Condition 'x&3==2' is always false\n", errout_str());
check("void f() {\n"
" if (a & fred1.x == fred2.y) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Suspicious condition (bitwise operator + comparison); Clarify expression with parentheses.\n"
"[test.cpp:2]: (style) Boolean result is used in bitwise operation. Clarify expression with parentheses.\n"
, errout_str());
}
// clarify condition that uses ! operator and then bitwise operator
void clarifyCondition3() {
check("void f(int w) {\n"
" if(!w & 0x8000) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Boolean result is used in bitwise operation. Clarify expression with parentheses.\n", errout_str());
check("void f(int w) {\n"
" if((!w) & 0x8000) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" if (x == foo() & 2) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Boolean result is used in bitwise operation. Clarify expression with parentheses.\n", errout_str());
check("void f() {\n"
" if (2 & x == foo()) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Boolean result is used in bitwise operation. Clarify expression with parentheses.\n", errout_str());
check("void f() {\n"
" if (2 & (x == foo())) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(std::list<int> &ints) { }");
ASSERT_EQUALS("", errout_str());
check("void f() { A<x &> a; }");
ASSERT_EQUALS("", errout_str());
check("void f() { a(x<y|z,0); }", "test.c"); // filename is c => there are never templates
ASSERT_EQUALS("[test.c:1]: (style) Boolean result is used in bitwise operation. Clarify expression with parentheses.\n", errout_str());
check("class A<B&,C>;", "test.cpp");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" if (result != (char *)&inline_result) { }\n" // don't simplify and verify cast
"}");
ASSERT_EQUALS("", errout_str());
// #8495
check("void f(bool a, bool b) {\n"
" C & a & b;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void clarifyCondition4() { // ticket #3110
check("typedef double SomeType;\n"
"typedef std::pair<std::string,SomeType> PairType;\n"
"struct S\n"
"{\n"
" bool operator()\n"
" ( PairType const & left\n"
" , PairType const & right) const\n"
" {\n"
" return left.first < right.first;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void clarifyCondition5() { // ticket #3609 (using | in template instantiation)
check("template<bool B> struct CWinTraits;\n"
"CWinTraits<WS_CHILD|WS_VISIBLE>::GetWndStyle(0);");
ASSERT_EQUALS("", errout_str());
}
void clarifyCondition6() {
check("template<class Y>\n"
"SharedPtr& operator=( SharedPtr<Y> const & r ) {\n"
" px = r.px;\n"
" return *this;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void clarifyCondition7() {
// Ensure that binary and unary &, and & in declarations are distinguished properly
check("void f(bool error) {\n"
" bool & withoutSideEffects=found.first->second;\n" // Declaring a reference to a boolean; & is no operator at all
" execute(secondExpression, &programMemory, &result, &error);\n" // Unary &
"}");
ASSERT_EQUALS("", errout_str());
}
void clarifyCondition8() {
// don't warn when boolean result comes from function call, array index, etc
// the operator precedence is not unknown then
check("bool a();\n"
"bool f(bool b) {\n"
" return (a() & b);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool f(bool *a, bool b) {\n"
" return (a[10] & b);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct A { bool a; };\n"
"bool f(struct A a, bool b) {\n"
" return (a.a & b);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct A { bool a; };\n"
"bool f(struct A a, bool b) {\n"
" return (A::a & b);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void testBug5895() {
check("void png_parse(uint64_t init, int buf_size) {\n"
" if (init == 0x89504e470d0a1a0a || init == 0x8a4d4e470d0a1a0a)\n"
" ;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void testBug5309() {
check("extern uint64_t value;\n"
"void foo() {\n"
" if( ( value >= 0x7ff0000000000001ULL )\n"
" && ( value <= 0x7fffffffffffffffULL ) );\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void alwaysTrue() {
check("void f(const struct S *s) {\n" //#8196
" int x1 = s->x;\n"
" int x2 = s->x;\n"
" if (x1 == 10 && x2 == 10) {}\n" // <<
"}");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:4]: (style) Condition 'x2==10' is always true\n", errout_str());
check("void f ()\n"// #8220
"{\n"
" int a;\n"
" int b = 0;\n"
" int ret;\n"
" \n"
" a = rand();\n"
" while (((0 < a) && (a < 2)) && ((8 < a) && (a < 10))) \n"
" {\n"
" b += a;\n"
" a ++;\n"
" }\n"
" ret = b;\n"
"}");
ASSERT_EQUALS("[test.cpp:8] -> [test.cpp:8]: (style) Condition '8<a' is always false\n", errout_str());
check("void f() {\n" // #4842
" int x = 0;\n"
" if (a) { return; }\n" // <- this is just here to fool simplifyKnownVariabels
" if (!x) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Condition '!x' is always true\n", errout_str());
check("bool f(int x) {\n"
" if(x == 0) { x++; return x == 0; }\n"
" return false;\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:2]: (style) Return value 'x==0' is always false\n", errout_str());
check("void f() {\n" // #6898 (Token::expressionString)
" int x = 0;\n"
" A(x++ == 1);\n"
" A(x++ == 2);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Condition 'x++==1' is always false\n"
"[test.cpp:4]: (style) Condition 'x++==2' is always false\n",
errout_str());
check("bool foo(int bar) {\n"
" bool ret = false;\n"
" if (bar == 1)\n"
" return ret;\n" // <- #9326 - FP condition is always false
" if (bar == 2)\n"
" ret = true;\n"
" return ret;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f1(const std::string &s) { if(s.empty()) if(s.size() == 0) {}}");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:1]: (style) Condition 's.size()==0' is always true\n", errout_str());
check("void f() {\n"
" int buf[42];\n"
" if( buf != 0) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Condition 'buf!=0' is always true\n", errout_str()); // #8924
check("void f() {\n"
" int buf[42];\n"
" if( !buf ) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Condition '!buf' is always false\n", errout_str());
check("void f() {\n"
" int buf[42];\n"
" bool b = buf;\n"
" if( b ) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Condition 'b' is always true\n", errout_str());
check("void f() {\n"
" int buf[42];\n"
" bool b = buf;\n"
" if( !b ) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Condition '!b' is always false\n", errout_str());
check("void f() {\n"
" int buf[42];\n"
" int * p = nullptr;\n"
" if( buf == p ) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Condition 'buf==p' is always false\n", errout_str());
check("void f(bool x) {\n"
" int buf[42];\n"
" if( buf || x ) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Condition 'buf' is always true\n", errout_str());
check("void f(int * p) {\n"
" int buf[42];\n"
" if( buf == p ) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int buf[42];\n"
" int p[42];\n"
" if( buf == p ) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int buf[42];\n"
" if( buf == 1) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
// Avoid FP when condition comes from macro
check("#define NOT !\n"
"void f() {\n"
" int x = 0;\n"
" if (a) { return; }\n" // <- this is just here to fool simplifyKnownVariabels
" if (NOT x) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("#define M x != 0\n"
"void f() {\n"
" int x = 0;\n"
" if (a) { return; }\n" // <- this is just here to fool simplifyKnownVariabels
" if (M) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("#define IF(X) if (X && x())\n"
"void f() {\n"
" IF(1) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
// Avoid FP for sizeof condition
check("void f() {\n"
" if (sizeof(char) != 123) {}\n"
" if (123 != sizeof(char)) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int x = 123;\n"
" if (sizeof(char) != x) {}\n"
" if (x != sizeof(char)) {}\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:3]: (style) Condition 'sizeof(char)!=x' is always true\n"
"[test.cpp:4]: (style) Condition 'x!=sizeof(char)' is always true\n", "", errout_str());
// Don't warn in assertions. Condition is often 'always true' by intention.
// If platform,defines,etc cause an 'always false' assertion then that is not very dangerous neither
check("void f() {\n"
" int x = 0;\n"
" assert(x == 0);\n"
"}");
ASSERT_EQUALS("", errout_str());
// #9363 - do not warn about value passed to function
check("void f(bool b) {\n"
" if (b) {\n"
" if (bar(!b)) {}\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// #7783 FP knownConditionTrueFalse on assert(0 && "message")
check("void foo(int x) {\n"
" if (x<0)\n"
" {\n"
" assert(0 && \"bla\");\n"
" ASSERT(0 && \"bla\");\n"
" assert_foo(0 && \"bla\");\n"
" ASSERT_FOO(0 && \"bla\");\n"
" assert((int)(0==0));\n"
" assert((int)(0==0) && \"bla\");\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// #7750 char literals in boolean expressions
check("void f() {\n"
" if('a'){}\n"
" if(L'b'){}\n"
" if(1 && 'c'){}\n"
" int x = 'd' ? 1 : 2;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #8206 - knownCondition always false
check("void f(int i)\n"
"{\n"
" if(i > 4)\n"
" for( int x = 0; i < 3; ++x){}\n" // <<
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:4]: (style) Condition 'i<3' is always false\n", errout_str());
// Skip literals
check("void f() { if(true) {} }");
ASSERT_EQUALS("", errout_str());
check("void f() { if(false) {} }");
ASSERT_EQUALS("", errout_str());
check("void f() { if(!true) {} }");
ASSERT_EQUALS("", errout_str());
check("void f() { if(!false) {} }");
ASSERT_EQUALS("", errout_str());
check("void f() { if(0) {} }");
ASSERT_EQUALS("", errout_str());
check("void f() { if(1) {} }");
ASSERT_EQUALS("", errout_str());
check("void f(int i) {\n"
" bool b = false;\n"
" if (i == 0) b = true;\n"
" else if (!b && i == 1) {}\n"
" if (b)\n"
" {}\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Condition '!b' is always true\n", errout_str());
check("bool f() { return nullptr; }");
ASSERT_EQUALS("", errout_str());
check("enum E { A };\n"
"bool f() { return A; }");
ASSERT_EQUALS("", errout_str());
check("bool f() {\n"
" const int x = 0;\n"
" return x;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f(void){return 1/abs(10);}");
ASSERT_EQUALS("", errout_str());
check("bool f() {\n"
" int x = 0;\n"
" return x;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool f() {\n"
" const int a = 50;\n"
" const int b = 52;\n"
" return a+b;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Return value 'a+b' is always true\n", errout_str());
check("int f() {\n"
" int a = 50;\n"
" int b = 52;\n"
" a++;\n"
" b++;\n"
" return a+b;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool& g();\n"
"bool f() {\n"
" bool & b = g();\n"
" b = false;\n"
" return b;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct A {\n"
" bool b;\n"
" bool f() {\n"
" b = false;\n"
" return b;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("bool f(long maxtime) {\n"
" if (std::time(0) > maxtime)\n"
" return std::time(0) > maxtime;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(double param) {\n"
" while(bar()) {\n"
" if (param<0.)\n"
" return;\n"
" }\n"
" if (param<0.)\n"
" return;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(int i) {\n"
" if (i==42)\n"
" {\n"
" bar();\n"
" }\n"
" if (cond && (42==i))\n"
" return;\n"
"}");
ASSERT_EQUALS("", errout_str());
// 8842 crash
check("class a {\n"
" int b;\n"
" c(b);\n"
" void f() {\n"
" if (b) return;\n"
" }\n"
"};");
ASSERT_EQUALS("", errout_str());
check("void f(const char* x, const char* t) {\n"
" if (!(strcmp(x, y) == 0)) { return; }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(const int a[]){ if (a == 0){} }");
ASSERT_EQUALS("", errout_str());
check("struct S {\n"
" bool operator<(const S&);\n"
"};\n"
"int main() {\n"
" S s;\n"
" bool c = s<s;\n"
" if (c) return 0;\n"
" else return 42;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("long X::g(bool unknown, int& result) {\n"
" long ret = 0;\n"
" bool f = false;\n"
" f = f || unknown;\n"
" f ? result = 42 : ret = -1;\n"
" return ret;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f(void *handle) {\n"
" if (!handle) return 0;\n"
" if (handle) return 1;\n"
" else return 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) Condition 'handle' is always true\n", errout_str());
check("int f(void *handle) {\n"
" if (handle == 0) return 0;\n"
" if (handle) return 1;\n"
" else return 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Condition 'handle' is always true\n", errout_str());
check("int f(void *handle) {\n"
" if (handle != 0) return 0;\n"
" if (handle) return 1;\n"
" else return 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (warning) Identical condition 'handle!=0', second condition is always false\n", errout_str());
check("int f(void *handle) {\n"
" if (handle != nullptr) return 0;\n"
" if (handle) return 1;\n"
" else return 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (warning) Identical condition 'handle!=nullptr', second condition is always false\n", errout_str());
check("void f(void* x, void* y) {\n"
" if (x == nullptr && y == nullptr)\n"
" return;\n"
" if (x == nullptr || y == nullptr)\n"
" return;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void* g();\n"
"void f(void* a, void* b) {\n"
" while (a) {\n"
" a = g();\n"
" if (a == b)\n"
" break;\n"
" }\n"
" if (a) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void* g();\n"
"void f(void* a, void* b) {\n"
" while (a) {\n"
" a = g();\n"
" }\n"
" if (a) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:6]: (style) Condition 'a' is always false\n", errout_str());
check("void f(int * x, bool b) {\n"
" if (!x && b) {}\n"
" else if (x) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" const std::string x=\"xyz\";\n"
" if(!x.empty()){}\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Condition '!x.empty()' is always true\n", errout_str());
check("std::string g();\n"
"void f() {\n"
" const std::string msg = g();\n"
" if(!msg.empty()){}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int *array, int size ) {\n"
" for(int i = 0; i < size; ++i) {\n"
" if(array == 0)\n"
" continue;\n"
" if(array){}\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (style) Condition 'array' is always true\n", errout_str());
check("void f(int *array, int size ) {\n"
" for(int i = 0; i < size; ++i) {\n"
" if(array == 0)\n"
" continue;\n"
" else if(array){}\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:5]: (style) Condition 'array' is always true\n", errout_str());
// #9277
check("int f() {\n"
" constexpr bool x = true;\n"
" if constexpr (x)\n"
" return 0;\n"
" else\n"
" return 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #9954
check("void f() {\n"
" const size_t a(8 * sizeof(short));\n"
" const size_t b(8 * sizeof(int));\n"
" if constexpr (a == 16 && b == 16) {}\n"
" else if constexpr (a == 16 && b == 32) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #9319
check("struct S {\n"
" int a;\n"
" int b;\n"
"};\n"
"void g(S s, bool& x);\n"
"void f() {\n"
" bool x = false;\n"
" g({0, 1}, x);\n"
" if (x) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
// #9318
check("class A {};\n"
"class B : public A {};\n"
"void f(A* x) {\n"
" if (!x)\n"
" return;\n"
" auto b = dynamic_cast<B*>(x);\n"
" if (b) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int foo() {\n"
" auto x = getX();\n"
" if (x == nullptr)\n"
" return 1;\n"
" auto y = dynamic_cast<Y*>(x)\n"
" if (y == nullptr)\n"
" return 2;\n"
" return 3;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// handleKnownValuesInLoop
check("bool g();\n"
"void f(bool x) {\n"
" if (x) while(x) x = g();\n"
"}");
ASSERT_EQUALS("", errout_str());
// isLikelyStream
check("void f(std::istringstream& iss) {\n"
" std::string x;\n"
" while (iss) {\n"
" iss >> x;\n"
" if (!iss) break;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// #9332
check("struct A { void* g(); };\n"
"void f() {\n"
" A a;\n"
" void* b = a.g();\n"
" if (!b) return;\n"
" void* c = a.g();\n"
" if (!c) return;\n"
" bool compare = c == b;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #9361
check("void f(char c) {\n"
" if (c == '.') {}\n"
" else if (isdigit(c) != 0) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
// #9351
check("int f(int x) {\n"
" const bool b = x < 42;\n"
" if(b) return b?0:-1;\n"
" return 42;\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:3]: (style) Condition 'b' is always true\n", errout_str());
// #9362
check("uint8_t g();\n"
"void f() {\n"
" const uint8_t v = g();\n"
" if((v != 0x00)) {\n"
" if( (v & 0x01) == 0x00) {}\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// #9367
check("void f(long x) {\n"
" if (x <= 0L)\n"
" return;\n"
" if (x % 360L == 0)\n"
" return;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("int f(int a, int b) {\n"
" static const int x = 10;\n"
" return x == 1 ? a : b;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("const bool x = false;\n"
"void f() {\n"
" if (x) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("const bool x = false;\n"
"void f() {\n"
" if (!x) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
// #9709
check("void f(int a) {\n"
" bool ok = false;\n"
" const char * r = nullptr;\n"
" do_something(&r);\n"
" if (r != nullptr)\n"
" ok = a != 0;\n"
" if (ok) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
// #9816
check("bool g();\n"
"void f() {\n"
" bool b = false;\n"
" do {\n"
" do {\n"
" if (g())\n"
" break;\n"
" b = true;\n"
" } while(false);\n"
" } while(!b);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #9865
check("void f(const std::string &s) {\n"
" for (std::string::const_iterator it = s.begin(); it != s.end(); ++it) {\n"
" const unsigned char c = static_cast<unsigned char>(*it);\n"
" if (c == '0') {}\n"
" else if ((c == 'a' || c == 'A')\n"
" || (c == 'b' || c == 'B')) {}\n"
" else {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #9711
check("int main(int argc, char* argv[]) {\n"
" int foo = 0;\n"
" struct option options[] = {\n"
" {\"foo\", no_argument, &foo, \'f\'},\n"
" {NULL, 0, NULL, 0},\n"
" };\n"
" getopt_long(argc, argv, \"f\", options, NULL);\n"
" if (foo) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// TODO: if (!v) is a known condition as well
check("struct a {\n"
" int *b();\n"
"};\n"
"bool g(a c, a* d) {\n"
" a *v, *e = v = &c;\n"
" if (!v)\n"
" return true;\n"
" int *f = v->b();\n"
" if (f)\n"
" v = nullptr;\n"
" if (v == nullptr && e) {}\n"
" return d;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:11]: (style) Condition 'e' is always true\n", errout_str());
// #10037
check("struct a {\n"
" int* p;\n"
"};\n"
"void g(a*);\n"
"void f() {\n"
" struct a b;\n"
" uint32_t p = (uint32_t) -1;\n"
" b.p = (void *) &p;\n"
" int r = g(&b);\n"
" if (r == 0)\n"
" if (p != (uint32_t) -1) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #9890
check("int g(int);\n"
"bool h(int*);\n"
"int f(int *x) {\n"
" int y = g(0);\n"
" if (!y) {\n"
" if (h(x)) {\n"
" y = g(1);\n"
" if (y) {}\n"
" return 0;\n"
" }\n"
" if (!y) {}\n"
" }\n"
" return 0;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:11]: (style) Condition '!y' is always true\n", errout_str());
// #10134
check("bool foo(bool b);\n"
"bool thud(const std::vector<std::wstring>& Arr, const std::wstring& Str) {\n"
" if (Arr.empty() && Str.empty())\n"
" return false;\n"
" bool OldFormat = Arr.empty() && !Str.empty();\n"
" if (OldFormat)\n"
" return foo(OldFormat);\n"
" return false;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #10208
check("bool GetFirst(std::string &first);\n"
"bool GetNext(std::string &next);\n"
"void g(const std::string& name);\n"
"void f() {\n"
" for (std::string name; name.empty() ? GetFirst(name) : GetNext(name);)\n"
" g(name);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("bool GetFirst(std::string &first);\n"
"bool GetNext(std::string &next);\n"
"void g(const std::string& name);\n"
"void f() {\n"
" for (std::string name{}; name.empty() ? GetFirst(name) : GetNext(name);)\n"
" g(name);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("bool GetFirst(std::string &first);\n"
"bool GetNext(std::string &next);\n"
"void g(const std::string& name);\n"
"void f() {\n"
" for (std::string name{'a', 'b'}; name.empty() ? GetFirst(name) : GetNext(name);)\n"
" g(name);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("bool GetFirst(const std::string &first);\n"
"bool GetNext(const std::string &next);\n"
"void g(const std::string& name);\n"
"void f() {\n"
" for (std::string name; name.empty() ? GetFirst(name) : GetNext(name);)\n"
" g(name);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5]: (style) Condition 'name.empty()' is always true\n", errout_str());
// #10278
check("void foo(unsigned int x) {\n"
" if ((100 - x) > 0) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #10298
check("void foo(unsigned int x) {\n"
" if (x == -1) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #10121
check("struct AB {\n"
" int a;\n"
"};\n"
"struct ABC {\n"
" AB* ab;\n"
"};\n"
"void g(ABC*);\n"
"int f(struct ABC *abc) {\n"
" int err = 0;\n"
" AB *ab = abc->ab;\n"
" if (ab->a == 123){\n"
" g(abc);\n"
" if (ab->a != 123) {\n"
" err = 1;\n"
" }\n"
" }\n"
" return err;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #10323
check("void foo(int x) {\n"
" if(x)\n"
" if(x == 1) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void foo(int x) {\n"
" if(x) {}\n"
" else\n"
" if(x == 1) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:4]: (style) Condition 'x==1' is always false\n", errout_str());
// do not report both unsignedLessThanZero and knownConditionTrueFalse
check("void foo(unsigned int max) {\n"
" unsigned int num = max - 1;\n"
" if (num < 0) {}\n" // <- do not report knownConditionTrueFalse
"}");
ASSERT_EQUALS("", errout_str());
// #10297
check("void foo(size_t len, int start) {\n"
" if (start < 0) {\n"
" start = len+start;\n"
" if (start < 0) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #10362
check("int tok;\n"
"void next();\n"
"void parse_attribute() {\n"
" if (tok == '(') {\n"
" int parenthesis = 0;\n"
" do {\n"
" if (tok == '(')\n"
" parenthesis++;\n"
" else if (tok == ')')\n"
" parenthesis--;\n"
" next();\n"
" } while (parenthesis && tok != -1);\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #7843
check("void f(int i) {\n"
" if(abs(i) == -1) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Condition 'abs(i)==-1' is always false\n", errout_str());
// #7844
check("void f(int i) {\n"
" if(i > 0 && abs(i) == i) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Condition 'abs(i)==i' is always true\n", errout_str());
check("void f(int i) {\n"
" if(i < 0 && abs(i) == i) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:2]: (style) Condition 'abs(i)==i' is always false\n", errout_str());
check("void f(int i) {\n"
" if(i > -3 && abs(i) == i) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #9948
check("bool f(bool a, bool b) {\n"
" return a || ! b || ! a;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:2]: (style) Return value '!a' is always true\n", errout_str());
// #10148
check("void f(int i) {\n"
" if (i >= 64) {}\n"
" else if (i >= 32) {\n"
" i &= 31;\n"
" if (i == 0) {}\n"
" else {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #10548
check("void f() {\n"
" int i = 0;\n"
" do {} while (i++ == 0);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #10582
check("static void fun(message_t *message) {\n"
" if (message->length >= 1) {\n"
" switch (data[0]) {}\n"
" }\n"
" uint8_t d0 = message->length > 0 ? data[0] : 0xff;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #8266
check("void f(bool b) {\n"
" if (b)\n"
" return;\n"
" if (g(&b) || b)\n"
" return;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #9720
check("bool bar(int &);\n"
"void f(int a, int b) {\n"
" if (a + b == 3)\n"
" return;\n"
" if (bar(a) && (a + b == 3)) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #10437
check("void f() {\n"
" Obj* PObj = nullptr;\n"
" bool b = false;\n"
" if (GetObj(PObj) && PObj != nullptr)\n"
" b = true;\n"
" if (b) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #10223
check("static volatile sig_atomic_t is_running;\n"
"static void handler(int signum) {\n"
" is_running = 0;\n"
"}\n"
"void f() {\n"
" signal(SIGINT, &handler);\n"
" is_running = 1;\n"
" while (is_running) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #10659
check("auto func(const std::tuple<int, int>& t) {\n"
" auto& [foo, bar] = t;\n"
" std::cout << foo << bar << std::endl;\n"
" return foo < bar;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #10484
check("void f() {\n"
" static bool init = true;\n"
" if (init)\n"
" init = false;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:3]: (style) The statement 'if (init) init=false' is logically equivalent to 'init=false'.\n", errout_str());
check("void f() {\n"
" static bool init(true);\n"
" if (init)\n"
" init = false;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:3]: (style) The statement 'if (init) init=false' is logically equivalent to 'init=false'.\n", errout_str());
check("void f() {\n"
" static bool init{ true };\n"
" if (init)\n"
" init = false;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:3]: (style) The statement 'if (init) init=false' is logically equivalent to 'init=false'.\n", errout_str());
// #10248
check("void f() {\n"
" static int var(1);\n"
" if (var == 1) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" static int var{ 1 };\n"
" if (var == 1) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void Fun();\n"
"using Fn = void (*)();\n"
"void f() {\n"
" static Fn logger = nullptr;\n"
" if (logger == nullptr)\n"
" logger = Fun;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void Fun();\n"
"using Fn = void (*)();\n"
"void f() {\n"
" static Fn logger(nullptr);\n"
" if (logger == nullptr)\n"
" logger = Fun;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void Fun();\n"
"using Fn = void (*)();\n"
"void f() {\n"
" static Fn logger{ nullptr };\n"
" if (logger == nullptr)\n"
" logger = Fun;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void Fun();\n"
"typedef void (*Fn)();\n"
"void f() {\n"
" static Fn logger = nullptr;\n"
" if (logger == nullptr)\n"
" logger = Fun;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void Fun();\n"
"typedef void (*Fn)();\n"
"void f() {\n"
" static Fn logger(nullptr);\n"
" if (logger == nullptr)\n"
" logger = Fun;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void Fun();\n"
"typedef void (*Fn)();\n"
"void f() {\n"
" static Fn logger{ nullptr };\n"
" if (logger == nullptr)\n"
" logger = Fun;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #9256
check("bool f() {\n"
" bool b = false;\n"
" b = true;\n"
" return b;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #10702
check("struct Object {\n"
" int _count=0;\n"
" void increment() { ++_count;}\n"
" auto get() const { return _count; }\n"
"};\n"
"struct Modifier {\n"
"Object & _object;\n"
" explicit Modifier(Object & object) : _object(object) {}\n"
" void do_something() { _object.increment(); }\n"
"};\n"
"struct Foo {\n"
" Object _object;\n"
" void foo() {\n"
" Modifier mod(_object);\n"
" if (_object.get()>0)\n"
" return;\n"
" mod.do_something();\n"
" if (_object.get()>0)\n"
" return;\n"
" }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
check("struct Object {\n"
" int _count=0;\n"
" auto get() const;\n"
"};\n"
"struct Modifier {\n"
"Object & _object;\n"
" explicit Modifier(Object & object);\n"
" void do_something();\n"
"};\n"
"struct Foo {\n"
" Object _object;\n"
" void foo() {\n"
" Modifier mod(_object);\n"
" if (_object.get()>0)\n"
" return;\n"
" mod.do_something();\n"
" if (_object.get()>0)\n"
" return;\n"
" }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
check("void f(const uint32_t u) {\n"
" const uint32_t v = u < 4;\n"
" if (v) {\n"
" const uint32_t w = v < 2;\n"
" if (w) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (style) Condition 'v<2' is always true\n"
"[test.cpp:5]: (style) Condition 'w' is always true\n",
errout_str());
check("void f(double d) {\n" // #10792
" if (d != 0) {\n"
" int i = (int)d;\n"
" if (i == 0) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(double d) {\n"
" if (0 != d) {\n"
" int i = (int)d;\n"
" if (i == 0) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct A { double d; }\n"
"void f(A a) {\n"
" if (a.d != 0) {\n"
" int i = a.d;\n"
" if (i == 0) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" if(strlen(\"abc\") == 3) {;}\n"
" if(strlen(\"abc\") == 1) {;}\n"
" if(wcslen(L\"abc\") == 3) {;}\n"
" if(wcslen(L\"abc\") == 1) {;}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Condition 'strlen(\"abc\")==3' is always true\n"
"[test.cpp:3]: (style) Condition 'strlen(\"abc\")==1' is always false\n"
"[test.cpp:4]: (style) Condition 'wcslen(L\"abc\")==3' is always true\n"
"[test.cpp:5]: (style) Condition 'wcslen(L\"abc\")==1' is always false\n",
errout_str());
check("int foo(bool a, bool b) {\n"
" if(!a && b && (!a == !b))\n"
" return 1;\n"
" return 0;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:2]: (style) Condition '!a==!b' is always false\n", errout_str());
// #10454
check("struct S {\n"
" int f() const { return g() ? 0 : 1; }\n"
" bool g() const { return u == 18446744073709551615ULL; }\n"
" unsigned long long u{};\n"
"};\n");
ASSERT_EQUALS("", errout_str());
// #8358
check("void f(double d) { if ((d * 0) != 0) {} }");
ASSERT_EQUALS("", errout_str());
// #6870
check("struct S {\n"
" int* p;\n"
" void f() const;\n"
" int g();\n"
"};\n"
"void S::f() {\n"
" if ((p == NULL) || ((p) && (g() >= *p))) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:7]: (style) Condition 'p' is always true\n", errout_str());
// #10749
check("struct Interface {\n"
" virtual int method() = 0;\n"
"};\n"
"struct Child : Interface {\n"
" int method() override { return 0; }\n"
" auto foo() {\n"
" if (method() == 0)\n"
" return true;\n"
" else\n"
" return false;\n"
" }\n"
"};\n"
"struct GrandChild : Child {\n"
" int method() override { return 1; }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
// #6855
check("struct S { int i; };\n"
"void f(S& s) {\n"
" if (!(s.i > 0) && (s.i != 0))\n"
" s.i = 0;\n"
" else if (s.i < 0)\n"
" s.s = 0;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:5]: (style) Condition 's.i<0' is always false\n", errout_str());
// #6857
check("int bar(int i) { return i; }\n"
"void foo() {\n"
" if (bar(1) == 0 && bar(1) > 0) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) Condition 'bar(1)==0' is always false\n"
"[test.cpp:3]: (style) Condition 'bar(1)>0' is always true\n",
errout_str());
check("struct S { int bar(int i) const; };\n"
"void foo(const S& s) {\n"
" if (s.bar(1) == 0 && s.bar(1) > 0) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (warning) Logical conjunction always evaluates to false: s.bar(1) == 0 && s.bar(1) > 0.\n",
errout_str());
check("struct B {\n" // #10618
" void Modify();\n"
" static void Static();\n"
" virtual void CalledByModify();\n"
"};\n"
"struct D : B {\n"
" int i{};\n"
" void testV();\n"
" void testS();\n"
" void CalledByModify() override { i = 0; }\n"
"};\n"
"void D::testV() {\n"
" i = 1;\n"
" B::Modify();\n"
" if (i == 1) {}\n"
"}\n"
"void D::testS() {\n"
" i = 1;\n"
" B::Static();\n"
" if (i == 1) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:20]: (style) Condition 'i==1' is always true\n", errout_str());
check("typedef struct { bool x; } s_t;\n" // #8446
"unsigned f(bool a, bool b) {\n"
" s_t s;\n"
" const unsigned col = a ? (s.x = false) : (b = true);\n"
" if (!s.x) {}\n"
" return col;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct S {\n" // #11233
" static std::string m;\n"
" static void f() { m = \"abc\"; }\n"
" static void g() {\n"
" m.clear();\n"
" f();\n"
" if (m.empty()) {}\n"
" }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
// #11203
check("void f() {\n"
" int i = 10;\n"
" if(i > 9.9){}\n"
" float f = 9.9f;\n"
" if(f < 10) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) Condition 'i>9.9' is always true\n"
"[test.cpp:5]: (style) Condition 'f<10' is always true\n",
errout_str());
check("constexpr int f() {\n" // #11238
" return 1;\n"
"}\n"
"constexpr bool g() {\n"
" return f() == 1;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("int g() { return -1; }\n"
"void f() {\n"
" if (g() == 1 && g() == -1) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) Condition 'g()==1' is always false\n"
"[test.cpp:3]: (style) Condition 'g()==-1' is always true\n",
errout_str());
// #9817
check("void f(float x) {\n"
" if (x <= 0) {}\n"
" else if (x < 1) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #10426
check("int f() {\n"
" std::string s;\n"
" for (; !s.empty();) {}\n"
" for (; s.empty();) {}\n"
" if (s.empty()) {}\n"
" if ((bool)0) {}\n"
" return s.empty();"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) Condition '!s.empty()' is always false\n"
"[test.cpp:4]: (style) Condition 's.empty()' is always true\n"
"[test.cpp:5]: (style) Condition 's.empty()' is always true\n"
"[test.cpp:6]: (style) Condition '(bool)0' is always false\n"
"[test.cpp:7]: (style) Return value 's.empty()' is always true\n",
errout_str());
check("int f(bool b) {\n"
" if (b) return static_cast<int>(1);\n"
" return (int)0;\n"
"}\n"
"bool g(bool b) {\n"
" if (b) return static_cast<int>(1);\n"
" return (int)0;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:6]: (style) Return value 'static_cast<int>(1)' is always true\n"
"[test.cpp:7]: (style) Return value '(int)0' is always false\n",
errout_str());
check("int f() { return 3; }\n"
"int g() { return f(); }\n"
"int h() { if (f()) {} }\n"
"int i() { return f() == 3; }\n");
ASSERT_EQUALS("[test.cpp:3]: (style) Condition 'f()' is always true\n"
"[test.cpp:4]: (style) Return value 'f()==3' is always true\n",
errout_str());
check("int f() {\n"
" const char *n;\n"
" return((n=42) &&\n"
" *n == 'A');\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(std::istringstream& i) {\n" // #9327
" std::string s;\n"
" if (!(i >> s))\n"
" return;\n"
" if (!(i >> s))\n"
" return;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #11227
check("struct S {\n"
" int get();\n"
"};\n"
"void f(const S* s) {\n"
" if (!s)\n"
" return;\n"
" g(s ? s->get() : 0);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:7]: (style) Condition 's' is always true\n", errout_str());
check("void f(const char* o) {\n" // #11558
" if (!o || !o[0])\n"
" return;\n"
" if (o[0] == '-' && o[1]) {\n"
" if (o[1] == '-') {}\n"
" if (o[1] == '\\0') {}\n"
" }\n"
"}\n");
if (std::numeric_limits<char>::is_signed) {
ASSERT_EQUALS("[test.cpp:6]: (style) Condition 'o[1]=='\\0'' is always false\n", errout_str());
} else {
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:6]: (style) Condition 'o[1]=='\\0'' is always false\n", errout_str());
}
check("void f(int x) {\n" // #11449
" int i = x;\n"
" i = (std::min)(i, 1);\n"
" if (i == 1) {}\n"
" int j = x;\n"
" j = (::std::min)(j, 1);\n"
" if (j == 1) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void h(int);\n" // #11679
"bool g(int a) { h(a); return false; }\n"
"bool f(int i) {\n"
" return g(i);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(std::string a) {\n" // #11051
" a = \"x\";\n"
" if (a == \"x\") {}\n"
" return a;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) Condition 'a==\"x\"' is always true\n", errout_str());
check("void g(bool);\n"
"void f() {\n"
" int i = 5;\n"
" int* p = &i;\n"
" g(i == 7);\n"
" g(p == nullptr);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5]: (style) Condition 'i==7' is always false\n"
"[test.cpp:6]: (style) Condition 'p==nullptr' is always false\n",
errout_str());
check("enum E { E0, E1 };\n"
"void f() {\n"
" static_assert(static_cast<int>(E::E1) == 1);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct a {\n"
" bool g();\n"
" int h();\n"
"};\n"
"void f(a c, int d, int e) {\n"
" if (c.g() && c.h()) {}\n"
" else {\n"
" bool u = false;\n"
" if (d && e)\n"
" u = true;\n"
" if (u) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("int f(int i) {\n" // #11741
" i = -i - 1;\n"
" if (i < 0 || i >= 20)\n"
" return 0;\n"
" return 1;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("namespace S { int s{}; };\n" // #11046
"void f(bool b) {\n"
" if (S::s) {\n"
" if (b) {\n"
" if (S::s) {}\n"
" }\n"
" }\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5]: (style) Condition 'S::s' is always true\n", errout_str());
check("void f() {\n" // #10811
" int i = 0;\n"
" if ((i = g(), 1) != 0) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) Condition '(i=g(),1)!=0' is always true\n", errout_str());
check("void f(unsigned i) {\n"
" const int a[2] = {};\n"
" const int* q = a + i;\n"
" if (q) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (style) Condition 'q' is always true\n", errout_str());
check("void f() {\n" // #12786
" const int b[2] = {};\n"
" if (b) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) Condition 'b' is always true\n", errout_str());
check("void f(int i) {\n"
" int j = 0;\n"
" switch (i) {\n"
" case 1:\n"
" j = 0;\n"
" break;\n"
" default:\n"
" j = 1;\n"
" }\n"
" if (j != 0) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" const char *s1 = foo();\n"
" const char *s2 = bar();\n"
" if (s2 == NULL)\n"
" return;\n"
" size_t len = s2 - s1;\n"
" if (len == 0)\n"
" return;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("int h();\n" // #12858
"bool g() {\n"
" bool b{};\n"
" try {\n"
" int x = h();\n"
" switch (x) {\n"
" default:\n"
" b = true;\n"
" }\n"
" }\n"
" catch (...) {\n"
" b = false;\n"
" }\n"
" return b;\n"
"}\n"
"void f() {\n"
" if (g()) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("int f(int x, int y) {\n" // #11822
" if (x) {\n"
" switch (y) {\n"
" case 1:\n"
" return 7;\n"
" }\n"
" }\n"
" \n"
" if (y)\n"
" return 8;\n"
" \n"
" if (x)\n"
" return 9;\n"
" \n"
" return 0;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void alwaysTrueSymbolic()
{
check("void f(const uint32_t x) {\n"
" uint32_t y[1];\n"
" y[0]=x;\n"
" if(x > 0 || y[0] < 42){}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:4]: (style) Condition 'y[0]<42' is always true\n", errout_str());
check("void f(int x, int y) {\n"
" if(x < y && x < 42) {\n"
" --x;\n"
" if(x == y) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:4]: (style) Condition 'x==y' is always false\n", errout_str());
check("void f(bool a, bool b) { if (a == b && a && !b){} }");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:1]: (style) Condition '!b' is always false\n", errout_str());
check("bool f(bool a, bool b) { if(a && b && (!a)){} }");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:1]: (style) Condition '!a' is always false\n", errout_str());
check("void f(int x, int y) {\n"
" if (x < y) {\n"
" auto z = y - x;\n"
" if (z < 1) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:4]: (style) Condition 'z<1' is always false\n", errout_str());
check("bool f(int &index, const int s, const double * const array, double & x) {\n"
" if (index >= s)\n"
" return false;\n"
" else {\n"
" x = array[index];\n"
" return (index++) >= s;\n"
" }\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:6]: (style) Return value '(index++)>=s' is always false\n", errout_str());
check("struct a {\n"
" a *b() const;\n"
"} c;\n"
"void d() {\n"
" a *e = nullptr;\n"
" e = c.b();\n"
" if (e) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("int g(int i) {\n"
" if (i < 256)\n"
" return 1;\n"
" const int N = 2 * i;\n"
" i -= 256;\n"
" if (i == 0)\n"
" return 0;\n"
" return N;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(int i, int j) {\n"
" if (i < j) {\n"
" i++;\n"
" if (i >= j)\n"
" return;\n"
" i++;\n"
" if (i >= j) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("int get_delta() {\n"
" clock_t now_ms = (clock() / (CLOCKS_PER_SEC / 1000));\n"
" static clock_t last_clock_ms = now_ms;\n"
" clock_t delta = now_ms - last_clock_ms;\n"
" last_clock_ms = now_ms;\n"
" if (delta > 50)\n"
" delta = 50;\n"
" return delta;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #10555
check("struct C {\n"
" int GetI() const { return i; }\n"
" int i{};\n"
"};\n"
"struct B {\n"
" C *m_PC{};\n"
" Modify();\n"
"};\n"
"struct D : B {\n"
" void test(); \n"
"};\n"
"void D::test() {\n"
" const int I = m_PC->GetI();\n"
" Modify();\n"
" if (m_PC->GetI() != I) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #10624
check("struct Data {\n"
" Base* PBase{};\n"
"};\n"
"void f(Data* BaseData) {\n"
" Base* PObj = BaseData->PBase;\n"
" if (PObj == nullptr)\n"
" return;\n"
" Derived* pD = dynamic_cast<Derived*>(PObj);\n"
" if (pD) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #9549
check("void f(const uint32_t v) {\n"
" const uint32_t v16 = v >> 16;\n"
" if (v16) {\n"
" const uint32_t v8 = v16 >> 8;\n"
" if (v8) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #10649
check("void foo(struct diag_msg *msg) {\n"
" msg = msg->next;\n"
" if (msg == NULL)\n"
" return CMD_OK;\n"
" msg = msg->next;\n"
" if (msg == NULL)\n"
" return CMD_OK;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("int foo(bool a, bool b) {\n"
" if((!a == !b) && !a && b)\n"
" return 1;\n"
" return 0;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:2]: (style) Condition 'b' is always false\n", errout_str());
// #11124
check("struct Basket {\n"
" std::vector<int> getApples() const;\n"
" std::vector<int> getBananas() const; \n"
"};\n"
"int getFruit(const Basket & b, bool preferApples)\n"
"{\n"
" std::vector<int> apples = b.getApples();\n"
" int apple = apples.empty() ? -1 : apples.front();\n"
" std::vector<int> bananas = b.getBananas();\n"
" int banana = bananas.empty() ? -1 : bananas.front();\n"
" int fruit = std::max(apple, banana);\n"
" if (fruit == -1)\n"
" return fruit;\n"
" if (std::min(apple, banana) != -1)\n"
" fruit = preferApples ? apple : banana;\n"
" return fruit;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(const std::string & s, int i) {\n"
" const char c = s[i];\n"
" if (!std::isalnum(c)) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct S {\n" // #11404
" int f() const;\n"
" void g();\n"
"};\n"
"void h(std::vector<S*>::iterator it) {\n"
" auto i = (*it)->f();\n"
" (*it)->g();\n"
" auto j = (*it)->f();\n"
" if (i == j) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #11384
check("bool f(const int* it, const int* end) {\n"
" return (it != end) && *it++ &&\n"
" (it != end) && *it;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #12116
check("void f(int n) {\n"
" for (int i = 0; i < N; ++i) {\n"
" if (i < n) {}\n"
" else if (i > n) {}\n"
" else {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #12681
check("void f(unsigned u) {\n"
" if (u > 0) {\n"
" u--;\n"
" if (u == 0) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(unsigned u) {\n"
" if (u < 0xFFFFFFFF) {\n"
" u++;\n"
" if (u == 0xFFFFFFFF) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(bool a, bool b) {\n" // #12937
" bool c = !a && b;\n"
" if (a) {}\n"
" else {\n"
" if (c) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void alwaysTrueInfer() {
check("void f(int x) {\n"
" if (x > 5) {\n"
" x++;\n"
" if (x == 1) {}\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:4]: (style) Condition 'x==1' is always false\n", errout_str());
check("void f(int x) {\n"
" if (x > 5) {\n"
" x++;\n"
" if (x != 1) {}\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:4]: (style) Condition 'x!=1' is always true\n", errout_str());
// #6890
check("void f(int i) {\n"
" int x = i;\n"
" if (x >= 1) {}\n"
" else {\n"
" x = 8 - x;\n"
" if (x == -1) {}\n"
" else {}\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:6]: (style) Condition 'x==-1' is always false\n", errout_str());
check("void f(int i) {\n"
" int x = i;\n"
" if (x >= 1) {}\n"
" else {\n"
" x = 8 - x;\n"
" if (x != -1) {}\n"
" else {}\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:6]: (style) Condition 'x!=-1' is always true\n", errout_str());
check("void f(int i) {\n"
" int x = i;\n"
" if (x >= 1) {}\n"
" else {\n"
" x = 8 - x;\n"
" if (x >= -1) {}\n"
" else {}\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:6]: (style) Condition 'x>=-1' is always true\n", errout_str());
check("void f(int i) {\n"
" int x = i;\n"
" if (x >= 1) {}\n"
" else {\n"
" x = 8 - x;\n"
" if (x > -1) {}\n"
" else {}\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:6]: (style) Condition 'x>-1' is always true\n", errout_str());
check("void f(int i) {\n"
" int x = i;\n"
" if (x >= 1) {}\n"
" else {\n"
" x = 8 - x;\n"
" if (x < -1) {}\n"
" else {}\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:6]: (style) Condition 'x<-1' is always false\n", errout_str());
check("void f(int i) {\n"
" int x = i;\n"
" if (x >= 1) {}\n"
" else {\n"
" x = 8 - x;\n"
" if (x <= -1) {}\n"
" else {}\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:6]: (style) Condition 'x<=-1' is always false\n", errout_str());
check("void f(int i) {\n"
" int x = i;\n"
" if (x >= 1) {}\n"
" else {\n"
" x = 8 - x;\n"
" if (x > 7) {}\n"
" else {}\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:6]: (style) Condition 'x>7' is always true\n", errout_str());
check("void f(int i) {\n"
" int x = i;\n"
" if (x >= 1) {}\n"
" else {\n"
" x = 8 - x;\n"
" if (x > 9) {}\n"
" else {}\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int i) {\n"
" int x = i;\n"
" if (x >= 1) {}\n"
" else {\n"
" x = 8 - x;\n"
" if (x > 10) {}\n"
" else {}\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
// #11100
check("struct T {\n"
" bool m{};\n"
" void f(bool b);\n"
" bool get() const { return m; }\n"
" void set(bool v) { m = v; }\n"
"};\n"
"void T::f(bool b) {\n"
" bool tmp = get();\n"
" set(b);\n"
" if (tmp != get()) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #9541
check("int f(int pos, int a) {\n"
" if (pos <= 0)\n"
" pos = 0;\n"
" else if (pos < a)\n"
" if(pos > 0)\n"
" --pos;\n"
" return pos;\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:5]: (style) Condition 'pos>0' is always true\n", errout_str());
// #9721
check("void f(int x) {\n"
" if (x > 127) {\n"
" if ( (x>255) || (-128>x) )\n"
" return;\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) Condition '-128>x' is always false\n", errout_str());
// #8778
check("void f() {\n"
" for(int i = 0; i < 19; ++i)\n"
" if(i<=18) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (style) Condition 'i<=18' is always true\n", errout_str());
// #8209
check("void f() {\n"
" for(int x = 0; x < 3; ++x)\n"
" if(x == -5) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Condition 'x==-5' is always false\n", errout_str());
// #8407
check("int f(void) {\n"
" for(int i = 0; i <1; ++i)\n"
" if(i == 0) return 1; \n" // <<
" else return 0;\n"
" return -1;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Condition 'i==0' is always true\n", errout_str());
check("void f(unsigned int u1, unsigned int u2) {\n"
" if (u1 <= 10 && u2 >= 20) {\n"
" if (u1 != u2) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) Condition 'u1!=u2' is always true\n", errout_str());
// #10544
check("void f(int N) {\n"
" if (N > 0) {\n"
" while (N)\n"
" N = test();\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #11098
check("void f(unsigned int x) { if (x == -1u) {} }\n");
ASSERT_EQUALS("", errout_str());
check("bool f(const int *p, const int *q) {\n"
" return p != NULL && q != NULL && p == NULL;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Return value 'p==NULL' is always false\n", errout_str());
check("struct S {\n" // #11789
" std::vector<int> v;\n"
" void f(int i) const;\n"
"};\n"
"void S::f(int i) const {\n"
" int j = i - v.size();\n"
" if (j >= 0) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(int i) {\n" // #12039
" if ((128 + i < 255 ? 128 + i : 255) > 0) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct S {\n" // #12727
" bool f() const {\n"
" return g() > 0;\n"
" }\n"
" std::size_t g() const {\n"
" return 5 - h();\n"
" }\n"
" std::size_t h() const {\n"
" if (x > 7)\n"
" return 5;\n"
" return (5 + x) % 5;\n"
" }\n"
" std::size_t x;\n"
"};\n");
ASSERT_EQUALS("", errout_str());
}
void alwaysTrueContainer() {
// #9329
check("void c1(std::vector<double>&);\n"
"void c2(std::vector<double>&);\n"
"void foo(int flag) {\n"
" std::vector<double> g;\n"
" if (flag)\n"
" c1(g );\n"
" else\n"
" c2(g );\n"
" if ( !g.empty() )\n"
" return;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void foo(int flag) {\n"
" std::vector<double> g;\n"
" if (flag)\n"
" c1(g );\n"
" else\n"
" c2(g );\n"
" if ( !g.empty() )\n"
" return;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct A {\n"
" std::vector<int> v;\n"
" void g();\n"
" void f(bool b) {\n"
" v.clear();\n"
" g();\n"
" return !v.empty();\n"
" }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
// #10409
check("void foo(const std::string& s) {\n"
" if( s.size() < 2 ) return;\n"
" if( s == \"ab\" ) return;\n"
" if( s.size() < 3 ) return;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void foo(const std::string& s) {\n"
" if( s.size() < 2 ) return;\n"
" if( s != \"ab\" )\n"
" if( s.size() < 3 ) return;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #10226
check("int f(std::vector<int>::iterator it, const std::vector<int>& vector) {\n"
" if (!(it != vector.end() && it != vector.begin()))\n"
" throw 0;\n"
" if (it != vector.end() && *it == 0)\n"
" return -1;\n"
" return *it;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (style) Condition 'it!=vector.end()' is always true\n", errout_str());
// #11303
check("void f(int n) {\n"
" std::vector<char> buffer(n);\n"
" if(buffer.back() == 0 ||\n"
" buffer.back() == '\\n' ||\n"
" buffer.back() == '\\0') {}\n"
"}\n");
if (std::numeric_limits<char>::is_signed) {
ASSERT_EQUALS("[test.cpp:5]: (style) Condition 'buffer.back()=='\\0'' is always false\n", errout_str());
} else {
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:5]: (style) Condition 'buffer.back()=='\\0'' is always false\n", errout_str());
}
// #9353
check("struct X { std::string s; };\n"
"void f(const std::vector<X>&v) {\n"
" for (std::vector<X>::const_iterator it = v.begin(); it != v.end(); ++it)\n"
" if (!it->s.empty()) {\n"
" if (!it->s.empty()) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:5]: (style) Condition '!it->s.empty()' is always true\n", errout_str());
check("struct X { std::string s; };\n"
"void f(const std::vector<struct X>&v) {\n"
" for (std::vector<struct X>::const_iterator it = v.begin(); it != v.end(); ++it)\n"
" if (!it->s.empty()) {\n"
" if (!it->s.empty()) {}\n"
" }\n"
"}\n");
TODO_ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:5]: (style) Condition '!it->s.empty()' is always true\n", "", errout_str());
// #10508
check("bool f(const std::string& a, const std::string& b) {\n"
" return a.empty() || (b.empty() && a.empty());\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:2]: (style) Return value 'a.empty()' is always false\n", errout_str());
check("struct A {\n"
" struct iterator;\n"
" iterator begin() const;\n"
" iterator end() const;\n"
"};\n"
"A g();\n"
"void f(bool b) {\n"
" std::set<int> s;\n"
" auto v = g();\n"
" s.insert(v.begin(), v.end());\n"
" if(!b && s.size() != 1)\n"
" return;\n"
" if(!s.empty()) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("int f(std::string s) {\n"
" if (s.empty())\n"
" return -1;\n"
" s += '\\n';\n"
" if (s.empty())\n"
" return -1;\n"
" return -1;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5]: (style) Condition 's.empty()' is always false\n", errout_str());
check("void f(std::string& p) {\n"
" const std::string d{ \"abc\" };\n"
" p += d;\n"
" if(p.empty()) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (style) Condition 'p.empty()' is always false\n", errout_str());
check("bool f(int i, FILE* fp) {\n"
" std::string s = \"abc\";\n"
" s += std::to_string(i);\n"
" s += \"\\n\";\n"
" return fwrite(s.c_str(), 1, s.length(), fp) == s.length();\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(const std::string& s) {\n" // #9148
" if (s.empty() || s.size() < 1) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:2]: (style) Condition 's.size()<1' is always false\n", errout_str());
check("void bar(std::vector<int>& vv) {\n" // #11464
" class F {\n"
" public:\n"
" F(int, std::vector<int>& lv) : mV(lv) {\n"
" mV.push_back(0);\n"
" }\n"
" private:\n"
" std::vector<int>& mV;\n"
" } fi(1, vv);\n"
"}\n"
"void g() {\n"
" std::vector<int> v;\n"
" bar(v);\n"
" if (v.empty()) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct F {\n"
" F(int, std::vector<int>&lv) : mV(lv) {\n"
" mV.push_back(0);\n"
" }\n"
" std::vector<int>& mV;\n"
"};\n"
"void g(std::vector<int>& vv) {\n"
" F(1, vv);\n"
"}\n"
"void f() {\n"
" std::vector<int> v;\n"
" g(v);\n"
" if (v.empty()) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void alwaysTrueLoop()
{
check("long foo() {\n"
" bool bUpdated = false;\n"
" long Ret{};\n"
" do {\n"
" Ret = bar();\n"
" if (Ret == 0) {\n"
" if (bUpdated)\n"
" return 1;\n"
" bUpdated = true;\n"
" }\n"
" else\n"
" bUpdated = false;\n"
" }\n"
" while (bUpdated);\n"
" return Ret;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("bool foo() {\n"
" bool bFirst = true;\n"
" do {\n"
" if (bFirst)\n"
" bar();\n"
" if (baz())\n"
" break; \n"
" bFirst = false;\n"
" } while (true);\n"
" return bFirst;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" void * pool = NULL;\n"
" do {\n"
" pool = malloc(40);\n"
" if (dostuff())\n"
" break;\n"
" pool = NULL;\n"
" }\n"
" while (0);\n"
" if (pool) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// #8499
check("void f(void)\n"
"{\n"
" for (int i = 0; i < 2; ++i)\n"
" {\n"
" for (int j = 0; j < 8; ++j)\n"
" {\n"
" if ( (i==0|| i==1)\n" // << always true
" && (j==0) )\n"
" {;}\n"
" }\n"
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:7] -> [test.cpp:7]: (style) Condition 'i==1' is always true\n", errout_str());
// #10863
check("void f(const int A[], int Len) {\n"
" if (Len <= 0)\n"
" return;\n"
" int I = 0;\n"
" while (I < Len) {\n"
" int K = I + 1;\n"
" for (; K < Len; K++) {\n"
" if (A[I] != A[K])\n"
" break;\n"
" } \n"
" I = K; \n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f() {\n" // #11434
" const int N = 5;\n"
" bool a[N];\n"
" for (int i = 0; i < N; a[i++] = false);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f() {\n" // #8192
" for (int i = 0; i > 10; ++i) {}\n"
"}\n");
TODO_ASSERT_EQUALS("[test.cpp:2]: (style) Condition 'i>10' is always false\n", "", errout_str());
check("void f() {\n"
" for (int i = 1000; i < 20; ++i) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Condition 'i<20' is always false\n", errout_str());
check("int foo(int foo, int bar, bool baz, bool flag) {\n"
" if (baz && flag) {\n"
" do {\n"
" if (bar==42)\n"
" return 0;\n"
" } while (flag);\n"
" }\n"
" return foo;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:6]: (style) Condition 'flag' is always true\n", errout_str());
}
void alwaysTrueTryCatch()
{
check("void g();\n"
"void f(int x)\n"
"{\n"
" if( x ) {\n"
" try {\n"
" g();\n"
" }\n"
" catch(...) {\n"
" return;\n"
" }\n"
" }\n"
" g();\n"
" if( x ) {\n"
" g();\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void g();\n"
"void h();\n"
"void f(int x) {\n"
" if( x ) {\n"
" try {\n"
" g();\n"
" return;\n"
" }\n"
" catch( ... ) {}\n"
" }\n"
" h();\n"
" if( x ) {\n"
" g();\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f() {\n" // #10701
" std::string s;\n"
" try {\n"
" try {\n"
" s = g();\n"
" }\n"
" catch (const Err& err) {}\n"
" }\n"
" catch (const std::exception& e) {}\n"
" if (s != \"abc\") {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void multiConditionAlwaysTrue() {
check("void f() {\n"
" int val = 0;\n"
" if (val < 0) continue;\n"
" if (val > 0) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int val = 0;\n"
" if (val < 0) {\n"
" if (val > 0) {}\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int val = 0;\n"
" if (val < 0) {\n"
" if (val < 0) {}\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int activate = 0;\n"
" int foo = 0;\n"
" if (activate) {}\n"
" else if (foo) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Condition 'activate' is always false\n"
"[test.cpp:5]: (style) Condition 'foo' is always false\n", errout_str());
// #6904
check("void f() {\n"
" const int b[2] = { 1,0 };\n"
" if(b[1] == 2) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Condition 'b[1]==2' is always false\n", errout_str());
// #9878
check("void f(bool a, bool b) {\n"
" if (a && b){;}\n"
" else if (!a && b){;}\n"
" else if (!a && !b){;}\n"
" else {;}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void duplicateCondition() {
check("void f(bool x) {\n"
" if(x) {}\n"
" if(x) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) The if condition is the same as the previous if condition\n",
errout_str());
check("void f(int x) {\n"
" if(x == 1) {}\n"
" if(x == 1) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) The if condition is the same as the previous if condition\n",
errout_str());
check("void f(int x) {\n"
" if(x == 1) {}\n"
" if(x == 2) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
" if(x == 1) {}\n"
" if(x != 1) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(bool x) {\n"
" if(x) {}\n"
" g();\n"
" if(x) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
" if(x == 1) { x++; }\n"
" if(x == 1) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
// #8996
check("void g(int** v);\n"
"void f() {\n"
" int a = 0;\n"
" int b = 0;\n"
" int* d[] = {&a, &b};\n"
" g(d);\n"
" if (a) {}\n"
" if (b) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
// #9311
check("struct c {\n"
" int* p;\n"
"};\n"
"void g(struct c* v);\n"
"void f() {\n"
" int a = 0;\n"
" int b = 0;\n"
" struct c d[] = {{&a}, {&b}};\n"
" g(d);\n"
" if (a) {}\n"
" if (b) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
// #8993
check("void f(const std::string& x) {\n"
" auto y = x;\n"
" if (x.empty()) y = \"1\";\n"
" if (y.empty()) return;\n"
"}");
ASSERT_EQUALS("", errout_str());
// #9106
check("struct A {int b;};\n"
"void f(A a, int c) {\n"
" if (a.b) a.b = c;\n"
" if (a.b) {}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct A {\n"
" int a;\n"
" void b() const {\n"
" return a == 1;\n"
" }\n"
" void c();\n"
" void d() {\n"
" if(b()) {\n"
" c();\n"
" }\n"
" if (b()) {\n"
" a = 3;\n"
" }\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct A {\n"
" int a;\n"
" void b() const {\n"
" return a == 1;\n"
" }\n"
" void d() {\n"
" if(b()) {\n"
" a = 2;\n"
" }\n"
" if (b()) {\n"
" a = 3;\n"
" }\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct A {\n"
" int a;\n"
" void b() const {\n"
" return a == 1;\n"
" }\n"
" void d() {\n"
" if(b()) {\n"
" }\n"
" if (b()) {\n"
" a = 3;\n"
" }\n"
" }\n"
"}\n");
ASSERT_EQUALS("[test.cpp:7] -> [test.cpp:9]: (style) The if condition is the same as the previous if condition\n",
errout_str());
check("void f(bool a, bool b) {\n"
" auto g = [&] { b = !a; };\n"
" if (b)\n"
" g();\n"
" if (b) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void g(bool& a);\n"
"void f(bool b) {\n"
" auto h = std::bind(&g, std::ref(b));\n"
" if (b)\n"
" h();\n"
" if (b) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(int *i) {\n"
" if (*i == 0) {\n"
" *i = 1;\n"
" }\n"
" if (*i == 0) {\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void g(std::function<void()>);\n"
"void f(std::vector<int> v) {\n"
" auto x = [&v] { v.push_back(1); };\n"
" if(v.empty()) {\n"
" g(x);\n"
" }\n"
" if(v.empty())\n"
" return;\n"
" return;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct S { int i; };\n"
"int f(const S& s) {\n"
" int a = 0, b = 0;\n"
" if (s.i == 0)\n"
" a = 1;\n"
" if (s.i == 0)\n"
" b = 1;\n"
" return a + b;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:6]: (style) The if condition is the same as the previous if condition\n", errout_str());
check("void f(double d) {\n" // #12712
" if (std::isfinite(d)) {}\n"
" if (std::isfinite(d)) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) The if condition is the same as the previous if condition\n", errout_str());
check("struct S { int x; };\n" // #12391
"int f(const struct S* a, const struct S* b) {\n"
" const struct S* p = b;\n"
" if (a->x < p->x) p++;\n"
" if (a->x < p->x) p++;\n"
" return p->x;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
// do not crash
check("void assign(const MMA& other) {\n"
" if (mPA.cols != other.mPA.cols || mPA.rows != other.mPA.rows)\n"
" ;\n"
" if (other.mPA.cols > 0 && other.mPA.rows > 0)\n"
" ;\n"
"}");
}
void checkInvalidTestForOverflow() {
check("void f(char *p, unsigned int x) {\n"
" assert((p + x) < p);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Invalid test for overflow '(p+x)<p'; pointer overflow is undefined behavior. Some mainstream compilers remove such overflow tests when optimising the code and assume it's always false.\n", errout_str());
check("void f(char *p, unsigned int x) {\n"
" assert((p + x) >= p);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Invalid test for overflow '(p+x)>=p'; pointer overflow is undefined behavior. Some mainstream compilers remove such overflow tests when optimising the code and assume it's always true.\n", errout_str());
check("void f(char *p, unsigned int x) {\n"
" assert(p > (p + x));\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Invalid test for overflow 'p>(p+x)'; pointer overflow is undefined behavior. Some mainstream compilers remove such overflow tests when optimising the code and assume it's always false.\n", errout_str());
check("void f(char *p, unsigned int x) {\n"
" assert(p <= (p + x));\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Invalid test for overflow 'p<=(p+x)'; pointer overflow is undefined behavior. Some mainstream compilers remove such overflow tests when optimising the code and assume it's always true.\n", errout_str());
check("void f(signed int x) {\n" // unsigned overflow => don't warn
" assert(x + 100U < x);\n"
"}");
ASSERT_EQUALS("", errout_str());
// x + c < x
#define MSG(EXPR, RESULT) "[test.cpp:1]: (warning) Invalid test for overflow '" EXPR "'; signed integer overflow is undefined behavior. Some mainstream compilers remove such overflow tests when optimising the code and assume it's always " RESULT ".\n"
check("int f(int x) { return x + 10 > x; }");
ASSERT_EQUALS(MSG("x+10>x", "true"), errout_str());
check("int f(int x) { return x + 10 >= x; }");
ASSERT_EQUALS(MSG("x+10>=x", "true"), errout_str());
check("int f(int x) { return x + 10 < x; }");
ASSERT_EQUALS(MSG("x+10<x", "false"), errout_str());
check("int f(int x) { return x + 10 <= x; }");
ASSERT_EQUALS(MSG("x+10<=x", "false"), errout_str());
check("int f(int x) { return x - 10 > x; }");
ASSERT_EQUALS(MSG("x-10>x", "false"), errout_str());
check("int f(int x) { return x - 10 >= x; }");
ASSERT_EQUALS(MSG("x-10>=x", "false"), errout_str());
check("int f(int x) { return x - 10 < x; }");
ASSERT_EQUALS(MSG("x-10<x", "true"), errout_str());
check("int f(int x) { return x - 10 <= x; }");
ASSERT_EQUALS(MSG("x-10<=x", "true"), errout_str());
// x + y < x
#undef MSG
#define MSG(EXPR, RESULT) "[test.cpp:1]: (warning) Invalid test for overflow '" EXPR "'; signed integer overflow is undefined behavior. Some mainstream compilers removes handling of overflows when optimising the code and change the code to '" RESULT "'.\n"
check("int f(int x, int y) { return x + y < x; }");
ASSERT_EQUALS(MSG("x+y<x", "y<0"), errout_str());
check("int f(int x, int y) { return x + y <= x; }");
ASSERT_EQUALS(MSG("x+y<=x", "y<=0"), errout_str());
check("int f(int x, int y) { return x + y > x; }");
ASSERT_EQUALS(MSG("x+y>x", "y>0"), errout_str());
check("int f(int x, int y) { return x + y >= x; }");
ASSERT_EQUALS(MSG("x+y>=x", "y>=0"), errout_str());
// x - y < x
check("int f(int x, int y) { return x - y < x; }");
ASSERT_EQUALS(MSG("x-y<x", "y>0"), errout_str());
check("int f(int x, int y) { return x - y <= x; }");
ASSERT_EQUALS(MSG("x-y<=x", "y>=0"), errout_str());
check("int f(int x, int y) { return x - y > x; }");
ASSERT_EQUALS(MSG("x-y>x", "y<0"), errout_str());
check("int f(int x, int y) { return x - y >= x; }");
ASSERT_EQUALS(MSG("x-y>=x", "y<=0"), errout_str());
}
void checkConditionIsAlwaysTrueOrFalseInsideIfWhile() {
check("void f() {\n"
" enum states {A,B,C};\n"
" const unsigned g_flags = B|C;\n"
" if(g_flags & A) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) Condition 'g_flags&A' is always false\n", errout_str());
check("void f() {\n"
" int a = 5;"
" if(a) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Condition 'a' is always true\n", errout_str());
check("void f() {\n"
" int a = 5;"
" while(a + 1) { a--; }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" int a = 5;"
" while(a + 1) { return; }\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Condition 'a+1' is always true\n", errout_str());
}
void alwaysTrueFalseInLogicalOperators() {
check("bool f();\n"
"void foo() { bool x = true; if(x||f()) {}}");
ASSERT_EQUALS("[test.cpp:2]: (style) Condition 'x' is always true\n", errout_str());
check("void foo(bool b) { bool x = true; if(x||b) {}}");
ASSERT_EQUALS("[test.cpp:1]: (style) Condition 'x' is always true\n", errout_str());
check("void foo(bool b) { if(true||b) {}}");
ASSERT_EQUALS("", errout_str());
check("bool f();\n"
"void foo() { bool x = false; if(x||f()) {}}");
ASSERT_EQUALS("[test.cpp:2]: (style) Condition 'x' is always false\n", errout_str());
check("bool f();\n"
"void foo() { bool x = false; if(x&&f()) {}}");
ASSERT_EQUALS("[test.cpp:2]: (style) Condition 'x' is always false\n", errout_str());
check("void foo(bool b) { bool x = false; if(x&&b) {}}");
ASSERT_EQUALS("[test.cpp:1]: (style) Condition 'x' is always false\n", errout_str());
check("void foo(bool b) { if(false&&b) {}}");
ASSERT_EQUALS("", errout_str());
check("bool f();\n"
"void foo() { bool x = true; if(x&&f()) {}}");
ASSERT_EQUALS("[test.cpp:2]: (style) Condition 'x' is always true\n", errout_str());
// #9578
check("bool f(const std::string &s) {\n"
" return s.size()>2U && s[0]=='4' && s[0]=='2';\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:2]: (style) Return value 's[0]=='2'' is always false\n", errout_str());
check("void f(int i) { if (i == 1 || 2) {} }\n"); // #12487
ASSERT_EQUALS("[test.cpp:1]: (style) Condition 'i==1||2' is always true\n", errout_str());
check("enum E { E1 = 1, E2 = 2 };\n"
"void f(int i) { if (i == E1 || E2) {} }\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Condition 'i==E1||E2' is always true\n", errout_str());
}
void pointerAdditionResultNotNull() {
check("void f(char *ptr) {\n"
" if (ptr + 1 != 0);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Comparison is wrong. Result of 'ptr+1' can't be 0 unless there is pointer overflow, and pointer overflow is undefined behaviour.\n", errout_str());
}
void duplicateConditionalAssign() {
setMultiline();
check("void f(int& x, int y) {\n"
" if (x == y)\n"
" x = y;\n"
"}");
ASSERT_EQUALS("test.cpp:3:style:Assignment 'x=y' is redundant with condition 'x==y'.\n"
"test.cpp:2:note:Condition 'x==y'\n"
"test.cpp:3:note:Assignment 'x=y' is redundant\n", errout_str());
check("void f(int& x, int y) {\n"
" if (x != y)\n"
" x = y;\n"
"}");
ASSERT_EQUALS("test.cpp:2:style:The statement 'if (x!=y) x=y' is logically equivalent to 'x=y'.\n"
"test.cpp:3:note:Assignment 'x=y'\n"
"test.cpp:2:note:Condition 'x!=y' is redundant\n", errout_str());
check("void f(int& x, int y) {\n"
" if (x == y)\n"
" x = y;\n"
" else\n"
" x = 1;\n"
"}");
ASSERT_EQUALS("test.cpp:3:style:Assignment 'x=y' is redundant with condition 'x==y'.\n"
"test.cpp:2:note:Condition 'x==y'\n"
"test.cpp:3:note:Assignment 'x=y' is redundant\n", errout_str());
check("void f(int& x, int y) {\n"
" if (x != y)\n"
" x = y;\n"
" else\n"
" x = 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(int& x, int y) {\n"
" if (x == y)\n"
" x = y + 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void g();\n"
"void f(int& x, int y) {\n"
" if (x == y) {\n"
" x = y;\n"
" g();\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool f(bool b) {\n"
" if (b)\n"
" b = false;\n"
" else\n"
" g();\n"
" return b;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(int& i) {\n"
" if (!i)\n"
" i = 1; \n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct S {\n" // #9406
" S() : b(false) {}\n"
" void f() {\n"
" if (b) b = true;\n"
" if (b) b = false;\n"
" if (!b) b = true;\n"
" if (!b) b = false;\n"
" }\n"
" bool b;\n"
"};\n");
ASSERT_EQUALS("test.cpp:4:style:The statement 'if (b) b=true' is redundant.\n"
"test.cpp:4:note:Assignment 'b=true'\n"
"test.cpp:4:note:Condition 'b' is redundant\n"
"test.cpp:5:style:The statement 'if (b) b=false' is logically equivalent to 'b=false'.\n"
"test.cpp:5:note:Assignment 'b=false'\n"
"test.cpp:5:note:Condition 'b' is redundant\n"
"test.cpp:6:style:The statement 'if (!b) b=true' is logically equivalent to 'b=true'.\n"
"test.cpp:6:note:Assignment 'b=true'\n"
"test.cpp:6:note:Condition '!b' is redundant\n"
"test.cpp:7:style:The statement 'if (!b) b=false' is redundant.\n"
"test.cpp:7:note:Assignment 'b=false'\n"
"test.cpp:7:note:Condition '!b' is redundant\n",
errout_str());
}
void checkAssignmentInCondition() {
check("void f(std::string s) {\n"
" if (s=\"123\"){}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Suspicious assignment in condition. Condition 's=\"123\"' is always true.\n", errout_str());
check("void f(std::string *p) {\n"
" if (p=foo()){}\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f(uint32_t u) {\n" // #2490
" if ((u = 0x00000000) || (u = 0xffffffff)) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Condition 'u=0x00000000' is always false\n"
"[test.cpp:2]: (style) Condition 'u=0xffffffff' is always true\n",
errout_str());
}
void compareOutOfTypeRange() {
const Settings settingsUnix64 = settingsBuilder().severity(Severity::style).platform(Platform::Type::Unix64).build();
check("void f(unsigned char c) {\n"
" if (c == 256) {}\n"
"}", settingsUnix64);
ASSERT_EQUALS("[test.cpp:2]: (style) Comparing expression of type 'unsigned char' against value 256. Condition is always false.\n", errout_str());
check("void f(unsigned char* b, int i) {\n" // #6372
" if (b[i] == 256) {}\n"
"}", settingsUnix64);
ASSERT_EQUALS("[test.cpp:2]: (style) Comparing expression of type 'unsigned char' against value 256. Condition is always false.\n", errout_str());
check("void f(unsigned char c) {\n"
" if (c == 255) {}\n"
"}", settingsUnix64);
ASSERT_EQUALS("", errout_str());
check("void f(bool b) {\n"
" if (b == true) {}\n"
"}", settingsUnix64);
ASSERT_EQUALS("", errout_str());
// #10372
check("void f(signed char x) {\n"
" if (x == 0xff) {}\n"
"}", settingsUnix64);
ASSERT_EQUALS("[test.cpp:2]: (style) Comparing expression of type 'signed char' against value 255. Condition is always false.\n", errout_str());
check("void f(short x) {\n"
" if (x == 0xffff) {}\n"
"}", settingsUnix64);
ASSERT_EQUALS("[test.cpp:2]: (style) Comparing expression of type 'signed short' against value 65535. Condition is always false.\n", errout_str());
check("void f(int x) {\n"
" if (x == 0xffffffff) {}\n"
"}", settingsUnix64);
ASSERT_EQUALS("", errout_str());
check("void f(long x) {\n"
" if (x == ~0L) {}\n"
"}", settingsUnix64);
ASSERT_EQUALS("", errout_str());
check("void f(long long x) {\n"
" if (x == ~0LL) {}\n"
"}", settingsUnix64);
ASSERT_EQUALS("", errout_str());
check("int f(int x) {\n"
" const int i = 0xFFFFFFFF;\n"
" if (x == i) {}\n"
"}", settingsUnix64);
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" char c;\n"
" if ((c = foo()) != -1) {}\n"
"}", settingsUnix64);
ASSERT_EQUALS("", errout_str());
check("void f(int x) {\n"
" if (x < 3000000000) {}\n"
"}", settingsUnix64);
ASSERT_EQUALS("[test.cpp:2]: (style) Comparing expression of type 'signed int' against value 3000000000. Condition is always true.\n", errout_str());
check("void f(const signed char i) {\n" // #8545
" if (i > -129) {}\n" // warn
" if (i >= -128) {}\n" // warn
" if (i >= -127) {}\n"
" if (i < +128) {}\n" // warn
" if (i <= +127) {}\n" // warn
" if (i <= +126) {}\n"
"}\n", settingsUnix64);
ASSERT_EQUALS("[test.cpp:2]: (style) Comparing expression of type 'const signed char' against value -129. Condition is always true.\n"
"[test.cpp:3]: (style) Comparing expression of type 'const signed char' against value -128. Condition is always true.\n"
"[test.cpp:5]: (style) Comparing expression of type 'const signed char' against value 128. Condition is always true.\n"
"[test.cpp:6]: (style) Comparing expression of type 'const signed char' against value 127. Condition is always true.\n",
errout_str());
check("void f(const unsigned char u) {\n"
" if (u > 0) {}\n"
" if (u < 0) {}\n" // warn
" if (u >= 0) {}\n" // warn
" if (u <= 0) {}\n"
" if (u > 255) {}\n" // warn
" if (u < 255) {}\n"
" if (u >= 255) {}\n"
" if (u <= 255) {}\n" // warn
" if (0 < u) {}\n"
" if (0 > u) {}\n" // warn
" if (0 <= u) {}\n" // warn
" if (0 >= u) {}\n"
" if (255 < u) {}\n" // warn
" if (255 > u) {}\n"
" if (255 <= u) {}\n"
" if (255 >= u) {}\n" // warn
"}\n", settingsUnix64);
ASSERT_EQUALS("[test.cpp:3]: (style) Comparing expression of type 'const unsigned char' against value 0. Condition is always false.\n"
"[test.cpp:4]: (style) Comparing expression of type 'const unsigned char' against value 0. Condition is always true.\n"
"[test.cpp:6]: (style) Comparing expression of type 'const unsigned char' against value 255. Condition is always false.\n"
"[test.cpp:9]: (style) Comparing expression of type 'const unsigned char' against value 255. Condition is always true.\n"
"[test.cpp:11]: (style) Comparing expression of type 'const unsigned char' against value 0. Condition is always false.\n"
"[test.cpp:12]: (style) Comparing expression of type 'const unsigned char' against value 0. Condition is always true.\n"
"[test.cpp:14]: (style) Comparing expression of type 'const unsigned char' against value 255. Condition is always false.\n"
"[test.cpp:17]: (style) Comparing expression of type 'const unsigned char' against value 255. Condition is always true.\n",
errout_str());
}
void knownConditionCast() {
check("void f(int i) {\n" // #9976
" if (i < 0 || (unsigned)i > 5) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct B {\n" // #12941
" virtual void f();\n"
"};\n"
"struct One : public B {};\n"
"struct Two : public B {};\n"
"void g(const B& b) {\n"
" const Two* two = nullptr;\n"
" const One* one = dynamic_cast<const One*>(&b);\n"
" if (one == nullptr)\n"
" two = dynamic_cast<const Two*>(&b);\n"
" if (two) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void knownConditionIncrementLoop() { // #9808
check("void f() {\n"
" int a = 0;\n"
" while (++a < 5) {}\n"
" if (a == 1) {}\n"
" std::cout << a;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void knownConditionAfterBailout() { // #12526
check(
"#include <list>\n"
"int func()\n"
"{\n"
" return VALUE_1;"
"}\n"
"\n"
"struct S1 {\n"
" bool b{};\n"
"};\n"
"\n"
"struct S {\n"
" void f(const std::list<int>& l) const\n"
" {\n"
" if (mS.b)\n"
" return;\n"
" for (int i : l)\n"
" {\n"
" (void)i;\n"
" if (mS.b)\n"
" continue;\n"
" }\n"
" }\n"
"\n"
" S1 mS;\n"
"};"
);
ASSERT_EQUALS("[test.cpp:13] -> [test.cpp:18]: (style) Condition 'mS.b' is always false\n", errout_str());
}
void knownConditionIncDecOperator() {
check(
"void f() {\n"
" unsigned int d = 0;\n"
" for (int i = 0; i < 4; ++i) {\n"
" if (i < 3)\n"
" ++d;\n"
" else if (--d == 0)\n"
" ;\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
};
REGISTER_TEST(TestCondition)
| null |
998 | cpp | cppcheck | testmathlib.cpp | test/testmathlib.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "config.h"
#include "mathlib.h"
#include "fixture.h"
#include <limits>
#include <string>
class TestMathLib : public TestFixture {
public:
TestMathLib() : TestFixture("TestMathLib") {}
private:
void run() override {
TEST_CASE(isint);
TEST_CASE(isbin);
TEST_CASE(isdec);
TEST_CASE(isoct);
TEST_CASE(isFloatHex);
TEST_CASE(isIntHex);
TEST_CASE(isValidIntegerSuffix);
TEST_CASE(isnegative);
TEST_CASE(ispositive);
TEST_CASE(isFloat);
TEST_CASE(isDecimalFloat);
TEST_CASE(isGreater);
TEST_CASE(isGreaterEqual);
TEST_CASE(isEqual);
TEST_CASE(isNotEqual);
TEST_CASE(isLess);
TEST_CASE(isLessEqual);
TEST_CASE(calculate);
TEST_CASE(calculate1);
TEST_CASE(typesuffix);
TEST_CASE(toBigNumber);
TEST_CASE(toBigUNumber);
TEST_CASE(toDoubleNumber);
TEST_CASE(naninf);
TEST_CASE(isNullValue);
TEST_CASE(sin);
TEST_CASE(cos);
TEST_CASE(tan);
TEST_CASE(abs);
TEST_CASE(toString);
}
void isGreater() const {
ASSERT_EQUALS(true, MathLib::isGreater("1.0", "0.001"));
ASSERT_EQUALS(false, MathLib::isGreater("-1.0", "0.001"));
}
void isGreaterEqual() const {
ASSERT_EQUALS(true, MathLib::isGreaterEqual("1.00", "1.0"));
ASSERT_EQUALS(true, MathLib::isGreaterEqual("1.001", "1.0"));
ASSERT_EQUALS(true, MathLib::isGreaterEqual("1.0", "0.001"));
ASSERT_EQUALS(false, MathLib::isGreaterEqual("-1.0", "0.001"));
}
void isEqual() const {
ASSERT_EQUALS(true, MathLib::isEqual("1.0", "1.0"));
ASSERT_EQUALS(false, MathLib::isEqual("1.", "1.01"));
ASSERT_EQUALS(true, MathLib::isEqual("0.1","1.0E-1"));
}
void isNotEqual() const {
ASSERT_EQUALS(false, MathLib::isNotEqual("1.0", "1.0"));
ASSERT_EQUALS(true, MathLib::isNotEqual("1.", "1.01"));
}
void isLess() const {
ASSERT_EQUALS(false, MathLib::isLess("1.0", "0.001"));
ASSERT_EQUALS(true, MathLib::isLess("-1.0", "0.001"));
}
void isLessEqual() const {
ASSERT_EQUALS(true, MathLib::isLessEqual("1.00", "1.0"));
ASSERT_EQUALS(false, MathLib::isLessEqual("1.001", "1.0"));
ASSERT_EQUALS(false, MathLib::isLessEqual("1.0", "0.001"));
ASSERT_EQUALS(true, MathLib::isLessEqual("-1.0", "0.001"));
}
void calculate() const {
// addition
ASSERT_EQUALS("256", MathLib::add("0xff", "1"));
ASSERT_EQUALS("249", MathLib::add("250", "-1"));
ASSERT_EQUALS("251", MathLib::add("250", "1"));
ASSERT_EQUALS("-2.0", MathLib::add("-1.", "-1"));
ASSERT_EQUALS("-1", MathLib::add("0", "-1"));
ASSERT_EQUALS("1", MathLib::add("1", "0"));
ASSERT_EQUALS("0.0", MathLib::add("0", "0."));
ASSERT_EQUALS("1.00000001", MathLib::add("1", "0.00000001")); // #4016
ASSERT_EQUALS("30666.22", MathLib::add("30666.22", "0.0")); // #4068
// subtraction
ASSERT_EQUALS("254", MathLib::subtract("0xff", "1"));
ASSERT_EQUALS("251", MathLib::subtract("250", "-1"));
ASSERT_EQUALS("249", MathLib::subtract("250", "1"));
ASSERT_EQUALS("0.0", MathLib::subtract("-1.", "-1"));
ASSERT_EQUALS("1", MathLib::subtract("0", "-1"));
ASSERT_EQUALS("1", MathLib::subtract("1", "0"));
ASSERT_EQUALS("0.0", MathLib::subtract("0", "0."));
ASSERT_EQUALS("0.99999999", MathLib::subtract("1", "0.00000001")); // #4016
ASSERT_EQUALS("30666.22", MathLib::subtract("30666.22", "0.0")); // #4068
ASSERT_EQUALS("0.0", MathLib::subtract("0.0", "0.0"));
// multiply
ASSERT_EQUALS("-0.003", MathLib::multiply("-1e-3", "3"));
ASSERT_EQUALS("-11.96", MathLib::multiply("-2.3", "5.2"));
ASSERT_EQUALS("3000.0", MathLib::multiply("1E3", "3"));
ASSERT_EQUALS("3000.0", MathLib::multiply("1E+3", "3"));
ASSERT_EQUALS("3000.0", MathLib::multiply("1.0E3", "3"));
ASSERT_EQUALS("-3000.0", MathLib::multiply("-1.0E3", "3"));
ASSERT_EQUALS("-3000.0", MathLib::multiply("-1.0E+3", "3"));
ASSERT_EQUALS("0.0", MathLib::multiply("+1.0E+3", "0"));
ASSERT_EQUALS("2147483648", MathLib::multiply("2","1073741824"));
ASSERT_EQUALS("536870912", MathLib::multiply("512","1048576"));
// divide
ASSERT_EQUALS("1", MathLib::divide("1", "1"));
ASSERT_EQUALS("0", MathLib::divide("0", "1"));
ASSERT_EQUALS("5", MathLib::divide("-10", "-2"));
ASSERT_EQUALS("-2.5", MathLib::divide("-10.", "4"));
ASSERT_EQUALS("2.5", MathLib::divide("-10.", "-4"));
ASSERT_EQUALS("5.0", MathLib::divide("25.5", "5.1"));
ASSERT_EQUALS("7.0", MathLib::divide("21.", "3"));
ASSERT_EQUALS("1", MathLib::divide("3", "2"));
ASSERT_THROW_INTERNAL_EQUALS(MathLib::divide("123", "0"), INTERNAL, "Internal Error: Division by zero"); // decimal zero: throw
ASSERT_THROW_INTERNAL_EQUALS(MathLib::divide("123", "00"), INTERNAL, "Internal Error: Division by zero"); // octal zero: throw
ASSERT_THROW_INTERNAL_EQUALS(MathLib::divide("123", "0x0"), INTERNAL, "Internal Error: Division by zero"); // hex zero: throw
ASSERT_NO_THROW(MathLib::divide("123", "0.0f")); // float zero
ASSERT_NO_THROW(MathLib::divide("123", "0.0")); // double zero
ASSERT_NO_THROW(MathLib::divide("123", "0.0L")); // long double zero
ASSERT_THROW_INTERNAL_EQUALS(MathLib::divide("-9223372036854775808", "-1"), INTERNAL, "Internal Error: Division overflow"); // #4520 - out of range => throw
ASSERT_EQUALS("4611686018427387904", MathLib::divide("-9223372036854775808", "-2")); // #6679
// invoke for each supported action
ASSERT_EQUALS("3", MathLib::calculate("2", "1", '+'));
ASSERT_EQUALS("1", MathLib::calculate("2", "1", '-'));
ASSERT_EQUALS("2", MathLib::calculate("2", "1", '*'));
ASSERT_EQUALS("2", MathLib::calculate("2", "1", '/'));
ASSERT_EQUALS("0", MathLib::calculate("2", "1", '%'));
ASSERT_EQUALS("0", MathLib::calculate("1", "2", '&'));
ASSERT_EQUALS("1", MathLib::calculate("1", "1", '|'));
ASSERT_EQUALS("1", MathLib::calculate("0", "1", '^'));
// Unknown action should throw exception
ASSERT_THROW_INTERNAL_EQUALS(MathLib::calculate("1","2",'j'),INTERNAL, "Unexpected action 'j' in MathLib::calculate(). Please report this to Cppcheck developers.");
}
void calculate1() const {
ASSERT_EQUALS("0", MathLib::calculate("2", "1", '%'));
ASSERT_EQUALS("2", MathLib::calculate("12", "5", '%'));
ASSERT_EQUALS("1", MathLib::calculate("100", "3", '%'));
#ifndef TEST_MATHLIB_VALUE
// floating point modulo is not defined in C/C++
ASSERT_EQUALS("0.0", MathLib::calculate("2.0", "1.0", '%'));
ASSERT_EQUALS("12.0", MathLib::calculate("12.0", "13.0", '%'));
ASSERT_EQUALS("1.3", MathLib::calculate("5.3", "2.0", '%'));
ASSERT_EQUALS("1.7", MathLib::calculate("18.5", "4.2", '%'));
ASSERT_NO_THROW(MathLib::calculate("123", "0.0", '%'));
#endif
ASSERT_THROW_INTERNAL_EQUALS(MathLib::calculate("123", "0", '%'), INTERNAL, "Internal Error: Division by zero"); // throw
ASSERT_EQUALS("0", MathLib::calculate("1", "1", '^'));
ASSERT_EQUALS("3", MathLib::calculate("2", "1", '^'));
}
void typesuffix() const {
ASSERT_EQUALS("2", MathLib::add("1", "1"));
ASSERT_EQUALS("2U", MathLib::add("1U", "1"));
ASSERT_EQUALS("2L", MathLib::add("1L", "1"));
ASSERT_EQUALS("2UL", MathLib::add("1UL", "1"));
ASSERT_EQUALS("2LL", MathLib::add("1LL", "1"));
ASSERT_EQUALS("2LL", MathLib::add("1i64", "1"));
ASSERT_EQUALS("2ULL", MathLib::add("1ULL", "1"));
ASSERT_EQUALS("2ULL", MathLib::add("1ui64","1"));
ASSERT_EQUALS("2U", MathLib::add("1", "1U"));
ASSERT_EQUALS("2U", MathLib::add("1U", "1U"));
ASSERT_EQUALS("2L", MathLib::add("1L", "1U"));
ASSERT_EQUALS("2UL", MathLib::add("1UL", "1U"));
ASSERT_EQUALS("2LL", MathLib::add("1LL", "1U"));
ASSERT_EQUALS("2ULL", MathLib::add("1ULL", "1U"));
ASSERT_EQUALS("2L", MathLib::add("1", "1L"));
ASSERT_EQUALS("2L", MathLib::add("1U", "1L"));
ASSERT_EQUALS("2L", MathLib::add("1L", "1L"));
ASSERT_EQUALS("2UL", MathLib::add("1UL", "1L"));
ASSERT_EQUALS("2LL", MathLib::add("1LL", "1L"));
ASSERT_EQUALS("2ULL", MathLib::add("1ULL", "1L"));
ASSERT_EQUALS("2UL", MathLib::add("1", "1UL"));
ASSERT_EQUALS("2UL", MathLib::add("1U", "1UL"));
ASSERT_EQUALS("2UL", MathLib::add("1L", "1UL"));
ASSERT_EQUALS("2UL", MathLib::add("1UL", "1UL"));
ASSERT_EQUALS("2LL", MathLib::add("1LL", "1UL"));
ASSERT_EQUALS("2ULL", MathLib::add("1ULL", "1UL"));
ASSERT_EQUALS("2UL", MathLib::add("1", "1LU"));
ASSERT_EQUALS("2UL", MathLib::add("1U", "1LU"));
ASSERT_EQUALS("2UL", MathLib::add("1L", "1LU"));
ASSERT_EQUALS("2UL", MathLib::add("1UL", "1LU"));
ASSERT_EQUALS("2LL", MathLib::add("1LL", "1LU"));
ASSERT_EQUALS("2ULL", MathLib::add("1ULL", "1LU"));
ASSERT_EQUALS("2LL", MathLib::add("1", "1LL"));
ASSERT_EQUALS("2LL", MathLib::add("1U", "1LL"));
ASSERT_EQUALS("2LL", MathLib::add("1L", "1LL"));
ASSERT_EQUALS("2LL", MathLib::add("1UL", "1LL"));
ASSERT_EQUALS("2LL", MathLib::add("1LL", "1LL"));
ASSERT_EQUALS("2ULL", MathLib::add("1ULL", "1LL"));
ASSERT_EQUALS("2ULL", MathLib::add("1", "1ULL"));
ASSERT_EQUALS("2ULL", MathLib::add("1U", "1ULL"));
ASSERT_EQUALS("2ULL", MathLib::add("1L", "1ULL"));
ASSERT_EQUALS("2ULL", MathLib::add("1UL", "1ULL"));
ASSERT_EQUALS("2ULL", MathLib::add("1LL", "1ULL"));
ASSERT_EQUALS("2ULL", MathLib::add("1ULL", "1ULL"));
ASSERT_EQUALS("2ULL", MathLib::add("1", "1LLU"));
ASSERT_EQUALS("2ULL", MathLib::add("1U", "1LLU"));
ASSERT_EQUALS("2ULL", MathLib::add("1L", "1LLU"));
ASSERT_EQUALS("2ULL", MathLib::add("1UL", "1LLU"));
ASSERT_EQUALS("2ULL", MathLib::add("1LL", "1LLU"));
ASSERT_EQUALS("2ULL", MathLib::add("1ULL", "1LLU"));
}
void toBigNumber() const {
// zero input
ASSERT_EQUALS(0, MathLib::toBigNumber("0"));
ASSERT_EQUALS(0, MathLib::toBigNumber("-0"));
ASSERT_EQUALS(0, MathLib::toBigNumber("+0"));
ASSERT_EQUALS(0, MathLib::toBigNumber("0L"));
ASSERT_EQUALS(0, MathLib::toBigNumber("0l"));
ASSERT_EQUALS(0, MathLib::toBigNumber("0LL"));
ASSERT_EQUALS(0, MathLib::toBigNumber("0ll"));
ASSERT_EQUALS(0, MathLib::toBigNumber("0U"));
ASSERT_EQUALS(0, MathLib::toBigNumber("0u"));
ASSERT_EQUALS(0, MathLib::toBigNumber("0UL"));
ASSERT_EQUALS(0, MathLib::toBigNumber("0ul"));
ASSERT_EQUALS(0, MathLib::toBigNumber("0ULL"));
ASSERT_EQUALS(0, MathLib::toBigNumber("0ull"));
ASSERT_EQUALS(0, MathLib::toBigNumber("0i64")); // Visual Studio-specific
ASSERT_EQUALS(0, MathLib::toBigNumber("0ui64")); // Visual Studio-specific
// TODO: needs to fail
//ASSERT_EQUALS(0, MathLib::toBigNumber("0lll"));
//ASSERT_EQUALS(0, MathLib::toBigNumber("0uu"));
ASSERT_EQUALS(1U, MathLib::toBigNumber("1U"));
ASSERT_EQUALS(10000U, MathLib::toBigNumber("1e4"));
ASSERT_EQUALS(10000U, MathLib::toBigNumber("1e4"));
ASSERT_EQUALS(0xFF00000000000000UL, MathLib::toBigNumber("0xFF00000000000000UL"));
ASSERT_EQUALS(0x0A00000000000000UL, MathLib::toBigNumber("0x0A00000000000000UL"));
// from hex
ASSERT_EQUALS(0, MathLib::toBigNumber("0x0"));
ASSERT_EQUALS(0, MathLib::toBigNumber("-0x0"));
ASSERT_EQUALS(0, MathLib::toBigNumber("+0x0"));
ASSERT_EQUALS(10, MathLib::toBigNumber("0xa"));
ASSERT_EQUALS(10995, MathLib::toBigNumber("0x2AF3"));
ASSERT_EQUALS(-10, MathLib::toBigNumber("-0xa"));
ASSERT_EQUALS(-10995, MathLib::toBigNumber("-0x2AF3"));
ASSERT_EQUALS(10, MathLib::toBigNumber("+0xa"));
ASSERT_EQUALS(10995, MathLib::toBigNumber("+0x2AF3"));
// from octal
ASSERT_EQUALS(8, MathLib::toBigNumber("010"));
ASSERT_EQUALS(8, MathLib::toBigNumber("+010"));
ASSERT_EQUALS(-8, MathLib::toBigNumber("-010"));
ASSERT_EQUALS(125, MathLib::toBigNumber("0175"));
ASSERT_EQUALS(125, MathLib::toBigNumber("+0175"));
ASSERT_EQUALS(-125, MathLib::toBigNumber("-0175"));
// from binary
ASSERT_EQUALS(0, MathLib::toBigNumber("0b0"));
ASSERT_EQUALS(1, MathLib::toBigNumber("0b1"));
ASSERT_EQUALS(1, MathLib::toBigNumber("0b1U"));
ASSERT_EQUALS(1, MathLib::toBigNumber("0b1L"));
ASSERT_EQUALS(1, MathLib::toBigNumber("0b1LU"));
ASSERT_EQUALS(1, MathLib::toBigNumber("0b1LL"));
ASSERT_EQUALS(1, MathLib::toBigNumber("0b1LLU"));
ASSERT_EQUALS(1, MathLib::toBigNumber("+0b1"));
ASSERT_EQUALS(-1, MathLib::toBigNumber("-0b1"));
ASSERT_EQUALS(9U, MathLib::toBigNumber("011"));
ASSERT_EQUALS(5U, MathLib::toBigNumber("0b101"));
ASSERT_EQUALS(215, MathLib::toBigNumber("0b11010111"));
ASSERT_EQUALS(-215, MathLib::toBigNumber("-0b11010111"));
ASSERT_EQUALS(215, MathLib::toBigNumber("0B11010111"));
// from base 10
ASSERT_EQUALS(10, MathLib::toBigNumber("10"));
ASSERT_EQUALS(10, MathLib::toBigNumber("10."));
ASSERT_EQUALS(10, MathLib::toBigNumber("10.0"));
ASSERT_EQUALS(100, MathLib::toBigNumber("10E+1"));
ASSERT_EQUALS(1, MathLib::toBigNumber("10E-1"));
ASSERT_EQUALS(100, MathLib::toBigNumber("+10E+1"));
ASSERT_EQUALS(-1, MathLib::toBigNumber("-10E-1"));
ASSERT_EQUALS(100, MathLib::toBigNumber("+10.E+1"));
ASSERT_EQUALS(-1, MathLib::toBigNumber("-10.E-1"));
ASSERT_EQUALS(100, MathLib::toBigNumber("+10.0E+1"));
ASSERT_EQUALS(-1, MathLib::toBigNumber("-10.0E-1"));
// from char
ASSERT_EQUALS((int)('A'), MathLib::toBigNumber("'A'"));
ASSERT_EQUALS((int)('\x10'), MathLib::toBigNumber("'\\x10'"));
ASSERT_EQUALS((int)('\100'), MathLib::toBigNumber("'\\100'"));
ASSERT_EQUALS((int)('\200'), MathLib::toBigNumber("'\\200'"));
ASSERT_EQUALS((int)(L'A'), MathLib::toBigNumber("L'A'"));
ASSERT_EQUALS(-8552249625308161526, MathLib::toBigNumber("0x89504e470d0a1a0a"));
ASSERT_EQUALS(-8481036456200365558, MathLib::toBigNumber("0x8a4d4e470d0a1a0a"));
// from long long
/*
* ASSERT_EQUALS(0xFF00000000000000LL, MathLib::toBigNumber("0xFF00000000000000LL"));
* This does not work in a portable way!
* While it succeeds on 32bit Visual Studio it fails on Linux 64bit because it is greater than 0x7FFFFFFFFFFFFFFF (=LLONG_MAX)
*/
ASSERT_EQUALS(0x0A00000000000000LL, MathLib::toBigNumber("0x0A00000000000000LL"));
// min/max numeric limits
ASSERT_EQUALS(std::numeric_limits<long long>::min(),
MathLib::toBigNumber(std::to_string(std::numeric_limits<long long>::min())));
ASSERT_EQUALS(std::numeric_limits<long long>::max(),
MathLib::toBigNumber(std::to_string(std::numeric_limits<long long>::max())));
ASSERT_EQUALS(std::numeric_limits<unsigned long long>::min(),
MathLib::toBigNumber(std::to_string(std::numeric_limits<unsigned long long>::min())));
ASSERT_EQUALS(std::numeric_limits<unsigned long long>::max(),
MathLib::toBigNumber(std::to_string(std::numeric_limits<unsigned long long>::max())));
// min/max and out-of-bounds - hex
{
constexpr MathLib::bigint i = 0xFFFFFFFFFFFFFFFF;
ASSERT_EQUALS(i, MathLib::toBigNumber(std::to_string(i)));
ASSERT_EQUALS(i, MathLib::toBigNumber("0xFFFFFFFFFFFFFFFF"));
}
{
constexpr MathLib::bigint i = -0xFFFFFFFFFFFFFFFF;
ASSERT_EQUALS(i, MathLib::toBigNumber(std::to_string(i)));
ASSERT_EQUALS(i, MathLib::toBigNumber("-0xFFFFFFFFFFFFFFFF"));
}
ASSERT_THROW_INTERNAL_EQUALS(MathLib::toBigNumber("0x10000000000000000"), INTERNAL, "Internal Error. MathLib::toBigNumber: out_of_range: 0x10000000000000000");
ASSERT_THROW_INTERNAL_EQUALS(MathLib::toBigNumber("-0x10000000000000000"), INTERNAL, "Internal Error. MathLib::toBigNumber: out_of_range: -0x10000000000000000");
// min/max and out-of-bounds - octal
{
constexpr MathLib::bigint i = 01777777777777777777777;
ASSERT_EQUALS(i, MathLib::toBigNumber(std::to_string(i)));
ASSERT_EQUALS(i, MathLib::toBigNumber("01777777777777777777777"));
}
{
constexpr MathLib::bigint i = -01777777777777777777777;
ASSERT_EQUALS(i, MathLib::toBigNumber(std::to_string(i)));
ASSERT_EQUALS(i, MathLib::toBigNumber("-01777777777777777777777"));
}
ASSERT_THROW_INTERNAL_EQUALS(MathLib::toBigNumber("02000000000000000000000"), INTERNAL, "Internal Error. MathLib::toBigNumber: out_of_range: 02000000000000000000000");
ASSERT_THROW_INTERNAL_EQUALS(MathLib::toBigNumber("-02000000000000000000000"), INTERNAL, "Internal Error. MathLib::toBigNumber: out_of_range: -02000000000000000000000");
// min/max and out-of-bounds - decimal
SUPPRESS_WARNING_CLANG_PUSH("-Wimplicitly-unsigned-literal")
SUPPRESS_WARNING_GCC_PUSH("-Woverflow")
{
constexpr MathLib::bigint i = 18446744073709551615;
ASSERT_EQUALS(i, MathLib::toBigNumber(std::to_string(i)));
ASSERT_EQUALS(i, MathLib::toBigNumber("18446744073709551615"));
}
{
constexpr MathLib::bigint i = -18446744073709551615;
ASSERT_EQUALS(i, MathLib::toBigNumber(std::to_string(i)));
ASSERT_EQUALS(i, MathLib::toBigNumber("-18446744073709551615"));
}
SUPPRESS_WARNING_GCC_POP
SUPPRESS_WARNING_CLANG_POP
ASSERT_THROW_INTERNAL_EQUALS(MathLib::toBigNumber("18446744073709551616"), INTERNAL, "Internal Error. MathLib::toBigNumber: out_of_range: 18446744073709551616");
ASSERT_THROW_INTERNAL_EQUALS(MathLib::toBigNumber("-18446744073709551616"), INTERNAL, "Internal Error. MathLib::toBigNumber: out_of_range: -18446744073709551616");
ASSERT_THROW_INTERNAL_EQUALS(MathLib::toBigNumber("invalid"), INTERNAL, "Internal Error. MathLib::toBigNumber: invalid_argument: invalid");
ASSERT_THROW_INTERNAL_EQUALS(MathLib::toBigNumber("1invalid"), INTERNAL, "Internal Error. MathLib::toBigNumber: input was not completely consumed: 1invalid");
ASSERT_THROW_INTERNAL_EQUALS(MathLib::toBigNumber("1 invalid"), INTERNAL, "Internal Error. MathLib::toBigNumber: input was not completely consumed: 1 invalid");
// TODO: test binary
// TODO: test floating point
// TODO: test with 128-bit values
}
void toBigUNumber() const {
// zero input
ASSERT_EQUALS(0, MathLib::toBigUNumber("0"));
ASSERT_EQUALS(0, MathLib::toBigUNumber("-0"));
ASSERT_EQUALS(0, MathLib::toBigUNumber("+0"));
ASSERT_EQUALS(0, MathLib::toBigUNumber("0L"));
ASSERT_EQUALS(0, MathLib::toBigUNumber("0l"));
ASSERT_EQUALS(0, MathLib::toBigUNumber("0LL"));
ASSERT_EQUALS(0, MathLib::toBigUNumber("0ll"));
ASSERT_EQUALS(0, MathLib::toBigUNumber("0U"));
ASSERT_EQUALS(0, MathLib::toBigUNumber("0u"));
ASSERT_EQUALS(0, MathLib::toBigUNumber("0UL"));
ASSERT_EQUALS(0, MathLib::toBigUNumber("0ul"));
ASSERT_EQUALS(0, MathLib::toBigUNumber("0ULL"));
ASSERT_EQUALS(0, MathLib::toBigUNumber("0ull"));
ASSERT_EQUALS(0, MathLib::toBigUNumber("0i64")); // Visual Studio-specific
ASSERT_EQUALS(0, MathLib::toBigUNumber("0ui64")); // Visual Studio-specific
// TODO: needs to fail
//ASSERT_EQUALS(0, MathLib::toBigUNumber("0lll"));
//ASSERT_EQUALS(0, MathLib::toBigUNumber("0uu"));
ASSERT_EQUALS(1U, MathLib::toBigUNumber("1U"));
ASSERT_EQUALS(10000U, MathLib::toBigUNumber("1e4"));
ASSERT_EQUALS(10000U, MathLib::toBigUNumber("1e4"));
ASSERT_EQUALS(0xFF00000000000000UL, MathLib::toBigUNumber("0xFF00000000000000UL"));
ASSERT_EQUALS(0x0A00000000000000UL, MathLib::toBigUNumber("0x0A00000000000000UL"));
// from hex
ASSERT_EQUALS(0, MathLib::toBigUNumber("0x0"));
ASSERT_EQUALS(0, MathLib::toBigUNumber("-0x0"));
ASSERT_EQUALS(0, MathLib::toBigUNumber("+0x0"));
ASSERT_EQUALS(10, MathLib::toBigUNumber("0xa"));
ASSERT_EQUALS(10995, MathLib::toBigUNumber("0x2AF3"));
ASSERT_EQUALS(-10, MathLib::toBigUNumber("-0xa"));
ASSERT_EQUALS(-10995, MathLib::toBigUNumber("-0x2AF3"));
ASSERT_EQUALS(10, MathLib::toBigUNumber("+0xa"));
ASSERT_EQUALS(10995, MathLib::toBigUNumber("+0x2AF3"));
// from octal
ASSERT_EQUALS(8, MathLib::toBigUNumber("010"));
ASSERT_EQUALS(8, MathLib::toBigUNumber("+010"));
ASSERT_EQUALS(-8, MathLib::toBigUNumber("-010"));
ASSERT_EQUALS(125, MathLib::toBigUNumber("0175"));
ASSERT_EQUALS(125, MathLib::toBigUNumber("+0175"));
ASSERT_EQUALS(-125, MathLib::toBigUNumber("-0175"));
// from binary
ASSERT_EQUALS(0, MathLib::toBigUNumber("0b0"));
ASSERT_EQUALS(1, MathLib::toBigUNumber("0b1"));
ASSERT_EQUALS(1, MathLib::toBigUNumber("0b1U"));
ASSERT_EQUALS(1, MathLib::toBigUNumber("0b1L"));
ASSERT_EQUALS(1, MathLib::toBigUNumber("0b1LU"));
ASSERT_EQUALS(1, MathLib::toBigUNumber("0b1LL"));
ASSERT_EQUALS(1, MathLib::toBigUNumber("0b1LLU"));
ASSERT_EQUALS(1, MathLib::toBigUNumber("+0b1"));
ASSERT_EQUALS(-1, MathLib::toBigUNumber("-0b1"));
ASSERT_EQUALS(9U, MathLib::toBigUNumber("011"));
ASSERT_EQUALS(5U, MathLib::toBigUNumber("0b101"));
ASSERT_EQUALS(215, MathLib::toBigUNumber("0b11010111"));
ASSERT_EQUALS(-215, MathLib::toBigUNumber("-0b11010111"));
ASSERT_EQUALS(215, MathLib::toBigUNumber("0B11010111"));
// from base 10
ASSERT_EQUALS(10, MathLib::toBigUNumber("10"));
ASSERT_EQUALS(10, MathLib::toBigUNumber("10."));
ASSERT_EQUALS(10, MathLib::toBigUNumber("10.0"));
ASSERT_EQUALS(100, MathLib::toBigUNumber("10E+1"));
ASSERT_EQUALS(1, MathLib::toBigUNumber("10E-1"));
ASSERT_EQUALS(100, MathLib::toBigUNumber("+10E+1"));
ASSERT_EQUALS(-1, MathLib::toBigUNumber("-10E-1"));
ASSERT_EQUALS(100, MathLib::toBigUNumber("+10.E+1"));
ASSERT_EQUALS(-1, MathLib::toBigUNumber("-10.E-1"));
ASSERT_EQUALS(100, MathLib::toBigUNumber("+10.0E+1"));
ASSERT_EQUALS(-1, MathLib::toBigUNumber("-10.0E-1"));
// from char
ASSERT_EQUALS((int)('A'), MathLib::toBigUNumber("'A'"));
ASSERT_EQUALS((int)('\x10'), MathLib::toBigUNumber("'\\x10'"));
ASSERT_EQUALS((int)('\100'), MathLib::toBigUNumber("'\\100'"));
ASSERT_EQUALS((int)('\200'), MathLib::toBigUNumber("'\\200'"));
ASSERT_EQUALS((int)(L'A'), MathLib::toBigUNumber("L'A'"));
ASSERT_EQUALS(9894494448401390090ULL, MathLib::toBigUNumber("0x89504e470d0a1a0a"));
ASSERT_EQUALS(9965707617509186058ULL, MathLib::toBigUNumber("0x8a4d4e470d0a1a0a"));
// from long long
/*
* ASSERT_EQUALS(0xFF00000000000000LL, MathLib::toBigUNumber("0xFF00000000000000LL"));
* This does not work in a portable way!
* While it succeeds on 32bit Visual Studio it fails on Linux 64bit because it is greater than 0x7FFFFFFFFFFFFFFF (=LLONG_MAX)
*/
ASSERT_EQUALS(0x0A00000000000000LL, MathLib::toBigUNumber("0x0A00000000000000LL"));
// min/max numeric limits
ASSERT_EQUALS(std::numeric_limits<long long>::min(),
MathLib::toBigUNumber(std::to_string(std::numeric_limits<long long>::min())));
ASSERT_EQUALS(std::numeric_limits<long long>::max(),
MathLib::toBigUNumber(std::to_string(std::numeric_limits<long long>::max())));
ASSERT_EQUALS(std::numeric_limits<unsigned long long>::min(),
MathLib::toBigUNumber(std::to_string(std::numeric_limits<unsigned long long>::min())));
ASSERT_EQUALS(std::numeric_limits<unsigned long long>::max(),
MathLib::toBigUNumber(std::to_string(std::numeric_limits<unsigned long long>::max())));
// min/max and out-of-bounds - hex
{
constexpr MathLib::biguint u = 0xFFFFFFFFFFFFFFFF;
ASSERT_EQUALS(u, MathLib::toBigUNumber(std::to_string(u)));
ASSERT_EQUALS(u, MathLib::toBigUNumber("0xFFFFFFFFFFFFFFFF"));
}
{
constexpr MathLib::biguint u = -0xFFFFFFFFFFFFFFFF;
ASSERT_EQUALS(u, MathLib::toBigUNumber(std::to_string(u)));
ASSERT_EQUALS(u, MathLib::toBigUNumber("-0xFFFFFFFFFFFFFFFF"));
}
ASSERT_THROW_INTERNAL_EQUALS(MathLib::toBigUNumber("0x10000000000000000"), INTERNAL, "Internal Error. MathLib::toBigUNumber: out_of_range: 0x10000000000000000");
ASSERT_THROW_INTERNAL_EQUALS(MathLib::toBigUNumber("-0x10000000000000000"), INTERNAL, "Internal Error. MathLib::toBigUNumber: out_of_range: -0x10000000000000000");
// min/max and out-of-bounds - octal
{
constexpr MathLib::biguint u = 01777777777777777777777;
ASSERT_EQUALS(u, MathLib::toBigUNumber(std::to_string(u)));
ASSERT_EQUALS(u, MathLib::toBigUNumber("01777777777777777777777"));
}
{
constexpr MathLib::biguint u = -01777777777777777777777;
ASSERT_EQUALS(u, MathLib::toBigUNumber(std::to_string(u)));
ASSERT_EQUALS(u, MathLib::toBigUNumber("-01777777777777777777777"));
}
ASSERT_THROW_INTERNAL_EQUALS(MathLib::toBigUNumber("02000000000000000000000"), INTERNAL, "Internal Error. MathLib::toBigUNumber: out_of_range: 02000000000000000000000");
ASSERT_THROW_INTERNAL_EQUALS(MathLib::toBigUNumber("-02000000000000000000000"), INTERNAL, "Internal Error. MathLib::toBigUNumber: out_of_range: -02000000000000000000000");
// min/max and out-of-bounds - decimal
SUPPRESS_WARNING_CLANG_PUSH("-Wimplicitly-unsigned-literal")
SUPPRESS_WARNING_GCC_PUSH("-Woverflow")
{
constexpr MathLib::biguint u = 18446744073709551615;
ASSERT_EQUALS(u, MathLib::toBigUNumber(std::to_string(u)));
ASSERT_EQUALS(u, MathLib::toBigUNumber("18446744073709551615"));
}
{
constexpr MathLib::biguint u = -18446744073709551615;
ASSERT_EQUALS(u, MathLib::toBigUNumber(std::to_string(u)));
ASSERT_EQUALS(u, MathLib::toBigUNumber("-18446744073709551615"));
}
SUPPRESS_WARNING_GCC_POP
SUPPRESS_WARNING_CLANG_POP
ASSERT_THROW_INTERNAL_EQUALS(MathLib::toBigUNumber("18446744073709551616"), INTERNAL, "Internal Error. MathLib::toBigUNumber: out_of_range: 18446744073709551616");
ASSERT_THROW_INTERNAL_EQUALS(MathLib::toBigUNumber("-18446744073709551616"), INTERNAL, "Internal Error. MathLib::toBigUNumber: out_of_range: -18446744073709551616");
ASSERT_THROW_INTERNAL_EQUALS(MathLib::toBigUNumber("invalid"), INTERNAL, "Internal Error. MathLib::toBigUNumber: invalid_argument: invalid");
ASSERT_THROW_INTERNAL_EQUALS(MathLib::toBigUNumber("1invalid"), INTERNAL, "Internal Error. MathLib::toBigUNumber: input was not completely consumed: 1invalid");
ASSERT_THROW_INTERNAL_EQUALS(MathLib::toBigUNumber("1 invalid"), INTERNAL, "Internal Error. MathLib::toBigUNumber: input was not completely consumed: 1 invalid");
// TODO: test binary
// TODO: test floating point
// TODO: test with 128-bit values
}
void toDoubleNumber() const {
// float values
ASSERT_EQUALS_DOUBLE(1.0, MathLib::toDoubleNumber("1."), 0.001);
ASSERT_EQUALS_DOUBLE(1.0, MathLib::toDoubleNumber("1.f"), 0.001);
ASSERT_EQUALS_DOUBLE(1.0, MathLib::toDoubleNumber("1.F"), 0.001);
ASSERT_EQUALS_DOUBLE(1.0, MathLib::toDoubleNumber("1.l"), 0.001);
ASSERT_EQUALS_DOUBLE(1.0, MathLib::toDoubleNumber("1.L"), 0.001);
ASSERT_EQUALS_DOUBLE(1.0, MathLib::toDoubleNumber("1.0"), 0.001);
ASSERT_EQUALS_DOUBLE(1.0, MathLib::toDoubleNumber("1.0f"), 0.001);
ASSERT_EQUALS_DOUBLE(1.0, MathLib::toDoubleNumber("1.0F"), 0.001);
ASSERT_EQUALS_DOUBLE(1.0, MathLib::toDoubleNumber("1.0l"), 0.001);
ASSERT_EQUALS_DOUBLE(1.0, MathLib::toDoubleNumber("1.0L"), 0.001);
ASSERT_EQUALS_DOUBLE(1.0, MathLib::toDoubleNumber("0x1"), 0.001);
ASSERT_EQUALS_DOUBLE(10.0, MathLib::toDoubleNumber("10"), 0.001);
ASSERT_EQUALS_DOUBLE(1000.0, MathLib::toDoubleNumber("10E+2"), 0.001);
ASSERT_EQUALS_DOUBLE(1000.0, MathLib::toDoubleNumber("10E+2l"), 0.001);
ASSERT_EQUALS_DOUBLE(1000.0, MathLib::toDoubleNumber("10E+2L"), 0.001);
ASSERT_EQUALS_DOUBLE(100.0, MathLib::toDoubleNumber("1.0E+2"), 0.001);
ASSERT_EQUALS_DOUBLE(-100.0, MathLib::toDoubleNumber("-1.0E+2"), 0.001);
ASSERT_EQUALS_DOUBLE(-1e+10, MathLib::toDoubleNumber("-1.0E+10"), 1);
ASSERT_EQUALS_DOUBLE(100.0, MathLib::toDoubleNumber("+1.0E+2"), 0.001);
ASSERT_EQUALS_DOUBLE(1e+10, MathLib::toDoubleNumber("+1.0E+10"), 1);
ASSERT_EQUALS_DOUBLE(100.0, MathLib::toDoubleNumber("1.0E+2"), 0.001);
ASSERT_EQUALS_DOUBLE(1e+10, MathLib::toDoubleNumber("1.0E+10"), 1);
// valid non-float values
ASSERT_EQUALS_DOUBLE(1.0, MathLib::toDoubleNumber("1"), 0.001);
ASSERT_EQUALS_DOUBLE(1.0, MathLib::toDoubleNumber("1l"), 0.001);
ASSERT_EQUALS_DOUBLE(1.0, MathLib::toDoubleNumber("1L"), 0.001);
ASSERT_EQUALS_DOUBLE(1.0, MathLib::toDoubleNumber("1ll"), 0.001);
ASSERT_EQUALS_DOUBLE(1.0, MathLib::toDoubleNumber("1LL"), 0.001);
ASSERT_EQUALS_DOUBLE(1.0, MathLib::toDoubleNumber("1u"), 0.001);
ASSERT_EQUALS_DOUBLE(1.0, MathLib::toDoubleNumber("1U"), 0.001);
ASSERT_EQUALS_DOUBLE(1.0, MathLib::toDoubleNumber("1ul"), 0.001);
ASSERT_EQUALS_DOUBLE(1.0, MathLib::toDoubleNumber("1UL"), 0.001);
ASSERT_EQUALS_DOUBLE(1.0, MathLib::toDoubleNumber("1ULL"), 0.001);
// TODO: make these work with libc++
#ifndef _LIBCPP_VERSION
ASSERT_EQUALS_DOUBLE(1.0, MathLib::toDoubleNumber("1i64"), 0.001);
ASSERT_EQUALS_DOUBLE(1.0, MathLib::toDoubleNumber("1I64"), 0.001);
ASSERT_EQUALS_DOUBLE(1.0, MathLib::toDoubleNumber("1ui64"), 0.001);
ASSERT_EQUALS_DOUBLE(1.0, MathLib::toDoubleNumber("1UI64"), 0.001);
ASSERT_EQUALS_DOUBLE(1.0, MathLib::toDoubleNumber("1I64"), 0.001);
#endif
ASSERT_EQUALS_DOUBLE(0.0, MathLib::toDoubleNumber("0E+0"), 0.000001);
ASSERT_EQUALS_DOUBLE(0.0, MathLib::toDoubleNumber("0E-0"), 0.000001);
ASSERT_EQUALS_DOUBLE(0.0, MathLib::toDoubleNumber("0E+00"), 0.000001);
ASSERT_EQUALS_DOUBLE(0.0, MathLib::toDoubleNumber("0E-00"), 0.000001);
ASSERT_EQUALS_DOUBLE(0.0, MathLib::toDoubleNumber("-0E+00"), 0.000001);
ASSERT_EQUALS_DOUBLE(0.0, MathLib::toDoubleNumber("+0E-00"), 0.000001);
ASSERT_EQUALS_DOUBLE(0.0, MathLib::toDoubleNumber("0"), 0.000001);
ASSERT_EQUALS_DOUBLE(0.0, MathLib::toDoubleNumber("0."), 0.000001);
ASSERT_EQUALS_DOUBLE(0.0, MathLib::toDoubleNumber("0.0"), 0.000001);
ASSERT_EQUALS_DOUBLE(0.0, MathLib::toDoubleNumber("-0"), 0.000001);
ASSERT_EQUALS_DOUBLE(0.0, MathLib::toDoubleNumber("+0"), 0.000001);
ASSERT_EQUALS_DOUBLE(0.0, MathLib::toDoubleNumber("-0."), 0.000001);
ASSERT_EQUALS_DOUBLE(0.0, MathLib::toDoubleNumber("+0."), 0.000001);
ASSERT_EQUALS_DOUBLE(0.0, MathLib::toDoubleNumber("-0.0"), 0.000001);
ASSERT_EQUALS_DOUBLE(0.0, MathLib::toDoubleNumber("+0.0"), 0.000001);
ASSERT_EQUALS_DOUBLE('0', MathLib::toDoubleNumber("'0'"), 0.000001);
ASSERT_EQUALS_DOUBLE(L'0', MathLib::toDoubleNumber("L'0'"), 0.000001);
ASSERT_EQUALS_DOUBLE(192, MathLib::toDoubleNumber("0x0.3p10"), 0.000001);
ASSERT_EQUALS_DOUBLE(5.42101e-20, MathLib::toDoubleNumber("0x1p-64"), 1e-20);
ASSERT_EQUALS_DOUBLE(3.14159, MathLib::toDoubleNumber("0x1.921fb5p+1"), 0.000001);
ASSERT_EQUALS_DOUBLE(2006, MathLib::toDoubleNumber("0x1.f58000p+10"), 0.000001);
ASSERT_EQUALS_DOUBLE(1e-010, MathLib::toDoubleNumber("0x1.b7cdfep-34"), 0.000001);
ASSERT_EQUALS_DOUBLE(.484375, MathLib::toDoubleNumber("0x1.fp-2"), 0.000001);
ASSERT_EQUALS_DOUBLE(9.0, MathLib::toDoubleNumber("0x1.2P3"), 0.000001);
ASSERT_EQUALS_DOUBLE(0.0625, MathLib::toDoubleNumber("0x.1P0"), 0.000001);
// from char
ASSERT_EQUALS_DOUBLE((double)('A'), MathLib::toDoubleNumber("'A'"), 0.000001);
ASSERT_EQUALS_DOUBLE((double)('\x10'), MathLib::toDoubleNumber("'\\x10'"), 0.000001);
ASSERT_EQUALS_DOUBLE((double)('\100'), MathLib::toDoubleNumber("'\\100'"), 0.000001);
ASSERT_EQUALS_DOUBLE((double)('\200'), MathLib::toDoubleNumber("'\\200'"), 0.000001);
ASSERT_EQUALS_DOUBLE((double)(L'A'), MathLib::toDoubleNumber("L'A'"), 0.000001);
ASSERT_THROW_INTERNAL_EQUALS(MathLib::toDoubleNumber("invalid"), INTERNAL, "Internal Error. MathLib::toDoubleNumber: conversion failed: invalid");
#if defined(_LIBCPP_VERSION) && (defined(__APPLE__) && defined(__MACH__))
ASSERT_THROW_INTERNAL_EQUALS(MathLib::toDoubleNumber("1invalid"), INTERNAL, "Internal Error. MathLib::toDoubleNumber: conversion failed: 1invalid");
ASSERT_THROW_INTERNAL_EQUALS(MathLib::toDoubleNumber("1.1invalid"), INTERNAL, "Internal Error. MathLib::toDoubleNumber: conversion failed: 1.1invalid");
#else
ASSERT_THROW_INTERNAL_EQUALS(MathLib::toDoubleNumber("1invalid"), INTERNAL, "Internal Error. MathLib::toDoubleNumber: input was not completely consumed: 1invalid");
ASSERT_THROW_INTERNAL_EQUALS(MathLib::toDoubleNumber("1.1invalid"), INTERNAL, "Internal Error. MathLib::toDoubleNumber: input was not completely consumed: 1.1invalid");
#endif
ASSERT_THROW_INTERNAL_EQUALS(MathLib::toDoubleNumber("1 invalid"), INTERNAL, "Internal Error. MathLib::toDoubleNumber: input was not completely consumed: 1 invalid");
ASSERT_THROW_INTERNAL_EQUALS(MathLib::toDoubleNumber("-1e-08.0"), INTERNAL, "Internal Error. MathLib::toDoubleNumber: input was not completely consumed: -1e-08.0");
// invalid suffices
#ifdef _LIBCPP_VERSION
ASSERT_THROW_INTERNAL_EQUALS(MathLib::toDoubleNumber("1f"), INTERNAL, "Internal Error. MathLib::toDoubleNumber: conversion failed: 1f");
ASSERT_THROW_INTERNAL_EQUALS(MathLib::toDoubleNumber("1F"), INTERNAL, "Internal Error. MathLib::toDoubleNumber: conversion failed: 1F");
ASSERT_THROW_INTERNAL_EQUALS(MathLib::toDoubleNumber("1.ff"), INTERNAL, "Internal Error. MathLib::toDoubleNumber: conversion failed: 1.ff");
ASSERT_THROW_INTERNAL_EQUALS(MathLib::toDoubleNumber("1.FF"), INTERNAL, "Internal Error. MathLib::toDoubleNumber: conversion failed: 1.FF");
ASSERT_THROW_INTERNAL_EQUALS(MathLib::toDoubleNumber("1.0ff"), INTERNAL, "Internal Error. MathLib::toDoubleNumber: conversion failed: 1.0ff");
ASSERT_THROW_INTERNAL_EQUALS(MathLib::toDoubleNumber("1.0FF"), INTERNAL, "Internal Error. MathLib::toDoubleNumber: conversion failed: 1.0FF");
#else
ASSERT_THROW_INTERNAL_EQUALS(MathLib::toDoubleNumber("1f"), INTERNAL, "Internal Error. MathLib::toDoubleNumber: input was not completely consumed: 1f");
ASSERT_THROW_INTERNAL_EQUALS(MathLib::toDoubleNumber("1F"), INTERNAL, "Internal Error. MathLib::toDoubleNumber: input was not completely consumed: 1F");
ASSERT_THROW_INTERNAL_EQUALS(MathLib::toDoubleNumber("1.ff"), INTERNAL, "Internal Error. MathLib::toDoubleNumber: input was not completely consumed: 1.ff");
ASSERT_THROW_INTERNAL_EQUALS(MathLib::toDoubleNumber("1.FF"), INTERNAL, "Internal Error. MathLib::toDoubleNumber: input was not completely consumed: 1.FF");
ASSERT_THROW_INTERNAL_EQUALS(MathLib::toDoubleNumber("1.0ff"), INTERNAL, "Internal Error. MathLib::toDoubleNumber: input was not completely consumed: 1.0ff");
ASSERT_THROW_INTERNAL_EQUALS(MathLib::toDoubleNumber("1.0FF"), INTERNAL, "Internal Error. MathLib::toDoubleNumber: input was not completely consumed: 1.0FF");
#endif
// TODO: needs to fail
//ASSERT_THROW_INTERNAL_EQUALS(MathLib::toDoubleNumber("1.ll"), INTERNAL, "Internal Error. MathLib::toDoubleNumber: input was not completely consumed: 1.ll");
//ASSERT_THROW_INTERNAL_EQUALS(MathLib::toDoubleNumber("1.0LL"), INTERNAL, "Internal Error. MathLib::toDoubleNumber: input was not completely consumed: 1.0LL");
//ASSERT_THROW_INTERNAL_EQUALS(MathLib::toDoubleNumber("1.0ll"), INTERNAL, "Internal Error. MathLib::toDoubleNumber: input was not completely consumed: 1.0ll");
//ASSERT_THROW_INTERNAL_EQUALS(MathLib::toDoubleNumber("1.0LL"), INTERNAL, "Internal Error. MathLib::toDoubleNumber: input was not completely consumed: 1.0LL");
// verify: string --> double --> string conversion
// TODO: add L, min/max
ASSERT_EQUALS("1.0", MathLib::toString(MathLib::toDoubleNumber("1.0f")));
ASSERT_EQUALS("1.0", MathLib::toString(MathLib::toDoubleNumber("1.0")));
ASSERT_EQUALS("0.0", MathLib::toString(MathLib::toDoubleNumber("0.0f")));
ASSERT_EQUALS("0.0", MathLib::toString(MathLib::toDoubleNumber("0.0")));
ASSERT_EQUALS("-1.0", MathLib::toString(MathLib::toDoubleNumber("-1.0f")));
ASSERT_EQUALS("-1.0", MathLib::toString(MathLib::toDoubleNumber("-1.0")));
ASSERT_EQUALS("0.0", MathLib::toString(MathLib::toDoubleNumber("-0.0f")));
ASSERT_EQUALS("0.0", MathLib::toString(MathLib::toDoubleNumber("-0.0")));
ASSERT_EQUALS("1.0", MathLib::toString(MathLib::toDoubleNumber("+1.0f")));
ASSERT_EQUALS("1.0", MathLib::toString(MathLib::toDoubleNumber("+1.0")));
ASSERT_EQUALS("0.0", MathLib::toString(MathLib::toDoubleNumber("+0.0f")));
ASSERT_EQUALS("0.0", MathLib::toString(MathLib::toDoubleNumber("+0.0")));
ASSERT_EQUALS("0.0", MathLib::toString(MathLib::toDoubleNumber("-0")));
ASSERT_EQUALS("0.0", MathLib::toString(MathLib::toDoubleNumber("-0.")));
ASSERT_EQUALS("0.0", MathLib::toString(MathLib::toDoubleNumber("-0.0")));
}
void isint() const {
// zero tests
ASSERT_EQUALS(true, MathLib::isInt("0"));
ASSERT_EQUALS(false, MathLib::isInt("0."));
ASSERT_EQUALS(false, MathLib::isInt("0.0"));
ASSERT_EQUALS(false, MathLib::isInt("-0."));
ASSERT_EQUALS(false, MathLib::isInt("+0."));
ASSERT_EQUALS(false, MathLib::isInt("-0.0"));
ASSERT_EQUALS(false, MathLib::isInt("+0.0"));
ASSERT_EQUALS(false, MathLib::isInt("+0.0E+1"));
ASSERT_EQUALS(false, MathLib::isInt("+0.0E-1"));
ASSERT_EQUALS(false, MathLib::isInt("-0.0E+1"));
ASSERT_EQUALS(false, MathLib::isInt("-0.0E-1"));
ASSERT_EQUALS(true, MathLib::isInt("1"));
ASSERT_EQUALS(true, MathLib::isInt("-1"));
ASSERT_EQUALS(true, MathLib::isInt("+1"));
ASSERT_EQUALS(false, MathLib::isInt("+1E+1"));
ASSERT_EQUALS(false, MathLib::isInt("+1E+10000"));
ASSERT_EQUALS(false, MathLib::isInt("-1E+1"));
ASSERT_EQUALS(false, MathLib::isInt("-1E+10000"));
ASSERT_EQUALS(false, MathLib::isInt("-1E-1"));
ASSERT_EQUALS(false, MathLib::isInt("-1E-10000"));
ASSERT_EQUALS(true, MathLib::isInt("0xff"));
ASSERT_EQUALS(true, MathLib::isInt("0xa"));
ASSERT_EQUALS(true, MathLib::isInt("0b1000"));
ASSERT_EQUALS(true, MathLib::isInt("0B1000"));
ASSERT_EQUALS(true, MathLib::isInt("0l"));
ASSERT_EQUALS(true, MathLib::isInt("0L"));
ASSERT_EQUALS(true, MathLib::isInt("0ul"));
ASSERT_EQUALS(true, MathLib::isInt("0ull"));
ASSERT_EQUALS(true, MathLib::isInt("0llu"));
ASSERT_EQUALS(true, MathLib::isInt("333L"));
ASSERT_EQUALS(true, MathLib::isInt("330L"));
ASSERT_EQUALS(true, MathLib::isInt("330llu"));
ASSERT_EQUALS(true, MathLib::isInt("07"));
ASSERT_EQUALS(true, MathLib::isInt("0123"));
ASSERT_EQUALS(false, MathLib::isInt("0.4"));
ASSERT_EQUALS(false, MathLib::isInt("2352.3f"));
ASSERT_EQUALS(false, MathLib::isInt("0.00004"));
ASSERT_EQUALS(false, MathLib::isInt("2352.00001f"));
ASSERT_EQUALS(false, MathLib::isInt(".4"));
ASSERT_EQUALS(false, MathLib::isInt("1.0E+1"));
ASSERT_EQUALS(false, MathLib::isInt("1.0E-1"));
ASSERT_EQUALS(false, MathLib::isInt("-1.0E+1"));
ASSERT_EQUALS(false, MathLib::isInt("+1.0E-1"));
ASSERT_EQUALS(false, MathLib::isInt("-1.E+1"));
ASSERT_EQUALS(false, MathLib::isInt("+1.E-1"));
ASSERT_EQUALS(false, MathLib::isInt(" 1.0E+1"));
// with whitespace in front
ASSERT_EQUALS(false, MathLib::isInt(" 1.0E-1"));
ASSERT_EQUALS(false, MathLib::isInt(" -1.0E+1"));
ASSERT_EQUALS(false, MathLib::isInt(" +1.0E-1"));
ASSERT_EQUALS(false, MathLib::isInt(" -1.E+1"));
ASSERT_EQUALS(false, MathLib::isInt(" +1.E-1"));
// with whitespace in front and end
ASSERT_EQUALS(false, MathLib::isInt(" 1.0E-1 "));
ASSERT_EQUALS(false, MathLib::isInt(" -1.0E+1 "));
ASSERT_EQUALS(false, MathLib::isInt(" +1.0E-1 "));
ASSERT_EQUALS(false, MathLib::isInt(" -1.E+1 "));
ASSERT_EQUALS(false, MathLib::isInt(" +1.E-1 "));
// with whitespace in front and end
ASSERT_EQUALS(false, MathLib::isInt("1.0E-1 "));
ASSERT_EQUALS(false, MathLib::isInt("-1.0E+1 "));
ASSERT_EQUALS(false, MathLib::isInt("+1.0E-1 "));
ASSERT_EQUALS(false, MathLib::isInt("-1.E+1 "));
ASSERT_EQUALS(false, MathLib::isInt("+1.E-1 "));
// test some garbage
ASSERT_EQUALS(false, MathLib::isInt("u"));
ASSERT_EQUALS(false, MathLib::isInt("l"));
ASSERT_EQUALS(false, MathLib::isInt("ul"));
ASSERT_EQUALS(false, MathLib::isInt("ll"));
ASSERT_EQUALS(false, MathLib::isInt("U"));
ASSERT_EQUALS(false, MathLib::isInt("L"));
ASSERT_EQUALS(false, MathLib::isInt("uL"));
ASSERT_EQUALS(false, MathLib::isInt("LL"));
ASSERT_EQUALS(false, MathLib::isInt("e2"));
ASSERT_EQUALS(false, MathLib::isInt("E2"));
ASSERT_EQUALS(false, MathLib::isInt(".e2"));
ASSERT_EQUALS(false, MathLib::isInt(".E2"));
ASSERT_EQUALS(false, MathLib::isInt("0x"));
ASSERT_EQUALS(false, MathLib::isInt("0xu"));
ASSERT_EQUALS(false, MathLib::isInt("0xl"));
ASSERT_EQUALS(false, MathLib::isInt("0xul"));
// test empty string
ASSERT_EQUALS(false, MathLib::isInt(""));
}
void isbin() const {
// positive testing
ASSERT_EQUALS(true, MathLib::isBin("0b0"));
ASSERT_EQUALS(true, MathLib::isBin("0b1"));
ASSERT_EQUALS(true, MathLib::isBin("+0b1"));
ASSERT_EQUALS(true, MathLib::isBin("-0b1"));
ASSERT_EQUALS(true, MathLib::isBin("0b11010111"));
ASSERT_EQUALS(true, MathLib::isBin("-0b11010111"));
ASSERT_EQUALS(true, MathLib::isBin("0B11010111"));
ASSERT_EQUALS(true, MathLib::isBin("0b11010111u"));
ASSERT_EQUALS(true, MathLib::isBin("0b11010111ul"));
ASSERT_EQUALS(true, MathLib::isBin("0b11010111ull"));
ASSERT_EQUALS(true, MathLib::isBin("0b11010111l"));
ASSERT_EQUALS(true, MathLib::isBin("0b11010111ll"));
ASSERT_EQUALS(true, MathLib::isBin("0b11010111llu"));
ASSERT_EQUALS(true, MathLib::isBin("0b11010111l"));
ASSERT_EQUALS(true, MathLib::isBin("0b11010111lu"));
ASSERT_EQUALS(false, MathLib::isBin("0b11010111lul")); // Suffix LUL not allowed
// negative testing
ASSERT_EQUALS(false, MathLib::isBin("100101bx"));
ASSERT_EQUALS(false, MathLib::isBin("0"));
ASSERT_EQUALS(false, MathLib::isBin("0B"));
ASSERT_EQUALS(false, MathLib::isBin("0C"));
ASSERT_EQUALS(false, MathLib::isBin("+0B"));
ASSERT_EQUALS(false, MathLib::isBin("-0B"));
ASSERT_EQUALS(false, MathLib::isBin("-0Bx"));
ASSERT_EQUALS(false, MathLib::isBin("0b11010111x"));
ASSERT_EQUALS(false, MathLib::isBin("0b11010111ux"));
ASSERT_EQUALS(false, MathLib::isBin("0b11010111lx"));
ASSERT_EQUALS(false, MathLib::isBin("0b11010111lux"));
ASSERT_EQUALS(false, MathLib::isBin("0b11010111ulx"));
ASSERT_EQUALS(false, MathLib::isBin("0b11010111lulx"));
ASSERT_EQUALS(false, MathLib::isBin("0b11010111ullx"));
ASSERT_EQUALS(false, MathLib::isBin("0b11010111lll"));
// test empty string
ASSERT_EQUALS(false, MathLib::isBin(""));
}
void isnegative() const {
ASSERT_EQUALS(true, MathLib::isNegative("-1"));
ASSERT_EQUALS(true, MathLib::isNegative("-1."));
ASSERT_EQUALS(true, MathLib::isNegative("-1.0"));
ASSERT_EQUALS(true, MathLib::isNegative("-1.0E+2"));
ASSERT_EQUALS(true, MathLib::isNegative("-1.0E-2"));
ASSERT_EQUALS(false, MathLib::isNegative("+1"));
ASSERT_EQUALS(false, MathLib::isNegative("+1."));
ASSERT_EQUALS(false, MathLib::isNegative("+1.0"));
ASSERT_EQUALS(false, MathLib::isNegative("+1.0E+2"));
ASSERT_EQUALS(false, MathLib::isNegative("+1.0E-2"));
// test empty string
ASSERT_EQUALS(false, MathLib::isNegative(""));
}
void isoct() const {
// octal number format: [+|-]0[0-7][suffix]
// positive testing
ASSERT_EQUALS(true, MathLib::isOct("010"));
ASSERT_EQUALS(true, MathLib::isOct("+010"));
ASSERT_EQUALS(true, MathLib::isOct("-010"));
ASSERT_EQUALS(true, MathLib::isOct("0175"));
ASSERT_EQUALS(true, MathLib::isOct("+0175"));
ASSERT_EQUALS(true, MathLib::isOct("-0175"));
ASSERT_EQUALS(true, MathLib::isOct("00"));
ASSERT_EQUALS(true, MathLib::isOct("02"));
ASSERT_EQUALS(true, MathLib::isOct("+042"));
ASSERT_EQUALS(true, MathLib::isOct("-042"));
ASSERT_EQUALS(true, MathLib::isOct("+042U"));
ASSERT_EQUALS(true, MathLib::isOct("-042U"));
ASSERT_EQUALS(true, MathLib::isOct("+042L"));
ASSERT_EQUALS(true, MathLib::isOct("-042L"));
ASSERT_EQUALS(true, MathLib::isOct("+042LU"));
ASSERT_EQUALS(true, MathLib::isOct("-042LU"));
ASSERT_EQUALS(true, MathLib::isOct("+042UL"));
ASSERT_EQUALS(true, MathLib::isOct("-042UL"));
ASSERT_EQUALS(true, MathLib::isOct("+042ULL"));
ASSERT_EQUALS(true, MathLib::isOct("-042ULL"));
ASSERT_EQUALS(true, MathLib::isOct("+042LLU"));
ASSERT_EQUALS(true, MathLib::isOct("-042LLU"));
// test empty string
ASSERT_EQUALS(false, MathLib::isOct(""));
// negative testing
ASSERT_EQUALS(false, MathLib::isOct("0"));
ASSERT_EQUALS(false, MathLib::isOct("-0x175"));
ASSERT_EQUALS(false, MathLib::isOct("-0_garbage_"));
ASSERT_EQUALS(false, MathLib::isOct(" "));
ASSERT_EQUALS(false, MathLib::isOct(" "));
ASSERT_EQUALS(false, MathLib::isOct("02."));
ASSERT_EQUALS(false, MathLib::isOct("02E2"));
ASSERT_EQUALS(false, MathLib::isOct("+042x"));
ASSERT_EQUALS(false, MathLib::isOct("-042x"));
ASSERT_EQUALS(false, MathLib::isOct("+042Ux"));
ASSERT_EQUALS(false, MathLib::isOct("-042Ux"));
ASSERT_EQUALS(false, MathLib::isOct("+042Lx"));
ASSERT_EQUALS(false, MathLib::isOct("-042Lx"));
ASSERT_EQUALS(false, MathLib::isOct("+042ULx"));
ASSERT_EQUALS(false, MathLib::isOct("-042ULx"));
ASSERT_EQUALS(false, MathLib::isOct("+042LLx"));
ASSERT_EQUALS(false, MathLib::isOct("-042LLx"));
ASSERT_EQUALS(false, MathLib::isOct("+042ULLx"));
ASSERT_EQUALS(false, MathLib::isOct("-042ULLx"));
ASSERT_EQUALS(false, MathLib::isOct("+042LLUx"));
ASSERT_EQUALS(false, MathLib::isOct("-042LLUx"));
ASSERT_EQUALS(false, MathLib::isOct("+042LUL"));
ASSERT_EQUALS(false, MathLib::isOct("-042LUL"));
// white space in front
ASSERT_EQUALS(false, MathLib::isOct(" -042ULL"));
// trailing white space
ASSERT_EQUALS(false, MathLib::isOct("-042ULL "));
// front and trailing white space
ASSERT_EQUALS(false, MathLib::isOct(" -042ULL "));
ASSERT_EQUALS(false, MathLib::isOct("+042LUL+0"));
}
void isFloatHex() const {
// hex number syntax: [sign]0x[hexnumbers][suffix]
ASSERT_EQUALS(true, MathLib::isFloatHex("0x1.999999999999ap-4"));
ASSERT_EQUALS(true, MathLib::isFloatHex("0x0.3p10"));
ASSERT_EQUALS(true, MathLib::isFloatHex("0x1.fp3"));
ASSERT_EQUALS(true, MathLib::isFloatHex("0x1P-1"));
ASSERT_EQUALS(true, MathLib::isFloatHex("0xcc.ccccccccccdp-11"));
ASSERT_EQUALS(true, MathLib::isFloatHex("0x3.243F6A88p+03"));
ASSERT_EQUALS(true, MathLib::isFloatHex("0xA.Fp-10"));
ASSERT_EQUALS(true, MathLib::isFloatHex("0x1.2p-10f"));
ASSERT_EQUALS(true, MathLib::isFloatHex("0x1.2p+10F"));
ASSERT_EQUALS(true, MathLib::isFloatHex("0x1.2p+10l"));
ASSERT_EQUALS(true, MathLib::isFloatHex("0x1.2p+10L"));
ASSERT_EQUALS(true, MathLib::isFloatHex("0X.2p-0"));
ASSERT_EQUALS(false, MathLib::isFloatHex(""));
ASSERT_EQUALS(false, MathLib::isFloatHex("0"));
ASSERT_EQUALS(false, MathLib::isFloatHex("0x"));
ASSERT_EQUALS(false, MathLib::isFloatHex("0xa"));
ASSERT_EQUALS(false, MathLib::isFloatHex("+0x"));
ASSERT_EQUALS(false, MathLib::isFloatHex("-0x"));
ASSERT_EQUALS(false, MathLib::isFloatHex("0x"));
ASSERT_EQUALS(false, MathLib::isFloatHex("0x."));
ASSERT_EQUALS(false, MathLib::isFloatHex("0XP"));
ASSERT_EQUALS(false, MathLib::isFloatHex("0xx"));
ASSERT_EQUALS(false, MathLib::isFloatHex("0x1P+-1"));
ASSERT_EQUALS(false, MathLib::isFloatHex("0x1p+10e"));
ASSERT_EQUALS(false, MathLib::isFloatHex("0x1p+1af"));
ASSERT_EQUALS(false, MathLib::isFloatHex("0x1p+10LL"));
}
void isIntHex() const {
// hex number syntax: [sign]0x[hexnumbers][suffix]
// positive testing
ASSERT_EQUALS(true, MathLib::isIntHex("0xa"));
ASSERT_EQUALS(true, MathLib::isIntHex("0x2AF3"));
ASSERT_EQUALS(true, MathLib::isIntHex("-0xa"));
ASSERT_EQUALS(true, MathLib::isIntHex("-0x2AF3"));
ASSERT_EQUALS(true, MathLib::isIntHex("+0xa"));
ASSERT_EQUALS(true, MathLib::isIntHex("+0x2AF3"));
ASSERT_EQUALS(true, MathLib::isIntHex("0x0"));
ASSERT_EQUALS(true, MathLib::isIntHex("+0x0"));
ASSERT_EQUALS(true, MathLib::isIntHex("-0x0"));
ASSERT_EQUALS(true, MathLib::isIntHex("+0x0U"));
ASSERT_EQUALS(true, MathLib::isIntHex("-0x0U"));
ASSERT_EQUALS(true, MathLib::isIntHex("+0x0L"));
ASSERT_EQUALS(true, MathLib::isIntHex("-0x0L"));
ASSERT_EQUALS(true, MathLib::isIntHex("+0x0LU"));
ASSERT_EQUALS(true, MathLib::isIntHex("-0x0LU"));
ASSERT_EQUALS(true, MathLib::isIntHex("+0x0UL"));
ASSERT_EQUALS(true, MathLib::isIntHex("-0x0UL"));
ASSERT_EQUALS(true, MathLib::isIntHex("+0x0LL"));
ASSERT_EQUALS(true, MathLib::isIntHex("-0x0LL"));
ASSERT_EQUALS(true, MathLib::isIntHex("+0x0ULL"));
ASSERT_EQUALS(true, MathLib::isIntHex("-0x0ULL"));
ASSERT_EQUALS(true, MathLib::isIntHex("+0x0LLU"));
ASSERT_EQUALS(true, MathLib::isIntHex("-0x0LLU"));
ASSERT_EQUALS(true, MathLib::isIntHex("+0x0Z"));
ASSERT_EQUALS(true, MathLib::isIntHex("-0x0Z"));
ASSERT_EQUALS(true, MathLib::isIntHex("+0x0ZU"));
ASSERT_EQUALS(true, MathLib::isIntHex("-0x0ZU"));
ASSERT_EQUALS(true, MathLib::isIntHex("+0x0UZ"));
ASSERT_EQUALS(true, MathLib::isIntHex("-0x0UZ"));
ASSERT_EQUALS(true, MathLib::isIntHex("+0x0Uz"));
ASSERT_EQUALS(true, MathLib::isIntHex("-0x0Uz"));
// negative testing
ASSERT_EQUALS(false, MathLib::isIntHex("+0x"));
ASSERT_EQUALS(false, MathLib::isIntHex("-0x"));
ASSERT_EQUALS(false, MathLib::isIntHex("0x"));
ASSERT_EQUALS(false, MathLib::isIntHex("0xl"));
ASSERT_EQUALS(false, MathLib::isIntHex("0xx"));
ASSERT_EQUALS(false, MathLib::isIntHex("-0175"));
ASSERT_EQUALS(false, MathLib::isIntHex("-0_garbage_"));
ASSERT_EQUALS(false, MathLib::isIntHex(" "));
ASSERT_EQUALS(false, MathLib::isIntHex(" "));
ASSERT_EQUALS(false, MathLib::isIntHex("0"));
ASSERT_EQUALS(false, MathLib::isIntHex("+0x0Lz"));
ASSERT_EQUALS(false, MathLib::isIntHex("-0x0Lz"));
ASSERT_EQUALS(false, MathLib::isIntHex("+0x0LUz"));
ASSERT_EQUALS(false, MathLib::isIntHex("-0x0LUz"));
ASSERT_EQUALS(false, MathLib::isIntHex("+0x0ULz"));
ASSERT_EQUALS(false, MathLib::isIntHex("-0x0ULz"));
ASSERT_EQUALS(false, MathLib::isIntHex("+0x0LLz"));
ASSERT_EQUALS(false, MathLib::isIntHex("-0x0LLz"));
ASSERT_EQUALS(false, MathLib::isIntHex("+0x0ULLz"));
ASSERT_EQUALS(false, MathLib::isIntHex("-0x0ULLz"));
ASSERT_EQUALS(false, MathLib::isIntHex("+0x0LLUz"));
ASSERT_EQUALS(false, MathLib::isIntHex("-0x0LLUz"));
ASSERT_EQUALS(false, MathLib::isIntHex("0x0+0"));
ASSERT_EQUALS(false, MathLib::isIntHex("e2"));
ASSERT_EQUALS(false, MathLib::isIntHex("+E2"));
// test empty string
ASSERT_EQUALS(false, MathLib::isIntHex(""));
}
void isValidIntegerSuffix() const {
// negative testing
ASSERT_EQUALS(false, MathLib::isValidIntegerSuffix(""));
ASSERT_EQUALS(false, MathLib::isValidIntegerSuffix("ux"));
ASSERT_EQUALS(false, MathLib::isValidIntegerSuffix("ulx"));
ASSERT_EQUALS(false, MathLib::isValidIntegerSuffix("uu"));
ASSERT_EQUALS(false, MathLib::isValidIntegerSuffix("lx"));
ASSERT_EQUALS(false, MathLib::isValidIntegerSuffix("lux"));
ASSERT_EQUALS(false, MathLib::isValidIntegerSuffix("lll"));
ASSERT_EQUALS(false, MathLib::isValidIntegerSuffix("garbage"));
ASSERT_EQUALS(false, MathLib::isValidIntegerSuffix("llu "));
ASSERT_EQUALS(false, MathLib::isValidIntegerSuffix("i"));
ASSERT_EQUALS(false, MathLib::isValidIntegerSuffix("iX"));
ASSERT_EQUALS(false, MathLib::isValidIntegerSuffix("i6X"));
ASSERT_EQUALS(false, MathLib::isValidIntegerSuffix("i64X"));
ASSERT_EQUALS(false, MathLib::isValidIntegerSuffix("i64 "));
ASSERT_EQUALS(false, MathLib::isValidIntegerSuffix("i66"));
// positive testing
ASSERT_EQUALS(true, MathLib::isValidIntegerSuffix("u"));
ASSERT_EQUALS(true, MathLib::isValidIntegerSuffix("ul"));
ASSERT_EQUALS(true, MathLib::isValidIntegerSuffix("ull"));
ASSERT_EQUALS(true, MathLib::isValidIntegerSuffix("uz"));
ASSERT_EQUALS(true, MathLib::isValidIntegerSuffix("l"));
ASSERT_EQUALS(true, MathLib::isValidIntegerSuffix("lu"));
ASSERT_EQUALS(true, MathLib::isValidIntegerSuffix("ll"));
ASSERT_EQUALS(true, MathLib::isValidIntegerSuffix("llu"));
ASSERT_EQUALS(true, MathLib::isValidIntegerSuffix("llU"));
ASSERT_EQUALS(true, MathLib::isValidIntegerSuffix("LLU"));
ASSERT_EQUALS(true, MathLib::isValidIntegerSuffix("z"));
ASSERT_EQUALS(true, MathLib::isValidIntegerSuffix("Z"));
ASSERT_EQUALS(true, MathLib::isValidIntegerSuffix("zu"));
ASSERT_EQUALS(true, MathLib::isValidIntegerSuffix("UZ"));
ASSERT_EQUALS(true, MathLib::isValidIntegerSuffix("ZU"));
// Microsoft extensions:
ASSERT_EQUALS(true, MathLib::isValidIntegerSuffix("i64"));
ASSERT_EQUALS(true, MathLib::isValidIntegerSuffix("I64"));
ASSERT_EQUALS(true, MathLib::isValidIntegerSuffix("ui64"));
ASSERT_EQUALS(true, MathLib::isValidIntegerSuffix("UI64"));
ASSERT_EQUALS(false, MathLib::isValidIntegerSuffix("i64", false));
ASSERT_EQUALS(false, MathLib::isValidIntegerSuffix("I64", false));
ASSERT_EQUALS(false, MathLib::isValidIntegerSuffix("ui64", false));
ASSERT_EQUALS(false, MathLib::isValidIntegerSuffix("UI64", false));
// User defined suffix literals
ASSERT_EQUALS(false, MathLib::isValidIntegerSuffix("_"));
ASSERT_EQUALS(true, MathLib::isValidIntegerSuffix("_MyUserDefinedLiteral"));
}
void ispositive() const {
ASSERT_EQUALS(false, MathLib::isPositive("-1"));
ASSERT_EQUALS(false, MathLib::isPositive("-1."));
ASSERT_EQUALS(false, MathLib::isPositive("-1.0"));
ASSERT_EQUALS(false, MathLib::isPositive("-1.0E+2"));
ASSERT_EQUALS(false, MathLib::isPositive("-1.0E-2"));
ASSERT_EQUALS(true, MathLib::isPositive("+1"));
ASSERT_EQUALS(true, MathLib::isPositive("+1."));
ASSERT_EQUALS(true, MathLib::isPositive("+1.0"));
ASSERT_EQUALS(true, MathLib::isPositive("+1.0E+2"));
ASSERT_EQUALS(true, MathLib::isPositive("+1.0E-2"));
// test empty string
ASSERT_EQUALS(false, MathLib::isPositive("")); // "" is neither positive nor negative
}
void isFloat() const {
ASSERT_EQUALS(false, MathLib::isFloat(""));
ASSERT_EQUALS(true, MathLib::isFloat("0.f"));
ASSERT_EQUALS(true, MathLib::isFloat("0.f"));
ASSERT_EQUALS(true, MathLib::isFloat("0xA.Fp-10"));
// User defined suffix literals
ASSERT_EQUALS(false, MathLib::isFloat("0_"));
ASSERT_EQUALS(false, MathLib::isFloat("0._"));
ASSERT_EQUALS(false, MathLib::isFloat("0.1_"));
ASSERT_EQUALS(true, MathLib::isFloat("0.0_MyUserDefinedLiteral"));
ASSERT_EQUALS(true, MathLib::isFloat("0._MyUserDefinedLiteral"));
}
void isDecimalFloat() const {
ASSERT_EQUALS(false, MathLib::isDecimalFloat(""));
ASSERT_EQUALS(false, MathLib::isDecimalFloat("."));
ASSERT_EQUALS(false, MathLib::isDecimalFloat("..."));
ASSERT_EQUALS(false, MathLib::isDecimalFloat(".e"));
ASSERT_EQUALS(false, MathLib::isDecimalFloat(".e2"));
ASSERT_EQUALS(false, MathLib::isDecimalFloat(".E"));
ASSERT_EQUALS(false, MathLib::isDecimalFloat("+E."));
ASSERT_EQUALS(false, MathLib::isDecimalFloat("+e."));
ASSERT_EQUALS(false, MathLib::isDecimalFloat("-E."));
ASSERT_EQUALS(false, MathLib::isDecimalFloat("-e."));
ASSERT_EQUALS(false, MathLib::isDecimalFloat("-X"));
ASSERT_EQUALS(false, MathLib::isDecimalFloat("+X"));
ASSERT_EQUALS(false, MathLib::isDecimalFloat("-."));
ASSERT_EQUALS(false, MathLib::isDecimalFloat("-."));
ASSERT_EQUALS(false, MathLib::isDecimalFloat("-"));
ASSERT_EQUALS(false, MathLib::isDecimalFloat("+"));
ASSERT_EQUALS(false, MathLib::isDecimalFloat(" "));
ASSERT_EQUALS(false, MathLib::isDecimalFloat("0"));
ASSERT_EQUALS(false, MathLib::isDecimalFloat("0 "));
ASSERT_EQUALS(false, MathLib::isDecimalFloat(" 0 "));
ASSERT_EQUALS(false, MathLib::isDecimalFloat(" 0"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("0."));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("0.f"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("0.F"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("0.l"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("0.L"));
ASSERT_EQUALS(false, MathLib::isDecimalFloat("0. "));
ASSERT_EQUALS(false, MathLib::isDecimalFloat(" 0. "));
ASSERT_EQUALS(false, MathLib::isDecimalFloat(" 0."));
ASSERT_EQUALS(false, MathLib::isDecimalFloat("0.."));
ASSERT_EQUALS(false, MathLib::isDecimalFloat("..0.."));
ASSERT_EQUALS(false, MathLib::isDecimalFloat("..0"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("0.0"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("0.0f"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("0.0F"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("0.0l"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("0.0L"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("-0."));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("+0."));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("-0.0"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("+0.0"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("0E0"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("+0E0"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("+0E0"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("+0E+0"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("+0E-0"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("-0E+0"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("-0E-0"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("+0.0E+1"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("+0.0E-1"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("-0.0E+1"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("-0.0E-1"));
ASSERT_EQUALS(false, MathLib::isDecimalFloat("1"));
ASSERT_EQUALS(false, MathLib::isDecimalFloat("-1"));
ASSERT_EQUALS(false, MathLib::isDecimalFloat("+1"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("+1e+1"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("+1E+1"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("+1E+100"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("+1E+100f"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("+1E+100F"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("+1E+100l"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("+1E+100L"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("+1E+007")); // to be sure about #5485
ASSERT_EQUALS(true, MathLib::isDecimalFloat("+1E+001f"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("+1E+001F"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("+1E+001l"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("+1E+001L"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("+1E+10000"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("-1E+1"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("-1E+10000"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat(".1250E+04"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("-1E-1"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("-1E-10000"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("+1.23e+01"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("+1.23E+01"));
ASSERT_EQUALS(false, MathLib::isDecimalFloat("+1e+x"));
ASSERT_EQUALS(false, MathLib::isDecimalFloat("+1E+X"));
ASSERT_EQUALS(false, MathLib::isDecimalFloat("+1E+001lX"));
ASSERT_EQUALS(false, MathLib::isDecimalFloat("+1E+001LX"));
ASSERT_EQUALS(false, MathLib::isDecimalFloat("+1E+001f2"));
ASSERT_EQUALS(false, MathLib::isDecimalFloat("+1E+001F2"));
ASSERT_EQUALS(false, MathLib::isDecimalFloat("+1e+003x"));
ASSERT_EQUALS(false, MathLib::isDecimalFloat("+1E+003X"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("0.4"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("2352.3f"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("2352.3F"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("2352.3l"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("2352.3L"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("0.00004"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("2352.00001f"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("2352.00001F"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("2352.00001l"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("2352.00001L"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat(".4"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat(".3e2"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("1.0E+1"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("1.0E-1"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("-1.0E+1"));
// User defined suffix literals
ASSERT_EQUALS(false, MathLib::isDecimalFloat("0_"));
ASSERT_EQUALS(false, MathLib::isDecimalFloat(".1_"));
ASSERT_EQUALS(false, MathLib::isDecimalFloat("0.1_"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat("0.0_MyUserDefinedLiteral"));
ASSERT_EQUALS(true, MathLib::isDecimalFloat(".1_MyUserDefinedLiteral"));
}
void naninf() const {
ASSERT_EQUALS("nan.0", MathLib::divide("0.0", "0.0")); // nan
ASSERT_EQUALS("nan.0", MathLib::divide("0.0", "0.f")); // nan (#5875)
ASSERT_EQUALS("nan.0", MathLib::divide("-0.0", "0.f")); // nan (#5875)
ASSERT_EQUALS("nan.0", MathLib::divide("-0.f", "0.f")); // nan (#5875)
ASSERT_EQUALS("nan.0", MathLib::divide("-0.0", "-0.f")); // nan (#5875)
ASSERT_EQUALS("nan.0", MathLib::divide("-.0", "-0.f")); // nan (#5875)
ASSERT_EQUALS("nan.0", MathLib::divide("0.0", "-0.f")); // nan (#5875)
ASSERT_EQUALS("nan.0", MathLib::divide("0.f", "-0.f")); // nan (#5875)
ASSERT_EQUALS("inf.0", MathLib::divide("3.0", "0.0")); // inf
ASSERT_EQUALS("inf.0", MathLib::divide("3.0", "0.f")); // inf (#5875)
ASSERT_EQUALS("-inf.0", MathLib::divide("-3.0", "0.0")); // -inf (#5142)
ASSERT_EQUALS("-inf.0", MathLib::divide("-3.0", "0.0f")); // -inf (#5142)
ASSERT_EQUALS("inf.0", MathLib::divide("-3.0", "-0.0f")); // inf (#5142)
}
void isdec() const {
// positive testing
ASSERT_EQUALS(true, MathLib::isDec("1"));
ASSERT_EQUALS(true, MathLib::isDec("+1"));
ASSERT_EQUALS(true, MathLib::isDec("-1"));
ASSERT_EQUALS(true, MathLib::isDec("-100"));
ASSERT_EQUALS(true, MathLib::isDec("-1L"));
ASSERT_EQUALS(true, MathLib::isDec("1UL"));
// negative testing
ASSERT_EQUALS(false, MathLib::isDec("-1."));
ASSERT_EQUALS(false, MathLib::isDec("+1."));
ASSERT_EQUALS(false, MathLib::isDec("-x"));
ASSERT_EQUALS(false, MathLib::isDec("+x"));
ASSERT_EQUALS(false, MathLib::isDec("x"));
ASSERT_EQUALS(false, MathLib::isDec(""));
// User defined suffix literals
ASSERT_EQUALS(false, MathLib::isDec("0_"));
ASSERT_EQUALS(false, MathLib::isDec("+0_"));
ASSERT_EQUALS(false, MathLib::isDec("-1_"));
ASSERT_EQUALS(true, MathLib::isDec("0_MyUserDefinedLiteral"));
ASSERT_EQUALS(true, MathLib::isDec("+1_MyUserDefinedLiteral"));
ASSERT_EQUALS(true, MathLib::isDec("-1_MyUserDefinedLiteral"));
}
void isNullValue() const {
// inter zero value
ASSERT_EQUALS(true, MathLib::isNullValue("0"));
ASSERT_EQUALS(true, MathLib::isNullValue("+0"));
ASSERT_EQUALS(true, MathLib::isNullValue("-0"));
// inter zero value (octal)
ASSERT_EQUALS(true, MathLib::isNullValue("00"));
ASSERT_EQUALS(true, MathLib::isNullValue("+00"));
ASSERT_EQUALS(true, MathLib::isNullValue("-00"));
// inter zero value (hex)
ASSERT_EQUALS(true, MathLib::isNullValue("0x0"));
ASSERT_EQUALS(true, MathLib::isNullValue("+0x0"));
ASSERT_EQUALS(true, MathLib::isNullValue("-0x0"));
ASSERT_EQUALS(true, MathLib::isNullValue("+0X0"));
ASSERT_EQUALS(true, MathLib::isNullValue("-0X0"));
// unsigned integer zero value
ASSERT_EQUALS(true, MathLib::isNullValue("0U"));
ASSERT_EQUALS(true, MathLib::isNullValue("+0U"));
ASSERT_EQUALS(true, MathLib::isNullValue("-0U"));
// long integer zero value
ASSERT_EQUALS(true, MathLib::isNullValue("0L"));
ASSERT_EQUALS(true, MathLib::isNullValue("+0L"));
ASSERT_EQUALS(true, MathLib::isNullValue("-0L"));
// unsigned long integer zero value
ASSERT_EQUALS(true, MathLib::isNullValue("0UL"));
ASSERT_EQUALS(true, MathLib::isNullValue("+0UL"));
ASSERT_EQUALS(true, MathLib::isNullValue("-0UL"));
// unsigned long integer zero value
ASSERT_EQUALS(true, MathLib::isNullValue("0LU"));
ASSERT_EQUALS(true, MathLib::isNullValue("+0LU"));
ASSERT_EQUALS(true, MathLib::isNullValue("-0LU"));
// long long integer zero value
ASSERT_EQUALS(true, MathLib::isNullValue("0LL"));
ASSERT_EQUALS(true, MathLib::isNullValue("+0LL"));
ASSERT_EQUALS(true, MathLib::isNullValue("-0LL"));
// long long unsigned zero value
ASSERT_EQUALS(true, MathLib::isNullValue("0LLU"));
ASSERT_EQUALS(true, MathLib::isNullValue("+0LLU"));
ASSERT_EQUALS(true, MathLib::isNullValue("-0LLU"));
// unsigned long long zero value
ASSERT_EQUALS(true, MathLib::isNullValue("0ULL"));
ASSERT_EQUALS(true, MathLib::isNullValue("+0ULL"));
ASSERT_EQUALS(true, MathLib::isNullValue("-0ULL"));
// floating pointer zero value (no trailing zero after dot)
ASSERT_EQUALS(true, MathLib::isNullValue("0."));
ASSERT_EQUALS(true, MathLib::isNullValue("+0."));
ASSERT_EQUALS(true, MathLib::isNullValue("-0."));
// floating pointer zero value (1 trailing zero after dot)
ASSERT_EQUALS(true, MathLib::isNullValue("0.0"));
ASSERT_EQUALS(true, MathLib::isNullValue("+0.0"));
ASSERT_EQUALS(true, MathLib::isNullValue("-0.0"));
// floating pointer zero value (3 trailing zeros after dot)
ASSERT_EQUALS(true, MathLib::isNullValue("0.000"));
ASSERT_EQUALS(true, MathLib::isNullValue("+0.000"));
ASSERT_EQUALS(true, MathLib::isNullValue("-0.000"));
// floating pointer zero value (no trailing zero after dot)
ASSERT_EQUALS(true, MathLib::isNullValue("00."));
ASSERT_EQUALS(true, MathLib::isNullValue("+00."));
ASSERT_EQUALS(true, MathLib::isNullValue("-00."));
// floating pointer zero value (1 trailing zero after dot)
ASSERT_EQUALS(true, MathLib::isNullValue("00.0"));
ASSERT_EQUALS(true, MathLib::isNullValue("+00.0"));
ASSERT_EQUALS(true, MathLib::isNullValue("-00.0"));
// floating pointer zero value (3 trailing zero after dot)
ASSERT_EQUALS(true, MathLib::isNullValue("00.000"));
ASSERT_EQUALS(true, MathLib::isNullValue("+00.000"));
ASSERT_EQUALS(true, MathLib::isNullValue("-00.000"));
// floating pointer zero value (3 trailing zero after dot)
ASSERT_EQUALS(true, MathLib::isNullValue(".000"));
// integer scientific notation
ASSERT_EQUALS(true, MathLib::isNullValue("0E0"));
ASSERT_EQUALS(true, MathLib::isNullValue("+0E0"));
ASSERT_EQUALS(true, MathLib::isNullValue("-0E0"));
ASSERT_EQUALS(true, MathLib::isNullValue("+0e0"));
ASSERT_EQUALS(true, MathLib::isNullValue("-0e0"));
// integer scientific notation
ASSERT_EQUALS(true, MathLib::isNullValue("0E1"));
ASSERT_EQUALS(true, MathLib::isNullValue("+0E1"));
ASSERT_EQUALS(true, MathLib::isNullValue("-0E1"));
// integer scientific notation
ASSERT_EQUALS(true, MathLib::isNullValue("0E42"));
ASSERT_EQUALS(true, MathLib::isNullValue("+0E42"));
ASSERT_EQUALS(true, MathLib::isNullValue("-0E42"));
// integer scientific notation
ASSERT_EQUALS(true, MathLib::isNullValue("0E429999"));
ASSERT_EQUALS(true, MathLib::isNullValue("+0E429999"));
ASSERT_EQUALS(true, MathLib::isNullValue("-0E429999"));
// integer scientific notation
ASSERT_EQUALS(true, MathLib::isNullValue("0E+1"));
ASSERT_EQUALS(true, MathLib::isNullValue("+0E+1"));
ASSERT_EQUALS(true, MathLib::isNullValue("-0E+1"));
// integer scientific notation
ASSERT_EQUALS(true, MathLib::isNullValue("0E+42"));
ASSERT_EQUALS(true, MathLib::isNullValue("+0E+42"));
ASSERT_EQUALS(true, MathLib::isNullValue("-0E+42"));
// integer scientific notation
ASSERT_EQUALS(true, MathLib::isNullValue("0E+429999"));
ASSERT_EQUALS(true, MathLib::isNullValue("+0E+429999"));
ASSERT_EQUALS(true, MathLib::isNullValue("-0E+429999"));
// integer scientific notation
ASSERT_EQUALS(true, MathLib::isNullValue("0E-1"));
ASSERT_EQUALS(true, MathLib::isNullValue("+0E-1"));
ASSERT_EQUALS(true, MathLib::isNullValue("-0E-1"));
// integer scientific notation
ASSERT_EQUALS(true, MathLib::isNullValue("0E-42"));
ASSERT_EQUALS(true, MathLib::isNullValue("+0E-42"));
ASSERT_EQUALS(true, MathLib::isNullValue("-0E-42"));
// integer scientific notation
ASSERT_EQUALS(true, MathLib::isNullValue("0E-429999"));
ASSERT_EQUALS(true, MathLib::isNullValue("+0E-429999"));
ASSERT_EQUALS(true, MathLib::isNullValue("-0E-429999"));
// floating point scientific notation
ASSERT_EQUALS(true, MathLib::isNullValue("0.E0"));
ASSERT_EQUALS(true, MathLib::isNullValue("+0.E0"));
ASSERT_EQUALS(true, MathLib::isNullValue("-0.E0"));
// floating point scientific notation
ASSERT_EQUALS(true, MathLib::isNullValue("0.E-0"));
ASSERT_EQUALS(true, MathLib::isNullValue("+0.E-0"));
ASSERT_EQUALS(true, MathLib::isNullValue("-0.E+0"));
// floating point scientific notation
ASSERT_EQUALS(true, MathLib::isNullValue("0.E+0"));
ASSERT_EQUALS(true, MathLib::isNullValue("+0.E+0"));
ASSERT_EQUALS(true, MathLib::isNullValue("-0.E+0"));
// floating point scientific notation
ASSERT_EQUALS(true, MathLib::isNullValue("0.00E-0"));
ASSERT_EQUALS(true, MathLib::isNullValue("+0.00E-0"));
ASSERT_EQUALS(true, MathLib::isNullValue("-0.00E-0"));
// floating point scientific notation
ASSERT_EQUALS(true, MathLib::isNullValue("00000.00E-000000000"));
ASSERT_EQUALS(true, MathLib::isNullValue("+00000.00E-000000000"));
ASSERT_EQUALS(true, MathLib::isNullValue("-00000.00E-000000000"));
// floating point scientific notation (suffix f)
ASSERT_EQUALS(true, MathLib::isNullValue("0.f"));
ASSERT_EQUALS(true, MathLib::isNullValue("+0.f"));
ASSERT_EQUALS(true, MathLib::isNullValue("-0.f"));
// floating point scientific notation (suffix f)
ASSERT_EQUALS(true, MathLib::isNullValue("0.0f"));
ASSERT_EQUALS(true, MathLib::isNullValue("0.0F"));
ASSERT_EQUALS(true, MathLib::isNullValue("+0.0f"));
ASSERT_EQUALS(true, MathLib::isNullValue("-0.0f"));
// floating point scientific notation (suffix f)
ASSERT_EQUALS(true, MathLib::isNullValue("00.0f"));
ASSERT_EQUALS(true, MathLib::isNullValue("+00.0f"));
ASSERT_EQUALS(true, MathLib::isNullValue("-00.0f"));
// floating point scientific notation (suffix f)
ASSERT_EQUALS(true, MathLib::isNullValue("00.00f"));
ASSERT_EQUALS(true, MathLib::isNullValue("+00.00f"));
ASSERT_EQUALS(true, MathLib::isNullValue("-00.00f"));
// floating point scientific notation (suffix f)
ASSERT_EQUALS(true, MathLib::isNullValue("00.00E+1f"));
ASSERT_EQUALS(true, MathLib::isNullValue("+00.00E+1f"));
ASSERT_EQUALS(true, MathLib::isNullValue("-00.00E+1f"));
// hex float
ASSERT_EQUALS(true, MathLib::isNullValue("0x0p3"));
ASSERT_EQUALS(true, MathLib::isNullValue("0X0P3"));
ASSERT_EQUALS(true, MathLib::isNullValue("0X0p-3"));
ASSERT_EQUALS(true, MathLib::isNullValue("-0x0p3"));
ASSERT_EQUALS(true, MathLib::isNullValue("+0x0p3"));
// binary numbers
ASSERT_EQUALS(true, MathLib::isNullValue("0b00"));
ASSERT_EQUALS(true, MathLib::isNullValue("+0b00"));
ASSERT_EQUALS(true, MathLib::isNullValue("-0b00"));
// binary numbers (long)
ASSERT_EQUALS(true, MathLib::isNullValue("0b00L"));
ASSERT_EQUALS(true, MathLib::isNullValue("+0b00L"));
ASSERT_EQUALS(true, MathLib::isNullValue("-0b00L"));
// negative testing
ASSERT_EQUALS(false, MathLib::isNullValue("0.1"));
ASSERT_EQUALS(false, MathLib::isNullValue("1.0"));
ASSERT_EQUALS(false, MathLib::isNullValue("0.01"));
ASSERT_EQUALS(false, MathLib::isNullValue("0xF"));
ASSERT_EQUALS(false, MathLib::isNullValue("0XFF"));
ASSERT_EQUALS(false, MathLib::isNullValue("0b01"));
ASSERT_EQUALS(false, MathLib::isNullValue("0B01"));
ASSERT_EQUALS(false, MathLib::isNullValue("0x1p0"));
ASSERT_EQUALS(false, MathLib::isNullValue("0x1P0"));
ASSERT_EQUALS(false, MathLib::isNullValue("0xap0"));
ASSERT_EQUALS(false, MathLib::isNullValue("0xbp0"));
ASSERT_EQUALS(false, MathLib::isNullValue("0xcp0"));
ASSERT_EQUALS(false, MathLib::isNullValue("0xdp0"));
ASSERT_EQUALS(false, MathLib::isNullValue("0xep0"));
ASSERT_EQUALS(false, MathLib::isNullValue("0xfp0"));
ASSERT_EQUALS(false, MathLib::isNullValue("-00.01e-12"));
ASSERT_EQUALS(false, MathLib::isNullValue("-00.01e+12"));
ASSERT_EQUALS(false, MathLib::isNullValue(""));
ASSERT_EQUALS(false, MathLib::isNullValue(" "));
ASSERT_EQUALS(false, MathLib::isNullValue("x"));
ASSERT_EQUALS(false, MathLib::isNullValue("garbage"));
ASSERT_EQUALS(false, MathLib::isNullValue("UL"));
ASSERT_EQUALS(false, MathLib::isNullValue("-ENOMEM"));
}
void sin() const {
ASSERT_EQUALS("0.0", MathLib::sin("0"));
}
void cos() const {
ASSERT_EQUALS("1.0", MathLib::cos("0"));
}
void tan() const {
ASSERT_EQUALS("0.0", MathLib::tan("0"));
}
void abs() const {
ASSERT_EQUALS("", MathLib::abs(""));
ASSERT_EQUALS("0", MathLib::abs("0"));
ASSERT_EQUALS("+0", MathLib::abs("+0"));
ASSERT_EQUALS("0", MathLib::abs("-0"));
ASSERT_EQUALS("+1", MathLib::abs("+1"));
ASSERT_EQUALS("+1.0", MathLib::abs("+1.0"));
ASSERT_EQUALS("1", MathLib::abs("-1"));
ASSERT_EQUALS("1.0", MathLib::abs("-1.0"));
ASSERT_EQUALS("9007199254740991", MathLib::abs("9007199254740991"));
}
void toString() const {
ASSERT_EQUALS("0.0", MathLib::toString(0.0));
ASSERT_EQUALS("0.0", MathLib::toString(+0.0));
ASSERT_EQUALS("0.0", MathLib::toString(-0.0));
ASSERT_EQUALS("1e-08", MathLib::toString(0.00000001));
ASSERT_EQUALS("-1e-08", MathLib::toString(-0.00000001));
ASSERT_EQUALS("2.22507385851e-308", MathLib::toString(std::numeric_limits<double>::min()));
ASSERT_EQUALS("1.79769313486e+308", MathLib::toString(std::numeric_limits<double>::max()));
}
};
REGISTER_TEST(TestMathLib)
| null |
999 | cpp | cppcheck | testtype.cpp | test/testtype.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "checktype.h"
#include "errortypes.h"
#include "fixture.h"
#include "helpers.h"
#include "platform.h"
#include "settings.h"
#include "standards.h"
#include "tokenize.h"
#include <cstddef>
#include <string>
#include <vector>
class TestType : public TestFixture {
public:
TestType() : TestFixture("TestType") {}
private:
void run() override {
TEST_CASE(checkTooBigShift_Unix32);
TEST_CASE(checkIntegerOverflow);
TEST_CASE(signConversion);
TEST_CASE(longCastAssign);
TEST_CASE(longCastReturn);
TEST_CASE(checkFloatToIntegerOverflow);
TEST_CASE(integerOverflow); // #11794
TEST_CASE(shiftTooManyBits); // #11496
}
#define check(...) check_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
void check_(const char* file, int line, const char (&code)[size], const Settings& settings, bool cpp = true, Standards::cppstd_t standard = Standards::cppstd_t::CPP11) {
const Settings settings1 = settingsBuilder(settings).severity(Severity::warning).severity(Severity::portability).cpp(standard).build();
// Tokenize..
SimpleTokenizer tokenizer(settings1, *this);
ASSERT_LOC(tokenizer.tokenize(code, cpp), file, line);
// Check..
runChecks<CheckType>(tokenizer, this);
}
// TODO: get rid of this
void check_(const char* file, int line, const std::string& code, const Settings& settings, bool cpp = true, Standards::cppstd_t standard = Standards::cppstd_t::CPP11) {
const Settings settings1 = settingsBuilder(settings).severity(Severity::warning).severity(Severity::portability).cpp(standard).build();
// Tokenize..
SimpleTokenizer tokenizer(settings1, *this);
ASSERT_LOC(tokenizer.tokenize(code, cpp), file, line);
// Check..
runChecks<CheckType>(tokenizer, this);
}
#define checkP(...) checkP_(__FILE__, __LINE__, __VA_ARGS__)
template<size_t size>
void checkP_(const char* file, int line, const char (&code)[size], const Settings& settings, const char filename[] = "test.cpp") {
const Settings settings1 = settingsBuilder(settings).severity(Severity::warning).severity(Severity::portability).build();
std::vector<std::string> files(1, filename);
Tokenizer tokenizer(settings1, *this);
PreprocessorHelper::preprocess(code, files, tokenizer, *this);
// Tokenizer..
ASSERT_LOC(tokenizer.simplifyTokens1(""), file, line);
// Check..
runChecks<CheckType>(tokenizer, this);
}
void checkTooBigShift_Unix32() {
const Settings settings = settingsBuilder().platform(Platform::Type::Unix32).build();
// unsigned types getting promoted to int sizeof(int) = 4 bytes
// and unsigned types having already a size of 4 bytes
{
const std::string types[] = {"unsigned char", /*[unsigned]*/ "char", "bool", "unsigned short", "unsigned int", "unsigned long"};
for (const std::string& type : types) {
check(type + " f(" + type +" x) { return x << 31; }", settings);
ASSERT_EQUALS("", errout_str());
check(type + " f(" + type +" x) { return x << 33; }", settings);
ASSERT_EQUALS("[test.cpp:1]: (error) Shifting 32-bit value by 33 bits is undefined behaviour\n", errout_str());
check(type + " f(int x) { return (x = (" + type + ")x << 32); }", settings);
ASSERT_EQUALS("[test.cpp:1]: (error) Shifting 32-bit value by 32 bits is undefined behaviour\n", errout_str());
check(type + " foo(" + type + " x) { return x << 31; }", settings);
ASSERT_EQUALS("", errout_str());
}
}
// signed types getting promoted to int sizeof(int) = 4 bytes
// and signed types having already a size of 4 bytes
{
const std::string types[] = {"signed char", "signed short", /*[signed]*/ "short", "wchar_t", /*[signed]*/ "int", "signed int", /*[signed]*/ "long", "signed long"};
for (const std::string& type : types) {
// c++11
check(type + " f(" + type +" x) { return x << 33; }", settings);
ASSERT_EQUALS("[test.cpp:1]: (error) Shifting 32-bit value by 33 bits is undefined behaviour\n", errout_str());
check(type + " f(int x) { return (x = (" + type + ")x << 32); }", settings);
ASSERT_EQUALS("[test.cpp:1]: (error) Shifting 32-bit value by 32 bits is undefined behaviour\n", errout_str());
check(type + " foo(" + type + " x) { return x << 31; }", settings);
ASSERT_EQUALS("[test.cpp:1]: (error) Shifting signed 32-bit value by 31 bits is undefined behaviour\n", errout_str());
check(type + " foo(" + type + " x) { return x << 30; }", settings);
ASSERT_EQUALS("", errout_str());
// c++14
check(type + " foo(" + type + " x) { return x << 31; }", settings, true, Standards::cppstd_t::CPP14);
ASSERT_EQUALS("[test.cpp:1]: (portability) Shifting signed 32-bit value by 31 bits is implementation-defined behaviour\n", errout_str());
check(type + " f(int x) { return (x = (" + type + ")x << 32); }", settings, true, Standards::cppstd_t::CPP14);
ASSERT_EQUALS("[test.cpp:1]: (error) Shifting 32-bit value by 32 bits is undefined behaviour\n", errout_str());
}
}
// 64 bit width types
{
// unsigned long long
check("unsigned long long foo(unsigned long long x) { return x << 64; }",settings);
ASSERT_EQUALS("[test.cpp:1]: (error) Shifting 64-bit value by 64 bits is undefined behaviour\n", errout_str());
check("unsigned long long f(int x) { return (x = (unsigned long long)x << 64); }",settings);
ASSERT_EQUALS("[test.cpp:1]: (error) Shifting 64-bit value by 64 bits is undefined behaviour\n", errout_str());
check("unsigned long long f(unsigned long long x) { return x << 63; }",settings);
ASSERT_EQUALS("", errout_str());
// [signed] long long
check("long long foo(long long x) { return x << 64; }",settings);
ASSERT_EQUALS("[test.cpp:1]: (error) Shifting 64-bit value by 64 bits is undefined behaviour\n", errout_str());
check("long long f(int x) { return (x = (long long)x << 64); }",settings);
ASSERT_EQUALS("[test.cpp:1]: (error) Shifting 64-bit value by 64 bits is undefined behaviour\n", errout_str());
check("long long f(long long x) { return x << 63; }",settings);
ASSERT_EQUALS("[test.cpp:1]: (error) Shifting signed 64-bit value by 63 bits is undefined behaviour\n", errout_str());
check("long long f(long long x) { return x << 62; }",settings);
ASSERT_EQUALS("", errout_str());
// signed long long
check("signed long long foo(signed long long x) { return x << 64; }",settings);
ASSERT_EQUALS("[test.cpp:1]: (error) Shifting 64-bit value by 64 bits is undefined behaviour\n", errout_str());
check("signed long long f(long long x) { return (x = (signed long long)x << 64); }",settings);
ASSERT_EQUALS("[test.cpp:1]: (error) Shifting 64-bit value by 64 bits is undefined behaviour\n", errout_str());
check("signed long long f(signed long long x) { return x << 63; }",settings);
ASSERT_EQUALS("[test.cpp:1]: (error) Shifting signed 64-bit value by 63 bits is undefined behaviour\n", errout_str());
check("signed long long f(signed long long x) { return x << 62; }",settings);
ASSERT_EQUALS("", errout_str());
// c++14
check("signed long long foo(signed long long x) { return x << 64; }",settings, true, Standards::cppstd_t::CPP14);
ASSERT_EQUALS("[test.cpp:1]: (error) Shifting 64-bit value by 64 bits is undefined behaviour\n", errout_str());
check("signed long long f(long long x) { return (x = (signed long long)x << 64); }",settings, true, Standards::cppstd_t::CPP14);
ASSERT_EQUALS("[test.cpp:1]: (error) Shifting 64-bit value by 64 bits is undefined behaviour\n", errout_str());
check("signed long long f(signed long long x) { return x << 63; }",settings, true, Standards::cppstd_t::CPP14);
ASSERT_EQUALS("[test.cpp:1]: (portability) Shifting signed 64-bit value by 63 bits is implementation-defined behaviour\n", errout_str());
check("signed long long f(signed long long x) { return x << 62; }",settings);
ASSERT_EQUALS("", errout_str());
}
check("void f() { int x; x = 1 >> 64; }", settings);
ASSERT_EQUALS("[test.cpp:1]: (error) Shifting 32-bit value by 64 bits is undefined behaviour\n", errout_str());
check("void foo() {\n"
" QList<int> someList;\n"
" someList << 300;\n"
"}", settings);
ASSERT_EQUALS("", errout_str());
// Ticket #6793
check("template<unsigned int I> int foo(unsigned int x) { return x << I; }\n"
"const unsigned int f = foo<31>(0);\n"
"const unsigned int g = foo<100>(0);\n"
"template<unsigned int I> int hoo(unsigned int x) { return x << 32; }\n"
"const unsigned int h = hoo<100>(0);", settings);
ASSERT_EQUALS("[test.cpp:4]: (error) Shifting 32-bit value by 32 bits is undefined behaviour\n"
"[test.cpp:1]: (error) Shifting 32-bit value by 100 bits is undefined behaviour\n", errout_str());
// #7266: C++, shift in macro
check("void f(unsigned int x) {\n"
" UINFO(x << 1234);\n"
"}", settingsDefault);
ASSERT_EQUALS("", errout_str());
// #8640
check("int f (void)\n"
"{\n"
" constexpr const int a = 1;\n"
" constexpr const int shift[1] = {32};\n"
" constexpr const int ret = a << shift[0];\n" // shift too many bits
" return ret;\n"
"}", settingsDefault);
ASSERT_EQUALS("[test.cpp:5]: (error) Shifting 32-bit value by 32 bits is undefined behaviour\n"
"[test.cpp:5]: (error) Signed integer overflow for expression 'a<<shift[0]'.\n", errout_str());
// #8885
check("int f(int k, int rm) {\n"
" if (k == 32)\n"
" return 0;\n"
" if (k > 32)\n"
" return 0;\n"
" return rm>> k;\n"
"}", settingsDefault);
ASSERT_EQUALS(
"[test.cpp:4] -> [test.cpp:6]: (warning) Shifting signed 32-bit value by 31 bits is undefined behaviour. See condition at line 4.\n",
errout_str());
check("int f(int k, int rm) {\n"
" if (k == 0 || k == 32)\n"
" return 0;\n"
" else if (k > 32)\n"
" return 0;\n"
" else\n"
" return rm>> k;\n"
"}", settingsDefault);
ASSERT_EQUALS(
"[test.cpp:4] -> [test.cpp:7]: (warning) Shifting signed 32-bit value by 31 bits is undefined behaviour. See condition at line 4.\n",
errout_str());
check("int f(int k, int rm) {\n"
" if (k == 0 || k == 32 || k == 31)\n"
" return 0;\n"
" else if (k > 32)\n"
" return 0;\n"
" else\n"
" return rm>> k;\n"
"}", settingsDefault);
ASSERT_EQUALS("", errout_str());
check("static long long f(int x, long long y) {\n"
" if (x >= 64)\n"
" return 0;\n"
" return -(y << (x-1));\n"
"}", settingsDefault);
ASSERT_EQUALS("", errout_str());
check("bool f() {\n"
" std::ofstream outfile;\n"
" outfile << vec_points[0](0) << static_cast<int>(d) << ' ';\n"
"}", settingsDefault);
ASSERT_EQUALS("", errout_str());
check("void f(unsigned b, int len, unsigned char rem) {\n" // #10773
" int bits = 0;\n"
" while (len > 8) {\n"
" b = b >> rem;\n"
" bits += 8 - rem;\n"
" if (bits == 512)\n"
" len -= 8;\n"
" }\n"
"}\n", settingsDefault);
ASSERT_EQUALS("", errout_str());
}
void checkIntegerOverflow() {
const Settings settings = settingsBuilder().severity(Severity::warning).platform(Platform::Type::Unix32).build();
check("x = (int)0x10000 * (int)0x10000;", settings);
ASSERT_EQUALS("[test.cpp:1]: (error) Signed integer overflow for expression '(int)0x10000*(int)0x10000'.\n", errout_str());
check("x = (long)0x10000 * (long)0x10000;", settings);
ASSERT_EQUALS("[test.cpp:1]: (error) Signed integer overflow for expression '(long)0x10000*(long)0x10000'.\n", errout_str());
check("void foo() {\n"
" int intmax = 0x7fffffff;\n"
" return intmax + 1;\n"
"}",settings);
ASSERT_EQUALS("[test.cpp:3]: (error) Signed integer overflow for expression 'intmax+1'.\n", errout_str());
check("void foo() {\n"
" int intmax = 0x7fffffff;\n"
" return intmax - 1;\n"
"}",settings);
ASSERT_EQUALS("", errout_str());
check("int foo(signed int x) {\n"
" if (x==123456) {}\n"
" return x * x;\n"
"}",settings);
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (warning) Either the condition 'x==123456' is redundant or there is signed integer overflow for expression 'x*x'.\n", errout_str());
check("int foo(signed int x) {\n"
" if (x==123456) {}\n"
" return -123456 * x;\n"
"}",settings);
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (warning) Either the condition 'x==123456' is redundant or there is signed integer underflow for expression '-123456*x'.\n", errout_str());
check("int foo(signed int x) {\n"
" if (x==123456) {}\n"
" return 123456U * x;\n"
"}",settings);
ASSERT_EQUALS("", errout_str());
check("int f(int i) {\n" // #12117
" return (i == 31) ? 1 << i : 0;\n"
"}", settings);
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:2]: (warning) Shifting signed 32-bit value by 31 bits is undefined behaviour. See condition at line 2.\n", errout_str());
check("void f() {\n" // #13092
" int n = 0;\n"
" for (int i = 0; i < 10; i++) {\n"
" n = n * 47163 - 57412;\n"
" }\n"
"}", settings);
ASSERT_EQUALS("[test.cpp:4]: (error) Signed integer underflow for expression 'n*47163'.\n"
"[test.cpp:4]: (error) Signed integer underflow for expression 'n*47163-57412'.\n",
errout_str());
}
void signConversion() {
const Settings settings = settingsBuilder().platform(Platform::Type::Unix64).build();
check("x = -4 * (unsigned)y;", settingsDefault);
ASSERT_EQUALS("[test.cpp:1]: (warning) Expression '-4' has a negative value. That is converted to an unsigned value and used in an unsigned calculation.\n", errout_str());
check("x = (unsigned)y * -4;", settingsDefault);
ASSERT_EQUALS("[test.cpp:1]: (warning) Expression '-4' has a negative value. That is converted to an unsigned value and used in an unsigned calculation.\n", errout_str());
check("unsigned int dostuff(int x) {\n" // x is signed
" if (x==0) {}\n"
" return (x-1)*sizeof(int);\n"
"}", settings);
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (warning) Expression 'x-1' can have a negative value. That is converted to an unsigned value and used in an unsigned calculation.\n", errout_str());
check("unsigned int f1(signed int x, unsigned int y) {" // x is signed
" return x * y;\n"
"}\n"
"void f2() { f1(-4,4); }", settingsDefault);
ASSERT_EQUALS(
"[test.cpp:1]: (warning) Expression 'x' can have a negative value. That is converted to an unsigned value and used in an unsigned calculation.\n",
errout_str());
check("unsigned int f1(int x) {"
" return x * 5U;\n"
"}\n"
"void f2() { f1(-4); }", settingsDefault);
ASSERT_EQUALS(
"[test.cpp:1]: (warning) Expression 'x' can have a negative value. That is converted to an unsigned value and used in an unsigned calculation.\n",
errout_str());
check("unsigned int f1(int x) {" // #6168: FP for inner calculation
" return 5U * (1234 - x);\n" // <- signed subtraction, x is not sign converted
"}\n"
"void f2() { f1(-4); }", settingsDefault);
ASSERT_EQUALS("", errout_str());
// Don't warn for + and -
check("void f1(int x) {"
" a = x + 5U;\n"
"}\n"
"void f2() { f1(-4); }", settingsDefault);
ASSERT_EQUALS("", errout_str());
check("size_t foo(size_t x) {\n"
" return -2 * x;\n"
"}", settingsDefault);
ASSERT_EQUALS("[test.cpp:2]: (warning) Expression '-2' has a negative value. That is converted to an unsigned value and used in an unsigned calculation.\n", errout_str());
checkP("void f() {\n" // #12110 FP signConversion with integer overflow
" if (LLONG_MIN / (-1)) {}\n"
"}\n", settingsDefault);
ASSERT_EQUALS("", errout_str());
}
void longCastAssign() {
const Settings settings = settingsBuilder().severity(Severity::style).platform(Platform::Type::Unix64).build();
const Settings settingsWin = settingsBuilder().severity(Severity::style).platform(Platform::Type::Win64).build();
const char code[] = "long f(int x, int y) {\n"
" const long ret = x * y;\n"
" return ret;\n"
"}\n";
check(code, settings);
ASSERT_EQUALS("[test.cpp:2]: (style) int result is assigned to long variable. If the variable is long to avoid loss of information, then you have loss of information.\n", errout_str());
check(code, settingsWin);
ASSERT_EQUALS("", errout_str());
check("long f(int x, int y) {\n"
" long ret = x * y;\n"
" return ret;\n"
"}\n", settings);
ASSERT_EQUALS("[test.cpp:2]: (style) int result is assigned to long variable. If the variable is long to avoid loss of information, then you have loss of information.\n", errout_str());
check("long f() {\n"
" const long long ret = 256 * (1 << 10);\n"
" return ret;\n"
"}\n", settings);
ASSERT_EQUALS("", errout_str());
// typedef
check("long f(int x, int y) {\n"
" const size_t ret = x * y;\n"
" return ret;\n"
"}\n", settings);
ASSERT_EQUALS("", errout_str());
// astIsIntResult
check("long f(int x, int y) {\n"
" const long ret = (long)x * y;\n"
" return ret;\n"
"}\n", settings);
ASSERT_EQUALS("", errout_str());
check("double g(float f) {\n"
" return f * f;\n"
"}\n", settings);
ASSERT_EQUALS("[test.cpp:2]: (style) float result is returned as double value. If the return value is double to avoid loss of information, then you have loss of information.\n",
errout_str());
check("void f(int* p) {\n" // #11862
" long long j = *(p++);\n"
"}\n", settings);
ASSERT_EQUALS("", errout_str());
check("template <class T>\n" // #12393
"struct S {\n"
" S& operator=(const S&) { return *this; }\n"
" struct U {\n"
" S<T>* p;\n"
" };\n"
" U u;\n"
"};\n", settings);
ASSERT_EQUALS("", errout_str()); // don't crash
check("void f(long& r, long i) {\n"
" r = 1 << i;\n"
"}\n", settingsWin);
ASSERT_EQUALS("", errout_str());
}
void longCastReturn() {
const Settings settings = settingsBuilder().severity(Severity::style).platform(Platform::Type::Unix64).build();
const Settings settingsWin = settingsBuilder().severity(Severity::style).platform(Platform::Type::Win64).build();
const char code[] = "long f(int x, int y) {\n"
" return x * y;\n"
"}\n";
check(code, settings);
ASSERT_EQUALS("[test.cpp:2]: (style) int result is returned as long value. If the return value is long to avoid loss of information, then you have loss of information.\n", errout_str());
check(code, settingsWin);
ASSERT_EQUALS("", errout_str());
const char code2[] = "long long f(int x, int y) {\n"
" return x * y;\n"
"}\n";
check(code2, settings);
ASSERT_EQUALS("[test.cpp:2]: (style) int result is returned as long long value. If the return value is long long to avoid loss of information, then you have loss of information.\n", errout_str());
check(code2, settingsWin);
ASSERT_EQUALS("[test.cpp:2]: (style) int result is returned as long long value. If the return value is long long to avoid loss of information, then you have loss of information.\n", errout_str());
// typedef
check("size_t f(int x, int y) {\n"
" return x * y;\n"
"}\n", settings);
ASSERT_EQUALS("[test.cpp:2]: (style) int result is returned as long value. If the return value is long to avoid loss of information, then you have loss of information.\n", errout_str());
}
// This function ensure that test works with different compilers. Floats can
// be stringified differently.
static std::string removeFloat(const std::string& msg) {
const std::string::size_type pos1 = msg.find("float (");
const std::string::size_type pos2 = msg.find(") to integer conversion");
if (pos1 == std::string::npos || pos2 == std::string::npos || pos1 > pos2)
return msg;
return msg.substr(0,pos1+7) + msg.substr(pos2);
}
void checkFloatToIntegerOverflow() {
check("x = (int)1E100;", settingsDefault);
ASSERT_EQUALS("[test.cpp:1]: (error) Undefined behaviour: float () to integer conversion overflow.\n", removeFloat(errout_str()));
check("void f(void) {\n"
" return (int)1E100;\n"
"}", settingsDefault);
ASSERT_EQUALS("[test.cpp:2]: (error) Undefined behaviour: float () to integer conversion overflow.\n", removeFloat(errout_str()));
check("void f(void) {\n"
" return (int)-1E100;\n"
"}", settingsDefault);
ASSERT_EQUALS("[test.cpp:2]: (error) Undefined behaviour: float () to integer conversion overflow.\n", removeFloat(errout_str()));
check("void f(void) {\n"
" return (short)1E6;\n"
"}", settingsDefault);
ASSERT_EQUALS("[test.cpp:2]: (error) Undefined behaviour: float () to integer conversion overflow.\n", removeFloat(errout_str()));
check("void f(void) {\n"
" return (unsigned char)256.0;\n"
"}", settingsDefault);
ASSERT_EQUALS("[test.cpp:2]: (error) Undefined behaviour: float () to integer conversion overflow.\n", removeFloat(errout_str()));
check("void f(void) {\n"
" return (unsigned char)255.5;\n"
"}", settingsDefault);
ASSERT_EQUALS("", removeFloat(errout_str()));
check("void f(void) {\n"
" char c = 1234.5;\n"
"}", settingsDefault);
ASSERT_EQUALS("[test.cpp:2]: (error) Undefined behaviour: float () to integer conversion overflow.\n", removeFloat(errout_str()));
check("char f(void) {\n"
" return 1234.5;\n"
"}", settingsDefault);
ASSERT_EQUALS("[test.cpp:2]: (error) Undefined behaviour: float () to integer conversion overflow.\n", removeFloat(errout_str()));
checkP("#define TEST(b, f) b ? 5000 : (unsigned short)f\n" // #11685
"void f()\n"
"{\n"
" unsigned short u = TEST(true, 75000.0);\n"
"}\n", settingsDefault);
ASSERT_EQUALS("", errout_str());
checkP("#define TEST(b, f) b ? 5000 : (unsigned short)f\n"
"void f()\n"
"{\n"
" unsigned short u = TEST(false, 75000.0);\n"
"}\n", settingsDefault);
ASSERT_EQUALS("[test.cpp:4]: (error) Undefined behaviour: float () to integer conversion overflow.\n", removeFloat(errout_str()));
check( "bool f(unsigned short x);\n"
"bool g() {\n"
" return false && f((unsigned short)75000.0);\n"
"}\n", settingsDefault);
ASSERT_EQUALS("", errout_str());
check( "bool f(unsigned short x);\n"
"bool g() {\n"
" return true && f((unsigned short)75000.0);\n"
"}\n", settingsDefault);
ASSERT_EQUALS("[test.cpp:3]: (error) Undefined behaviour: float () to integer conversion overflow.\n", removeFloat(errout_str()));
check( "bool f(unsigned short x);\n"
"bool g() {\n"
" return true || f((unsigned short)75000.0);\n"
"}\n", settingsDefault);
ASSERT_EQUALS("", errout_str());
check( "bool f(unsigned short x);\n"
"bool g() {\n"
" return false || f((unsigned short)75000.0);\n"
"}\n", settingsDefault);
ASSERT_EQUALS("[test.cpp:3]: (error) Undefined behaviour: float () to integer conversion overflow.\n", removeFloat(errout_str()));
checkP("#define TEST(b, f) b ? 5000 : (unsigned short)f\n" // #11685
"void f()\n"
"{\n"
" unsigned short u = TEST(true, 75000.0);\n"
"}\n", settingsDefault, "test.c");
ASSERT_EQUALS("", errout_str());
checkP("#define TEST(b, f) b ? 5000 : (unsigned short)f\n"
"void f()\n"
"{\n"
" unsigned short u = TEST(false, 75000.0);\n"
"}\n", settingsDefault, "test.c");
ASSERT_EQUALS("[test.c:4]: (error) Undefined behaviour: float () to integer conversion overflow.\n", removeFloat(errout_str()));
}
void integerOverflow() { // #11794
// std.cfg for int32_t
// Platform::Unix32 for INT_MIN=-2147483648 and INT32_MAX=2147483647
const Settings s = settingsBuilder().library("std.cfg").cpp(Standards::CPP11).platform(Platform::Unix32).build();
checkP("int fun(int x)\n"
"{\n"
" if(x < 0) x = -x;\n"
" return x >= 0;\n"
"}\n"
"int f()\n"
"{\n"
" fun(INT_MIN);\n"
"}", s, "test.cpp");
ASSERT_EQUALS("[test.cpp:3]: (error) Signed integer overflow for expression '-x'.\n", errout_str());
checkP("void f() {\n" // #8399
" int32_t i = INT32_MAX;\n"
" i << 1;\n"
" i << 2;\n"
"}", s, "test.cpp");
ASSERT_EQUALS("[test.cpp:4]: (error) Signed integer overflow for expression 'i<<2'.\n", errout_str());
}
void shiftTooManyBits() { // #11496
check("template<unsigned int width> struct B {\n"
" unsigned long long f(unsigned int n) const {\n"
" if (width == 1)\n"
" return 1ULL << width;\n"
" return 0;\n"
" }\n"
"};\n"
"static B<64> b;\n", settingsDefault);
ASSERT_EQUALS("", errout_str());
}
};
REGISTER_TEST(TestType)
| null |
1,000 | cpp | cppcheck | testincompletestatement.cpp | test/testincompletestatement.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "checkother.h"
#include "errortypes.h"
#include "helpers.h"
#include "settings.h"
#include "fixture.h"
#include "tokenize.h"
#include <string>
#include <vector>
class TestIncompleteStatement : public TestFixture {
public:
TestIncompleteStatement() : TestFixture("TestIncompleteStatement") {}
private:
const Settings settings = settingsBuilder().severity(Severity::warning).build();
#define check(...) check_(__FILE__, __LINE__, __VA_ARGS__)
void check_(const char* file, int line, const char code[], bool inconclusive = false, bool cpp = true) {
const Settings settings1 = settingsBuilder(settings).certainty(Certainty::inconclusive, inconclusive).build();
std::vector<std::string> files(1, cpp ? "test.cpp" : "test.c");
Tokenizer tokenizer(settings1, *this);
PreprocessorHelper::preprocess(code, files, tokenizer, *this);
// Tokenize..
ASSERT_LOC(tokenizer.simplifyTokens1(""), file, line);
// Check for incomplete statements..
CheckOther checkOther(&tokenizer, &settings1, this);
checkOther.checkIncompleteStatement();
}
void run() override {
TEST_CASE(test1);
TEST_CASE(test2);
TEST_CASE(test3);
TEST_CASE(test4);
TEST_CASE(test5);
TEST_CASE(test6);
TEST_CASE(test7);
TEST_CASE(test_numeric);
TEST_CASE(void0); // #6327: No fp for statement "(void)0;"
TEST_CASE(intarray);
TEST_CASE(structarraynull);
TEST_CASE(structarray);
TEST_CASE(conditionalcall); // ; 0==x ? X() : Y();
TEST_CASE(structinit); // #2462 : ABC abc{1,2,3};
TEST_CASE(returnstruct);
TEST_CASE(cast); // #3009 : (struct Foo *)123.a = 1;
TEST_CASE(increment); // #3251 : FP for increment
TEST_CASE(cpp11init); // #5493 : int i{1};
TEST_CASE(cpp11init2); // #8449
TEST_CASE(cpp11init3); // #8995
TEST_CASE(block); // ({ do_something(); 0; })
TEST_CASE(mapindex);
TEST_CASE(commaoperator1);
TEST_CASE(commaoperator2);
TEST_CASE(redundantstmts);
TEST_CASE(vardecl);
TEST_CASE(archive); // ar & x
TEST_CASE(ast);
TEST_CASE(oror); // dostuff() || x=32;
}
void test1() {
check("void foo()\n"
"{\n"
" const char def[] =\n"
" \"abc\";\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void test2() {
check("void foo()\n"
"{\n"
" \"abc\";\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Redundant code: Found a statement that begins with string constant.\n", errout_str());
}
void test3() {
check("void foo()\n"
"{\n"
" const char *str[] = { \"abc\" };\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void test4() {
check("void foo()\n"
"{\n"
"const char *a =\n"
"{\n"
"\"hello \"\n"
"\"more \"\n"
"\"world\"\n"
"};\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void test5() {
check("void foo()\n"
"{\n"
" 50;\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Redundant code: Found a statement that begins with numeric constant.\n", errout_str());
}
void test6() {
// don't crash
check("void f() {\n"
" 1 == (two + three);\n"
" 2 != (two + three);\n"
" (one + two) != (two + three);\n"
"}");
}
void test7() { // #9335
check("namespace { std::string S = \"\"; }\n"
"\n"
"class C {\n"
"public:\n"
" explicit C(const std::string& s);\n"
"};\n"
"\n"
"void f() {\n"
" for (C c(S); ; ) {\n"
" (void)c;\n"
" }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void test_numeric() {
check("struct P {\n"
" double a;\n"
" double b;\n"
"};\n"
"void f() {\n"
" const P values[2] =\n"
" {\n"
" { 346.1,114.1 }, { 347.1,111.1 }\n"
" };\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void void0() { // #6327
check("void f() { (void*)0; }");
ASSERT_EQUALS("", errout_str());
check("#define X 0\n"
"void f() { X; }");
ASSERT_EQUALS("", errout_str());
}
void intarray() {
check("int arr[] = { 100/2, 1*100 };");
ASSERT_EQUALS("", errout_str());
}
void structarraynull() {
check("struct st arr[] = {\n"
" { 100/2, 1*100 }\n"
" { 90, 70 }\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void structarray() {
check("struct st arr[] = {\n"
" { 100/2, 1*100 }\n"
" { 90, 70 }\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void conditionalcall() {
check("void f() {\n"
" 0==x ? X() : Y();\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void structinit() {
// #2462 - C++11 struct initialization
check("void f() {\n"
" ABC abc{1,2,3};\n"
"}");
ASSERT_EQUALS("", errout_str());
// #6260 - C++11 array initialization
check("void foo() {\n"
" static const char* a[][2] {\n"
" {\"b\", \"\"},\n"
" };\n"
"}");
ASSERT_EQUALS("", errout_str());
// #2482 - false positive for empty struct
check("struct A {};");
ASSERT_EQUALS("", errout_str());
// #4387 - C++11 initializer list
check("A::A() : abc{0} {}");
ASSERT_EQUALS("", errout_str());
// #5042 - C++11 initializer list
check("A::A() : abc::def<int>{0} {}");
ASSERT_EQUALS("", errout_str());
// #4503 - vector init
check("void f() { vector<int> v{1}; }");
ASSERT_EQUALS("", errout_str());
}
void returnstruct() {
check("struct s foo() {\n"
" return (struct s){0,0};\n"
"}");
ASSERT_EQUALS("", errout_str());
// #4754
check("unordered_map<string, string> foo() {\n"
" return {\n"
" {\"hi\", \"there\"},\n"
" {\"happy\", \"sad\"}\n"
" };\n"
"}");
ASSERT_EQUALS("", errout_str());
check("struct s foo() {\n"
" return (struct s){0};\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void cast() {
check("void f() {\n"
" ((struct foo *)(0x1234))->xy = 1;\n"
"}");
ASSERT_EQUALS("", errout_str());
check("bool f(const std::exception& e) {\n" // #10918
" try {\n"
" dynamic_cast<const InvalidTypeException&>(e);\n"
" return true;\n"
" }\n"
" catch (...) {\n"
" return false;\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void increment() {
check("void f() {\n"
" int x = 1;\n"
" x++, x++;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void cpp11init() {
check("void f() {\n"
" int x{1};\n"
"}");
ASSERT_EQUALS("", errout_str());
check("std::vector<int> f(int* p) {\n"
" return std::vector<int>({ p[0] });\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
void cpp11init2() {
check("x<string> handlers{\n"
" { \"mode2\", []() { return 2; } },\n"
"};");
ASSERT_EQUALS("", errout_str());
}
void cpp11init3() {
check("struct A { void operator()(int); };\n"
"void f() {\n"
"A{}(0);\n"
"}");
ASSERT_EQUALS("", errout_str());
check("template<class> struct A { void operator()(int); };\n"
"void f() {\n"
"A<int>{}(0);\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void block() {
check("void f() {\n"
" ({ do_something(); 0; });\n"
"}");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
"out:\n"
" ({ do_something(); 0; });\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void mapindex() {
check("void f() {\n"
" map[{\"1\",\"2\"}]=0;\n"
"}");
ASSERT_EQUALS("", errout_str());
}
void commaoperator1() {
check("void foo(int,const char*,int);\n" // #8827
"void f(int value) {\n"
" foo(42,\"test\",42),(value&42);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (warning) Found suspicious operator ',', result is not used.\n", errout_str());
check("int f() {\n" // #11257
" int y;\n"
" y = (3, 4);\n"
" return y;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (warning) Found suspicious operator ',', result is not used.\n", errout_str());
}
void commaoperator2() {
check("void f() {\n"
" for(unsigned int a=0, b; a<10; a++ ) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void g();\n" // #10952
"bool f() {\n"
" return (void)g(), false;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(int a, int b, int c, int d) {\n"
" Eigen::Vector4d V;\n"
" V << a, b, c, d;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct S { Eigen::Vector4d V; };\n"
"struct T { int a, int b, int c, int d; };\n"
"void f(S& s, const T& t) {\n"
" s.V << t.a, t.b, t.c, t.d;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct S { Eigen::Vector4d V[2]; };\n"
"void f(int a, int b, int c, int d) {\n"
" S s[1];\n"
" s[0].V[1] << a, b, c, d;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f() {\n"
" a.b[4][3].c()->d << x , y, z;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct V {\n"
" Eigen::Vector3d& operator[](int i) { return v[i]; }\n"
" void f(int a, int b, int c);\n"
" Eigen::Vector3d v[1];\n"
"};\n"
"void V::f(int a, int b, int c) {\n"
" (*this)[0] << a, b, c;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f() {\n" // #11359
" struct S {\n"
" S(int x, int y) {}\n"
" } s(1, 2);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}
// #8451
void redundantstmts() {
check("void f1(int x) {\n"
" 1;\n"
" (1);\n"
" (char)1;\n"
" ((char)1);\n"
" !x;\n"
" (!x);\n"
" (unsigned int)!x;\n"
" ~x;\n"
"}\n", true);
ASSERT_EQUALS("[test.cpp:2]: (warning) Redundant code: Found a statement that begins with numeric constant.\n"
"[test.cpp:3]: (warning) Redundant code: Found a statement that begins with numeric constant.\n"
"[test.cpp:4]: (warning) Redundant code: Found a statement that begins with numeric constant.\n"
"[test.cpp:5]: (warning) Redundant code: Found a statement that begins with numeric constant.\n"
"[test.cpp:6]: (warning, inconclusive) Found suspicious operator '!', result is not used.\n"
"[test.cpp:7]: (warning, inconclusive) Found suspicious operator '!', result is not used.\n"
"[test.cpp:8]: (warning) Redundant code: Found unused cast of expression '!x'.\n"
"[test.cpp:9]: (warning, inconclusive) Found suspicious operator '~', result is not used.\n",
errout_str());
check("void f1(int x) { x; }", true);
ASSERT_EQUALS("[test.cpp:1]: (warning) Unused variable value 'x'\n", errout_str());
check("void f() { if (Type t; g(t)) {} }"); // #9776
ASSERT_EQUALS("", errout_str());
check("void f(int x) { static_cast<unsigned>(x); }");
ASSERT_EQUALS("[test.cpp:1]: (warning) Redundant code: Found unused cast of expression 'x'.\n", errout_str());
check("void f(int x, int* p) {\n"
" static_cast<void>(x);\n"
" (void)x;\n"
" static_cast<void*>(p);\n"
" (void*)p;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f() { false; }"); // #10856
ASSERT_EQUALS("[test.cpp:1]: (warning) Redundant code: Found a statement that begins with bool constant.\n", errout_str());
check("void f(int i) {\n"
" (float)(char)i;\n"
" static_cast<float>((char)i);\n"
" (char)static_cast<float>(i);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (warning) Redundant code: Found unused cast of expression 'i'.\n"
"[test.cpp:3]: (warning) Redundant code: Found unused cast of expression 'i'.\n"
"[test.cpp:4]: (warning) Redundant code: Found unused cast of expression 'i'.\n",
errout_str());
check("namespace M {\n"
" namespace N { typedef char T; }\n"
"}\n"
"void f(int i) {\n"
" (M::N::T)i;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5]: (warning) Redundant code: Found unused cast of expression 'i'.\n", errout_str());
check("void f(int (g)(int a, int b)) {\n" // #10873
" int p = 0, q = 1;\n"
" (g)(p, q);\n"
"}\n"
"void f() {\n"
" char buf[10];\n"
" (sprintf)(buf, \"%d\", 42);\n"
" (printf)(\"abc\");\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct S; struct T; struct U;\n"
"void f() {\n"
" T t;\n"
" (S)(U)t;\n"
" (S)static_cast<U>(t);\n"
" static_cast<S>((U)t);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(bool b) { b ? true : false; }\n"); // #10865
ASSERT_EQUALS("[test.cpp:1]: (warning) Redundant code: Found unused result of ternary operator.\n", errout_str());
check("struct S { void (*f)() = nullptr; };\n" // #10877
"void g(S* s) {\n"
" (s->f == nullptr) ? nullptr : (s->f(), nullptr);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(bool b) {\n"
" g() ? true : false;\n"
" true ? g() : false;\n"
" false ? true : g();\n"
" g(b ? true : false, 1);\n"
" C c{ b ? true : false, 1 };\n"
" b = (b ? true : false);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(int i) {\n"
" for (i; ;) {}\n"
" for ((long)i; ;) {}\n"
" for (1; ;) {}\n"
" for (true; ;) {}\n"
" for ('a'; ;) {}\n"
" for (L'b'; ;) {}\n"
" for (\"x\"; ;) {}\n"
" for (L\"y\"; ;) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (warning) Unused variable value 'i'\n"
"[test.cpp:3]: (warning) Redundant code: Found unused cast of expression 'i'.\n"
"[test.cpp:4]: (warning) Redundant code: Found a statement that begins with numeric constant.\n"
"[test.cpp:5]: (warning) Redundant code: Found a statement that begins with bool constant.\n"
"[test.cpp:6]: (warning) Redundant code: Found a statement that begins with character constant.\n"
"[test.cpp:7]: (warning) Redundant code: Found a statement that begins with character constant.\n"
"[test.cpp:8]: (warning) Redundant code: Found a statement that begins with string constant.\n"
"[test.cpp:9]: (warning) Redundant code: Found a statement that begins with string constant.\n",
errout_str());
check("struct S { bool b{}; };\n"
"struct T {\n"
" S s[2];\n"
" void g();\n"
"};\n"
"void f(const S& r, const S* p) {\n"
" r.b;\n"
" p->b;\n"
" S s;\n"
" (s.b);\n"
" T t, u[2];\n"
" t.s[1].b;\n"
" t.g();\n"
" u[0].g();\n"
" u[1].s[0].b;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:7]: (warning) Redundant code: Found unused member access.\n"
"[test.cpp:8]: (warning) Redundant code: Found unused member access.\n"
"[test.cpp:10]: (warning) Redundant code: Found unused member access.\n"
"[test.cpp:12]: (warning) Redundant code: Found unused member access.\n"
"[test.cpp:15]: (warning) Redundant code: Found unused member access.\n",
errout_str());
check("struct S { int a[2]{}; };\n"
"struct T { S s; };\n"
"void f() {\n"
" int i[2];\n"
" i[0] = 0;\n"
" i[0];\n" // <--
" S s[1];\n"
" s[0].a[1];\n" // <--
" T t;\n"
" t.s.a[1];\n" // <--
" int j[2][2][1] = {};\n"
" j[0][0][0];\n" // <--
"}\n");
ASSERT_EQUALS("[test.cpp:6]: (warning) Redundant code: Found unused array access.\n"
"[test.cpp:8]: (warning) Redundant code: Found unused array access.\n"
"[test.cpp:10]: (warning) Redundant code: Found unused array access.\n"
"[test.cpp:12]: (warning) Redundant code: Found unused array access.\n",
errout_str());
check("void g(std::map<std::string, std::string>& map) {\n"
" int j[2]{};\n"
" int k[2] = {};\n"
" int l[]{ 1, 2 };\n"
" int m[] = { 1, 2 };\n"
" h(0, j[0], 1);\n"
" C c{ 0, j[0], 1 };\n"
" c[0];\n"
" int j[2][2][2] = {};\n"
" j[h()][0][0];\n"
" j[0][h()][0];\n"
" j[0][0][h()];\n"
" std::map<std::string, int> M;\n"
" M[\"abc\"];\n"
" map[\"abc\"];\n" // #10928
" std::auto_ptr<Int> app[4];" // #10919
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct S { void* p; };\n" // #10875
"void f(S s) {\n"
" delete (int*)s.p;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct T {\n" // #10874
" T* p;\n"
"};\n"
"void f(T* t) {\n"
" for (decltype(t->p) (c) = t->p; ;) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(int i, std::vector<int*> v);\n" // #10880
"void g() {\n"
" f(1, { static_cast<int*>(nullptr) });\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct S { int i; };\n" // #10882
"enum E {};\n"
"void f(const S* s) {\n"
" E e = (E)!s->i;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(int* p) {\n" // #10932
" int& r(*p[0]);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("struct S { int i; };\n" // #10917
"bool f(S s) {\n"
" return [](int i) { return i > 0; }(s.i);\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("extern int (*p);\n" // #10936
"void f() {\n"
" for (int i = 0; ;) {}\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("class T {};\n" // #10849
"void f() {\n"
" auto g = [](const T* t) -> int {\n"
" const T* u{}, * v{};\n"
" return 0;\n"
" };\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("namespace N {\n" // #10876
" template <class R, class S, void(*T)(R&, float, S)>\n"
" inline void f() {}\n"
" template<class T>\n"
" void g(T& c) {\n"
" for (typename T::iterator v = c.begin(); v != c.end(); ++v) {}\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("void f(std::string a, std::string b) {\n" // #7529
" const std::string s = \" x \" + a;\n"
" +\" y = \" + b;\n"
"}\n", /*inconclusive*/ true);
ASSERT_EQUALS("[test.cpp:3]: (warning, inconclusive) Found suspicious operator '+', result is not used.\n", errout_str());
check("void f() {\n"
" *new int;\n"
"}\n", /*inconclusive*/ true);
ASSERT_EQUALS("[test.cpp:2]: (warning, inconclusive) Found suspicious operator '*', result is not used.\n", errout_str());
check("void f(int x, int y) {\n" // #12525
" x * y;\n"
"}\n", /*inconclusive*/ true);
ASSERT_EQUALS("[test.cpp:2]: (warning, inconclusive) Found suspicious operator '*', result is not used.\n", errout_str());
check("void f() {\n" // #5475
" std::string(\"a\") + \"a\";\n"
"}\n"
"void f(std::string& a) {\n"
" a.erase(3) + \"suf\";\n"
"}\n", /*inconclusive*/ true);
ASSERT_EQUALS("[test.cpp:2]: (warning, inconclusive) Found suspicious operator '+', result is not used.\n"
"[test.cpp:5]: (warning, inconclusive) Found suspicious operator '+', result is not used.\n",
errout_str());
check("void f(XMLElement& parent) {\n" // #11234
" auto** elem = &parent.firstChild;\n"
"}\n", /*inconclusive*/ true);
ASSERT_EQUALS("", errout_str());
check("void f() {\n" // #11301
" NULL;\n"
" nullptr;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (warning) Redundant code: Found a statement that begins with NULL constant.\n"
"[test.cpp:3]: (warning) Redundant code: Found a statement that begins with NULL constant.\n",
errout_str());
check("struct S { int i; };\n" // #6504
"void f(S* s) {\n"
" (*s).i;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (warning) Redundant code: Found unused member access.\n", errout_str());
check("int a[2];\n" // #11370
"void f() {\n"
" auto g = [](decltype(a[0]) i) {};\n"
"}\n");
ASSERT_EQUALS("", errout_str());
check("enum E { E0 };\n"
"void f() {\n"
" E0;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (warning) Redundant code: Found a statement that begins with enumerator constant.\n",
errout_str());
check("void f(int* a) {\n" // #12534
" a[a[3]];\n"
" a[a[g()]];\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (warning) Redundant code: Found unused array access.\n",
errout_str());
}
void vardecl() {
// #8984
check("void f() { a::b *c = d(); }", true);
ASSERT_EQUALS("", errout_str());
check("void f() { std::vector<b> *c; }", true);
ASSERT_EQUALS("", errout_str());
check("void f() { a::b &c = d(); }", true);
ASSERT_EQUALS("", errout_str());
check("void f() { std::vector<b> &c; }", true);
ASSERT_EQUALS("", errout_str());
check("void f() { a::b &&c = d(); }", true);
ASSERT_EQUALS("", errout_str());
check("void f() { std::vector<b> &&c; }", true);
ASSERT_EQUALS("", errout_str());
check("void f() { char * const * a, * const * b; }", true);
ASSERT_EQUALS("", errout_str());
check("void f() { char * const * a = 0, * volatile restrict * b; }", true, /*cpp*/ false);
ASSERT_EQUALS("", errout_str());
check("void f() { char * const * a = 0, * volatile const * b; }", true);
ASSERT_EQUALS("", errout_str());
}
void archive() {
check("void f(Archive &ar) {\n"
" ar & x;\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("void f(int ar) {\n"
" ar & x;\n"
"}", true);
ASSERT_EQUALS("[test.cpp:2]: (warning, inconclusive) Found suspicious operator '&', result is not used.\n", errout_str());
}
void ast() {
check("struct c { void a() const { for (int x=0; x;); } };", true);
ASSERT_EQUALS("", errout_str());
}
void oror() {
check("void foo() {\n"
" params_given (params, \"overrides\") || (overrides = \"1\");\n"
"}", true);
ASSERT_EQUALS("", errout_str());
check("void f(std::ifstream& file) {\n" // #10930
" int a{}, b{};\n"
" (file >> a) || (file >> b);\n"
" (file >> a) && (file >> b);\n"
"}\n", true);
ASSERT_EQUALS("", errout_str());
}
};
REGISTER_TEST(TestIncompleteStatement)
| null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.