Rename _tokenizer, _settings, _errorLogger

This commit is contained in:
Daniel Marjamäki 2018-06-16 16:10:28 +02:00
parent 8209c4aebd
commit 79ffe1d4fc
40 changed files with 1013 additions and 1013 deletions

View File

@ -25,7 +25,7 @@
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
Check::Check(const std::string &aname) Check::Check(const std::string &aname)
: _tokenizer(nullptr), _settings(nullptr), _errorLogger(nullptr), _name(aname) : mTokenizer(nullptr), mSettings(nullptr), mErrorLogger(nullptr), _name(aname)
{ {
for (std::list<Check*>::iterator i = instances().begin(); i != instances().end(); ++i) { for (std::list<Check*>::iterator i = instances().begin(); i != instances().end(); ++i) {
if ((*i)->name() > aname) { if ((*i)->name() > aname) {

View File

@ -52,11 +52,11 @@ public:
/** This constructor is used when running checks. */ /** This constructor is used when running checks. */
Check(const std::string &aname, const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) Check(const std::string &aname, const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: _tokenizer(tokenizer), _settings(settings), _errorLogger(errorLogger), _name(aname) { : mTokenizer(tokenizer), mSettings(settings), mErrorLogger(errorLogger), _name(aname) {
} }
virtual ~Check() { virtual ~Check() {
if (!_tokenizer) if (!mTokenizer)
instances().remove(this); instances().remove(this);
} }
@ -118,9 +118,9 @@ public:
} }
protected: protected:
const Tokenizer * const _tokenizer; const Tokenizer * const mTokenizer;
const Settings * const _settings; const Settings * const mSettings;
ErrorLogger * const _errorLogger; ErrorLogger * const mErrorLogger;
/** report an error */ /** report an error */
template<typename T, typename U> template<typename T, typename U>
@ -144,17 +144,17 @@ protected:
/** report an error */ /** report an error */
template<typename T, typename U> template<typename T, typename U>
void reportError(const std::list<const Token *> &callstack, Severity::SeverityType severity, const T id, const U msg, const CWE &cwe, bool inconclusive) { void reportError(const std::list<const Token *> &callstack, Severity::SeverityType severity, const T id, const U msg, const CWE &cwe, bool inconclusive) {
const ErrorLogger::ErrorMessage errmsg(callstack, _tokenizer ? &_tokenizer->list : nullptr, severity, id, msg, cwe, inconclusive); const ErrorLogger::ErrorMessage errmsg(callstack, mTokenizer ? &mTokenizer->list : nullptr, severity, id, msg, cwe, inconclusive);
if (_errorLogger) if (mErrorLogger)
_errorLogger->reportErr(errmsg); mErrorLogger->reportErr(errmsg);
else else
reportError(errmsg); reportError(errmsg);
} }
void reportError(const ErrorPath &errorPath, Severity::SeverityType severity, const char id[], const std::string &msg, const CWE &cwe, bool inconclusive) { void reportError(const ErrorPath &errorPath, Severity::SeverityType severity, const char id[], const std::string &msg, const CWE &cwe, bool inconclusive) {
const ErrorLogger::ErrorMessage errmsg(errorPath, _tokenizer ? &_tokenizer->list : nullptr, severity, id, msg, cwe, inconclusive); const ErrorLogger::ErrorMessage errmsg(errorPath, mTokenizer ? &mTokenizer->list : nullptr, severity, id, msg, cwe, inconclusive);
if (_errorLogger) if (mErrorLogger)
_errorLogger->reportErr(errmsg); mErrorLogger->reportErr(errmsg);
else else
reportError(errmsg); reportError(errmsg);
} }
@ -163,7 +163,7 @@ protected:
ErrorPath errorPath; ErrorPath errorPath;
if (!value) { if (!value) {
errorPath.emplace_back(errtok,bug); errorPath.emplace_back(errtok,bug);
} else if (_settings->verbose || _settings->xml || !_settings->templateLocation.empty()) { } else if (mSettings->verbose || mSettings->xml || !mSettings->templateLocation.empty()) {
errorPath = value->errorPath; errorPath = value->errorPath;
errorPath.emplace_back(errtok,bug); errorPath.emplace_back(errtok,bug);
} else { } else {

View File

@ -43,10 +43,10 @@ namespace {
void Check64BitPortability::pointerassignment() void Check64BitPortability::pointerassignment()
{ {
if (!_settings->isEnabled(Settings::PORTABILITY)) if (!mSettings->isEnabled(Settings::PORTABILITY))
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
// Check return values // Check return values
for (const Scope * scope : symbolDatabase->functionScopes) { for (const Scope * scope : symbolDatabase->functionScopes) {

View File

@ -41,10 +41,10 @@ namespace {
void CheckAssert::assertWithSideEffects() void CheckAssert::assertWithSideEffects()
{ {
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
for (const Token* tok = _tokenizer->list.front(); tok; tok = tok->next()) { for (const Token* tok = mTokenizer->list.front(); tok; tok = tok->next()) {
if (!Token::simpleMatch(tok, "assert (")) if (!Token::simpleMatch(tok, "assert ("))
continue; continue;

View File

@ -179,12 +179,12 @@ static bool variableIsUsedInScope(const Token* start, unsigned int varId, const
void CheckAutoVariables::assignFunctionArg() void CheckAutoVariables::assignFunctionArg()
{ {
const bool printStyle = _settings->isEnabled(Settings::STYLE); const bool printStyle = mSettings->isEnabled(Settings::STYLE);
const bool printWarning = _settings->isEnabled(Settings::WARNING); const bool printWarning = mSettings->isEnabled(Settings::WARNING);
if (!printStyle && !printWarning) if (!printStyle && !printWarning)
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) { for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token *tok = scope->bodyStart; tok && tok != scope->bodyEnd; tok = tok->next()) { for (const Token *tok = scope->bodyStart; tok && tok != scope->bodyEnd; tok = tok->next()) {
// TODO: What happens if this is removed? // TODO: What happens if this is removed?
@ -224,8 +224,8 @@ static bool reassignedGlobalPointer(const Token *vartok, unsigned int pointerVar
void CheckAutoVariables::autoVariables() void CheckAutoVariables::autoVariables()
{ {
const bool printInconclusive = _settings->inconclusive; const bool printInconclusive = mSettings->inconclusive;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) { for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token *tok = scope->bodyStart; tok && tok != scope->bodyEnd; tok = tok->next()) { for (const Token *tok = scope->bodyStart; tok && tok != scope->bodyEnd; tok = tok->next()) {
// Critical assignment // Critical assignment
@ -235,7 +235,7 @@ void CheckAutoVariables::autoVariables()
} else if (Token::Match(tok, "[;{}] * %var% = & %var%") && isPtrArg(tok->tokAt(2)) && isAutoVar(tok->tokAt(5))) { } else if (Token::Match(tok, "[;{}] * %var% = & %var%") && isPtrArg(tok->tokAt(2)) && isAutoVar(tok->tokAt(5))) {
if (checkRvalueExpression(tok->tokAt(5))) if (checkRvalueExpression(tok->tokAt(5)))
errorAutoVariableAssignment(tok->next(), false); errorAutoVariableAssignment(tok->next(), false);
} else if (_settings->isEnabled(Settings::WARNING) && Token::Match(tok, "[;{}] %var% = &| %var% ;") && isGlobalPtr(tok->next())) { } else if (mSettings->isEnabled(Settings::WARNING) && Token::Match(tok, "[;{}] %var% = &| %var% ;") && isGlobalPtr(tok->next())) {
const Token * const pointer = tok->next(); const Token * const pointer = tok->next();
if (isAutoVarArray(tok->tokAt(3))) { if (isAutoVarArray(tok->tokAt(3))) {
const Token * const array = tok->tokAt(3); const Token * const array = tok->tokAt(3);
@ -281,7 +281,7 @@ void CheckAutoVariables::autoVariables()
for (std::list<ValueFlow::Value>::const_iterator it = values.begin(); it != values.end(); ++it) { for (std::list<ValueFlow::Value>::const_iterator it = values.begin(); it != values.end(); ++it) {
if (!it->isTokValue()) if (!it->isTokValue())
continue; continue;
if (!_settings->inconclusive && it->isInconclusive()) if (!mSettings->inconclusive && it->isInconclusive())
continue; continue;
if (!Token::Match(it->tokvalue->previous(), "= & %var%")) if (!Token::Match(it->tokvalue->previous(), "= & %var%"))
continue; continue;
@ -306,13 +306,13 @@ void CheckAutoVariables::autoVariables()
} }
} }
// Invalid pointer deallocation // Invalid pointer deallocation
else if ((Token::Match(tok, "%name% ( %var% ) ;") && _settings->library.dealloc(tok)) || else if ((Token::Match(tok, "%name% ( %var% ) ;") && mSettings->library.dealloc(tok)) ||
(_tokenizer->isCPP() && Token::Match(tok, "delete [| ]| (| %var% !!["))) { (mTokenizer->isCPP() && Token::Match(tok, "delete [| ]| (| %var% !!["))) {
tok = Token::findmatch(tok->next(), "%var%"); tok = Token::findmatch(tok->next(), "%var%");
if (isAutoVarArray(tok)) if (isAutoVarArray(tok))
errorInvalidDeallocation(tok); errorInvalidDeallocation(tok);
} else if ((Token::Match(tok, "%name% ( & %var% ) ;") && _settings->library.dealloc(tok)) || } else if ((Token::Match(tok, "%name% ( & %var% ) ;") && mSettings->library.dealloc(tok)) ||
(_tokenizer->isCPP() && Token::Match(tok, "delete [| ]| (| & %var% !!["))) { (mTokenizer->isCPP() && Token::Match(tok, "delete [| ]| (| & %var% !!["))) {
tok = Token::findmatch(tok->next(), "%var%"); tok = Token::findmatch(tok->next(), "%var%");
if (isAutoVar(tok)) if (isAutoVar(tok))
errorInvalidDeallocation(tok); errorInvalidDeallocation(tok);
@ -325,7 +325,7 @@ void CheckAutoVariables::autoVariables()
void CheckAutoVariables::returnPointerToLocalArray() void CheckAutoVariables::returnPointerToLocalArray()
{ {
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) { for (const Scope * scope : symbolDatabase->functionScopes) {
if (!scope->function) if (!scope->function)
@ -506,10 +506,10 @@ static bool astHasAutoResult(const Token *tok)
void CheckAutoVariables::returnReference() void CheckAutoVariables::returnReference()
{ {
if (_tokenizer->isC()) if (mTokenizer->isC())
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) { for (const Scope * scope : symbolDatabase->functionScopes) {
if (!scope->function) if (!scope->function)

View File

@ -54,10 +54,10 @@ static bool isNonBoolStdType(const Variable* var)
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
void CheckBool::checkIncrementBoolean() void CheckBool::checkIncrementBoolean()
{ {
if (!_settings->isEnabled(Settings::STYLE)) if (!mSettings->isEnabled(Settings::STYLE))
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) { for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (Token::Match(tok, "%var% ++")) { if (Token::Match(tok, "%var% ++")) {
@ -87,15 +87,15 @@ void CheckBool::incrementBooleanError(const Token *tok)
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
void CheckBool::checkBitwiseOnBoolean() void CheckBool::checkBitwiseOnBoolean()
{ {
if (!_settings->isEnabled(Settings::STYLE)) if (!mSettings->isEnabled(Settings::STYLE))
return; return;
// danmar: this is inconclusive because I don't like that there are // danmar: this is inconclusive because I don't like that there are
// warnings for calculations. Example: set_flag(a & b); // warnings for calculations. Example: set_flag(a & b);
if (!_settings->inconclusive) if (!mSettings->inconclusive)
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) { for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (Token::Match(tok, "(|.|return|&&|%oror%|throw|, %var% [&|]")) { if (Token::Match(tok, "(|.|return|&&|%oror%|throw|, %var% [&|]")) {
@ -129,10 +129,10 @@ void CheckBool::bitwiseOnBooleanError(const Token *tok, const std::string &varna
void CheckBool::checkComparisonOfBoolWithInt() void CheckBool::checkComparisonOfBoolWithInt()
{ {
if (!_settings->isEnabled(Settings::WARNING) || !_tokenizer->isCPP()) if (!mSettings->isEnabled(Settings::WARNING) || !mTokenizer->isCPP())
return; return;
const SymbolDatabase* const symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) { for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
const Token* const left = tok->astOperand1(); const Token* const left = tok->astOperand1();
@ -178,13 +178,13 @@ static bool tokenIsFunctionReturningBool(const Token* tok)
void CheckBool::checkComparisonOfFuncReturningBool() void CheckBool::checkComparisonOfFuncReturningBool()
{ {
if (!_settings->isEnabled(Settings::STYLE)) if (!mSettings->isEnabled(Settings::STYLE))
return; return;
if (!_tokenizer->isCPP()) if (!mTokenizer->isCPP())
return; return;
const SymbolDatabase * const symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase * const symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) { for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
@ -237,16 +237,16 @@ void CheckBool::checkComparisonOfBoolWithBool()
{ {
// FIXME: This checking is "experimental" because of the false positives // FIXME: This checking is "experimental" because of the false positives
// when self checking lib/tokenize.cpp (#2617) // when self checking lib/tokenize.cpp (#2617)
if (!_settings->experimental) if (!mSettings->experimental)
return; return;
if (!_settings->isEnabled(Settings::STYLE)) if (!mSettings->isEnabled(Settings::STYLE))
return; return;
if (!_tokenizer->isCPP()) if (!mTokenizer->isCPP())
return; return;
const SymbolDatabase* const symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) { for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
@ -289,7 +289,7 @@ void CheckBool::comparisonOfBoolWithBoolError(const Token *tok, const std::strin
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
void CheckBool::checkAssignBoolToPointer() void CheckBool::checkAssignBoolToPointer()
{ {
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) { for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) { for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
if (tok->str() == "=" && astIsBool(tok->astOperand2())) { if (tok->str() == "=" && astIsBool(tok->astOperand2())) {
@ -315,10 +315,10 @@ void CheckBool::assignBoolToPointerError(const Token *tok)
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
void CheckBool::checkComparisonOfBoolExpressionWithInt() void CheckBool::checkComparisonOfBoolExpressionWithInt()
{ {
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
const SymbolDatabase* symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) { for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
@ -359,7 +359,7 @@ void CheckBool::checkComparisonOfBoolExpressionWithInt()
: Token::Match(tok, ">|==|!="))) : Token::Match(tok, ">|==|!=")))
continue; continue;
comparisonOfBoolExpressionWithIntError(tok, true); comparisonOfBoolExpressionWithIntError(tok, true);
} else if (isNonBoolStdType(numTok->variable()) && _tokenizer->isCPP()) } else if (isNonBoolStdType(numTok->variable()) && mTokenizer->isCPP())
comparisonOfBoolExpressionWithIntError(tok, false); comparisonOfBoolExpressionWithIntError(tok, false);
} }
} }
@ -378,7 +378,7 @@ void CheckBool::comparisonOfBoolExpressionWithIntError(const Token *tok, bool n0
void CheckBool::pointerArithBool() void CheckBool::pointerArithBool()
{ {
const SymbolDatabase* symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope &scope : symbolDatabase->scopeList) { for (const Scope &scope : symbolDatabase->scopeList) {
if (scope.type != Scope::eIf && scope.type != Scope::eWhile && scope.type != Scope::eDo && scope.type != Scope::eFor) if (scope.type != Scope::eIf && scope.type != Scope::eWhile && scope.type != Scope::eDo && scope.type != Scope::eFor)
@ -429,11 +429,11 @@ void CheckBool::pointerArithBoolError(const Token *tok)
void CheckBool::checkAssignBoolToFloat() void CheckBool::checkAssignBoolToFloat()
{ {
if (!_tokenizer->isCPP()) if (!mTokenizer->isCPP())
return; return;
if (!_settings->isEnabled(Settings::STYLE)) if (!mSettings->isEnabled(Settings::STYLE))
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) { for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) { for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
if (tok->str() == "=" && astIsBool(tok->astOperand2())) { if (tok->str() == "=" && astIsBool(tok->astOperand2())) {

View File

@ -33,7 +33,7 @@ static const CWE CWE664(664);
void CheckBoost::checkBoostForeachModification() void CheckBoost::checkBoostForeachModification()
{ {
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) { for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token *tok = scope->bodyStart->next(); tok && tok != scope->bodyEnd; tok = tok->next()) { for (const Token *tok = scope->bodyStart->next(); tok && tok != scope->bodyEnd; tok = tok->next()) {
if (!Token::simpleMatch(tok, "BOOST_FOREACH (")) if (!Token::simpleMatch(tok, "BOOST_FOREACH ("))

View File

@ -93,7 +93,7 @@ void CheckBufferOverrun::arrayIndexOutOfBoundsError(const Token *tok, const Arra
} }
std::list<ErrorPathItem> errorPath; std::list<ErrorPathItem> errorPath;
if (_settings->xml || !_settings->templateLocation.empty()) { if (mSettings->xml || !mSettings->templateLocation.empty()) {
for (std::size_t i = 0; i < index.size(); ++i) { for (std::size_t i = 0; i < index.size(); ++i) {
const ErrorPath &e = getErrorPath(tok, &index[i], ""); const ErrorPath &e = getErrorPath(tok, &index[i], "");
for (ErrorPath::const_iterator it = e.begin(); it != e.end(); ++it) { for (ErrorPath::const_iterator it = e.begin(); it != e.end(); ++it) {
@ -114,7 +114,7 @@ void CheckBufferOverrun::arrayIndexOutOfBoundsError(const Token *tok, const Arra
} }
if (condition != nullptr) { if (condition != nullptr) {
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
std::ostringstream errmsg; std::ostringstream errmsg;
@ -198,7 +198,7 @@ void CheckBufferOverrun::possibleBufferOverrunError(const Token *tok, const std:
void CheckBufferOverrun::strncatUsageError(const Token *tok) void CheckBufferOverrun::strncatUsageError(const Token *tok)
{ {
if (_settings && !_settings->isEnabled(Settings::WARNING)) if (mSettings && !mSettings->isEnabled(Settings::WARNING))
return; return;
reportError(tok, Severity::warning, "strncatUsage", reportError(tok, Severity::warning, "strncatUsage",
@ -249,7 +249,7 @@ void CheckBufferOverrun::pointerOutOfBoundsError(const Token *tok, const Token *
void CheckBufferOverrun::sizeArgumentAsCharError(const Token *tok) void CheckBufferOverrun::sizeArgumentAsCharError(const Token *tok)
{ {
if (_settings && !_settings->isEnabled(Settings::WARNING)) if (mSettings && !mSettings->isEnabled(Settings::WARNING))
return; return;
reportError(tok, Severity::warning, "sizeArgumentAsChar", "The size argument is given as a char constant.", CWE682, false); reportError(tok, Severity::warning, "sizeArgumentAsChar", "The size argument is given as a char constant.", CWE682, false);
} }
@ -421,7 +421,7 @@ static bool checkMinSizes(const std::vector<Library::ArgumentChecks::MinSize> &m
void CheckBufferOverrun::checkFunctionParameter(const Token &ftok, unsigned int paramIndex, const ArrayInfo &arrayInfo, const std::list<const Token *>& callstack) void CheckBufferOverrun::checkFunctionParameter(const Token &ftok, unsigned int paramIndex, const ArrayInfo &arrayInfo, const std::list<const Token *>& callstack)
{ {
const std::vector<Library::ArgumentChecks::MinSize> * const minsizes = _settings->library.argminsizes(&ftok, paramIndex); const std::vector<Library::ArgumentChecks::MinSize> * const minsizes = mSettings->library.argminsizes(&ftok, paramIndex);
if (minsizes) { if (minsizes) {
MathLib::bigint arraySize = arrayInfo.element_size(); MathLib::bigint arraySize = arrayInfo.element_size();
@ -435,7 +435,7 @@ void CheckBufferOverrun::checkFunctionParameter(const Token &ftok, unsigned int
return; return;
const Token *charSizeToken = nullptr; const Token *charSizeToken = nullptr;
if (checkMinSizes(*minsizes, &ftok, arraySize, &charSizeToken, _settings)) if (checkMinSizes(*minsizes, &ftok, arraySize, &charSizeToken, mSettings))
bufferOverrunError(callstack, arrayInfo.varname()); bufferOverrunError(callstack, arrayInfo.varname());
if (charSizeToken) if (charSizeToken)
sizeArgumentAsCharError(charSizeToken); sizeArgumentAsCharError(charSizeToken);
@ -511,7 +511,7 @@ void CheckBufferOverrun::checkFunctionParameter(const Token &ftok, unsigned int
} }
// Check 'float x[10]' arguments in declaration // Check 'float x[10]' arguments in declaration
if (_settings->isEnabled(Settings::WARNING)) { if (mSettings->isEnabled(Settings::WARNING)) {
const Function* const func = ftok.function(); const Function* const func = ftok.function();
// If argument is '%type% a[num]' then check bounds against num // If argument is '%type% a[num]' then check bounds against num
@ -588,7 +588,7 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vector<const st
return; return;
} }
const bool printInconclusive = _settings->inconclusive; const bool printInconclusive = mSettings->inconclusive;
const MathLib::bigint total_size = arrayInfo.element_size() * size; const MathLib::bigint total_size = arrayInfo.element_size() * size;
const unsigned int declarationId = arrayInfo.declarationId(); const unsigned int declarationId = arrayInfo.declarationId();
@ -612,7 +612,7 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vector<const st
// out of bounds then this flag will be set. // out of bounds then this flag will be set.
bool pointerIsOutOfBounds = false; bool pointerIsOutOfBounds = false;
const bool printPortability = _settings->isEnabled(Settings::PORTABILITY); const bool printPortability = mSettings->isEnabled(Settings::PORTABILITY);
for (const Token* const end = tok->scope()->bodyEnd; tok && tok != end; tok = tok->next()) { for (const Token* const end = tok->scope()->bodyEnd; tok && tok != end; tok = tok->next()) {
if (declarationId != 0 && Token::Match(tok, "%varid% = new|malloc|realloc", declarationId)) { if (declarationId != 0 && Token::Match(tok, "%varid% = new|malloc|realloc", declarationId)) {
@ -833,7 +833,7 @@ void CheckBufferOverrun::valueFlowCheckArrayIndex(const Token * const tok, const
return; return;
} }
*/ */
const bool printInconclusive = _settings->inconclusive; const bool printInconclusive = mSettings->inconclusive;
// Taking address? // Taking address?
const bool addressOf = isAddressOf(tok); const bool addressOf = isAddressOf(tok);
@ -844,7 +844,7 @@ void CheckBufferOverrun::valueFlowCheckArrayIndex(const Token * const tok, const
const Token *index = tok2->astOperand2(); const Token *index = tok2->astOperand2();
if (!index) if (!index)
continue; continue;
const ValueFlow::Value *value = index->getValueLE(-1LL,_settings); const ValueFlow::Value *value = index->getValueLE(-1LL,mSettings);
if (value) if (value)
negativeIndexError(index, *value); negativeIndexError(index, *value);
} }
@ -941,9 +941,9 @@ void CheckBufferOverrun::checkScope(const Token *tok, std::map<unsigned int, Arr
void CheckBufferOverrun::checkScope_inner(const Token *tok, const ArrayInfo &arrayInfo) void CheckBufferOverrun::checkScope_inner(const Token *tok, const ArrayInfo &arrayInfo)
{ {
const bool printPortability = _settings->isEnabled(Settings::PORTABILITY); const bool printPortability = mSettings->isEnabled(Settings::PORTABILITY);
const bool printWarning = _settings->isEnabled(Settings::WARNING); const bool printWarning = mSettings->isEnabled(Settings::WARNING);
const bool printInconclusive = _settings->inconclusive; const bool printInconclusive = mSettings->inconclusive;
const Token *astParent = tok->astParent(); const Token *astParent = tok->astParent();
@ -959,9 +959,9 @@ void CheckBufferOverrun::checkScope_inner(const Token *tok, const ArrayInfo &arr
else else
index = astParent->astOperand1(); index = astParent->astOperand1();
if (index) { if (index) {
const ValueFlow::Value *value = index->getValueGE(arrayInfo.num(0) + 1U, _settings); const ValueFlow::Value *value = index->getValueGE(arrayInfo.num(0) + 1U, mSettings);
if (!value) if (!value)
value = index->getValueLE(-1, _settings); value = index->getValueLE(-1, mSettings);
if (value) if (value)
pointerOutOfBoundsError(astParent, index, value->intvalue); pointerOutOfBoundsError(astParent, index, value->intvalue);
} }
@ -971,9 +971,9 @@ void CheckBufferOverrun::checkScope_inner(const Token *tok, const ArrayInfo &arr
const Variable *var = symbolDatabase->getVariableFromVarId(arrayInfo.declarationId()); const Variable *var = symbolDatabase->getVariableFromVarId(arrayInfo.declarationId());
if (var && var->isArray()) { if (var && var->isArray()) {
const Token *index = astParent->astOperand2(); const Token *index = astParent->astOperand2();
const ValueFlow::Value *value = index ? index->getValueGE(1,_settings) : nullptr; const ValueFlow::Value *value = index ? index->getValueGE(1,mSettings) : nullptr;
if (index && !value) if (index && !value)
value = index->getValueLE(-1 - arrayInfo.num(0), _settings); value = index->getValueLE(-1 - arrayInfo.num(0), mSettings);
if (value) if (value)
pointerOutOfBoundsError(astParent, index, value->intvalue); pointerOutOfBoundsError(astParent, index, value->intvalue);
} }
@ -1114,7 +1114,7 @@ void CheckBufferOverrun::negativeArraySize()
const Token * const nameToken = var->nameToken(); const Token * const nameToken = var->nameToken();
if (!Token::Match(nameToken, "%var% [") || !nameToken->next()->astOperand2()) if (!Token::Match(nameToken, "%var% [") || !nameToken->next()->astOperand2())
continue; continue;
const ValueFlow::Value *sz = nameToken->next()->astOperand2()->getValueLE(-1,_settings); const ValueFlow::Value *sz = nameToken->next()->astOperand2()->getValueLE(-1,mSettings);
// don't warn about constant negative index because that is a compiler error // don't warn about constant negative index because that is a compiler error
if (sz && isVLAIndex(nameToken->next()->astOperand2())) if (sz && isVLAIndex(nameToken->next()->astOperand2()))
negativeArraySizeError(nameToken); negativeArraySizeError(nameToken);
@ -1160,7 +1160,7 @@ bool CheckBufferOverrun::isArrayOfStruct(const Token* tok, int &position)
void CheckBufferOverrun::checkGlobalAndLocalVariable() void CheckBufferOverrun::checkGlobalAndLocalVariable()
{ {
// check string literals // check string literals
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (Token::Match(tok, "%str% [") && tok->next()->astOperand2()) { if (Token::Match(tok, "%str% [") && tok->next()->astOperand2()) {
const std::size_t size = Token::getStrSize(tok); const std::size_t size = Token::getStrSize(tok);
const ValueFlow::Value *value = tok->next()->astOperand2()->getMaxValue(false); const ValueFlow::Value *value = tok->next()->astOperand2()->getMaxValue(false);
@ -1212,11 +1212,11 @@ void CheckBufferOverrun::checkGlobalAndLocalVariable()
for (std::list<Variable>::const_iterator var = scope->varlist.cbegin(); var != scope->varlist.cend(); ++var) { for (std::list<Variable>::const_iterator var = scope->varlist.cbegin(); var != scope->varlist.cend(); ++var) {
if (!var->isArray() || var->dimension(0) <= 0) if (!var->isArray() || var->dimension(0) <= 0)
continue; continue;
_errorLogger->reportProgress(_tokenizer->list.getSourceFilePath(), mErrorLogger->reportProgress(mTokenizer->list.getSourceFilePath(),
"Check (BufferOverrun::checkGlobalAndLocalVariable 1)", "Check (BufferOverrun::checkGlobalAndLocalVariable 1)",
var->nameToken()->progressValue()); var->nameToken()->progressValue());
if (_tokenizer->isMaxTime()) if (mTokenizer->isMaxTime())
return; return;
const Token *tok = var->nameToken(); const Token *tok = var->nameToken();
@ -1234,7 +1234,7 @@ void CheckBufferOverrun::checkGlobalAndLocalVariable()
arrayInfos[var->declarationId()] = ArrayInfo(&*var, symbolDatabase, var->declarationId()); arrayInfos[var->declarationId()] = ArrayInfo(&*var, symbolDatabase, var->declarationId());
} }
if (!arrayInfos.empty()) if (!arrayInfos.empty())
checkScope(scope->bodyStart ? scope->bodyStart : _tokenizer->tokens(), arrayInfos); checkScope(scope->bodyStart ? scope->bodyStart : mTokenizer->tokens(), arrayInfos);
} }
const std::vector<const std::string*> v; const std::vector<const std::string*> v;
@ -1254,17 +1254,17 @@ void CheckBufferOverrun::checkGlobalAndLocalVariable()
// nextTok : used to skip to next statement. // nextTok : used to skip to next statement.
const Token * nextTok = tok; const Token * nextTok = tok;
_errorLogger->reportProgress(_tokenizer->list.getSourceFilePath(), mErrorLogger->reportProgress(mTokenizer->list.getSourceFilePath(),
"Check (BufferOverrun::checkGlobalAndLocalVariable 2)", "Check (BufferOverrun::checkGlobalAndLocalVariable 2)",
tok->progressValue()); tok->progressValue());
if (_tokenizer->isMaxTime()) if (mTokenizer->isMaxTime())
return; return;
// varid : The variable id for the array // varid : The variable id for the array
const Variable *var = tok->next()->variable(); const Variable *var = tok->next()->variable();
if (_tokenizer->isCPP() && Token::Match(tok, "[*;{}] %var% = new %type% [")) { if (mTokenizer->isCPP() && Token::Match(tok, "[*;{}] %var% = new %type% [")) {
tok = tok->tokAt(5); tok = tok->tokAt(5);
if (tok->astOperand2() == nullptr || tok->astOperand2()->getMaxValue(false) == nullptr) if (tok->astOperand2() == nullptr || tok->astOperand2()->getMaxValue(false) == nullptr)
continue; continue;
@ -1273,7 +1273,7 @@ void CheckBufferOverrun::checkGlobalAndLocalVariable()
if (size < 0) { if (size < 0) {
negativeMemoryAllocationSizeError(tok); negativeMemoryAllocationSizeError(tok);
} }
} else if (_tokenizer->isCPP() && Token::Match(tok, "[*;{}] %var% = new %type% (|;")) { } else if (mTokenizer->isCPP() && Token::Match(tok, "[*;{}] %var% = new %type% (|;")) {
size = 1; size = 1;
tok = tok->tokAt(5); tok = tok->tokAt(5);
if (tok->str() == ";") if (tok->str() == ";")
@ -1489,8 +1489,8 @@ void CheckBufferOverrun::checkStructVariable()
void CheckBufferOverrun::bufferOverrun() void CheckBufferOverrun::bufferOverrun()
{ {
// singlepass checking using ast, symboldatabase and valueflow // singlepass checking using ast, symboldatabase and valueflow
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (_settings->isEnabled(Settings::PORTABILITY) && tok->str() == "+" && tok->valueType() && tok->valueType()->pointer > 0) { if (mSettings->isEnabled(Settings::PORTABILITY) && tok->str() == "+" && tok->valueType() && tok->valueType()->pointer > 0) {
if (!tok->astOperand1() || !tok->astOperand1()->valueType()) if (!tok->astOperand1() || !tok->astOperand1()->valueType())
continue; continue;
if (!tok->astOperand2() || !tok->astOperand2()->valueType()) if (!tok->astOperand2() || !tok->astOperand2()->valueType())
@ -1519,7 +1519,7 @@ void CheckBufferOverrun::bufferOverrun()
if (!var || !var->isArray() || var->dimension(0) <= 0) if (!var || !var->isArray() || var->dimension(0) <= 0)
continue; continue;
const ValueFlow::Value *value = indexToken->getValueGE(var->dimension(0)+1, _settings); const ValueFlow::Value *value = indexToken->getValueGE(var->dimension(0)+1, mSettings);
if (value) { if (value) {
pointerOutOfBoundsError(tok, indexToken, value->intvalue); pointerOutOfBoundsError(tok, indexToken, value->intvalue);
} }
@ -1531,7 +1531,7 @@ void CheckBufferOverrun::bufferOverrun()
// TODO: what to do about negative index.. // TODO: what to do about negative index..
const Token *index = tok->next()->astOperand2(); const Token *index = tok->next()->astOperand2();
if (index && index->getValueLE(-1LL,_settings)) if (index && index->getValueLE(-1LL,mSettings))
continue; continue;
// Set full varname.. // Set full varname..
@ -1717,7 +1717,7 @@ void CheckBufferOverrun::checkBufferAllocatedWithStrlen()
const Token *varTok = tok->tokAt(4); const Token *varTok = tok->tokAt(4);
srcVarId = varTok->varId(); srcVarId = varTok->varId();
tok = varTok->tokAt(2); tok = varTok->tokAt(2);
} else if (_tokenizer->isCPP() && Token::Match(tok, "new char [ strlen ( %var% ) ]")) { } else if (mTokenizer->isCPP() && Token::Match(tok, "new char [ strlen ( %var% ) ]")) {
const Token *varTok = tok->tokAt(5); const Token *varTok = tok->tokAt(5);
srcVarId = varTok->varId(); srcVarId = varTok->varId();
tok = varTok->tokAt(2); tok = varTok->tokAt(2);
@ -1755,7 +1755,7 @@ void CheckBufferOverrun::checkStringArgument()
for (std::size_t functionIndex = 0; functionIndex < functions; ++functionIndex) { for (std::size_t functionIndex = 0; functionIndex < functions; ++functionIndex) {
const Scope * const scope = symbolDatabase->functionScopes[functionIndex]; const Scope * const scope = symbolDatabase->functionScopes[functionIndex];
for (const Token *tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) { for (const Token *tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
if (!Token::Match(tok, "%name% (") || !_settings->library.hasminsize(tok->str())) if (!Token::Match(tok, "%name% (") || !mSettings->library.hasminsize(tok->str()))
continue; continue;
unsigned int argnr = 1; unsigned int argnr = 1;
@ -1765,10 +1765,10 @@ void CheckBufferOverrun::checkStringArgument()
const Token *strtoken = argtok->getValueTokenMinStrSize(); const Token *strtoken = argtok->getValueTokenMinStrSize();
if (!strtoken) if (!strtoken)
continue; continue;
const std::vector<Library::ArgumentChecks::MinSize> *minsizes = _settings->library.argminsizes(tok, argnr); const std::vector<Library::ArgumentChecks::MinSize> *minsizes = mSettings->library.argminsizes(tok, argnr);
if (!minsizes) if (!minsizes)
continue; continue;
if (checkMinSizes(*minsizes, tok, Token::getStrSize(strtoken), nullptr, _settings)) if (checkMinSizes(*minsizes, tok, Token::getStrSize(strtoken), nullptr, mSettings))
bufferOverrunError(argtok); bufferOverrunError(argtok);
} }
} }
@ -1920,7 +1920,7 @@ MathLib::bigint CheckBufferOverrun::ArrayInfo::totalIndex(const std::vector<Valu
void CheckBufferOverrun::arrayIndexThenCheck() void CheckBufferOverrun::arrayIndexThenCheck()
{ {
if (!_settings->isEnabled(Settings::PORTABILITY)) if (!mSettings->isEnabled(Settings::PORTABILITY))
return; return;
const std::size_t functions = symbolDatabase->functionScopes.size(); const std::size_t functions = symbolDatabase->functionScopes.size();

View File

@ -80,12 +80,12 @@ CheckClass::CheckClass(const Tokenizer *tokenizer, const Settings *settings, Err
void CheckClass::constructors() void CheckClass::constructors()
{ {
const bool printStyle = _settings->isEnabled(Settings::STYLE); const bool printStyle = mSettings->isEnabled(Settings::STYLE);
const bool printWarnings = _settings->isEnabled(Settings::WARNING); const bool printWarnings = mSettings->isEnabled(Settings::WARNING);
if (!printStyle && !printWarnings) if (!printStyle && !printWarnings)
return; return;
const bool printInconclusive = _settings->inconclusive; const bool printInconclusive = mSettings->inconclusive;
for (const Scope * scope : symbolDatabase->classAndStructScopes) { for (const Scope * scope : symbolDatabase->classAndStructScopes) {
bool usedInUnion = false; bool usedInUnion = false;
@ -210,7 +210,7 @@ void CheckClass::constructors()
if (classNameUsed) if (classNameUsed)
operatorEqVarError(func->token, scope->className, var->name(), inconclusive); operatorEqVarError(func->token, scope->className, var->name(), inconclusive);
} else if (func->access != Private || _settings->standards.cpp >= Standards::CPP11) { } else if (func->access != Private || mSettings->standards.cpp >= Standards::CPP11) {
const Scope *varType = var->typeScope(); const Scope *varType = var->typeScope();
if (!varType || varType->type != Scope::eUnion) { if (!varType || varType->type != Scope::eUnion) {
if (func->type == Function::eConstructor && if (func->type == Function::eConstructor &&
@ -232,7 +232,7 @@ void CheckClass::constructors()
void CheckClass::checkExplicitConstructors() void CheckClass::checkExplicitConstructors()
{ {
if (!_settings->isEnabled(Settings::STYLE)) if (!mSettings->isEnabled(Settings::STYLE))
return; return;
for (const Scope * scope : symbolDatabase->classAndStructScopes) { for (const Scope * scope : symbolDatabase->classAndStructScopes) {
@ -252,7 +252,7 @@ void CheckClass::checkExplicitConstructors()
// Abstract classes can't be instantiated. But if there is C++11 // Abstract classes can't be instantiated. But if there is C++11
// "misuse" by derived classes then these constructors must be explicit. // "misuse" by derived classes then these constructors must be explicit.
if (isAbstractClass && _settings->standards.cpp != Standards::CPP11) if (isAbstractClass && mSettings->standards.cpp != Standards::CPP11)
continue; continue;
for (const Function &func : scope->functionList) { for (const Function &func : scope->functionList) {
@ -301,7 +301,7 @@ static bool isNonCopyable(const Scope *scope, bool *unknown)
void CheckClass::copyconstructors() void CheckClass::copyconstructors()
{ {
if (!_settings->isEnabled(Settings::STYLE)) if (!mSettings->isEnabled(Settings::STYLE))
return; return;
for (const Scope * scope : symbolDatabase->classAndStructScopes) { for (const Scope * scope : symbolDatabase->classAndStructScopes) {
@ -313,7 +313,7 @@ void CheckClass::copyconstructors()
const Token* tok = func.token->linkAt(1); const Token* tok = func.token->linkAt(1);
for (const Token* const end = func.functionScope->bodyStart; tok != end; tok = tok->next()) { for (const Token* const end = func.functionScope->bodyStart; tok != end; tok = tok->next()) {
if (Token::Match(tok, "%var% ( new") || if (Token::Match(tok, "%var% ( new") ||
(Token::Match(tok, "%var% ( %name% (") && _settings->library.alloc(tok->tokAt(2)))) { (Token::Match(tok, "%var% ( %name% (") && mSettings->library.alloc(tok->tokAt(2)))) {
const Variable* var = tok->variable(); const Variable* var = tok->variable();
if (var && var->isPointer() && var->scope() == scope) if (var && var->isPointer() && var->scope() == scope)
allocatedVars[tok->varId()] = tok; allocatedVars[tok->varId()] = tok;
@ -321,7 +321,7 @@ void CheckClass::copyconstructors()
} }
for (const Token* const end = func.functionScope->bodyEnd; tok != end; tok = tok->next()) { for (const Token* const end = func.functionScope->bodyEnd; tok != end; tok = tok->next()) {
if (Token::Match(tok, "%var% = new") || if (Token::Match(tok, "%var% = new") ||
(Token::Match(tok, "%var% = %name% (") && _settings->library.alloc(tok->tokAt(2)))) { (Token::Match(tok, "%var% = %name% (") && mSettings->library.alloc(tok->tokAt(2)))) {
const Variable* var = tok->variable(); const Variable* var = tok->variable();
if (var && var->isPointer() && var->scope() == scope && !var->isStatic()) if (var && var->isPointer() && var->scope() == scope && !var->isStatic())
allocatedVars[tok->varId()] = tok; allocatedVars[tok->varId()] = tok;
@ -914,7 +914,7 @@ void CheckClass::operatorEqVarError(const Token *tok, const std::string &classna
void CheckClass::initializationListUsage() void CheckClass::initializationListUsage()
{ {
if (!_settings->isEnabled(Settings::PERFORMANCE)) if (!mSettings->isEnabled(Settings::PERFORMANCE))
return; return;
for (const Scope *scope : symbolDatabase->functionScopes) { for (const Scope *scope : symbolDatabase->functionScopes) {
@ -1027,7 +1027,7 @@ static bool checkFunctionUsage(const Function *privfunc, const Scope* scope)
void CheckClass::privateFunctions() void CheckClass::privateFunctions()
{ {
if (!_settings->isEnabled(Settings::STYLE)) if (!mSettings->isEnabled(Settings::STYLE))
return; return;
for (const Scope * scope : symbolDatabase->classAndStructScopes) { for (const Scope * scope : symbolDatabase->classAndStructScopes) {
@ -1095,7 +1095,7 @@ static const Scope* findFunctionOf(const Scope* scope)
void CheckClass::checkMemset() void CheckClass::checkMemset()
{ {
const bool printWarnings = _settings->isEnabled(Settings::WARNING); const bool printWarnings = mSettings->isEnabled(Settings::WARNING);
for (const Scope *scope : symbolDatabase->functionScopes) { for (const Scope *scope : symbolDatabase->functionScopes) {
for (const Token *tok = scope->bodyStart; tok && tok != scope->bodyEnd; tok = tok->next()) { for (const Token *tok = scope->bodyStart; tok && tok != scope->bodyEnd; tok = tok->next()) {
if (Token::Match(tok, "memset|memcpy|memmove (")) { if (Token::Match(tok, "memset|memcpy|memmove (")) {
@ -1180,7 +1180,7 @@ void CheckClass::checkMemsetType(const Scope *start, const Token *tok, const Sco
return; return;
parsedTypes.insert(type); parsedTypes.insert(type);
const bool printPortability = _settings->isEnabled(Settings::PORTABILITY); const bool printPortability = mSettings->isEnabled(Settings::PORTABILITY);
// recursively check all parent classes // recursively check all parent classes
for (std::size_t i = 0; i < type->definedType->derivedFrom.size(); i++) { for (std::size_t i = 0; i < type->definedType->derivedFrom.size(); i++) {
@ -1215,7 +1215,7 @@ void CheckClass::checkMemsetType(const Scope *start, const Token *tok, const Sco
const Scope *typeScope = var->typeScope(); const Scope *typeScope = var->typeScope();
// check for std:: type // check for std:: type
if (var->isStlType() && tok1->strAt(2) != "array" && !_settings->library.podtype(tok1->strAt(2))) if (var->isStlType() && tok1->strAt(2) != "array" && !mSettings->library.podtype(tok1->strAt(2)))
if (allocation) if (allocation)
mallocOnClassError(tok, tok->str(), type->classDef, "'std::" + tok1->strAt(2) + "'"); mallocOnClassError(tok, tok->str(), type->classDef, "'std::" + tok1->strAt(2) + "'");
else else
@ -1287,7 +1287,7 @@ void CheckClass::memsetErrorFloat(const Token *tok, const std::string &type)
void CheckClass::operatorEq() void CheckClass::operatorEq()
{ {
if (!_settings->isEnabled(Settings::STYLE)) if (!mSettings->isEnabled(Settings::STYLE))
return; return;
for (const Scope * scope : symbolDatabase->classAndStructScopes) { for (const Scope * scope : symbolDatabase->classAndStructScopes) {
@ -1340,7 +1340,7 @@ void CheckClass::operatorEqReturnError(const Token *tok, const std::string &clas
void CheckClass::operatorEqRetRefThis() void CheckClass::operatorEqRetRefThis()
{ {
if (!_settings->isEnabled(Settings::STYLE)) if (!mSettings->isEnabled(Settings::STYLE))
return; return;
for (const Scope * scope : symbolDatabase->classAndStructScopes) { for (const Scope * scope : symbolDatabase->classAndStructScopes) {
@ -1426,7 +1426,7 @@ void CheckClass::checkReturnPtrThis(const Scope *scope, const Function *func, co
} }
return; return;
} }
if (_settings->library.isScopeNoReturn(last, nullptr)) { if (mSettings->library.isScopeNoReturn(last, nullptr)) {
// Typical wrong way to prohibit default assignment operator // Typical wrong way to prohibit default assignment operator
// by always throwing an exception or calling a noreturn function // by always throwing an exception or calling a noreturn function
operatorEqShouldBeLeftUnimplementedError(func->token); operatorEqShouldBeLeftUnimplementedError(func->token);
@ -1471,7 +1471,7 @@ void CheckClass::operatorEqMissingReturnStatementError(const Token *tok, bool er
void CheckClass::operatorEqToSelf() void CheckClass::operatorEqToSelf()
{ {
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
for (const Scope * scope : symbolDatabase->classAndStructScopes) { for (const Scope * scope : symbolDatabase->classAndStructScopes) {
@ -1594,7 +1594,7 @@ void CheckClass::virtualDestructor()
// * base class is deleted // * base class is deleted
// unless inconclusive in which case: // unless inconclusive in which case:
// * base class has virtual members but doesn't have virtual destructor // * base class has virtual members but doesn't have virtual destructor
const bool printInconclusive = _settings->inconclusive; const bool printInconclusive = mSettings->inconclusive;
std::list<const Function *> inconclusiveErrors; std::list<const Function *> inconclusiveErrors;
@ -1659,7 +1659,7 @@ void CheckClass::virtualDestructor()
// No deletion of derived class instance through base class pointer found => the code is ok // No deletion of derived class instance through base class pointer found => the code is ok
bool ok = true; bool ok = true;
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (Token::Match(tok, "[;{}] %var% =") && if (Token::Match(tok, "[;{}] %var% =") &&
baseClassPointers.find(tok->next()->varId()) != baseClassPointers.end()) { baseClassPointers.find(tok->next()->varId()) != baseClassPointers.end()) {
// new derived class.. // new derived class..
@ -1720,7 +1720,7 @@ void CheckClass::virtualDestructor()
void CheckClass::virtualDestructorError(const Token *tok, const std::string &Base, const std::string &Derived, bool inconclusive) void CheckClass::virtualDestructorError(const Token *tok, const std::string &Base, const std::string &Derived, bool inconclusive)
{ {
if (inconclusive) { if (inconclusive) {
if (_settings->isEnabled(Settings::WARNING)) if (mSettings->isEnabled(Settings::WARNING))
reportError(tok, Severity::warning, "virtualDestructor", "$symbol:" + Base + "\nClass '$symbol' which has virtual members does not have a virtual destructor.", CWE404, true); reportError(tok, Severity::warning, "virtualDestructor", "$symbol:" + Base + "\nClass '$symbol' which has virtual members does not have a virtual destructor.", CWE404, true);
} else { } else {
reportError(tok, Severity::error, "virtualDestructor", reportError(tok, Severity::error, "virtualDestructor",
@ -1740,10 +1740,10 @@ void CheckClass::virtualDestructorError(const Token *tok, const std::string &Bas
void CheckClass::thisSubtraction() void CheckClass::thisSubtraction()
{ {
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
const Token *tok = _tokenizer->tokens(); const Token *tok = mTokenizer->tokens();
for (;;) { for (;;) {
tok = Token::findmatch(tok, "this - %name%"); tok = Token::findmatch(tok, "this - %name%");
if (!tok) if (!tok)
@ -1768,10 +1768,10 @@ void CheckClass::thisSubtractionError(const Token *tok)
void CheckClass::checkConst() void CheckClass::checkConst()
{ {
// This is an inconclusive check. False positives: #3322. // This is an inconclusive check. False positives: #3322.
if (!_settings->inconclusive) if (!mSettings->inconclusive)
return; return;
if (!_settings->isEnabled(Settings::STYLE)) if (!mSettings->isEnabled(Settings::STYLE))
return; return;
for (const Scope * scope : symbolDatabase->classAndStructScopes) { for (const Scope * scope : symbolDatabase->classAndStructScopes) {
@ -2147,14 +2147,14 @@ namespace { // avoid one-definition-rule violation
void CheckClass::initializerListOrder() void CheckClass::initializerListOrder()
{ {
if (!_settings->isEnabled(Settings::STYLE)) if (!mSettings->isEnabled(Settings::STYLE))
return; return;
// This check is not inconclusive. However it only determines if the initialization // This check is not inconclusive. However it only determines if the initialization
// order is incorrect. It does not determine if being out of order causes // order is incorrect. It does not determine if being out of order causes
// a real error. Out of order is not necessarily an error but you can never // a real error. Out of order is not necessarily an error but you can never
// have an error if the list is in order so this enforces defensive programming. // have an error if the list is in order so this enforces defensive programming.
if (!_settings->inconclusive) if (!mSettings->inconclusive)
return; return;
for (const Scope * scope : symbolDatabase->classAndStructScopes) { for (const Scope * scope : symbolDatabase->classAndStructScopes) {
@ -2248,7 +2248,7 @@ void CheckClass::selfInitializationError(const Token* tok, const std::string& va
void CheckClass::checkVirtualFunctionCallInConstructor() void CheckClass::checkVirtualFunctionCallInConstructor()
{ {
if (! _settings->isEnabled(Settings::WARNING)) if (! mSettings->isEnabled(Settings::WARNING))
return; return;
std::map<const Function *, std::list<const Token *> > virtualFunctionCallsMap; std::map<const Function *, std::list<const Token *> > virtualFunctionCallsMap;
for (const Scope *scope : symbolDatabase->functionScopes) { for (const Scope *scope : symbolDatabase->functionScopes) {
@ -2310,8 +2310,8 @@ const std::list<const Token *> & CheckClass::getVirtualFunctionCalls(const Funct
tok->previous()->str() == "(") { tok->previous()->str() == "(") {
const Token * prev = tok->previous(); const Token * prev = tok->previous();
if (prev->previous() && if (prev->previous() &&
(_settings->library.ignorefunction(tok->str()) (mSettings->library.ignorefunction(tok->str())
|| _settings->library.ignorefunction(prev->previous()->str()))) || mSettings->library.ignorefunction(prev->previous()->str())))
continue; continue;
} }
@ -2410,7 +2410,7 @@ void CheckClass::pureVirtualFunctionCallInConstructorError(
void CheckClass::checkDuplInheritedMembers() void CheckClass::checkDuplInheritedMembers()
{ {
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
// Iterate over all classes // Iterate over all classes
@ -2470,7 +2470,7 @@ enum CtorType {
void CheckClass::checkCopyCtorAndEqOperator() void CheckClass::checkCopyCtorAndEqOperator()
{ {
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
for (const Scope * scope : symbolDatabase->classAndStructScopes) { for (const Scope * scope : symbolDatabase->classAndStructScopes) {
@ -2535,7 +2535,7 @@ void CheckClass::checkUnsafeClassDivZero(bool test)
// style severity: it is a style decision if classes should be safe or // style severity: it is a style decision if classes should be safe or
// if users should be required to be careful. I expect that many users // if users should be required to be careful. I expect that many users
// will disagree about these reports. // will disagree about these reports.
if (!_settings->isEnabled(Settings::STYLE)) if (!mSettings->isEnabled(Settings::STYLE))
return; return;
for (const Scope * classScope : symbolDatabase->classAndStructScopes) { for (const Scope * classScope : symbolDatabase->classAndStructScopes) {
@ -2576,9 +2576,9 @@ void CheckClass::unsafeClassDivZeroError(const Token *tok, const std::string &cl
void CheckClass::checkOverride() void CheckClass::checkOverride()
{ {
if (!_settings->isEnabled(Settings::STYLE)) if (!mSettings->isEnabled(Settings::STYLE))
return; return;
if (_settings->standards.cpp < Standards::CPP11) if (mSettings->standards.cpp < Standards::CPP11)
return; return;
for (const Scope * classScope : symbolDatabase->classAndStructScopes) { for (const Scope * classScope : symbolDatabase->classAndStructScopes) {
if (!classScope->definedType || classScope->definedType->derivedFrom.empty()) if (!classScope->definedType || classScope->definedType->derivedFrom.empty())

View File

@ -53,7 +53,7 @@ namespace {
bool CheckCondition::isAliased(const std::set<unsigned int> &vars) const bool CheckCondition::isAliased(const std::set<unsigned int> &vars) const
{ {
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (Token::Match(tok, "= & %var% ;") && vars.find(tok->tokAt(2)->varId()) != vars.end()) if (Token::Match(tok, "= & %var% ;") && vars.find(tok->tokAt(2)->varId()) != vars.end())
return true; return true;
} }
@ -62,10 +62,10 @@ bool CheckCondition::isAliased(const std::set<unsigned int> &vars) const
void CheckCondition::assignIf() void CheckCondition::assignIf()
{ {
if (!_settings->isEnabled(Settings::STYLE)) if (!mSettings->isEnabled(Settings::STYLE))
return; return;
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (tok->str() != "=") if (tok->str() != "=")
continue; continue;
@ -168,7 +168,7 @@ bool CheckCondition::assignIfParseScope(const Token * const assignTok,
// is variable changed in loop? // is variable changed in loop?
const Token *bodyStart = tok2->linkAt(1)->next(); const Token *bodyStart = tok2->linkAt(1)->next();
const Token *bodyEnd = bodyStart ? bodyStart->link() : nullptr; const Token *bodyEnd = bodyStart ? bodyStart->link() : nullptr;
if (!bodyEnd || bodyEnd->str() != "}" || isVariableChanged(bodyStart, bodyEnd, varid, !islocal, _settings, _tokenizer->isCPP())) if (!bodyEnd || bodyEnd->str() != "}" || isVariableChanged(bodyStart, bodyEnd, varid, !islocal, mSettings, mTokenizer->isCPP()))
continue; continue;
} }
@ -261,10 +261,10 @@ static bool inBooleanFunction(const Token *tok)
void CheckCondition::checkBadBitmaskCheck() void CheckCondition::checkBadBitmaskCheck()
{ {
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (tok->str() == "|" && tok->astOperand1() && tok->astOperand2() && tok->astParent()) { if (tok->str() == "|" && tok->astOperand1() && tok->astOperand2() && tok->astParent()) {
const Token* parent = tok->astParent(); const Token* parent = tok->astParent();
const bool isBoolean = Token::Match(parent, "&&|%oror%") || const bool isBoolean = Token::Match(parent, "&&|%oror%") ||
@ -289,10 +289,10 @@ void CheckCondition::badBitmaskCheckError(const Token *tok)
void CheckCondition::comparison() void CheckCondition::comparison()
{ {
if (!_settings->isEnabled(Settings::STYLE)) if (!mSettings->isEnabled(Settings::STYLE))
return; return;
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (!tok->isComparisonOp()) if (!tok->isComparisonOp())
continue; continue;
@ -369,7 +369,7 @@ bool CheckCondition::isOverlappingCond(const Token * const cond1, const Token *
return false; return false;
// same expressions // same expressions
if (isSameExpression(_tokenizer->isCPP(), true, cond1, cond2, _settings->library, pure)) if (isSameExpression(mTokenizer->isCPP(), true, cond1, cond2, mSettings->library, pure))
return true; return true;
// bitwise overlap for example 'x&7' and 'x==1' // bitwise overlap for example 'x&7' and 'x==1'
@ -392,7 +392,7 @@ bool CheckCondition::isOverlappingCond(const Token * const cond1, const Token *
if (!num2->isNumber() || MathLib::isNegative(num2->str())) if (!num2->isNumber() || MathLib::isNegative(num2->str()))
return false; return false;
if (!isSameExpression(_tokenizer->isCPP(), true, expr1, expr2, _settings->library, pure)) if (!isSameExpression(mTokenizer->isCPP(), true, expr1, expr2, mSettings->library, pure))
return false; return false;
const MathLib::bigint value1 = MathLib::toLongNumber(num1->str()); const MathLib::bigint value1 = MathLib::toLongNumber(num1->str());
@ -407,10 +407,10 @@ bool CheckCondition::isOverlappingCond(const Token * const cond1, const Token *
void CheckCondition::multiCondition() void CheckCondition::multiCondition()
{ {
if (!_settings->isEnabled(Settings::STYLE)) if (!mSettings->isEnabled(Settings::STYLE))
return; return;
const SymbolDatabase* const symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
for (std::list<Scope>::const_iterator i = symbolDatabase->scopeList.begin(); i != symbolDatabase->scopeList.end(); ++i) { for (std::list<Scope>::const_iterator i = symbolDatabase->scopeList.begin(); i != symbolDatabase->scopeList.end(); ++i) {
if (i->type != Scope::eIf) if (i->type != Scope::eIf)
@ -467,10 +467,10 @@ static bool isNonConstFunctionCall(const Token *ftok, const Library &library)
void CheckCondition::multiCondition2() void CheckCondition::multiCondition2()
{ {
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (std::list<Scope>::const_iterator scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) { for (std::list<Scope>::const_iterator scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) {
const Token *condTok = nullptr; const Token *condTok = nullptr;
@ -504,7 +504,7 @@ void CheckCondition::multiCondition2()
continue; continue;
if (Token::Match(cond, "%name% (")) { if (Token::Match(cond, "%name% (")) {
nonConstFunctionCall = isNonConstFunctionCall(cond, _settings->library); nonConstFunctionCall = isNonConstFunctionCall(cond, mSettings->library);
if (nonConstFunctionCall) if (nonConstFunctionCall)
break; break;
} }
@ -521,7 +521,7 @@ void CheckCondition::multiCondition2()
} }
} else if (!nonlocal && cond->isName()) { } else if (!nonlocal && cond->isName()) {
// varid is 0. this is possibly a nonlocal variable.. // varid is 0. this is possibly a nonlocal variable..
nonlocal = Token::Match(cond->astParent(), "%cop%|(|[") || Token::Match(cond, "%name% .") || (_tokenizer->isCPP() && cond->str() == "this"); nonlocal = Token::Match(cond->astParent(), "%cop%|(|[") || Token::Match(cond, "%name% .") || (mTokenizer->isCPP() && cond->str() == "this");
} else { } else {
tokens.push(cond->astOperand1()); tokens.push(cond->astOperand1());
tokens.push(cond->astOperand2()); tokens.push(cond->astOperand2());
@ -577,10 +577,10 @@ void CheckCondition::multiCondition2()
if (firstCondition->str() == "&&") { if (firstCondition->str() == "&&") {
tokens1.push(firstCondition->astOperand1()); tokens1.push(firstCondition->astOperand1());
tokens1.push(firstCondition->astOperand2()); tokens1.push(firstCondition->astOperand2());
} else if (isOppositeCond(false, _tokenizer->isCPP(), firstCondition, cond2, _settings->library, true)) { } else if (isOppositeCond(false, mTokenizer->isCPP(), firstCondition, cond2, mSettings->library, true)) {
if (!isAliased(vars)) if (!isAliased(vars))
oppositeInnerConditionError(firstCondition, cond2); oppositeInnerConditionError(firstCondition, cond2);
} else if (isSameExpression(_tokenizer->isCPP(), true, firstCondition, cond2, _settings->library, true)) { } else if (isSameExpression(mTokenizer->isCPP(), true, firstCondition, cond2, mSettings->library, true)) {
identicalInnerConditionError(firstCondition, cond2); identicalInnerConditionError(firstCondition, cond2);
} }
} }
@ -595,14 +595,14 @@ void CheckCondition::multiCondition2()
if (secondCondition->str() == "||" || secondCondition->str() == "&&") { if (secondCondition->str() == "||" || secondCondition->str() == "&&") {
tokens2.push(secondCondition->astOperand1()); tokens2.push(secondCondition->astOperand1());
tokens2.push(secondCondition->astOperand2()); tokens2.push(secondCondition->astOperand2());
} else if (isSameExpression(_tokenizer->isCPP(), true, cond1, secondCondition, _settings->library, true)) { } else if (isSameExpression(mTokenizer->isCPP(), true, cond1, secondCondition, mSettings->library, true)) {
if (!isAliased(vars)) if (!isAliased(vars))
identicalConditionAfterEarlyExitError(cond1, secondCondition); identicalConditionAfterEarlyExitError(cond1, secondCondition);
} }
} }
} }
} }
if (Token::Match(tok, "%type% (") && nonlocal && isNonConstFunctionCall(tok, _settings->library)) // non const function call -> bailout if there are nonlocal variables if (Token::Match(tok, "%type% (") && nonlocal && isNonConstFunctionCall(tok, mSettings->library)) // non const function call -> bailout if there are nonlocal variables
break; break;
if (Token::Match(tok, "case|break|continue|return|throw") && tok->scope() == endToken->scope()) if (Token::Match(tok, "case|break|continue|return|throw") && tok->scope() == endToken->scope())
break; break;
@ -629,7 +629,7 @@ void CheckCondition::multiCondition2()
} }
bool changed = false; bool changed = false;
for (std::set<unsigned int>::const_iterator it = vars.begin(); it != vars.end(); ++it) { for (std::set<unsigned int>::const_iterator it = vars.begin(); it != vars.end(); ++it) {
if (isVariableChanged(tok1, tok2, *it, nonlocal, _settings, _tokenizer->isCPP())) { if (isVariableChanged(tok1, tok2, *it, nonlocal, mSettings, mTokenizer->isCPP())) {
changed = true; changed = true;
break; break;
} }
@ -648,9 +648,9 @@ void CheckCondition::multiCondition2()
if (Token::Match(parent->astParent(), "%assign%|++|--")) if (Token::Match(parent->astParent(), "%assign%|++|--"))
break; break;
} }
if (_tokenizer->isCPP() && Token::Match(tok, "%name% <<") && (!tok->valueType() || !tok->valueType()->isIntegral())) if (mTokenizer->isCPP() && Token::Match(tok, "%name% <<") && (!tok->valueType() || !tok->valueType()->isIntegral()))
break; break;
if (isLikelyStreamRead(_tokenizer->isCPP(), tok->next()) || isLikelyStreamRead(_tokenizer->isCPP(), tok->previous())) if (isLikelyStreamRead(mTokenizer->isCPP(), tok->next()) || isLikelyStreamRead(mTokenizer->isCPP(), tok->previous()))
break; break;
if (Token::Match(tok, "%name% [")) { if (Token::Match(tok, "%name% [")) {
const Token *tok2 = tok->linkAt(1); const Token *tok2 = tok->linkAt(1);
@ -864,13 +864,13 @@ static std::string conditionString(bool not1, const Token *expr1, const std::str
void CheckCondition::checkIncorrectLogicOperator() void CheckCondition::checkIncorrectLogicOperator()
{ {
const bool printStyle = _settings->isEnabled(Settings::STYLE); const bool printStyle = mSettings->isEnabled(Settings::STYLE);
const bool printWarning = _settings->isEnabled(Settings::WARNING); const bool printWarning = mSettings->isEnabled(Settings::WARNING);
if (!printWarning && !printStyle) if (!printWarning && !printStyle)
return; return;
const bool printInconclusive = _settings->inconclusive; const bool printInconclusive = mSettings->inconclusive;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
const std::size_t functions = symbolDatabase->functionScopes.size(); const std::size_t functions = symbolDatabase->functionScopes.size();
for (std::size_t ii = 0; ii < functions; ++ii) { for (std::size_t ii = 0; ii < functions; ++ii) {
const Scope * scope = symbolDatabase->functionScopes[ii]; const Scope * scope = symbolDatabase->functionScopes[ii];
@ -881,7 +881,7 @@ void CheckCondition::checkIncorrectLogicOperator()
// Opposite comparisons around || or && => always true or always false // Opposite comparisons around || or && => always true or always false
if ((tok->astOperand1()->isName() || tok->astOperand2()->isName()) && if ((tok->astOperand1()->isName() || tok->astOperand2()->isName()) &&
isOppositeCond(true, _tokenizer->isCPP(), tok->astOperand1(), tok->astOperand2(), _settings->library, true)) { isOppositeCond(true, mTokenizer->isCPP(), tok->astOperand1(), tok->astOperand2(), mSettings->library, true)) {
const bool alwaysTrue(tok->str() == "||"); const bool alwaysTrue(tok->str() == "||");
incorrectLogicOperatorError(tok, tok->expressionString(), alwaysTrue, false); incorrectLogicOperatorError(tok, tok->expressionString(), alwaysTrue, false);
@ -895,7 +895,7 @@ void CheckCondition::checkIncorrectLogicOperator()
((tok->str() == "||" && tok->astOperand2()->str() == "&&") || ((tok->str() == "||" && tok->astOperand2()->str() == "&&") ||
(tok->str() == "&&" && tok->astOperand2()->str() == "||"))) { (tok->str() == "&&" && tok->astOperand2()->str() == "||"))) {
const Token* tok2 = tok->astOperand2()->astOperand1(); const Token* tok2 = tok->astOperand2()->astOperand1();
if (isOppositeCond(true, _tokenizer->isCPP(), tok->astOperand1(), tok2, _settings->library, true)) { if (isOppositeCond(true, mTokenizer->isCPP(), tok->astOperand1(), tok2, mSettings->library, true)) {
std::string expr1(tok->astOperand1()->expressionString()); std::string expr1(tok->astOperand1()->expressionString());
std::string expr2(tok->astOperand2()->astOperand1()->expressionString()); std::string expr2(tok->astOperand2()->astOperand1()->expressionString());
std::string expr3(tok->astOperand2()->astOperand2()->expressionString()); std::string expr3(tok->astOperand2()->astOperand2()->expressionString());
@ -956,9 +956,9 @@ void CheckCondition::checkIncorrectLogicOperator()
if (inconclusive && !printInconclusive) if (inconclusive && !printInconclusive)
continue; continue;
if (isSameExpression(_tokenizer->isCPP(), true, comp1, comp2, _settings->library, true)) if (isSameExpression(mTokenizer->isCPP(), true, comp1, comp2, mSettings->library, true))
continue; // same expressions => only report that there are same expressions continue; // same expressions => only report that there are same expressions
if (!isSameExpression(_tokenizer->isCPP(), true, expr1, expr2, _settings->library, true)) if (!isSameExpression(mTokenizer->isCPP(), true, expr1, expr2, mSettings->library, true))
continue; continue;
const bool isfloat = astIsFloat(expr1, true) || MathLib::isFloat(value1) || astIsFloat(expr2, true) || MathLib::isFloat(value2); const bool isfloat = astIsFloat(expr1, true) || MathLib::isFloat(value1) || astIsFloat(expr2, true) || MathLib::isFloat(value2);
@ -1059,10 +1059,10 @@ void CheckCondition::redundantConditionError(const Token *tok, const std::string
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
void CheckCondition::checkModuloAlwaysTrueFalse() void CheckCondition::checkModuloAlwaysTrueFalse()
{ {
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
const std::size_t functions = symbolDatabase->functionScopes.size(); const std::size_t functions = symbolDatabase->functionScopes.size();
for (std::size_t i = 0; i < functions; ++i) { for (std::size_t i = 0; i < functions; ++i) {
const Scope * scope = symbolDatabase->functionScopes[i]; const Scope * scope = symbolDatabase->functionScopes[i];
@ -1113,12 +1113,12 @@ static int countPar(const Token *tok1, const Token *tok2)
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
void CheckCondition::clarifyCondition() void CheckCondition::clarifyCondition()
{ {
if (!_settings->isEnabled(Settings::STYLE)) if (!mSettings->isEnabled(Settings::STYLE))
return; return;
const bool isC = _tokenizer->isC(); const bool isC = mTokenizer->isC();
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
const std::size_t functions = symbolDatabase->functionScopes.size(); const std::size_t functions = symbolDatabase->functionScopes.size();
for (std::size_t i = 0; i < functions; ++i) { for (std::size_t i = 0; i < functions; ++i) {
const Scope * scope = symbolDatabase->functionScopes[i]; const Scope * scope = symbolDatabase->functionScopes[i];
@ -1180,10 +1180,10 @@ void CheckCondition::clarifyConditionError(const Token *tok, bool assign, bool b
void CheckCondition::alwaysTrueFalse() void CheckCondition::alwaysTrueFalse()
{ {
if (!_settings->isEnabled(Settings::STYLE)) if (!mSettings->isEnabled(Settings::STYLE))
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
const std::size_t functions = symbolDatabase->functionScopes.size(); const std::size_t functions = symbolDatabase->functionScopes.size();
for (std::size_t i = 0; i < functions; ++i) { for (std::size_t i = 0; i < functions; ++i) {
@ -1291,10 +1291,10 @@ void CheckCondition::alwaysTrueFalseError(const Token *tok, const ValueFlow::Val
void CheckCondition::checkInvalidTestForOverflow() void CheckCondition::checkInvalidTestForOverflow()
{ {
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
const std::size_t functions = symbolDatabase->functionScopes.size(); const std::size_t functions = symbolDatabase->functionScopes.size();
for (std::size_t i = 0; i < functions; ++i) { for (std::size_t i = 0; i < functions; ++i) {
const Scope * scope = symbolDatabase->functionScopes[i]; const Scope * scope = symbolDatabase->functionScopes[i];
@ -1323,9 +1323,9 @@ void CheckCondition::checkInvalidTestForOverflow()
continue; continue;
const Token *termToken; const Token *termToken;
if (isSameExpression(_tokenizer->isCPP(), true, exprToken, calcToken->astOperand1(), _settings->library, true)) if (isSameExpression(mTokenizer->isCPP(), true, exprToken, calcToken->astOperand1(), mSettings->library, true))
termToken = calcToken->astOperand2(); termToken = calcToken->astOperand2();
else if (isSameExpression(_tokenizer->isCPP(), true, exprToken, calcToken->astOperand2(), _settings->library, true)) else if (isSameExpression(mTokenizer->isCPP(), true, exprToken, calcToken->astOperand2(), mSettings->library, true))
termToken = calcToken->astOperand1(); termToken = calcToken->astOperand1();
else else
continue; continue;
@ -1355,10 +1355,10 @@ void CheckCondition::invalidTestForOverflow(const Token* tok, bool result)
void CheckCondition::checkPointerAdditionResultNotNull() void CheckCondition::checkPointerAdditionResultNotNull()
{ {
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
const std::size_t functions = symbolDatabase->functionScopes.size(); const std::size_t functions = symbolDatabase->functionScopes.size();
for (std::size_t i = 0; i < functions; ++i) { for (std::size_t i = 0; i < functions; ++i) {
const Scope * scope = symbolDatabase->functionScopes[i]; const Scope * scope = symbolDatabase->functionScopes[i];

View File

@ -38,10 +38,10 @@ namespace {
void CheckExceptionSafety::destructors() void CheckExceptionSafety::destructors()
{ {
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
const SymbolDatabase* const symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
// Perform check.. // Perform check..
const std::size_t functions = symbolDatabase->functionScopes.size(); const std::size_t functions = symbolDatabase->functionScopes.size();
@ -80,11 +80,11 @@ void CheckExceptionSafety::destructors()
void CheckExceptionSafety::deallocThrow() void CheckExceptionSafety::deallocThrow()
{ {
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
const bool printInconclusive = _settings->inconclusive; const bool printInconclusive = mSettings->inconclusive;
const SymbolDatabase* const symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
// Deallocate a global/member pointer and then throw exception // Deallocate a global/member pointer and then throw exception
// the pointer will be a dead pointer // the pointer will be a dead pointer
@ -149,10 +149,10 @@ void CheckExceptionSafety::deallocThrow()
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
void CheckExceptionSafety::checkRethrowCopy() void CheckExceptionSafety::checkRethrowCopy()
{ {
if (!_settings->isEnabled(Settings::STYLE)) if (!mSettings->isEnabled(Settings::STYLE))
return; return;
const SymbolDatabase* const symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
for (std::list<Scope>::const_iterator i = symbolDatabase->scopeList.begin(); i != symbolDatabase->scopeList.end(); ++i) { for (std::list<Scope>::const_iterator i = symbolDatabase->scopeList.begin(); i != symbolDatabase->scopeList.end(); ++i) {
if (i->type != Scope::eCatch) if (i->type != Scope::eCatch)
@ -177,10 +177,10 @@ void CheckExceptionSafety::checkRethrowCopy()
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
void CheckExceptionSafety::checkCatchExceptionByValue() void CheckExceptionSafety::checkCatchExceptionByValue()
{ {
if (!_settings->isEnabled(Settings::STYLE)) if (!mSettings->isEnabled(Settings::STYLE))
return; return;
const SymbolDatabase* const symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
for (std::list<Scope>::const_iterator i = symbolDatabase->scopeList.begin(); i != symbolDatabase->scopeList.end(); ++i) { for (std::list<Scope>::const_iterator i = symbolDatabase->scopeList.begin(); i != symbolDatabase->scopeList.end(); ++i) {
if (i->type != Scope::eCatch) if (i->type != Scope::eCatch)
@ -243,7 +243,7 @@ static const Token * functionThrows(const Function * function)
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
void CheckExceptionSafety::nothrowThrows() void CheckExceptionSafety::nothrowThrows()
{ {
const SymbolDatabase* const symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
const std::size_t functions = symbolDatabase->functionScopes.size(); const std::size_t functions = symbolDatabase->functionScopes.size();
for (std::size_t i = 0; i < functions; ++i) { for (std::size_t i = 0; i < functions; ++i) {
@ -281,10 +281,10 @@ void CheckExceptionSafety::nothrowThrows()
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
void CheckExceptionSafety::unhandledExceptionSpecification() void CheckExceptionSafety::unhandledExceptionSpecification()
{ {
if (!_settings->isEnabled(Settings::STYLE) || !_settings->inconclusive) if (!mSettings->isEnabled(Settings::STYLE) || !mSettings->inconclusive)
return; return;
const SymbolDatabase* const symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
const std::size_t functions = symbolDatabase->functionScopes.size(); const std::size_t functions = symbolDatabase->functionScopes.size();
for (std::size_t i = 0; i < functions; ++i) { for (std::size_t i = 0; i < functions; ++i) {

View File

@ -53,17 +53,17 @@ static const CWE CWE688(688U); // Function Call With Incorrect Variable or Refe
void CheckFunctions::checkProhibitedFunctions() void CheckFunctions::checkProhibitedFunctions()
{ {
const bool checkAlloca = _settings->isEnabled(Settings::WARNING) && ((_settings->standards.c >= Standards::C99 && _tokenizer->isC()) || _settings->standards.cpp >= Standards::CPP11); const bool checkAlloca = mSettings->isEnabled(Settings::WARNING) && ((mSettings->standards.c >= Standards::C99 && mTokenizer->isC()) || mSettings->standards.cpp >= Standards::CPP11);
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope *scope : symbolDatabase->functionScopes) { for (const Scope *scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) { for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
if (!Token::Match(tok, "%name% (") && tok->varId() == 0) if (!Token::Match(tok, "%name% (") && tok->varId() == 0)
continue; continue;
// alloca() is special as it depends on the code being C or C++, so it is not in Library // alloca() is special as it depends on the code being C or C++, so it is not in Library
if (checkAlloca && Token::simpleMatch(tok, "alloca (") && (!tok->function() || tok->function()->nestedIn->type == Scope::eGlobal)) { if (checkAlloca && Token::simpleMatch(tok, "alloca (") && (!tok->function() || tok->function()->nestedIn->type == Scope::eGlobal)) {
if (_tokenizer->isC()) { if (mTokenizer->isC()) {
if (_settings->standards.c > Standards::C89) if (mSettings->standards.c > Standards::C89)
reportError(tok, Severity::warning, "allocaCalled", reportError(tok, Severity::warning, "allocaCalled",
"$symbol:alloca\n" "$symbol:alloca\n"
"Obsolete function 'alloca' called. In C99 and later it is recommended to use a variable length array instead.\n" "Obsolete function 'alloca' called. In C99 and later it is recommended to use a variable length array instead.\n"
@ -81,9 +81,9 @@ void CheckFunctions::checkProhibitedFunctions()
if (tok->function() && tok->function()->hasBody()) if (tok->function() && tok->function()->hasBody())
continue; continue;
const Library::WarnInfo* wi = _settings->library.getWarnInfo(tok); const Library::WarnInfo* wi = mSettings->library.getWarnInfo(tok);
if (wi) { if (wi) {
if (_settings->isEnabled(wi->severity) && _settings->standards.c >= wi->standards.c && _settings->standards.cpp >= wi->standards.cpp) { if (mSettings->isEnabled(wi->severity) && mSettings->standards.c >= wi->standards.c && mSettings->standards.cpp >= wi->standards.cpp) {
reportError(tok, wi->severity, tok->str() + "Called", wi->message, CWE477, false); reportError(tok, wi->severity, tok->str() + "Called", wi->message, CWE477, false);
} }
} }
@ -97,7 +97,7 @@ void CheckFunctions::checkProhibitedFunctions()
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
void CheckFunctions::invalidFunctionUsage() void CheckFunctions::invalidFunctionUsage()
{ {
const SymbolDatabase* symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope *scope : symbolDatabase->functionScopes) { for (const Scope *scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (!Token::Match(tok, "%name% ( !!)")) if (!Token::Match(tok, "%name% ( !!)"))
@ -108,21 +108,21 @@ void CheckFunctions::invalidFunctionUsage()
const Token * const argtok = arguments[argnr-1]; const Token * const argtok = arguments[argnr-1];
// check <valid>...</valid> // check <valid>...</valid>
const ValueFlow::Value *invalidValue = argtok->getInvalidValue(functionToken,argnr,_settings); const ValueFlow::Value *invalidValue = argtok->getInvalidValue(functionToken,argnr,mSettings);
if (invalidValue) { if (invalidValue) {
invalidFunctionArgError(argtok, functionToken->next()->astOperand1()->expressionString(), argnr, invalidValue, _settings->library.validarg(functionToken, argnr)); invalidFunctionArgError(argtok, functionToken->next()->astOperand1()->expressionString(), argnr, invalidValue, mSettings->library.validarg(functionToken, argnr));
} }
if (astIsBool(argtok)) { if (astIsBool(argtok)) {
// check <not-bool> // check <not-bool>
if (_settings->library.isboolargbad(functionToken, argnr)) if (mSettings->library.isboolargbad(functionToken, argnr))
invalidFunctionArgBoolError(argtok, functionToken->str(), argnr); invalidFunctionArgBoolError(argtok, functionToken->str(), argnr);
// Are the values 0 and 1 valid? // Are the values 0 and 1 valid?
else if (!_settings->library.isargvalid(functionToken, argnr, 0)) else if (!mSettings->library.isargvalid(functionToken, argnr, 0))
invalidFunctionArgError(argtok, functionToken->str(), argnr, nullptr, _settings->library.validarg(functionToken, argnr)); invalidFunctionArgError(argtok, functionToken->str(), argnr, nullptr, mSettings->library.validarg(functionToken, argnr));
else if (!_settings->library.isargvalid(functionToken, argnr, 1)) else if (!mSettings->library.isargvalid(functionToken, argnr, 1))
invalidFunctionArgError(argtok, functionToken->str(), argnr, nullptr, _settings->library.validarg(functionToken, argnr)); invalidFunctionArgError(argtok, functionToken->str(), argnr, nullptr, mSettings->library.validarg(functionToken, argnr));
} }
} }
} }
@ -171,10 +171,10 @@ void CheckFunctions::invalidFunctionArgBoolError(const Token *tok, const std::st
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
void CheckFunctions::checkIgnoredReturnValue() void CheckFunctions::checkIgnoredReturnValue()
{ {
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope *scope : symbolDatabase->functionScopes) { for (const Scope *scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
// skip c++11 initialization, ({...}) // skip c++11 initialization, ({...})
@ -195,7 +195,7 @@ void CheckFunctions::checkIgnoredReturnValue()
} }
if ((!tok->function() || !Token::Match(tok->function()->retDef, "void %name%")) && if ((!tok->function() || !Token::Match(tok->function()->retDef, "void %name%")) &&
(_settings->library.isUseRetVal(tok) || (tok->function() && tok->function()->isAttributeNodiscard())) && (mSettings->library.isUseRetVal(tok) || (tok->function() && tok->function()->isAttributeNodiscard())) &&
!WRONG_DATA(!tok->next()->astOperand1(), tok)) { !WRONG_DATA(!tok->next()->astOperand1(), tok)) {
ignoredReturnValueError(tok, tok->next()->astOperand1()->expressionString()); ignoredReturnValueError(tok, tok->next()->astOperand1()->expressionString());
} }
@ -215,10 +215,10 @@ void CheckFunctions::ignoredReturnValueError(const Token* tok, const std::string
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
void CheckFunctions::checkMathFunctions() void CheckFunctions::checkMathFunctions()
{ {
const bool styleC99 = _settings->isEnabled(Settings::STYLE) && _settings->standards.c != Standards::C89 && _settings->standards.cpp != Standards::CPP03; const bool styleC99 = mSettings->isEnabled(Settings::STYLE) && mSettings->standards.c != Standards::C89 && mSettings->standards.cpp != Standards::CPP03;
const bool printWarnings = _settings->isEnabled(Settings::WARNING); const bool printWarnings = mSettings->isEnabled(Settings::WARNING);
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope *scope : symbolDatabase->functionScopes) { for (const Scope *scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (tok->varId()) if (tok->varId())
@ -312,10 +312,10 @@ void CheckFunctions::memsetZeroBytes()
// <warn knownIntValue="0" severity="warning" msg="..."/> // <warn knownIntValue="0" severity="warning" msg="..."/>
// </arg> // </arg>
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope *scope : symbolDatabase->functionScopes) { for (const Scope *scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (Token::Match(tok, "memset|wmemset (") && (numberOfArguments(tok)==3)) { if (Token::Match(tok, "memset|wmemset (") && (numberOfArguments(tok)==3)) {
@ -349,12 +349,12 @@ void CheckFunctions::memsetInvalid2ndParam()
// <warn possibleIntValue=":-129,256:" severity="warning" msg="..."/> // <warn possibleIntValue=":-129,256:" severity="warning" msg="..."/>
// </arg> // </arg>
const bool printPortability = _settings->isEnabled(Settings::PORTABILITY); const bool printPortability = mSettings->isEnabled(Settings::PORTABILITY);
const bool printWarning = _settings->isEnabled(Settings::WARNING); const bool printWarning = mSettings->isEnabled(Settings::WARNING);
if (!printWarning && !printPortability) if (!printWarning && !printPortability)
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope *scope : symbolDatabase->functionScopes) { for (const Scope *scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok && (tok != scope->bodyEnd); tok = tok->next()) { for (const Token* tok = scope->bodyStart->next(); tok && (tok != scope->bodyEnd); tok = tok->next()) {
if (!Token::simpleMatch(tok, "memset (")) if (!Token::simpleMatch(tok, "memset ("))
@ -376,8 +376,8 @@ void CheckFunctions::memsetInvalid2ndParam()
if (printWarning && secondParamTok->isNumber()) { // Check if the second parameter is a literal and is out of range if (printWarning && secondParamTok->isNumber()) { // Check if the second parameter is a literal and is out of range
const long long int value = MathLib::toLongNumber(secondParamTok->str()); const long long int value = MathLib::toLongNumber(secondParamTok->str());
const long long sCharMin = _settings->signedCharMin(); const long long sCharMin = mSettings->signedCharMin();
const long long uCharMax = _settings->unsignedCharMax(); const long long uCharMax = mSettings->unsignedCharMax();
if (value < sCharMin || value > uCharMax) if (value < sCharMin || value > uCharMax)
memsetValueOutOfRangeError(secondParamTok, secondParamTok->str()); memsetValueOutOfRangeError(secondParamTok, secondParamTok->str());
} }
@ -407,11 +407,11 @@ void CheckFunctions::memsetValueOutOfRangeError(const Token *tok, const std::str
void CheckFunctions::checkLibraryMatchFunctions() void CheckFunctions::checkLibraryMatchFunctions()
{ {
if (!_settings->checkLibrary || !_settings->isEnabled(Settings::INFORMATION)) if (!mSettings->checkLibrary || !mSettings->isEnabled(Settings::INFORMATION))
return; return;
bool New = false; bool New = false;
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (!tok->scope() || !tok->scope()->isExecutable()) if (!tok->scope() || !tok->scope()->isExecutable())
continue; continue;
@ -431,11 +431,11 @@ void CheckFunctions::checkLibraryMatchFunctions()
if (tok->linkAt(1)->strAt(1) == "(") if (tok->linkAt(1)->strAt(1) == "(")
continue; continue;
if (!_settings->library.isNotLibraryFunction(tok)) if (!mSettings->library.isNotLibraryFunction(tok))
continue; continue;
const std::string &functionName = _settings->library.getFunctionName(tok); const std::string &functionName = mSettings->library.getFunctionName(tok);
if (functionName.empty() || _settings->library.functions.find(functionName) != _settings->library.functions.end()) if (functionName.empty() || mSettings->library.functions.find(functionName) != mSettings->library.functions.end())
continue; continue;
reportError(tok, reportError(tok,

View File

@ -35,7 +35,7 @@ namespace {
void CheckInternal::checkTokenMatchPatterns() void CheckInternal::checkTokenMatchPatterns()
{ {
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (std::size_t i = 0; i < symbolDatabase->functionScopes.size(); ++i) { for (std::size_t i = 0; i < symbolDatabase->functionScopes.size(); ++i) {
const Scope * scope = symbolDatabase->functionScopes[i]; const Scope * scope = symbolDatabase->functionScopes[i];
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
@ -87,7 +87,7 @@ void CheckInternal::checkTokenMatchPatterns()
void CheckInternal::checkRedundantTokCheck() void CheckInternal::checkRedundantTokCheck()
{ {
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (Token::Match(tok, "&& Token :: simpleMatch|Match|findsimplematch|findmatch (")) { if (Token::Match(tok, "&& Token :: simpleMatch|Match|findsimplematch|findmatch (")) {
// in code like // in code like
// if (tok->previous() && Token::match(tok->previous(), "bla")) {} // if (tok->previous() && Token::match(tok->previous(), "bla")) {}
@ -123,7 +123,7 @@ void CheckInternal::checkRedundantTokCheckError(const Token* tok)
void CheckInternal::checkTokenSimpleMatchPatterns() void CheckInternal::checkTokenSimpleMatchPatterns()
{ {
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (std::size_t i = 0; i < symbolDatabase->functionScopes.size(); ++i) { for (std::size_t i = 0; i < symbolDatabase->functionScopes.size(); ++i) {
const Scope * scope = symbolDatabase->functionScopes[i]; const Scope * scope = symbolDatabase->functionScopes[i];
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
@ -212,7 +212,7 @@ namespace {
void CheckInternal::checkMissingPercentCharacter() void CheckInternal::checkMissingPercentCharacter()
{ {
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (std::size_t i = 0; i < symbolDatabase->functionScopes.size(); ++i) { for (std::size_t i = 0; i < symbolDatabase->functionScopes.size(); ++i) {
const Scope * scope = symbolDatabase->functionScopes[i]; const Scope * scope = symbolDatabase->functionScopes[i];
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
@ -255,7 +255,7 @@ void CheckInternal::checkMissingPercentCharacter()
void CheckInternal::checkUnknownPattern() void CheckInternal::checkUnknownPattern()
{ {
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (std::size_t i = 0; i < symbolDatabase->functionScopes.size(); ++i) { for (std::size_t i = 0; i < symbolDatabase->functionScopes.size(); ++i) {
const Scope * scope = symbolDatabase->functionScopes[i]; const Scope * scope = symbolDatabase->functionScopes[i];
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
@ -290,7 +290,7 @@ void CheckInternal::checkUnknownPattern()
void CheckInternal::checkRedundantNextPrevious() void CheckInternal::checkRedundantNextPrevious()
{ {
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (std::size_t i = 0; i < symbolDatabase->functionScopes.size(); ++i) { for (std::size_t i = 0; i < symbolDatabase->functionScopes.size(); ++i) {
const Scope * scope = symbolDatabase->functionScopes[i]; const Scope * scope = symbolDatabase->functionScopes[i];
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
@ -322,7 +322,7 @@ void CheckInternal::checkRedundantNextPrevious()
void CheckInternal::checkExtraWhitespace() void CheckInternal::checkExtraWhitespace()
{ {
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (std::size_t i = 0; i < symbolDatabase->functionScopes.size(); ++i) { for (std::size_t i = 0; i < symbolDatabase->functionScopes.size(); ++i) {
const Scope * scope = symbolDatabase->functionScopes[i]; const Scope * scope = symbolDatabase->functionScopes[i];
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
@ -349,7 +349,7 @@ void CheckInternal::checkExtraWhitespace()
void CheckInternal::checkStlUsage() void CheckInternal::checkStlUsage()
{ {
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope *scope : symbolDatabase->functionScopes) { for (const Scope *scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (Token::simpleMatch(tok, ". emplace (")) if (Token::simpleMatch(tok, ". emplace ("))

View File

@ -58,10 +58,10 @@ static const CWE CWE910(910U); // Use of Expired File Descriptor
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
void CheckIO::checkCoutCerrMisusage() void CheckIO::checkCoutCerrMisusage()
{ {
if (_tokenizer->isC()) if (mTokenizer->isC())
return; return;
const SymbolDatabase * const symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase * const symbolDatabase = mTokenizer->getSymbolDatabase();
const std::size_t functions = symbolDatabase->functionScopes.size(); const std::size_t functions = symbolDatabase->functionScopes.size();
for (std::size_t i = 0; i < functions; ++i) { for (std::size_t i = 0; i < functions; ++i) {
const Scope * scope = symbolDatabase->functionScopes[i]; const Scope * scope = symbolDatabase->functionScopes[i];
@ -119,13 +119,13 @@ namespace {
void CheckIO::checkFileUsage() void CheckIO::checkFileUsage()
{ {
const bool windows = _settings->isWindowsPlatform(); const bool windows = mSettings->isWindowsPlatform();
const bool printPortability = _settings->isEnabled(Settings::PORTABILITY); const bool printPortability = mSettings->isEnabled(Settings::PORTABILITY);
const bool printWarnings = _settings->isEnabled(Settings::WARNING); const bool printWarnings = mSettings->isEnabled(Settings::WARNING);
std::map<unsigned int, Filepointer> filepointers; std::map<unsigned int, Filepointer> filepointers;
const SymbolDatabase* symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Variable* var : symbolDatabase->variableList()) { for (const Variable* var : symbolDatabase->variableList()) {
if (!var || !var->declarationId() || var->isArray() || !Token::simpleMatch(var->typeStartToken(), "FILE *")) if (!var || !var->declarationId() || var->isArray() || !Token::simpleMatch(var->typeStartToken(), "FILE *"))
continue; continue;
@ -158,7 +158,7 @@ void CheckIO::checkFileUsage()
i->second.lastOperation = Filepointer::UNKNOWN_OP; i->second.lastOperation = Filepointer::UNKNOWN_OP;
} }
} }
} else if (tok->str() == "return" || tok->str() == "continue" || tok->str() == "break" || _settings->library.isnoreturn(tok)) { // Reset upon return, continue or break } else if (tok->str() == "return" || tok->str() == "continue" || tok->str() == "break" || mSettings->library.isnoreturn(tok)) { // Reset upon return, continue or break
for (std::map<unsigned int, Filepointer>::iterator i = filepointers.begin(); i != filepointers.end(); ++i) { for (std::map<unsigned int, Filepointer>::iterator i = filepointers.begin(); i != filepointers.end(); ++i) {
i->second.mode_indent = 0; i->second.mode_indent = 0;
i->second.mode = UNKNOWN_OM; i->second.mode = UNKNOWN_OM;
@ -234,7 +234,7 @@ void CheckIO::checkFileUsage()
if ((tok->str() == "ungetc" || tok->str() == "ungetwc") && fileTok) if ((tok->str() == "ungetc" || tok->str() == "ungetwc") && fileTok)
fileTok = fileTok->nextArgument(); fileTok = fileTok->nextArgument();
operation = Filepointer::UNIMPORTANT; operation = Filepointer::UNIMPORTANT;
} else if (!Token::Match(tok, "if|for|while|catch|switch") && !_settings->library.isFunctionConst(tok->str(), true)) { } else if (!Token::Match(tok, "if|for|while|catch|switch") && !mSettings->library.isFunctionConst(tok->str(), true)) {
const Token* const end2 = tok->linkAt(1); 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 (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())) { if (!tok->function() || (tok->function()->nestedIn && tok->function()->nestedIn->isClassOrStruct())) {
@ -378,10 +378,10 @@ void CheckIO::seekOnAppendedFileError(const Token *tok)
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
void CheckIO::invalidScanf() void CheckIO::invalidScanf()
{ {
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
const SymbolDatabase * const symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase * const symbolDatabase = mTokenizer->getSymbolDatabase();
const std::size_t functions = symbolDatabase->functionScopes.size(); const std::size_t functions = symbolDatabase->functionScopes.size();
for (std::size_t j = 0; j < functions; ++j) { for (std::size_t j = 0; j < functions; ++j) {
const Scope * scope = symbolDatabase->functionScopes[j]; const Scope * scope = symbolDatabase->functionScopes[j];
@ -494,8 +494,8 @@ static inline bool typesMatch(const std::string& iToTest, const std::string& iTy
void CheckIO::checkWrongPrintfScanfArguments() void CheckIO::checkWrongPrintfScanfArguments()
{ {
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
const bool isWindows = _settings->isWindowsPlatform(); const bool isWindows = mSettings->isWindowsPlatform();
const std::size_t functions = symbolDatabase->functionScopes.size(); const std::size_t functions = symbolDatabase->functionScopes.size();
for (std::size_t j = 0; j < functions; ++j) { for (std::size_t j = 0; j < functions; ++j) {
@ -510,10 +510,10 @@ void CheckIO::checkWrongPrintfScanfArguments()
bool scanf_s = false; bool scanf_s = false;
int formatStringArgNo = -1; int formatStringArgNo = -1;
if (tok->strAt(1) == "(" && _settings->library.formatstr_function(tok)) { if (tok->strAt(1) == "(" && mSettings->library.formatstr_function(tok)) {
formatStringArgNo = _settings->library.formatstr_argno(tok); formatStringArgNo = mSettings->library.formatstr_argno(tok);
scan = _settings->library.formatstr_scan(tok); scan = mSettings->library.formatstr_scan(tok);
scanf_s = _settings->library.formatstr_secure(tok); scanf_s = mSettings->library.formatstr_secure(tok);
} }
if (formatStringArgNo >= 0) { if (formatStringArgNo >= 0) {
@ -570,7 +570,7 @@ void CheckIO::checkFormatString(const Token * const tok,
const bool scan, const bool scan,
const bool scanf_s) const bool scanf_s)
{ {
const bool printWarning = _settings->isEnabled(Settings::WARNING); const bool printWarning = mSettings->isEnabled(Settings::WARNING);
const std::string &formatString = formatStringTok->str(); const std::string &formatString = formatStringTok->str();
// Count format string parameters.. // Count format string parameters..
@ -665,9 +665,9 @@ void CheckIO::checkFormatString(const Token * const tok,
} }
// Perform type checks // Perform type checks
ArgumentInfo argInfo(argListTok, _settings, _tokenizer->isCPP()); ArgumentInfo argInfo(argListTok, mSettings, mTokenizer->isCPP());
if (argInfo.typeToken && !argInfo.isLibraryType(_settings)) { if (argInfo.typeToken && !argInfo.isLibraryType(mSettings)) {
if (scan) { if (scan) {
std::string specifier; std::string specifier;
bool done = false; bool done = false;
@ -1688,7 +1688,7 @@ void CheckIO::wrongPrintfScanfArgumentsError(const Token* tok,
unsigned int numFunction) unsigned int numFunction)
{ {
const Severity::SeverityType severity = numFormat > numFunction ? Severity::error : Severity::warning; const Severity::SeverityType severity = numFormat > numFunction ? Severity::error : Severity::warning;
if (severity != Severity::error && !_settings->isEnabled(Settings::WARNING)) if (severity != Severity::error && !mSettings->isEnabled(Settings::WARNING))
return; return;
std::ostringstream errmsg; std::ostringstream errmsg;
@ -1707,7 +1707,7 @@ void CheckIO::wrongPrintfScanfArgumentsError(const Token* tok,
void CheckIO::wrongPrintfScanfPosixParameterPositionError(const Token* tok, const std::string& functionName, void CheckIO::wrongPrintfScanfPosixParameterPositionError(const Token* tok, const std::string& functionName,
unsigned int index, unsigned int numFunction) unsigned int index, unsigned int numFunction)
{ {
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
std::ostringstream errmsg; std::ostringstream errmsg;
errmsg << functionName << ": "; errmsg << functionName << ": ";
@ -1722,7 +1722,7 @@ void CheckIO::wrongPrintfScanfPosixParameterPositionError(const Token* tok, cons
void CheckIO::invalidScanfArgTypeError_s(const Token* tok, unsigned int numFormat, const std::string& specifier, const ArgumentInfo* argInfo) void CheckIO::invalidScanfArgTypeError_s(const Token* tok, unsigned int numFormat, const std::string& specifier, const ArgumentInfo* argInfo)
{ {
const Severity::SeverityType severity = getSeverity(argInfo); const Severity::SeverityType severity = getSeverity(argInfo);
if (!_settings->isEnabled(severity)) if (!mSettings->isEnabled(severity))
return; return;
std::ostringstream errmsg; std::ostringstream errmsg;
errmsg << "%" << specifier << " in format string (no. " << numFormat << ") requires a \'"; errmsg << "%" << specifier << " in format string (no. " << numFormat << ") requires a \'";
@ -1738,7 +1738,7 @@ void CheckIO::invalidScanfArgTypeError_s(const Token* tok, unsigned int numForma
void CheckIO::invalidScanfArgTypeError_int(const Token* tok, unsigned int numFormat, const std::string& specifier, const ArgumentInfo* argInfo, bool isUnsigned) void CheckIO::invalidScanfArgTypeError_int(const Token* tok, unsigned int numFormat, const std::string& specifier, const ArgumentInfo* argInfo, bool isUnsigned)
{ {
const Severity::SeverityType severity = getSeverity(argInfo); const Severity::SeverityType severity = getSeverity(argInfo);
if (!_settings->isEnabled(severity)) if (!mSettings->isEnabled(severity))
return; return;
std::ostringstream errmsg; std::ostringstream errmsg;
errmsg << "%" << specifier << " in format string (no. " << numFormat << ") requires \'"; errmsg << "%" << specifier << " in format string (no. " << numFormat << ") requires \'";
@ -1783,7 +1783,7 @@ void CheckIO::invalidScanfArgTypeError_int(const Token* tok, unsigned int numFor
void CheckIO::invalidScanfArgTypeError_float(const Token* tok, unsigned int numFormat, const std::string& specifier, const ArgumentInfo* argInfo) void CheckIO::invalidScanfArgTypeError_float(const Token* tok, unsigned int numFormat, const std::string& specifier, const ArgumentInfo* argInfo)
{ {
const Severity::SeverityType severity = getSeverity(argInfo); const Severity::SeverityType severity = getSeverity(argInfo);
if (!_settings->isEnabled(severity)) if (!mSettings->isEnabled(severity))
return; return;
std::ostringstream errmsg; std::ostringstream errmsg;
errmsg << "%" << specifier << " in format string (no. " << numFormat << ") requires \'"; errmsg << "%" << specifier << " in format string (no. " << numFormat << ") requires \'";
@ -1802,7 +1802,7 @@ void CheckIO::invalidScanfArgTypeError_float(const Token* tok, unsigned int numF
void CheckIO::invalidPrintfArgTypeError_s(const Token* tok, unsigned int numFormat, const ArgumentInfo* argInfo) void CheckIO::invalidPrintfArgTypeError_s(const Token* tok, unsigned int numFormat, const ArgumentInfo* argInfo)
{ {
const Severity::SeverityType severity = getSeverity(argInfo); const Severity::SeverityType severity = getSeverity(argInfo);
if (!_settings->isEnabled(severity)) if (!mSettings->isEnabled(severity))
return; return;
std::ostringstream errmsg; std::ostringstream errmsg;
errmsg << "%s in format string (no. " << numFormat << ") requires \'char *\' but the argument type is "; errmsg << "%s in format string (no. " << numFormat << ") requires \'char *\' but the argument type is ";
@ -1813,7 +1813,7 @@ void CheckIO::invalidPrintfArgTypeError_s(const Token* tok, unsigned int numForm
void CheckIO::invalidPrintfArgTypeError_n(const Token* tok, unsigned int numFormat, const ArgumentInfo* argInfo) void CheckIO::invalidPrintfArgTypeError_n(const Token* tok, unsigned int numFormat, const ArgumentInfo* argInfo)
{ {
const Severity::SeverityType severity = getSeverity(argInfo); const Severity::SeverityType severity = getSeverity(argInfo);
if (!_settings->isEnabled(severity)) if (!mSettings->isEnabled(severity))
return; return;
std::ostringstream errmsg; std::ostringstream errmsg;
errmsg << "%n in format string (no. " << numFormat << ") requires \'int *\' but the argument type is "; errmsg << "%n in format string (no. " << numFormat << ") requires \'int *\' but the argument type is ";
@ -1824,7 +1824,7 @@ void CheckIO::invalidPrintfArgTypeError_n(const Token* tok, unsigned int numForm
void CheckIO::invalidPrintfArgTypeError_p(const Token* tok, unsigned int numFormat, const ArgumentInfo* argInfo) void CheckIO::invalidPrintfArgTypeError_p(const Token* tok, unsigned int numFormat, const ArgumentInfo* argInfo)
{ {
const Severity::SeverityType severity = getSeverity(argInfo); const Severity::SeverityType severity = getSeverity(argInfo);
if (!_settings->isEnabled(severity)) if (!mSettings->isEnabled(severity))
return; return;
std::ostringstream errmsg; std::ostringstream errmsg;
errmsg << "%p in format string (no. " << numFormat << ") requires an address but the argument type is "; errmsg << "%p in format string (no. " << numFormat << ") requires an address but the argument type is ";
@ -1874,7 +1874,7 @@ static void printfFormatType(std::ostream& os, const std::string& specifier, boo
void CheckIO::invalidPrintfArgTypeError_uint(const Token* tok, unsigned int numFormat, const std::string& specifier, const ArgumentInfo* argInfo) void CheckIO::invalidPrintfArgTypeError_uint(const Token* tok, unsigned int numFormat, const std::string& specifier, const ArgumentInfo* argInfo)
{ {
const Severity::SeverityType severity = getSeverity(argInfo); const Severity::SeverityType severity = getSeverity(argInfo);
if (!_settings->isEnabled(severity)) if (!mSettings->isEnabled(severity))
return; return;
std::ostringstream errmsg; std::ostringstream errmsg;
errmsg << "%" << specifier << " in format string (no. " << numFormat << ") requires "; errmsg << "%" << specifier << " in format string (no. " << numFormat << ") requires ";
@ -1888,7 +1888,7 @@ void CheckIO::invalidPrintfArgTypeError_uint(const Token* tok, unsigned int numF
void CheckIO::invalidPrintfArgTypeError_sint(const Token* tok, unsigned int numFormat, const std::string& specifier, const ArgumentInfo* argInfo) void CheckIO::invalidPrintfArgTypeError_sint(const Token* tok, unsigned int numFormat, const std::string& specifier, const ArgumentInfo* argInfo)
{ {
const Severity::SeverityType severity = getSeverity(argInfo); const Severity::SeverityType severity = getSeverity(argInfo);
if (!_settings->isEnabled(severity)) if (!mSettings->isEnabled(severity))
return; return;
std::ostringstream errmsg; std::ostringstream errmsg;
errmsg << "%" << specifier << " in format string (no. " << numFormat << ") requires "; errmsg << "%" << specifier << " in format string (no. " << numFormat << ") requires ";
@ -1901,7 +1901,7 @@ void CheckIO::invalidPrintfArgTypeError_sint(const Token* tok, unsigned int numF
void CheckIO::invalidPrintfArgTypeError_float(const Token* tok, unsigned int numFormat, const std::string& specifier, const ArgumentInfo* argInfo) void CheckIO::invalidPrintfArgTypeError_float(const Token* tok, unsigned int numFormat, const std::string& specifier, const ArgumentInfo* argInfo)
{ {
const Severity::SeverityType severity = getSeverity(argInfo); const Severity::SeverityType severity = getSeverity(argInfo);
if (!_settings->isEnabled(severity)) if (!mSettings->isEnabled(severity))
return; return;
std::ostringstream errmsg; std::ostringstream errmsg;
errmsg << "%" << specifier << " in format string (no. " << numFormat << ") requires \'"; errmsg << "%" << specifier << " in format string (no. " << numFormat << ") requires \'";
@ -1971,7 +1971,7 @@ void CheckIO::argumentType(std::ostream& os, const ArgumentInfo * argInfo)
void CheckIO::invalidLengthModifierError(const Token* tok, unsigned int numFormat, const std::string& modifier) void CheckIO::invalidLengthModifierError(const Token* tok, unsigned int numFormat, const std::string& modifier)
{ {
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
std::ostringstream errmsg; std::ostringstream errmsg;
errmsg << "'" << modifier << "' in format string (no. " << numFormat << ") is a length modifier and cannot be used without a conversion specifier."; errmsg << "'" << modifier << "' in format string (no. " << numFormat << ") is a length modifier and cannot be used without a conversion specifier.";
@ -1990,7 +1990,7 @@ void CheckIO::invalidScanfFormatWidthError(const Token* tok, unsigned int numFor
std::ostringstream errmsg; std::ostringstream errmsg;
if (arrlen > width) { if (arrlen > width) {
if (!_settings->inconclusive || !_settings->isEnabled(Settings::WARNING)) if (!mSettings->inconclusive || !mSettings->isEnabled(Settings::WARNING))
return; return;
errmsg << "Width " << width << " given in format string (no. " << numFormat << ") is smaller than destination buffer" errmsg << "Width " << width << " given in format string (no. " << numFormat << ") is smaller than destination buffer"
<< " '" << varname << "[" << arrlen << "]'."; << " '" << varname << "[" << arrlen << "]'.";

View File

@ -103,8 +103,8 @@ void VarInfo::possibleUsageAll(const std::string &functionName)
void CheckLeakAutoVar::leakError(const Token *tok, const std::string &varname, int type) void CheckLeakAutoVar::leakError(const Token *tok, const std::string &varname, int type)
{ {
const CheckMemoryLeak checkmemleak(_tokenizer, _errorLogger, _settings); const CheckMemoryLeak checkmemleak(mTokenizer, mErrorLogger, mSettings);
if (_settings->library.isresource(type)) if (mSettings->library.isresource(type))
checkmemleak.resourceLeakError(tok, varname); checkmemleak.resourceLeakError(tok, varname);
else else
checkmemleak.memleakError(tok, varname); checkmemleak.memleakError(tok, varname);
@ -112,14 +112,14 @@ void CheckLeakAutoVar::leakError(const Token *tok, const std::string &varname, i
void CheckLeakAutoVar::mismatchError(const Token *tok, const std::string &varname) void CheckLeakAutoVar::mismatchError(const Token *tok, const std::string &varname)
{ {
const CheckMemoryLeak c(_tokenizer, _errorLogger, _settings); const CheckMemoryLeak c(mTokenizer, mErrorLogger, mSettings);
const std::list<const Token *> callstack(1, tok); const std::list<const Token *> callstack(1, tok);
c.mismatchAllocDealloc(callstack, varname); c.mismatchAllocDealloc(callstack, varname);
} }
void CheckLeakAutoVar::deallocUseError(const Token *tok, const std::string &varname) void CheckLeakAutoVar::deallocUseError(const Token *tok, const std::string &varname)
{ {
const CheckMemoryLeak c(_tokenizer, _errorLogger, _settings); const CheckMemoryLeak c(mTokenizer, mErrorLogger, mSettings);
c.deallocuseError(tok, varname); c.deallocuseError(tok, varname);
} }
@ -130,7 +130,7 @@ void CheckLeakAutoVar::deallocReturnError(const Token *tok, const std::string &v
void CheckLeakAutoVar::configurationInfo(const Token* tok, const std::string &functionName) void CheckLeakAutoVar::configurationInfo(const Token* tok, const std::string &functionName)
{ {
if (_settings->checkLibrary && _settings->isEnabled(Settings::INFORMATION)) { if (mSettings->checkLibrary && mSettings->isEnabled(Settings::INFORMATION)) {
reportError(tok, reportError(tok,
Severity::information, Severity::information,
"checkLibraryUseIgnore", "checkLibraryUseIgnore",
@ -140,7 +140,7 @@ void CheckLeakAutoVar::configurationInfo(const Token* tok, const std::string &fu
void CheckLeakAutoVar::doubleFreeError(const Token *tok, const std::string &varname, int type) void CheckLeakAutoVar::doubleFreeError(const Token *tok, const std::string &varname, int type)
{ {
if (_settings->library.isresource(type)) if (mSettings->library.isresource(type))
reportError(tok, Severity::error, "doubleFree", "$symbol:" + varname + "\nResource handle '$symbol' freed twice.", CWE415, false); reportError(tok, Severity::error, "doubleFree", "$symbol:" + varname + "\nResource handle '$symbol' freed twice.", CWE415, false);
else else
reportError(tok, Severity::error, "doubleFree", "$symbol:" + varname + "\nMemory pointed to by '$symbol' is freed twice.", CWE415, false); reportError(tok, Severity::error, "doubleFree", "$symbol:" + varname + "\nMemory pointed to by '$symbol' is freed twice.", CWE415, false);
@ -149,7 +149,7 @@ void CheckLeakAutoVar::doubleFreeError(const Token *tok, const std::string &varn
void CheckLeakAutoVar::check() void CheckLeakAutoVar::check()
{ {
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
// Local variables that are known to be non-zero. // Local variables that are known to be non-zero.
const std::set<unsigned int> notzero; const std::set<unsigned int> notzero;
@ -322,7 +322,7 @@ void CheckLeakAutoVar::checkScope(const Token * const startToken,
continue; continue;
// non-pod variable // non-pod variable
if (_tokenizer->isCPP()) { if (mTokenizer->isCPP()) {
if (!var) if (!var)
continue; continue;
// Possibly automatically deallocated memory // Possibly automatically deallocated memory
@ -334,13 +334,13 @@ void CheckLeakAutoVar::checkScope(const Token * const startToken,
// allocation? // allocation?
if (tokRightAstOperand && Token::Match(tokRightAstOperand->previous(), "%type% (")) { if (tokRightAstOperand && Token::Match(tokRightAstOperand->previous(), "%type% (")) {
const Library::AllocFunc* f = _settings->library.alloc(tokRightAstOperand->previous()); const Library::AllocFunc* f = mSettings->library.alloc(tokRightAstOperand->previous());
if (f && f->arg == -1) { if (f && f->arg == -1) {
VarInfo::AllocInfo& varAlloc = alloctype[varTok->varId()]; VarInfo::AllocInfo& varAlloc = alloctype[varTok->varId()];
varAlloc.type = f->groupId; varAlloc.type = f->groupId;
varAlloc.status = VarInfo::ALLOC; varAlloc.status = VarInfo::ALLOC;
} }
} else if (_tokenizer->isCPP() && Token::Match(varTok->tokAt(2), "new !!(")) { } else if (mTokenizer->isCPP() && Token::Match(varTok->tokAt(2), "new !!(")) {
const Token* tok2 = varTok->tokAt(2)->astOperand1(); const Token* tok2 = varTok->tokAt(2)->astOperand1();
const bool arrayNew = (tok2 && (tok2->str() == "[" || (tok2->str() == "(" && tok2->astOperand1() && tok2->astOperand1()->str() == "["))); const bool arrayNew = (tok2 && (tok2->str() == "[" || (tok2->str() == "(" && tok2->astOperand1() && tok2->astOperand1()->str() == "[")));
VarInfo::AllocInfo& varAlloc = alloctype[varTok->varId()]; VarInfo::AllocInfo& varAlloc = alloctype[varTok->varId()];
@ -369,13 +369,13 @@ void CheckLeakAutoVar::checkScope(const Token * const startToken,
if (Token::Match(innerTok, "%var% =")) { if (Token::Match(innerTok, "%var% =")) {
// allocation? // allocation?
if (Token::Match(innerTok->tokAt(2), "%type% (")) { if (Token::Match(innerTok->tokAt(2), "%type% (")) {
const Library::AllocFunc* f = _settings->library.alloc(innerTok->tokAt(2)); const Library::AllocFunc* f = mSettings->library.alloc(innerTok->tokAt(2));
if (f && f->arg == -1) { if (f && f->arg == -1) {
VarInfo::AllocInfo& varAlloc = alloctype[innerTok->varId()]; VarInfo::AllocInfo& varAlloc = alloctype[innerTok->varId()];
varAlloc.type = f->groupId; varAlloc.type = f->groupId;
varAlloc.status = VarInfo::ALLOC; varAlloc.status = VarInfo::ALLOC;
} }
} else if (_tokenizer->isCPP() && Token::Match(innerTok->tokAt(2), "new !!(")) { } else if (mTokenizer->isCPP() && Token::Match(innerTok->tokAt(2), "new !!(")) {
const Token* tok2 = innerTok->tokAt(2)->astOperand1(); const Token* tok2 = innerTok->tokAt(2)->astOperand1();
const bool arrayNew = (tok2 && (tok2->str() == "[" || (tok2->str() == "(" && tok2->astOperand1() && tok2->astOperand1()->str() == "["))); const bool arrayNew = (tok2 && (tok2->str() == "[" || (tok2->str() == "(" && tok2->astOperand1() && tok2->astOperand1()->str() == "[")));
VarInfo::AllocInfo& varAlloc = alloctype[innerTok->varId()]; VarInfo::AllocInfo& varAlloc = alloctype[innerTok->varId()];
@ -526,7 +526,7 @@ void CheckLeakAutoVar::checkScope(const Token * const startToken,
} }
// throw // throw
else if (_tokenizer->isCPP() && tok->str() == "throw") { else if (mTokenizer->isCPP() && tok->str() == "throw") {
bool tryFound = false; bool tryFound = false;
const Scope* scope = tok->scope(); const Scope* scope = tok->scope();
while (scope && scope->isExecutable()) { while (scope && scope->isExecutable()) {
@ -543,7 +543,7 @@ void CheckLeakAutoVar::checkScope(const Token * const startToken,
// Function call.. // Function call..
else if (isFunctionCall(ftok)) { else if (isFunctionCall(ftok)) {
const Token * openingPar = isFunctionCall(ftok); const Token * openingPar = isFunctionCall(ftok);
const Library::AllocFunc* af = _settings->library.dealloc(ftok); const Library::AllocFunc* af = mSettings->library.dealloc(ftok);
VarInfo::AllocInfo allocation(af ? af->groupId : 0, VarInfo::DEALLOC); VarInfo::AllocInfo allocation(af ? af->groupId : 0, VarInfo::DEALLOC);
if (allocation.type == 0) if (allocation.type == 0)
allocation.status = VarInfo::NOALLOC; allocation.status = VarInfo::NOALLOC;
@ -555,10 +555,10 @@ void CheckLeakAutoVar::checkScope(const Token * const startToken,
if (allocation.status == VarInfo::NOALLOC && Token::simpleMatch(tok, ") ; }")) { if (allocation.status == VarInfo::NOALLOC && Token::simpleMatch(tok, ") ; }")) {
const std::string &functionName(tok->link()->previous()->str()); const std::string &functionName(tok->link()->previous()->str());
bool unknown = false; bool unknown = false;
if (_tokenizer->IsScopeNoReturn(tok->tokAt(2), &unknown)) { if (mTokenizer->IsScopeNoReturn(tok->tokAt(2), &unknown)) {
if (!unknown) if (!unknown)
varInfo->clear(); varInfo->clear();
else if (!_settings->library.isLeakIgnore(functionName) && !_settings->library.isUse(functionName)) else if (!mSettings->library.isLeakIgnore(functionName) && !mSettings->library.isUse(functionName))
varInfo->possibleUsageAll(functionName); varInfo->possibleUsageAll(functionName);
} }
} }
@ -567,7 +567,7 @@ void CheckLeakAutoVar::checkScope(const Token * const startToken,
} }
// delete // delete
else if (_tokenizer->isCPP() && tok->str() == "delete") { else if (mTokenizer->isCPP() && tok->str() == "delete") {
const bool arrayDelete = (tok->strAt(1) == "["); const bool arrayDelete = (tok->strAt(1) == "[");
if (arrayDelete) if (arrayDelete)
tok = tok->tokAt(3); tok = tok->tokAt(3);
@ -629,7 +629,7 @@ void CheckLeakAutoVar::checkScope(const Token * const startToken,
// Check if its a pointer to a function // Check if its a pointer to a function
const Token * dtok = Token::findmatch(deleterToken, "& %name%", endDeleterToken); const Token * dtok = Token::findmatch(deleterToken, "& %name%", endDeleterToken);
if (dtok) { if (dtok) {
af = _settings->library.dealloc(dtok->tokAt(1)); af = mSettings->library.dealloc(dtok->tokAt(1));
} else { } else {
const Token * tscopeStart = nullptr; const Token * tscopeStart = nullptr;
const Token * tscopeEnd = nullptr; const Token * tscopeEnd = nullptr;
@ -651,7 +651,7 @@ void CheckLeakAutoVar::checkScope(const Token * const startToken,
if (tscopeStart && tscopeEnd) { if (tscopeStart && tscopeEnd) {
for (const Token *tok2 = tscopeStart; tok2 != tscopeEnd; tok2 = tok2->next()) { for (const Token *tok2 = tscopeStart; tok2 != tscopeEnd; tok2 = tok2->next()) {
af = _settings->library.dealloc(tok2); af = mSettings->library.dealloc(tok2);
if (af) if (af)
break; break;
} }
@ -691,7 +691,7 @@ const Token * CheckLeakAutoVar::checkTokenInsideExpression(const Token * const t
// check for function call // check for function call
const Token * const openingPar = isFunctionCall(tok); const Token * const openingPar = isFunctionCall(tok);
if (openingPar) { if (openingPar) {
const Library::AllocFunc* allocFunc = _settings->library.dealloc(tok); const Library::AllocFunc* allocFunc = mSettings->library.dealloc(tok);
VarInfo::AllocInfo alloc(allocFunc ? allocFunc->groupId : 0, VarInfo::DEALLOC); VarInfo::AllocInfo alloc(allocFunc ? allocFunc->groupId : 0, VarInfo::DEALLOC);
if (alloc.type == 0) if (alloc.type == 0)
alloc.status = VarInfo::NOALLOC; alloc.status = VarInfo::NOALLOC;
@ -733,7 +733,7 @@ void CheckLeakAutoVar::changeAllocStatus(VarInfo *varInfo, const VarInfo::AllocI
void CheckLeakAutoVar::functionCall(const Token *tokName, const Token *tokOpeningPar, VarInfo *varInfo, const VarInfo::AllocInfo& allocation, const Library::AllocFunc* af) void CheckLeakAutoVar::functionCall(const Token *tokName, const Token *tokOpeningPar, VarInfo *varInfo, const VarInfo::AllocInfo& allocation, const Library::AllocFunc* af)
{ {
// Ignore function call? // Ignore function call?
if (_settings->library.isLeakIgnore(tokName->str())) if (mSettings->library.isLeakIgnore(tokName->str()))
return; return;
const Token * const tokFirstArg = tokOpeningPar->next(); const Token * const tokFirstArg = tokOpeningPar->next();
@ -744,7 +744,7 @@ void CheckLeakAutoVar::functionCall(const Token *tokName, const Token *tokOpenin
int argNr = 1; int argNr = 1;
for (const Token *arg = tokFirstArg; arg; arg = arg->nextArgument()) { for (const Token *arg = tokFirstArg; arg; arg = arg->nextArgument()) {
if (_tokenizer->isCPP() && arg->str() == "new") { if (mTokenizer->isCPP() && arg->str() == "new") {
arg = arg->next(); arg = arg->next();
if (Token::simpleMatch(arg, "( std :: nothrow )")) if (Token::simpleMatch(arg, "( std :: nothrow )"))
arg = arg->tokAt(5); arg = arg->tokAt(5);
@ -789,14 +789,14 @@ void CheckLeakAutoVar::functionCall(const Token *tokName, const Token *tokOpenin
// Check if its a pointer to a function // Check if its a pointer to a function
const Token * dtok = Token::findmatch(deleterToken, "& %name%", endDeleterToken); const Token * dtok = Token::findmatch(deleterToken, "& %name%", endDeleterToken);
if (dtok) { if (dtok) {
sp_af = _settings->library.dealloc(dtok->tokAt(1)); sp_af = mSettings->library.dealloc(dtok->tokAt(1));
} else { } else {
// If the deleter is a class, check if class calls the dealloc function // If the deleter is a class, check if class calls the dealloc function
dtok = Token::findmatch(deleterToken, "%type%", endDeleterToken); dtok = Token::findmatch(deleterToken, "%type%", endDeleterToken);
if (dtok && dtok->type()) { if (dtok && dtok->type()) {
const Scope * tscope = dtok->type()->classScope; const Scope * tscope = dtok->type()->classScope;
for (const Token *tok2 = tscope->bodyStart; tok2 != tscope->bodyEnd; tok2 = tok2->next()) { for (const Token *tok2 = tscope->bodyStart; tok2 != tscope->bodyEnd; tok2 = tok2->next()) {
sp_af = _settings->library.dealloc(tok2); sp_af = mSettings->library.dealloc(tok2);
if (sp_af) if (sp_af)
break; break;
} }
@ -838,7 +838,7 @@ void CheckLeakAutoVar::ret(const Token *tok, const VarInfo &varInfo)
const std::map<unsigned int, VarInfo::AllocInfo> &alloctype = varInfo.alloctype; const std::map<unsigned int, VarInfo::AllocInfo> &alloctype = varInfo.alloctype;
const std::map<unsigned int, std::string> &possibleUsage = varInfo.possibleUsage; const std::map<unsigned int, std::string> &possibleUsage = varInfo.possibleUsage;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (std::map<unsigned int, VarInfo::AllocInfo>::const_iterator it = alloctype.begin(); it != alloctype.end(); ++it) { for (std::map<unsigned int, VarInfo::AllocInfo>::const_iterator it = alloctype.begin(); it != alloctype.end(); ++it) {
// don't warn if variable is conditionally allocated // don't warn if variable is conditionally allocated
if (!it->second.managed() && varInfo.conditionalAlloc.find(it->first) != varInfo.conditionalAlloc.end()) if (!it->second.managed() && varInfo.conditionalAlloc.find(it->first) != varInfo.conditionalAlloc.end())

View File

@ -524,7 +524,7 @@ namespace {
const char * CheckMemoryLeakInFunction::call_func(const Token *tok, std::list<const Token *> callstack, const unsigned int varid, AllocType &alloctype, AllocType &dealloctype, bool &allocpar, unsigned int sz) const char * CheckMemoryLeakInFunction::call_func(const Token *tok, std::list<const Token *> callstack, const unsigned int varid, AllocType &alloctype, AllocType &dealloctype, bool &allocpar, unsigned int sz)
{ {
if (test_white_list(tok->str(), _settings, tokenizer->isCPP())) { if (test_white_list(tok->str(), mSettings, tokenizer->isCPP())) {
if (call_func_keywords.find(tok->str())!=call_func_keywords.end()) if (call_func_keywords.find(tok->str())!=call_func_keywords.end())
return nullptr; return nullptr;
@ -550,7 +550,7 @@ const char * CheckMemoryLeakInFunction::call_func(const Token *tok, std::list<co
return nullptr; return nullptr;
} }
if (_settings->library.isnoreturn(tok) && tok->strAt(-1) != "=") if (mSettings->library.isnoreturn(tok) && tok->strAt(-1) != "=")
return "exit"; return "exit";
if (varid > 0 && (getReallocationType(tok, varid) != No || getDeallocationType(tok, varid) != No)) if (varid > 0 && (getReallocationType(tok, varid) != No || getDeallocationType(tok, varid) != No))
@ -593,9 +593,9 @@ const char * CheckMemoryLeakInFunction::call_func(const Token *tok, std::list<co
// Function is not noreturn // Function is not noreturn
if (tok->function() && tok->function()->functionScope) { if (tok->function() && tok->function()->functionScope) {
std::string temp; std::string temp;
if (!_settings->library.isScopeNoReturn(tok->function()->functionScope->bodyEnd, &temp) && temp.empty()) if (!mSettings->library.isScopeNoReturn(tok->function()->functionScope->bodyEnd, &temp) && temp.empty())
return nullptr; return nullptr;
} else if (_settings->library.isnotnoreturn(tok)) } else if (mSettings->library.isnotnoreturn(tok))
return nullptr; return nullptr;
return "callfunc"; return "callfunc";
@ -668,7 +668,7 @@ const char * CheckMemoryLeakInFunction::call_func(const Token *tok, std::list<co
if (Token::Match(tok, "%varid% . %name% [,)]", varid)) if (Token::Match(tok, "%varid% . %name% [,)]", varid))
return "use"; return "use";
} }
return (eq || _settings->experimental) ? nullptr : "callfunc"; return (eq || mSettings->experimental) ? nullptr : "callfunc";
} }
template<typename T> template<typename T>
@ -868,7 +868,7 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::list<const Toke
if (alloc != Many && dealloctype != No && dealloctype != Many && dealloctype != alloc) { if (alloc != Many && dealloctype != No && dealloctype != Many && dealloctype != alloc) {
callstack.push_back(tok); callstack.push_back(tok);
mismatchAllocDealloc(callstack, Token::findmatch(_tokenizer->tokens(), "%varid%", varid)->str()); mismatchAllocDealloc(callstack, Token::findmatch(mTokenizer->tokens(), "%varid%", varid)->str());
callstack.pop_back(); callstack.pop_back();
} }
@ -939,7 +939,7 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::list<const Toke
if (dealloc != Many && alloctype != No && alloctype != Many && alloctype != dealloc) { if (dealloc != Many && alloctype != No && alloctype != Many && alloctype != dealloc) {
callstack.push_back(tok); callstack.push_back(tok);
mismatchAllocDealloc(callstack, Token::findmatch(_tokenizer->tokens(), "%varid%", varid)->str()); mismatchAllocDealloc(callstack, Token::findmatch(mTokenizer->tokens(), "%varid%", varid)->str());
callstack.pop_back(); callstack.pop_back();
} }
dealloctype = dealloc; dealloctype = dealloc;
@ -1004,7 +1004,7 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::list<const Toke
dep = true; dep = true;
} else if (Token::Match(tok2, "! %varid%", varid)) { } else if (Token::Match(tok2, "! %varid%", varid)) {
dep = true; dep = true;
} else if (Token::Match(tok2, "%name% (") && !test_white_list(tok2->str(), _settings, tokenizer->isCPP())) { } else if (Token::Match(tok2, "%name% (") && !test_white_list(tok2->str(), mSettings, tokenizer->isCPP())) {
bool use = false; bool use = false;
for (const Token *tok3 = tok2->tokAt(2); tok3; tok3 = tok3->nextArgument()) { for (const Token *tok3 = tok2->tokAt(2); tok3; tok3 = tok3->nextArgument()) {
if (Token::Match(tok3->previous(), "(|, &| %varid% ,|)", varid)) { if (Token::Match(tok3->previous(), "(|, &| %varid% ,|)", varid)) {
@ -1170,7 +1170,7 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::list<const Toke
tok2->strAt(1) == "[") { tok2->strAt(1) == "[") {
; ;
} else if (functions.empty() || } else if (functions.empty() ||
!test_white_list(functions.top()->str(), _settings, tokenizer->isCPP()) || !test_white_list(functions.top()->str(), mSettings, tokenizer->isCPP()) ||
getDeallocationType(functions.top(),varid) != AllocType::No) { getDeallocationType(functions.top(),varid) != AllocType::No) {
use = true; use = true;
} }
@ -1252,10 +1252,10 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::list<const Toke
// just add a "::use" // just add a "::use"
// The "::use" means that a member function was probably called but it wasn't analysed further // The "::use" means that a member function was probably called but it wasn't analysed further
else if (classmember) { else if (classmember) {
if (_settings->library.isnoreturn(tok)) if (mSettings->library.isnoreturn(tok))
addtoken(&rettail, tok, "exit"); addtoken(&rettail, tok, "exit");
else if (!test_white_list(tok->str(), _settings, tokenizer->isCPP())) { else if (!test_white_list(tok->str(), mSettings, tokenizer->isCPP())) {
const Token* const end2 = tok->linkAt(1); const Token* const end2 = tok->linkAt(1);
for (const Token *tok2 = tok->tokAt(2); tok2 != end2; tok2 = tok2->next()) { for (const Token *tok2 = tok->tokAt(2); tok2 != end2; tok2 = tok2->next()) {
if (tok2->varId() == varid) { if (tok2->varId() == varid) {
@ -1330,7 +1330,7 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::list<const Toke
parent = parent->astParent(); parent = parent->astParent();
if (parent && parent->astOperand1() && parent->astOperand1()->isName()) { if (parent && parent->astOperand1() && parent->astOperand1()->isName()) {
const std::string &functionName = parent->astOperand1()->str(); const std::string &functionName = parent->astOperand1()->str();
if (_settings->library.isLeakIgnore(functionName)) if (mSettings->library.isLeakIgnore(functionName))
leakignore = true; leakignore = true;
} }
} }
@ -1356,7 +1356,7 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::list<const Toke
void CheckMemoryLeakInFunction::simplifycode(Token *tok) const void CheckMemoryLeakInFunction::simplifycode(Token *tok) const
{ {
if (_tokenizer->isCPP()) { if (mTokenizer->isCPP()) {
// Replace "throw" that is not in a try block with "return" // Replace "throw" that is not in a try block with "return"
int indentlevel = 0; int indentlevel = 0;
int trylevel = -1; int trylevel = -1;
@ -1374,7 +1374,7 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok) const
} }
} }
const bool printExperimental = _settings->experimental; const bool printExperimental = mSettings->experimental;
// Insert extra ";" // Insert extra ";"
for (Token *tok2 = tok; tok2; tok2 = tok2->next()) { for (Token *tok2 = tok; tok2; tok2 = tok2->next()) {
@ -2066,7 +2066,7 @@ void CheckMemoryLeakInFunction::checkScope(const Token *startTok, const std::str
simplifycode(tok); simplifycode(tok);
if (_settings->debug && _settings->verbose) { if (mSettings->debug && mSettings->verbose) {
tok->printOut(("Checkmemoryleak: simplifycode result for: " + varname).c_str()); tok->printOut(("Checkmemoryleak: simplifycode result for: " + varname).c_str());
} }
@ -2091,7 +2091,7 @@ void CheckMemoryLeakInFunction::checkScope(const Token *startTok, const std::str
} }
// detect cases that "simplifycode" don't handle well.. // detect cases that "simplifycode" don't handle well..
else if (tok && _settings->debugwarnings) { else if (tok && mSettings->debugwarnings) {
Token *first = tok; Token *first = tok;
while (first && first->str() == ";") while (first && first->str() == ";")
first = first->next(); first = first->next();
@ -2156,7 +2156,7 @@ void CheckMemoryLeakInFunction::checkReallocUsage()
if (Token::simpleMatch(tokEndRealloc->next(), "; if (") && if (Token::simpleMatch(tokEndRealloc->next(), "; if (") &&
notvar(tokEndRealloc->tokAt(3)->astOperand2(), tok->varId())) { notvar(tokEndRealloc->tokAt(3)->astOperand2(), tok->varId())) {
const Token* tokEndBrace = tokEndRealloc->linkAt(3)->linkAt(1); const Token* tokEndBrace = tokEndRealloc->linkAt(3)->linkAt(1);
if (tokEndBrace && _tokenizer->IsScopeNoReturn(tokEndBrace)) if (tokEndBrace && mTokenizer->IsScopeNoReturn(tokEndBrace))
continue; continue;
} }
@ -2224,7 +2224,7 @@ void CheckMemoryLeakInFunction::check()
if (var->scope()->hasInlineOrLambdaFunction()) if (var->scope()->hasInlineOrLambdaFunction())
continue; continue;
unsigned int sz = _tokenizer->sizeOfType(var->typeStartToken()); unsigned int sz = mTokenizer->sizeOfType(var->typeStartToken());
if (sz < 1) if (sz < 1)
sz = 1; sz = 1;
@ -2244,7 +2244,7 @@ void CheckMemoryLeakInFunction::check()
void CheckMemoryLeakInClass::check() void CheckMemoryLeakInClass::check()
{ {
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
// only check classes and structures // only check classes and structures
const std::size_t classes = symbolDatabase->classAndStructScopes.size(); const std::size_t classes = symbolDatabase->classAndStructScopes.size();
@ -2362,7 +2362,7 @@ void CheckMemoryLeakInClass::variable(const Scope *scope, const Token *tokVarnam
// Function call .. possible deallocation // Function call .. possible deallocation
else if (Token::Match(tok->previous(), "[{};] %name% (")) { else if (Token::Match(tok->previous(), "[{};] %name% (")) {
if (!CheckMemoryLeakInFunction::test_white_list(tok->str(), _settings, tokenizer->isCPP())) { if (!CheckMemoryLeakInFunction::test_white_list(tok->str(), mSettings, tokenizer->isCPP())) {
return; return;
} }
} }
@ -2379,7 +2379,7 @@ void CheckMemoryLeakInClass::variable(const Scope *scope, const Token *tokVarnam
void CheckMemoryLeakInClass::unsafeClassError(const Token *tok, const std::string &classname, const std::string &varname) void CheckMemoryLeakInClass::unsafeClassError(const Token *tok, const std::string &classname, const std::string &varname)
{ {
if (!_settings->isEnabled(Settings::STYLE)) if (!mSettings->isEnabled(Settings::STYLE))
return; return;
reportError(tok, Severity::style, "unsafeClassCanLeak", reportError(tok, Severity::style, "unsafeClassCanLeak",
@ -2395,7 +2395,7 @@ void CheckMemoryLeakInClass::checkPublicFunctions(const Scope *scope, const Toke
// Check that public functions deallocate the pointers that they allocate. // Check that public functions deallocate the pointers that they allocate.
// There is no checking how these functions are used and therefore it // There is no checking how these functions are used and therefore it
// isn't established if there is real leaks or not. // isn't established if there is real leaks or not.
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
const unsigned int varid = classtok->varId(); const unsigned int varid = classtok->varId();
@ -2430,7 +2430,7 @@ void CheckMemoryLeakInClass::publicAllocationError(const Token *tok, const std::
void CheckMemoryLeakStructMember::check() void CheckMemoryLeakStructMember::check()
{ {
const SymbolDatabase* symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Variable* var : symbolDatabase->variableList()) { for (const Variable* var : symbolDatabase->variableList()) {
if (!var || !var->isLocal() || var->isStatic()) if (!var || !var->isLocal() || var->isStatic())
continue; continue;
@ -2461,7 +2461,7 @@ void CheckMemoryLeakStructMember::checkStructVariable(const Variable * const var
// Check that variable is allocated with malloc // Check that variable is allocated with malloc
if (!isMalloc(variable)) if (!isMalloc(variable))
return; return;
} else if (!_tokenizer->isC() && (!variable->typeScope() || variable->typeScope()->getDestructor())) { } else if (!mTokenizer->isC() && (!variable->typeScope() || variable->typeScope()->getDestructor())) {
// For non-C code a destructor might cleanup members // For non-C code a destructor might cleanup members
return; return;
} }
@ -2597,7 +2597,7 @@ void CheckMemoryLeakStructMember::checkStructVariable(const Variable * const var
// using struct in a function call.. // using struct in a function call..
else if (Token::Match(tok3, "%name% (")) { else if (Token::Match(tok3, "%name% (")) {
// Calling non-function / function that doesn't deallocate? // Calling non-function / function that doesn't deallocate?
if (CheckMemoryLeakInFunction::test_white_list(tok3->str(), _settings, tokenizer->isCPP())) if (CheckMemoryLeakInFunction::test_white_list(tok3->str(), mSettings, tokenizer->isCPP()))
continue; continue;
// Check if the struct is used.. // Check if the struct is used..
@ -2629,7 +2629,7 @@ void CheckMemoryLeakStructMember::checkStructVariable(const Variable * const var
void CheckMemoryLeakNoVar::check() void CheckMemoryLeakNoVar::check()
{ {
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
// only check functions // only check functions
const std::size_t functions = symbolDatabase->functionScopes.size(); const std::size_t functions = symbolDatabase->functionScopes.size();
@ -2665,7 +2665,7 @@ void CheckMemoryLeakNoVar::check()
functionName == "fclose" || functionName == "fclose" ||
functionName == "realloc") functionName == "realloc")
break; break;
if (CheckMemoryLeakInFunction::test_white_list(functionName, _settings, tokenizer->isCPP())) { if (CheckMemoryLeakInFunction::test_white_list(functionName, mSettings, tokenizer->isCPP())) {
functionCallLeak(tok, tok->strAt(1), functionName); functionCallLeak(tok, tok->strAt(1), functionName);
break; break;
} }
@ -2723,7 +2723,7 @@ void CheckMemoryLeakNoVar::checkForUnusedReturnValue(const Scope *scope)
void CheckMemoryLeakNoVar::checkForUnsafeArgAlloc(const Scope *scope) void CheckMemoryLeakNoVar::checkForUnsafeArgAlloc(const Scope *scope)
{ {
// This test only applies to C++ source // This test only applies to C++ source
if (!_tokenizer->isCPP() || !_settings->inconclusive || !_settings->isEnabled(Settings::WARNING)) if (!mTokenizer->isCPP() || !mSettings->inconclusive || !mSettings->isEnabled(Settings::WARNING))
return; return;
for (const Token *tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) { for (const Token *tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {

View File

@ -234,7 +234,7 @@ public:
const char * call_func(const Token *tok, std::list<const Token *> callstack, const unsigned int varid, AllocType &alloctype, AllocType &dealloctype, bool &allocpar, unsigned int sz); const char * call_func(const Token *tok, std::list<const Token *> callstack, const unsigned int varid, AllocType &alloctype, AllocType &dealloctype, bool &allocpar, unsigned int sz);
/** /**
* Extract a new tokens list that is easier to parse than the "_tokenizer->tokens()", the * Extract a new tokens list that is easier to parse than the "mTokenizer->tokens()", the
* extracted tokens list describes how the given variable is used. * extracted tokens list describes how the given variable is used.
* The getcode and call_func are recursive * The getcode and call_func are recursive
* @param tok start parse token * @param tok start parse token

View File

@ -252,10 +252,10 @@ bool CheckNullPointer::isPointerDeRef(const Token *tok, bool &unknown)
void CheckNullPointer::nullPointerLinkedList() void CheckNullPointer::nullPointerLinkedList()
{ {
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
const SymbolDatabase* const symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
// looping through items in a linked list in a inner loop. // looping through items in a linked list in a inner loop.
// Here is an example: // Here is an example:
@ -318,9 +318,9 @@ void CheckNullPointer::nullPointerLinkedList()
void CheckNullPointer::nullPointerByDeRefAndChec() void CheckNullPointer::nullPointerByDeRefAndChec()
{ {
const bool printInconclusive = (_settings->inconclusive); const bool printInconclusive = (mSettings->inconclusive);
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (Token::Match(tok, "sizeof|decltype|typeid|typeof (")) { if (Token::Match(tok, "sizeof|decltype|typeid|typeof (")) {
tok = tok->next()->link(); tok = tok->next()->link();
continue; continue;
@ -349,7 +349,7 @@ void CheckNullPointer::nullPointerByDeRefAndChec()
if (!ftok || !ftok->previous()) if (!ftok || !ftok->previous())
continue; continue;
std::list<const Token *> varlist; std::list<const Token *> varlist;
parseFunctionCall(*ftok->previous(), varlist, &_settings->library); parseFunctionCall(*ftok->previous(), varlist, &mSettings->library);
if (std::find(varlist.begin(), varlist.end(), tok) != varlist.end()) { if (std::find(varlist.begin(), varlist.end(), tok) != varlist.end()) {
nullPointerError(tok, tok->str(), value, value->isInconclusive()); nullPointerError(tok, tok->str(), value, value->isInconclusive());
} }
@ -384,7 +384,7 @@ namespace {
/** Dereferencing null constant (simplified token list) */ /** Dereferencing null constant (simplified token list) */
void CheckNullPointer::nullConstantDereference() void CheckNullPointer::nullConstantDereference()
{ {
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) { for (const Scope * scope : symbolDatabase->functionScopes) {
if (scope->function == nullptr || !scope->function->hasBody()) // We only look for functions with a body if (scope->function == nullptr || !scope->function->hasBody()) // We only look for functions with a body
@ -415,7 +415,7 @@ void CheckNullPointer::nullConstantDereference()
nullPointerError(tok); nullPointerError(tok);
} else { // function call } else { // function call
std::list<const Token *> var; std::list<const Token *> var;
parseFunctionCall(*tok, var, &_settings->library); parseFunctionCall(*tok, var, &mSettings->library);
// is one of the var items a NULL pointer? // is one of the var items a NULL pointer?
for (std::list<const Token *>::const_iterator it = var.begin(); it != var.end(); ++it) { for (std::list<const Token *>::const_iterator it = var.begin(); it != var.end(); ++it) {
@ -435,7 +435,7 @@ void CheckNullPointer::nullConstantDereference()
continue; continue;
if (argtok->values().front().intvalue != 0) if (argtok->values().front().intvalue != 0)
continue; continue;
if (_settings->library.isnullargbad(tok, argnr+1)) if (mSettings->library.isnullargbad(tok, argnr+1))
nullPointerError(argtok); nullPointerError(argtok);
} }
} }
@ -492,7 +492,7 @@ void CheckNullPointer::nullPointerError(const Token *tok, const std::string &var
return; return;
} }
if (!_settings->isEnabled(value, inconclusive)) if (!mSettings->isEnabled(value, inconclusive))
return; return;
const ErrorPath errorPath = getErrorPath(tok, value, "Null pointer dereference"); const ErrorPath errorPath = getErrorPath(tok, value, "Null pointer dereference");
@ -517,7 +517,7 @@ void CheckNullPointer::nullPointerError(const Token *tok, const std::string &var
void CheckNullPointer::arithmetic() void CheckNullPointer::arithmetic()
{ {
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) { for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (!Token::Match(tok, "-|+|+=|-=|++|--")) if (!Token::Match(tok, "-|+|+=|-=|++|--"))
@ -548,9 +548,9 @@ void CheckNullPointer::arithmetic()
const ValueFlow::Value *value = pointerOperand->getValue(checkValue); const ValueFlow::Value *value = pointerOperand->getValue(checkValue);
if (!value) if (!value)
continue; continue;
if (!_settings->inconclusive && value->isInconclusive()) if (!mSettings->inconclusive && value->isInconclusive())
continue; continue;
if (value->condition && !_settings->isEnabled(Settings::WARNING)) if (value->condition && !mSettings->isEnabled(Settings::WARNING))
continue; continue;
arithmeticError(tok,value); arithmeticError(tok,value);
} }

View File

@ -80,10 +80,10 @@ static const struct CWE CWE783(783U); // Operator Precedence Logic Error
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
void CheckOther::checkCastIntToCharAndBack() void CheckOther::checkCastIntToCharAndBack()
{ {
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) { for (const Scope * scope : symbolDatabase->functionScopes) {
std::map<unsigned int, std::string> vars; std::map<unsigned int, std::string> vars;
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
@ -101,13 +101,13 @@ void CheckOther::checkCastIntToCharAndBack()
if (var && var->typeEndToken()->str() == "char" && !var->typeEndToken()->isSigned()) { if (var && var->typeEndToken()->str() == "char" && !var->typeEndToken()->isSigned()) {
checkCastIntToCharAndBackError(tok, tok->strAt(2)); checkCastIntToCharAndBackError(tok, tok->strAt(2));
} }
} else if (_tokenizer->isCPP() && (Token::Match(tok, "EOF %comp% ( %var% = std :: cin . get (") || Token::Match(tok, "EOF %comp% ( %var% = cin . get ("))) { } else if (mTokenizer->isCPP() && (Token::Match(tok, "EOF %comp% ( %var% = std :: cin . get (") || Token::Match(tok, "EOF %comp% ( %var% = cin . get ("))) {
tok = tok->tokAt(3); tok = tok->tokAt(3);
const Variable *var = tok->variable(); const Variable *var = tok->variable();
if (var && var->typeEndToken()->str() == "char" && !var->typeEndToken()->isSigned()) { if (var && var->typeEndToken()->str() == "char" && !var->typeEndToken()->isSigned()) {
checkCastIntToCharAndBackError(tok, "cin.get"); checkCastIntToCharAndBackError(tok, "cin.get");
} }
} else if (_tokenizer->isCPP() && (Token::Match(tok, "%var% = std :: cin . get (") || Token::Match(tok, "%var% = cin . get ("))) { } else if (mTokenizer->isCPP() && (Token::Match(tok, "%var% = std :: cin . get (") || Token::Match(tok, "%var% = cin . get ("))) {
const Variable *var = tok->variable(); const Variable *var = tok->variable();
if (var && var->typeEndToken()->str() == "char" && !var->typeEndToken()->isSigned()) { if (var && var->typeEndToken()->str() == "char" && !var->typeEndToken()->isSigned()) {
vars[tok->varId()] = "cin.get"; vars[tok->varId()] = "cin.get";
@ -148,10 +148,10 @@ void CheckOther::checkCastIntToCharAndBackError(const Token *tok, const std::str
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
void CheckOther::clarifyCalculation() void CheckOther::clarifyCalculation()
{ {
if (!_settings->isEnabled(Settings::STYLE)) if (!mSettings->isEnabled(Settings::STYLE))
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) { for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
// ? operator where lhs is arithmetical expression // ? operator where lhs is arithmetical expression
@ -200,10 +200,10 @@ void CheckOther::clarifyCalculationError(const Token *tok, const std::string &op
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
void CheckOther::clarifyStatement() void CheckOther::clarifyStatement()
{ {
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) { for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart; tok && tok != scope->bodyEnd; tok = tok->next()) { for (const Token* tok = scope->bodyStart; tok && tok != scope->bodyEnd; tok = tok->next()) {
if (Token::Match(tok, "* %name%") && tok->astOperand1()) { if (Token::Match(tok, "* %name%") && tok->astOperand1()) {
@ -234,10 +234,10 @@ void CheckOther::clarifyStatementError(const Token *tok)
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
void CheckOther::checkSuspiciousSemicolon() void CheckOther::checkSuspiciousSemicolon()
{ {
if (!_settings->inconclusive || !_settings->isEnabled(Settings::WARNING)) if (!mSettings->inconclusive || !mSettings->isEnabled(Settings::WARNING))
return; return;
const SymbolDatabase* const symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
// Look for "if(); {}", "for(); {}" or "while(); {}" // Look for "if(); {}", "for(); {}" or "while(); {}"
for (std::list<Scope>::const_iterator i = symbolDatabase->scopeList.begin(); i != symbolDatabase->scopeList.end(); ++i) { for (std::list<Scope>::const_iterator i = symbolDatabase->scopeList.begin(); i != symbolDatabase->scopeList.end(); ++i) {
@ -266,10 +266,10 @@ void CheckOther::SuspiciousSemicolonError(const Token* tok)
void CheckOther::warningOldStylePointerCast() void CheckOther::warningOldStylePointerCast()
{ {
// Only valid on C++ code // Only valid on C++ code
if (!_settings->isEnabled(Settings::STYLE) || !_tokenizer->isCPP()) if (!mSettings->isEnabled(Settings::STYLE) || !mTokenizer->isCPP())
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) { for (const Scope * scope : symbolDatabase->functionScopes) {
const Token* tok; const Token* tok;
if (scope->function && scope->function->isConstructor()) if (scope->function && scope->function->isConstructor())
@ -316,11 +316,11 @@ void CheckOther::cstyleCastError(const Token *tok)
void CheckOther::invalidPointerCast() void CheckOther::invalidPointerCast()
{ {
if (!_settings->isEnabled(Settings::PORTABILITY)) if (!mSettings->isEnabled(Settings::PORTABILITY))
return; return;
const bool printInconclusive = _settings->inconclusive; const bool printInconclusive = mSettings->inconclusive;
const SymbolDatabase* const symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) { for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
const Token* toTok = nullptr; const Token* toTok = nullptr;
@ -377,10 +377,10 @@ void CheckOther::invalidPointerCastError(const Token* tok, const std::string& fr
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
void CheckOther::checkPipeParameterSize() void CheckOther::checkPipeParameterSize()
{ {
if (!_settings->standards.posix) if (!mSettings->standards.posix)
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) { for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (Token::Match(tok, "pipe ( %var% )") || if (Token::Match(tok, "pipe ( %var% )") ||
@ -472,14 +472,14 @@ static bool checkExceptionHandling(const Token* tok)
void CheckOther::checkRedundantAssignment() void CheckOther::checkRedundantAssignment()
{ {
const bool printPerformance = _settings->isEnabled(Settings::PERFORMANCE); const bool printPerformance = mSettings->isEnabled(Settings::PERFORMANCE);
const bool printStyle = _settings->isEnabled(Settings::STYLE); const bool printStyle = mSettings->isEnabled(Settings::STYLE);
const bool printWarning = _settings->isEnabled(Settings::WARNING); const bool printWarning = mSettings->isEnabled(Settings::WARNING);
if (!printWarning && !printPerformance && !printStyle) if (!printWarning && !printPerformance && !printStyle)
return; return;
const bool printInconclusive = _settings->inconclusive; const bool printInconclusive = mSettings->inconclusive;
const SymbolDatabase* symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase();
for (std::list<Scope>::const_iterator scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) { for (std::list<Scope>::const_iterator scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) {
if (!scope->isExecutable()) if (!scope->isExecutable())
@ -577,7 +577,7 @@ void CheckOther::checkRedundantAssignment()
} }
// Ensure that LHS in assignments are the same // Ensure that LHS in assignments are the same
bool error = oldeq && eq->astOperand1() && isSameExpression(_tokenizer->isCPP(), true, eq->astOperand1(), oldeq->astOperand1(), _settings->library, true); bool error = oldeq && eq->astOperand1() && isSameExpression(mTokenizer->isCPP(), true, eq->astOperand1(), oldeq->astOperand1(), mSettings->library, true);
// Ensure that variable is not used on right side // Ensure that variable is not used on right side
std::stack<const Token *> tokens; std::stack<const Token *> tokens;
@ -608,7 +608,7 @@ void CheckOther::checkRedundantAssignment()
redundantAssignmentInSwitchError(it->second, tok, eq->astOperand1()->expressionString()); redundantAssignmentInSwitchError(it->second, tok, eq->astOperand1()->expressionString());
else if (printStyle) { else if (printStyle) {
// c++, unknown type => assignment might have additional side effects // c++, unknown type => assignment might have additional side effects
const bool possibleSideEffects(_tokenizer->isCPP() && !tok->valueType()); const bool possibleSideEffects(mTokenizer->isCPP() && !tok->valueType());
// TODO nonlocal variables are not tracked entirely. // TODO nonlocal variables are not tracked entirely.
const bool nonlocal = it->second->variable() && nonLocalVolatile(it->second->variable()); const bool nonlocal = it->second->variable() && nonLocalVolatile(it->second->variable());
@ -618,7 +618,7 @@ void CheckOther::checkRedundantAssignment()
const bool inconclusive = possibleSideEffects | nonlocal; const bool inconclusive = possibleSideEffects | nonlocal;
if (printInconclusive || !inconclusive) if (printInconclusive || !inconclusive)
if (_tokenizer->isC() || checkExceptionHandling(tok)) // see #6555 to see how exception handling might have an impact if (mTokenizer->isC() || checkExceptionHandling(tok)) // see #6555 to see how exception handling might have an impact
redundantAssignmentError(it->second, tok, eq->astOperand1()->expressionString(), inconclusive); redundantAssignmentError(it->second, tok, eq->astOperand1()->expressionString(), inconclusive);
} }
} }
@ -638,7 +638,7 @@ void CheckOther::checkRedundantAssignment()
if (!writtenArgumentsEnd) // Indicates that we are in the first argument of strcpy/memcpy/... function if (!writtenArgumentsEnd) // Indicates that we are in the first argument of strcpy/memcpy/... function
memAssignments.erase(tok->varId()); memAssignments.erase(tok->varId());
} }
} else if (Token::Match(tok, "%name% (") && !_settings->library.isFunctionConst(tok->str(), true)) { // Function call. Global variables might be used. Reset their status } else if (Token::Match(tok, "%name% (") && !mSettings->library.isFunctionConst(tok->str(), true)) { // Function call. Global variables might be used. Reset their status
const bool memfunc = Token::Match(tok, "memcpy|memmove|memset|strcpy|strncpy|sprintf|snprintf|strcat|strncat|wcscpy|wcsncpy|swprintf|wcscat|wcsncat"); const bool memfunc = Token::Match(tok, "memcpy|memmove|memset|strcpy|strncpy|sprintf|snprintf|strcat|strncat|wcscpy|wcsncpy|swprintf|wcscat|wcsncat");
if (tok->varId()) // operator() or function pointer if (tok->varId()) // operator() or function pointer
varAssignments.erase(tok->varId()); varAssignments.erase(tok->varId());
@ -683,7 +683,7 @@ void CheckOther::checkRedundantAssignment()
} }
const Token* funcEnd = func->functionScope->bodyEnd; const Token* funcEnd = func->functionScope->bodyEnd;
bool noreturn; bool noreturn;
if (!_tokenizer->IsScopeNoReturn(funcEnd, &noreturn) && !noreturn) { if (!mTokenizer->IsScopeNoReturn(funcEnd, &noreturn) && !noreturn) {
eraseNotLocalArg(varAssignments, symbolDatabase); eraseNotLocalArg(varAssignments, symbolDatabase);
eraseNotLocalArg(memAssignments, symbolDatabase); eraseNotLocalArg(memAssignments, symbolDatabase);
} else { } else {
@ -757,10 +757,10 @@ static inline bool isFunctionOrBreakPattern(const Token *tok)
void CheckOther::checkRedundantAssignmentInSwitch() void CheckOther::checkRedundantAssignmentInSwitch()
{ {
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
// Find the beginning of a switch. E.g.: // Find the beginning of a switch. E.g.:
// switch (var) { ... // switch (var) { ...
@ -884,10 +884,10 @@ void CheckOther::redundantBitwiseOperationInSwitchError(const Token *tok, const
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
void CheckOther::checkSuspiciousCaseInSwitch() void CheckOther::checkSuspiciousCaseInSwitch()
{ {
if (!_settings->inconclusive || !_settings->isEnabled(Settings::WARNING)) if (!mSettings->inconclusive || !mSettings->isEnabled(Settings::WARNING))
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope & scope : symbolDatabase->scopeList) { for (const Scope & scope : symbolDatabase->scopeList) {
if (scope.type != Scope::eSwitch) if (scope.type != Scope::eSwitch)
@ -927,10 +927,10 @@ void CheckOther::suspiciousCaseInSwitchError(const Token* tok, const std::string
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
void CheckOther::checkSuspiciousEqualityComparison() void CheckOther::checkSuspiciousEqualityComparison()
{ {
if (!_settings->isEnabled(Settings::WARNING) || !_settings->inconclusive) if (!mSettings->isEnabled(Settings::WARNING) || !mSettings->inconclusive)
return; return;
const SymbolDatabase* symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) { for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) { for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
if (Token::simpleMatch(tok, "for (")) { if (Token::simpleMatch(tok, "for (")) {
@ -980,10 +980,10 @@ void CheckOther::suspiciousEqualityComparisonError(const Token* tok)
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
void CheckOther::checkUnreachableCode() void CheckOther::checkUnreachableCode()
{ {
if (!_settings->isEnabled(Settings::STYLE)) if (!mSettings->isEnabled(Settings::STYLE))
return; return;
const bool printInconclusive = _settings->inconclusive; const bool printInconclusive = mSettings->inconclusive;
const SymbolDatabase* symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) { for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart; tok && tok != scope->bodyEnd; tok = tok->next()) { for (const Token* tok = scope->bodyStart; tok && tok != scope->bodyEnd; tok = tok->next()) {
const Token* secondBreak = nullptr; const Token* secondBreak = nullptr;
@ -1005,7 +1005,7 @@ void CheckOther::checkUnreachableCode()
} else if (Token::Match(tok, "goto %any% ;")) { } else if (Token::Match(tok, "goto %any% ;")) {
secondBreak = tok->tokAt(3); secondBreak = tok->tokAt(3);
labelName = tok->next(); labelName = tok->next();
} else if (Token::Match(tok, "%name% (") && _settings->library.isnoreturn(tok) && !Token::Match(tok->next()->astParent(), "?|:")) { } else if (Token::Match(tok, "%name% (") && mSettings->library.isnoreturn(tok) && !Token::Match(tok->next()->astParent(), "?|:")) {
if ((!tok->function() || (tok->function()->token != tok && tok->function()->tokenDef != tok)) && tok->linkAt(1)->strAt(1) != "{") if ((!tok->function() || (tok->function()->token != tok && tok->function()->tokenDef != tok)) && tok->linkAt(1)->strAt(1) != "{")
secondBreak = tok->linkAt(1)->tokAt(2); secondBreak = tok->linkAt(1)->tokAt(2);
} }
@ -1091,10 +1091,10 @@ void CheckOther::unreachableCodeError(const Token *tok, bool inconclusive)
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
void CheckOther::checkVariableScope() void CheckOther::checkVariableScope()
{ {
if (!_settings->isEnabled(Settings::STYLE)) if (!mSettings->isEnabled(Settings::STYLE))
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Variable* var : symbolDatabase->variableList()) { for (const Variable* var : symbolDatabase->variableList()) {
if (!var || !var->isLocal() || (!var->isPointer() && !var->typeStartToken()->isStandardType())) if (!var || !var->isLocal() || (!var->isPointer() && !var->typeStartToken()->isStandardType()))
@ -1276,13 +1276,13 @@ void CheckOther::variableScopeError(const Token *tok, const std::string &varname
void CheckOther::checkCommaSeparatedReturn() void CheckOther::checkCommaSeparatedReturn()
{ {
// This is experimental for now. See #5076 // This is experimental for now. See #5076
if (!_settings->experimental) if (!mSettings->experimental)
return; return;
if (!_settings->isEnabled(Settings::STYLE)) if (!mSettings->isEnabled(Settings::STYLE))
return; return;
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (tok->str() == "return") { if (tok->str() == "return") {
tok = tok->next(); tok = tok->next();
while (tok && tok->str() != ";") { while (tok && tok->str() != ";") {
@ -1410,10 +1410,10 @@ static bool canBeConst(const Variable *var)
void CheckOther::checkPassByReference() void CheckOther::checkPassByReference()
{ {
if (!_settings->isEnabled(Settings::PERFORMANCE) || _tokenizer->isC()) if (!mSettings->isEnabled(Settings::PERFORMANCE) || mTokenizer->isC())
return; return;
const SymbolDatabase * const symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase * const symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Variable* var : symbolDatabase->variableList()) { for (const Variable* var : symbolDatabase->variableList()) {
if (!var || !var->isArgument() || !var->isClass() || var->isPointer() || var->isArray() || var->isReference() || var->isEnumType()) if (!var || !var->isArgument() || !var->isClass() || var->isPointer() || var->isArray() || var->isReference() || var->isEnumType())
@ -1433,12 +1433,12 @@ void CheckOther::checkPassByReference()
// Ensure that it is a large object. // Ensure that it is a large object.
if (!var->type()->classScope) if (!var->type()->classScope)
inconclusive = true; inconclusive = true;
else if (estimateSize(var->type(), _settings, symbolDatabase) <= 2 * _settings->sizeof_pointer) else if (estimateSize(var->type(), mSettings, symbolDatabase) <= 2 * mSettings->sizeof_pointer)
continue; continue;
} else } else
continue; continue;
if (inconclusive && !_settings->inconclusive) if (inconclusive && !mSettings->inconclusive)
continue; continue;
const bool isConst = var->isConst(); const bool isConst = var->isConst();
@ -1472,12 +1472,12 @@ void CheckOther::passedByValueError(const Token *tok, const std::string &parname
void CheckOther::checkCharVariable() void CheckOther::checkCharVariable()
{ {
const bool warning = _settings->isEnabled(Settings::WARNING); const bool warning = mSettings->isEnabled(Settings::WARNING);
const bool portability = _settings->isEnabled(Settings::PORTABILITY); const bool portability = mSettings->isEnabled(Settings::PORTABILITY);
if (!warning && !portability) if (!warning && !portability)
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) { for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) { for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
if (Token::Match(tok, "%var% [")) { if (Token::Match(tok, "%var% [")) {
@ -1486,24 +1486,24 @@ void CheckOther::checkCharVariable()
if (!tok->variable()->isArray() && !tok->variable()->isPointer()) if (!tok->variable()->isArray() && !tok->variable()->isPointer())
continue; continue;
const Token *index = tok->next()->astOperand2(); const Token *index = tok->next()->astOperand2();
if (warning && tok->variable()->isArray() && astIsSignedChar(index) && index->getValueGE(0x80, _settings)) if (warning && tok->variable()->isArray() && astIsSignedChar(index) && index->getValueGE(0x80, mSettings))
signedCharArrayIndexError(tok); signedCharArrayIndexError(tok);
if (portability && astIsUnknownSignChar(index) && index->getValueGE(0x80, _settings)) if (portability && astIsUnknownSignChar(index) && index->getValueGE(0x80, mSettings))
unknownSignCharArrayIndexError(tok); unknownSignCharArrayIndexError(tok);
} else if (warning && Token::Match(tok, "[&|^]") && tok->astOperand2() && tok->astOperand1()) { } else if (warning && Token::Match(tok, "[&|^]") && tok->astOperand2() && tok->astOperand1()) {
bool warn = false; bool warn = false;
if (astIsSignedChar(tok->astOperand1())) { if (astIsSignedChar(tok->astOperand1())) {
const ValueFlow::Value *v1 = tok->astOperand1()->getValueLE(-1, _settings); const ValueFlow::Value *v1 = tok->astOperand1()->getValueLE(-1, mSettings);
const ValueFlow::Value *v2 = tok->astOperand2()->getMaxValue(false); const ValueFlow::Value *v2 = tok->astOperand2()->getMaxValue(false);
if (!v1) if (!v1)
v1 = tok->astOperand1()->getValueGE(0x80, _settings); v1 = tok->astOperand1()->getValueGE(0x80, mSettings);
if (v1 && !(tok->str() == "&" && v2 && v2->isKnown() && v2->intvalue >= 0 && v2->intvalue < 0x100)) if (v1 && !(tok->str() == "&" && v2 && v2->isKnown() && v2->intvalue >= 0 && v2->intvalue < 0x100))
warn = true; warn = true;
} else if (astIsSignedChar(tok->astOperand2())) { } else if (astIsSignedChar(tok->astOperand2())) {
const ValueFlow::Value *v1 = tok->astOperand2()->getValueLE(-1, _settings); const ValueFlow::Value *v1 = tok->astOperand2()->getValueLE(-1, mSettings);
const ValueFlow::Value *v2 = tok->astOperand1()->getMaxValue(false); const ValueFlow::Value *v2 = tok->astOperand1()->getMaxValue(false);
if (!v1) if (!v1)
v1 = tok->astOperand2()->getValueGE(0x80, _settings); v1 = tok->astOperand2()->getValueGE(0x80, mSettings);
if (v1 && !(tok->str() == "&" && v2 && v2->isKnown() && v2->intvalue >= 0 && v2->intvalue < 0x100)) if (v1 && !(tok->str() == "&" && v2 && v2->isKnown() && v2->intvalue >= 0 && v2->intvalue < 0x100))
warn = true; warn = true;
} }
@ -1559,10 +1559,10 @@ void CheckOther::charBitOpError(const Token *tok)
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
void CheckOther::checkIncompleteStatement() void CheckOther::checkIncompleteStatement()
{ {
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (Token::Match(tok, "(|[")) if (Token::Match(tok, "(|["))
tok = tok->link(); tok = tok->link();
@ -1623,7 +1623,7 @@ void CheckOther::constStatementError(const Token *tok, const std::string &type)
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
void CheckOther::checkZeroDivision() void CheckOther::checkZeroDivision()
{ {
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (!tok->astOperand2() || !tok->astOperand1()) if (!tok->astOperand2() || !tok->astOperand1())
continue; continue;
if (tok->str() != "%" && tok->str() != "/" && tok->str() != "%=" && tok->str() != "/=") if (tok->str() != "%" && tok->str() != "/" && tok->str() != "%=" && tok->str() != "/=")
@ -1641,7 +1641,7 @@ void CheckOther::checkZeroDivision()
// Value flow.. // Value flow..
const ValueFlow::Value *value = tok->astOperand2()->getValue(0LL); const ValueFlow::Value *value = tok->astOperand2()->getValue(0LL);
if (value && _settings->isEnabled(value, false)) if (value && mSettings->isEnabled(value, false))
zerodivError(tok, value); zerodivError(tok, value);
} }
} }
@ -1677,7 +1677,7 @@ void CheckOther::zerodivError(const Token *tok, const ValueFlow::Value *value)
void CheckOther::checkNanInArithmeticExpression() void CheckOther::checkNanInArithmeticExpression()
{ {
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (Token::Match(tok, "inf.0 +|-") || if (Token::Match(tok, "inf.0 +|-") ||
Token::Match(tok, "+|- inf.0") || Token::Match(tok, "+|- inf.0") ||
Token::Match(tok, "+|- %num% / 0.0")) { Token::Match(tok, "+|- %num% / 0.0")) {
@ -1700,13 +1700,13 @@ void CheckOther::nanInArithmeticExpressionError(const Token *tok)
void CheckOther::checkMisusedScopedObject() void CheckOther::checkMisusedScopedObject()
{ {
// Skip this check for .c files // Skip this check for .c files
if (_tokenizer->isC()) if (mTokenizer->isC())
return; return;
if (!_settings->isEnabled(Settings::STYLE)) if (!mSettings->isEnabled(Settings::STYLE))
return; return;
const SymbolDatabase * const symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase * const symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) { for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token *tok = scope->bodyStart; tok && tok != scope->bodyEnd; tok = tok->next()) { for (const Token *tok = scope->bodyStart; tok && tok != scope->bodyEnd; tok = tok->next()) {
if ((tok->next()->type() || (tok->next()->function() && tok->next()->function()->isConstructor())) // TODO: The rhs of || should be removed; It is a workaround for a symboldatabase bug if ((tok->next()->type() || (tok->next()->function() && tok->next()->function()->isConstructor())) // TODO: The rhs of || should be removed; It is a workaround for a symboldatabase bug
@ -1744,10 +1744,10 @@ void CheckOther::checkDuplicateBranch()
// and their conditional code is a duplicate of the condition that // and their conditional code is a duplicate of the condition that
// is always true just in case it would be false. See for instance // is always true just in case it would be false. See for instance
// abiword. // abiword.
if (!_settings->isEnabled(Settings::STYLE) || !_settings->inconclusive) if (!mSettings->isEnabled(Settings::STYLE) || !mSettings->inconclusive)
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope & scope : symbolDatabase->scopeList) { for (const Scope & scope : symbolDatabase->scopeList) {
if (scope.type != Scope::eIf) if (scope.type != Scope::eIf)
@ -1803,8 +1803,8 @@ void CheckOther::checkInvalidFree()
{ {
std::map<unsigned int, bool> allocatedVariables; std::map<unsigned int, bool> allocatedVariables;
const bool printInconclusive = _settings->inconclusive; const bool printInconclusive = mSettings->inconclusive;
const SymbolDatabase* symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) { for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
@ -1853,7 +1853,7 @@ void CheckOther::checkInvalidFree()
// If the previously-allocated variable is passed in to another function // If the previously-allocated variable is passed in to another function
// as a parameter, it might be modified, so we shouldn't report an error // as a parameter, it might be modified, so we shouldn't report an error
// if it is later used to free memory // if it is later used to free memory
else if (Token::Match(tok, "%name% (") && !_settings->library.isFunctionConst(tok->str(), true)) { else if (Token::Match(tok, "%name% (") && !mSettings->library.isFunctionConst(tok->str(), true)) {
const Token* tok2 = Token::findmatch(tok->next(), "%var%", tok->linkAt(1)); const Token* tok2 = Token::findmatch(tok->next(), "%var%", tok->linkAt(1));
while (tok2 != nullptr) { while (tok2 != nullptr) {
allocatedVariables.erase(tok2->varId()); allocatedVariables.erase(tok2->varId());
@ -1906,13 +1906,13 @@ namespace {
void CheckOther::checkDuplicateExpression() void CheckOther::checkDuplicateExpression()
{ {
const bool styleEnabled=_settings->isEnabled(Settings::STYLE); const bool styleEnabled=mSettings->isEnabled(Settings::STYLE);
const bool warningEnabled=_settings->isEnabled(Settings::WARNING); const bool warningEnabled=mSettings->isEnabled(Settings::WARNING);
if (!styleEnabled && !warningEnabled) if (!styleEnabled && !warningEnabled)
return; return;
// Parse all executing scopes.. // Parse all executing scopes..
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
std::list<const Function*> constFunctions; std::list<const Function*> constFunctions;
getConstFunctions(symbolDatabase, constFunctions); getConstFunctions(symbolDatabase, constFunctions);
@ -1946,8 +1946,8 @@ void CheckOther::checkDuplicateExpression()
) && ) &&
tok->next()->tokType() != Token::eType && tok->next()->tokType() != Token::eType &&
tok->next()->tokType() != Token::eName && tok->next()->tokType() != Token::eName &&
isSameExpression(_tokenizer->isCPP(), true, tok->next(), nextAssign->next(), _settings->library, true) && isSameExpression(mTokenizer->isCPP(), true, tok->next(), nextAssign->next(), mSettings->library, true) &&
isSameExpression(_tokenizer->isCPP(), true, tok->astOperand2(), nextAssign->astOperand2(), _settings->library, true) && isSameExpression(mTokenizer->isCPP(), true, tok->astOperand2(), nextAssign->astOperand2(), mSettings->library, true) &&
!isUniqueExpression(tok->astOperand2())) { !isUniqueExpression(tok->astOperand2())) {
bool assigned = false; bool assigned = false;
const Scope * varScope = var1->scope() ? var1->scope() : &*scope; const Scope * varScope = var1->scope() ? var1->scope() : &*scope;
@ -1967,13 +1967,13 @@ void CheckOther::checkDuplicateExpression()
if (tok->isOp() && tok->astOperand1() && !Token::Match(tok, "+|*|<<|>>|+=|*=|<<=|>>=")) { if (tok->isOp() && tok->astOperand1() && !Token::Match(tok, "+|*|<<|>>|+=|*=|<<=|>>=")) {
if (Token::Match(tok, "==|!=|-") && astIsFloat(tok->astOperand1(), true)) if (Token::Match(tok, "==|!=|-") && astIsFloat(tok->astOperand1(), true))
continue; continue;
if (isSameExpression(_tokenizer->isCPP(), true, tok->astOperand1(), tok->astOperand2(), _settings->library, true)) { if (isSameExpression(mTokenizer->isCPP(), true, tok->astOperand1(), tok->astOperand2(), mSettings->library, true)) {
if (isWithoutSideEffects(_tokenizer->isCPP(), tok->astOperand1())) { if (isWithoutSideEffects(mTokenizer->isCPP(), tok->astOperand1())) {
const bool assignment = tok->str() == "="; const bool assignment = tok->str() == "=";
if (assignment && warningEnabled) if (assignment && warningEnabled)
selfAssignmentError(tok, tok->astOperand1()->expressionString()); selfAssignmentError(tok, tok->astOperand1()->expressionString());
else if (styleEnabled) { else if (styleEnabled) {
if (_tokenizer->isCPP() && _settings->standards.cpp==Standards::CPP11 && tok->str() == "==") { if (mTokenizer->isCPP() && mSettings->standards.cpp==Standards::CPP11 && tok->str() == "==") {
const Token* parent = tok->astParent(); const Token* parent = tok->astParent();
while (parent && parent->astParent()) { while (parent && parent->astParent()) {
parent = parent->astParent(); parent = parent->astParent();
@ -1986,23 +1986,23 @@ void CheckOther::checkDuplicateExpression()
} }
} }
} else if (styleEnabled && } else if (styleEnabled &&
isOppositeExpression(_tokenizer->isCPP(), tok->astOperand1(), tok->astOperand2(), _settings->library, false) && isOppositeExpression(mTokenizer->isCPP(), tok->astOperand1(), tok->astOperand2(), mSettings->library, false) &&
!Token::Match(tok, "=|-|-=|/|/=") && !Token::Match(tok, "=|-|-=|/|/=") &&
isWithoutSideEffects(_tokenizer->isCPP(), tok->astOperand1())) { isWithoutSideEffects(mTokenizer->isCPP(), tok->astOperand1())) {
oppositeExpressionError(tok, tok, tok->str()); oppositeExpressionError(tok, tok, tok->str());
} else if (!Token::Match(tok, "[-/%]")) { // These operators are not associative } else if (!Token::Match(tok, "[-/%]")) { // These operators are not associative
if (styleEnabled && tok->astOperand2() && tok->str() == tok->astOperand1()->str() && isSameExpression(_tokenizer->isCPP(), true, tok->astOperand2(), tok->astOperand1()->astOperand2(), _settings->library, true) && isWithoutSideEffects(_tokenizer->isCPP(), tok->astOperand2())) if (styleEnabled && tok->astOperand2() && tok->str() == tok->astOperand1()->str() && isSameExpression(mTokenizer->isCPP(), true, tok->astOperand2(), tok->astOperand1()->astOperand2(), mSettings->library, true) && isWithoutSideEffects(mTokenizer->isCPP(), tok->astOperand2()))
duplicateExpressionError(tok->astOperand2(), tok->astOperand2(), tok->str()); duplicateExpressionError(tok->astOperand2(), tok->astOperand2(), tok->str());
else if (tok->astOperand2()) { else if (tok->astOperand2()) {
const Token *ast1 = tok->astOperand1(); const Token *ast1 = tok->astOperand1();
while (ast1 && tok->str() == ast1->str()) { while (ast1 && tok->str() == ast1->str()) {
if (isSameExpression(_tokenizer->isCPP(), true, ast1->astOperand1(), tok->astOperand2(), _settings->library, true) && isWithoutSideEffects(_tokenizer->isCPP(), ast1->astOperand1())) if (isSameExpression(mTokenizer->isCPP(), true, ast1->astOperand1(), tok->astOperand2(), mSettings->library, true) && isWithoutSideEffects(mTokenizer->isCPP(), ast1->astOperand1()))
// TODO: warn if variables are unchanged. See #5683 // TODO: warn if variables are unchanged. See #5683
// Probably the message should be changed to 'duplicate expressions X in condition or something like that'. // Probably the message should be changed to 'duplicate expressions X in condition or something like that'.
;//duplicateExpressionError(ast1->astOperand1(), tok->astOperand2(), tok->str()); ;//duplicateExpressionError(ast1->astOperand1(), tok->astOperand2(), tok->str());
else if (styleEnabled && isSameExpression(_tokenizer->isCPP(), true, ast1->astOperand2(), tok->astOperand2(), _settings->library, true) && isWithoutSideEffects(_tokenizer->isCPP(), ast1->astOperand2())) else if (styleEnabled && isSameExpression(mTokenizer->isCPP(), true, ast1->astOperand2(), tok->astOperand2(), mSettings->library, true) && isWithoutSideEffects(mTokenizer->isCPP(), ast1->astOperand2()))
duplicateExpressionError(ast1->astOperand2(), tok->astOperand2(), tok->str()); duplicateExpressionError(ast1->astOperand2(), tok->astOperand2(), tok->str());
if (!isConstExpression(ast1->astOperand2(), _settings->library, true)) if (!isConstExpression(ast1->astOperand2(), mSettings->library, true))
break; break;
ast1 = ast1->astOperand1(); ast1 = ast1->astOperand1();
} }
@ -2011,7 +2011,7 @@ void CheckOther::checkDuplicateExpression()
} else if (styleEnabled && tok->astOperand1() && tok->astOperand2() && tok->str() == ":" && tok->astParent() && tok->astParent()->str() == "?") { } else if (styleEnabled && tok->astOperand1() && tok->astOperand2() && tok->str() == ":" && tok->astParent() && tok->astParent()->str() == "?") {
if (!tok->astOperand1()->values().empty() && !tok->astOperand2()->values().empty() && isEqualKnownValue(tok->astOperand1(), tok->astOperand2())) if (!tok->astOperand1()->values().empty() && !tok->astOperand2()->values().empty() && isEqualKnownValue(tok->astOperand1(), tok->astOperand2()))
duplicateValueTernaryError(tok); duplicateValueTernaryError(tok);
else if (isSameExpression(_tokenizer->isCPP(), true, tok->astOperand1(), tok->astOperand2(), _settings->library, false)) else if (isSameExpression(mTokenizer->isCPP(), true, tok->astOperand1(), tok->astOperand2(), mSettings->library, false))
duplicateExpressionTernaryError(tok); duplicateExpressionTernaryError(tok);
} }
} }
@ -2082,10 +2082,10 @@ void CheckOther::selfAssignmentError(const Token *tok, const std::string &varnam
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
void CheckOther::checkComparisonFunctionIsAlwaysTrueOrFalse() void CheckOther::checkComparisonFunctionIsAlwaysTrueOrFalse()
{ {
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) { for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (tok->isName() && Token::Match(tok, "isgreater|isless|islessgreater|isgreaterequal|islessequal ( %var% , %var% )")) { if (tok->isName() && Token::Match(tok, "isgreater|isless|islessgreater|isgreaterequal|islessequal ( %var% , %var% )")) {
@ -2125,14 +2125,14 @@ void CheckOther::checkComparisonFunctionIsAlwaysTrueOrFalseError(const Token* to
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
void CheckOther::checkSignOfUnsignedVariable() void CheckOther::checkSignOfUnsignedVariable()
{ {
if (!_settings->isEnabled(Settings::STYLE)) if (!mSettings->isEnabled(Settings::STYLE))
return; return;
const bool inconclusive = _tokenizer->codeWithTemplates(); const bool inconclusive = mTokenizer->codeWithTemplates();
if (inconclusive && !_settings->inconclusive) if (inconclusive && !mSettings->inconclusive)
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) { for (const Scope * scope : symbolDatabase->functionScopes) {
// check all the code in the function // check all the code in the function
@ -2239,10 +2239,10 @@ static bool constructorTakesReference(const Scope * const classScope)
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
void CheckOther::checkRedundantCopy() void CheckOther::checkRedundantCopy()
{ {
if (!_settings->isEnabled(Settings::PERFORMANCE) || _tokenizer->isC() || !_settings->inconclusive) if (!mSettings->isEnabled(Settings::PERFORMANCE) || mTokenizer->isC() || !mSettings->inconclusive)
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Variable* var : symbolDatabase->variableList()) { for (const Variable* var : symbolDatabase->variableList()) {
if (!var || var->isReference() || !var->isConst() || var->isPointer() || (!var->type() && !var->isStlType())) // bailout if var is of standard type, if it is a pointer or non-const if (!var || var->isReference() || !var->isConst() || var->isPointer() || (!var->type() && !var->isStlType())) // bailout if var is of standard type, if it is a pointer or non-const
@ -2294,9 +2294,9 @@ static bool isNegative(const Token *tok, const Settings *settings)
void CheckOther::checkNegativeBitwiseShift() void CheckOther::checkNegativeBitwiseShift()
{ {
const bool portability = _settings->isEnabled(Settings::PORTABILITY); const bool portability = mSettings->isEnabled(Settings::PORTABILITY);
for (const Token* tok = _tokenizer->tokens(); tok; tok = tok->next()) { for (const Token* tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (!tok->astOperand1() || !tok->astOperand2()) if (!tok->astOperand1() || !tok->astOperand2())
continue; continue;
@ -2304,7 +2304,7 @@ void CheckOther::checkNegativeBitwiseShift()
continue; continue;
// don't warn if lhs is a class. this is an overloaded operator then // don't warn if lhs is a class. this is an overloaded operator then
if (_tokenizer->isCPP()) { if (mTokenizer->isCPP()) {
const ValueType * lhsType = tok->astOperand1()->valueType(); const ValueType * lhsType = tok->astOperand1()->valueType();
if (!lhsType || !lhsType->isIntegral()) if (!lhsType || !lhsType->isIntegral())
continue; continue;
@ -2322,9 +2322,9 @@ void CheckOther::checkNegativeBitwiseShift()
continue; continue;
// Get negative rhs value. preferably a value which doesn't have 'condition'. // Get negative rhs value. preferably a value which doesn't have 'condition'.
if (portability && isNegative(tok->astOperand1(), _settings)) if (portability && isNegative(tok->astOperand1(), mSettings))
negativeBitwiseShiftError(tok, 1); negativeBitwiseShiftError(tok, 1);
else if (isNegative(tok->astOperand2(), _settings)) else if (isNegative(tok->astOperand2(), mSettings))
negativeBitwiseShiftError(tok, 2); negativeBitwiseShiftError(tok, 2);
} }
} }
@ -2346,14 +2346,14 @@ void CheckOther::negativeBitwiseShiftError(const Token *tok, int op)
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
void CheckOther::checkIncompleteArrayFill() void CheckOther::checkIncompleteArrayFill()
{ {
if (!_settings->inconclusive) if (!mSettings->inconclusive)
return; return;
const bool printWarning = _settings->isEnabled(Settings::WARNING); const bool printWarning = mSettings->isEnabled(Settings::WARNING);
const bool printPortability = _settings->isEnabled(Settings::PORTABILITY); const bool printPortability = mSettings->isEnabled(Settings::PORTABILITY);
if (!printPortability && !printWarning) if (!printPortability && !printWarning)
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) { for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
@ -2363,9 +2363,9 @@ void CheckOther::checkIncompleteArrayFill()
continue; continue;
if (MathLib::toLongNumber(tok->linkAt(1)->strAt(-1)) == var->dimension(0)) { if (MathLib::toLongNumber(tok->linkAt(1)->strAt(-1)) == var->dimension(0)) {
unsigned int size = _tokenizer->sizeOfType(var->typeStartToken()); unsigned int size = mTokenizer->sizeOfType(var->typeStartToken());
if (size == 0 && var->typeStartToken()->next()->str() == "*") if (size == 0 && var->typeStartToken()->next()->str() == "*")
size = _settings->sizeof_pointer; size = mSettings->sizeof_pointer;
if ((size != 1 && size != 100 && size != 0) || var->isPointer()) { if ((size != 1 && size != 100 && size != 0) || var->isPointer()) {
if (printWarning) if (printWarning)
incompleteArrayFillError(tok, var->name(), tok->str(), false); incompleteArrayFillError(tok, var->name(), tok->str(), false);
@ -2399,10 +2399,10 @@ void CheckOther::incompleteArrayFillError(const Token* tok, const std::string& b
void CheckOther::checkVarFuncNullUB() void CheckOther::checkVarFuncNullUB()
{ {
if (!_settings->isEnabled(Settings::PORTABILITY)) if (!mSettings->isEnabled(Settings::PORTABILITY))
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) { for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) { for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
// Is NULL passed to a function? // Is NULL passed to a function?
@ -2482,11 +2482,11 @@ void CheckOther::varFuncNullUBError(const Token *tok)
void CheckOther::checkRedundantPointerOp() void CheckOther::checkRedundantPointerOp()
{ {
if (!_settings->isEnabled(Settings::STYLE)) if (!mSettings->isEnabled(Settings::STYLE))
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (tok->str() == "&") { if (tok->str() == "&") {
// bail out for logical AND operator // bail out for logical AND operator
if (tok->astOperand2()) if (tok->astOperand2())
@ -2520,11 +2520,11 @@ void CheckOther::redundantPointerOpError(const Token* tok, const std::string &va
void CheckOther::checkInterlockedDecrement() void CheckOther::checkInterlockedDecrement()
{ {
if (!_settings->isWindowsPlatform()) { if (!mSettings->isWindowsPlatform()) {
return; return;
} }
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (tok->isName() && Token::Match(tok, "InterlockedDecrement ( & %name% ) ; if ( %name%|!|0")) { if (tok->isName() && Token::Match(tok, "InterlockedDecrement ( & %name% ) ; if ( %name%|!|0")) {
const Token* interlockedVarTok = tok->tokAt(3); const Token* interlockedVarTok = tok->tokAt(3);
const Token* checkStartTok = interlockedVarTok->tokAt(5); const Token* checkStartTok = interlockedVarTok->tokAt(5);
@ -2564,10 +2564,10 @@ void CheckOther::raceAfterInterlockedDecrementError(const Token* tok)
void CheckOther::checkUnusedLabel() void CheckOther::checkUnusedLabel()
{ {
if (!_settings->isEnabled(Settings::STYLE) && !_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::STYLE) && !mSettings->isEnabled(Settings::WARNING))
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) { for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) { for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
if (!tok->scope()->isExecutable()) if (!tok->scope()->isExecutable())
@ -2584,12 +2584,12 @@ void CheckOther::checkUnusedLabel()
void CheckOther::unusedLabelError(const Token* tok, bool inSwitch) void CheckOther::unusedLabelError(const Token* tok, bool inSwitch)
{ {
if (inSwitch) { if (inSwitch) {
if (!tok || _settings->isEnabled(Settings::WARNING)) if (!tok || mSettings->isEnabled(Settings::WARNING))
reportError(tok, Severity::warning, "unusedLabelSwitch", reportError(tok, Severity::warning, "unusedLabelSwitch",
"$symbol:" + (tok ? tok->str() : emptyString) + "\n" "$symbol:" + (tok ? tok->str() : emptyString) + "\n"
"Label '$symbol' is not used. Should this be a 'case' of the enclosing switch()?", CWE398, false); "Label '$symbol' is not used. Should this be a 'case' of the enclosing switch()?", CWE398, false);
} else { } else {
if (!tok || _settings->isEnabled(Settings::STYLE)) if (!tok || mSettings->isEnabled(Settings::STYLE))
reportError(tok, Severity::style, "unusedLabel", reportError(tok, Severity::style, "unusedLabel",
"$symbol:" + (tok ? tok->str() : emptyString) + "\n" "$symbol:" + (tok ? tok->str() : emptyString) + "\n"
"Label '$symbol' is not used.", CWE398, false); "Label '$symbol' is not used.", CWE398, false);
@ -2600,10 +2600,10 @@ void CheckOther::unusedLabelError(const Token* tok, bool inSwitch)
void CheckOther::checkEvaluationOrder() void CheckOther::checkEvaluationOrder()
{ {
// This checker is not written according to C++11 sequencing rules // This checker is not written according to C++11 sequencing rules
if (_tokenizer->isCPP() && _settings->standards.cpp >= Standards::CPP11) if (mTokenizer->isCPP() && mSettings->standards.cpp >= Standards::CPP11)
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * functionScope : symbolDatabase->functionScopes) { for (const Scope * functionScope : symbolDatabase->functionScopes) {
for (const Token* tok = functionScope->bodyStart; tok != functionScope->bodyEnd; tok = tok->next()) { for (const Token* tok = functionScope->bodyStart; tok != functionScope->bodyEnd; tok = tok->next()) {
if (!Token::Match(tok, "++|--") && !tok->isAssignmentOp()) if (!Token::Match(tok, "++|--") && !tok->isAssignmentOp())
@ -2641,9 +2641,9 @@ void CheckOther::checkEvaluationOrder()
if (tok2 == tok && if (tok2 == tok &&
tok->str() == "=" && tok->str() == "=" &&
parent->str() == "=" && parent->str() == "=" &&
isSameExpression(_tokenizer->isCPP(), false, tok->astOperand1(), parent->astOperand1(), _settings->library, true)) { isSameExpression(mTokenizer->isCPP(), false, tok->astOperand1(), parent->astOperand1(), mSettings->library, true)) {
if (_settings->isEnabled(Settings::WARNING) && if (mSettings->isEnabled(Settings::WARNING) &&
isSameExpression(_tokenizer->isCPP(), true, tok->astOperand1(), parent->astOperand1(), _settings->library, true)) isSameExpression(mTokenizer->isCPP(), true, tok->astOperand1(), parent->astOperand1(), mSettings->library, true))
selfAssignmentError(parent, tok->astOperand1()->expressionString()); selfAssignmentError(parent, tok->astOperand1()->expressionString());
break; break;
} }
@ -2663,7 +2663,7 @@ void CheckOther::checkEvaluationOrder()
continue; // don't care about sizeof usage continue; // don't care about sizeof usage
tokens.push(tok3->astOperand1()); tokens.push(tok3->astOperand1());
tokens.push(tok3->astOperand2()); tokens.push(tok3->astOperand2());
if (isSameExpression(_tokenizer->isCPP(), false, tok->astOperand1(), tok3, _settings->library, true)) { if (isSameExpression(mTokenizer->isCPP(), false, tok->astOperand1(), tok3, mSettings->library, true)) {
foundError = true; foundError = true;
} }
} }
@ -2685,10 +2685,10 @@ void CheckOther::unknownEvaluationOrder(const Token* tok)
void CheckOther::checkAccessOfMovedVariable() void CheckOther::checkAccessOfMovedVariable()
{ {
if (!_tokenizer->isCPP() || _settings->standards.cpp < Standards::CPP11 || !_settings->isEnabled(Settings::WARNING)) if (!mTokenizer->isCPP() || mSettings->standards.cpp < Standards::CPP11 || !mSettings->isEnabled(Settings::WARNING))
return; return;
const bool reportInconclusive = _settings->inconclusive; const bool reportInconclusive = mSettings->inconclusive;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) { for (const Scope * scope : symbolDatabase->functionScopes) {
const Token * scopeStart = scope->bodyStart; const Token * scopeStart = scope->bodyStart;
if (scope->function) { if (scope->function) {
@ -2711,7 +2711,7 @@ void CheckOther::checkAccessOfMovedVariable()
else else
inconclusive = true; inconclusive = true;
} else { } else {
const bool isVariableChanged = isVariableChangedByFunctionCall(tok, _settings, &inconclusive); const bool isVariableChanged = isVariableChangedByFunctionCall(tok, mSettings, &inconclusive);
accessOfMoved = !isVariableChanged; accessOfMoved = !isVariableChanged;
if (inconclusive) { if (inconclusive) {
accessOfMoved = !isMovedParameterAllowedForInconclusiveFunction(tok); accessOfMoved = !isMovedParameterAllowedForInconclusiveFunction(tok);
@ -2769,14 +2769,14 @@ void CheckOther::accessMovedError(const Token *tok, const std::string &varname,
void CheckOther::checkFuncArgNamesDifferent() void CheckOther::checkFuncArgNamesDifferent()
{ {
const bool style = _settings->isEnabled(Settings::STYLE); const bool style = mSettings->isEnabled(Settings::STYLE);
const bool inconclusive = _settings->inconclusive; const bool inconclusive = mSettings->inconclusive;
const bool warning = _settings->isEnabled(Settings::WARNING); const bool warning = mSettings->isEnabled(Settings::WARNING);
if (!(warning || (style && inconclusive))) if (!(warning || (style && inconclusive)))
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
// check every function // check every function
for (std::size_t i = 0, end = symbolDatabase->functionScopes.size(); i < end; ++i) { for (std::size_t i = 0, end = symbolDatabase->functionScopes.size(); i < end; ++i) {
const Function * function = symbolDatabase->functionScopes[i]->function; const Function * function = symbolDatabase->functionScopes[i]->function;

View File

@ -45,10 +45,10 @@ static const struct CWE CWE398(398U); // Indicator of Poor Code Quality
void CheckPostfixOperator::postfixOperator() void CheckPostfixOperator::postfixOperator()
{ {
if (!_settings->isEnabled(Settings::PERFORMANCE)) if (!mSettings->isEnabled(Settings::PERFORMANCE))
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
const std::size_t functions = symbolDatabase->functionScopes.size(); const std::size_t functions = symbolDatabase->functionScopes.size();
for (std::size_t i = 0; i < functions; ++i) { for (std::size_t i = 0; i < functions; ++i) {

View File

@ -42,10 +42,10 @@ static const struct CWE CWE682(682U); // Incorrect Calculation
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
void CheckSizeof::checkSizeofForNumericParameter() void CheckSizeof::checkSizeofForNumericParameter()
{ {
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
const std::size_t functions = symbolDatabase->functionScopes.size(); const std::size_t functions = symbolDatabase->functionScopes.size();
for (std::size_t i = 0; i < functions; ++i) { for (std::size_t i = 0; i < functions; ++i) {
const Scope * scope = symbolDatabase->functionScopes[i]; const Scope * scope = symbolDatabase->functionScopes[i];
@ -72,9 +72,9 @@ void CheckSizeof::sizeofForNumericParameterError(const Token *tok)
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
void CheckSizeof::checkSizeofForArrayParameter() void CheckSizeof::checkSizeofForArrayParameter()
{ {
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
const std::size_t functions = symbolDatabase->functionScopes.size(); const std::size_t functions = symbolDatabase->functionScopes.size();
for (std::size_t i = 0; i < functions; ++i) { for (std::size_t i = 0; i < functions; ++i) {
const Scope * scope = symbolDatabase->functionScopes[i]; const Scope * scope = symbolDatabase->functionScopes[i];
@ -112,10 +112,10 @@ void CheckSizeof::sizeofForArrayParameterError(const Token *tok)
void CheckSizeof::checkSizeofForPointerSize() void CheckSizeof::checkSizeofForPointerSize()
{ {
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
const std::size_t functions = symbolDatabase->functionScopes.size(); const std::size_t functions = symbolDatabase->functionScopes.size();
for (std::size_t i = 0; i < functions; ++i) { for (std::size_t i = 0; i < functions; ++i) {
const Scope * scope = symbolDatabase->functionScopes[i]; const Scope * scope = symbolDatabase->functionScopes[i];
@ -262,10 +262,10 @@ void CheckSizeof::divideBySizeofError(const Token *tok, const std::string &memfu
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
void CheckSizeof::sizeofsizeof() void CheckSizeof::sizeofsizeof()
{ {
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (Token::Match(tok, "sizeof (| sizeof")) { if (Token::Match(tok, "sizeof (| sizeof")) {
sizeofsizeofError(tok); sizeofsizeofError(tok);
tok = tok->next(); tok = tok->next();
@ -286,12 +286,12 @@ void CheckSizeof::sizeofsizeofError(const Token *tok)
void CheckSizeof::sizeofCalculation() void CheckSizeof::sizeofCalculation()
{ {
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
const bool printInconclusive = _settings->inconclusive; const bool printInconclusive = mSettings->inconclusive;
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (!Token::simpleMatch(tok, "sizeof (")) if (!Token::simpleMatch(tok, "sizeof ("))
continue; continue;
@ -321,10 +321,10 @@ void CheckSizeof::sizeofCalculationError(const Token *tok, bool inconclusive)
void CheckSizeof::sizeofFunction() void CheckSizeof::sizeofFunction()
{ {
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (Token::simpleMatch(tok, "sizeof (")) { if (Token::simpleMatch(tok, "sizeof (")) {
// ignore if the `sizeof` result is cast to void inside a macro, i.e. the calculation is // ignore if the `sizeof` result is cast to void inside a macro, i.e. the calculation is
@ -362,11 +362,11 @@ void CheckSizeof::sizeofFunctionError(const Token *tok)
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
void CheckSizeof::suspiciousSizeofCalculation() void CheckSizeof::suspiciousSizeofCalculation()
{ {
if (!_settings->isEnabled(Settings::WARNING) || !_settings->inconclusive) if (!mSettings->isEnabled(Settings::WARNING) || !mSettings->inconclusive)
return; return;
// TODO: Use AST here. This should be possible as soon as sizeof without brackets is correctly parsed // TODO: Use AST here. This should be possible as soon as sizeof without brackets is correctly parsed
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (Token::simpleMatch(tok, "sizeof (")) { if (Token::simpleMatch(tok, "sizeof (")) {
const Token* const end = tok->linkAt(1); const Token* const end = tok->linkAt(1);
const Variable* var = end->previous()->variable(); const Variable* var = end->previous()->variable();
@ -395,10 +395,10 @@ void CheckSizeof::divideSizeofError(const Token *tok)
void CheckSizeof::sizeofVoid() void CheckSizeof::sizeofVoid()
{ {
if (!_settings->isEnabled(Settings::PORTABILITY)) if (!mSettings->isEnabled(Settings::PORTABILITY))
return; return;
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (Token::simpleMatch(tok, "sizeof ( )")) { // "sizeof(void)" gets simplified to sizeof ( ) if (Token::simpleMatch(tok, "sizeof ( )")) { // "sizeof(void)" gets simplified to sizeof ( )
sizeofVoidError(tok); sizeofVoidError(tok);
} else if (Token::simpleMatch(tok, "sizeof (") && tok->next()->astOperand2()) { } else if (Token::simpleMatch(tok, "sizeof (") && tok->next()->astOperand2()) {

View File

@ -128,7 +128,7 @@ static std::string getContainerName(const Token *containerToken)
void CheckStl::iterators() void CheckStl::iterators()
{ {
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Variable* var : symbolDatabase->variableList()) { for (const Variable* var : symbolDatabase->variableList()) {
bool inconclusiveType=false; bool inconclusiveType=false;
@ -344,7 +344,7 @@ static const Variable *getContainer(const Token *argtok)
void CheckStl::mismatchingContainers() void CheckStl::mismatchingContainers()
{ {
// Check if different containers are used in various calls of standard functions // Check if different containers are used in various calls of standard functions
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
const std::size_t functions = symbolDatabase->functionScopes.size(); const std::size_t functions = symbolDatabase->functionScopes.size();
for (std::size_t ii = 0; ii < functions; ++ii) { for (std::size_t ii = 0; ii < functions; ++ii) {
const Scope * scope = symbolDatabase->functionScopes[ii]; const Scope * scope = symbolDatabase->functionScopes[ii];
@ -357,7 +357,7 @@ void CheckStl::mismatchingContainers()
int argnr = 1; int argnr = 1;
std::map<const Variable *, unsigned int> containerNr; std::map<const Variable *, unsigned int> containerNr;
for (const Token *argTok = arg1; argTok; argTok = argTok->nextArgument()) { for (const Token *argTok = arg1; argTok; argTok = argTok->nextArgument()) {
const Library::ArgumentChecks::IteratorInfo *i = _settings->library.getArgIteratorInfo(ftok,argnr++); const Library::ArgumentChecks::IteratorInfo *i = mSettings->library.getArgIteratorInfo(ftok,argnr++);
if (!i) if (!i)
continue; continue;
const Variable *c = getContainer(argTok); const Variable *c = getContainer(argTok);
@ -376,7 +376,7 @@ void CheckStl::mismatchingContainers()
mismatchingContainersError(argTok); mismatchingContainersError(argTok);
} }
} }
const int ret = _settings->library.returnValueContainer(ftok); const int ret = mSettings->library.returnValueContainer(ftok);
if (ret != -1 && Token::Match(ftok->next()->astParent(), "==|!=")) { if (ret != -1 && Token::Match(ftok->next()->astParent(), "==|!=")) {
const Token *parent = ftok->next()->astParent(); const Token *parent = ftok->next()->astParent();
const Token *other = (parent->astOperand1() == ftok->next()) ? parent->astOperand2() : parent->astOperand1(); const Token *other = (parent->astOperand1() == ftok->next()) ? parent->astOperand2() : parent->astOperand1();
@ -401,7 +401,7 @@ void CheckStl::mismatchingContainers()
void CheckStl::stlOutOfBounds() void CheckStl::stlOutOfBounds()
{ {
const SymbolDatabase* const symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
// Scan through all scopes.. // Scan through all scopes..
for (std::list<Scope>::const_iterator i = symbolDatabase->scopeList.begin(); i != symbolDatabase->scopeList.end(); ++i) { for (std::list<Scope>::const_iterator i = symbolDatabase->scopeList.begin(); i != symbolDatabase->scopeList.end(); ++i) {
@ -429,7 +429,7 @@ void CheckStl::stlOutOfBounds()
if (!var) if (!var)
continue; continue;
const Library::Container* container = _settings->library.detectContainer(var->typeStartToken()); const Library::Container* container = mSettings->library.detectContainer(var->typeStartToken());
if (!container) if (!container)
continue; continue;
@ -471,7 +471,7 @@ void CheckStl::stlOutOfBoundsError(const Token *tok, const std::string &num, con
void CheckStl::negativeIndex() void CheckStl::negativeIndex()
{ {
// Negative index is out of bounds.. // Negative index is out of bounds..
const SymbolDatabase* const symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
const std::size_t functions = symbolDatabase->functionScopes.size(); const std::size_t functions = symbolDatabase->functionScopes.size();
for (std::size_t ii = 0; ii < functions; ++ii) { for (std::size_t ii = 0; ii < functions; ++ii) {
const Scope * scope = symbolDatabase->functionScopes[ii]; const Scope * scope = symbolDatabase->functionScopes[ii];
@ -481,10 +481,10 @@ void CheckStl::negativeIndex()
const Variable * const var = tok->variable(); const Variable * const var = tok->variable();
if (!var || tok == var->nameToken()) if (!var || tok == var->nameToken())
continue; continue;
const Library::Container * const container = _settings->library.detectContainer(var->typeStartToken()); const Library::Container * const container = mSettings->library.detectContainer(var->typeStartToken());
if (!container || !container->arrayLike_indexOp) if (!container || !container->arrayLike_indexOp)
continue; continue;
const ValueFlow::Value *index = tok->next()->astOperand2()->getValueLE(-1, _settings); const ValueFlow::Value *index = tok->next()->astOperand2()->getValueLE(-1, mSettings);
if (!index) if (!index)
continue; continue;
negativeIndexError(tok, *index); negativeIndexError(tok, *index);
@ -506,7 +506,7 @@ void CheckStl::negativeIndexError(const Token *tok, const ValueFlow::Value &inde
void CheckStl::erase() void CheckStl::erase()
{ {
const SymbolDatabase* const symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
for (std::list<Scope>::const_iterator i = symbolDatabase->scopeList.begin(); i != symbolDatabase->scopeList.end(); ++i) { for (std::list<Scope>::const_iterator i = symbolDatabase->scopeList.begin(); i != symbolDatabase->scopeList.end(); ++i) {
if (i->type == Scope::eFor && Token::simpleMatch(i->classDef, "for (")) { if (i->type == Scope::eFor && Token::simpleMatch(i->classDef, "for (")) {
@ -567,7 +567,7 @@ void CheckStl::eraseCheckLoopVar(const Scope &scope, const Variable *var)
void CheckStl::pushback() void CheckStl::pushback()
{ {
// Pointer can become invalid after push_back, push_front, reserve or resize.. // Pointer can become invalid after push_back, push_front, reserve or resize..
const SymbolDatabase* const symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
const std::size_t functions = symbolDatabase->functionScopes.size(); const std::size_t functions = symbolDatabase->functionScopes.size();
for (std::size_t i = 0; i < functions; ++i) { for (std::size_t i = 0; i < functions; ++i) {
const Scope * scope = symbolDatabase->functionScopes[i]; const Scope * scope = symbolDatabase->functionScopes[i];
@ -724,12 +724,12 @@ void CheckStl::invalidPointerError(const Token *tok, const std::string &func, co
void CheckStl::stlBoundaries() void CheckStl::stlBoundaries()
{ {
const SymbolDatabase* const symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Variable* var : symbolDatabase->variableList()) { for (const Variable* var : symbolDatabase->variableList()) {
if (!var || !var->scope() || !var->scope()->isExecutable()) if (!var || !var->scope() || !var->scope()->isExecutable())
continue; continue;
const Library::Container* container = _settings->library.detectContainer(var->typeStartToken(), true); const Library::Container* container = mSettings->library.detectContainer(var->typeStartToken(), true);
if (!container || container->opLessAllowed) if (!container || container->opLessAllowed)
continue; continue;
@ -771,12 +771,12 @@ static bool if_findCompare(const Token * const tokBack)
void CheckStl::if_find() void CheckStl::if_find()
{ {
const bool printWarning = _settings->isEnabled(Settings::WARNING); const bool printWarning = mSettings->isEnabled(Settings::WARNING);
const bool printPerformance = _settings->isEnabled(Settings::PERFORMANCE); const bool printPerformance = mSettings->isEnabled(Settings::PERFORMANCE);
if (!printWarning && !printPerformance) if (!printWarning && !printPerformance)
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (std::list<Scope>::const_iterator i = symbolDatabase->scopeList.begin(); i != symbolDatabase->scopeList.end(); ++i) { for (std::list<Scope>::const_iterator i = symbolDatabase->scopeList.begin(); i != symbolDatabase->scopeList.end(); ++i) {
if ((i->type != Scope::eIf && i->type != Scope::eWhile) || !i->classDef) if ((i->type != Scope::eIf && i->type != Scope::eWhile) || !i->classDef)
@ -790,7 +790,7 @@ void CheckStl::if_find()
tok = tok->linkAt(1); tok = tok->linkAt(1);
else if (tok->variable() && Token::Match(tok, "%var% . %name% (")) { else if (tok->variable() && Token::Match(tok, "%var% . %name% (")) {
container = _settings->library.detectContainer(tok->variable()->typeStartToken()); container = mSettings->library.detectContainer(tok->variable()->typeStartToken());
funcTok = tok->tokAt(2); funcTok = tok->tokAt(2);
} }
@ -804,16 +804,16 @@ void CheckStl::if_find()
funcTok = tok2->astParent()->next(); funcTok = tok2->astParent()->next();
if (tok->variable()->isArrayOrPointer()) if (tok->variable()->isArrayOrPointer())
container = _settings->library.detectContainer(tok->variable()->typeStartToken()); container = mSettings->library.detectContainer(tok->variable()->typeStartToken());
else { // Container of container - find the inner container else { // Container of container - find the inner container
container = _settings->library.detectContainer(tok->variable()->typeStartToken()); // outer container container = mSettings->library.detectContainer(tok->variable()->typeStartToken()); // outer container
tok2 = Token::findsimplematch(tok->variable()->typeStartToken(), "<", tok->variable()->typeEndToken()); tok2 = Token::findsimplematch(tok->variable()->typeStartToken(), "<", tok->variable()->typeEndToken());
if (container && container->type_templateArgNo >= 0 && tok2) { if (container && container->type_templateArgNo >= 0 && tok2) {
tok2 = tok2->next(); tok2 = tok2->next();
for (int j = 0; j < container->type_templateArgNo; j++) for (int j = 0; j < container->type_templateArgNo; j++)
tok2 = tok2->nextTemplateArgument(); tok2 = tok2->nextTemplateArgument();
container = _settings->library.detectContainer(tok2); // innner container container = mSettings->library.detectContainer(tok2); // innner container
} else } else
container = nullptr; container = nullptr;
} }
@ -865,13 +865,13 @@ static bool isCpp03ContainerSizeSlow(const Token *tok)
void CheckStl::size() void CheckStl::size()
{ {
if (!_settings->isEnabled(Settings::PERFORMANCE)) if (!mSettings->isEnabled(Settings::PERFORMANCE))
return; return;
if (_settings->standards.cpp == Standards::CPP11) if (mSettings->standards.cpp == Standards::CPP11)
return; return;
const SymbolDatabase* const symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
const std::size_t functions = symbolDatabase->functionScopes.size(); const std::size_t functions = symbolDatabase->functionScopes.size();
for (std::size_t i = 0; i < functions; ++i) { for (std::size_t i = 0; i < functions; ++i) {
const Scope * scope = symbolDatabase->functionScopes[i]; const Scope * scope = symbolDatabase->functionScopes[i];
@ -926,10 +926,10 @@ void CheckStl::sizeError(const Token *tok)
void CheckStl::redundantCondition() void CheckStl::redundantCondition()
{ {
if (!_settings->isEnabled(Settings::STYLE)) if (!mSettings->isEnabled(Settings::STYLE))
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (std::list<Scope>::const_iterator i = symbolDatabase->scopeList.begin(); i != symbolDatabase->scopeList.end(); ++i) { for (std::list<Scope>::const_iterator i = symbolDatabase->scopeList.begin(); i != symbolDatabase->scopeList.end(); ++i) {
if (i->type != Scope::eIf) if (i->type != Scope::eIf)
@ -965,10 +965,10 @@ void CheckStl::redundantIfRemoveError(const Token *tok)
void CheckStl::missingComparison() void CheckStl::missingComparison()
{ {
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
const SymbolDatabase* const symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
for (std::list<Scope>::const_iterator i = symbolDatabase->scopeList.begin(); i != symbolDatabase->scopeList.end(); ++i) { for (std::list<Scope>::const_iterator i = symbolDatabase->scopeList.begin(); i != symbolDatabase->scopeList.end(); ++i) {
if (i->type != Scope::eFor || !i->classDef) if (i->type != Scope::eFor || !i->classDef)
@ -1056,10 +1056,10 @@ namespace {
void CheckStl::string_c_str() void CheckStl::string_c_str()
{ {
const bool printInconclusive = _settings->inconclusive; const bool printInconclusive = mSettings->inconclusive;
const bool printPerformance = _settings->isEnabled(Settings::PERFORMANCE); const bool printPerformance = mSettings->isEnabled(Settings::PERFORMANCE);
const SymbolDatabase* symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase();
// Find all functions that take std::string as argument // Find all functions that take std::string as argument
std::multimap<std::string, unsigned int> c_strFuncParam; std::multimap<std::string, unsigned int> c_strFuncParam;
@ -1272,10 +1272,10 @@ void CheckStl::checkAutoPointer()
std::set<unsigned int> autoPtrVarId; std::set<unsigned int> autoPtrVarId;
std::map<unsigned int, const std::string> mallocVarId; // variables allocated by the malloc-like function std::map<unsigned int, const std::string> mallocVarId; // variables allocated by the malloc-like function
const char STL_CONTAINER_LIST[] = "array|bitset|deque|list|forward_list|map|multimap|multiset|priority_queue|queue|set|stack|vector|hash_map|hash_multimap|hash_set|unordered_map|unordered_multimap|unordered_set|unordered_multiset|basic_string"; const char STL_CONTAINER_LIST[] = "array|bitset|deque|list|forward_list|map|multimap|multiset|priority_queue|queue|set|stack|vector|hash_map|hash_multimap|hash_set|unordered_map|unordered_multimap|unordered_set|unordered_multiset|basic_string";
const int malloc = _settings->library.allocId("malloc"); // allocation function, which are not compatible with auto_ptr const int malloc = mSettings->library.allocId("malloc"); // allocation function, which are not compatible with auto_ptr
const bool printStyle = _settings->isEnabled(Settings::STYLE); const bool printStyle = mSettings->isEnabled(Settings::STYLE);
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (Token::simpleMatch(tok, "auto_ptr <")) { if (Token::simpleMatch(tok, "auto_ptr <")) {
if ((tok->strAt(-1) == "<" && Token::Match(tok->tokAt(-2), STL_CONTAINER_LIST)) || if ((tok->strAt(-1) == "<" && Token::Match(tok->tokAt(-2), STL_CONTAINER_LIST)) ||
(Token::simpleMatch(tok->tokAt(-3), "< std :: auto_ptr") && Token::Match(tok->tokAt(-4), STL_CONTAINER_LIST))) { (Token::simpleMatch(tok->tokAt(-3), "< std :: auto_ptr") && Token::Match(tok->tokAt(-4), STL_CONTAINER_LIST))) {
@ -1288,7 +1288,7 @@ void CheckStl::checkAutoPointer()
if (Token::Match(tok3, "( new %type%") && hasArrayEndParen(tok3)) { if (Token::Match(tok3, "( new %type%") && hasArrayEndParen(tok3)) {
autoPointerArrayError(tok2->next()); autoPointerArrayError(tok2->next());
} }
if (Token::Match(tok3, "( %name% (") && malloc && _settings->library.alloc(tok3->next(), -1) == malloc) { if (Token::Match(tok3, "( %name% (") && malloc && mSettings->library.alloc(tok3->next(), -1) == malloc) {
// malloc-like function allocated memory passed to the auto_ptr constructor -> error // malloc-like function allocated memory passed to the auto_ptr constructor -> error
autoPointerMallocError(tok2->next(), tok3->next()->str()); autoPointerMallocError(tok2->next(), tok3->next()->str());
} }
@ -1307,7 +1307,7 @@ void CheckStl::checkAutoPointer()
if (Token::simpleMatch(tok3->previous(), "[ ] )")) { if (Token::simpleMatch(tok3->previous(), "[ ] )")) {
autoPointerArrayError(tok2->next()); autoPointerArrayError(tok2->next());
} else if (tok3->varId()) { } else if (tok3->varId()) {
const Token *decltok = Token::findmatch(_tokenizer->tokens(), "%varid% = new %type%", tok3->varId()); const Token *decltok = Token::findmatch(mTokenizer->tokens(), "%varid% = new %type%", tok3->varId());
if (decltok && hasArrayEnd(decltok)) { if (decltok && hasArrayEnd(decltok)) {
autoPointerArrayError(tok2->next()); autoPointerArrayError(tok2->next());
} }
@ -1332,7 +1332,7 @@ void CheckStl::checkAutoPointer()
if (iter != autoPtrVarId.end()) { if (iter != autoPtrVarId.end()) {
autoPointerArrayError(tok); autoPointerArrayError(tok);
} }
} else if (Token::Match(tok, "%var% = %name% (") && malloc && _settings->library.alloc(tok->tokAt(2), -1) == malloc) { } else if (Token::Match(tok, "%var% = %name% (") && malloc && mSettings->library.alloc(tok->tokAt(2), -1) == malloc) {
// C library function like 'malloc' used together with auto pointer -> error // C library function like 'malloc' used together with auto pointer -> error
const std::set<unsigned int>::const_iterator iter = autoPtrVarId.find(tok->varId()); const std::set<unsigned int>::const_iterator iter = autoPtrVarId.find(tok->varId());
if (iter != autoPtrVarId.end()) { if (iter != autoPtrVarId.end()) {
@ -1341,7 +1341,7 @@ void CheckStl::checkAutoPointer()
// it is not an auto pointer variable and it is allocated by malloc like function. // it is not an auto pointer variable and it is allocated by malloc like function.
mallocVarId.insert(std::make_pair(tok->varId(), tok->strAt(2))); mallocVarId.insert(std::make_pair(tok->varId(), tok->strAt(2)));
} }
} else if (Token::Match(tok, "%var% . reset ( %name% (") && malloc && _settings->library.alloc(tok->tokAt(4), -1) == malloc) { } else if (Token::Match(tok, "%var% . reset ( %name% (") && malloc && mSettings->library.alloc(tok->tokAt(4), -1) == malloc) {
// C library function like 'malloc' used when resetting auto pointer -> error // C library function like 'malloc' used when resetting auto pointer -> error
const std::set<unsigned int>::const_iterator iter = autoPtrVarId.find(tok->varId()); const std::set<unsigned int>::const_iterator iter = autoPtrVarId.find(tok->varId());
if (iter != autoPtrVarId.end()) { if (iter != autoPtrVarId.end()) {
@ -1396,13 +1396,13 @@ namespace {
void CheckStl::uselessCalls() void CheckStl::uselessCalls()
{ {
const bool printPerformance = _settings->isEnabled(Settings::PERFORMANCE); const bool printPerformance = mSettings->isEnabled(Settings::PERFORMANCE);
const bool printWarning = _settings->isEnabled(Settings::WARNING); const bool printWarning = mSettings->isEnabled(Settings::WARNING);
if (!printPerformance && !printWarning) if (!printPerformance && !printWarning)
return; return;
const SymbolDatabase* symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase();
const std::size_t functions = symbolDatabase->functionScopes.size(); const std::size_t functions = symbolDatabase->functionScopes.size();
for (std::size_t i = 0; i < functions; ++i) { for (std::size_t i = 0; i < functions; ++i) {
const Scope * scope = symbolDatabase->functionScopes[i]; const Scope * scope = symbolDatabase->functionScopes[i];
@ -1487,12 +1487,12 @@ void CheckStl::uselessCallsRemoveError(const Token *tok, const std::string& func
// E.g. if (*i && i != str.end()) { } // E.g. if (*i && i != str.end()) { }
void CheckStl::checkDereferenceInvalidIterator() void CheckStl::checkDereferenceInvalidIterator()
{ {
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
// Iterate over "if", "while", and "for" conditions where there may // Iterate over "if", "while", and "for" conditions where there may
// be an iterator that is dereferenced before being checked for validity. // be an iterator that is dereferenced before being checked for validity.
const std::list<Scope>& scopeList = _tokenizer->getSymbolDatabase()->scopeList; const std::list<Scope>& scopeList = mTokenizer->getSymbolDatabase()->scopeList;
for (std::list<Scope>::const_iterator i = scopeList.begin(); i != scopeList.end(); ++i) { for (std::list<Scope>::const_iterator i = scopeList.begin(); i != scopeList.end(); ++i) {
if (!(i->type == Scope::eIf || i->type == Scope::eDo || i->type == Scope::eWhile || i->type == Scope::eFor)) if (!(i->type == Scope::eIf || i->type == Scope::eDo || i->type == Scope::eWhile || i->type == Scope::eFor))
continue; continue;
@ -1601,15 +1601,15 @@ void CheckStl::readingEmptyStlContainer_parseUsage(const Token* tok, const Libra
void CheckStl::readingEmptyStlContainer() void CheckStl::readingEmptyStlContainer()
{ {
if (!_settings->isEnabled(Settings::STYLE)) if (!mSettings->isEnabled(Settings::STYLE))
return; return;
if (!_settings->inconclusive) if (!mSettings->inconclusive)
return; return;
std::map<unsigned int, const Library::Container*> emptyContainer; std::map<unsigned int, const Library::Container*> emptyContainer;
const std::list<Scope>& scopeList = _tokenizer->getSymbolDatabase()->scopeList; const std::list<Scope>& scopeList = mTokenizer->getSymbolDatabase()->scopeList;
for (std::list<Scope>::const_iterator i = scopeList.begin(); i != scopeList.end(); ++i) { for (std::list<Scope>::const_iterator i = scopeList.begin(); i != scopeList.end(); ++i) {
if (i->type != Scope::eFunction) if (i->type != Scope::eFunction)
@ -1639,7 +1639,7 @@ void CheckStl::readingEmptyStlContainer()
// function call // function call
if (Token::Match(tok, "!!. %name% (") && !Token::simpleMatch(tok->linkAt(2), ") {")) { if (Token::Match(tok, "!!. %name% (") && !Token::simpleMatch(tok->linkAt(2), ") {")) {
for (std::map<unsigned int, const Library::Container*>::iterator it = emptyContainer.begin(); it != emptyContainer.end();) { for (std::map<unsigned int, const Library::Container*>::iterator it = emptyContainer.begin(); it != emptyContainer.end();) {
const Variable *var = _tokenizer->getSymbolDatabase()->getVariableFromVarId(it->first); const Variable *var = mTokenizer->getSymbolDatabase()->getVariableFromVarId(it->first);
if (var && (var->isLocal() || var->isArgument())) if (var && (var->isLocal() || var->isArgument()))
++it; ++it;
else else
@ -1661,7 +1661,7 @@ void CheckStl::readingEmptyStlContainer()
} }
if (insert) { if (insert) {
const Library::Container* container = _settings->library.detectContainer(var->typeStartToken()); const Library::Container* container = mSettings->library.detectContainer(var->typeStartToken());
if (container) if (container)
emptyContainer[var->declarationId()] = container; emptyContainer[var->declarationId()] = container;
continue; continue;

View File

@ -55,7 +55,7 @@ static const struct CWE CWE758(758U); // Reliance on Undefined, Unspecified, o
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
void CheckString::stringLiteralWrite() void CheckString::stringLiteralWrite()
{ {
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
const std::size_t functions = symbolDatabase->functionScopes.size(); const std::size_t functions = symbolDatabase->functionScopes.size();
for (std::size_t i = 0; i < functions; ++i) { for (std::size_t i = 0; i < functions; ++i) {
const Scope * scope = symbolDatabase->functionScopes[i]; const Scope * scope = symbolDatabase->functionScopes[i];
@ -98,10 +98,10 @@ void CheckString::stringLiteralWriteError(const Token *tok, const Token *strValu
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
void CheckString::checkAlwaysTrueOrFalseStringCompare() void CheckString::checkAlwaysTrueOrFalseStringCompare()
{ {
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
for (const Token* tok = _tokenizer->tokens(); tok; tok = tok->next()) { 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|_memicmp|_memicmp_l|_stricmp|_wcsicmp|_mbsicmp|_stricmp_l|_wcsicmp_l|_mbsicmp_l")) { 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|_memicmp|_memicmp_l|_stricmp|_wcsicmp|_mbsicmp|_stricmp_l|_wcsicmp_l|_mbsicmp_l")) {
if (Token::Match(tok->tokAt(2), "%str% , %str% ,|)")) { if (Token::Match(tok->tokAt(2), "%str% , %str% ,|)")) {
const std::string &str1 = tok->strAt(2); const std::string &str1 = tok->strAt(2);
@ -165,10 +165,10 @@ void CheckString::alwaysTrueStringVariableCompareError(const Token *tok, const s
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
void CheckString::checkSuspiciousStringCompare() void CheckString::checkSuspiciousStringCompare()
{ {
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
const SymbolDatabase* symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase();
const std::size_t functions = symbolDatabase->functionScopes.size(); const std::size_t functions = symbolDatabase->functionScopes.size();
for (std::size_t i = 0; i < functions; ++i) { for (std::size_t i = 0; i < functions; ++i) {
const Scope * scope = symbolDatabase->functionScopes[i]; const Scope * scope = symbolDatabase->functionScopes[i];
@ -186,7 +186,7 @@ void CheckString::checkSuspiciousStringCompare()
continue; continue;
// Pointer addition? // Pointer addition?
if (varTok->str() == "+" && _tokenizer->isC()) { if (varTok->str() == "+" && mTokenizer->isC()) {
const Token * const tokens[2] = { varTok->astOperand1(), varTok->astOperand2() }; const Token * const tokens[2] = { varTok->astOperand1(), varTok->astOperand2() };
for (int nr = 0; nr < 2; nr++) { for (int nr = 0; nr < 2; nr++) {
const Token *t = tokens[nr]; const Token *t = tokens[nr];
@ -198,7 +198,7 @@ void CheckString::checkSuspiciousStringCompare()
} }
if (varTok->str() == "*") { if (varTok->str() == "*") {
if (!_tokenizer->isC() || varTok->astOperand2() != nullptr || litTok->tokType() != Token::eString) if (!mTokenizer->isC() || varTok->astOperand2() != nullptr || litTok->tokType() != Token::eString)
continue; continue;
varTok = varTok->astOperand1(); varTok = varTok->astOperand1();
} }
@ -216,7 +216,7 @@ void CheckString::checkSuspiciousStringCompare()
const bool ischar(litTok->tokType() == Token::eChar); const bool ischar(litTok->tokType() == Token::eChar);
if (litTok->tokType() == Token::eString) { if (litTok->tokType() == Token::eString) {
if (_tokenizer->isC() || (var && var->isArrayOrPointer())) if (mTokenizer->isC() || (var && var->isArrayOrPointer()))
suspiciousStringCompareError(tok, varname); suspiciousStringCompareError(tok, varname);
} else if (ischar && var && var->isPointer()) { } else if (ischar && var && var->isPointer()) {
suspiciousStringCompareError_char(tok, varname); suspiciousStringCompareError_char(tok, varname);
@ -249,7 +249,7 @@ static bool isChar(const Variable* var)
void CheckString::strPlusChar() void CheckString::strPlusChar()
{ {
const SymbolDatabase* symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase();
const std::size_t functions = symbolDatabase->functionScopes.size(); const std::size_t functions = symbolDatabase->functionScopes.size();
for (std::size_t i = 0; i < functions; ++i) { for (std::size_t i = 0; i < functions; ++i) {
const Scope * scope = symbolDatabase->functionScopes[i]; const Scope * scope = symbolDatabase->functionScopes[i];
@ -275,10 +275,10 @@ void CheckString::strPlusCharError(const Token *tok)
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
void CheckString::checkIncorrectStringCompare() void CheckString::checkIncorrectStringCompare()
{ {
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
const std::size_t functions = symbolDatabase->functionScopes.size(); const std::size_t functions = symbolDatabase->functionScopes.size();
for (std::size_t i = 0; i < functions; ++i) { for (std::size_t i = 0; i < functions; ++i) {
const Scope * scope = symbolDatabase->functionScopes[i]; const Scope * scope = symbolDatabase->functionScopes[i];
@ -338,10 +338,10 @@ void CheckString::incorrectStringBooleanError(const Token *tok, const std::strin
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
void CheckString::overlappingStrcmp() void CheckString::overlappingStrcmp()
{ {
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
const std::size_t functions = symbolDatabase->functionScopes.size(); const std::size_t functions = symbolDatabase->functionScopes.size();
for (std::size_t i = 0; i < functions; ++i) { for (std::size_t i = 0; i < functions; ++i) {
const Scope * scope = symbolDatabase->functionScopes[i]; const Scope * scope = symbolDatabase->functionScopes[i];
@ -397,7 +397,7 @@ void CheckString::overlappingStrcmp()
if (args1[1]->isLiteral() && if (args1[1]->isLiteral() &&
args2[1]->isLiteral() && args2[1]->isLiteral() &&
args1[1]->str() != args2[1]->str() && args1[1]->str() != args2[1]->str() &&
isSameExpression(_tokenizer->isCPP(), true, args1[0], args2[0], _settings->library, true)) isSameExpression(mTokenizer->isCPP(), true, args1[0], args2[0], mSettings->library, true))
overlappingStrcmpError(tok1, tok2); overlappingStrcmpError(tok1, tok2);
} }
} }
@ -424,7 +424,7 @@ void CheckString::overlappingStrcmpError(const Token *eq0, const Token *ne0)
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
void CheckString::sprintfOverlappingData() void CheckString::sprintfOverlappingData()
{ {
const SymbolDatabase* symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase();
const std::size_t functions = symbolDatabase->functionScopes.size(); const std::size_t functions = symbolDatabase->functionScopes.size();
for (std::size_t i = 0; i < functions; ++i) { for (std::size_t i = 0; i < functions; ++i) {
const Scope * scope = symbolDatabase->functionScopes[i]; const Scope * scope = symbolDatabase->functionScopes[i];
@ -436,11 +436,11 @@ void CheckString::sprintfOverlappingData()
const int formatString = Token::simpleMatch(tok, "sprintf") ? 1 : 2; const int formatString = Token::simpleMatch(tok, "sprintf") ? 1 : 2;
for (unsigned int argnr = formatString + 1; argnr < args.size(); ++argnr) { for (unsigned int argnr = formatString + 1; argnr < args.size(); ++argnr) {
const bool same = isSameExpression(_tokenizer->isCPP(), const bool same = isSameExpression(mTokenizer->isCPP(),
false, false,
args[0], args[0],
args[argnr], args[argnr],
_settings->library, mSettings->library,
true); true);
if (same) { if (same) {
sprintfOverlappingDataError(args[argnr], args[argnr]->expressionString()); sprintfOverlappingDataError(args[argnr], args[argnr]->expressionString());

View File

@ -54,12 +54,12 @@ static const struct CWE CWE190(190U); // Integer Overflow or Wraparound
void CheckType::checkTooBigBitwiseShift() void CheckType::checkTooBigBitwiseShift()
{ {
// unknown sizeof(int) => can't run this checker // unknown sizeof(int) => can't run this checker
if (_settings->platformType == Settings::Unspecified) if (mSettings->platformType == Settings::Unspecified)
return; return;
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
// C++ and macro: OUT(x<<y) // C++ and macro: OUT(x<<y)
if (_tokenizer->isCPP() && Token::Match(tok, "[;{}] %name% (") && Token::simpleMatch(tok->linkAt(2), ") ;") && tok->next()->isUpperCaseName() && !tok->next()->function()) if (mTokenizer->isCPP() && Token::Match(tok, "[;{}] %name% (") && Token::simpleMatch(tok->linkAt(2), ") ;") && tok->next()->isUpperCaseName() && !tok->next()->function())
tok = tok->linkAt(2); tok = tok->linkAt(2);
if (!tok->astOperand1() || !tok->astOperand2()) if (!tok->astOperand1() || !tok->astOperand2())
@ -80,21 +80,21 @@ void CheckType::checkTooBigBitwiseShift()
(lhstype->type == ValueType::Type::SHORT) || (lhstype->type == ValueType::Type::SHORT) ||
(lhstype->type == ValueType::Type::BOOL) || (lhstype->type == ValueType::Type::BOOL) ||
(lhstype->type == ValueType::Type::INT)) (lhstype->type == ValueType::Type::INT))
lhsbits = _settings->int_bit; lhsbits = mSettings->int_bit;
else if (lhstype->type == ValueType::Type::LONG) else if (lhstype->type == ValueType::Type::LONG)
lhsbits = _settings->long_bit; lhsbits = mSettings->long_bit;
else if (lhstype->type == ValueType::Type::LONGLONG) else if (lhstype->type == ValueType::Type::LONGLONG)
lhsbits = _settings->long_long_bit; lhsbits = mSettings->long_long_bit;
else else
continue; continue;
// Get biggest rhs value. preferably a value which doesn't have 'condition'. // Get biggest rhs value. preferably a value which doesn't have 'condition'.
const ValueFlow::Value * value = tok->astOperand2()->getValueGE(lhsbits, _settings); const ValueFlow::Value * value = tok->astOperand2()->getValueGE(lhsbits, mSettings);
if (value && _settings->isEnabled(value, false)) if (value && mSettings->isEnabled(value, false))
tooBigBitwiseShiftError(tok, lhsbits, *value); tooBigBitwiseShiftError(tok, lhsbits, *value);
else if (lhstype->sign == ValueType::Sign::SIGNED) { else if (lhstype->sign == ValueType::Sign::SIGNED) {
value = tok->astOperand2()->getValueGE(lhsbits-1, _settings); value = tok->astOperand2()->getValueGE(lhsbits-1, mSettings);
if (value && _settings->isEnabled(value, false)) if (value && mSettings->isEnabled(value, false))
tooBigSignedBitwiseShiftError(tok, lhsbits, *value); tooBigSignedBitwiseShiftError(tok, lhsbits, *value);
} }
} }
@ -145,10 +145,10 @@ void CheckType::tooBigSignedBitwiseShiftError(const Token *tok, int lhsbits, con
void CheckType::checkIntegerOverflow() void CheckType::checkIntegerOverflow()
{ {
// unknown sizeof(int) => can't run this checker // unknown sizeof(int) => can't run this checker
if (_settings->platformType == Settings::Unspecified || _settings->int_bit >= MathLib::bigint_bits) if (mSettings->platformType == Settings::Unspecified || mSettings->int_bit >= MathLib::bigint_bits)
return; return;
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (!tok->isArithmeticalOp()) if (!tok->isArithmeticalOp())
continue; continue;
@ -159,11 +159,11 @@ void CheckType::checkIntegerOverflow()
unsigned int bits; unsigned int bits;
if (vt->type == ValueType::Type::INT) if (vt->type == ValueType::Type::INT)
bits = _settings->int_bit; bits = mSettings->int_bit;
else if (vt->type == ValueType::Type::LONG) else if (vt->type == ValueType::Type::LONG)
bits = _settings->long_bit; bits = mSettings->long_bit;
else if (vt->type == ValueType::Type::LONGLONG) else if (vt->type == ValueType::Type::LONGLONG)
bits = _settings->long_long_bit; bits = mSettings->long_long_bit;
else else
continue; continue;
@ -174,10 +174,10 @@ void CheckType::checkIntegerOverflow()
const MathLib::bigint maxvalue = (((MathLib::bigint)1) << (bits - 1)) - 1; const MathLib::bigint maxvalue = (((MathLib::bigint)1) << (bits - 1)) - 1;
// is there a overflow result value // is there a overflow result value
const ValueFlow::Value *value = tok->getValueGE(maxvalue + 1, _settings); const ValueFlow::Value *value = tok->getValueGE(maxvalue + 1, mSettings);
if (!value) if (!value)
value = tok->getValueLE(-maxvalue - 2, _settings); value = tok->getValueLE(-maxvalue - 2, mSettings);
if (!value || !_settings->isEnabled(value,false)) if (!value || !mSettings->isEnabled(value,false))
continue; continue;
// For left shift, it's common practice to shift into the sign bit // For left shift, it's common practice to shift into the sign bit
@ -213,10 +213,10 @@ void CheckType::integerOverflowError(const Token *tok, const ValueFlow::Value &v
void CheckType::checkSignConversion() void CheckType::checkSignConversion()
{ {
if (!_settings->isEnabled(Settings::WARNING)) if (!mSettings->isEnabled(Settings::WARNING))
return; return;
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (!tok->isArithmeticalOp() || Token::Match(tok,"+|-")) if (!tok->isArithmeticalOp() || Token::Match(tok,"+|-"))
continue; continue;
@ -233,7 +233,7 @@ void CheckType::checkSignConversion()
tokens.pop(); tokens.pop();
if (!tok1) if (!tok1)
continue; continue;
if (!tok1->getValueLE(-1,_settings)) if (!tok1->getValueLE(-1,mSettings))
continue; continue;
if (tok1->valueType() && tok1->valueType()->sign != ValueType::Sign::UNSIGNED) if (tok1->valueType() && tok1->valueType()->sign != ValueType::Sign::UNSIGNED)
signConversionError(tok1, tok1->isNumber()); signConversionError(tok1, tok1->isNumber());
@ -260,17 +260,17 @@ void CheckType::signConversionError(const Token *tok, const bool constvalue)
void CheckType::checkLongCast() void CheckType::checkLongCast()
{ {
if (!_settings->isEnabled(Settings::STYLE)) if (!mSettings->isEnabled(Settings::STYLE))
return; return;
// Assignments.. // Assignments..
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (tok->str() != "=" || !Token::Match(tok->astOperand2(), "*|<<")) if (tok->str() != "=" || !Token::Match(tok->astOperand2(), "*|<<"))
continue; continue;
if (tok->astOperand2()->hasKnownIntValue()) { if (tok->astOperand2()->hasKnownIntValue()) {
const ValueFlow::Value &v = tok->astOperand2()->values().front(); const ValueFlow::Value &v = tok->astOperand2()->values().front();
if (_settings->isIntValue(v.intvalue)) if (mSettings->isIntValue(v.intvalue))
continue; continue;
} }
@ -292,7 +292,7 @@ void CheckType::checkLongCast()
} }
// Return.. // Return..
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
const std::size_t functions = symbolDatabase->functionScopes.size(); const std::size_t functions = symbolDatabase->functionScopes.size();
for (std::size_t i = 0; i < functions; ++i) { for (std::size_t i = 0; i < functions; ++i) {
const Scope * scope = symbolDatabase->functionScopes[i]; const Scope * scope = symbolDatabase->functionScopes[i];
@ -356,7 +356,7 @@ void CheckType::longCastReturnError(const Token *tok)
void CheckType::checkFloatToIntegerOverflow() void CheckType::checkFloatToIntegerOverflow()
{ {
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
const ValueType *vtint, *vtfloat; const ValueType *vtint, *vtfloat;
const std::list<ValueFlow::Value> *floatValues; const std::list<ValueFlow::Value> *floatValues;
@ -388,24 +388,24 @@ void CheckType::checkFloatToIntegerOverflow()
for (std::list<ValueFlow::Value>::const_iterator it = floatValues->begin(); it != floatValues->end(); ++it) { for (std::list<ValueFlow::Value>::const_iterator it = floatValues->begin(); it != floatValues->end(); ++it) {
if (it->valueType != ValueFlow::Value::FLOAT) if (it->valueType != ValueFlow::Value::FLOAT)
continue; continue;
if (!_settings->isEnabled(&(*it), false)) if (!mSettings->isEnabled(&(*it), false))
continue; continue;
if (it->floatValue > ~0ULL) if (it->floatValue > ~0ULL)
floatToIntegerOverflowError(tok, *it); floatToIntegerOverflowError(tok, *it);
else if ((-it->floatValue) > (1ULL<<62)) else if ((-it->floatValue) > (1ULL<<62))
floatToIntegerOverflowError(tok, *it); floatToIntegerOverflowError(tok, *it);
else if (_settings->platformType != Settings::Unspecified) { else if (mSettings->platformType != Settings::Unspecified) {
int bits = 0; int bits = 0;
if (vtint->type == ValueType::Type::CHAR) if (vtint->type == ValueType::Type::CHAR)
bits = _settings->char_bit; bits = mSettings->char_bit;
else if (vtint->type == ValueType::Type::SHORT) else if (vtint->type == ValueType::Type::SHORT)
bits = _settings->short_bit; bits = mSettings->short_bit;
else if (vtint->type == ValueType::Type::INT) else if (vtint->type == ValueType::Type::INT)
bits = _settings->int_bit; bits = mSettings->int_bit;
else if (vtint->type == ValueType::Type::LONG) else if (vtint->type == ValueType::Type::LONG)
bits = _settings->long_bit; bits = mSettings->long_bit;
else if (vtint->type == ValueType::Type::LONGLONG) else if (vtint->type == ValueType::Type::LONGLONG)
bits = _settings->long_long_bit; bits = mSettings->long_long_bit;
else else
continue; continue;
if (bits < MathLib::bigint_bits && it->floatValue >= (((MathLib::biguint)1) << bits)) if (bits < MathLib::bigint_bits && it->floatValue >= (((MathLib::biguint)1) << bits))

View File

@ -56,10 +56,10 @@ static const struct CWE CWE825(825U);
void CheckUninitVar::check() void CheckUninitVar::check()
{ {
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
std::set<std::string> arrayTypeDefs; std::set<std::string> arrayTypeDefs;
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (Token::Match(tok, "%name% [") && tok->variable() && Token::Match(tok->variable()->typeStartToken(), "%type% %var% ;")) if (Token::Match(tok, "%name% [") && tok->variable() && Token::Match(tok->variable()->typeStartToken(), "%type% %var% ;"))
arrayTypeDefs.insert(tok->variable()->typeStartToken()->str()); arrayTypeDefs.insert(tok->variable()->typeStartToken()->str());
} }
@ -75,7 +75,7 @@ void CheckUninitVar::check()
void CheckUninitVar::checkScope(const Scope* scope, const std::set<std::string> &arrayTypeDefs) void CheckUninitVar::checkScope(const Scope* scope, const std::set<std::string> &arrayTypeDefs)
{ {
for (std::list<Variable>::const_iterator i = scope->varlist.begin(); i != scope->varlist.end(); ++i) { for (std::list<Variable>::const_iterator i = scope->varlist.begin(); i != scope->varlist.end(); ++i) {
if ((_tokenizer->isCPP() && i->type() && !i->isPointer() && i->type()->needInitialization != Type::True) || if ((mTokenizer->isCPP() && i->type() && !i->isPointer() && i->type()->needInitialization != Type::True) ||
i->isStatic() || i->isExtern() || i->isReference()) i->isStatic() || i->isExtern() || i->isReference())
continue; continue;
@ -105,7 +105,7 @@ void CheckUninitVar::checkScope(const Scope* scope, const std::set<std::string>
continue; continue;
} }
bool stdtype = _tokenizer->isC() && arrayTypeDefs.find(i->typeStartToken()->str()) == arrayTypeDefs.end(); bool stdtype = mTokenizer->isC() && arrayTypeDefs.find(i->typeStartToken()->str()) == arrayTypeDefs.end();
const Token* tok = i->typeStartToken(); const Token* tok = i->typeStartToken();
for (; tok != i->nameToken() && tok->str() != "<"; tok = tok->next()) { for (; tok != i->nameToken() && tok->str() != "<"; tok = tok->next()) {
if (tok->isStandardType() || tok->isEnumType()) if (tok->isStandardType() || tok->isEnumType())
@ -145,7 +145,7 @@ void CheckUninitVar::checkScope(const Scope* scope, const std::set<std::string>
// Treat the pointer as initialized until it is assigned by malloc // Treat the pointer as initialized until it is assigned by malloc
for (const Token *tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) { for (const Token *tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
if (Token::Match(tok, "[;{}] %varid% = %name% (", arg->declarationId()) && if (Token::Match(tok, "[;{}] %varid% = %name% (", arg->declarationId()) &&
_settings->library.returnuninitdata.count(tok->strAt(3)) == 1U) { mSettings->library.returnuninitdata.count(tok->strAt(3)) == 1U) {
if (arg->typeStartToken()->strAt(-1) == "struct" || (arg->type() && arg->type()->isStructType())) if (arg->typeStartToken()->strAt(-1) == "struct" || (arg->type() && arg->type()->isStructType()))
checkStruct(tok, *arg); checkStruct(tok, *arg);
else if (arg->typeStartToken()->isStandardType() || arg->typeStartToken()->isEnumType()) { else if (arg->typeStartToken()->isStandardType() || arg->typeStartToken()->isEnumType()) {
@ -163,14 +163,14 @@ void CheckUninitVar::checkScope(const Scope* scope, const std::set<std::string>
void CheckUninitVar::checkStruct(const Token *tok, const Variable &structvar) void CheckUninitVar::checkStruct(const Token *tok, const Variable &structvar)
{ {
const Token *typeToken = structvar.typeStartToken(); const Token *typeToken = structvar.typeStartToken();
const SymbolDatabase * symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase * symbolDatabase = mTokenizer->getSymbolDatabase();
for (std::size_t j = 0U; j < symbolDatabase->classAndStructScopes.size(); ++j) { for (std::size_t j = 0U; j < symbolDatabase->classAndStructScopes.size(); ++j) {
const Scope *scope2 = symbolDatabase->classAndStructScopes[j]; const Scope *scope2 = symbolDatabase->classAndStructScopes[j];
if (scope2->className == typeToken->str() && scope2->numConstructors == 0U) { if (scope2->className == typeToken->str() && scope2->numConstructors == 0U) {
for (std::list<Variable>::const_iterator it = scope2->varlist.begin(); it != scope2->varlist.end(); ++it) { for (std::list<Variable>::const_iterator it = scope2->varlist.begin(); it != scope2->varlist.end(); ++it) {
const Variable &var = *it; const Variable &var = *it;
if (var.hasDefault() || var.isArray() || (!_tokenizer->isC() && var.isClass() && (!var.type() || var.type()->needInitialization != Type::True))) if (var.hasDefault() || var.isArray() || (!mTokenizer->isC() && var.isClass() && (!var.type() || var.type()->needInitialization != Type::True)))
continue; continue;
// is the variable declared in a inner union? // is the variable declared in a inner union?
@ -321,7 +321,7 @@ static bool isVariableUsed(const Token *tok, const Variable& var)
bool CheckUninitVar::checkScopeForVariable(const Token *tok, const Variable& var, bool * const possibleInit, bool * const noreturn, Alloc* const alloc, const std::string &membervar, std::map<unsigned int, VariableValue> variableValue) bool CheckUninitVar::checkScopeForVariable(const Token *tok, const Variable& var, bool * const possibleInit, bool * const noreturn, Alloc* const alloc, const std::string &membervar, std::map<unsigned int, VariableValue> variableValue)
{ {
const bool suppressErrors(possibleInit && *possibleInit); // Assume that this is a variable delaratkon, rather than a fundef const bool suppressErrors(possibleInit && *possibleInit); // Assume that this is a variable delaratkon, rather than a fundef
const bool printDebug = _settings->debugwarnings; const bool printDebug = mSettings->debugwarnings;
if (possibleInit) if (possibleInit)
*possibleInit = false; *possibleInit = false;
@ -338,7 +338,7 @@ bool CheckUninitVar::checkScopeForVariable(const Token *tok, const Variable& var
*possibleInit = true; *possibleInit = true;
// might be a noreturn function.. // might be a noreturn function..
if (_tokenizer->IsScopeNoReturn(tok)) { if (mTokenizer->IsScopeNoReturn(tok)) {
if (noreturn) if (noreturn)
*noreturn = true; *noreturn = true;
return false; return false;
@ -656,7 +656,7 @@ bool CheckUninitVar::checkScopeForVariable(const Token *tok, const Variable& var
if (var.isPointer() && if (var.isPointer() &&
Token::Match(tok->next(), "= %name% (") && Token::Match(tok->next(), "= %name% (") &&
Token::simpleMatch(tok->linkAt(3), ") ;") && Token::simpleMatch(tok->linkAt(3), ") ;") &&
_settings->library.returnuninitdata.count(tok->strAt(2)) > 0U) { mSettings->library.returnuninitdata.count(tok->strAt(2)) > 0U) {
*alloc = NO_CTOR_CALL; *alloc = NO_CTOR_CALL;
continue; continue;
} }
@ -916,7 +916,7 @@ bool CheckUninitVar::isVariableUsage(const Token *vartok, bool pointer, Alloc al
break; break;
} }
if (alloc != NO_ALLOC && parent->str() == "(") { if (alloc != NO_ALLOC && parent->str() == "(") {
if (!_settings->library.isFunctionConst(parent->strAt(-1), true)) { if (!mSettings->library.isFunctionConst(parent->strAt(-1), true)) {
assignment = true; assignment = true;
break; break;
} }
@ -935,13 +935,13 @@ bool CheckUninitVar::isVariableUsage(const Token *vartok, bool pointer, Alloc al
} }
if (Token::Match(vartok->previous(), "++|--|%cop%")) { if (Token::Match(vartok->previous(), "++|--|%cop%")) {
if (_tokenizer->isCPP() && alloc == ARRAY && Token::Match(vartok->tokAt(-4), "& %var% =|( *")) if (mTokenizer->isCPP() && alloc == ARRAY && Token::Match(vartok->tokAt(-4), "& %var% =|( *"))
return false; return false;
if (isLikelyStreamRead(_tokenizer->isCPP(), vartok->previous())) if (isLikelyStreamRead(mTokenizer->isCPP(), vartok->previous()))
return false; return false;
if (_tokenizer->isCPP() && Token::simpleMatch(vartok->previous(), "<<")) { if (mTokenizer->isCPP() && Token::simpleMatch(vartok->previous(), "<<")) {
const Token* tok2 = vartok->previous(); const Token* tok2 = vartok->previous();
// Looks like stream operator, but could also initialize the variable. Check lhs. // Looks like stream operator, but could also initialize the variable. Check lhs.
@ -1011,7 +1011,7 @@ bool CheckUninitVar::isVariableUsage(const Token *vartok, bool pointer, Alloc al
return true; return true;
} }
if (_tokenizer->isCPP() && Token::simpleMatch(vartok->next(), "<<")) { if (mTokenizer->isCPP() && Token::simpleMatch(vartok->next(), "<<")) {
// Is this calculation done in rhs? // Is this calculation done in rhs?
const Token *tok = vartok; const Token *tok = vartok;
while (Token::Match(tok, "%name%|.|::")) while (Token::Match(tok, "%name%|.|::"))
@ -1088,10 +1088,10 @@ int CheckUninitVar::isFunctionParUsage(const Token *vartok, bool pointer, Alloc
// control-flow statement reading the variable "by value" // control-flow statement reading the variable "by value"
return alloc == NO_ALLOC; return alloc == NO_ALLOC;
} else { } else {
const bool isnullbad = _settings->library.isnullargbad(start->previous(), argumentNumber + 1); const bool isnullbad = mSettings->library.isnullargbad(start->previous(), argumentNumber + 1);
if (pointer && !address && isnullbad && alloc == NO_ALLOC) if (pointer && !address && isnullbad && alloc == NO_ALLOC)
return 1; return 1;
const bool isuninitbad = _settings->library.isuninitargbad(start->previous(), argumentNumber + 1); const bool isuninitbad = mSettings->library.isuninitargbad(start->previous(), argumentNumber + 1);
if (alloc != NO_ALLOC) if (alloc != NO_ALLOC)
return isnullbad && isuninitbad; return isnullbad && isuninitbad;
return isuninitbad && (!address || isnullbad); return isuninitbad && (!address || isnullbad);
@ -1109,7 +1109,7 @@ bool CheckUninitVar::isMemberVariableAssignment(const Token *tok, const std::str
return true; return true;
else if (Token::Match(tok->tokAt(-2), "[(,=] &")) else if (Token::Match(tok->tokAt(-2), "[(,=] &"))
return true; return true;
else if (isLikelyStreamRead(_tokenizer->isCPP(), tok->previous())) else if (isLikelyStreamRead(mTokenizer->isCPP(), tok->previous()))
return true; return true;
else if ((tok->previous() && tok->previous()->isConstOp()) || Token::Match(tok->previous(), "[|=")) else if ((tok->previous() && tok->previous()->isConstOp()) || Token::Match(tok->previous(), "[|="))
; // member variable usage ; // member variable usage
@ -1189,7 +1189,7 @@ bool CheckUninitVar::isMemberVariableUsage(const Token *tok, bool isPointer, All
tok->astParent()->astParent()->astParent()->astOperand2() == tok->astParent()->astParent()) tok->astParent()->astParent()->astParent()->astOperand2() == tok->astParent()->astParent())
return true; return true;
else if (_settings->experimental && else if (mSettings->experimental &&
!isPointer && !isPointer &&
Token::Match(tok->tokAt(-2), "[(,] & %name% [,)]") && Token::Match(tok->tokAt(-2), "[(,] & %name% [,)]") &&
isVariableUsage(tok, isPointer, alloc)) isVariableUsage(tok, isPointer, alloc))
@ -1223,7 +1223,7 @@ void CheckUninitVar::uninitStructMemberError(const Token *tok, const std::string
void CheckUninitVar::valueFlowUninit() void CheckUninitVar::valueFlowUninit()
{ {
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
// check every executable scope // check every executable scope
for (std::list<Scope>::const_iterator scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) { for (std::list<Scope>::const_iterator scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) {
@ -1248,7 +1248,7 @@ void CheckUninitVar::valueFlowUninit()
void CheckUninitVar::deadPointer() void CheckUninitVar::deadPointer()
{ {
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
// check every executable scope // check every executable scope
for (std::list<Scope>::const_iterator scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) { for (std::list<Scope>::const_iterator scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) {

View File

@ -310,7 +310,7 @@ bool CheckUnusedFunctions::check(ErrorLogger * const errorLogger, const Settings
/* /*
std::ostringstream errmsg; std::ostringstream errmsg;
errmsg << "The function '" << it->first << "' is only used in the file it was declared in so it should have local linkage."; errmsg << "The function '" << it->first << "' is only used in the file it was declared in so it should have local linkage.";
_errorLogger->reportErr( errmsg.str() ); mErrorLogger->reportErr( errmsg.str() );
errors = true; errors = true;
*/ */
} }

View File

@ -732,7 +732,7 @@ void CheckUnusedVar::checkFunctionVariableUsage_iterateScopes(const Scope* const
type = Variables::pointerPointer; type = Variables::pointerPointer;
else if (i->isPointer()) else if (i->isPointer())
type = Variables::pointer; type = Variables::pointer;
else if (_tokenizer->isC() || else if (mTokenizer->isC() ||
i->typeEndToken()->isStandardType() || i->typeEndToken()->isStandardType() ||
isRecordTypeWithoutSideEffects(i->type()) || isRecordTypeWithoutSideEffects(i->type()) ||
(i->isStlType() && (i->isStlType() &&
@ -858,7 +858,7 @@ void CheckUnusedVar::checkFunctionVariableUsage_iterateScopes(const Scope* const
// C++11 std::for_each // C++11 std::for_each
// No warning should be written if a variable is first read and // No warning should be written if a variable is first read and
// then written in the body. // then written in the body.
else if (_tokenizer->isCPP() && Token::simpleMatch(tok, "for_each (") && Token::simpleMatch(tok->linkAt(1), ") ;")) { else if (mTokenizer->isCPP() && Token::simpleMatch(tok, "for_each (") && Token::simpleMatch(tok->linkAt(1), ") ;")) {
const Token *end = tok->linkAt(1); const Token *end = tok->linkAt(1);
if (end->previous()->str() == "}") { if (end->previous()->str() == "}") {
std::set<unsigned int> readvar; std::set<unsigned int> readvar;
@ -912,7 +912,7 @@ void CheckUnusedVar::checkFunctionVariableUsage_iterateScopes(const Scope* const
} }
// Freeing memory (not considered "using" the pointer if it was also allocated in this function) // Freeing memory (not considered "using" the pointer if it was also allocated in this function)
if (Token::Match(tok, "free|g_free|kfree|vfree ( %var% )") || if (Token::Match(tok, "free|g_free|kfree|vfree ( %var% )") ||
(_tokenizer->isCPP() && (Token::Match(tok, "delete %var% ;") || Token::Match(tok, "delete [ ] %var% ;")))) { (mTokenizer->isCPP() && (Token::Match(tok, "delete %var% ;") || Token::Match(tok, "delete [ ] %var% ;")))) {
unsigned int varid = 0; unsigned int varid = 0;
if (tok->str() != "delete") { if (tok->str() != "delete") {
const Token *varTok = tok->tokAt(2); const Token *varTok = tok->tokAt(2);
@ -1020,7 +1020,7 @@ void CheckUnusedVar::checkFunctionVariableUsage_iterateScopes(const Scope* const
const Token *type = start->tokAt(3); const Token *type = start->tokAt(3);
// skip nothrow // skip nothrow
if (_tokenizer->isCPP() && (Token::simpleMatch(type, "( nothrow )") || if (mTokenizer->isCPP() && (Token::simpleMatch(type, "( nothrow )") ||
Token::simpleMatch(type, "( std :: nothrow )"))) Token::simpleMatch(type, "( std :: nothrow )")))
type = type->link()->next(); type = type->link()->next();
@ -1112,7 +1112,7 @@ void CheckUnusedVar::checkFunctionVariableUsage_iterateScopes(const Scope* const
} }
} }
else if (_tokenizer->isCPP() && Token::Match(tok, "[;{}] %var% <<")) { else if (mTokenizer->isCPP() && Token::Match(tok, "[;{}] %var% <<")) {
variables.erase(tok->next()->varId()); variables.erase(tok->next()->varId());
} }
@ -1122,13 +1122,13 @@ void CheckUnusedVar::checkFunctionVariableUsage_iterateScopes(const Scope* const
} else // addressof } else // addressof
variables.use(tok->next()->varId(), tok); // use = read + write variables.use(tok->next()->varId(), tok); // use = read + write
} else if (Token::Match(tok, ">>|>>= %name%")) { } else if (Token::Match(tok, ">>|>>= %name%")) {
if (isLikelyStreamRead(_tokenizer->isCPP(), tok)) if (isLikelyStreamRead(mTokenizer->isCPP(), tok))
variables.use(tok->next()->varId(), tok); // use = read + write variables.use(tok->next()->varId(), tok); // use = read + write
else else
variables.read(tok->next()->varId(), tok); variables.read(tok->next()->varId(), tok);
} else if (Token::Match(tok, "%var% >>|&") && Token::Match(tok->previous(), "[{};:]")) { } else if (Token::Match(tok, "%var% >>|&") && Token::Match(tok->previous(), "[{};:]")) {
variables.read(tok->varId(), tok); variables.read(tok->varId(), tok);
} else if (isLikelyStreamRead(_tokenizer->isCPP(),tok->previous())) { } else if (isLikelyStreamRead(mTokenizer->isCPP(),tok->previous())) {
variables.use(tok->varId(), tok); variables.use(tok->varId(), tok);
} }
@ -1213,11 +1213,11 @@ void CheckUnusedVar::checkFunctionVariableUsage_iterateScopes(const Scope* const
void CheckUnusedVar::checkFunctionVariableUsage() void CheckUnusedVar::checkFunctionVariableUsage()
{ {
if (!_settings->isEnabled(Settings::STYLE)) if (!mSettings->isEnabled(Settings::STYLE))
return; return;
// Parse all executing scopes.. // Parse all executing scopes..
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
// only check functions // only check functions
const std::size_t functions = symbolDatabase->functionScopes.size(); const std::size_t functions = symbolDatabase->functionScopes.size();
@ -1306,10 +1306,10 @@ void CheckUnusedVar::unassignedVariableError(const Token *tok, const std::string
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
void CheckUnusedVar::checkStructMemberUsage() void CheckUnusedVar::checkStructMemberUsage()
{ {
if (!_settings->isEnabled(Settings::STYLE)) if (!mSettings->isEnabled(Settings::STYLE))
return; return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (std::list<Scope>::const_iterator scope = symbolDatabase->scopeList.cbegin(); scope != symbolDatabase->scopeList.cend(); ++scope) { for (std::list<Scope>::const_iterator scope = symbolDatabase->scopeList.cbegin(); scope != symbolDatabase->scopeList.cend(); ++scope) {
if (scope->type != Scope::eStruct && scope->type != Scope::eUnion) if (scope->type != Scope::eStruct && scope->type != Scope::eUnion)
@ -1382,7 +1382,7 @@ void CheckUnusedVar::checkStructMemberUsage()
continue; continue;
// Check if the struct member variable is used anywhere in the file // Check if the struct member variable is used anywhere in the file
if (Token::findsimplematch(_tokenizer->tokens(), (". " + var->name()).c_str())) if (Token::findsimplematch(mTokenizer->tokens(), (". " + var->name()).c_str()))
continue; continue;
unusedStructMemberError(var->nameToken(), scope->className, var->name(), scope->type == Scope::eUnion); unusedStructMemberError(var->nameToken(), scope->className, var->name(), scope->type == Scope::eUnion);

View File

@ -46,9 +46,9 @@ static const struct CWE CWE758(758U); // Reliance on Undefined, Unspecified, o
void CheckVaarg::va_start_argument() void CheckVaarg::va_start_argument()
{ {
const SymbolDatabase* const symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
const std::size_t functions = symbolDatabase->functionScopes.size(); const std::size_t functions = symbolDatabase->functionScopes.size();
const bool printWarnings = _settings->isEnabled(Settings::WARNING); const bool printWarnings = mSettings->isEnabled(Settings::WARNING);
for (std::size_t i = 0; i < functions; ++i) { for (std::size_t i = 0; i < functions; ++i) {
const Scope* scope = symbolDatabase->functionScopes[i]; const Scope* scope = symbolDatabase->functionScopes[i];
@ -95,7 +95,7 @@ void CheckVaarg::referenceAs_va_start_error(const Token *tok, const std::string&
void CheckVaarg::va_list_usage() void CheckVaarg::va_list_usage()
{ {
const SymbolDatabase* const symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Variable* var : symbolDatabase->variableList()) { for (const Variable* var : symbolDatabase->variableList()) {
if (!var || var->isPointer() || var->isReference() || var->isArray() || !var->scope() || var->typeStartToken()->str() != "va_list") if (!var || var->isPointer() || var->isReference() || var->isArray() || !var->scope() || var->typeStartToken()->str() != "va_list")
continue; continue;
@ -139,7 +139,7 @@ void CheckVaarg::va_list_usage()
tok = scope->bodyEnd; tok = scope->bodyEnd;
if (!tok) if (!tok)
return; return;
} else if (tok->str() == "goto" || (_tokenizer->isCPP() && tok->str() == "try")) { } else if (tok->str() == "goto" || (mTokenizer->isCPP() && tok->str() == "try")) {
open = false; open = false;
break; break;
} else if (!open && tok->varId() == var->declarationId()) } else if (!open && tok->varId() == var->declarationId())

View File

@ -54,7 +54,7 @@ static TimerResults S_timerResults;
static const CWE CWE398(398U); // Indicator of Poor Code Quality static const CWE CWE398(398U); // Indicator of Poor Code Quality
CppCheck::CppCheck(ErrorLogger &errorLogger, bool useGlobalSuppressions) CppCheck::CppCheck(ErrorLogger &errorLogger, bool useGlobalSuppressions)
: _errorLogger(errorLogger), exitcode(0), _useGlobalSuppressions(useGlobalSuppressions), tooManyConfigs(false), _simplify(true) : mErrorLogger(errorLogger), exitcode(0), _useGlobalSuppressions(useGlobalSuppressions), tooManyConfigs(false), _simplify(true)
{ {
} }
@ -64,7 +64,7 @@ CppCheck::~CppCheck()
delete fileInfo.back(); delete fileInfo.back();
fileInfo.pop_back(); fileInfo.pop_back();
} }
S_timerResults.ShowResults(_settings.showtime); S_timerResults.ShowResults(mSettings.showtime);
} }
const char * CppCheck::version() const char * CppCheck::version()
@ -91,15 +91,15 @@ unsigned int CppCheck::check(const std::string &path, const std::string &content
unsigned int CppCheck::check(const ImportProject::FileSettings &fs) unsigned int CppCheck::check(const ImportProject::FileSettings &fs)
{ {
CppCheck temp(_errorLogger, _useGlobalSuppressions); CppCheck temp(mErrorLogger, _useGlobalSuppressions);
temp._settings = _settings; temp.mSettings = mSettings;
if (!temp._settings.userDefines.empty()) if (!temp.mSettings.userDefines.empty())
temp._settings.userDefines += ';'; temp.mSettings.userDefines += ';';
temp._settings.userDefines += fs.cppcheckDefines(); temp.mSettings.userDefines += fs.cppcheckDefines();
temp._settings.includePaths = fs.includePaths; temp.mSettings.includePaths = fs.includePaths;
// TODO: temp._settings.userUndefs = fs.undefs; // TODO: temp.mSettings.userUndefs = fs.undefs;
if (fs.platformType != Settings::Unspecified) { if (fs.platformType != Settings::Unspecified) {
temp._settings.platform(fs.platformType); temp.mSettings.platform(fs.platformType);
} }
std::ifstream fin(fs.filename); std::ifstream fin(fs.filename);
return temp.checkFile(Path::simplifyPath(fs.filename), fs.cfg, fin); return temp.checkFile(Path::simplifyPath(fs.filename), fs.cfg, fin);
@ -111,23 +111,23 @@ unsigned int CppCheck::checkFile(const std::string& filename, const std::string
// only show debug warnings for accepted C/C++ source files // only show debug warnings for accepted C/C++ source files
if (!Path::acceptFile(filename)) if (!Path::acceptFile(filename))
_settings.debugwarnings = false; mSettings.debugwarnings = false;
if (_settings.terminated()) if (mSettings.terminated())
return exitcode; return exitcode;
if (!_settings.quiet) { if (!mSettings.quiet) {
std::string fixedpath = Path::simplifyPath(filename); std::string fixedpath = Path::simplifyPath(filename);
fixedpath = Path::toNativeSeparators(fixedpath); fixedpath = Path::toNativeSeparators(fixedpath);
_errorLogger.reportOut(std::string("Checking ") + fixedpath + ' ' + cfgname + std::string("...")); mErrorLogger.reportOut(std::string("Checking ") + fixedpath + ' ' + cfgname + std::string("..."));
if (_settings.verbose) { if (mSettings.verbose) {
_errorLogger.reportOut("Defines: " + _settings.userDefines); mErrorLogger.reportOut("Defines: " + mSettings.userDefines);
std::string includePaths; std::string includePaths;
for (const std::string &I : _settings.includePaths) for (const std::string &I : mSettings.includePaths)
includePaths += " -I" + I; includePaths += " -I" + I;
_errorLogger.reportOut("Includes:" + includePaths); mErrorLogger.reportOut("Includes:" + includePaths);
_errorLogger.reportOut(std::string("Platform:") + _settings.platformString()); mErrorLogger.reportOut(std::string("Platform:") + mSettings.platformString());
} }
} }
@ -140,7 +140,7 @@ unsigned int CppCheck::checkFile(const std::string& filename, const std::string
bool internalErrorFound(false); bool internalErrorFound(false);
try { try {
Preprocessor preprocessor(_settings, this); Preprocessor preprocessor(mSettings, this);
std::set<std::string> configurations; std::set<std::string> configurations;
simplecpp::OutputList outputList; simplecpp::OutputList outputList;
@ -174,40 +174,40 @@ unsigned int CppCheck::checkFile(const std::string& filename, const std::string
it->msg, it->msg,
"syntaxError", "syntaxError",
false); false);
_errorLogger.reportErr(errmsg); mErrorLogger.reportErr(errmsg);
return 1; return 1;
} }
} }
preprocessor.loadFiles(tokens1, files); preprocessor.loadFiles(tokens1, files);
if (!_settings.plistOutput.empty()) { if (!mSettings.plistOutput.empty()) {
std::string filename2; std::string filename2;
if (filename.find('/') != std::string::npos) if (filename.find('/') != std::string::npos)
filename2 = filename.substr(filename.rfind('/') + 1); filename2 = filename.substr(filename.rfind('/') + 1);
else else
filename2 = filename; filename2 = filename;
filename2 = _settings.plistOutput + filename2.substr(0, filename2.find('.')) + ".plist"; filename2 = mSettings.plistOutput + filename2.substr(0, filename2.find('.')) + ".plist";
plistFile.open(filename2); plistFile.open(filename2);
plistFile << ErrorLogger::plistHeader(version(), files); plistFile << ErrorLogger::plistHeader(version(), files);
} }
// write dump file xml prolog // write dump file xml prolog
std::ofstream fdump; std::ofstream fdump;
if (_settings.dump) { if (mSettings.dump) {
const std::string dumpfile(_settings.dumpFile.empty() ? (filename + ".dump") : _settings.dumpFile); const std::string dumpfile(mSettings.dumpFile.empty() ? (filename + ".dump") : mSettings.dumpFile);
fdump.open(dumpfile); fdump.open(dumpfile);
if (fdump.is_open()) { if (fdump.is_open()) {
fdump << "<?xml version=\"1.0\"?>" << std::endl; fdump << "<?xml version=\"1.0\"?>" << std::endl;
fdump << "<dumps>" << std::endl; fdump << "<dumps>" << std::endl;
fdump << " <platform" fdump << " <platform"
<< " name=\"" << _settings.platformString() << '\"' << " name=\"" << mSettings.platformString() << '\"'
<< " char_bit=\"" << _settings.char_bit << '\"' << " char_bit=\"" << mSettings.char_bit << '\"'
<< " short_bit=\"" << _settings.short_bit << '\"' << " short_bit=\"" << mSettings.short_bit << '\"'
<< " int_bit=\"" << _settings.int_bit << '\"' << " int_bit=\"" << mSettings.int_bit << '\"'
<< " long_bit=\"" << _settings.long_bit << '\"' << " long_bit=\"" << mSettings.long_bit << '\"'
<< " long_long_bit=\"" << _settings.long_long_bit << '\"' << " long_long_bit=\"" << mSettings.long_long_bit << '\"'
<< " pointer_bit=\"" << (_settings.sizeof_pointer * _settings.char_bit) << '\"' << " pointer_bit=\"" << (mSettings.sizeof_pointer * mSettings.char_bit) << '\"'
<< "/>\n"; << "/>\n";
fdump << " <rawtokens>" << std::endl; fdump << " <rawtokens>" << std::endl;
for (unsigned int i = 0; i < files.size(); ++i) for (unsigned int i = 0; i < files.size(); ++i)
@ -225,27 +225,27 @@ unsigned int CppCheck::checkFile(const std::string& filename, const std::string
// Parse comments and then remove them // Parse comments and then remove them
preprocessor.inlineSuppressions(tokens1); preprocessor.inlineSuppressions(tokens1);
if (_settings.dump && fdump.is_open()) { if (mSettings.dump && fdump.is_open()) {
_settings.nomsg.dump(fdump); mSettings.nomsg.dump(fdump);
} }
tokens1.removeComments(); tokens1.removeComments();
preprocessor.removeComments(); preprocessor.removeComments();
if (!_settings.buildDir.empty()) { if (!mSettings.buildDir.empty()) {
// Get toolinfo // Get toolinfo
std::string toolinfo; std::string toolinfo;
toolinfo += CPPCHECK_VERSION_STRING; toolinfo += CPPCHECK_VERSION_STRING;
toolinfo += _settings.isEnabled(Settings::WARNING) ? 'w' : ' '; toolinfo += mSettings.isEnabled(Settings::WARNING) ? 'w' : ' ';
toolinfo += _settings.isEnabled(Settings::STYLE) ? 's' : ' '; toolinfo += mSettings.isEnabled(Settings::STYLE) ? 's' : ' ';
toolinfo += _settings.isEnabled(Settings::PERFORMANCE) ? 'p' : ' '; toolinfo += mSettings.isEnabled(Settings::PERFORMANCE) ? 'p' : ' ';
toolinfo += _settings.isEnabled(Settings::PORTABILITY) ? 'p' : ' '; toolinfo += mSettings.isEnabled(Settings::PORTABILITY) ? 'p' : ' ';
toolinfo += _settings.isEnabled(Settings::INFORMATION) ? 'i' : ' '; toolinfo += mSettings.isEnabled(Settings::INFORMATION) ? 'i' : ' ';
toolinfo += _settings.userDefines; toolinfo += mSettings.userDefines;
// Calculate checksum so it can be compared with old checksum / future checksums // Calculate checksum so it can be compared with old checksum / future checksums
const unsigned int checksum = preprocessor.calculateChecksum(tokens1, toolinfo); const unsigned int checksum = preprocessor.calculateChecksum(tokens1, toolinfo);
std::list<ErrorLogger::ErrorMessage> errors; std::list<ErrorLogger::ErrorMessage> errors;
if (!analyzerInformation.analyzeFile(_settings.buildDir, filename, cfgname, checksum, &errors)) { if (!analyzerInformation.analyzeFile(mSettings.buildDir, filename, cfgname, checksum, &errors)) {
while (!errors.empty()) { while (!errors.empty()) {
reportErr(errors.front()); reportErr(errors.front());
errors.pop_front(); errors.pop_front();
@ -261,14 +261,14 @@ unsigned int CppCheck::checkFile(const std::string& filename, const std::string
preprocessor.setPlatformInfo(&tokens1); preprocessor.setPlatformInfo(&tokens1);
// Get configurations.. // Get configurations..
if (_settings.userDefines.empty() || _settings.force) { if (mSettings.userDefines.empty() || mSettings.force) {
Timer t("Preprocessor::getConfigs", _settings.showtime, &S_timerResults); Timer t("Preprocessor::getConfigs", mSettings.showtime, &S_timerResults);
configurations = preprocessor.getConfigs(tokens1); configurations = preprocessor.getConfigs(tokens1);
} else { } else {
configurations.insert(_settings.userDefines); configurations.insert(mSettings.userDefines);
} }
if (_settings.checkConfiguration) { if (mSettings.checkConfiguration) {
for (const std::string &config : configurations) for (const std::string &config : configurations)
(void)preprocessor.getcode(tokens1, config, files, true); (void)preprocessor.getcode(tokens1, config, files, true);
@ -276,7 +276,7 @@ unsigned int CppCheck::checkFile(const std::string& filename, const std::string
} }
// Run define rules on raw code // Run define rules on raw code
for (const Settings::Rule &rule : _settings.rules) { for (const Settings::Rule &rule : mSettings.rules) {
if (rule.tokenlist != "define") if (rule.tokenlist != "define")
continue; continue;
@ -286,15 +286,15 @@ unsigned int CppCheck::checkFile(const std::string& filename, const std::string
if (dir.str.compare(0,8,"#define ") == 0) if (dir.str.compare(0,8,"#define ") == 0)
code += "#line " + MathLib::toString(dir.linenr) + " \"" + dir.file + "\"\n" + dir.str + '\n'; code += "#line " + MathLib::toString(dir.linenr) + " \"" + dir.file + "\"\n" + dir.str + '\n';
} }
Tokenizer tokenizer2(&_settings, this); Tokenizer tokenizer2(&mSettings, this);
std::istringstream istr2(code); std::istringstream istr2(code);
tokenizer2.list.createTokens(istr2); tokenizer2.list.createTokens(istr2);
executeRules("define", tokenizer2); executeRules("define", tokenizer2);
break; break;
} }
if (!_settings.force && configurations.size() > _settings.maxConfigs) { if (!mSettings.force && configurations.size() > mSettings.maxConfigs) {
if (_settings.isEnabled(Settings::INFORMATION)) { if (mSettings.isEnabled(Settings::INFORMATION)) {
tooManyConfigsError(Path::toNativeSeparators(filename),configurations.size()); tooManyConfigsError(Path::toNativeSeparators(filename),configurations.size());
} else { } else {
tooManyConfigs = true; tooManyConfigs = true;
@ -307,24 +307,24 @@ unsigned int CppCheck::checkFile(const std::string& filename, const std::string
std::list<std::string> configurationError; std::list<std::string> configurationError;
for (std::set<std::string>::const_iterator it = configurations.begin(); it != configurations.end(); ++it) { for (std::set<std::string>::const_iterator it = configurations.begin(); it != configurations.end(); ++it) {
// bail out if terminated // bail out if terminated
if (_settings.terminated()) if (mSettings.terminated())
break; break;
// Check only a few configurations (default 12), after that bail out, unless --force // Check only a few configurations (default 12), after that bail out, unless --force
// was used. // was used.
if (!_settings.force && ++checkCount > _settings.maxConfigs) if (!mSettings.force && ++checkCount > mSettings.maxConfigs)
break; break;
cfg = *it; cfg = *it;
if (!_settings.userDefines.empty()) { if (!mSettings.userDefines.empty()) {
if (!cfg.empty()) if (!cfg.empty())
cfg = ";" + cfg; cfg = ";" + cfg;
cfg = _settings.userDefines + cfg; cfg = mSettings.userDefines + cfg;
} }
if (_settings.preprocessOnly) { if (mSettings.preprocessOnly) {
Timer t("Preprocessor::getcode", _settings.showtime, &S_timerResults); Timer t("Preprocessor::getcode", mSettings.showtime, &S_timerResults);
std::string codeWithoutCfg = preprocessor.getcode(tokens1, cfg, files, true); std::string codeWithoutCfg = preprocessor.getcode(tokens1, cfg, files, true);
t.Stop(); t.Stop();
@ -343,57 +343,57 @@ unsigned int CppCheck::checkFile(const std::string& filename, const std::string
continue; continue;
} }
Tokenizer _tokenizer(&_settings, this); Tokenizer mTokenizer(&mSettings, this);
if (_settings.showtime != SHOWTIME_NONE) if (mSettings.showtime != SHOWTIME_NONE)
_tokenizer.setTimerResults(&S_timerResults); mTokenizer.setTimerResults(&S_timerResults);
try { try {
bool result; bool result;
// Create tokens, skip rest of iteration if failed // Create tokens, skip rest of iteration if failed
Timer timer("Tokenizer::createTokens", _settings.showtime, &S_timerResults); Timer timer("Tokenizer::createTokens", mSettings.showtime, &S_timerResults);
const simplecpp::TokenList &tokensP = preprocessor.preprocess(tokens1, cfg, files, true); const simplecpp::TokenList &tokensP = preprocessor.preprocess(tokens1, cfg, files, true);
_tokenizer.createTokens(&tokensP); mTokenizer.createTokens(&tokensP);
timer.Stop(); timer.Stop();
hasValidConfig = true; hasValidConfig = true;
// If only errors are printed, print filename after the check // If only errors are printed, print filename after the check
if (!_settings.quiet && (!cfg.empty() || it != configurations.begin())) { if (!mSettings.quiet && (!cfg.empty() || it != configurations.begin())) {
std::string fixedpath = Path::simplifyPath(filename); std::string fixedpath = Path::simplifyPath(filename);
fixedpath = Path::toNativeSeparators(fixedpath); fixedpath = Path::toNativeSeparators(fixedpath);
_errorLogger.reportOut("Checking " + fixedpath + ": " + cfg + "..."); mErrorLogger.reportOut("Checking " + fixedpath + ": " + cfg + "...");
} }
if (tokensP.empty()) if (tokensP.empty())
continue; continue;
// skip rest of iteration if just checking configuration // skip rest of iteration if just checking configuration
if (_settings.checkConfiguration) if (mSettings.checkConfiguration)
continue; continue;
// Check raw tokens // Check raw tokens
checkRawTokens(_tokenizer); checkRawTokens(mTokenizer);
// Simplify tokens into normal form, skip rest of iteration if failed // Simplify tokens into normal form, skip rest of iteration if failed
Timer timer2("Tokenizer::simplifyTokens1", _settings.showtime, &S_timerResults); Timer timer2("Tokenizer::simplifyTokens1", mSettings.showtime, &S_timerResults);
result = _tokenizer.simplifyTokens1(cfg); result = mTokenizer.simplifyTokens1(cfg);
timer2.Stop(); timer2.Stop();
if (!result) if (!result)
continue; continue;
// dump xml if --dump // dump xml if --dump
if (_settings.dump && fdump.is_open()) { if (mSettings.dump && fdump.is_open()) {
fdump << "<dump cfg=\"" << ErrorLogger::toxml(cfg) << "\">" << std::endl; fdump << "<dump cfg=\"" << ErrorLogger::toxml(cfg) << "\">" << std::endl;
preprocessor.dump(fdump); preprocessor.dump(fdump);
_tokenizer.dump(fdump); mTokenizer.dump(fdump);
fdump << "</dump>" << std::endl; fdump << "</dump>" << std::endl;
} }
// Skip if we already met the same simplified token list // Skip if we already met the same simplified token list
if (_settings.force || _settings.maxConfigs > 1) { if (mSettings.force || mSettings.maxConfigs > 1) {
const unsigned long long checksum = _tokenizer.list.calculateChecksum(); const unsigned long long checksum = mTokenizer.list.calculateChecksum();
if (checksums.find(checksum) != checksums.end()) { if (checksums.find(checksum) != checksums.end()) {
if (_settings.isEnabled(Settings::INFORMATION) && (_settings.debug || _settings.verbose)) if (mSettings.isEnabled(Settings::INFORMATION) && (mSettings.debug || mSettings.verbose))
purgedConfigurationMessage(filename, cfg); purgedConfigurationMessage(filename, cfg);
continue; continue;
} }
@ -401,23 +401,23 @@ unsigned int CppCheck::checkFile(const std::string& filename, const std::string
} }
// Check normal tokens // Check normal tokens
checkNormalTokens(_tokenizer); checkNormalTokens(mTokenizer);
// Analyze info.. // Analyze info..
if (!_settings.buildDir.empty()) if (!mSettings.buildDir.empty())
checkUnusedFunctions.parseTokens(_tokenizer, filename.c_str(), &_settings); checkUnusedFunctions.parseTokens(mTokenizer, filename.c_str(), &mSettings);
// simplify more if required, skip rest of iteration if failed // simplify more if required, skip rest of iteration if failed
if (_simplify) { if (_simplify) {
// if further simplification fails then skip rest of iteration // if further simplification fails then skip rest of iteration
Timer timer3("Tokenizer::simplifyTokenList2", _settings.showtime, &S_timerResults); Timer timer3("Tokenizer::simplifyTokenList2", mSettings.showtime, &S_timerResults);
result = _tokenizer.simplifyTokenList2(); result = mTokenizer.simplifyTokenList2();
timer3.Stop(); timer3.Stop();
if (!result) if (!result)
continue; continue;
// Check simplified tokens // Check simplified tokens
checkSimplifiedTokens(_tokenizer); checkSimplifiedTokens(mTokenizer);
} }
} catch (const simplecpp::Output &o) { } catch (const simplecpp::Output &o) {
@ -432,17 +432,17 @@ unsigned int CppCheck::checkFile(const std::string& filename, const std::string
ErrorLogger::ErrorMessage::FileLocation loc; ErrorLogger::ErrorMessage::FileLocation loc;
if (e.token) { if (e.token) {
loc.line = e.token->linenr(); loc.line = e.token->linenr();
const std::string fixedpath = Path::toNativeSeparators(_tokenizer.list.file(e.token)); const std::string fixedpath = Path::toNativeSeparators(mTokenizer.list.file(e.token));
loc.setfile(fixedpath); loc.setfile(fixedpath);
} else { } else {
ErrorLogger::ErrorMessage::FileLocation loc2; ErrorLogger::ErrorMessage::FileLocation loc2;
loc2.setfile(Path::toNativeSeparators(filename)); loc2.setfile(Path::toNativeSeparators(filename));
locationList.push_back(loc2); locationList.push_back(loc2);
loc.setfile(_tokenizer.list.getSourceFilePath()); loc.setfile(mTokenizer.list.getSourceFilePath());
} }
locationList.push_back(loc); locationList.push_back(loc);
ErrorLogger::ErrorMessage errmsg(locationList, ErrorLogger::ErrorMessage errmsg(locationList,
_tokenizer.list.getSourceFilePath(), mTokenizer.list.getSourceFilePath(),
Severity::error, Severity::error,
e.errorMessage, e.errorMessage,
e.id, e.id,
@ -452,7 +452,7 @@ unsigned int CppCheck::checkFile(const std::string& filename, const std::string
} }
} }
if (!hasValidConfig && configurations.size() > 1 && _settings.isEnabled(Settings::INFORMATION)) { if (!hasValidConfig && configurations.size() > 1 && mSettings.isEnabled(Settings::INFORMATION)) {
std::string msg; std::string msg;
msg = "This file is not analyzed. Cppcheck failed to extract a valid configuration. Use -v for more details."; msg = "This file is not analyzed. Cppcheck failed to extract a valid configuration. Use -v for more details.";
msg += "\nThis file is not analyzed. Cppcheck failed to extract a valid configuration. The tested configurations have these preprocessor errors:"; msg += "\nThis file is not analyzed. Cppcheck failed to extract a valid configuration. The tested configurations have these preprocessor errors:";
@ -473,7 +473,7 @@ unsigned int CppCheck::checkFile(const std::string& filename, const std::string
} }
// dumped all configs, close root </dumps> element now // dumped all configs, close root </dumps> element now
if (_settings.dump && fdump.is_open()) if (mSettings.dump && fdump.is_open())
fdump << "</dumps>" << std::endl; fdump << "</dumps>" << std::endl;
} catch (const std::runtime_error &e) { } catch (const std::runtime_error &e) {
@ -490,8 +490,8 @@ unsigned int CppCheck::checkFile(const std::string& filename, const std::string
// In jointSuppressionReport mode, unmatched suppressions are // In jointSuppressionReport mode, unmatched suppressions are
// collected after all files are processed // collected after all files are processed
if (!_settings.jointSuppressionReport && (_settings.isEnabled(Settings::INFORMATION) || _settings.checkConfiguration)) { if (!mSettings.jointSuppressionReport && (mSettings.isEnabled(Settings::INFORMATION) || mSettings.checkConfiguration)) {
reportUnmatchedSuppressions(_settings.nomsg.getUnmatchedLocalSuppressions(filename, isUnusedFunctionCheckEnabled())); reportUnmatchedSuppressions(mSettings.nomsg.getUnmatchedLocalSuppressions(filename, isUnusedFunctionCheckEnabled()));
} }
_errorList.clear(); _errorList.clear();
@ -506,7 +506,7 @@ void CppCheck::internalError(const std::string &filename, const std::string &msg
const std::string fixedpath = Path::toNativeSeparators(filename); const std::string fixedpath = Path::toNativeSeparators(filename);
const std::string fullmsg("Bailing out from checking " + fixedpath + " since there was an internal error: " + msg); const std::string fullmsg("Bailing out from checking " + fixedpath + " since there was an internal error: " + msg);
if (_settings.isEnabled(Settings::INFORMATION)) { if (mSettings.isEnabled(Settings::INFORMATION)) {
const ErrorLogger::ErrorMessage::FileLocation loc1(filename, 0); const ErrorLogger::ErrorMessage::FileLocation loc1(filename, 0);
std::list<ErrorLogger::ErrorMessage::FileLocation> callstack(1, loc1); std::list<ErrorLogger::ErrorMessage::FileLocation> callstack(1, loc1);
@ -517,10 +517,10 @@ void CppCheck::internalError(const std::string &filename, const std::string &msg
"internalError", "internalError",
false); false);
_errorLogger.reportErr(errmsg); mErrorLogger.reportErr(errmsg);
} else { } else {
// Report on stdout // Report on stdout
_errorLogger.reportOut(fullmsg); mErrorLogger.reportOut(fullmsg);
} }
} }
@ -541,19 +541,19 @@ void CppCheck::checkNormalTokens(const Tokenizer &tokenizer)
{ {
// call all "runChecks" in all registered Check classes // call all "runChecks" in all registered Check classes
for (std::list<Check *>::const_iterator it = Check::instances().begin(); it != Check::instances().end(); ++it) { for (std::list<Check *>::const_iterator it = Check::instances().begin(); it != Check::instances().end(); ++it) {
if (_settings.terminated()) if (mSettings.terminated())
return; return;
if (tokenizer.isMaxTime()) if (tokenizer.isMaxTime())
return; return;
Timer timerRunChecks((*it)->name() + "::runChecks", _settings.showtime, &S_timerResults); Timer timerRunChecks((*it)->name() + "::runChecks", mSettings.showtime, &S_timerResults);
(*it)->runChecks(&tokenizer, &_settings, this); (*it)->runChecks(&tokenizer, &mSettings, this);
} }
// Analyse the tokens.. // Analyse the tokens..
for (std::list<Check *>::const_iterator it = Check::instances().begin(); it != Check::instances().end(); ++it) { for (std::list<Check *>::const_iterator it = Check::instances().begin(); it != Check::instances().end(); ++it) {
Check::FileInfo *fi = (*it)->getFileInfo(&tokenizer, &_settings); Check::FileInfo *fi = (*it)->getFileInfo(&tokenizer, &mSettings);
if (fi != nullptr) { if (fi != nullptr) {
fileInfo.push_back(fi); fileInfo.push_back(fi);
analyzerInformation.setFileInfo((*it)->name(), fi->toString()); analyzerInformation.setFileInfo((*it)->name(), fi->toString());
@ -571,18 +571,18 @@ void CppCheck::checkSimplifiedTokens(const Tokenizer &tokenizer)
{ {
// call all "runSimplifiedChecks" in all registered Check classes // call all "runSimplifiedChecks" in all registered Check classes
for (std::list<Check *>::const_iterator it = Check::instances().begin(); it != Check::instances().end(); ++it) { for (std::list<Check *>::const_iterator it = Check::instances().begin(); it != Check::instances().end(); ++it) {
if (_settings.terminated()) if (mSettings.terminated())
return; return;
if (tokenizer.isMaxTime()) if (tokenizer.isMaxTime())
return; return;
Timer timerSimpleChecks((*it)->name() + "::runSimplifiedChecks", _settings.showtime, &S_timerResults); Timer timerSimpleChecks((*it)->name() + "::runSimplifiedChecks", mSettings.showtime, &S_timerResults);
(*it)->runSimplifiedChecks(&tokenizer, &_settings, this); (*it)->runSimplifiedChecks(&tokenizer, &mSettings, this);
timerSimpleChecks.Stop(); timerSimpleChecks.Stop();
} }
if (!_settings.terminated()) if (!mSettings.terminated())
executeRules("simple", tokenizer); executeRules("simple", tokenizer);
} }
@ -594,7 +594,7 @@ void CppCheck::executeRules(const std::string &tokenlist, const Tokenizer &token
#ifdef HAVE_RULES #ifdef HAVE_RULES
// Are there rules to execute? // Are there rules to execute?
bool isrule = false; bool isrule = false;
for (std::list<Settings::Rule>::const_iterator it = _settings.rules.begin(); it != _settings.rules.end(); ++it) { for (std::list<Settings::Rule>::const_iterator it = mSettings.rules.begin(); it != mSettings.rules.end(); ++it) {
if (it->tokenlist == tokenlist) if (it->tokenlist == tokenlist)
isrule = true; isrule = true;
} }
@ -609,7 +609,7 @@ void CppCheck::executeRules(const std::string &tokenlist, const Tokenizer &token
ostr << " " << tok->str(); ostr << " " << tok->str();
const std::string str(ostr.str()); const std::string str(ostr.str());
for (std::list<Settings::Rule>::const_iterator it = _settings.rules.begin(); it != _settings.rules.end(); ++it) { for (std::list<Settings::Rule>::const_iterator it = mSettings.rules.begin(); it != mSettings.rules.end(); ++it) {
const Settings::Rule &rule = *it; const Settings::Rule &rule = *it;
if (rule.pattern.empty() || rule.id.empty() || rule.severity == Severity::none || rule.tokenlist != tokenlist) if (rule.pattern.empty() || rule.id.empty() || rule.severity == Severity::none || rule.tokenlist != tokenlist)
continue; continue;
@ -676,17 +676,17 @@ void CppCheck::executeRules(const std::string &tokenlist, const Tokenizer &token
Settings &CppCheck::settings() Settings &CppCheck::settings()
{ {
return _settings; return mSettings;
} }
void CppCheck::tooManyConfigsError(const std::string &file, const std::size_t numberOfConfigurations) void CppCheck::tooManyConfigsError(const std::string &file, const std::size_t numberOfConfigurations)
{ {
if (!_settings.isEnabled(Settings::INFORMATION) && !tooManyConfigs) if (!mSettings.isEnabled(Settings::INFORMATION) && !tooManyConfigs)
return; return;
tooManyConfigs = false; tooManyConfigs = false;
if (_settings.isEnabled(Settings::INFORMATION) && file.empty()) if (mSettings.isEnabled(Settings::INFORMATION) && file.empty())
return; return;
std::list<ErrorLogger::ErrorMessage::FileLocation> loclist; std::list<ErrorLogger::ErrorMessage::FileLocation> loclist;
@ -697,8 +697,8 @@ void CppCheck::tooManyConfigsError(const std::string &file, const std::size_t nu
} }
std::ostringstream msg; std::ostringstream msg;
msg << "Too many #ifdef configurations - cppcheck only checks " << _settings.maxConfigs; msg << "Too many #ifdef configurations - cppcheck only checks " << mSettings.maxConfigs;
if (numberOfConfigurations > _settings.maxConfigs) if (numberOfConfigurations > mSettings.maxConfigs)
msg << " of " << numberOfConfigurations << " configurations. Use --force to check all configurations.\n"; msg << " of " << numberOfConfigurations << " configurations. Use --force to check all configurations.\n";
if (file.empty()) if (file.empty())
msg << " configurations. Use --force to check all configurations. For more details, use --enable=information.\n"; msg << " configurations. Use --force to check all configurations. For more details, use --enable=information.\n";
@ -724,7 +724,7 @@ void CppCheck::purgedConfigurationMessage(const std::string &file, const std::st
{ {
tooManyConfigs = false; tooManyConfigs = false;
if (_settings.isEnabled(Settings::INFORMATION) && file.empty()) if (mSettings.isEnabled(Settings::INFORMATION) && file.empty())
return; return;
std::list<ErrorLogger::ErrorMessage::FileLocation> loclist; std::list<ErrorLogger::ErrorMessage::FileLocation> loclist;
@ -748,10 +748,10 @@ void CppCheck::purgedConfigurationMessage(const std::string &file, const std::st
void CppCheck::reportErr(const ErrorLogger::ErrorMessage &msg) void CppCheck::reportErr(const ErrorLogger::ErrorMessage &msg)
{ {
if (!_settings.library.reportErrors(msg.file0)) if (!mSettings.library.reportErrors(msg.file0))
return; return;
const std::string errmsg = msg.toString(_settings.verbose); const std::string errmsg = msg.toString(mSettings.verbose);
if (errmsg.empty()) if (errmsg.empty())
return; return;
@ -762,40 +762,40 @@ void CppCheck::reportErr(const ErrorLogger::ErrorMessage &msg)
const Suppressions::ErrorMessage errorMessage = msg.toSuppressionsErrorMessage(); const Suppressions::ErrorMessage errorMessage = msg.toSuppressionsErrorMessage();
if (_useGlobalSuppressions) { if (_useGlobalSuppressions) {
if (_settings.nomsg.isSuppressed(errorMessage)) if (mSettings.nomsg.isSuppressed(errorMessage))
return; return;
} else { } else {
if (_settings.nomsg.isSuppressedLocal(errorMessage)) if (mSettings.nomsg.isSuppressedLocal(errorMessage))
return; return;
} }
if (!_settings.nofail.isSuppressed(errorMessage) && (_useGlobalSuppressions || !_settings.nomsg.isSuppressed(errorMessage))) if (!mSettings.nofail.isSuppressed(errorMessage) && (_useGlobalSuppressions || !mSettings.nomsg.isSuppressed(errorMessage)))
exitcode = 1; exitcode = 1;
_errorList.push_back(errmsg); _errorList.push_back(errmsg);
_errorLogger.reportErr(msg); mErrorLogger.reportErr(msg);
analyzerInformation.reportErr(msg, _settings.verbose); analyzerInformation.reportErr(msg, mSettings.verbose);
if (!_settings.plistOutput.empty() && plistFile.is_open()) { if (!mSettings.plistOutput.empty() && plistFile.is_open()) {
plistFile << ErrorLogger::plistData(msg); plistFile << ErrorLogger::plistData(msg);
} }
} }
void CppCheck::reportOut(const std::string &outmsg) void CppCheck::reportOut(const std::string &outmsg)
{ {
_errorLogger.reportOut(outmsg); mErrorLogger.reportOut(outmsg);
} }
void CppCheck::reportProgress(const std::string &filename, const char stage[], const std::size_t value) void CppCheck::reportProgress(const std::string &filename, const char stage[], const std::size_t value)
{ {
_errorLogger.reportProgress(filename, stage, value); mErrorLogger.reportProgress(filename, stage, value);
} }
void CppCheck::reportInfo(const ErrorLogger::ErrorMessage &msg) void CppCheck::reportInfo(const ErrorLogger::ErrorMessage &msg)
{ {
const Suppressions::ErrorMessage &errorMessage = msg.toSuppressionsErrorMessage(); const Suppressions::ErrorMessage &errorMessage = msg.toSuppressionsErrorMessage();
if (!_settings.nomsg.isSuppressed(errorMessage)) if (!mSettings.nomsg.isSuppressed(errorMessage))
_errorLogger.reportInfo(msg); mErrorLogger.reportInfo(msg);
} }
void CppCheck::reportStatus(unsigned int /*fileindex*/, unsigned int /*filecount*/, std::size_t /*sizedone*/, std::size_t /*sizetotal*/) void CppCheck::reportStatus(unsigned int /*fileindex*/, unsigned int /*filecount*/, std::size_t /*sizedone*/, std::size_t /*sizetotal*/)
@ -805,7 +805,7 @@ void CppCheck::reportStatus(unsigned int /*fileindex*/, unsigned int /*filecount
void CppCheck::getErrorMessages() void CppCheck::getErrorMessages()
{ {
Settings s(_settings); Settings s(mSettings);
s.addEnabled("warning"); s.addEnabled("warning");
s.addEnabled("style"); s.addEnabled("style");
s.addEnabled("portability"); s.addEnabled("portability");
@ -829,7 +829,7 @@ bool CppCheck::analyseWholeProgram()
bool errors = false; bool errors = false;
// Analyse the tokens // Analyse the tokens
for (std::list<Check *>::const_iterator it = Check::instances().begin(); it != Check::instances().end(); ++it) for (std::list<Check *>::const_iterator it = Check::instances().begin(); it != Check::instances().end(); ++it)
errors |= (*it)->analyseWholeProgram(fileInfo, _settings, *this); errors |= (*it)->analyseWholeProgram(fileInfo, mSettings, *this);
return errors && (exitcode > 0); return errors && (exitcode > 0);
} }
@ -838,7 +838,7 @@ void CppCheck::analyseWholeProgram(const std::string &buildDir, const std::map<s
(void)files; (void)files;
if (buildDir.empty()) if (buildDir.empty())
return; return;
if (_settings.isEnabled(Settings::UNUSED_FUNCTION)) if (mSettings.isEnabled(Settings::UNUSED_FUNCTION))
CheckUnusedFunctions::analyseWholeProgram(this, buildDir); CheckUnusedFunctions::analyseWholeProgram(this, buildDir);
std::list<Check::FileInfo*> fileInfoList; std::list<Check::FileInfo*> fileInfoList;
@ -880,7 +880,7 @@ void CppCheck::analyseWholeProgram(const std::string &buildDir, const std::map<s
// Analyse the tokens // Analyse the tokens
for (std::list<Check *>::const_iterator it = Check::instances().begin(); it != Check::instances().end(); ++it) for (std::list<Check *>::const_iterator it = Check::instances().begin(); it != Check::instances().end(); ++it)
(*it)->analyseWholeProgram(fileInfoList, _settings, *this); (*it)->analyseWholeProgram(fileInfoList, mSettings, *this);
for (std::list<Check::FileInfo*>::iterator fi = fileInfoList.begin(); fi != fileInfoList.end(); ++fi) for (std::list<Check::FileInfo*>::iterator fi = fileInfoList.begin(); fi != fileInfoList.end(); ++fi)
delete (*fi); delete (*fi);
@ -888,5 +888,5 @@ void CppCheck::analyseWholeProgram(const std::string &buildDir, const std::map<s
bool CppCheck::isUnusedFunctionCheckEnabled() const bool CppCheck::isUnusedFunctionCheckEnabled() const
{ {
return (_settings.jobs == 1 && _settings.isEnabled(Settings::UNUSED_FUNCTION)); return (mSettings.jobs == 1 && mSettings.isEnabled(Settings::UNUSED_FUNCTION));
} }

View File

@ -113,7 +113,7 @@ public:
* @brief Terminate checking. The checking will be terminated as soon as possible. * @brief Terminate checking. The checking will be terminated as soon as possible.
*/ */
void terminate() { void terminate() {
_settings.terminate(); mSettings.terminate();
} }
/** /**
@ -199,7 +199,7 @@ private:
virtual void reportOut(const std::string &outmsg) override; virtual void reportOut(const std::string &outmsg) override;
std::list<std::string> _errorList; std::list<std::string> _errorList;
Settings _settings; Settings mSettings;
void reportProgress(const std::string &filename, const char stage[], const std::size_t value) override; void reportProgress(const std::string &filename, const char stage[], const std::size_t value) override;
@ -208,7 +208,7 @@ private:
*/ */
virtual void reportInfo(const ErrorLogger::ErrorMessage &msg) override; virtual void reportInfo(const ErrorLogger::ErrorMessage &msg) override;
ErrorLogger &_errorLogger; ErrorLogger &mErrorLogger;
/** @brief Current preprocessor configuration */ /** @brief Current preprocessor configuration */
std::string cfg; std::string cfg;

View File

@ -57,7 +57,7 @@ bool Preprocessor::missingSystemIncludeFlag;
char Preprocessor::macroChar = char(1); char Preprocessor::macroChar = char(1);
Preprocessor::Preprocessor(Settings& settings, ErrorLogger *errorLogger) : _settings(settings), _errorLogger(errorLogger) Preprocessor::Preprocessor(Settings& settings, ErrorLogger *errorLogger) : mSettings(settings), mErrorLogger(errorLogger)
{ {
} }
@ -75,7 +75,7 @@ namespace {
}; };
} }
static void inlineSuppressions(const simplecpp::TokenList &tokens, Settings &_settings, std::list<BadInlineSuppression> *bad) static void inlineSuppressions(const simplecpp::TokenList &tokens, Settings &mSettings, std::list<BadInlineSuppression> *bad)
{ {
std::list<Suppressions::Suppression> inlineSuppressions; std::list<Suppressions::Suppression> inlineSuppressions;
for (const simplecpp::Token *tok = tokens.cfront(); tok; tok = tok->next) { for (const simplecpp::Token *tok = tokens.cfront(); tok; tok = tok->next) {
@ -96,9 +96,9 @@ static void inlineSuppressions(const simplecpp::TokenList &tokens, Settings &_se
// Relative filename // Relative filename
std::string relativeFilename(tok->location.file()); std::string relativeFilename(tok->location.file());
if (_settings.relativePaths) { if (mSettings.relativePaths) {
for (std::size_t j = 0U; j < _settings.basePaths.size(); ++j) { for (std::size_t j = 0U; j < mSettings.basePaths.size(); ++j) {
const std::string bp = _settings.basePaths[j] + "/"; const std::string bp = mSettings.basePaths[j] + "/";
if (relativeFilename.compare(0,bp.size(),bp)==0) { if (relativeFilename.compare(0,bp.size(),bp)==0) {
relativeFilename = relativeFilename.substr(bp.size()); relativeFilename = relativeFilename.substr(bp.size());
} }
@ -110,7 +110,7 @@ static void inlineSuppressions(const simplecpp::TokenList &tokens, Settings &_se
for (Suppressions::Suppression &suppr : inlineSuppressions) { for (Suppressions::Suppression &suppr : inlineSuppressions) {
suppr.fileName = relativeFilename; suppr.fileName = relativeFilename;
suppr.lineNumber = tok->location.line; suppr.lineNumber = tok->location.line;
_settings.nomsg.addSuppression(suppr); mSettings.nomsg.addSuppression(suppr);
} }
inlineSuppressions.clear(); inlineSuppressions.clear();
} }
@ -118,13 +118,13 @@ static void inlineSuppressions(const simplecpp::TokenList &tokens, Settings &_se
void Preprocessor::inlineSuppressions(const simplecpp::TokenList &tokens) void Preprocessor::inlineSuppressions(const simplecpp::TokenList &tokens)
{ {
if (!_settings.inlineSuppressions) if (!mSettings.inlineSuppressions)
return; return;
std::list<BadInlineSuppression> err; std::list<BadInlineSuppression> err;
::inlineSuppressions(tokens, _settings, &err); ::inlineSuppressions(tokens, mSettings, &err);
for (std::map<std::string,simplecpp::TokenList*>::const_iterator it = tokenlists.begin(); it != tokenlists.end(); ++it) { for (std::map<std::string,simplecpp::TokenList*>::const_iterator it = tokenlists.begin(); it != tokenlists.end(); ++it) {
if (it->second) if (it->second)
::inlineSuppressions(*it->second, _settings, &err); ::inlineSuppressions(*it->second, mSettings, &err);
} }
for (const BadInlineSuppression &bad : err) { for (const BadInlineSuppression &bad : err) {
error(bad.location.file(), bad.location.line, bad.errmsg); error(bad.location.file(), bad.location.line, bad.errmsg);
@ -430,11 +430,11 @@ std::set<std::string> Preprocessor::getConfigs(const simplecpp::TokenList &token
std::set<std::string> defined = { "__cplusplus" }; std::set<std::string> defined = { "__cplusplus" };
::getConfigs(tokens, defined, _settings.userDefines, _settings.userUndefs, ret); ::getConfigs(tokens, defined, mSettings.userDefines, mSettings.userUndefs, ret);
for (std::map<std::string, simplecpp::TokenList*>::const_iterator it = tokenlists.begin(); it != tokenlists.end(); ++it) { for (std::map<std::string, simplecpp::TokenList*>::const_iterator it = tokenlists.begin(); it != tokenlists.end(); ++it) {
if (!_settings.configurationExcluded(it->first)) if (!mSettings.configurationExcluded(it->first))
::getConfigs(*(it->second), defined, _settings.userDefines, _settings.userUndefs, ret); ::getConfigs(*(it->second), defined, mSettings.userDefines, mSettings.userUndefs, ret);
} }
return ret; return ret;
@ -452,7 +452,7 @@ void Preprocessor::preprocess(std::istream &istr, std::map<std::string, std::str
const std::set<std::string> configs = getConfigs(tokens1); const std::set<std::string> configs = getConfigs(tokens1);
for (std::set<std::string>::const_iterator it = configs.begin(); it != configs.end(); ++it) { for (std::set<std::string>::const_iterator it = configs.begin(); it != configs.end(); ++it) {
if (_settings.userUndefs.find(*it) == _settings.userUndefs.end()) { if (mSettings.userUndefs.find(*it) == mSettings.userUndefs.end()) {
result[ *it ] = getcode(tokens1, *it, files, false); result[ *it ] = getcode(tokens1, *it, files, false);
} }
} }
@ -520,15 +520,15 @@ static void splitcfg(const std::string &cfg, std::list<std::string> &defines, co
} }
} }
static simplecpp::DUI createDUI(const Settings &_settings, const std::string &cfg, const std::string &filename) static simplecpp::DUI createDUI(const Settings &mSettings, const std::string &cfg, const std::string &filename)
{ {
simplecpp::DUI dui; simplecpp::DUI dui;
splitcfg(_settings.userDefines, dui.defines, "1"); splitcfg(mSettings.userDefines, dui.defines, "1");
if (!cfg.empty()) if (!cfg.empty())
splitcfg(cfg, dui.defines, emptyString); splitcfg(cfg, dui.defines, emptyString);
for (std::vector<std::string>::const_iterator it = _settings.library.defines.begin(); it != _settings.library.defines.end(); ++it) { for (std::vector<std::string>::const_iterator it = mSettings.library.defines.begin(); it != mSettings.library.defines.end(); ++it) {
if (it->compare(0,8,"#define ")!=0) if (it->compare(0,8,"#define ")!=0)
continue; continue;
std::string s = it->substr(8); std::string s = it->substr(8);
@ -548,9 +548,9 @@ static simplecpp::DUI createDUI(const Settings &_settings, const std::string &cf
if (Path::isCPP(filename)) if (Path::isCPP(filename))
dui.defines.push_back("__cplusplus"); dui.defines.push_back("__cplusplus");
dui.undefined = _settings.userUndefs; // -U dui.undefined = mSettings.userUndefs; // -U
dui.includePaths = _settings.includePaths; // -I dui.includePaths = mSettings.includePaths; // -I
dui.includes = _settings.userIncludes; // --include dui.includes = mSettings.userIncludes; // --include
return dui; return dui;
} }
@ -575,7 +575,7 @@ static bool hasErrors(const simplecpp::OutputList &outputList)
void Preprocessor::loadFiles(const simplecpp::TokenList &rawtokens, std::vector<std::string> &files) void Preprocessor::loadFiles(const simplecpp::TokenList &rawtokens, std::vector<std::string> &files)
{ {
const simplecpp::DUI dui = createDUI(_settings, emptyString, files[0]); const simplecpp::DUI dui = createDUI(mSettings, emptyString, files[0]);
tokenlists = simplecpp::load(rawtokens, files, dui, nullptr); tokenlists = simplecpp::load(rawtokens, files, dui, nullptr);
} }
@ -590,34 +590,34 @@ void Preprocessor::removeComments()
void Preprocessor::setPlatformInfo(simplecpp::TokenList *tokens) const void Preprocessor::setPlatformInfo(simplecpp::TokenList *tokens) const
{ {
tokens->sizeOfType["bool"] = _settings.sizeof_bool; tokens->sizeOfType["bool"] = mSettings.sizeof_bool;
tokens->sizeOfType["short"] = _settings.sizeof_short; tokens->sizeOfType["short"] = mSettings.sizeof_short;
tokens->sizeOfType["int"] = _settings.sizeof_int; tokens->sizeOfType["int"] = mSettings.sizeof_int;
tokens->sizeOfType["long"] = _settings.sizeof_long; tokens->sizeOfType["long"] = mSettings.sizeof_long;
tokens->sizeOfType["long long"] = _settings.sizeof_long_long; tokens->sizeOfType["long long"] = mSettings.sizeof_long_long;
tokens->sizeOfType["float"] = _settings.sizeof_float; tokens->sizeOfType["float"] = mSettings.sizeof_float;
tokens->sizeOfType["double"] = _settings.sizeof_double; tokens->sizeOfType["double"] = mSettings.sizeof_double;
tokens->sizeOfType["long double"] = _settings.sizeof_long_double; tokens->sizeOfType["long double"] = mSettings.sizeof_long_double;
tokens->sizeOfType["bool *"] = _settings.sizeof_pointer; tokens->sizeOfType["bool *"] = mSettings.sizeof_pointer;
tokens->sizeOfType["short *"] = _settings.sizeof_pointer; tokens->sizeOfType["short *"] = mSettings.sizeof_pointer;
tokens->sizeOfType["int *"] = _settings.sizeof_pointer; tokens->sizeOfType["int *"] = mSettings.sizeof_pointer;
tokens->sizeOfType["long *"] = _settings.sizeof_pointer; tokens->sizeOfType["long *"] = mSettings.sizeof_pointer;
tokens->sizeOfType["long long *"] = _settings.sizeof_pointer; tokens->sizeOfType["long long *"] = mSettings.sizeof_pointer;
tokens->sizeOfType["float *"] = _settings.sizeof_pointer; tokens->sizeOfType["float *"] = mSettings.sizeof_pointer;
tokens->sizeOfType["double *"] = _settings.sizeof_pointer; tokens->sizeOfType["double *"] = mSettings.sizeof_pointer;
tokens->sizeOfType["long double *"] = _settings.sizeof_pointer; tokens->sizeOfType["long double *"] = mSettings.sizeof_pointer;
} }
simplecpp::TokenList Preprocessor::preprocess(const simplecpp::TokenList &tokens1, const std::string &cfg, std::vector<std::string> &files, bool throwError) simplecpp::TokenList Preprocessor::preprocess(const simplecpp::TokenList &tokens1, const std::string &cfg, std::vector<std::string> &files, bool throwError)
{ {
const simplecpp::DUI dui = createDUI(_settings, cfg, files[0]); const simplecpp::DUI dui = createDUI(mSettings, cfg, files[0]);
simplecpp::OutputList outputList; simplecpp::OutputList outputList;
std::list<simplecpp::MacroUsage> macroUsage; std::list<simplecpp::MacroUsage> macroUsage;
simplecpp::TokenList tokens2(files); simplecpp::TokenList tokens2(files);
simplecpp::preprocess(tokens2, tokens1, files, tokenlists, dui, &outputList, &macroUsage); simplecpp::preprocess(tokens2, tokens1, files, tokenlists, dui, &outputList, &macroUsage);
const bool showerror = (!_settings.userDefines.empty() && !_settings.force); const bool showerror = (!mSettings.userDefines.empty() && !mSettings.force);
reportOutput(outputList, showerror); reportOutput(outputList, showerror);
if (throwError && hasErrors(outputList)) { if (throwError && hasErrors(outputList)) {
for (const simplecpp::Output &output : outputList) { for (const simplecpp::Output &output : outputList) {
@ -731,7 +731,7 @@ void Preprocessor::error(const std::string &filename, unsigned int linenr, const
const ErrorLogger::ErrorMessage::FileLocation loc(filename, linenr); const ErrorLogger::ErrorMessage::FileLocation loc(filename, linenr);
locationList.push_back(loc); locationList.push_back(loc);
} }
_errorLogger->reportErr(ErrorLogger::ErrorMessage(locationList, mErrorLogger->reportErr(ErrorLogger::ErrorMessage(locationList,
file0, file0,
Severity::error, Severity::error,
msg, msg,
@ -747,17 +747,17 @@ void Preprocessor::missingInclude(const std::string &filename, unsigned int line
errorMessage.errorId = "missingInclude"; errorMessage.errorId = "missingInclude";
errorMessage.setFileName(fname); errorMessage.setFileName(fname);
errorMessage.lineNumber = linenr; errorMessage.lineNumber = linenr;
if (_settings.nomsg.isSuppressed(errorMessage)) if (mSettings.nomsg.isSuppressed(errorMessage))
return; return;
errorMessage.errorId = "missingIncludeSystem"; errorMessage.errorId = "missingIncludeSystem";
if (headerType == SystemHeader && _settings.nomsg.isSuppressed(errorMessage)) if (headerType == SystemHeader && mSettings.nomsg.isSuppressed(errorMessage))
return; return;
if (headerType == SystemHeader) if (headerType == SystemHeader)
missingSystemIncludeFlag = true; missingSystemIncludeFlag = true;
else else
missingIncludeFlag = true; missingIncludeFlag = true;
if (_errorLogger && _settings.checkConfiguration) { if (mErrorLogger && mSettings.checkConfiguration) {
std::list<ErrorLogger::ErrorMessage::FileLocation> locationList; std::list<ErrorLogger::ErrorMessage::FileLocation> locationList;
if (!filename.empty()) { if (!filename.empty()) {
@ -772,7 +772,7 @@ void Preprocessor::missingInclude(const std::string &filename, unsigned int line
"Include file: \"" + header + "\" not found.", "Include file: \"" + header + "\" not found.",
(headerType==SystemHeader) ? "missingIncludeSystem" : "missingInclude", (headerType==SystemHeader) ? "missingIncludeSystem" : "missingInclude",
false); false);
_errorLogger->reportInfo(errmsg); mErrorLogger->reportInfo(errmsg);
} }
} }
@ -797,7 +797,7 @@ bool Preprocessor::validateCfg(const std::string &cfg, const std::list<simplecpp
} }
} }
if (!directiveLocation) { if (!directiveLocation) {
if (_settings.isEnabled(Settings::INFORMATION)) if (mSettings.isEnabled(Settings::INFORMATION))
validateCfgError(mu.useLocation.file(), mu.useLocation.line, cfg, macroName); validateCfgError(mu.useLocation.file(), mu.useLocation.line, cfg, macroName);
ret = false; ret = false;
} }
@ -814,7 +814,7 @@ void Preprocessor::validateCfgError(const std::string &file, const unsigned int
const ErrorLogger::ErrorMessage::FileLocation loc(file, line); const ErrorLogger::ErrorMessage::FileLocation loc(file, line);
locationList.push_back(loc); locationList.push_back(loc);
const ErrorLogger::ErrorMessage errmsg(locationList, file0, Severity::information, "Skipping configuration '" + cfg + "' since the value of '" + macro + "' is unknown. Use -D if you want to check it. You can use -U to skip it explicitly.", id, false); const ErrorLogger::ErrorMessage errmsg(locationList, file0, Severity::information, "Skipping configuration '" + cfg + "' since the value of '" + macro + "' is unknown. Use -D if you want to check it. You can use -U to skip it explicitly.", id, false);
_errorLogger->reportInfo(errmsg); mErrorLogger->reportInfo(errmsg);
} }
void Preprocessor::getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) void Preprocessor::getErrorMessages(ErrorLogger *errorLogger, const Settings *settings)

View File

@ -206,8 +206,8 @@ private:
void missingInclude(const std::string &filename, unsigned int linenr, const std::string &header, HeaderTypes headerType); 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); void error(const std::string &filename, unsigned int linenr, const std::string &msg);
Settings& _settings; Settings& mSettings;
ErrorLogger *_errorLogger; ErrorLogger *mErrorLogger;
/** list of all directives met while preprocessing file */ /** list of all directives met while preprocessing file */
std::list<Directive> directives; std::list<Directive> directives;

View File

@ -36,13 +36,13 @@
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: _tokenizer(tokenizer), _settings(settings), _errorLogger(errorLogger) : mTokenizer(tokenizer), mSettings(settings), mErrorLogger(errorLogger)
{ {
cpp = isCPP(); cpp = isCPP();
if (_settings->defaultSign == 's' || _settings->defaultSign == 'S') if (mSettings->defaultSign == 's' || mSettings->defaultSign == 'S')
defaultSignedness = ValueType::SIGNED; defaultSignedness = ValueType::SIGNED;
else if (_settings->defaultSign == 'u' || _settings->defaultSign == 'U') else if (mSettings->defaultSign == 'u' || mSettings->defaultSign == 'U')
defaultSignedness = ValueType::UNSIGNED; defaultSignedness = ValueType::UNSIGNED;
else else
defaultSignedness = ValueType::UNKNOWN_SIGN; defaultSignedness = ValueType::UNKNOWN_SIGN;
@ -92,23 +92,23 @@ void SymbolDatabase::createSymbolDatabaseFindAllScopes()
std::map<const Scope*, AccessControl> access; std::map<const Scope*, AccessControl> access;
// find all scopes // find all scopes
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok ? tok->next() : nullptr) { for (const Token *tok = mTokenizer->tokens(); tok; tok = tok ? tok->next() : nullptr) {
// #5593 suggested to add here: // #5593 suggested to add here:
if (_errorLogger) if (mErrorLogger)
_errorLogger->reportProgress(_tokenizer->list.getSourceFilePath(), mErrorLogger->reportProgress(mTokenizer->list.getSourceFilePath(),
"SymbolDatabase", "SymbolDatabase",
tok->progressValue()); tok->progressValue());
// Locate next class // Locate next class
if ((_tokenizer->isCPP() && ((Token::Match(tok, "class|struct|union|namespace ::| %name% {|:|::|<") && if ((mTokenizer->isCPP() && ((Token::Match(tok, "class|struct|union|namespace ::| %name% {|:|::|<") &&
!Token::Match(tok->previous(), "new|friend|const|enum|typedef|mutable|volatile|)|(|<")) || !Token::Match(tok->previous(), "new|friend|const|enum|typedef|mutable|volatile|)|(|<")) ||
(Token::Match(tok, "enum class| %name% {") || (Token::Match(tok, "enum class| %name% {") ||
Token::Match(tok, "enum class| %name% : %name% {")))) Token::Match(tok, "enum class| %name% : %name% {"))))
|| (_tokenizer->isC() && Token::Match(tok, "struct|union|enum %name% {"))) { || (mTokenizer->isC() && Token::Match(tok, "struct|union|enum %name% {"))) {
const Token *tok2 = tok->tokAt(2); const Token *tok2 = tok->tokAt(2);
if (tok->strAt(1) == "::") if (tok->strAt(1) == "::")
tok2 = tok2->next(); tok2 = tok2->next();
else if (_tokenizer->isCPP() && tok->strAt(1) == "class") else if (mTokenizer->isCPP() && tok->strAt(1) == "class")
tok2 = tok2->next(); tok2 = tok2->next();
while (Token::Match(tok2, ":: %name%")) while (Token::Match(tok2, ":: %name%"))
@ -124,7 +124,7 @@ void SymbolDatabase::createSymbolDatabaseFindAllScopes()
} }
// skip over final // skip over final
if (_tokenizer->isCPP() && Token::simpleMatch(tok2, "final")) if (mTokenizer->isCPP() && Token::simpleMatch(tok2, "final"))
tok2 = tok2->next(); tok2 = tok2->next();
// make sure we have valid code // make sure we have valid code
@ -142,7 +142,7 @@ void SymbolDatabase::createSymbolDatabaseFindAllScopes()
// skip variable declaration // skip variable declaration
else if (Token::Match(tok2, "*|&|>")) else if (Token::Match(tok2, "*|&|>"))
continue; continue;
else if (Token::Match(tok2, "%name% (") && _tokenizer->isFunctionHead(tok2->next(), "{;")) else if (Token::Match(tok2, "%name% (") && mTokenizer->isFunctionHead(tok2->next(), "{;"))
continue; continue;
else if (Token::Match(tok2, "%name% [")) else if (Token::Match(tok2, "%name% ["))
continue; continue;
@ -183,7 +183,7 @@ void SymbolDatabase::createSymbolDatabaseFindAllScopes()
if (new_scope->isClassOrStruct()) { if (new_scope->isClassOrStruct()) {
// goto initial '{' // goto initial '{'
if (!new_scope->definedType) if (!new_scope->definedType)
_tokenizer->syntaxError(nullptr); // #6808 mTokenizer->syntaxError(nullptr); // #6808
tok2 = new_scope->definedType->initBaseInfo(tok, tok2); tok2 = new_scope->definedType->initBaseInfo(tok, tok2);
// make sure we have valid code // make sure we have valid code
if (!tok2) { if (!tok2) {
@ -192,7 +192,7 @@ void SymbolDatabase::createSymbolDatabaseFindAllScopes()
} }
// definition may be different than declaration // definition may be different than declaration
if (_tokenizer->isCPP() && tok->str() == "class") { if (mTokenizer->isCPP() && tok->str() == "class") {
access[new_scope] = Private; access[new_scope] = Private;
new_scope->type = Scope::eClass; new_scope->type = Scope::eClass;
} else if (tok->str() == "struct") { } else if (tok->str() == "struct") {
@ -205,7 +205,7 @@ void SymbolDatabase::createSymbolDatabaseFindAllScopes()
new_scope->bodyEnd = tok2->link(); new_scope->bodyEnd = tok2->link();
// make sure we have valid code // make sure we have valid code
if (!new_scope->bodyEnd) { if (!new_scope->bodyEnd) {
_tokenizer->syntaxError(tok); mTokenizer->syntaxError(tok);
} }
scope = new_scope; scope = new_scope;
tok = tok2; tok = tok2;
@ -237,7 +237,7 @@ void SymbolDatabase::createSymbolDatabaseFindAllScopes()
// make sure we have valid code // make sure we have valid code
if (!tok2) { if (!tok2) {
_tokenizer->syntaxError(tok); mTokenizer->syntaxError(tok);
} }
} else if (new_scope->type == Scope::eEnum) { } else if (new_scope->type == Scope::eEnum) {
if (tok2->str() == ":") if (tok2->str() == ":")
@ -249,15 +249,15 @@ void SymbolDatabase::createSymbolDatabaseFindAllScopes()
// make sure we have valid code // make sure we have valid code
if (!new_scope->bodyEnd) { if (!new_scope->bodyEnd) {
_tokenizer->syntaxError(tok); mTokenizer->syntaxError(tok);
} }
if (new_scope->type == Scope::eEnum) { if (new_scope->type == Scope::eEnum) {
tok2 = new_scope->addEnum(tok, _tokenizer->isCPP()); tok2 = new_scope->addEnum(tok, mTokenizer->isCPP());
scope->nestedList.push_back(new_scope); scope->nestedList.push_back(new_scope);
if (!tok2) if (!tok2)
_tokenizer->syntaxError(tok); mTokenizer->syntaxError(tok);
} else { } else {
// make the new scope the current scope // make the new scope the current scope
scope->nestedList.push_back(new_scope); scope->nestedList.push_back(new_scope);
@ -269,7 +269,7 @@ void SymbolDatabase::createSymbolDatabaseFindAllScopes()
} }
// Namespace and unknown macro (#3854) // Namespace and unknown macro (#3854)
else if (_tokenizer->isCPP() && else if (mTokenizer->isCPP() &&
Token::Match(tok, "namespace %name% %type% (") && Token::Match(tok, "namespace %name% %type% (") &&
tok->tokAt(2)->isUpperCaseName() && tok->tokAt(2)->isUpperCaseName() &&
Token::simpleMatch(tok->linkAt(3), ") {")) { Token::simpleMatch(tok->linkAt(3), ") {")) {
@ -309,7 +309,7 @@ void SymbolDatabase::createSymbolDatabaseFindAllScopes()
} }
// using namespace // using namespace
else if (_tokenizer->isCPP() && Token::Match(tok, "using namespace ::| %type% ;|::")) { else if (mTokenizer->isCPP() && Token::Match(tok, "using namespace ::| %type% ;|::")) {
Scope::UsingInfo using_info; Scope::UsingInfo using_info;
using_info.start = tok; // save location using_info.start = tok; // save location
@ -329,7 +329,7 @@ void SymbolDatabase::createSymbolDatabaseFindAllScopes()
} }
// using type alias // using type alias
else if (_tokenizer->isCPP() && Token::Match(tok, "using %name% =")) { else if (mTokenizer->isCPP() && Token::Match(tok, "using %name% =")) {
if (tok->strAt(-1) != ">" && !findType(tok->next(), scope)) { if (tok->strAt(-1) != ">" && !findType(tok->next(), scope)) {
// fill typeList.. // fill typeList..
typeList.emplace_back(tok, nullptr, scope); typeList.emplace_back(tok, nullptr, scope);
@ -365,7 +365,7 @@ void SymbolDatabase::createSymbolDatabaseFindAllScopes()
scope->definedTypesMap[new_type->name()] = new_type; scope->definedTypesMap[new_type->name()] = new_type;
} }
scope->addVariable(varNameTok, tok, tok, access[scope], new_scope->definedType, scope, &_settings->library); scope->addVariable(varNameTok, tok, tok, access[scope], new_scope->definedType, scope, &mSettings->library);
const Token *tok2 = tok->next(); const Token *tok2 = tok->next();
@ -461,7 +461,7 @@ void SymbolDatabase::createSymbolDatabaseFindAllScopes()
// class function? // class function?
else if (isFunction(tok, scope, &funcStart, &argStart, &declEnd)) { else if (isFunction(tok, scope, &funcStart, &argStart, &declEnd)) {
if (tok->previous()->str() != "::" || tok->strAt(-2) == scope->className) { if (tok->previous()->str() != "::" || tok->strAt(-2) == scope->className) {
Function function(_tokenizer, tok, scope, funcStart, argStart); Function function(mTokenizer, tok, scope, funcStart, argStart);
// save the access type // save the access type
function.access = access[scope]; function.access = access[scope];
@ -477,7 +477,7 @@ void SymbolDatabase::createSymbolDatabaseFindAllScopes()
function.arg = function.argDef; function.arg = function.argDef;
// out of line function // out of line function
if (const Token *endTok = _tokenizer->isFunctionHead(end, ";")) { if (const Token *endTok = mTokenizer->isFunctionHead(end, ";")) {
tok = endTok; tok = endTok;
scope->addFunction(function); scope->addFunction(function);
} }
@ -533,7 +533,7 @@ void SymbolDatabase::createSymbolDatabaseFindAllScopes()
} }
// friend class declaration? // friend class declaration?
else if (_tokenizer->isCPP() && Token::Match(tok, "friend class| ::| %any% ;|::")) { else if (mTokenizer->isCPP() && Token::Match(tok, "friend class| ::| %any% ;|::")) {
Type::FriendInfo friendInfo; Type::FriendInfo friendInfo;
// save the name start // save the name start
@ -552,7 +552,7 @@ void SymbolDatabase::createSymbolDatabaseFindAllScopes()
friendInfo.type = nullptr; friendInfo.type = nullptr;
if (!scope->definedType) if (!scope->definedType)
_tokenizer->syntaxError(tok); mTokenizer->syntaxError(tok);
scope->definedType->friendList.push_back(friendInfo); scope->definedType->friendList.push_back(friendInfo);
} }
@ -582,12 +582,12 @@ void SymbolDatabase::createSymbolDatabaseFindAllScopes()
Function* function = addGlobalFunction(scope, tok, argStart, funcStart); Function* function = addGlobalFunction(scope, tok, argStart, funcStart);
if (!function) if (!function)
_tokenizer->syntaxError(tok); mTokenizer->syntaxError(tok);
} }
// syntax error? // syntax error?
if (!scope) if (!scope)
_tokenizer->syntaxError(tok); mTokenizer->syntaxError(tok);
} }
// function prototype? // function prototype?
else if (declEnd && declEnd->str() == ";") { else if (declEnd && declEnd->str() == ";") {
@ -637,9 +637,9 @@ void SymbolDatabase::createSymbolDatabaseFindAllScopes()
scope->nestedList.push_back(&scopeList.back()); scope->nestedList.push_back(&scopeList.back());
scope = &scopeList.back(); scope = &scopeList.back();
if (scope->type == Scope::eFor) if (scope->type == Scope::eFor)
scope->checkVariable(tok->tokAt(2), Local, &_settings->library); // check for variable declaration and add it to new scope if found scope->checkVariable(tok->tokAt(2), Local, &mSettings->library); // check for variable declaration and add it to new scope if found
else if (scope->type == Scope::eCatch) else if (scope->type == Scope::eCatch)
scope->checkVariable(tok->tokAt(2), Throw, &_settings->library); // check for variable declaration and add it to new scope if found scope->checkVariable(tok->tokAt(2), Throw, &mSettings->library); // check for variable declaration and add it to new scope if found
tok = scopeStartTok; tok = scopeStartTok;
} else if (tok->str() == "{") { } else if (tok->str() == "{") {
if (tok->previous()->varId()) if (tok->previous()->varId())
@ -670,7 +670,7 @@ void SymbolDatabase::createSymbolDatabaseFindAllScopes()
void SymbolDatabase::createSymbolDatabaseClassInfo() void SymbolDatabase::createSymbolDatabaseClassInfo()
{ {
if (_tokenizer->isC()) if (mTokenizer->isC())
return; return;
// fill in using info // fill in using info
@ -696,7 +696,7 @@ void SymbolDatabase::createSymbolDatabaseClassInfo()
const Type* found = findType(it->derivedFrom[i].nameTok, it->enclosingScope); const Type* found = findType(it->derivedFrom[i].nameTok, it->enclosingScope);
if (found && found->findDependency(&(*it))) { if (found && found->findDependency(&(*it))) {
// circular dependency // circular dependency
//_tokenizer->syntaxError(nullptr); //mTokenizer->syntaxError(nullptr);
} else { } else {
it->derivedFrom[i].type = found; it->derivedFrom[i].type = found;
} }
@ -717,7 +717,7 @@ void SymbolDatabase::createSymbolDatabaseVariableInfo()
// fill in variable info // fill in variable info
for (std::list<Scope>::iterator it = scopeList.begin(); it != scopeList.end(); ++it) { for (std::list<Scope>::iterator it = scopeList.begin(); it != scopeList.end(); ++it) {
// find variables // find variables
it->getVariableList(&_settings->library); it->getVariableList(&mSettings->library);
} }
// fill in function arguments // fill in function arguments
@ -800,7 +800,7 @@ void SymbolDatabase::createSymbolDatabaseFunctionReturnTypes()
void SymbolDatabase::createSymbolDatabaseNeedInitialization() void SymbolDatabase::createSymbolDatabaseNeedInitialization()
{ {
if (_tokenizer->isC()) { if (mTokenizer->isC()) {
// For C code it is easy, as there are no constructors and no default values // For C code it is easy, as there are no constructors and no default values
for (std::list<Scope>::iterator it = scopeList.begin(); it != scopeList.end(); ++it) { for (std::list<Scope>::iterator it = scopeList.begin(); it != scopeList.end(); ++it) {
Scope *scope = &(*it); Scope *scope = &(*it);
@ -887,7 +887,7 @@ void SymbolDatabase::createSymbolDatabaseNeedInitialization()
} while (unknowns && retry < 100); } while (unknowns && retry < 100);
// this shouldn't happen so output a debug warning // this shouldn't happen so output a debug warning
if (retry == 100 && _settings->debugwarnings) { if (retry == 100 && mSettings->debugwarnings) {
for (std::list<Scope>::iterator it = scopeList.begin(); it != scopeList.end(); ++it) { for (std::list<Scope>::iterator it = scopeList.begin(); it != scopeList.end(); ++it) {
const Scope *scope = &(*it); const Scope *scope = &(*it);
@ -901,7 +901,7 @@ void SymbolDatabase::createSymbolDatabaseNeedInitialization()
void SymbolDatabase::createSymbolDatabaseVariableSymbolTable() void SymbolDatabase::createSymbolDatabaseVariableSymbolTable()
{ {
// create variable symbol table // create variable symbol table
_variableList.resize(_tokenizer->varIdCount() + 1); _variableList.resize(mTokenizer->varIdCount() + 1);
std::fill_n(_variableList.begin(), _variableList.size(), (const Variable*)nullptr); std::fill_n(_variableList.begin(), _variableList.size(), (const Variable*)nullptr);
// check all scopes for variables // check all scopes for variables
@ -973,8 +973,8 @@ void SymbolDatabase::createSymbolDatabaseSetScopePointers()
Token* start = const_cast<Token*>(it->bodyStart); Token* start = const_cast<Token*>(it->bodyStart);
Token* end = const_cast<Token*>(it->bodyEnd); Token* end = const_cast<Token*>(it->bodyEnd);
if (it->type == Scope::eGlobal) { if (it->type == Scope::eGlobal) {
start = const_cast<Token*>(_tokenizer->list.front()); start = const_cast<Token*>(mTokenizer->list.front());
end = const_cast<Token*>(_tokenizer->list.back()); end = const_cast<Token*>(mTokenizer->list.back());
} }
assert(start && end); assert(start && end);
@ -1018,7 +1018,7 @@ void SymbolDatabase::createSymbolDatabaseSetFunctionPointers(bool firstPass)
} }
// Set function call pointers // Set function call pointers
for (const Token* tok = _tokenizer->list.front(); tok != _tokenizer->list.back(); tok = tok->next()) { for (const Token* tok = mTokenizer->list.front(); tok != mTokenizer->list.back(); tok = tok->next()) {
if (!tok->function() && tok->varId() == 0 && Token::Match(tok, "%name% (") && !isReservedName(tok->str())) { if (!tok->function() && tok->varId() == 0 && Token::Match(tok, "%name% (") && !isReservedName(tok->str())) {
const Function *function = findFunction(tok); const Function *function = findFunction(tok);
if (function) if (function)
@ -1068,7 +1068,7 @@ void SymbolDatabase::createSymbolDatabaseSetTypePointers()
} }
// Set type pointers // Set type pointers
for (const Token* tok = _tokenizer->list.front(); tok != _tokenizer->list.back(); tok = tok->next()) { for (const Token* tok = mTokenizer->list.front(); tok != mTokenizer->list.back(); tok = tok->next()) {
if (!tok->isName() || tok->varId() || tok->function() || tok->type() || tok->enumerator()) if (!tok->isName() || tok->varId() || tok->function() || tok->type() || tok->enumerator())
continue; continue;
@ -1087,7 +1087,7 @@ void SymbolDatabase::fixVarId(VarIdMap & varIds, const Token * vartok, Token * m
if (varId == varIds.end()) { if (varId == varIds.end()) {
MemberIdMap memberId; MemberIdMap memberId;
if (membertok->varId() == 0) { if (membertok->varId() == 0) {
memberId[membervar->nameToken()->varId()] = const_cast<Tokenizer *>(_tokenizer)->newVarId(); memberId[membervar->nameToken()->varId()] = const_cast<Tokenizer *>(mTokenizer)->newVarId();
_variableList.push_back(membervar); _variableList.push_back(membervar);
} else } else
_variableList[membertok->varId()] = membervar; _variableList[membertok->varId()] = membervar;
@ -1097,7 +1097,7 @@ void SymbolDatabase::fixVarId(VarIdMap & varIds, const Token * vartok, Token * m
MemberIdMap::iterator memberId = varId->second.find(membervar->nameToken()->varId()); MemberIdMap::iterator memberId = varId->second.find(membervar->nameToken()->varId());
if (memberId == varId->second.end()) { if (memberId == varId->second.end()) {
if (membertok->varId() == 0) { if (membertok->varId() == 0) {
varId->second.insert(std::make_pair(membervar->nameToken()->varId(), const_cast<Tokenizer *>(_tokenizer)->newVarId())); varId->second.insert(std::make_pair(membervar->nameToken()->varId(), const_cast<Tokenizer *>(mTokenizer)->newVarId()));
_variableList.push_back(membervar); _variableList.push_back(membervar);
memberId = varId->second.find(membervar->nameToken()->varId()); memberId = varId->second.find(membervar->nameToken()->varId());
} else } else
@ -1112,7 +1112,7 @@ void SymbolDatabase::createSymbolDatabaseSetVariablePointers()
VarIdMap varIds; VarIdMap varIds;
// Set variable pointers // Set variable pointers
for (const Token* tok = _tokenizer->list.front(); tok != _tokenizer->list.back(); tok = tok->next()) { for (const Token* tok = mTokenizer->list.front(); tok != mTokenizer->list.back(); tok = tok->next()) {
if (tok->varId()) if (tok->varId())
const_cast<Token *>(tok)->variable(getVariableFromVarId(tok->varId())); const_cast<Token *>(tok)->variable(getVariableFromVarId(tok->varId()));
@ -1214,7 +1214,7 @@ void SymbolDatabase::createSymbolDatabaseEnums()
// look for initialization tokens that can be converted to enumerators and convert them // look for initialization tokens that can be converted to enumerators and convert them
if (enumerator.start) { if (enumerator.start) {
if (!enumerator.end) if (!enumerator.end)
_tokenizer->syntaxError(enumerator.start); mTokenizer->syntaxError(enumerator.start);
for (const Token * tok3 = enumerator.start; tok3 && tok3 != enumerator.end->next(); tok3 = tok3->next()) { for (const Token * tok3 = enumerator.start; tok3 && tok3 != enumerator.end->next(); tok3 = tok3->next()) {
if (tok3->tokType() == Token::eName) { if (tok3->tokType() == Token::eName) {
const Enumerator * e = findEnumerator(tok3); const Enumerator * e = findEnumerator(tok3);
@ -1228,7 +1228,7 @@ void SymbolDatabase::createSymbolDatabaseEnums()
const Token *rhs = enumerator.start->previous()->astOperand2(); const Token *rhs = enumerator.start->previous()->astOperand2();
// constant folding of expression: // constant folding of expression:
ValueFlow::valueFlowConstantFoldAST(rhs, _settings); ValueFlow::valueFlowConstantFoldAST(rhs, mSettings);
// get constant folded value: // get constant folded value:
if (rhs && rhs->values().size() == 1U && rhs->values().front().isKnown()) { if (rhs && rhs->values().size() == 1U && rhs->values().front().isKnown()) {
@ -1247,7 +1247,7 @@ void SymbolDatabase::createSymbolDatabaseEnums()
} }
// find enumerators // find enumerators
for (const Token* tok = _tokenizer->list.front(); tok != _tokenizer->list.back(); tok = tok->next()) { for (const Token* tok = mTokenizer->list.front(); tok != mTokenizer->list.back(); tok = tok->next()) {
if (tok->tokType() != Token::eName) if (tok->tokType() != Token::eName)
continue; continue;
const Enumerator * enumerator = findEnumerator(tok); const Enumerator * enumerator = findEnumerator(tok);
@ -1259,7 +1259,7 @@ void SymbolDatabase::createSymbolDatabaseEnums()
void SymbolDatabase::createSymbolDatabaseUnknownArrayDimensions() void SymbolDatabase::createSymbolDatabaseUnknownArrayDimensions()
{ {
// set all unknown array dimensions // set all unknown array dimensions
for (std::size_t i = 1; i <= _tokenizer->varIdCount(); i++) { for (std::size_t i = 1; i <= mTokenizer->varIdCount(); i++) {
// check each array variable // check each array variable
if (_variableList[i] && _variableList[i]->isArray()) { if (_variableList[i] && _variableList[i]->isArray()) {
// check each array dimension // check each array dimension
@ -1331,7 +1331,7 @@ void SymbolDatabase::createSymbolDatabaseUnknownArrayDimensions()
const Token *rhs = dimension.start->previous()->astOperand2(); const Token *rhs = dimension.start->previous()->astOperand2();
// constant folding of expression: // constant folding of expression:
ValueFlow::valueFlowConstantFoldAST(rhs, _settings); ValueFlow::valueFlowConstantFoldAST(rhs, mSettings);
// get constant folded value: // get constant folded value:
if (rhs && rhs->values().size() == 1U && rhs->values().front().isKnown()) { if (rhs && rhs->values().size() == 1U && rhs->values().front().isKnown()) {
@ -1348,7 +1348,7 @@ void SymbolDatabase::createSymbolDatabaseUnknownArrayDimensions()
SymbolDatabase::~SymbolDatabase() SymbolDatabase::~SymbolDatabase()
{ {
// Clear scope, type, function and variable pointers // Clear scope, type, function and variable pointers
for (const Token* tok = _tokenizer->list.front(); tok; tok = tok->next()) { for (const Token* tok = mTokenizer->list.front(); tok; tok = tok->next()) {
const_cast<Token *>(tok)->scope(nullptr); const_cast<Token *>(tok)->scope(nullptr);
const_cast<Token *>(tok)->type(nullptr); const_cast<Token *>(tok)->type(nullptr);
const_cast<Token *>(tok)->function(nullptr); const_cast<Token *>(tok)->function(nullptr);
@ -1403,7 +1403,7 @@ bool SymbolDatabase::isFunction(const Token *tok, const Scope* outerScope, const
const Token* tok1 = tok->previous(); const Token* tok1 = tok->previous();
const Token* tok2 = tok->next()->link()->next(); const Token* tok2 = tok->next()->link()->next();
if (!_tokenizer->isFunctionHead(tok->next(), ";:{")) if (!mTokenizer->isFunctionHead(tok->next(), ";:{"))
return false; return false;
// skip over destructor "~" // skip over destructor "~"
@ -1525,14 +1525,14 @@ bool SymbolDatabase::isFunction(const Token *tok, const Scope* outerScope, const
else if (Token::Match(tok, "%name% (") && !isReservedName(tok->str()) && else if (Token::Match(tok, "%name% (") && !isReservedName(tok->str()) &&
Token::simpleMatch(tok->linkAt(1), ") {") && Token::simpleMatch(tok->linkAt(1), ") {") &&
(!tok->previous() || Token::Match(tok->previous(), ";|}"))) { (!tok->previous() || Token::Match(tok->previous(), ";|}"))) {
if (_tokenizer->isC()) { if (mTokenizer->isC()) {
debugMessage(tok, "SymbolDatabase::isFunction found C function '" + tok->str() + "' without a return type."); debugMessage(tok, "SymbolDatabase::isFunction found C function '" + tok->str() + "' without a return type.");
*funcStart = tok; *funcStart = tok;
*argStart = tok->next(); *argStart = tok->next();
*declEnd = tok->linkAt(1)->next(); *declEnd = tok->linkAt(1)->next();
return true; return true;
} }
_tokenizer->syntaxError(tok); mTokenizer->syntaxError(tok);
} }
return false; return false;
@ -1547,11 +1547,11 @@ void SymbolDatabase::validateExecutableScopes() const
if (scope->isExecutable() && !function) { if (scope->isExecutable() && !function) {
const std::list<const Token*> callstack(1, scope->classDef); const std::list<const Token*> callstack(1, scope->classDef);
const std::string msg = std::string("Executable scope '") + scope->classDef->str() + "' with unknown function."; const std::string msg = std::string("Executable scope '") + scope->classDef->str() + "' with unknown function.";
const ErrorLogger::ErrorMessage errmsg(callstack, &_tokenizer->list, Severity::debug, const ErrorLogger::ErrorMessage errmsg(callstack, &mTokenizer->list, Severity::debug,
"symbolDatabaseWarning", "symbolDatabaseWarning",
msg, msg,
false); false);
_errorLogger->reportErr(errmsg); mErrorLogger->reportErr(errmsg);
} }
} }
} }
@ -1592,7 +1592,7 @@ void SymbolDatabase::validateVariables() const
void SymbolDatabase::validate() const void SymbolDatabase::validate() const
{ {
if (_settings->debugwarnings) { if (mSettings->debugwarnings) {
validateExecutableScopes(); validateExecutableScopes();
} }
//validateVariables(); //validateVariables();
@ -1708,7 +1708,7 @@ void Variable::evaluate(const Library* lib)
} }
} }
Function::Function(const Tokenizer *_tokenizer, const Token *tok, const Scope *scope, const Token *tokDef, const Token *tokArgDef) Function::Function(const Tokenizer *mTokenizer, const Token *tok, const Scope *scope, const Token *tokDef, const Token *tokArgDef)
: tokenDef(tokDef), : tokenDef(tokDef),
argDef(tokArgDef), argDef(tokArgDef),
token(nullptr), token(nullptr),
@ -1827,7 +1827,7 @@ Function::Function(const Tokenizer *_tokenizer, const Token *tok, const Scope *s
tok = tok->next(); tok = tok->next();
} }
if (_tokenizer->isFunctionHead(end, ":{")) { if (mTokenizer->isFunctionHead(end, ":{")) {
// assume implementation is inline (definition and implementation same) // assume implementation is inline (definition and implementation same)
token = tokenDef; token = tokenDef;
arg = argDef; arg = argDef;
@ -2074,7 +2074,7 @@ Function* SymbolDatabase::addGlobalFunction(Scope*& scope, const Token*& tok, co
Function* SymbolDatabase::addGlobalFunctionDecl(Scope*& scope, const Token *tok, const Token *argStart, const Token* funcStart) Function* SymbolDatabase::addGlobalFunctionDecl(Scope*& scope, const Token *tok, const Token *argStart, const Token* funcStart)
{ {
Function function(_tokenizer, tok, scope, funcStart, argStart); Function function(mTokenizer, tok, scope, funcStart, argStart);
scope->addFunction(function); scope->addFunction(function);
return &scope->functionList.back(); return &scope->functionList.back();
} }
@ -2368,15 +2368,15 @@ const std::string& Type::name() const
void SymbolDatabase::debugMessage(const Token *tok, const std::string &msg) const void SymbolDatabase::debugMessage(const Token *tok, const std::string &msg) const
{ {
if (tok && _settings->debugwarnings) { if (tok && mSettings->debugwarnings) {
const std::list<const Token*> locationList(1, tok); const std::list<const Token*> locationList(1, tok);
const ErrorLogger::ErrorMessage errmsg(locationList, &_tokenizer->list, const ErrorLogger::ErrorMessage errmsg(locationList, &mTokenizer->list,
Severity::debug, Severity::debug,
"debug", "debug",
msg, msg,
false); false);
if (_errorLogger) if (mErrorLogger)
_errorLogger->reportErr(errmsg); mErrorLogger->reportErr(errmsg);
} }
} }
@ -2600,12 +2600,12 @@ static std::string tokenType(const Token * tok)
void SymbolDatabase::printVariable(const Variable *var, const char *indent) const void SymbolDatabase::printVariable(const Variable *var, const char *indent) const
{ {
std::cout << indent << "mNameToken: " << tokenToString(var->nameToken(), _tokenizer) << std::endl; std::cout << indent << "mNameToken: " << tokenToString(var->nameToken(), mTokenizer) << std::endl;
if (var->nameToken()) { if (var->nameToken()) {
std::cout << indent << " declarationId: " << var->declarationId() << std::endl; std::cout << indent << " declarationId: " << var->declarationId() << std::endl;
} }
std::cout << indent << "mTypeStartToken: " << tokenToString(var->typeStartToken(), _tokenizer) << std::endl; std::cout << indent << "mTypeStartToken: " << tokenToString(var->typeStartToken(), mTokenizer) << std::endl;
std::cout << indent << "mTypeEndToken: " << tokenToString(var->typeEndToken(), _tokenizer) << std::endl; std::cout << indent << "mTypeEndToken: " << tokenToString(var->typeEndToken(), mTokenizer) << std::endl;
const Token * autoTok = nullptr; const Token * autoTok = nullptr;
std::cout << indent << " "; std::cout << indent << " ";
@ -2649,7 +2649,7 @@ void SymbolDatabase::printVariable(const Variable *var, const char *indent) cons
std::cout << indent << "_type: "; std::cout << indent << "_type: ";
if (var->type()) { if (var->type()) {
std::cout << var->type()->type() << " " << var->type()->name(); std::cout << var->type()->type() << " " << var->type()->name();
std::cout << " " << _tokenizer->list.fileLine(var->type()->classDef); std::cout << " " << mTokenizer->list.fileLine(var->type()->classDef);
std::cout << " " << var->type() << std::endl; std::cout << " " << var->type() << std::endl;
} else } else
std::cout << "none" << std::endl; std::cout << "none" << std::endl;
@ -2662,7 +2662,7 @@ void SymbolDatabase::printVariable(const Variable *var, const char *indent) cons
} }
} }
std::cout << indent << "_scope: " << scopeToString(var->scope(), _tokenizer) << std::endl; std::cout << indent << "_scope: " << scopeToString(var->scope(), mTokenizer) << std::endl;
std::cout << indent << "_dimensions:"; std::cout << indent << "_dimensions:";
for (std::size_t i = 0; i < var->dimensions().size(); i++) { for (std::size_t i = 0; i < var->dimensions().size(); i++) {
@ -2682,16 +2682,16 @@ void SymbolDatabase::printOut(const char *title) const
for (std::list<Scope>::const_iterator scope = scopeList.begin(); scope != scopeList.end(); ++scope) { for (std::list<Scope>::const_iterator scope = scopeList.begin(); scope != scopeList.end(); ++scope) {
std::cout << "Scope: " << &*scope << " " << scope->type << std::endl; std::cout << "Scope: " << &*scope << " " << scope->type << std::endl;
std::cout << " className: " << scope->className << std::endl; std::cout << " className: " << scope->className << std::endl;
std::cout << " classDef: " << tokenToString(scope->classDef, _tokenizer) << std::endl; std::cout << " classDef: " << tokenToString(scope->classDef, mTokenizer) << std::endl;
std::cout << " bodyStart: " << tokenToString(scope->bodyStart, _tokenizer) << std::endl; std::cout << " bodyStart: " << tokenToString(scope->bodyStart, mTokenizer) << std::endl;
std::cout << " bodyEnd: " << tokenToString(scope->bodyEnd, _tokenizer) << std::endl; std::cout << " bodyEnd: " << tokenToString(scope->bodyEnd, mTokenizer) << std::endl;
std::list<Function>::const_iterator func; std::list<Function>::const_iterator func;
// find the function body if not implemented inline // find the function body if not implemented inline
for (func = scope->functionList.begin(); func != scope->functionList.end(); ++func) { for (func = scope->functionList.begin(); func != scope->functionList.end(); ++func) {
std::cout << " Function: " << &*func << std::endl; std::cout << " Function: " << &*func << std::endl;
std::cout << " name: " << tokenToString(func->tokenDef, _tokenizer) << std::endl; std::cout << " name: " << tokenToString(func->tokenDef, mTokenizer) << std::endl;
std::cout << " type: " << (func->type == Function::eConstructor? "Constructor" : std::cout << " type: " << (func->type == Function::eConstructor? "Constructor" :
func->type == Function::eCopyConstructor ? "CopyConstructor" : func->type == Function::eCopyConstructor ? "CopyConstructor" :
func->type == Function::eMoveConstructor ? "MoveConstructor" : func->type == Function::eMoveConstructor ? "MoveConstructor" :
@ -2740,10 +2740,10 @@ void SymbolDatabase::printOut(const char *title) const
std::cout << std::endl; std::cout << std::endl;
std::cout << " noexceptArg: " << (func->noexceptArg ? func->noexceptArg->str() : "none") << 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 << " throwArg: " << (func->throwArg ? func->throwArg->str() : "none") << std::endl;
std::cout << " tokenDef: " << tokenToString(func->tokenDef, _tokenizer) << std::endl; std::cout << " tokenDef: " << tokenToString(func->tokenDef, mTokenizer) << std::endl;
std::cout << " argDef: " << tokenToString(func->argDef, _tokenizer) << std::endl; std::cout << " argDef: " << tokenToString(func->argDef, mTokenizer) << std::endl;
if (!func->isConstructor() && !func->isDestructor()) if (!func->isConstructor() && !func->isDestructor())
std::cout << " retDef: " << tokenToString(func->retDef, _tokenizer) << std::endl; std::cout << " retDef: " << tokenToString(func->retDef, mTokenizer) << std::endl;
if (func->retDef) { if (func->retDef) {
std::cout << " "; std::cout << " ";
for (const Token * tok = func->retDef; tok && tok != func->tokenDef && !Token::Match(tok, "{|;"); tok = tok->next()) for (const Token * tok = func->retDef; tok && tok != func->tokenDef && !Token::Match(tok, "{|;"); tok = tok->next())
@ -2761,11 +2761,11 @@ void SymbolDatabase::printOut(const char *title) const
} }
if (func->hasBody()) { if (func->hasBody()) {
std::cout << " token: " << tokenToString(func->token, _tokenizer) << std::endl; std::cout << " token: " << tokenToString(func->token, mTokenizer) << std::endl;
std::cout << " arg: " << tokenToString(func->arg, _tokenizer) << std::endl; std::cout << " arg: " << tokenToString(func->arg, mTokenizer) << std::endl;
} }
std::cout << " nestedIn: " << scopeToString(func->nestedIn, _tokenizer) << std::endl; std::cout << " nestedIn: " << scopeToString(func->nestedIn, mTokenizer) << std::endl;
std::cout << " functionScope: " << scopeToString(func->functionScope, _tokenizer) << std::endl; std::cout << " functionScope: " << scopeToString(func->functionScope, mTokenizer) << std::endl;
std::list<Variable>::const_iterator var; std::list<Variable>::const_iterator var;
@ -2843,10 +2843,10 @@ void SymbolDatabase::printOut(const char *title) const
std::cout << "::" << tok1->strAt(1); std::cout << "::" << tok1->strAt(1);
tok1 = tok1->tokAt(2); tok1 = tok1->tokAt(2);
} }
std::cout << " " << _tokenizer->list.fileLine(use->start) << std::endl; std::cout << " " << mTokenizer->list.fileLine(use->start) << std::endl;
} }
std::cout << " functionOf: " << scopeToString(scope->functionOf, _tokenizer) << std::endl; std::cout << " functionOf: " << scopeToString(scope->functionOf, mTokenizer) << std::endl;
std::cout << " function: " << scope->function; std::cout << " function: " << scope->function;
if (scope->function) if (scope->function)
@ -2857,7 +2857,7 @@ void SymbolDatabase::printOut(const char *title) const
for (std::list<Type>::const_iterator type = typeList.begin(); type != typeList.end(); ++type) { for (std::list<Type>::const_iterator type = typeList.begin(); type != typeList.end(); ++type) {
std::cout << "Type: " << &(*type) << std::endl; std::cout << "Type: " << &(*type) << std::endl;
std::cout << " name: " << type->name() << std::endl; std::cout << " name: " << type->name() << std::endl;
std::cout << " classDef: " << tokenToString(type->classDef, _tokenizer) << std::endl; std::cout << " classDef: " << tokenToString(type->classDef, mTokenizer) << std::endl;
std::cout << " classScope: " << type->classScope << std::endl; std::cout << " classScope: " << type->classScope << std::endl;
std::cout << " enclosingScope: " << type->enclosingScope << std::endl; std::cout << " enclosingScope: " << type->enclosingScope << std::endl;
std::cout << " needInitialization: " << (type->needInitialization == Type::Unknown ? "Unknown" : std::cout << " needInitialization: " << (type->needInitialization == Type::Unknown ? "Unknown" :
@ -2909,7 +2909,7 @@ void SymbolDatabase::printOut(const char *title) const
std::cout << "_variableList[" << i << "]: " << _variableList[i]; std::cout << "_variableList[" << i << "]: " << _variableList[i];
if (_variableList[i]) { if (_variableList[i]) {
std::cout << " " << _variableList[i]->name() << " " std::cout << " " << _variableList[i]->name() << " "
<< _tokenizer->list.fileLine(_variableList[i]->nameToken()); << mTokenizer->list.fileLine(_variableList[i]->nameToken());
} }
std::cout << std::endl; std::cout << std::endl;
} }
@ -3079,7 +3079,7 @@ void Function::addArguments(const SymbolDatabase *symbolDatabase, const Scope *s
while (Token::Match(typeTok, "const|volatile|enum|struct|::")) while (Token::Match(typeTok, "const|volatile|enum|struct|::"))
typeTok = typeTok->next(); typeTok = typeTok->next();
if (Token::Match(typeTok, ",|)")) { // #8333 if (Token::Match(typeTok, ",|)")) { // #8333
symbolDatabase->_tokenizer->syntaxError(typeTok); symbolDatabase->mTokenizer->syntaxError(typeTok);
return; return;
} }
// skip over qualification // skip over qualification
@ -3122,7 +3122,7 @@ void Function::addArguments(const SymbolDatabase *symbolDatabase, const Scope *s
while (Token::Match(startTok, "enum|struct|const|volatile")) while (Token::Match(startTok, "enum|struct|const|volatile"))
startTok = startTok->next(); startTok = startTok->next();
argumentList.emplace_back(nameTok, startTok, endTok, count++, Argument, argType, functionScope, &symbolDatabase->_settings->library); argumentList.emplace_back(nameTok, startTok, endTok, count++, Argument, argType, functionScope, &symbolDatabase->mSettings->library);
if (tok->str() == ")") { if (tok->str() == ")") {
// check for a variadic function // check for a variadic function
@ -3333,7 +3333,7 @@ void Scope::getVariableList(const Library* lib)
// global scope // global scope
else if (className.empty()) else if (className.empty())
start = check->_tokenizer->tokens(); start = check->mTokenizer->tokens();
// forward declaration // forward declaration
else else
@ -3524,12 +3524,12 @@ static const Token* skipPointers(const Token* tok)
bool Scope::isVariableDeclaration(const Token* const tok, const Token*& vartok, const Token*& typetok) const bool Scope::isVariableDeclaration(const Token* const tok, const Token*& vartok, const Token*& typetok) const
{ {
const bool isCPP = check && check->_tokenizer->isCPP(); const bool isCPP = check && check->mTokenizer->isCPP();
if (isCPP && Token::Match(tok, "throw|new")) if (isCPP && Token::Match(tok, "throw|new"))
return false; return false;
const bool isCPP11 = isCPP && check->_settings->standards.cpp >= Standards::CPP11; const bool isCPP11 = isCPP && check->mSettings->standards.cpp >= Standards::CPP11;
if (isCPP11 && tok->str() == "using") if (isCPP11 && tok->str() == "using")
return false; return false;
@ -4334,7 +4334,7 @@ const Function* SymbolDatabase::findFunction(const Token *tok) const
if (tok1->linkAt(-2)) if (tok1->linkAt(-2))
tok1 = tok1->linkAt(-2)->tokAt(-1); tok1 = tok1->linkAt(-2)->tokAt(-1);
else { else {
if (_settings->debugwarnings) if (mSettings->debugwarnings)
debugMessage(tok1->tokAt(-2), "SymbolDatabase::findFunction found '>' without link."); debugMessage(tok1->tokAt(-2), "SymbolDatabase::findFunction found '>' without link.");
return nullptr; return nullptr;
} }
@ -4509,7 +4509,7 @@ const Function *Scope::getDestructor() const
bool SymbolDatabase::isCPP() const bool SymbolDatabase::isCPP() const
{ {
return _tokenizer->isCPP(); return mTokenizer->isCPP();
} }
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
@ -4771,13 +4771,13 @@ bool SymbolDatabase::isReservedName(const std::string& iName) const
unsigned int SymbolDatabase::sizeOfType(const Token *type) const unsigned int SymbolDatabase::sizeOfType(const Token *type) const
{ {
unsigned int size = _tokenizer->sizeOfType(type); unsigned int size = mTokenizer->sizeOfType(type);
if (size == 0 && type->type() && type->type()->isEnumType() && type->type()->classScope) { if (size == 0 && type->type() && type->type()->isEnumType() && type->type()->classScope) {
size = _settings->sizeof_int; size = mSettings->sizeof_int;
const Token * enum_type = type->type()->classScope->enumType; const Token * enum_type = type->type()->classScope->enumType;
if (enum_type) if (enum_type)
size = _tokenizer->sizeOfType(enum_type); size = mTokenizer->sizeOfType(enum_type);
} }
return size; return size;
@ -4792,7 +4792,7 @@ void SymbolDatabase::setValueType(Token *tok, const Variable &var)
valuetype.bits = var.nameToken()->bits(); valuetype.bits = var.nameToken()->bits();
valuetype.pointer = var.dimensions().size(); valuetype.pointer = var.dimensions().size();
valuetype.typeScope = var.typeScope(); valuetype.typeScope = var.typeScope();
if (parsedecl(var.typeStartToken(), &valuetype, defaultSignedness, _settings)) if (parsedecl(var.typeStartToken(), &valuetype, defaultSignedness, mSettings))
setValueType(tok, valuetype); setValueType(tok, valuetype);
} }
@ -4804,7 +4804,7 @@ void SymbolDatabase::setValueType(Token *tok, const Enumerator &enumerator)
if (type) { if (type) {
valuetype.type = ValueType::typeFromString(type->str(), type->isLong()); valuetype.type = ValueType::typeFromString(type->str(), type->isLong());
if (valuetype.type == ValueType::Type::UNKNOWN_TYPE && type->isStandardType()) if (valuetype.type == ValueType::Type::UNKNOWN_TYPE && type->isStandardType())
valuetype.fromLibraryType(type->str(), _settings); valuetype.fromLibraryType(type->str(), mSettings);
if (valuetype.isIntegral()) { if (valuetype.isIntegral()) {
if (type->isSigned()) if (type->isSigned())
@ -4977,7 +4977,7 @@ void SymbolDatabase::setValueType(Token *tok, const ValueType &valuetype)
// TODO: Get type better // TODO: Get type better
if (Token::Match(typeStart, "std :: %type% < %type% *| *| >")) { if (Token::Match(typeStart, "std :: %type% < %type% *| *| >")) {
ValueType autovt; ValueType autovt;
if (parsedecl(typeStart->tokAt(4), &autovt, defaultSignedness, _settings)) { if (parsedecl(typeStart->tokAt(4), &autovt, defaultSignedness, mSettings)) {
setValueType(autoToken, autovt); setValueType(autoToken, autovt);
setAutoTokenProperties(autoToken); setAutoTokenProperties(autoToken);
ValueType varvt(autovt); ValueType varvt(autovt);
@ -5000,7 +5000,7 @@ void SymbolDatabase::setValueType(Token *tok, const ValueType &valuetype)
if (vt1 && vt1->containerTypeToken && parent->str() == "[") { if (vt1 && vt1->containerTypeToken && parent->str() == "[") {
ValueType vtParent; ValueType vtParent;
if (parsedecl(vt1->containerTypeToken, &vtParent, defaultSignedness, _settings)) { if (parsedecl(vt1->containerTypeToken, &vtParent, defaultSignedness, mSettings)) {
setValueType(parent, vtParent); setValueType(parent, vtParent);
return; return;
} }
@ -5227,7 +5227,7 @@ static const Function *getOperatorFunction(const Token * const tok)
void SymbolDatabase::setValueTypeInTokenList() void SymbolDatabase::setValueTypeInTokenList()
{ {
Token * tokens = const_cast<Tokenizer *>(_tokenizer)->list.front(); Token * tokens = const_cast<Tokenizer *>(mTokenizer)->list.front();
for (Token *tok = tokens; tok; tok = tok->next()) for (Token *tok = tokens; tok; tok = tok->next())
tok->setValueType(nullptr); tok->setValueType(nullptr);
@ -5247,11 +5247,11 @@ void SymbolDatabase::setValueTypeInTokenList()
ValueType::Sign sign = unsignedSuffix ? ValueType::Sign::UNSIGNED : ValueType::Sign::SIGNED; ValueType::Sign sign = unsignedSuffix ? ValueType::Sign::UNSIGNED : ValueType::Sign::SIGNED;
ValueType::Type type; ValueType::Type type;
const MathLib::bigint value = MathLib::toLongNumber(tok->str()); const MathLib::bigint value = MathLib::toLongNumber(tok->str());
if (_settings->platformType == cppcheck::Platform::Unspecified) if (mSettings->platformType == cppcheck::Platform::Unspecified)
type = ValueType::Type::INT; type = ValueType::Type::INT;
else if (_settings->isIntValue(unsignedSuffix ? (value >> 1) : value)) else if (mSettings->isIntValue(unsignedSuffix ? (value >> 1) : value))
type = ValueType::Type::INT; type = ValueType::Type::INT;
else if (_settings->isLongValue(unsignedSuffix ? (value >> 1) : value)) else if (mSettings->isLongValue(unsignedSuffix ? (value >> 1) : value))
type = ValueType::Type::LONG; type = ValueType::Type::LONG;
else else
type = ValueType::Type::LONGLONG; type = ValueType::Type::LONGLONG;
@ -5275,7 +5275,7 @@ void SymbolDatabase::setValueTypeInTokenList()
const Function *function = getOperatorFunction(tok); const Function *function = getOperatorFunction(tok);
if (function) { if (function) {
ValueType vt; ValueType vt;
parsedecl(function->retDef, &vt, defaultSignedness, _settings); parsedecl(function->retDef, &vt, defaultSignedness, mSettings);
setValueType(tok, vt); setValueType(tok, vt);
continue; continue;
} }
@ -5294,21 +5294,21 @@ void SymbolDatabase::setValueTypeInTokenList()
// cast // cast
if (!tok->astOperand2() && Token::Match(tok, "( %name%")) { if (!tok->astOperand2() && Token::Match(tok, "( %name%")) {
ValueType valuetype; ValueType valuetype;
if (Token::simpleMatch(parsedecl(tok->next(), &valuetype, defaultSignedness, _settings), ")")) if (Token::simpleMatch(parsedecl(tok->next(), &valuetype, defaultSignedness, mSettings), ")"))
setValueType(tok, valuetype); setValueType(tok, valuetype);
} }
// C++ cast // C++ cast
if (tok->astOperand2() && Token::Match(tok->astOperand1(), "static_cast|const_cast|dynamic_cast|reinterpret_cast < %name%") && tok->astOperand1()->linkAt(1)) { if (tok->astOperand2() && Token::Match(tok->astOperand1(), "static_cast|const_cast|dynamic_cast|reinterpret_cast < %name%") && tok->astOperand1()->linkAt(1)) {
ValueType valuetype; ValueType valuetype;
if (Token::simpleMatch(parsedecl(tok->astOperand1()->tokAt(2), &valuetype, defaultSignedness, _settings), ">")) if (Token::simpleMatch(parsedecl(tok->astOperand1()->tokAt(2), &valuetype, defaultSignedness, mSettings), ">"))
setValueType(tok, valuetype); setValueType(tok, valuetype);
} }
// function // function
else if (tok->previous() && tok->previous()->function() && tok->previous()->function()->retDef) { else if (tok->previous() && tok->previous()->function() && tok->previous()->function()->retDef) {
ValueType valuetype; ValueType valuetype;
if (parsedecl(tok->previous()->function()->retDef, &valuetype, defaultSignedness, _settings)) if (parsedecl(tok->previous()->function()->retDef, &valuetype, defaultSignedness, mSettings))
setValueType(tok, valuetype); setValueType(tok, valuetype);
} }
@ -5320,7 +5320,7 @@ void SymbolDatabase::setValueTypeInTokenList()
if (Token::Match(tok, "( %type% %type%| *| *| )")) { if (Token::Match(tok, "( %type% %type%| *| *| )")) {
ValueType vt; ValueType vt;
if (parsedecl(tok->next(), &vt, defaultSignedness, _settings)) { if (parsedecl(tok->next(), &vt, defaultSignedness, mSettings)) {
setValueType(tok->next(), vt); setValueType(tok->next(), vt);
} }
} }
@ -5343,7 +5343,7 @@ void SymbolDatabase::setValueTypeInTokenList()
// library function // library function
else if (tok->previous()) { else if (tok->previous()) {
const std::string& typestr(_settings->library.returnValueType(tok->previous())); const std::string& typestr(mSettings->library.returnValueType(tok->previous()));
if (typestr.empty() || typestr == "iterator") { if (typestr.empty() || typestr == "iterator") {
if (Token::simpleMatch(tok->astOperand1(), ".") && if (Token::simpleMatch(tok->astOperand1(), ".") &&
tok->astOperand1()->astOperand1() && tok->astOperand1()->astOperand1() &&
@ -5365,13 +5365,13 @@ void SymbolDatabase::setValueTypeInTokenList()
} }
continue; continue;
} }
TokenList tokenList(_settings); TokenList tokenList(mSettings);
std::istringstream istr(typestr+";"); std::istringstream istr(typestr+";");
if (tokenList.createTokens(istr)) { if (tokenList.createTokens(istr)) {
ValueType vt; ValueType vt;
assert(tokenList.front()); assert(tokenList.front());
tokenList.simplifyStdType(); tokenList.simplifyStdType();
if (parsedecl(tokenList.front(), &vt, defaultSignedness, _settings)) { if (parsedecl(tokenList.front(), &vt, defaultSignedness, mSettings)) {
setValueType(tok, vt); setValueType(tok, vt);
} }
} }
@ -5384,7 +5384,7 @@ void SymbolDatabase::setValueTypeInTokenList()
const Token *typeTok = tok->next(); const Token *typeTok = tok->next();
if (Token::Match(typeTok, "( std| ::| nothrow )")) if (Token::Match(typeTok, "( std| ::| nothrow )"))
typeTok = typeTok->link()->next(); typeTok = typeTok->link()->next();
if (const Library::Container *c = _settings->library.detectContainer(typeTok)) { if (const Library::Container *c = mSettings->library.detectContainer(typeTok)) {
ValueType vt; ValueType vt;
vt.pointer = 1; vt.pointer = 1;
vt.container = c; vt.container = c;
@ -5408,7 +5408,7 @@ void SymbolDatabase::setValueTypeInTokenList()
} else { } else {
vt.type = ValueType::typeFromString(typestr, typeTok->isLong()); vt.type = ValueType::typeFromString(typestr, typeTok->isLong());
if (vt.type == ValueType::Type::UNKNOWN_TYPE) if (vt.type == ValueType::Type::UNKNOWN_TYPE)
vt.fromLibraryType(typestr, _settings); vt.fromLibraryType(typestr, mSettings);
if (vt.type == ValueType::Type::UNKNOWN_TYPE) if (vt.type == ValueType::Type::UNKNOWN_TYPE)
continue; continue;
if (typeTok->isUnsigned()) if (typeTok->isUnsigned())

View File

@ -696,7 +696,7 @@ class CPPCHECKLIB Function {
public: public:
enum Type { eConstructor, eCopyConstructor, eMoveConstructor, eOperatorEqual, eDestructor, eFunction }; enum Type { eConstructor, eCopyConstructor, eMoveConstructor, eOperatorEqual, eDestructor, eFunction };
Function(const Tokenizer *_tokenizer, const Token *tok, const Scope *scope, const Token *tokDef, const Token *tokArgDef); Function(const Tokenizer *mTokenizer, const Token *tok, const Scope *scope, const Token *tokDef, const Token *tokArgDef);
const std::string &name() const { const std::string &name() const {
return tokenDef->str(); return tokenDef->str();
@ -1238,9 +1238,9 @@ private:
void setValueType(Token *tok, const Variable &var); void setValueType(Token *tok, const Variable &var);
void setValueType(Token *tok, const Enumerator &enumerator); void setValueType(Token *tok, const Enumerator &enumerator);
const Tokenizer *_tokenizer; const Tokenizer *mTokenizer;
const Settings *_settings; const Settings *mSettings;
ErrorLogger *_errorLogger; ErrorLogger *mErrorLogger;
/** variable symbol table */ /** variable symbol table */
std::vector<const Variable *> _variableList; std::vector<const Variable *> _variableList;

View File

@ -1480,7 +1480,7 @@ static bool matchSpecialization(const Token *templateDeclarationNameToken, const
bool TemplateSimplifier::simplifyTemplateInstantiations( bool TemplateSimplifier::simplifyTemplateInstantiations(
TokenList& tokenlist, TokenList& tokenlist,
ErrorLogger* errorlogger, ErrorLogger* errorlogger,
const Settings *_settings, const Settings *mSettings,
const TokenAndName &templateDeclaration, const TokenAndName &templateDeclaration,
const std::list<const Token *> &specializations, const std::list<const Token *> &specializations,
const std::time_t maxtime, const std::time_t maxtime,
@ -1499,7 +1499,7 @@ bool TemplateSimplifier::simplifyTemplateInstantiations(
if (!tok) if (!tok)
return false; return false;
const bool printDebug = _settings->debugwarnings; const bool printDebug = mSettings->debugwarnings;
// get the position of the template name // get the position of the template name
const int namepos = TemplateSimplifier::getTemplateNamePosition(tok); const int namepos = TemplateSimplifier::getTemplateNamePosition(tok);
@ -1733,7 +1733,7 @@ void TemplateSimplifier::replaceTemplateUsage(Token * const instantiationToken,
void TemplateSimplifier::simplifyTemplates( void TemplateSimplifier::simplifyTemplates(
TokenList& tokenlist, TokenList& tokenlist,
ErrorLogger* errorlogger, ErrorLogger* errorlogger,
const Settings *_settings, const Settings *mSettings,
const std::time_t maxtime, const std::time_t maxtime,
bool &_codeWithTemplates bool &_codeWithTemplates
) )
@ -1791,7 +1791,7 @@ void TemplateSimplifier::simplifyTemplates(
const bool instantiated = TemplateSimplifier::simplifyTemplateInstantiations(tokenlist, const bool instantiated = TemplateSimplifier::simplifyTemplateInstantiations(tokenlist,
errorlogger, errorlogger,
_settings, mSettings,
*iter1, *iter1,
specializations, specializations,
maxtime, maxtime,

View File

@ -164,7 +164,7 @@ public:
* @todo It seems that inner templates should be instantiated recursively * @todo It seems that inner templates should be instantiated recursively
* @param tokenlist token list * @param tokenlist token list
* @param errorlogger error logger * @param errorlogger error logger
* @param _settings settings * @param mSettings settings
* @param templateDeclaration template declaration * @param templateDeclaration template declaration
* @param specializations template specializations (list each template name token) * @param specializations template specializations (list each template name token)
* @param maxtime time when the simplification will stop * @param maxtime time when the simplification will stop
@ -175,7 +175,7 @@ public:
static bool simplifyTemplateInstantiations( static bool simplifyTemplateInstantiations(
TokenList& tokenlist, TokenList& tokenlist,
ErrorLogger* errorlogger, ErrorLogger* errorlogger,
const Settings *_settings, const Settings *mSettings,
const TokenAndName &templateDeclaration, const TokenAndName &templateDeclaration,
const std::list<const Token *> &specializations, const std::list<const Token *> &specializations,
const std::time_t maxtime, const std::time_t maxtime,
@ -202,14 +202,14 @@ public:
* Simplify templates * Simplify templates
* @param tokenlist token list * @param tokenlist token list
* @param errorlogger error logger * @param errorlogger error logger
* @param _settings settings * @param mSettings settings
* @param maxtime time when the simplification should be stopped * @param maxtime time when the simplification should be stopped
* @param _codeWithTemplates output parameter that is set if code contains templates * @param _codeWithTemplates output parameter that is set if code contains templates
*/ */
static void simplifyTemplates( static void simplifyTemplates(
TokenList& tokenlist, TokenList& tokenlist,
ErrorLogger* errorlogger, ErrorLogger* errorlogger,
const Settings *_settings, const Settings *mSettings,
const std::time_t maxtime, const std::time_t maxtime,
bool &_codeWithTemplates); bool &_codeWithTemplates);

View File

@ -140,8 +140,8 @@ static bool isClassStructUnionEnumStart(const Token * tok)
Tokenizer::Tokenizer() : Tokenizer::Tokenizer() :
list(nullptr), list(nullptr),
_settings(nullptr), mSettings(nullptr),
_errorLogger(nullptr), mErrorLogger(nullptr),
_symbolDatabase(nullptr), _symbolDatabase(nullptr),
_varId(0), _varId(0),
_unnamedCount(0), _unnamedCount(0),
@ -155,8 +155,8 @@ Tokenizer::Tokenizer() :
Tokenizer::Tokenizer(const Settings *settings, ErrorLogger *errorLogger) : Tokenizer::Tokenizer(const Settings *settings, ErrorLogger *errorLogger) :
list(settings), list(settings),
_settings(settings), mSettings(settings),
_errorLogger(errorLogger), mErrorLogger(errorLogger),
_symbolDatabase(nullptr), _symbolDatabase(nullptr),
_varId(0), _varId(0),
_unnamedCount(0), _unnamedCount(0),
@ -167,7 +167,7 @@ Tokenizer::Tokenizer(const Settings *settings, ErrorLogger *errorLogger) :
#endif #endif
{ {
// make sure settings are specified // make sure settings are specified
assert(_settings); assert(mSettings);
} }
Tokenizer::~Tokenizer() Tokenizer::~Tokenizer()
@ -190,16 +190,16 @@ unsigned int Tokenizer::sizeOfType(const Token *type) const
const std::map<std::string, unsigned int>::const_iterator it = _typeSize.find(type->str()); const std::map<std::string, unsigned int>::const_iterator it = _typeSize.find(type->str());
if (it == _typeSize.end()) { if (it == _typeSize.end()) {
const Library::PodType* podtype = _settings->library.podtype(type->str()); const Library::PodType* podtype = mSettings->library.podtype(type->str());
if (!podtype) if (!podtype)
return 0; return 0;
return podtype->size; return podtype->size;
} else if (type->isLong()) { } else if (type->isLong()) {
if (type->str() == "double") if (type->str() == "double")
return _settings->sizeof_long_double; return mSettings->sizeof_long_double;
else if (type->str() == "long") else if (type->str() == "long")
return _settings->sizeof_long_long; return mSettings->sizeof_long_long;
} }
return it->second; return it->second;
@ -336,7 +336,7 @@ bool Tokenizer::duplicateTypedef(Token **tokPtr, const Token *name, const Token
void Tokenizer::unsupportedTypedef(const Token *tok) const void Tokenizer::unsupportedTypedef(const Token *tok) const
{ {
if (!_settings->debugwarnings) if (!mSettings->debugwarnings)
return; return;
std::ostringstream str; std::ostringstream str;
@ -541,10 +541,10 @@ void Tokenizer::simplifyTypedef()
bool hasClass = false; bool hasClass = false;
bool goback = false; bool goback = false;
for (Token *tok = list.front(); tok; tok = tok->next()) { for (Token *tok = list.front(); tok; tok = tok->next()) {
if (_errorLogger && !list.getFiles().empty()) if (mErrorLogger && !list.getFiles().empty())
_errorLogger->reportProgress(list.getFiles()[0], "Tokenize (typedef)", tok->progressValue()); mErrorLogger->reportProgress(list.getFiles()[0], "Tokenize (typedef)", tok->progressValue());
if (_settings->terminated()) if (mSettings->terminated())
return; return;
if (isMaxTime()) if (isMaxTime())
@ -1010,7 +1010,7 @@ void Tokenizer::simplifyTypedef()
std::size_t classLevel = spaceInfo.size(); std::size_t classLevel = spaceInfo.size();
for (Token *tok2 = tok; tok2; tok2 = tok2->next()) { for (Token *tok2 = tok; tok2; tok2 = tok2->next()) {
if (_settings->terminated()) if (mSettings->terminated())
return; return;
if (tok2->link()) { // Pre-check for performance if (tok2->link()) { // Pre-check for performance
@ -1719,15 +1719,15 @@ bool Tokenizer::createTokens(std::istream &code,
const std::string& FileName) const std::string& FileName)
{ {
// make sure settings specified // make sure settings specified
assert(_settings); assert(mSettings);
return list.createTokens(code, Path::getRelativePath(Path::simplifyPath(FileName), _settings->basePaths)); return list.createTokens(code, Path::getRelativePath(Path::simplifyPath(FileName), mSettings->basePaths));
} }
void Tokenizer::createTokens(const simplecpp::TokenList *tokenList) void Tokenizer::createTokens(const simplecpp::TokenList *tokenList)
{ {
// make sure settings specified // make sure settings specified
assert(_settings); assert(mSettings);
list.createTokens(tokenList); list.createTokens(tokenList);
} }
@ -1759,7 +1759,7 @@ bool Tokenizer::simplifyTokens1(const std::string &configuration)
} }
_symbolDatabase->setValueTypeInTokenList(); _symbolDatabase->setValueTypeInTokenList();
ValueFlow::setValues(&list, _symbolDatabase, _errorLogger, _settings); ValueFlow::setValues(&list, _symbolDatabase, mErrorLogger, mSettings);
printDebugOutput(1); printDebugOutput(1);
@ -1800,16 +1800,16 @@ void Tokenizer::fillTypeSizes()
{ {
_typeSize.clear(); _typeSize.clear();
_typeSize["char"] = 1; _typeSize["char"] = 1;
_typeSize["_Bool"] = _settings->sizeof_bool; _typeSize["_Bool"] = mSettings->sizeof_bool;
_typeSize["bool"] = _settings->sizeof_bool; _typeSize["bool"] = mSettings->sizeof_bool;
_typeSize["short"] = _settings->sizeof_short; _typeSize["short"] = mSettings->sizeof_short;
_typeSize["int"] = _settings->sizeof_int; _typeSize["int"] = mSettings->sizeof_int;
_typeSize["long"] = _settings->sizeof_long; _typeSize["long"] = mSettings->sizeof_long;
_typeSize["float"] = _settings->sizeof_float; _typeSize["float"] = mSettings->sizeof_float;
_typeSize["double"] = _settings->sizeof_double; _typeSize["double"] = mSettings->sizeof_double;
_typeSize["wchar_t"] = _settings->sizeof_wchar_t; _typeSize["wchar_t"] = mSettings->sizeof_wchar_t;
_typeSize["size_t"] = _settings->sizeof_size_t; _typeSize["size_t"] = mSettings->sizeof_size_t;
_typeSize["*"] = _settings->sizeof_pointer; _typeSize["*"] = mSettings->sizeof_pointer;
} }
void Tokenizer::combineOperators() void Tokenizer::combineOperators()
@ -2292,8 +2292,8 @@ void Tokenizer::simplifyTemplates()
TemplateSimplifier::simplifyTemplates( TemplateSimplifier::simplifyTemplates(
list, list,
_errorLogger, mErrorLogger,
_settings, mSettings,
#ifdef MAXTIME #ifdef MAXTIME
maxtime, maxtime,
#else #else
@ -2675,7 +2675,7 @@ void Tokenizer::setVarIdPass1()
continue; continue;
} }
if (_settings->terminated()) if (mSettings->terminated())
return; return;
// locate the variable name.. // locate the variable name..
@ -3392,7 +3392,7 @@ bool Tokenizer::simplifySizeof()
tok->deleteThis(); tok->deleteThis();
tok->deleteNext(); tok->deleteNext();
std::ostringstream sz; std::ostringstream sz;
sz << ((isC()) ? _settings->sizeof_int : 1); sz << ((isC()) ? mSettings->sizeof_int : 1);
tok->str(sz.str()); tok->str(sz.str());
ret = true; ret = true;
continue; continue;
@ -3517,7 +3517,7 @@ bool Tokenizer::simplifySizeof()
bool Tokenizer::simplifyTokenList1(const char FileName[]) bool Tokenizer::simplifyTokenList1(const char FileName[])
{ {
if (_settings->terminated()) if (mSettings->terminated())
return false; return false;
// if MACRO // if MACRO
@ -3554,7 +3554,7 @@ bool Tokenizer::simplifyTokenList1(const char FileName[])
// Bail out if code is garbage // Bail out if code is garbage
if (_timerResults) { if (_timerResults) {
Timer t("Tokenizer::tokenize::findGarbageCode", _settings->showtime, _timerResults); Timer t("Tokenizer::tokenize::findGarbageCode", mSettings->showtime, _timerResults);
findGarbageCode(); findGarbageCode();
} else { } else {
findGarbageCode(); findGarbageCode();
@ -3574,7 +3574,7 @@ bool Tokenizer::simplifyTokenList1(const char FileName[])
} }
} }
if (_settings->terminated()) if (mSettings->terminated())
return false; return false;
// convert C++17 style nested namespaces to old style namespaces // convert C++17 style nested namespaces to old style namespaces
@ -3630,7 +3630,7 @@ bool Tokenizer::simplifyTokenList1(const char FileName[])
} }
} }
if (_settings->terminated()) if (mSettings->terminated())
return false; return false;
// Remove "inline", "register", and "restrict" // Remove "inline", "register", and "restrict"
@ -3668,11 +3668,11 @@ bool Tokenizer::simplifyTokenList1(const char FileName[])
// simplify '[;{}] * & ( %any% ) =' to '%any% =' // simplify '[;{}] * & ( %any% ) =' to '%any% ='
simplifyMulAndParens(); simplifyMulAndParens();
if (!isC() && !_settings->library.markupFile(FileName)) { if (!isC() && !mSettings->library.markupFile(FileName)) {
findComplicatedSyntaxErrorsInTemplates(); findComplicatedSyntaxErrorsInTemplates();
} }
if (_settings->terminated()) if (mSettings->terminated())
return false; return false;
// remove calling conventions __cdecl, __stdcall.. // remove calling conventions __cdecl, __stdcall..
@ -3701,7 +3701,7 @@ bool Tokenizer::simplifyTokenList1(const char FileName[])
// convert Microsoft string functions // convert Microsoft string functions
simplifyMicrosoftStringFunctions(); simplifyMicrosoftStringFunctions();
if (_settings->terminated()) if (mSettings->terminated())
return false; return false;
// Remove Qt signals and slots // Remove Qt signals and slots
@ -3724,7 +3724,7 @@ bool Tokenizer::simplifyTokenList1(const char FileName[])
// typedef.. // typedef..
if (_timerResults) { if (_timerResults) {
Timer t("Tokenizer::tokenize::simplifyTypedef", _settings->showtime, _timerResults); Timer t("Tokenizer::tokenize::simplifyTypedef", mSettings->showtime, _timerResults);
simplifyTypedef(); simplifyTypedef();
} else { } else {
simplifyTypedef(); simplifyTypedef();
@ -3743,7 +3743,7 @@ bool Tokenizer::simplifyTokenList1(const char FileName[])
} }
// class x y { // class x y {
if (isCPP() && _settings->isEnabled(Settings::INFORMATION)) { if (isCPP() && mSettings->isEnabled(Settings::INFORMATION)) {
for (const Token *tok = list.front(); tok; tok = tok->next()) { for (const Token *tok = list.front(); tok; tok = tok->next()) {
if (Token::Match(tok, "class %type% %type% [:{]")) { if (Token::Match(tok, "class %type% %type% [:{]")) {
unhandled_macro_class_x_y(tok); unhandled_macro_class_x_y(tok);
@ -3759,7 +3759,7 @@ bool Tokenizer::simplifyTokenList1(const char FileName[])
validate(); validate();
// The simplify enum have inner loops // The simplify enum have inner loops
if (_settings->terminated()) if (mSettings->terminated())
return false; return false;
// Put ^{} statements in asm() // Put ^{} statements in asm()
@ -3777,25 +3777,25 @@ bool Tokenizer::simplifyTokenList1(const char FileName[])
// unsigned long long int => long (with _isUnsigned=true,_isLong=true) // unsigned long long int => long (with _isUnsigned=true,_isLong=true)
list.simplifyStdType(); list.simplifyStdType();
if (_settings->terminated()) if (mSettings->terminated())
return false; return false;
// simplify bit fields.. // simplify bit fields..
simplifyBitfields(); simplifyBitfields();
if (_settings->terminated()) if (mSettings->terminated())
return false; return false;
// struct simplification "struct S {} s; => struct S { } ; S s ; // struct simplification "struct S {} s; => struct S { } ; S s ;
simplifyStructDecl(); simplifyStructDecl();
if (_settings->terminated()) if (mSettings->terminated())
return false; return false;
// x = ({ 123; }); => { x = 123; } // x = ({ 123; }); => { x = 123; }
simplifyAssignmentBlock(); simplifyAssignmentBlock();
if (_settings->terminated()) if (mSettings->terminated())
return false; return false;
simplifyVariableMultipleAssign(); simplifyVariableMultipleAssign();
@ -3817,7 +3817,7 @@ bool Tokenizer::simplifyTokenList1(const char FileName[])
simplifyTemplates(); simplifyTemplates();
// The simplifyTemplates have inner loops // The simplifyTemplates have inner loops
if (_settings->terminated()) if (mSettings->terminated())
return false; return false;
// sometimes the "simplifyTemplates" fail and then unsimplified // sometimes the "simplifyTemplates" fail and then unsimplified
@ -3842,7 +3842,7 @@ bool Tokenizer::simplifyTokenList1(const char FileName[])
validate(); // #6772 "segmentation fault (invalid code) in Tokenizer::setVarId" validate(); // #6772 "segmentation fault (invalid code) in Tokenizer::setVarId"
if (_timerResults) { if (_timerResults) {
Timer t("Tokenizer::tokenize::setVarId", _settings->showtime, _timerResults); Timer t("Tokenizer::tokenize::setVarId", mSettings->showtime, _timerResults);
setVarId(); setVarId();
} else { } else {
setVarId(); setVarId();
@ -3855,7 +3855,7 @@ bool Tokenizer::simplifyTokenList1(const char FileName[])
arraySize(); arraySize();
// The simplify enum might have inner loops // The simplify enum might have inner loops
if (_settings->terminated()) if (mSettings->terminated())
return false; return false;
// Add std:: in front of std classes, when using namespace std; was given // Add std:: in front of std classes, when using namespace std; was given
@ -3914,7 +3914,7 @@ bool Tokenizer::simplifyTokenList2()
simplifyStd(); simplifyStd();
if (_settings->terminated()) if (mSettings->terminated())
return false; return false;
simplifySizeof(); simplifySizeof();
@ -3927,7 +3927,7 @@ bool Tokenizer::simplifyTokenList2()
// e.g. const static int value = sizeof(X)/sizeof(Y); // e.g. const static int value = sizeof(X)/sizeof(Y);
simplifyCalculations(); simplifyCalculations();
if (_settings->terminated()) if (mSettings->terminated())
return false; return false;
// Replace "*(ptr + num)" => "ptr[num]" // Replace "*(ptr + num)" => "ptr[num]"
@ -3964,7 +3964,7 @@ bool Tokenizer::simplifyTokenList2()
bool modified = true; bool modified = true;
while (modified) { while (modified) {
if (_settings->terminated()) if (mSettings->terminated())
return false; return false;
modified = false; modified = false;
@ -4025,9 +4025,9 @@ bool Tokenizer::simplifyTokenList2()
createSymbolDatabase(); createSymbolDatabase();
_symbolDatabase->setValueTypeInTokenList(); _symbolDatabase->setValueTypeInTokenList();
ValueFlow::setValues(&list, _symbolDatabase, _errorLogger, _settings); ValueFlow::setValues(&list, _symbolDatabase, mErrorLogger, mSettings);
if (_settings->terminated()) if (mSettings->terminated())
return false; return false;
printDebugOutput(2); printDebugOutput(2);
@ -4038,33 +4038,33 @@ bool Tokenizer::simplifyTokenList2()
void Tokenizer::printDebugOutput(unsigned int simplification) const void Tokenizer::printDebugOutput(unsigned int simplification) const
{ {
const bool debug = (simplification != 1U && _settings->debug) || const bool debug = (simplification != 1U && mSettings->debug) ||
(simplification != 2U && _settings->debugnormal); (simplification != 2U && mSettings->debugnormal);
if (debug && list.front()) { if (debug && list.front()) {
list.front()->printOut(nullptr, list.getFiles()); list.front()->printOut(nullptr, list.getFiles());
if (_settings->xml) if (mSettings->xml)
std::cout << "<debug>" << std::endl; std::cout << "<debug>" << std::endl;
if (_symbolDatabase) { if (_symbolDatabase) {
if (_settings->xml) if (mSettings->xml)
_symbolDatabase->printXml(std::cout); _symbolDatabase->printXml(std::cout);
else if (_settings->verbose) { else if (mSettings->verbose) {
_symbolDatabase->printOut("Symbol database"); _symbolDatabase->printOut("Symbol database");
} }
} }
if (_settings->verbose) if (mSettings->verbose)
list.front()->printAst(_settings->verbose, _settings->xml, std::cout); list.front()->printAst(mSettings->verbose, mSettings->xml, std::cout);
list.front()->printValueFlow(_settings->xml, std::cout); list.front()->printValueFlow(mSettings->xml, std::cout);
if (_settings->xml) if (mSettings->xml)
std::cout << "</debug>" << std::endl; std::cout << "</debug>" << std::endl;
} }
if (_symbolDatabase && simplification == 2U && _settings->debugwarnings) { if (_symbolDatabase && simplification == 2U && mSettings->debugwarnings) {
printUnknownTypes(); printUnknownTypes();
// the typeStartToken() should come before typeEndToken() // the typeStartToken() should come before typeEndToken()
@ -4451,7 +4451,7 @@ void Tokenizer::simplifyFlowControl()
} else if (Token::Match(tok,"return|goto") || } else if (Token::Match(tok,"return|goto") ||
(Token::Match(tok->previous(), "[;{}] %name% (") && (Token::Match(tok->previous(), "[;{}] %name% (") &&
_settings->library.isnoreturn(tok)) || mSettings->library.isnoreturn(tok)) ||
(isCPP() && tok->str() == "throw")) { (isCPP() && tok->str() == "throw")) {
if (tok->next()->str() == "}") if (tok->next()->str() == "}")
syntaxError(tok->next()); // invalid code like in #6731 syntaxError(tok->next()); // invalid code like in #6731
@ -5183,7 +5183,7 @@ void Tokenizer::simplifyCasts()
// #4164 : ((unsigned char)1) => (1) // #4164 : ((unsigned char)1) => (1)
if (Token::Match(tok->next(), "( %type% ) %num%") && tok->next()->link()->previous()->isStandardType()) { if (Token::Match(tok->next(), "( %type% ) %num%") && tok->next()->link()->previous()->isStandardType()) {
const MathLib::bigint value = MathLib::toLongNumber(tok->next()->link()->next()->str()); const MathLib::bigint value = MathLib::toLongNumber(tok->next()->link()->next()->str());
unsigned int bits = _settings->char_bit * _typeSize[tok->next()->link()->previous()->str()]; unsigned int bits = mSettings->char_bit * _typeSize[tok->next()->link()->previous()->str()];
if (!tok->tokAt(2)->isUnsigned() && bits > 0) if (!tok->tokAt(2)->isUnsigned() && bits > 0)
bits--; bits--;
if (bits < 31 && value >= 0 && value < (1LL << bits)) { if (bits < 31 && value >= 0 && value < (1LL << bits)) {
@ -5576,7 +5576,7 @@ void Tokenizer::simplifyVarDecl(const bool only_k_r_fpar)
void Tokenizer::simplifyVarDecl(Token * tokBegin, const Token * const tokEnd, const bool only_k_r_fpar) void Tokenizer::simplifyVarDecl(Token * tokBegin, const Token * const tokEnd, const bool only_k_r_fpar)
{ {
const bool isCPP11 = _settings->standards.cpp >= Standards::CPP11; const bool isCPP11 = mSettings->standards.cpp >= Standards::CPP11;
// Split up variable declarations.. // Split up variable declarations..
// "int a=4;" => "int a; a=4;" // "int a=4;" => "int a; a=4;"
@ -5872,17 +5872,17 @@ void Tokenizer::simplifyVarDecl(Token * tokBegin, const Token * const tokEnd, co
void Tokenizer::simplifyPlatformTypes() void Tokenizer::simplifyPlatformTypes()
{ {
const bool isCPP11 = _settings->standards.cpp >= Standards::CPP11; const bool isCPP11 = mSettings->standards.cpp >= Standards::CPP11;
enum { isLongLong, isLong, isInt } type; enum { isLongLong, isLong, isInt } type;
/** @todo This assumes a flat address space. Not true for segmented address space (FAR *). */ /** @todo This assumes a flat address space. Not true for segmented address space (FAR *). */
if (_settings->sizeof_size_t == _settings->sizeof_long) if (mSettings->sizeof_size_t == mSettings->sizeof_long)
type = isLong; type = isLong;
else if (_settings->sizeof_size_t == _settings->sizeof_long_long) else if (mSettings->sizeof_size_t == mSettings->sizeof_long_long)
type = isLongLong; type = isLongLong;
else if (_settings->sizeof_size_t == _settings->sizeof_int) else if (mSettings->sizeof_size_t == mSettings->sizeof_int)
type = isInt; type = isInt;
else else
return; return;
@ -5935,13 +5935,13 @@ void Tokenizer::simplifyPlatformTypes()
} }
} }
const std::string platform_type(_settings->platformString()); const std::string platform_type(mSettings->platformString());
for (Token *tok = list.front(); tok; tok = tok->next()) { for (Token *tok = list.front(); tok; tok = tok->next()) {
if (tok->tokType() != Token::eType && tok->tokType() != Token::eName) if (tok->tokType() != Token::eType && tok->tokType() != Token::eName)
continue; continue;
const Library::PlatformType * const platformtype = _settings->library.platform_type(tok->str(), platform_type); const Library::PlatformType * const platformtype = mSettings->library.platform_type(tok->str(), platform_type);
if (platformtype) { if (platformtype) {
// check for namespace // check for namespace
@ -6566,7 +6566,7 @@ bool Tokenizer::simplifyKnownVariables()
bool valueIsPointer = false; bool valueIsPointer = false;
// there could be a hang here if tok2 is moved back by the function calls below for some reason // there could be a hang here if tok2 is moved back by the function calls below for some reason
if (_settings->terminated()) if (mSettings->terminated())
return false; return false;
if (!simplifyKnownVariablesGetData(varid, &tok2, &tok3, value, valueVarId, valueIsPointer, floatvars.find(tok2->varId()) != floatvars.end())) if (!simplifyKnownVariablesGetData(varid, &tok2, &tok3, value, valueVarId, valueIsPointer, floatvars.find(tok2->varId()) != floatvars.end()))
@ -6599,7 +6599,7 @@ bool Tokenizer::simplifyKnownVariables()
ret |= simplifyKnownVariablesSimplify(&tok2, tok3, varid, emptyString, value, valueVarId, valueIsPointer, valueToken, indentlevel); ret |= simplifyKnownVariablesSimplify(&tok2, tok3, varid, emptyString, value, valueVarId, valueIsPointer, valueToken, indentlevel);
// there could be a hang here if tok2 was moved back by the function call above for some reason // there could be a hang here if tok2 was moved back by the function call above for some reason
if (_settings->terminated()) if (mSettings->terminated())
return false; return false;
} }
} }
@ -6684,10 +6684,10 @@ bool Tokenizer::simplifyKnownVariablesSimplify(Token **tok2, Token *tok3, unsign
{ {
const bool pointeralias(valueToken->isName() || Token::Match(valueToken, "& %name% [")); const bool pointeralias(valueToken->isName() || Token::Match(valueToken, "& %name% ["));
const bool varIsGlobal = (indentlevel == 0); const bool varIsGlobal = (indentlevel == 0);
const bool printDebug = _settings->debugwarnings; const bool printDebug = mSettings->debugwarnings;
if (_errorLogger && !list.getFiles().empty()) if (mErrorLogger && !list.getFiles().empty())
_errorLogger->reportProgress(list.getFiles()[0], "Tokenize (simplifyKnownVariables)", tok3->progressValue()); mErrorLogger->reportProgress(list.getFiles()[0], "Tokenize (simplifyKnownVariables)", tok3->progressValue());
if (isMaxTime()) if (isMaxTime())
return false; return false;
@ -7574,10 +7574,10 @@ void Tokenizer::simplifyStd()
bool Tokenizer::IsScopeNoReturn(const Token *endScopeToken, bool *unknown) const bool Tokenizer::IsScopeNoReturn(const Token *endScopeToken, bool *unknown) const
{ {
std::string unknownFunc; std::string unknownFunc;
const bool ret = _settings->library.isScopeNoReturn(endScopeToken,&unknownFunc); const bool ret = mSettings->library.isScopeNoReturn(endScopeToken,&unknownFunc);
if (unknown) if (unknown)
*unknown = !unknownFunc.empty(); *unknown = !unknownFunc.empty();
if (!unknownFunc.empty() && _settings->checkLibrary && _settings->isEnabled(Settings::INFORMATION)) { if (!unknownFunc.empty() && mSettings->checkLibrary && mSettings->isEnabled(Settings::INFORMATION)) {
// Is function global? // Is function global?
bool globalFunction = true; bool globalFunction = true;
if (Token::simpleMatch(endScopeToken->tokAt(-2), ") ; }")) { if (Token::simpleMatch(endScopeToken->tokAt(-2), ") ; }")) {
@ -8273,7 +8273,7 @@ void Tokenizer::simplifyComma()
void Tokenizer::checkConfiguration() const void Tokenizer::checkConfiguration() const
{ {
if (!_settings->checkConfiguration) if (!mSettings->checkConfiguration)
return; return;
for (const Token *tok = tokens(); tok; tok = tok->next()) { for (const Token *tok = tokens(); tok; tok = tok->next()) {
if (!Token::Match(tok, "%name% (")) if (!Token::Match(tok, "%name% ("))
@ -8851,7 +8851,7 @@ void Tokenizer::simplifyStructDecl()
void Tokenizer::simplifyCallingConvention() void Tokenizer::simplifyCallingConvention()
{ {
const bool windows = _settings->isWindowsPlatform(); const bool windows = mSettings->isWindowsPlatform();
for (Token *tok = list.front(); tok; tok = tok->next()) { for (Token *tok = list.front(); tok; tok = tok->next()) {
while (Token::Match(tok, "__cdecl|__stdcall|__fastcall|__thiscall|__clrcall|__syscall|__pascal|__fortran|__far|__near") || (windows && Token::Match(tok, "WINAPI|APIENTRY|CALLBACK"))) { while (Token::Match(tok, "__cdecl|__stdcall|__fastcall|__thiscall|__clrcall|__syscall|__pascal|__fortran|__far|__near") || (windows && Token::Match(tok, "WINAPI|APIENTRY|CALLBACK"))) {
@ -8887,10 +8887,10 @@ void Tokenizer::simplifyDeclspec()
void Tokenizer::simplifyAttribute() void Tokenizer::simplifyAttribute()
{ {
for (Token *tok = list.front(); tok; tok = tok->next()) { for (Token *tok = list.front(); tok; tok = tok->next()) {
if (Token::Match(tok, "%type% (") && !_settings->library.isNotLibraryFunction(tok)) { if (Token::Match(tok, "%type% (") && !mSettings->library.isNotLibraryFunction(tok)) {
if (_settings->library.isFunctionConst(tok->str(), true)) if (mSettings->library.isFunctionConst(tok->str(), true))
tok->isAttributePure(true); tok->isAttributePure(true);
if (_settings->library.isFunctionConst(tok->str(), false)) if (mSettings->library.isFunctionConst(tok->str(), false))
tok->isAttributeConst(true); tok->isAttributeConst(true);
} }
while (Token::Match(tok, "__attribute__|__attribute (") && tok->next()->link() && tok->next()->link()->next()) { while (Token::Match(tok, "__attribute__|__attribute (") && tok->next()->link() && tok->next()->link()->next()) {
@ -8988,7 +8988,7 @@ void Tokenizer::simplifyAttribute()
void Tokenizer::simplifyCPPAttribute() void Tokenizer::simplifyCPPAttribute()
{ {
if (_settings->standards.cpp < Standards::CPP11 || isC()) if (mSettings->standards.cpp < Standards::CPP11 || isC())
return; return;
for (Token *tok = list.front(); tok; tok = tok->next()) { for (Token *tok = list.front(); tok; tok = tok->next()) {
@ -9038,13 +9038,13 @@ void Tokenizer::simplifyKeyword()
tok->deleteThis(); // Simplify.. tok->deleteThis(); // Simplify..
} }
if (isC() || _settings->standards.cpp == Standards::CPP03) { if (isC() || mSettings->standards.cpp == Standards::CPP03) {
if (tok->str() == "auto") if (tok->str() == "auto")
tok->deleteThis(); tok->deleteThis();
} }
if (_settings->standards.c >= Standards::C99) { if (mSettings->standards.c >= Standards::C99) {
while (tok->str() == "restrict") { while (tok->str() == "restrict") {
tok->deleteThis(); tok->deleteThis();
} }
@ -9056,13 +9056,13 @@ void Tokenizer::simplifyKeyword()
} }
} }
if (_settings->standards.c >= Standards::C11) { if (mSettings->standards.c >= Standards::C11) {
while (tok->str() == "_Atomic") { while (tok->str() == "_Atomic") {
tok->deleteThis(); tok->deleteThis();
} }
} }
if (isCPP() && _settings->standards.cpp >= Standards::CPP11) { if (isCPP() && mSettings->standards.cpp >= Standards::CPP11) {
while (tok->str() == "constexpr") { while (tok->str() == "constexpr") {
tok->deleteThis(); tok->deleteThis();
} }
@ -9430,7 +9430,7 @@ void Tokenizer::simplifyNamespaceStd()
if (!isCPP()) if (!isCPP())
return; return;
const bool isCPP11 = _settings->standards.cpp == Standards::CPP11; const bool isCPP11 = mSettings->standards.cpp == Standards::CPP11;
for (const Token* tok = Token::findsimplematch(list.front(), "using namespace std ;"); tok; tok = tok->next()) { for (const Token* tok = Token::findsimplematch(list.front(), "using namespace std ;"); tok; tok = tok->next()) {
bool insert = false; bool insert = false;
@ -9470,7 +9470,7 @@ void Tokenizer::simplifyNamespaceStd()
void Tokenizer::simplifyMicrosoftMemoryFunctions() void Tokenizer::simplifyMicrosoftMemoryFunctions()
{ {
// skip if not Windows // skip if not Windows
if (!_settings->isWindowsPlatform()) if (!mSettings->isWindowsPlatform())
return; return;
for (Token *tok = list.front(); tok; tok = tok->next()) { for (Token *tok = list.front(); tok; tok = tok->next()) {
@ -9565,10 +9565,10 @@ namespace {
void Tokenizer::simplifyMicrosoftStringFunctions() void Tokenizer::simplifyMicrosoftStringFunctions()
{ {
// skip if not Windows // skip if not Windows
if (!_settings->isWindowsPlatform()) if (!mSettings->isWindowsPlatform())
return; return;
const bool ansi = _settings->platformType == Settings::Win32A; const bool ansi = mSettings->platformType == Settings::Win32A;
for (Token *tok = list.front(); tok; tok = tok->next()) { for (Token *tok = list.front(); tok; tok = tok->next()) {
if (tok->strAt(1) != "(") if (tok->strAt(1) != "(")
continue; continue;
@ -9598,7 +9598,7 @@ void Tokenizer::simplifyMicrosoftStringFunctions()
void Tokenizer::simplifyBorland() void Tokenizer::simplifyBorland()
{ {
// skip if not Windows // skip if not Windows
if (!_settings->isWindowsPlatform()) if (!mSettings->isWindowsPlatform())
return; return;
if (isC()) if (isC())
return; return;
@ -9702,7 +9702,7 @@ void Tokenizer::simplifyQtSignalsSlots()
void Tokenizer::createSymbolDatabase() void Tokenizer::createSymbolDatabase()
{ {
if (!_symbolDatabase) if (!_symbolDatabase)
_symbolDatabase = new SymbolDatabase(this, _settings, _errorLogger); _symbolDatabase = new SymbolDatabase(this, mSettings, mErrorLogger);
_symbolDatabase->validate(); _symbolDatabase->validate();
} }
@ -9801,7 +9801,7 @@ void Tokenizer::simplifyOperatorName()
} }
} }
if (_settings->debugwarnings) { if (mSettings->debugwarnings) {
const Token *tok = list.front(); const Token *tok = list.front();
while ((tok = Token::findsimplematch(tok, "operator")) != nullptr) { while ((tok = Token::findsimplematch(tok, "operator")) != nullptr) {
@ -10156,22 +10156,22 @@ void Tokenizer::reportError(const Token* tok, const Severity::SeverityType sever
void Tokenizer::reportError(const std::list<const Token*>& callstack, Severity::SeverityType severity, const std::string& id, const std::string& msg, bool inconclusive) const void Tokenizer::reportError(const std::list<const Token*>& callstack, Severity::SeverityType severity, const std::string& id, const std::string& msg, bool inconclusive) const
{ {
const ErrorLogger::ErrorMessage errmsg(callstack, &list, severity, id, msg, inconclusive); const ErrorLogger::ErrorMessage errmsg(callstack, &list, severity, id, msg, inconclusive);
if (_errorLogger) if (mErrorLogger)
_errorLogger->reportErr(errmsg); mErrorLogger->reportErr(errmsg);
else else
Check::reportError(errmsg); Check::reportError(errmsg);
} }
void Tokenizer::setPodTypes() void Tokenizer::setPodTypes()
{ {
if (!_settings) if (!mSettings)
return; return;
for (Token *tok = list.front(); tok; tok = tok->next()) { for (Token *tok = list.front(); tok; tok = tok->next()) {
if (!tok->isName()) if (!tok->isName())
continue; continue;
// pod type // pod type
const struct Library::PodType *podType = _settings->library.podtype(tok->str()); const struct Library::PodType *podType = mSettings->library.podtype(tok->str());
if (podType) { if (podType) {
const Token *prev = tok->previous(); const Token *prev = tok->previous();
while (prev && prev->isName()) while (prev && prev->isName())

View File

@ -769,7 +769,7 @@ public:
void setSettings(const Settings *settings) { void setSettings(const Settings *settings) {
_settings = settings; mSettings = settings;
list.setSettings(settings); list.setSettings(settings);
} }
@ -866,10 +866,10 @@ private:
void setPodTypes(); void setPodTypes();
/** settings */ /** settings */
const Settings * _settings; const Settings * mSettings;
/** errorlogger */ /** errorlogger */
ErrorLogger* const _errorLogger; ErrorLogger* const mErrorLogger;
/** Symbol database that all checks etc can use */ /** Symbol database that all checks etc can use */
SymbolDatabase *_symbolDatabase; SymbolDatabase *_symbolDatabase;

View File

@ -39,7 +39,7 @@ static const unsigned int AST_MAX_DEPTH = 50U;
TokenList::TokenList(const Settings* settings) : TokenList::TokenList(const Settings* settings) :
_tokensFrontBack(), _tokensFrontBack(),
_settings(settings), mSettings(settings),
_isC(false), _isC(false),
_isCPP(false) _isCPP(false)
{ {
@ -83,12 +83,12 @@ unsigned int TokenList::appendFileIfNew(const std::string &fileName)
// Update _isC and _isCPP properties // Update _isC and _isCPP properties
if (_files.size() == 1) { // Update only useful if first file added to _files if (_files.size() == 1) { // Update only useful if first file added to _files
if (!_settings) { if (!mSettings) {
_isC = Path::isC(getSourceFilePath()); _isC = Path::isC(getSourceFilePath());
_isCPP = Path::isCPP(getSourceFilePath()); _isCPP = Path::isCPP(getSourceFilePath());
} else { } else {
_isC = _settings->enforcedLang == Settings::C || (_settings->enforcedLang == Settings::None && Path::isC(getSourceFilePath())); _isC = mSettings->enforcedLang == Settings::C || (mSettings->enforcedLang == Settings::None && Path::isC(getSourceFilePath()));
_isCPP = _settings->enforcedLang == Settings::CPP || (_settings->enforcedLang == Settings::None && Path::isCPP(getSourceFilePath())); _isCPP = mSettings->enforcedLang == Settings::CPP || (mSettings->enforcedLang == Settings::None && Path::isCPP(getSourceFilePath()));
} }
} }
return _files.size() - 1U; return _files.size() - 1U;
@ -133,7 +133,7 @@ void TokenList::addtoken(std::string str, const unsigned int lineno, const unsig
// TODO: It would be better if TokenList didn't simplify hexadecimal numbers // TODO: It would be better if TokenList didn't simplify hexadecimal numbers
std::string suffix; std::string suffix;
if (isHex && if (isHex &&
str.size() == (2 + _settings->int_bit / 4) && str.size() == (2 + mSettings->int_bit / 4) &&
(str[2] >= '8') && // includes A-F and a-f (str[2] >= '8') && // includes A-F and a-f
MathLib::getSuffix(str).empty() MathLib::getSuffix(str).empty()
) )
@ -275,9 +275,9 @@ void TokenList::createTokens(const simplecpp::TokenList *tokenList)
_isC = Path::isC(getSourceFilePath()); _isC = Path::isC(getSourceFilePath());
_isCPP = Path::isCPP(getSourceFilePath()); _isCPP = Path::isCPP(getSourceFilePath());
} }
if (_settings && _settings->enforcedLang != Settings::None) { if (mSettings && mSettings->enforcedLang != Settings::None) {
_isC = (_settings->enforcedLang == Settings::C); _isC = (mSettings->enforcedLang == Settings::C);
_isCPP = (_settings->enforcedLang == Settings::CPP); _isCPP = (mSettings->enforcedLang == Settings::CPP);
} }
for (const simplecpp::Token *tok = tokenList->cfront(); tok; tok = tok->next) { for (const simplecpp::Token *tok = tokenList->cfront(); tok; tok = tok->next) {
@ -291,8 +291,8 @@ void TokenList::createTokens(const simplecpp::TokenList *tokenList)
// TODO: It would be better if TokenList didn't simplify hexadecimal numbers // TODO: It would be better if TokenList didn't simplify hexadecimal numbers
std::string suffix; std::string suffix;
if (isHex && if (isHex &&
_settings && mSettings &&
str.size() == (2 + _settings->int_bit / 4) && str.size() == (2 + mSettings->int_bit / 4) &&
(str[2] >= '8') && // includes A-F and a-f (str[2] >= '8') && // includes A-F and a-f
MathLib::getSuffix(str).empty() MathLib::getSuffix(str).empty()
) )
@ -320,9 +320,9 @@ void TokenList::createTokens(const simplecpp::TokenList *tokenList)
_tokensFrontBack.back->isExpandedMacro(!tok->macro.empty()); _tokensFrontBack.back->isExpandedMacro(!tok->macro.empty());
} }
if (_settings && _settings->relativePaths) { if (mSettings && mSettings->relativePaths) {
for (std::size_t i = 0; i < _files.size(); i++) for (std::size_t i = 0; i < _files.size(); i++)
_files[i] = Path::getRelativePath(_files[i], _settings->basePaths); _files[i] = Path::getRelativePath(_files[i], mSettings->basePaths);
} }
Token::assignProgressValues(_tokensFrontBack.front); Token::assignProgressValues(_tokensFrontBack.front);
@ -1226,7 +1226,7 @@ bool TokenList::validateToken(const Token* tok) const
void TokenList::simplifyStdType() void TokenList::simplifyStdType()
{ {
for (Token *tok = front(); tok; tok = tok->next()) { for (Token *tok = front(); tok; tok = tok->next()) {
if (Token::Match(tok, "char|short|int|long|unsigned|signed|double|float") || (_settings->standards.c >= Standards::C99 && Token::Match(tok, "complex|_Complex"))) { if (Token::Match(tok, "char|short|int|long|unsigned|signed|double|float") || (mSettings->standards.c >= Standards::C99 && Token::Match(tok, "complex|_Complex"))) {
bool isFloat= false; bool isFloat= false;
bool isSigned = false; bool isSigned = false;
bool isUnsigned = false; bool isUnsigned = false;
@ -1249,7 +1249,7 @@ void TokenList::simplifyStdType()
else if (Token::Match(tok2, "float|double")) { else if (Token::Match(tok2, "float|double")) {
isFloat = true; isFloat = true;
typeSpec = tok2; typeSpec = tok2;
} else if (_settings->standards.c >= Standards::C99 && Token::Match(tok2, "complex|_Complex")) } else if (mSettings->standards.c >= Standards::C99 && Token::Match(tok2, "complex|_Complex"))
isComplex = !isFloat || tok2->str() == "_Complex" || Token::Match(tok2->next(), "*|&|%name%"); // Ensure that "complex" is not the variables name isComplex = !isFloat || tok2->str() == "_Complex" || Token::Match(tok2->next(), "*|&|%name%"); // Ensure that "complex" is not the variables name
else if (Token::Match(tok2, "char|int")) { else if (Token::Match(tok2, "char|int")) {
if (!typeSpec) if (!typeSpec)

View File

@ -43,11 +43,11 @@ public:
~TokenList(); ~TokenList();
void setSettings(const Settings *settings) { void setSettings(const Settings *settings) {
_settings = settings; mSettings = settings;
} }
const Settings *getSettings() const { const Settings *getSettings() const {
return _settings; return mSettings;
} }
/** @return the source file path. e.g. "file.cpp" */ /** @return the source file path. e.g. "file.cpp" */
@ -188,7 +188,7 @@ private:
std::vector<std::string> _files; std::vector<std::string> _files;
/** settings */ /** settings */
const Settings* _settings; const Settings* mSettings;
/** File is known to be C/C++ code */ /** File is known to be C/C++ code */
bool _isC, _isCPP; bool _isC, _isCPP;