fixed some unusedFunction warnings (#3618)

This commit is contained in:
Oliver Stöneberg 2022-01-04 15:48:08 +01:00 committed by GitHub
parent 4b5fba19bd
commit 0ba9cb4e64
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
20 changed files with 19 additions and 225 deletions

View File

@ -198,6 +198,7 @@ bool ApplicationList::checkAndAddApplication(const QString& appPath, const QStri
return false; return false;
} }
#ifdef _WIN32
bool ApplicationList::findDefaultWindowsEditor() bool ApplicationList::findDefaultWindowsEditor()
{ {
bool foundOne = false; bool foundOne = false;
@ -264,3 +265,4 @@ bool ApplicationList::findDefaultWindowsEditor()
return foundOne; return foundOne;
} }
#endif

View File

@ -108,11 +108,13 @@ protected:
*/ */
void clear(); void clear();
#ifdef _WIN32
/** /**
* @brief Find editor used by default in Windows. * @brief Find editor used by default in Windows.
* Check if Notepad++ is installed and use it. If not, use Notepad. * Check if Notepad++ is installed and use it. If not, use Notepad.
*/ */
bool findDefaultWindowsEditor(); bool findDefaultWindowsEditor();
#endif
private: private:

View File

@ -268,7 +268,7 @@ private:
void setLanguage(const QString &code); void setLanguage(const QString &code);
/** @brief Event coming when application is about to close. */ /** @brief Event coming when application is about to close. */
virtual void closeEvent(QCloseEvent *event); void closeEvent(QCloseEvent *event) override;
/** /**
* @brief Helper function to toggle all show error menu items * @brief Helper function to toggle all show error menu items

View File

@ -177,7 +177,7 @@ public:
*/ */
ShowTypes mShowSeverities; ShowTypes mShowSeverities;
virtual void keyPressEvent(QKeyEvent *event); void keyPressEvent(QKeyEvent *event) override;
signals: signals:
/** /**
@ -294,7 +294,7 @@ protected slots:
* @param current Model index to specify new selected item. * @param current Model index to specify new selected item.
* @param previous Model index to specify previous selected item. * @param previous Model index to specify previous selected item.
*/ */
virtual void currentChanged(const QModelIndex &current, const QModelIndex &previous); void currentChanged(const QModelIndex &current, const QModelIndex &previous) override;
protected: protected:
@ -365,7 +365,7 @@ protected:
* *
* @param e Event * @param e Event
*/ */
void contextMenuEvent(QContextMenuEvent * e); void contextMenuEvent(QContextMenuEvent * e) override;
/** /**
* @brief Add a new error item beneath a file or a backtrace item beneath an error * @brief Add a new error item beneath a file or a backtrace item beneath an error

View File

@ -3306,14 +3306,6 @@ bool FwdAnalysis::unusedValue(const Token *expr, const Token *startToken, const
return (result.type == FwdAnalysis::Result::Type::NONE || result.type == FwdAnalysis::Result::Type::RETURN) && !possiblyAliased(expr, startToken); return (result.type == FwdAnalysis::Result::Type::NONE || result.type == FwdAnalysis::Result::Type::RETURN) && !possiblyAliased(expr, startToken);
} }
std::vector<FwdAnalysis::KnownAndToken> FwdAnalysis::valueFlow(const Token *expr, const Token *startToken, const Token *endToken)
{
mWhat = What::ValueFlow;
mValueFlowKnown = true;
check(expr, startToken, endToken);
return mValueFlow;
}
bool FwdAnalysis::possiblyAliased(const Token *expr, const Token *startToken) const bool FwdAnalysis::possiblyAliased(const Token *expr, const Token *startToken) const
{ {
if (expr->isUnaryOp("*")) if (expr->isUnaryOp("*"))

View File

@ -363,8 +363,6 @@ public:
const Token *token; const Token *token;
}; };
std::vector<KnownAndToken> valueFlow(const Token *expr, const Token *startToken, const Token *endToken);
/** Is there some possible alias for given expression */ /** Is there some possible alias for given expression */
bool possiblyAliased(const Token *expr, const Token *startToken) const; bool possiblyAliased(const Token *expr, const Token *startToken) const;

View File

