From b6504c70cae19563e7d586c040474b67594107fc Mon Sep 17 00:00:00 2001 From: jrp2014 Date: Wed, 4 Apr 2018 21:51:31 +0200 Subject: [PATCH] Improve constness --- lib/analyzerinfo.cpp | 2 +- lib/checkbufferoverrun.cpp | 24 +++++++++++------------ lib/checkclass.cpp | 6 +++--- lib/checkcondition.cpp | 11 +++++------ lib/checkexceptionsafety.h | 2 +- lib/checkfunctions.cpp | 6 +++--- lib/checkio.cpp | 16 +++++++-------- lib/checkleakautovar.cpp | 16 +++++++-------- lib/checkmemoryleak.cpp | 6 +++--- lib/checkmemoryleak.h | 2 +- lib/checknullpointer.cpp | 2 +- lib/checkother.cpp | 16 +++++++-------- lib/checkother.h | 2 +- lib/checksizeof.cpp | 8 ++++---- lib/checkstl.cpp | 20 +++++++++---------- lib/checkstring.cpp | 18 ++++++++--------- lib/checkuninitvar.cpp | 18 ++++++++--------- lib/checkunusedfunctions.cpp | 2 +- lib/checkunusedvar.cpp | 2 +- lib/importproject.cpp | 14 ++++++------- lib/library.cpp | 38 ++++++++++++++++++------------------ lib/library.h | 4 ++-- lib/mathlib.cpp | 2 +- lib/preprocessor.cpp | 12 ++++++------ lib/suppressions.cpp | 4 ++-- lib/symboldatabase.cpp | 27 ++++++++++++------------- lib/templatesimplifier.cpp | 12 ++++++------ lib/timer.cpp | 2 +- lib/token.cpp | 6 +++--- lib/tokenize.cpp | 22 ++++++++++----------- lib/valueflow.cpp | 8 ++++---- 31 files changed, 164 insertions(+), 166 deletions(-) diff --git a/lib/analyzerinfo.cpp b/lib/analyzerinfo.cpp index f2b2a70f6..bda60a38d 100644 --- a/lib/analyzerinfo.cpp +++ b/lib/analyzerinfo.cpp @@ -76,7 +76,7 @@ void AnalyzerInformation::close() static bool skipAnalysis(const std::string &analyzerInfoFile, unsigned long long checksum, std::list *errors) { tinyxml2::XMLDocument doc; - tinyxml2::XMLError error = doc.LoadFile(analyzerInfoFile.c_str()); + const tinyxml2::XMLError error = doc.LoadFile(analyzerInfoFile.c_str()); if (error != tinyxml2::XML_SUCCESS) return false; diff --git a/lib/checkbufferoverrun.cpp b/lib/checkbufferoverrun.cpp index af7823a24..9eaedc1ac 100644 --- a/lib/checkbufferoverrun.cpp +++ b/lib/checkbufferoverrun.cpp @@ -233,8 +233,8 @@ void CheckBufferOverrun::pointerOutOfBoundsError(const Token *tok, const Token * } else { errmsg = "Undefined behaviour, pointer arithmetic '" + expr + "' is out of bounds"; } - std::string verbosemsg(errmsg + ". From chapter 6.5.6 in the C specification:\n" - "\"When an expression that has integer type is added to or subtracted from a pointer, ..\" and then \"If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.\""); + const std::string verbosemsg(errmsg + ". From chapter 6.5.6 in the C specification:\n" + "\"When an expression that has integer type is added to or subtracted from a pointer, ..\" and then \"If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.\""); reportError(tok, Severity::portability, "pointerOutOfBounds", errmsg + ".\n" + verbosemsg, CWE398, false); /* "Undefined behaviour: The result of this pointer arithmetic does not point into @@ -483,7 +483,7 @@ void CheckBufferOverrun::checkFunctionParameter(const Token &ftok, unsigned int std::list callstack2(callstack); callstack2.push_back(ftok2); - std::vector indexes(1, index); + const std::vector indexes(1, index); arrayIndexOutOfBoundsError(callstack2, arrayInfo, indexes); } } @@ -917,7 +917,7 @@ void CheckBufferOverrun::checkScope(const Token *tok, std::mapvariable() || tok->variable()->nameToken() == tok) continue; - std::map::const_iterator arrayInfo = arrayInfos.find(tok->varId()); + const std::map::const_iterator arrayInfo = arrayInfos.find(tok->varId()); if (arrayInfo == arrayInfos.cend()) continue; @@ -1304,7 +1304,7 @@ void CheckBufferOverrun::checkGlobalAndLocalVariable() if (totalSize == 0) continue; - ArrayInfo temp(var->declarationId(), var->name(), totalSize / size, size); + const ArrayInfo temp(var->declarationId(), var->name(), totalSize / size, size); checkScope(nextTok, v, temp); } } @@ -1420,7 +1420,7 @@ void CheckBufferOverrun::checkStructVariable() continue; // calculate real array size based on allocated size - MathLib::bigint elements = (size - 100) / arrayInfo.element_size(); + const MathLib::bigint elements = (size - 100) / arrayInfo.element_size(); arrayInfo.num(0, arrayInfo.num(0) + elements); } } @@ -1547,7 +1547,7 @@ void CheckBufferOverrun::bufferOverrun() // char arr[10] = "123"; // arr[7] = 'x'; // warning: arr[7] is inside the array bounds, but past the string's end - ArrayInfo arrayInfo(tok->varId(), varname, 1U, Token::getStrSize(strtoken)); + const ArrayInfo arrayInfo(tok->varId(), varname, 1U, Token::getStrSize(strtoken)); valueFlowCheckArrayIndex(tok->next(), arrayInfo); } else { if (var->nameToken() == tok || !var->isArray()) @@ -1697,7 +1697,7 @@ void CheckBufferOverrun::checkBufferAllocatedWithStrlen() for (std::size_t i = 0; i < functions; ++i) { const Scope * scope = symbolDatabase->functionScopes[i]; for (const Token *tok = scope->classStart->next(); tok && tok != scope->classEnd; tok = tok->next()) { - unsigned int dstVarId = tok->varId(); + const unsigned int dstVarId = tok->varId(); if (!dstVarId || tok->strAt(1) != "=") continue; @@ -2002,7 +2002,7 @@ Check::FileInfo* CheckBufferOverrun::getFileInfo(const Tokenizer *tokenizer, con const ValueFlow::Value *value = tok->next()->astOperand2()->getMaxValue(false); if (value && value->intvalue > 0) { const MathLib::bigint arrayIndex = value->intvalue; - std::map::iterator it = fileInfo->arrayUsage.find(tok->str()); + const std::map::iterator it = fileInfo->arrayUsage.find(tok->str()); if (it != fileInfo->arrayUsage.end() && it->second.index >= arrayIndex) continue; struct MyFileInfo::ArrayUsage arrayUsage; @@ -2070,14 +2070,14 @@ bool CheckBufferOverrun::analyseWholeProgram(const std::list & // merge array usage for (std::map::const_iterator it2 = fi->arrayUsage.begin(); it2 != fi->arrayUsage.end(); ++it2) { - std::map::const_iterator allit = all.arrayUsage.find(it2->first); + const std::map::const_iterator allit = all.arrayUsage.find(it2->first); if (allit == all.arrayUsage.end() || it2->second.index > allit->second.index) all.arrayUsage[it2->first] = it2->second; } // merge array info for (std::map::const_iterator it2 = fi->arraySize.begin(); it2 != fi->arraySize.end(); ++it2) { - std::map::const_iterator allit = all.arraySize.find(it2->first); + const std::map::const_iterator allit = all.arraySize.find(it2->first); if (allit == all.arraySize.end()) all.arraySize[it2->first] = it2->second; else @@ -2087,7 +2087,7 @@ bool CheckBufferOverrun::analyseWholeProgram(const std::list & // Check buffer usage for (std::map::const_iterator it = all.arrayUsage.begin(); it != all.arrayUsage.end(); ++it) { - std::map::const_iterator sz = all.arraySize.find(it->first); + const std::map::const_iterator sz = all.arraySize.find(it->first); if (sz != all.arraySize.end() && sz->second > 0 && sz->second < it->second.index) { ErrorLogger::ErrorMessage::FileLocation fileLoc; fileLoc.setfile(it->second.fileName); diff --git a/lib/checkclass.cpp b/lib/checkclass.cpp index be4522962..2e43354ef 100644 --- a/lib/checkclass.cpp +++ b/lib/checkclass.cpp @@ -1092,11 +1092,11 @@ void CheckClass::checkMemset() type = typeTok->type()->classScope; if (type) { - std::set parsedTypes; + const std::set parsedTypes; checkMemsetType(scope, tok, type, false, parsedTypes); } } else if (tok->variable() && tok->variable()->typeScope() && Token::Match(tok, "%var% = calloc|malloc|realloc|g_malloc|g_try_malloc|g_realloc|g_try_realloc (")) { - std::set parsedTypes; + const std::set parsedTypes; checkMemsetType(scope, tok->tokAt(2), tok->variable()->typeScope(), true, parsedTypes); if (printWarnings && tok->variable()->typeScope()->numConstructors > 0) @@ -1648,7 +1648,7 @@ void CheckClass::virtualDestructor() if (baseDestructor->access == Public) { virtualDestructorError(baseDestructor->token, derivedFrom->name(), derivedClass->str(), false); // check for duplicate error and remove it if found - std::list::iterator found = find(inconclusiveErrors.begin(), inconclusiveErrors.end(), baseDestructor); + const std::list::iterator found = find(inconclusiveErrors.begin(), inconclusiveErrors.end(), baseDestructor); if (found != inconclusiveErrors.end()) inconclusiveErrors.erase(found); } diff --git a/lib/checkcondition.cpp b/lib/checkcondition.cpp index 4d50199b7..61159afec 100644 --- a/lib/checkcondition.cpp +++ b/lib/checkcondition.cpp @@ -1335,12 +1335,11 @@ void CheckCondition::checkInvalidTestForOverflow() void CheckCondition::invalidTestForOverflow(const Token* tok, bool result) { - std::string errmsg; - errmsg = "Invalid test for overflow '" + - (tok ? tok->expressionString() : std::string("x + u < x")) + - "'. Condition is always " + - std::string(result ? "true" : "false") + - " unless there is overflow, and overflow is undefined behaviour."; + const std::string errmsg = "Invalid test for overflow '" + + (tok ? tok->expressionString() : std::string("x + u < x")) + + "'. Condition is always " + + std::string(result ? "true" : "false") + + " unless there is overflow, and overflow is undefined behaviour."; reportError(tok, Severity::warning, "invalidTestForOverflow", errmsg, (result ? CWE571 : CWE570), false); } diff --git a/lib/checkexceptionsafety.h b/lib/checkexceptionsafety.h index 9ba5355b5..60bab7f7c 100644 --- a/lib/checkexceptionsafety.h +++ b/lib/checkexceptionsafety.h @@ -128,7 +128,7 @@ private: /** Missing exception specification */ void unhandledExceptionSpecificationError(const Token * const tok1, const Token * const tok2, const std::string & funcname) { - std::string str1(tok1 ? tok1->str() : "foo"); + const std::string str1(tok1 ? tok1->str() : "foo"); const std::list locationList = make_container< std::list > () << tok1 << tok2; reportError(locationList, Severity::style, "unhandledExceptionSpecification", "Unhandled exception specification when calling function " + str1 + "().\n" diff --git a/lib/checkfunctions.cpp b/lib/checkfunctions.cpp index 608bd85da..0af7b09a1 100644 --- a/lib/checkfunctions.cpp +++ b/lib/checkfunctions.cpp @@ -228,9 +228,9 @@ void CheckFunctions::checkMathFunctions() if (tok->strAt(-1) != "." && Token::Match(tok, "log|logf|logl|log10|log10f|log10l ( %num% )")) { const std::string& number = tok->strAt(2); - bool isNegative = MathLib::isNegative(number); - bool isInt = MathLib::isInt(number); - bool isFloat = MathLib::isFloat(number); + const bool isNegative = MathLib::isNegative(number); + const bool isInt = MathLib::isInt(number); + const bool isFloat = MathLib::isFloat(number); if (isNegative && isInt && MathLib::toLongNumber(number) <= 0) { mathfunctionCallWarning(tok); // case log(-2) } else if (isNegative && isFloat && MathLib::toDoubleNumber(number) <= 0.) { diff --git a/lib/checkio.cpp b/lib/checkio.cpp index 447d43e45..b7cb4d5eb 100644 --- a/lib/checkio.cpp +++ b/lib/checkio.cpp @@ -62,7 +62,7 @@ void CheckIO::checkCoutCerrMisusage() return; const SymbolDatabase * const symbolDatabase = _tokenizer->getSymbolDatabase(); - std::size_t functions = symbolDatabase->functionScopes.size(); + const std::size_t functions = symbolDatabase->functionScopes.size(); for (std::size_t i = 0; i < functions; ++i) { const Scope * scope = symbolDatabase->functionScopes[i]; for (const Token *tok = scope->classStart; tok && tok != scope->classEnd; tok = tok->next()) { @@ -127,7 +127,7 @@ void CheckIO::checkFileUsage() std::map filepointers; const SymbolDatabase* symbolDatabase = _tokenizer->getSymbolDatabase(); - std::size_t varListSize = symbolDatabase->getVariableListSize(); + const std::size_t varListSize = symbolDatabase->getVariableListSize(); for (std::size_t i = 1; i < varListSize; ++i) { const Variable* var = symbolDatabase->getVariableFromVarId(i); if (!var || !var->declarationId() || var->isArray() || !Token::simpleMatch(var->typeStartToken(), "FILE *")) @@ -144,7 +144,7 @@ void CheckIO::checkFileUsage() } } - std::size_t functions = symbolDatabase->functionScopes.size(); + const std::size_t functions = symbolDatabase->functionScopes.size(); for (std::size_t j = 0; j < functions; ++j) { const Scope * scope = symbolDatabase->functionScopes[j]; unsigned int indent = 0; @@ -387,7 +387,7 @@ void CheckIO::invalidScanf() return; const SymbolDatabase * const symbolDatabase = _tokenizer->getSymbolDatabase(); - std::size_t functions = symbolDatabase->functionScopes.size(); + const std::size_t functions = symbolDatabase->functionScopes.size(); for (std::size_t j = 0; j < functions; ++j) { const Scope * scope = symbolDatabase->functionScopes[j]; for (const Token *tok = scope->classStart->next(); tok != scope->classEnd; tok = tok->next()) { @@ -430,7 +430,7 @@ void CheckIO::invalidScanf() void CheckIO::invalidScanfError(const Token *tok) { - std::string fname = (tok ? tok->str() : std::string("scanf")); + const std::string fname = (tok ? tok->str() : std::string("scanf")); reportError(tok, Severity::warning, "invalidscanf", fname + "() without field width limits can crash with huge input data.\n" + fname + "() without field width limits can crash with huge input data. Add a field width " @@ -502,7 +502,7 @@ void CheckIO::checkWrongPrintfScanfArguments() const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const bool isWindows = _settings->isWindowsPlatform(); - std::size_t functions = symbolDatabase->functionScopes.size(); + const std::size_t functions = symbolDatabase->functionScopes.size(); for (std::size_t j = 0; j < functions; ++j) { const Scope * scope = symbolDatabase->functionScopes[j]; for (const Token *tok = scope->classStart->next(); tok != scope->classEnd; tok = tok->next()) { @@ -682,7 +682,7 @@ void CheckIO::checkFormatString(const Token * const tok, specifier += *i; if (argInfo.variableInfo && argInfo.isKnownType() && argInfo.variableInfo->isArray() && (argInfo.variableInfo->dimensions().size() == 1) && argInfo.variableInfo->dimensions()[0].known) { if (!width.empty()) { - int numWidth = std::atoi(width.c_str()); + const int numWidth = std::atoi(width.c_str()); if (numWidth != (argInfo.variableInfo->dimension(0) - 1)) invalidScanfFormatWidthError(tok, numFormat, numWidth, argInfo.variableInfo, 's'); } @@ -705,7 +705,7 @@ void CheckIO::checkFormatString(const Token * const tok, case 'c': if (argInfo.variableInfo && argInfo.isKnownType() && argInfo.variableInfo->isArray() && (argInfo.variableInfo->dimensions().size() == 1) && argInfo.variableInfo->dimensions()[0].known) { if (!width.empty()) { - int numWidth = std::atoi(width.c_str()); + const int numWidth = std::atoi(width.c_str()); if (numWidth > argInfo.variableInfo->dimension(0)) invalidScanfFormatWidthError(tok, numFormat, numWidth, argInfo.variableInfo, 'c'); } diff --git a/lib/checkleakautovar.cpp b/lib/checkleakautovar.cpp index 57855b518..2f1ab6e2d 100644 --- a/lib/checkleakautovar.cpp +++ b/lib/checkleakautovar.cpp @@ -106,7 +106,7 @@ void CheckLeakAutoVar::leakError(const Token *tok, const std::string &varname, i void CheckLeakAutoVar::mismatchError(const Token *tok, const std::string &varname) { const CheckMemoryLeak c(_tokenizer, _errorLogger, _settings); - std::list callstack(1, tok); + const std::list callstack(1, tok); c.mismatchAllocDealloc(callstack, varname); } @@ -221,7 +221,7 @@ void CheckLeakAutoVar::checkScope(const Token * const startToken, } if (tok->str() == "(" && tok->previous()->isName()) { - VarInfo::AllocInfo allocation(0, VarInfo::NOALLOC); + const VarInfo::AllocInfo allocation(0, VarInfo::NOALLOC); functionCall(tok->previous(), varInfo, allocation, nullptr); tok = tok->link(); continue; @@ -305,7 +305,7 @@ void CheckLeakAutoVar::checkScope(const Token * const startToken, } } else if (_tokenizer->isCPP() && Token::Match(varTok->tokAt(2), "new !!(")) { const Token* tok2 = varTok->tokAt(2)->astOperand1(); - 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()]; varAlloc.type = arrayNew ? -2 : -1; varAlloc.status = VarInfo::ALLOC; @@ -336,7 +336,7 @@ void CheckLeakAutoVar::checkScope(const Token * const startToken, } } else if (_tokenizer->isCPP() && Token::Match(innerTok->tokAt(2), "new !!(")) { const Token* tok2 = innerTok->tokAt(2)->astOperand1(); - 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()]; varAlloc.type = arrayNew ? -2 : -1; varAlloc.status = VarInfo::ALLOC; @@ -346,7 +346,7 @@ void CheckLeakAutoVar::checkScope(const Token * const startToken, if (innerTok->str() == ")") break; if (innerTok->str() == "(" && innerTok->previous()->isName()) { - VarInfo::AllocInfo allocation(0, VarInfo::NOALLOC); + const VarInfo::AllocInfo allocation(0, VarInfo::NOALLOC); functionCall(innerTok->previous(), varInfo, allocation, nullptr); innerTok = innerTok->link(); } @@ -526,7 +526,7 @@ void CheckLeakAutoVar::checkScope(const Token * const startToken, // delete else if (_tokenizer->isCPP() && tok->str() == "delete") { - bool arrayDelete = (tok->strAt(1) == "["); + const bool arrayDelete = (tok->strAt(1) == "["); if (arrayDelete) tok = tok->tokAt(3); else @@ -535,7 +535,7 @@ void CheckLeakAutoVar::checkScope(const Token * const startToken, tok = tok->tokAt(2); const bool isnull = tok->hasKnownIntValue() && tok->values().front().intvalue == 0; if (!isnull && tok->varId() && tok->strAt(1) != "[") { - VarInfo::AllocInfo allocation(arrayDelete ? -2 : -1, VarInfo::DEALLOC); + const VarInfo::AllocInfo allocation(arrayDelete ? -2 : -1, VarInfo::DEALLOC); changeAllocStatus(varInfo, allocation, tok, tok); } } @@ -601,7 +601,7 @@ void CheckLeakAutoVar::functionCall(const Token *tok, VarInfo *varInfo, const Va if (arg->str() == "&") arg = arg->next(); - bool isnull = arg->hasKnownIntValue() && arg->values().front().intvalue == 0; + const bool isnull = arg->hasKnownIntValue() && arg->values().front().intvalue == 0; // Is variable allocated? if (!isnull && (!af || af->arg == argNr)) diff --git a/lib/checkmemoryleak.cpp b/lib/checkmemoryleak.cpp index 8c8dd232d..1ccbf66b2 100644 --- a/lib/checkmemoryleak.cpp +++ b/lib/checkmemoryleak.cpp @@ -148,7 +148,7 @@ CheckMemoryLeak::AllocType CheckMemoryLeak::getAllocationType(const Token *tok2, if (Token::Match(tok2, "open|openat|creat|mkstemp|mkostemp|socket (")) { // simple sanity check of function parameters.. // TODO: Make such check for all these functions - unsigned int num = countParameters(tok2); + const unsigned int num = countParameters(tok2); if (tok2->str() == "open" && num != 2 && num != 3) return No; @@ -353,7 +353,7 @@ CheckMemoryLeak::AllocType CheckMemoryLeak::functionReturnType(const Function* f unsigned int varid = 0; for (const Token *tok2 = func->functionScope->classStart; tok2 != func->functionScope->classEnd; tok2 = tok2->next()) { if (tok2->str() == "return") { - AllocType allocType = getAllocationType(tok2->next(), 0, callstack); + const AllocType allocType = getAllocationType(tok2->next(), 0, callstack); if (allocType != No) return allocType; @@ -2014,7 +2014,7 @@ const Token *CheckMemoryLeakInFunction::findleak(const Token *tokens) // Check for memory leaks for a function variable. void CheckMemoryLeakInFunction::checkScope(const Token *startTok, const std::string &varname, unsigned int varid, bool classmember, unsigned int sz) { - std::list callstack; + const std::list callstack; AllocType alloctype = No; AllocType dealloctype = No; diff --git a/lib/checkmemoryleak.h b/lib/checkmemoryleak.h index b3b59e988..12b026c8d 100644 --- a/lib/checkmemoryleak.h +++ b/lib/checkmemoryleak.h @@ -297,7 +297,7 @@ private: c.deallocDeallocError(nullptr, "varname"); c.deallocuseError(nullptr, "varname"); c.mismatchSizeError(nullptr, "sz"); - std::list callstack; + const std::list callstack; c.mismatchAllocDealloc(callstack, "varname"); c.memleakUponReallocFailureError(nullptr, "varname"); } diff --git a/lib/checknullpointer.cpp b/lib/checknullpointer.cpp index 09898acfe..677da04d8 100644 --- a/lib/checknullpointer.cpp +++ b/lib/checknullpointer.cpp @@ -87,7 +87,7 @@ void CheckNullPointer::parseFunctionCall(const Token &tok, std::liststrValue(); diff --git a/lib/checkother.cpp b/lib/checkother.cpp index 77623a58b..1131dac7c 100644 --- a/lib/checkother.cpp +++ b/lib/checkother.cpp @@ -562,7 +562,7 @@ void CheckOther::checkRedundantAssignment() membervars[startToken->varId()].insert(startToken->tokAt(2)->varId()); } - std::map::iterator it = varAssignments.find(tok->varId()); + const std::map::iterator it = varAssignments.find(tok->varId()); if (eq && Token::Match(startToken, "[;{}]")) { // Assignment if (it != varAssignments.end()) { const Token *oldeq = nullptr; @@ -810,8 +810,8 @@ void CheckOther::checkRedundantAssignmentInSwitch() else if (Token::Match(tok2->previous(), ";|{|}|: %var% %assign% %num% ;") && (tok2->strAt(1) == "|=" || tok2->strAt(1) == "&=") && Token::Match(tok2->next()->astOperand2(), "%num%")) { - std::string bitOp = tok2->strAt(1)[0] + tok2->strAt(2); - std::map::const_iterator i2 = varsWithBitsSet.find(tok2->varId()); + const std::string bitOp = tok2->strAt(1)[0] + tok2->strAt(2); + const std::map::const_iterator i2 = varsWithBitsSet.find(tok2->varId()); // This variable has not had a bit operation performed on it yet, so just make a note of it if (i2 == varsWithBitsSet.end()) { @@ -835,8 +835,8 @@ void CheckOther::checkRedundantAssignmentInSwitch() // case 4: b = b | 1; else if (Token::Match(tok2->previous(), ";|{|}|: %var% = %name% %or%|& %num% ;") && tok2->varId() == tok2->tokAt(2)->varId()) { - std::string bitOp = tok2->strAt(3) + tok2->strAt(4); - std::map::const_iterator i2 = varsWithBitsSet.find(tok2->varId()); + const std::string bitOp = tok2->strAt(3) + tok2->strAt(4); + const std::map::const_iterator i2 = varsWithBitsSet.find(tok2->varId()); // This variable has not had a bit operation performed on it yet, so just make a note of it if (i2 == varsWithBitsSet.end()) { @@ -1661,7 +1661,7 @@ void CheckOther::zerodivError(const Token *tok, const ValueFlow::Value *value) std::ostringstream errmsg; if (value->condition) { - unsigned int line = tok ? tok->linenr() : 0; + const unsigned int line = tok ? tok->linenr() : 0; errmsg << ValueFlow::eitherTheConditionIsRedundant(value->condition) << " or there is division by zero at line " << line << "."; } else @@ -1779,7 +1779,7 @@ void CheckOther::checkDuplicateBranch() continue; // save else branch code - std::string branch2 = scope->classEnd->tokAt(3)->stringifyList(scope->classEnd->linkAt(2)); + const std::string branch2 = scope->classEnd->tokAt(3)->stringifyList(scope->classEnd->linkAt(2)); // check for duplicates if (branch1 == branch2) @@ -2656,7 +2656,7 @@ void CheckOther::checkAccessOfMovedVariable() else inconclusive = true; } else { - bool isVariableChanged = isVariableChangedByFunctionCall(tok, _settings, &inconclusive); + const bool isVariableChanged = isVariableChangedByFunctionCall(tok, _settings, &inconclusive); accessOfMoved = !isVariableChanged; if (inconclusive) { accessOfMoved = !isMovedParameterAllowedForInconclusiveFunction(tok); diff --git a/lib/checkother.h b/lib/checkother.h index b3b4b0467..6f11f4a7d 100644 --- a/lib/checkother.h +++ b/lib/checkother.h @@ -318,7 +318,7 @@ private: c.accessMovedError(nullptr, "v", nullptr, false); c.funcArgNamesDifferent("function", 1, nullptr, nullptr); - std::vector nullvec; + const std::vector nullvec; c.funcArgOrderDifferent("function", nullptr, nullptr, nullvec, nullvec); } diff --git a/lib/checksizeof.cpp b/lib/checksizeof.cpp index ff3789bfb..aef609216 100644 --- a/lib/checksizeof.cpp +++ b/lib/checksizeof.cpp @@ -409,16 +409,16 @@ void CheckSizeof::sizeofVoid() // only warn for: 'void *' - 'integral' const ValueType *vt1 = tok->astOperand1() ? tok->astOperand1()->valueType() : nullptr; const ValueType *vt2 = tok->astOperand2() ? tok->astOperand2()->valueType() : nullptr; - bool op1IsvoidPointer = (vt1 && vt1->type == ValueType::Type::VOID && vt1->pointer == 1U); - bool op2IsIntegral = (vt2 && vt2->isIntegral() && vt2->pointer == 0U); + const bool op1IsvoidPointer = (vt1 && vt1->type == ValueType::Type::VOID && vt1->pointer == 1U); + const bool op2IsIntegral = (vt2 && vt2->isIntegral() && vt2->pointer == 0U); if (op1IsvoidPointer && op2IsIntegral) arithOperationsOnVoidPointerError(tok, tok->astOperand1()->expressionString(), vt1->str()); } else if (Token::Match(tok, "+|++|--|+=|-=")) { // Arithmetic operations on variable of type "void*" const ValueType *vt1 = tok->astOperand1() ? tok->astOperand1()->valueType() : nullptr; const ValueType *vt2 = tok->astOperand2() ? tok->astOperand2()->valueType() : nullptr; - bool voidpointer1 = (vt1 && vt1->type == ValueType::Type::VOID && vt1->pointer == 1U); - bool voidpointer2 = (vt2 && vt2->type == ValueType::Type::VOID && vt2->pointer == 1U); + const bool voidpointer1 = (vt1 && vt1->type == ValueType::Type::VOID && vt1->pointer == 1U); + const bool voidpointer2 = (vt2 && vt2->type == ValueType::Type::VOID && vt2->pointer == 1U); if (voidpointer1) arithOperationsOnVoidPointerError(tok, tok->astOperand1()->expressionString(), vt1->str()); diff --git a/lib/checkstl.cpp b/lib/checkstl.cpp index 9133fadc6..f803c4e28 100644 --- a/lib/checkstl.cpp +++ b/lib/checkstl.cpp @@ -370,13 +370,13 @@ void CheckStl::mismatchingContainers() mismatchingContainersError(argTok); } } - int ret = _settings->library.returnValueContainer(ftok); + const int ret = _settings->library.returnValueContainer(ftok); if (ret != -1 && Token::Match(ftok->next()->astParent(), "==|!=")) { const Token *parent = ftok->next()->astParent(); const Token *other = (parent->astOperand1() == ftok->next()) ? parent->astOperand2() : parent->astOperand1(); const Variable *c = getContainer(other); if (c) { - std::map::const_iterator it = containerNr.find(c); + const std::map::const_iterator it = containerNr.find(c); if (it == containerNr.end() || it->second != ret) mismatchingContainersError(other); } @@ -446,7 +446,7 @@ void CheckStl::stlOutOfBounds() } else if (container->arrayLike_indexOp && Token::Match(tok3, "[ %varid% ]", numId)) stlOutOfBoundsError(tok3, tok3->strAt(1), var->name(), false); else if (Token::Match(tok3, ". %name% ( %varid% )", numId)) { - Library::Container::Yield yield = container->getYield(tok3->strAt(1)); + const Library::Container::Yield yield = container->getYield(tok3->strAt(1)); if (yield == Library::Container::AT_INDEX) stlOutOfBoundsError(tok3, tok3->strAt(3), var->name(), true); } @@ -1103,7 +1103,7 @@ void CheckStl::string_c_str() string_c_strError(tok); } else if (printPerformance && Token::Match(tok, "%name% ( !!)") && c_strFuncParam.find(tok->str()) != c_strFuncParam.end() && !Token::Match(tok->previous(), "::|.") && tok->varId() == 0 && tok->str() != scope->className) { // calling function. TODO: Add support for member functions - std::pair::const_iterator, std::multimap::const_iterator> range = c_strFuncParam.equal_range(tok->str()); + const std::pair::const_iterator, std::multimap::const_iterator> range = c_strFuncParam.equal_range(tok->str()); for (std::multimap::const_iterator i = range.first; i != range.second; ++i) { if (i->second == 0) continue; @@ -1283,7 +1283,7 @@ void CheckStl::checkAutoPointer() autoPointerMallocError(tok2->next(), tok3->next()->str()); } if (Token::Match(tok3, "( %var%")) { - std::map::const_iterator it = mallocVarId.find(tok3->next()->varId()); + const std::map::const_iterator it = mallocVarId.find(tok3->next()->varId()); if (it != mallocVarId.cend()) { // pointer on the memory allocated by malloc used in the auto pointer constructor -> error autoPointerMallocError(tok2->next(), it->second); @@ -1311,20 +1311,20 @@ void CheckStl::checkAutoPointer() } else { if (Token::Match(tok, "%name% = %var% ;")) { if (printStyle) { - std::set::const_iterator iter = autoPtrVarId.find(tok->tokAt(2)->varId()); + const std::set::const_iterator iter = autoPtrVarId.find(tok->tokAt(2)->varId()); if (iter != autoPtrVarId.end()) { autoPointerError(tok->tokAt(2)); } } } else if ((Token::Match(tok, "%var% = new %type%") && hasArrayEnd(tok)) || (Token::Match(tok, "%var% . reset ( new %type%") && hasArrayEndParen(tok))) { - std::set::const_iterator iter = autoPtrVarId.find(tok->varId()); + const std::set::const_iterator iter = autoPtrVarId.find(tok->varId()); if (iter != autoPtrVarId.end()) { autoPointerArrayError(tok); } } else if (Token::Match(tok, "%var% = %name% (") && malloc && _settings->library.alloc(tok->tokAt(2), -1) == malloc) { // C library function like 'malloc' used together with auto pointer -> error - std::set::const_iterator iter = autoPtrVarId.find(tok->varId()); + const std::set::const_iterator iter = autoPtrVarId.find(tok->varId()); if (iter != autoPtrVarId.end()) { autoPointerMallocError(tok, tok->strAt(2)); } else if (tok->varId()) { @@ -1333,7 +1333,7 @@ void CheckStl::checkAutoPointer() } } else if (Token::Match(tok, "%var% . reset ( %name% (") && malloc && _settings->library.alloc(tok->tokAt(4), -1) == malloc) { // C library function like 'malloc' used when resetting auto pointer -> error - std::set::const_iterator iter = autoPtrVarId.find(tok->varId()); + const std::set::const_iterator iter = autoPtrVarId.find(tok->varId()); if (iter != autoPtrVarId.end()) { autoPointerMallocError(tok, tok->strAt(4)); } @@ -1565,7 +1565,7 @@ void CheckStl::readingEmptyStlContainer_parseUsage(const Token* tok, const Libra const Token* parent = tok->tokAt(3)->astParent(); const Library::Container::Yield yield = container->getYield(tok->strAt(2)); - bool yieldsIterator = (yield == Library::Container::ITERATOR || yield == Library::Container::START_ITERATOR || yield == Library::Container::END_ITERATOR); + const bool yieldsIterator = (yield == Library::Container::ITERATOR || yield == Library::Container::START_ITERATOR || yield == Library::Container::END_ITERATOR); if (yield != Library::Container::NO_YIELD && (!parent || Token::Match(parent, "%cop%|*") || parent->isAssignmentOp() || !yieldsIterator)) { // These functions read from the container if (!noerror && (!yieldsIterator || !parent || !parent->isAssignmentOp())) diff --git a/lib/checkstring.cpp b/lib/checkstring.cpp index e366532e7..3b0135e05 100644 --- a/lib/checkstring.cpp +++ b/lib/checkstring.cpp @@ -290,7 +290,7 @@ void CheckString::checkIncorrectStringCompare() tok = tok->next()->link(); if (Token::simpleMatch(tok, ". substr (") && Token::Match(tok->tokAt(3)->nextArgument(), "%num% )")) { - MathLib::biguint clen = MathLib::toULongNumber(tok->linkAt(2)->strAt(-1)); + const MathLib::biguint clen = MathLib::toULongNumber(tok->linkAt(2)->strAt(-1)); const Token* begin = tok->previous(); for (;;) { // Find start of statement while (begin->link() && Token::Match(begin, "]|)|>")) @@ -303,12 +303,12 @@ void CheckString::checkIncorrectStringCompare() begin = begin->previous(); const Token* end = tok->linkAt(2)->next(); if (Token::Match(begin->previous(), "%str% ==|!=") && begin->strAt(-2) != "+") { - std::size_t slen = Token::getStrLength(begin->previous()); + const std::size_t slen = Token::getStrLength(begin->previous()); if (clen != slen) { incorrectStringCompareError(tok->next(), "substr", begin->strAt(-1)); } } else if (Token::Match(end, "==|!= %str% !!+")) { - std::size_t slen = Token::getStrLength(end->next()); + const std::size_t slen = Token::getStrLength(end->next()); if (clen != slen) { incorrectStringCompareError(tok->next(), "substr", end->strAt(1)); } @@ -436,12 +436,12 @@ void CheckString::sprintfOverlappingData() const int formatString = Token::simpleMatch(tok, "sprintf") ? 1 : 2; for (unsigned int argnr = formatString + 1; argnr < args.size(); ++argnr) { - bool same = isSameExpression(_tokenizer->isCPP(), - false, - args[0], - args[argnr], - _settings->library, - true); + const bool same = isSameExpression(_tokenizer->isCPP(), + false, + args[0], + args[argnr], + _settings->library, + true); if (same) { sprintfOverlappingDataError(args[argnr], args[argnr]->expressionString()); } diff --git a/lib/checkuninitvar.cpp b/lib/checkuninitvar.cpp index 0019fba7c..a34b4fa04 100644 --- a/lib/checkuninitvar.cpp +++ b/lib/checkuninitvar.cpp @@ -126,13 +126,13 @@ void CheckUninitVar::checkScope(const Scope* scope, const std::set if (i->isArray()) { Alloc alloc = ARRAY; - std::map variableValue; + const std::map variableValue; checkScopeForVariable(tok, *i, nullptr, nullptr, &alloc, emptyString, variableValue); continue; } if (stdtype || i->isPointer()) { Alloc alloc = NO_ALLOC; - std::map variableValue; + const std::map variableValue; checkScopeForVariable(tok, *i, nullptr, nullptr, &alloc, emptyString, variableValue); } if (i->type()) @@ -151,7 +151,7 @@ void CheckUninitVar::checkScope(const Scope* scope, const std::set checkStruct(tok, *arg); else if (arg->typeStartToken()->isStandardType() || arg->typeStartToken()->isEnumType()) { Alloc alloc = NO_ALLOC; - std::map variableValue; + const std::map variableValue; checkScopeForVariable(tok->next(), *arg, nullptr, nullptr, &alloc, emptyString, variableValue); } } @@ -193,7 +193,7 @@ void CheckUninitVar::checkStruct(const Token *tok, const Variable &structvar) const Token *tok2 = tok; if (tok->str() == "}") tok2 = tok2->next(); - std::map variableValue; + const std::map variableValue; checkScopeForVariable(tok2, structvar, nullptr, nullptr, &alloc, var.name(), variableValue); } } @@ -322,7 +322,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 variableValue) { - const bool suppressErrors(possibleInit && *possibleInit); + const bool suppressErrors(possibleInit && *possibleInit); // Assume that this is a variable delaratkon, rather than a fundef const bool printDebug = _settings->debugwarnings; if (possibleInit) @@ -380,7 +380,7 @@ bool CheckUninitVar::checkScopeForVariable(const Token *tok, const Variable& var ; else if (Token::simpleMatch(tok, "if (") && astIsVariableComparison(tok->next()->astOperand2(), "!=", "0", &condVarTok)) { - std::map::const_iterator it = variableValue.find(condVarTok->varId()); + const std::map::const_iterator it = variableValue.find(condVarTok->varId()); if (it != variableValue.end() && it->second != 0) return true; // this scope is not fully analysed => return true else { @@ -396,7 +396,7 @@ bool CheckUninitVar::checkScopeForVariable(const Token *tok, const Variable& var while (Token::simpleMatch(vartok, ".")) vartok = vartok->astOperand2(); if (vartok && vartok->varId() && numtok) { - std::map::const_iterator it = variableValue.find(vartok->varId()); + const std::map::const_iterator it = variableValue.find(vartok->varId()); if (it != variableValue.end() && it->second != MathLib::toLongNumber(numtok->str())) return true; // this scope is not fully analysed => return true else { @@ -532,7 +532,7 @@ bool CheckUninitVar::checkScopeForVariable(const Token *tok, const Variable& var const Token *tok2 = forwhile ? tok->next()->link()->next() : tok->next(); if (tok2 && tok2->str() == "{") { - bool init = checkLoopBody(tok2, var, *alloc, membervar, (number_of_if > 0) || suppressErrors); + const bool init = checkLoopBody(tok2, var, *alloc, membervar, (number_of_if > 0) || suppressErrors); // variable is initialized in the loop.. if (init) @@ -1167,7 +1167,7 @@ bool CheckUninitVar::isMemberVariableUsage(const Token *tok, bool isPointer, All { if (Token::Match(tok->previous(), "[(,] %name% . %name% [,)]") && tok->strAt(2) == membervar) { - int use = isFunctionParUsage(tok, isPointer, alloc); + const int use = isFunctionParUsage(tok, isPointer, alloc); if (use == 1) return true; } diff --git a/lib/checkunusedfunctions.cpp b/lib/checkunusedfunctions.cpp index d61fe90d4..28a4e7079 100644 --- a/lib/checkunusedfunctions.cpp +++ b/lib/checkunusedfunctions.cpp @@ -396,7 +396,7 @@ void CheckUnusedFunctions::analyseWholeProgram(ErrorLogger * const errorLogger, const std::string sourcefile = filesTxtLine.substr(lastColon+1); tinyxml2::XMLDocument doc; - tinyxml2::XMLError error = doc.LoadFile(xmlfile.c_str()); + const tinyxml2::XMLError error = doc.LoadFile(xmlfile.c_str()); if (error != tinyxml2::XML_SUCCESS) continue; diff --git a/lib/checkunusedvar.cpp b/lib/checkunusedvar.cpp index 7d3136487..71ca4495a 100644 --- a/lib/checkunusedvar.cpp +++ b/lib/checkunusedvar.cpp @@ -529,7 +529,7 @@ static const Token* doAssignment(Variables &variables, const Token *tok, bool de } // check if variable is local - unsigned int varid2 = tok->varId(); + const unsigned int varid2 = tok->varId(); const Variables::VariableUsage* var2 = variables.find(varid2); if (var2) { // local variable (alias or read it) diff --git a/lib/importproject.cpp b/lib/importproject.cpp index 656b9d3b4..76317317e 100644 --- a/lib/importproject.cpp +++ b/lib/importproject.cpp @@ -71,8 +71,8 @@ void ImportProject::ignoreOtherPlatforms(cppcheck::Platform::PlatformType platfo void ImportProject::FileSettings::setDefines(std::string defs) { while (defs.find(";%(") != std::string::npos) { - std::string::size_type pos1 = defs.find(";%("); - std::string::size_type pos2 = defs.find(';', pos1+1); + const std::string::size_type pos1 = defs.find(";%("); + const std::string::size_type pos2 = defs.find(';', pos1+1); defs.erase(pos1, pos2 == std::string::npos ? pos2 : (pos2-pos1)); } while (defs.find(";;") != std::string::npos) @@ -102,7 +102,7 @@ static bool simplifyPathWithVariables(std::string &s, std::map expanded; std::string::size_type start = 0; while ((start = s.find("$(")) != std::string::npos) { - std::string::size_type end = s.find(')',start); + const std::string::size_type end = s.find(')',start); if (end == std::string::npos) break; const std::string var = s.substr(start+2,end-start-2); @@ -215,7 +215,7 @@ void ImportProject::importCompileCommands(std::istream &istr) pos++; if (pos >= command.size()) break; - char F = command[pos++]; + const char F = command[pos++]; std::string fval; while (pos < command.size() && command[pos] != ' ' && command[pos] != '=') { if (command[pos] != '\\') @@ -421,7 +421,7 @@ static void importPropertyGroup(const tinyxml2::XMLElement *node, std::mapFirstChildElement(); cfg; cfg = cfg->NextSiblingElement()) { if (std::strcmp(cfg->Name(), "ProjectConfiguration") == 0) { - ProjectConfiguration p(cfg); + const ProjectConfiguration p(cfg); if (p.platform != ProjectConfiguration::Unknown) projectConfigurationList.push_back(ProjectConfiguration(cfg)); } diff --git a/lib/library.cpp b/lib/library.cpp index 534b09c4b..16e6642ef 100644 --- a/lib/library.cpp +++ b/lib/library.cpp @@ -329,7 +329,7 @@ Library::Error Library::load(const tinyxml2::XMLDocument &doc) const char* const inherits = node->Attribute("inherits"); if (inherits) { - std::map::const_iterator i = containers.find(inherits); + const std::map::const_iterator i = containers.find(inherits); if (i != containers.end()) container = i->second; // Take values from parent and overwrite them if necessary else @@ -776,7 +776,7 @@ std::string Library::getFunctionName(const Token *ftok) const // Lookup function name using AST.. if (ftok->astParent()) { bool error = false; - std::string ret = getFunctionName(ftok->next()->astOperand1(), &error); + const std::string ret = getFunctionName(ftok->next()->astOperand1(), &error); return error ? std::string() : ret; } @@ -800,7 +800,7 @@ bool Library::isnullargbad(const Token *ftok, int argnr) const if (!arg) { // scan format string argument should not be null const std::string funcname = getFunctionName(ftok); - std::map::const_iterator it = functions.find(funcname); + const std::map::const_iterator it = functions.find(funcname); if (it != functions.cend() && it->second.formatstr && it->second.formatstr_scan) return true; } @@ -813,7 +813,7 @@ bool Library::isuninitargbad(const Token *ftok, int argnr) const if (!arg) { // non-scan format string argument should not be uninitialized const std::string funcname = getFunctionName(ftok); - std::map::const_iterator it = functions.find(funcname); + const std::map::const_iterator it = functions.find(funcname); if (it != functions.cend() && it->second.formatstr && !it->second.formatstr_scan) return true; } @@ -854,7 +854,7 @@ const Library::ArgumentChecks * Library::getarg(const Token *ftok, int argnr) co { if (isNotLibraryFunction(ftok)) return nullptr; - std::map::const_iterator it1 = functions.find(getFunctionName(ftok)); + const std::map::const_iterator it1 = functions.find(getFunctionName(ftok)); if (it1 == functions.cend()) return nullptr; const std::map::const_iterator it2 = it1->second.argumentChecks.find(argnr); @@ -955,7 +955,7 @@ bool Library::isNotLibraryFunction(const Token *ftok) const bool Library::matchArguments(const Token *ftok, const std::string &functionName) const { - int callargs = numberOfArguments(ftok); + const int callargs = numberOfArguments(ftok); const std::map::const_iterator it = functions.find(functionName); if (it == functions.cend()) return (callargs == 0); @@ -988,7 +988,7 @@ bool Library::formatstr_function(const Token* ftok) const if (isNotLibraryFunction(ftok)) return false; - std::map::const_iterator it = functions.find(getFunctionName(ftok)); + const std::map::const_iterator it = functions.find(getFunctionName(ftok)); if (it != functions.cend()) return it->second.formatstr; return false; @@ -1019,7 +1019,7 @@ bool Library::isUseRetVal(const Token* ftok) const { if (isNotLibraryFunction(ftok)) return false; - std::map::const_iterator it = functions.find(getFunctionName(ftok)); + const std::map::const_iterator it = functions.find(getFunctionName(ftok)); if (it != functions.cend()) return it->second.useretval; return false; @@ -1029,7 +1029,7 @@ const std::string& Library::returnValue(const Token *ftok) const { if (isNotLibraryFunction(ftok)) return emptyString; - std::map::const_iterator it = _returnValue.find(getFunctionName(ftok)); + const std::map::const_iterator it = _returnValue.find(getFunctionName(ftok)); return it != _returnValue.end() ? it->second : emptyString; } @@ -1037,7 +1037,7 @@ const std::string& Library::returnValueType(const Token *ftok) const { if (isNotLibraryFunction(ftok)) return emptyString; - std::map::const_iterator it = _returnValueType.find(getFunctionName(ftok)); + const std::map::const_iterator it = _returnValueType.find(getFunctionName(ftok)); return it != _returnValueType.end() ? it->second : emptyString; } @@ -1045,13 +1045,13 @@ int Library::returnValueContainer(const Token *ftok) const { if (isNotLibraryFunction(ftok)) return -1; - std::map::const_iterator it = _returnValueContainer.find(getFunctionName(ftok)); + const std::map::const_iterator it = _returnValueContainer.find(getFunctionName(ftok)); return it != _returnValueContainer.end() ? it->second : -1; } bool Library::hasminsize(const std::string &functionName) const { - std::map::const_iterator it1 = functions.find(functionName); + const std::map::const_iterator it1 = functions.find(functionName); if (it1 == functions.cend()) return false; for (std::map::const_iterator it2 = it1->second.argumentChecks.cbegin(); it2 != it1->second.argumentChecks.cend(); ++it2) { @@ -1063,28 +1063,28 @@ bool Library::hasminsize(const std::string &functionName) const bool Library::ignorefunction(const std::string& functionName) const { - std::map::const_iterator it = functions.find(functionName); + const std::map::const_iterator it = functions.find(functionName); if (it != functions.cend()) return it->second.ignore; return false; } bool Library::isUse(const std::string& functionName) const { - std::map::const_iterator it = functions.find(functionName); + const std::map::const_iterator it = functions.find(functionName); if (it != functions.cend()) return it->second.use; return false; } bool Library::isLeakIgnore(const std::string& functionName) const { - std::map::const_iterator it = functions.find(functionName); + const std::map::const_iterator it = functions.find(functionName); if (it != functions.cend()) return it->second.leakignore; return false; } bool Library::isFunctionConst(const std::string& functionName, bool pure) const { - std::map::const_iterator it = functions.find(functionName); + const std::map::const_iterator it = functions.find(functionName); if (it != functions.cend()) return pure ? it->second.ispure : it->second.isconst; return false; @@ -1095,7 +1095,7 @@ bool Library::isFunctionConst(const Token *ftok) const return true; if (isNotLibraryFunction(ftok)) return false; - std::map::const_iterator it = functions.find(getFunctionName(ftok)); + const std::map::const_iterator it = functions.find(getFunctionName(ftok)); return (it != functions.end() && it->second.isconst); } bool Library::isnoreturn(const Token *ftok) const @@ -1104,7 +1104,7 @@ bool Library::isnoreturn(const Token *ftok) const return true; if (isNotLibraryFunction(ftok)) return false; - std::map::const_iterator it = _noreturn.find(getFunctionName(ftok)); + const std::map::const_iterator it = _noreturn.find(getFunctionName(ftok)); return (it != _noreturn.end() && it->second); } @@ -1114,7 +1114,7 @@ bool Library::isnotnoreturn(const Token *ftok) const return false; if (isNotLibraryFunction(ftok)) return false; - std::map::const_iterator it = _noreturn.find(getFunctionName(ftok)); + const std::map::const_iterator it = _noreturn.find(getFunctionName(ftok)); return (it != _noreturn.end() && !it->second); } diff --git a/lib/library.h b/lib/library.h index 44ad9a86b..730635df8 100644 --- a/lib/library.h +++ b/lib/library.h @@ -201,14 +201,14 @@ public: bool opLessAllowed; Action getAction(const std::string& function) const { - std::map::const_iterator i = functions.find(function); + const std::map::const_iterator i = functions.find(function); if (i != functions.end()) return i->second.action; return NO_ACTION; } Yield getYield(const std::string& function) const { - std::map::const_iterator i = functions.find(function); + const std::map::const_iterator i = functions.find(function); if (i != functions.end()) return i->second.yield; return NO_YIELD; diff --git a/lib/mathlib.cpp b/lib/mathlib.cpp index 4c6e9d72a..b799a350a 100644 --- a/lib/mathlib.cpp +++ b/lib/mathlib.cpp @@ -61,7 +61,7 @@ MathLib::value::value(const std::string &s) : // read suffix if (s.size() >= 2U) { for (std::size_t i = s.size() - 1U; i > 0U; --i) { - char c = s[i]; + const char c = s[i]; if (c == 'u' || c == 'U') isUnsigned = true; else if (c == 'l' || c == 'L') { diff --git a/lib/preprocessor.cpp b/lib/preprocessor.cpp index 388e27b38..ac47679f5 100644 --- a/lib/preprocessor.cpp +++ b/lib/preprocessor.cpp @@ -270,7 +270,7 @@ static bool isUndefined(const std::string &cfg, const std::set &und const std::string::size_type pos2 = cfg.find(';',pos1); const std::string def = (pos2 == std::string::npos) ? cfg.substr(pos1) : cfg.substr(pos1, pos2 - pos1); - std::string::size_type eq = def.find('='); + const std::string::size_type eq = def.find('='); if (eq == std::string::npos && undefined.find(def) != undefined.end()) return true; if (eq != std::string::npos && undefined.find(def.substr(0,eq)) != undefined.end() && def.substr(eq) != "=0") @@ -521,7 +521,7 @@ static simplecpp::DUI createDUI(const Settings &_settings, const std::string &cf if (it->compare(0,8,"#define ")!=0) continue; std::string s = it->substr(8); - std::string::size_type pos = s.find_first_of(" ("); + const std::string::size_type pos = s.find_first_of(" ("); if (pos == std::string::npos) { dui.defines.push_back(s); continue; @@ -606,7 +606,7 @@ simplecpp::TokenList Preprocessor::preprocess(const simplecpp::TokenList &tokens simplecpp::TokenList tokens2(files); simplecpp::preprocess(tokens2, tokens1, files, tokenlists, dui, &outputList, ¯oUsage); - bool showerror = (!_settings.userDefines.empty() && !_settings.force); + const bool showerror = (!_settings.userDefines.empty() && !_settings.force); reportOutput(outputList, showerror); if (hasErrors(outputList)) return simplecpp::TokenList(files); @@ -698,7 +698,7 @@ void Preprocessor::error(const std::string &filename, unsigned int linenr, const { std::list locationList; if (!filename.empty()) { - ErrorLogger::ErrorMessage::FileLocation loc(filename, linenr); + const ErrorLogger::ErrorMessage::FileLocation loc(filename, linenr); locationList.push_back(loc); } _errorLogger->reportErr(ErrorLogger::ErrorMessage(locationList, @@ -776,9 +776,9 @@ void Preprocessor::validateCfgError(const std::string &file, const unsigned int { const std::string id = "ConfigurationNotChecked"; std::list locationList; - ErrorLogger::ErrorMessage::FileLocation loc(file, line); + const ErrorLogger::ErrorMessage::FileLocation loc(file, line); locationList.push_back(loc); - 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); } diff --git a/lib/suppressions.cpp b/lib/suppressions.cpp index 2ad0498aa..cf8d67233 100644 --- a/lib/suppressions.cpp +++ b/lib/suppressions.cpp @@ -160,7 +160,7 @@ std::string Suppressions::FileMatcher::addFile(const std::string &name, unsigned if (name.find_first_of("*?") != std::string::npos) { for (std::string::const_iterator i = name.begin(); i != name.end(); ++i) { if (*i == '*') { - std::string::const_iterator j = i + 1; + const std::string::const_iterator j = i + 1; if (j != name.end() && (*j == '*' || *j == '?')) { return "Failed to add suppression. Syntax error in glob."; } @@ -270,7 +270,7 @@ std::list Suppressions::getUnmatchedLocalSuppres if (!unusedFunctionChecking && i->first == "unusedFunction") continue; - std::map >::const_iterator f = i->second._files.find(Path::fromNativeSeparators(file)); + const std::map >::const_iterator f = i->second._files.find(Path::fromNativeSeparators(file)); if (f != i->second._files.end()) { for (std::map::const_iterator l = f->second.begin(); l != f->second.end(); ++l) { if (!l->second) { diff --git a/lib/symboldatabase.cpp b/lib/symboldatabase.cpp index a040601cb..bc1730a25 100644 --- a/lib/symboldatabase.cpp +++ b/lib/symboldatabase.cpp @@ -1997,7 +1997,7 @@ bool Function::argsMatch(const Scope *scope, const Token *first, const Token *se short_path.resize(short_path.size() - 4); // remove last name - std::string::size_type lastSpace = short_path.find_last_of(' '); + const std::string::size_type lastSpace = short_path.find_last_of(' '); if (lastSpace != std::string::npos) short_path.resize(lastSpace+1); @@ -2430,7 +2430,7 @@ void SymbolDatabase::debugMessage(const Token *tok, const std::string &msg) cons const Function* Type::getFunction(const std::string& funcName) const { if (classScope) { - std::multimap::const_iterator it = classScope->functionMap.find(funcName); + const std::multimap::const_iterator it = classScope->functionMap.find(funcName); if (it != classScope->functionMap.end()) return it->second; @@ -3979,10 +3979,10 @@ static void checkVariableCallMatch(const Variable* callarg, const Variable* func else if (constEquals && funcarg->isStlStringType() && Token::Match(callarg->typeStartToken(), "char|wchar_t")) fallback2++; } else if (ptrequals) { - bool takesInt = Token::Match(funcarg->typeStartToken(), "char|short|int|long"); - bool takesFloat = Token::Match(funcarg->typeStartToken(), "float|double"); - bool passesInt = Token::Match(callarg->typeStartToken(), "char|short|int|long"); - bool passesFloat = Token::Match(callarg->typeStartToken(), "float|double"); + const bool takesInt = Token::Match(funcarg->typeStartToken(), "char|short|int|long"); + const bool takesFloat = Token::Match(funcarg->typeStartToken(), "float|double"); + const bool passesInt = Token::Match(callarg->typeStartToken(), "char|short|int|long"); + const bool passesFloat = Token::Match(callarg->typeStartToken(), "float|double"); if ((takesInt && passesInt) || (takesFloat && passesFloat)) fallback1++; else if ((takesInt && passesFloat) || (takesFloat && passesInt)) @@ -4067,7 +4067,7 @@ const Function* Scope::findFunction(const Token *tok, bool requireConst) const else if (Token::Match(arguments[j], "& %var% ,|)")) { const Variable * callarg = check->getVariableFromVarId(arguments[j]->next()->varId()); if (callarg) { - bool funcargptr = (funcarg->typeEndToken()->str() == "*"); + const bool funcargptr = (funcarg->typeEndToken()->str() == "*"); if (funcargptr && (callarg->typeStartToken()->str() == funcarg->typeStartToken()->str() && callarg->typeStartToken()->isUnsigned() == funcarg->typeStartToken()->isUnsigned() && @@ -4279,7 +4279,7 @@ const Function* Scope::findFunction(const Token *tok, bool requireConst) const } } - size_t hasToBe = func->isVariadic() ? (func->argCount() - 1) : args; + const size_t hasToBe = func->isVariadic() ? (func->argCount() - 1) : args; // check if all arguments matched if (same == hasToBe) { @@ -4950,7 +4950,7 @@ void SymbolDatabase::setValueType(Token *tok, const ValueType &valuetype) if (parent->astOperand2() && !vt2) return; - bool ternary = parent->str() == ":" && parent->astParent() && parent->astParent()->str() == "?"; + const bool ternary = parent->str() == ":" && parent->astParent() && parent->astParent()->str() == "?"; if (ternary) { if (vt2 && vt1->pointer == vt2->pointer && vt1->type == vt2->type && vt1->sign == vt2->sign) setValueType(parent, *vt2); @@ -5048,7 +5048,7 @@ static const Token * parsedecl(const Token *type, ValueType * const valuetype, V valuetype->sign = ValueType::Sign::UNSIGNED; else valuetype->sign = defaultSignedness; - ValueType::Type t = ValueType::typeFromString(enum_type->str(), enum_type->isLong()); + const ValueType::Type t = ValueType::typeFromString(enum_type->str(), enum_type->isLong()); if (t != ValueType::Type::UNKNOWN_TYPE) valuetype->type = t; else if (enum_type->isStandardType()) @@ -5139,9 +5139,8 @@ static const Function *getOperatorFunction(const Token * const tok) { const std::string functionName("operator" + tok->str()); std::multimap::const_iterator it; - const Scope *classScope; - classScope = getClassScope(tok->astOperand1()); + const Scope *classScope = getClassScope(tok->astOperand1()); if (classScope) { it = classScope->functionMap.find(functionName); if (it != classScope->functionMap.end()) @@ -5176,7 +5175,7 @@ void SymbolDatabase::setValueTypeInTokenList() type = ValueType::Type::LONGDOUBLE; setValueType(tok, ValueType(ValueType::Sign::UNKNOWN_SIGN, type, 0U)); } else if (MathLib::isInt(tok->str())) { - bool unsignedSuffix = (tok->str().find_last_of("uU") != std::string::npos); + const bool unsignedSuffix = (tok->str().find_last_of("uU") != std::string::npos); ValueType::Sign sign = unsignedSuffix ? ValueType::Sign::UNSIGNED : ValueType::Sign::SIGNED; ValueType::Type type; const MathLib::bigint value = MathLib::toLongNumber(tok->str()); @@ -5269,7 +5268,7 @@ void SymbolDatabase::setValueTypeInTokenList() tok->astOperand1()->astOperand1()->valueType() && tok->astOperand1()->astOperand1()->valueType()->container) { const Library::Container *cont = tok->astOperand1()->astOperand1()->valueType()->container; - std::map::const_iterator it = cont->functions.find(tok->astOperand1()->astOperand2()->str()); + const std::map::const_iterator it = cont->functions.find(tok->astOperand1()->astOperand2()->str()); if (it != cont->functions.end()) { if (it->second.yield == Library::Container::Yield::START_ITERATOR || it->second.yield == Library::Container::Yield::END_ITERATOR || diff --git a/lib/templatesimplifier.cpp b/lib/templatesimplifier.cpp index 0064607e6..6aebb7713 100644 --- a/lib/templatesimplifier.cpp +++ b/lib/templatesimplifier.cpp @@ -513,7 +513,7 @@ std::list TemplateSimplifier::getTemplateDecla break; // Implementation => add to "templates" else if (tok2->str() == "{") { - int namepos = getTemplateNamePosition(parmEnd); + const int namepos = getTemplateNamePosition(parmEnd); if (namepos > 0) declarations.push_back(TokenAndName(tok, getScopeName(scopeInfo), getFullName(scopeInfo, parmEnd->strAt(namepos)))); break; @@ -1207,9 +1207,9 @@ bool TemplateSimplifier::simplifyNumericCalculations(Token *tok) // Logical operations else if (Token::Match(op, "%oror%|&&")) { - bool op1 = !MathLib::isNullValue(tok->str()); - bool op2 = !MathLib::isNullValue(tok->strAt(2)); - bool result = (op->str() == "||") ? (op1 || op2) : (op1 && op2); + const bool op1 = !MathLib::isNullValue(tok->str()); + const bool op2 = !MathLib::isNullValue(tok->strAt(2)); + const bool result = (op->str() == "||") ? (op1 || op2) : (op1 && op2); tok->str(result ? "1" : "0"); } @@ -1279,7 +1279,7 @@ bool TemplateSimplifier::simplifyCalculations(Token *_tokens) Token::Match(tok->previous(), "[(=,] 1 %oror%")) { unsigned int par = 0; const Token *tok2 = tok; - bool andAnd = (tok->next()->str() == "&&"); + const bool andAnd = (tok->next()->str() == "&&"); for (; tok2; tok2 = tok2->next()) { if (tok2->str() == "(" || tok2->str() == "[") ++par; @@ -1510,7 +1510,7 @@ bool TemplateSimplifier::simplifyTemplateInstantiations( if (namepos == -1) { // debug message that we bail out.. if (printDebug && errorlogger) { - std::list callstack(1, tok); + const std::list callstack(1, tok); errorlogger->reportErr(ErrorLogger::ErrorMessage(callstack, &tokenlist, Severity::debug, "debug", "simplifyTemplates: bailing out", false)); } return false; diff --git a/lib/timer.cpp b/lib/timer.cpp index ab3a7110d..27c190a53 100644 --- a/lib/timer.cpp +++ b/lib/timer.cpp @@ -94,7 +94,7 @@ void Timer::Stop() const std::clock_t diff = end - _start; if (_showtimeMode == SHOWTIME_FILE) { - double sec = (double)diff / CLOCKS_PER_SEC; + const double sec = (double)diff / CLOCKS_PER_SEC; std::cout << _str << ": " << sec << "s" << std::endl; } else { if (_timerResults) diff --git a/lib/token.cpp b/lib/token.cpp index a20b64f25..5aa76bb8e 100644 --- a/lib/token.cpp +++ b/lib/token.cpp @@ -499,7 +499,7 @@ int Token::multiCompare(const Token *tok, const char *haystack, unsigned int var const char *needlePointer = needle; for (;;) { if (needlePointer == needle && haystack[0] == '%' && haystack[1] != '|' && haystack[1] != '\0' && haystack[1] != ' ') { - int ret = multiComparePercent(tok, haystack, varid); + const int ret = multiComparePercent(tok, haystack, varid); if (ret < 2) return ret; } else if (*haystack == '|') { @@ -553,7 +553,7 @@ bool Token::simpleMatch(const Token *tok, const char pattern[]) next = pattern + std::strlen(pattern); while (*current) { - std::size_t length = next - current; + const std::size_t length = next - current; if (!tok || length != tok->_str.length() || std::strncmp(current, tok->_str.c_str(), length)) return false; @@ -663,7 +663,7 @@ bool Token::Match(const Token *tok, const char pattern[], unsigned int varid) // Parse multi options, such as void|int|char (accept token which is one of these 3) else { - int res = multiCompare(tok, p, varid); + const int res = multiCompare(tok, p, varid); if (res == 0) { // Empty alternative matches, use the same token on next round while (*p && *p != ' ') diff --git a/lib/tokenize.cpp b/lib/tokenize.cpp index a9f96ac1a..d2ad7b77e 100644 --- a/lib/tokenize.cpp +++ b/lib/tokenize.cpp @@ -191,7 +191,7 @@ unsigned int Tokenizer::sizeOfType(const Token *type) const if (type->tokType() == Token::eString) return Token::getStrLength(type) + 1U; - std::map::const_iterator it = _typeSize.find(type->str()); + const std::map::const_iterator it = _typeSize.find(type->str()); if (it == _typeSize.end()) { const Library::PodType* podtype = _settings->library.podtype(type->str()); if (!podtype) @@ -2090,7 +2090,7 @@ void Tokenizer::arraySize() if (addlength || Token::Match(tok, "%var% [ ] = %str% ;")) { tok = tok->next(); - std::size_t sz = Token::getStrSize(tok->tokAt(3)); + const std::size_t sz = Token::getStrSize(tok->tokAt(3)); tok->insertToken(MathLib::toString(sz)); tok = tok->tokAt(5); } @@ -2255,8 +2255,8 @@ void Tokenizer::simplifyCaseRange() } } } else if (Token::Match(tok, "case %char% . . . %char% :")) { - char start = tok->strAt(1)[1]; - char end = tok->strAt(5)[1]; + const char start = tok->strAt(1)[1]; + const char end = tok->strAt(5)[1]; if (start < end) { tok = tok->tokAt(2); tok->str(":"); @@ -2981,7 +2981,7 @@ void Tokenizer::setVarIdPass2() } if (tok->str() == "}") { - std::map::iterator it = endOfScope.find(tok); + const std::map::iterator it = endOfScope.find(tok); if (it != endOfScope.end()) scope.remove(it->second); } @@ -3127,7 +3127,7 @@ void Tokenizer::setVarIdPass2() break; // set varid - std::map::const_iterator varpos = thisClassVars.find(tok3->str()); + const std::map::const_iterator varpos = thisClassVars.find(tok3->str()); if (varpos != thisClassVars.end()) tok3->varId(varpos->second); @@ -3432,7 +3432,7 @@ bool Tokenizer::simplifySizeof() // sizeof( a ) else if (Token::Match(tok->next(), "( %var% )")) { - std::map::const_iterator sizeOfVarPos = sizeOfVar.find(tok->tokAt(2)->varId()); + const std::map::const_iterator sizeOfVarPos = sizeOfVar.find(tok->tokAt(2)->varId()); if (sizeOfVarPos != sizeOfVar.end()) { tok->deleteNext(); tok->deleteThis(); @@ -4492,7 +4492,7 @@ bool Tokenizer::removeRedundantConditions() // Find matching else Token *elseTag = tok->linkAt(4)->next(); - bool boolValue = (tok->strAt(2) == "true"); + const bool boolValue = (tok->strAt(2) == "true"); // Handle if with else if (Token::simpleMatch(elseTag, "else {")) { @@ -4553,7 +4553,7 @@ void Tokenizer::removeRedundantFor() Token::Match(tok, "[;{}] for ( %type% %name% = %num% ; %name% < %num% ; ++| %name% ++| ) {")) { // Same variable name.. const Token* varTok = tok->tokAt(3); - bool type = varTok->next()->isName(); + const bool type = varTok->next()->isName(); if (type) varTok = varTok->next(); const std::string varname(varTok->str()); @@ -8794,7 +8794,7 @@ void Tokenizer::simplifyStructDecl() void Tokenizer::simplifyCallingConvention() { - bool windows = _settings->isWindowsPlatform(); + const bool windows = _settings->isWindowsPlatform(); 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"))) { @@ -9533,7 +9533,7 @@ void Tokenizer::simplifyMicrosoftStringFunctions() if (tok->strAt(1) != "(") continue; - std::map::const_iterator match = apis.find(tok->str()); + const std::map::const_iterator match = apis.find(tok->str()); if (match!=apis.end()) { tok->str(ansi ? match->second.mbcs : match->second.unicode); tok->originalName(match->first); diff --git a/lib/valueflow.cpp b/lib/valueflow.cpp index bc03c7e03..360dc3e46 100644 --- a/lib/valueflow.cpp +++ b/lib/valueflow.cpp @@ -1729,9 +1729,9 @@ static bool valueFlowForward(Token * const startToken, Token * const start = tok2->linkAt(1)->next(); Token * const end = start->link(); - bool varusage = (indentlevel >= 0 && constValue && number_of_if == 0U) ? - isVariableChanged(start,end,varid,var->isGlobal(),settings) : - (nullptr != Token::findmatch(start, "%varid%", end, varid)); + const bool varusage = (indentlevel >= 0 && constValue && number_of_if == 0U) ? + isVariableChanged(start,end,varid,var->isGlobal(),settings) : + (nullptr != Token::findmatch(start, "%varid%", end, varid)); if (!read) { read = bool(nullptr != Token::findmatch(tok2, "%varid% !!=", end, varid)); } @@ -3131,7 +3131,7 @@ static void valueFlowSubFunction(TokenList *tokenlist, ErrorLogger *errorLogger, // Error path.. for (std::list::iterator it = argvalues.begin(); it != argvalues.end(); ++it) { - std::string nr = MathLib::toString(argnr + 1) + getOrdinalText(argnr + 1); + const std::string nr = MathLib::toString(argnr + 1) + getOrdinalText(argnr + 1); it->errorPath.push_back(ErrorPathItem(argtok, "Calling function '" +