@ -408,57 +408,6 @@ CheckMemoryLeak::AllocType CheckMemoryLeak::functionReturnType(const Function* f
} }
const char *CheckMemoryLeak::functionArgAlloc(const Function *func, nonneg int targetpar, AllocType &allocType) const
{
allocType = No;
if (!func || !func->functionScope)
return "";
if (!Token::simpleMatch(func->retDef, "void"))
return "";
std::list<Variable>::const_iterator arg = func->argumentList.begin();
for (; arg != func->argumentList.end(); ++arg) {
if (arg->index() == targetpar-1)
break;
}
if (arg == func->argumentList.end())
return "";
// Is **
if (!arg->isPointer())
return "";
const Token* tok = arg->typeEndToken();
tok = tok->previous();
if (tok->str() != "*")
return "";
// Check if pointer is allocated.
bool realloc = false;
for (tok = func->functionScope->bodyStart; tok && tok != func->functionScope->bodyEnd; tok = tok->next()) {
if (tok->varId() == arg->declarationId()) {
if (Token::Match(tok->tokAt(-3), "free ( * %name% )")) {
realloc = true;
allocType = No;
} else if (Token::Match(tok->previous(), "* %name% =")) {
allocType = getAllocationType(tok->tokAt(2), arg->declarationId());
if (allocType != No) {
if (realloc)
return "realloc";
return "alloc";
}
} else {
// unhandled variable usage: bailout
return "";
}
}
}
return "";
}
static bool notvar(const Token *tok, nonneg int varid) static bool notvar(const Token *tok, nonneg int varid)
{ {
if (!tok) if (!tok)

View File

@ -145,9 +145,6 @@ public:
/** What type of allocated memory does the given function return? */ /** What type of allocated memory does the given function return? */
AllocType functionReturnType(const Function* func, std::list<const Function*> *callstack = nullptr) const; AllocType functionReturnType(const Function* func, std::list<const Function*> *callstack = nullptr) const;
/** Function allocates pointed-to argument (a la asprintf)? */
const char *functionArgAlloc(const Function *func, nonneg int targetpar, AllocType &allocType) const;
}; };
/// @} /// @}

View File

@ -2381,31 +2381,6 @@ void CheckStl::dereferenceInvalidIteratorError(const Token* deref, const std::st
"Possible dereference of an invalid iterator: $symbol. Make sure to check that the iterator is valid before dereferencing it - not after.", CWE825, Certainty::normal); "Possible dereference of an invalid iterator: $symbol. Make sure to check that the iterator is valid before dereferencing it - not after.", CWE825, Certainty::normal);
} }
void CheckStl::readingEmptyStlContainer2()
{
for (const Scope *function : mTokenizer->getSymbolDatabase()->functionScopes) {
for (const Token *tok = function->bodyStart; tok != function->bodyEnd; tok = tok->next()) {
if (!tok->isName() || !tok->valueType())
continue;
const Library::Container *container = tok->valueType()->container;
if (!container)
continue;
const ValueFlow::Value *value = tok->getContainerSizeValue(0);
if (!value)
continue;
if (value->isInconclusive() && !mSettings->certainty.isEnabled(Certainty::inconclusive))
continue;
if (!value->errorSeverity() && !mSettings->severity.isEnabled(Severity::warning))
continue;
if (Token::Match(tok, "%name% . %name% (")) {
if (container->getYield(tok->strAt(2)) == Library::Container::Yield::ITEM)
readingEmptyStlContainerError(tok,value);
}
}
}
}
void CheckStl::readingEmptyStlContainerError(const Token *tok, const ValueFlow::Value *value) void CheckStl::readingEmptyStlContainerError(const Token *tok, const ValueFlow::Value *value)
{ {
const std::string varname = tok ? tok->str() : std::string("var"); const std::string varname = tok ? tok->str() : std::string("var");

View File

@ -178,9 +178,6 @@ public:
*/ */
void dereferenceErasedError(const Token* erased, const Token* deref, const std::string& itername, bool inconclusive); void dereferenceErasedError(const Token* erased, const Token* deref, const std::string& itername, bool inconclusive);
/** @brief Reading from empty stl container (using valueflow) */
void readingEmptyStlContainer2();
/** @brief Look for loops that can replaced with std algorithms */ /** @brief Look for loops that can replaced with std algorithms */
void useStlAlgorithm(); void useStlAlgorithm();

View File

@ -76,16 +76,6 @@ void ImportProject::ignoreOtherConfigs(const std::string &cfg)
} }
} }
void ImportProject::ignoreOtherPlatforms(cppcheck::Platform::PlatformType platformType)
{
for (std::list<FileSettings>::iterator it = fileSettings.begin(); it != fileSettings.end();) {
if (it->platformType != cppcheck::Platform::Unspecified && it->platformType != platformType)
fileSettings.erase(it++);
else
++it;
}
}
void ImportProject::FileSettings::setDefines(std::string defs) void ImportProject::FileSettings::setDefines(std::string defs)
{ {
while (defs.find(";%(") != std::string::npos) { while (defs.find(";%(") != std::string::npos) {

View File

@ -103,7 +103,6 @@ public:
void ignorePaths(const std::vector<std::string> &ipaths); void ignorePaths(const std::vector<std::string> &ipaths);
void ignoreOtherConfigs(const std::string &cfg); void ignoreOtherConfigs(const std::string &cfg);
void ignoreOtherPlatforms(cppcheck::Platform::PlatformType platformType);
Type import(const std::string &filename, Settings *settings=nullptr); Type import(const std::string &filename, Settings *settings=nullptr);
protected: protected:

View File

@ -559,36 +559,6 @@ void Preprocessor::preprocess(std::istream &istr, std::map<std::string, std::str
} }
} }
std::string Preprocessor::removeSpaceNearNL(const std::string &str)
{
std::string tmp;
char prev = '\n'; // treat start of file as newline
for (std::size_t i = 0; i < str.size(); i++) {
if (str[i] == ' ' &&
(prev == '\n' ||
i + 1 >= str.size() || // treat end of file as newline
str[i+1] == '\n'
)
) {
// Ignore space that has new line in either side of it
} else {
tmp.append(1, str[i]);
prev = str[i];
}
}
return tmp;
}
void Preprocessor::preprocessWhitespaces(std::string &processedFile)
{
// Replace all tabs with spaces..
std::replace(processedFile.begin(), processedFile.end(), '\t', ' ');
// Remove space characters that are after or before new line character
processedFile = removeSpaceNearNL(processedFile);
}
void Preprocessor::preprocess(std::istream &srcCodeStream, std::string &processedFile, std::list<std::string> &resultConfigurations, const std::string &filename, const std::list<std::string> &includePaths) void Preprocessor::preprocess(std::istream &srcCodeStream, std::string &processedFile, std::list<std::string> &resultConfigurations, const std::string &filename, const std::list<std::string> &includePaths)
{ {
(void)includePaths; (void)includePaths;

View File

@ -154,12 +154,6 @@ public:
*/ */
std::string getcode(const std::string &filedata, const std::string &cfg, const std::string &filename); std::string getcode(const std::string &filedata, const std::string &cfg, const std::string &filename);
/**
* preprocess all whitespaces
* @param processedFile The data to be processed
*/
static void preprocessWhitespaces(std::string &processedFile);
/** /**
* make sure empty configuration macros are not used in code. the given code must be a single configuration * make sure empty configuration macros are not used in code. the given code must be a single configuration
* @param cfg configuration * @param cfg configuration
@ -184,14 +178,6 @@ private:
static void simplifyPragmaAsmPrivate(simplecpp::TokenList *tokenList); static void simplifyPragmaAsmPrivate(simplecpp::TokenList *tokenList);
/**
* Remove space that has new line character on left or right side of it.
*
* @param str The string to be converted
* @return The string where space characters have been removed.
*/
static std::string removeSpaceNearNL(const std::string &str);
public: public:

View File

@ -1840,6 +1840,7 @@ void SymbolDatabase::validate() const
if (mSettings->debugwarnings) { if (mSettings->debugwarnings) {
validateExecutableScopes(); validateExecutableScopes();
} }
// TODO
//validateVariables(); //validateVariables();
} }
@ -5329,17 +5330,6 @@ const Scope *SymbolDatabase::findScopeByName(const std::string& name) const
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
Scope *Scope::findInNestedList(const std::string & name)
{
for (Scope *scope: nestedList) {
if (scope->className == name)
return scope;
}
return nullptr;
}
//---------------------------------------------------------------------------
const Scope *Scope::findRecordInNestedList(const std::string & name) const const Scope *Scope::findRecordInNestedList(const std::string & name) const
{ {
for (const Scope* scope: nestedList) { for (const Scope* scope: nestedList) {

View File

@ -1128,12 +1128,6 @@ public:
*/ */
const Function *findFunction(const Token *tok, bool requireConst=false) const; const Function *findFunction(const Token *tok, bool requireConst=false) const;
/**
* @brief find if name is in nested list
* @param name name of nested scope
*/
Scope *findInNestedList(const std::string & name);
const Scope *findRecordInNestedList(const std::string & name) const; const Scope *findRecordInNestedList(const std::string & name) const;
Scope *findRecordInNestedList(const std::string & name) { Scope *findRecordInNestedList(const std::string & name) {
return const_cast<Scope *>(const_cast<const Scope *>(this)->findRecordInNestedList(name)); return const_cast<Scope *>(const_cast<const Scope *>(this)->findRecordInNestedList(name));

View File

@ -1915,46 +1915,6 @@ const Token *Token::getValueTokenMaxStrLength() const
return ret; return ret;
} }
static const Scope *getfunctionscope(const Scope *s)
{
while (s && s->type != Scope::eFunction)
s = s->nestedIn;
return s;
}
const Token *Token::getValueTokenDeadPointer() const
{
const Scope * const functionscope = getfunctionscope(this->scope());
std::list<ValueFlow::Value>::const_iterator it;
for (it = values().begin(); it != values().end(); ++it) {
// Is this a pointer alias?
if (!it->isTokValue() || (it->tokvalue && it->tokvalue->str() != "&"))
continue;
// Get variable
const Token *vartok = it->tokvalue->astOperand1();
if (!vartok || !vartok->isName() || !vartok->variable())
continue;
const Variable * const var = vartok->variable();
if (var->isStatic() || var->isReference())
continue;
if (!var->scope())
return nullptr; // #6804
if (var->scope()->type == Scope::eUnion && var->scope()->nestedIn == this->scope())
continue;
// variable must be in same function (not in subfunction)
if (functionscope != getfunctionscope(var->scope()))
continue;
// Is variable defined in this scope or upper scope?
const Scope *s = this->scope();
while ((s != nullptr) && (s != var->scope()))
s = s->nestedIn;
if (!s)
return it->tokvalue;
}
return nullptr;
}
static bool isAdjacent(const ValueFlow::Value& x, const ValueFlow::Value& y) static bool isAdjacent(const ValueFlow::Value& x, const ValueFlow::Value& y)
{ {
if (x.bound != ValueFlow::Value::Bound::Point && x.bound == y.bound) if (x.bound != ValueFlow::Value::Bound::Point && x.bound == y.bound)

View File

@ -863,7 +863,7 @@ public:
void printOut(const char *title, const std::vector<std::string> &fileNames) const; void printOut(const char *title, const std::vector<std::string> &fileNames) const;
/** /**
* print out tokens * print out tokens - used for debugging
*/ */
void printLines(int lines=5) const; void printLines(int lines=5) const;
@ -1171,8 +1171,6 @@ public:
const Token *getValueTokenMaxStrLength() const; const Token *getValueTokenMaxStrLength() const;
const Token *getValueTokenMinStrSize(const Settings *settings) const; const Token *getValueTokenMinStrSize(const Settings *settings) const;
const Token *getValueTokenDeadPointer() const;
/** Add token value. Return true if value is added. */ /** Add token value. Return true if value is added. */
bool addValue(const ValueFlow::Value &value); bool addValue(const ValueFlow::Value &value);

View File

@ -1966,9 +1966,6 @@ struct ValueFlowAnalyzer : Analyzer {
virtual ProgramState getProgramState() const = 0; virtual ProgramState getProgramState() const = 0;
virtual const ValueType* getValueType(const Token*) const {
return nullptr;
}
virtual int getIndirect(const Token* tok) const { virtual int getIndirect(const Token* tok) const {
const ValueFlow::Value* value = getValue(tok); const ValueFlow::Value* value = getValue(tok);
if (value) if (value)
@ -2640,10 +2637,6 @@ struct ExpressionAnalyzer : SingleValueFlowAnalyzer {
setupExprVarIds(val.tokvalue); setupExprVarIds(val.tokvalue);
} }
virtual const ValueType* getValueType(const Token*) const OVERRIDE {
return expr->valueType();
}
static bool nonLocal(const Variable* var, bool deref) { static bool nonLocal(const Variable* var, bool deref) {
return !var || (!var->isLocal() && !var->isArgument()) || (deref && var->isArgument() && var->isPointer()) || return !var || (!var->isLocal() && !var->isArgument()) || (deref && var->isArgument() && var->isPointer()) ||
var->isStatic() || var->isReference() || var->isExtern(); var->isStatic() || var->isReference() || var->isExtern();

View File

@ -130,6 +130,7 @@ private:
TEST_CASE(errorlistverbose2); TEST_CASE(errorlistverbose2);
TEST_CASE(ignorepathsnopath); TEST_CASE(ignorepathsnopath);
// TODO
// Disabling these tests since they use relative paths to the // Disabling these tests since they use relative paths to the
// testrunner executable. // testrunner executable.
//TEST_CASE(ignorepaths1); //TEST_CASE(ignorepaths1);
@ -974,8 +975,8 @@ private:
ASSERT_EQUALS("src/", parser.getIgnoredPaths()[0]); ASSERT_EQUALS("src/", parser.getIgnoredPaths()[0]);
ASSERT_EQUALS("module/", parser.getIgnoredPaths()[1]); ASSERT_EQUALS("module/", parser.getIgnoredPaths()[1]);
} }
*/
void ignorepaths4() { void ignorepaths4() {
REDIRECT; REDIRECT;
const char * const argv[] = {"cppcheck", "-i", "src", "-i", "module", "file.cpp"}; const char * const argv[] = {"cppcheck", "-i", "src", "-i", "module", "file.cpp"};
CmdLineParser parser(&settings); CmdLineParser parser(&settings);
@ -983,8 +984,8 @@ private:
ASSERT_EQUALS(2, parser.getIgnoredPaths().size()); ASSERT_EQUALS(2, parser.getIgnoredPaths().size());
ASSERT_EQUALS("src/", parser.getIgnoredPaths()[0]); ASSERT_EQUALS("src/", parser.getIgnoredPaths()[0]);
ASSERT_EQUALS("module/", parser.getIgnoredPaths()[1]); ASSERT_EQUALS("module/", parser.getIgnoredPaths()[1]);
} }
/*
void ignorefilepaths1() { void ignorefilepaths1() {
REDIRECT; REDIRECT;
const char * const argv[] = {"cppcheck", "-ifoo.cpp", "file.cpp"}; const char * const argv[] = {"cppcheck", "-ifoo.cpp", "file.cpp"};
@ -993,15 +994,16 @@ private:
ASSERT_EQUALS(1, parser.getIgnoredPaths().size()); ASSERT_EQUALS(1, parser.getIgnoredPaths().size());
ASSERT_EQUALS("foo.cpp", parser.getIgnoredPaths()[0]); ASSERT_EQUALS("foo.cpp", parser.getIgnoredPaths()[0]);
} }
*/
void ignorefilepaths2() { void ignorefilepaths2() {
REDIRECT; REDIRECT;
const char * const argv[] = {"cppcheck", "-isrc/foo.cpp", "file.cpp"}; const char * const argv[] = {"cppcheck", "-isrc/foo.cpp", "file.cpp"};
CmdLineParser parser(&settings); CmdLineParser parser(&settings);
ASSERT(parser.parseFromArgs(3, argv)); ASSERT(parser.parseFromArgs(3, argv));
ASSERT_EQUALS(1, parser.getIgnoredPaths().size()); ASSERT_EQUALS(1, parser.getIgnoredPaths().size());
ASSERT_EQUALS("src/foo.cpp", parser.getIgnoredPaths()[0]); ASSERT_EQUALS("src/foo.cpp", parser.getIgnoredPaths()[0]);
} }
*/
void checkconfig() { void checkconfig() {
REDIRECT; REDIRECT;