running astyle

This commit is contained in:
orbitcowboy 2014-11-20 10:13:03 +01:00
parent b1329bfb40
commit f5d804f71a
132 changed files with 7331 additions and 3689 deletions

View File

@ -54,42 +54,48 @@ public:
/**
* Return if user wanted to see program version.
*/
bool GetShowVersion() const {
bool GetShowVersion() const
{
return _showVersion;
}
/**
* Return if user wanted to see list of error messages.
*/
bool GetShowErrorMessages() const {
bool GetShowErrorMessages() const
{
return _showErrorMessages;
}
/**
* Return the path names user gave to command line.
*/
const std::vector<std::string>& GetPathNames() const {
const std::vector<std::string>& GetPathNames() const
{
return _pathnames;
}
/**
* Return if help is shown to user.
*/
bool GetShowHelp() const {
bool GetShowHelp() const
{
return _showHelp;
}
/**
* Return if we should exit after printing version, help etc.
*/
bool ExitAfterPrinting() const {
bool ExitAfterPrinting() const
{
return _exitAfterPrint;
}
/**
* Return a list of paths user wants to ignore.
*/
const std::vector<std::string>& GetIgnoredPaths() const {
const std::vector<std::string>& GetIgnoredPaths() const
{
return _ignoredPaths;
}

View File

@ -37,7 +37,8 @@ public:
* @param files output map that associates the size of each file with its name
* @param path root path
*/
static void recursiveAddFiles(std::map<std::string, std::size_t> &files, const std::string &path) {
static void recursiveAddFiles(std::map<std::string, std::size_t> &files, const std::string &path)
{
const std::set<std::string> extra;
recursiveAddFiles(files, path, extra);
}

View File

@ -98,7 +98,8 @@ public:
/**
* @return true if support for threads exist.
*/
static bool isEnabled() {
static bool isEnabled()
{
return true;
}
@ -128,7 +129,8 @@ public:
/**
* @return true if support for threads exist.
*/
static bool isEnabled() {
static bool isEnabled()
{
return true;
}
#else
@ -136,7 +138,8 @@ public:
/**
* @return true if support for threads exist.
*/
static bool isEnabled() {
static bool isEnabled()
{
return false;
}
#endif

View File

@ -33,24 +33,28 @@ public:
CppcheckExecutor()
: ErrorLogger()
, stoptime(std::time(NULL)+2U)
, cppcheck(*this,false) {
, cppcheck(*this,false)
{
cppcheck.settings().addEnabled("all");
cppcheck.settings().inconclusive = true;
}
void run(const char code[]) {
void run(const char code[])
{
cppcheck.check("test.c", code);
}
void reportOut(const std::string &outmsg) { }
void reportErr(const ErrorLogger::ErrorMessage &msg) {
void reportErr(const ErrorLogger::ErrorMessage &msg)
{
printf("%s\n", msg.toString(true).c_str());
}
void reportProgress(const
std::string &filename,
const char stage[],
const unsigned int value) {
const unsigned int value)
{
if (std::time(NULL) >= stoptime) {
printf("time to analyse the "
"code is more than 1 "

View File

@ -49,7 +49,8 @@ public:
* @brief Get application name.
* @return Application name.
*/
QString getName() const {
QString getName() const
{
return mName;
}
@ -57,7 +58,8 @@ public:
* @brief Get application path.
* @return Application path.
*/
QString getPath() const {
QString getPath() const
{
return mPath;
}
@ -65,7 +67,8 @@ public:
* @brief Get application command line parameters.
* @return Application command line parameters.
*/
QString getParameters() const {
QString getParameters() const
{
return mParameters;
}
@ -73,7 +76,8 @@ public:
* @brief Set application name.
* @param name Application name.
*/
void setName(const QString &name) {
void setName(const QString &name)
{
mName = name;
}
@ -81,7 +85,8 @@ public:
* @brief Set application path.
* @param path Application path.
*/
void setPath(const QString &path) {
void setPath(const QString &path)
{
mPath = path;
}
@ -89,7 +94,8 @@ public:
* @brief Set application command line parameters.
* @param parameters Application command line parameters.
*/
void setParameters(const QString &parameters) {
void setParameters(const QString &parameters)
{
mParameters = parameters;
}

View File

@ -69,7 +69,8 @@ public:
* @brief Return the default application.
* @return Index of the default application.
*/
int GetDefaultApplication() const {
int GetDefaultApplication() const
{
return mDefaultApplicationIndex;
}

View File

@ -37,11 +37,13 @@ class ErrorLine;
*/
class GuiSeverity {
public:
static QString toString(Severity::SeverityType severity) {
static QString toString(Severity::SeverityType severity)
{
return QString(Severity::toString(severity).c_str());
}
static Severity::SeverityType fromString(const QString &severity) {
static Severity::SeverityType fromString(const QString &severity)
{
return Severity::fromString(severity.toStdString());
}
};

View File

@ -68,7 +68,7 @@ void FileList::AddDirectory(const QString &directory, bool recursive)
dir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot);
QFileInfoList list = dir.entryInfoList();
QFileInfo item;
foreach(item, list) {
foreach (item, list) {
const QString path = item.canonicalFilePath();
AddDirectory(path, recursive);
}
@ -78,7 +78,7 @@ void FileList::AddDirectory(const QString &directory, bool recursive)
void FileList::AddPathList(const QStringList &paths)
{
QString path;
foreach(path, paths) {
foreach (path, paths) {
QFileInfo inf(path);
if (inf.isFile())
AddFile(path);
@ -91,7 +91,7 @@ QStringList FileList::GetFileList() const
{
if (mExcludedPaths.empty()) {
QStringList names;
foreach(QFileInfo item, mFileList) {
foreach (QFileInfo item, mFileList) {
QString name = QDir::fromNativeSeparators(item.canonicalFilePath());
names << name;
}
@ -109,7 +109,7 @@ void FileList::AddExcludeList(const QStringList &paths)
QStringList FileList::ApplyExcludeList() const
{
QStringList paths;
foreach(QFileInfo item, mFileList) {
foreach (QFileInfo item, mFileList) {
QString name = QDir::fromNativeSeparators(item.canonicalFilePath());
if (!Match(name))
paths << name;

View File

@ -57,7 +57,7 @@ int main(int argc, char *argv[])
QSettings* settings = new QSettings("Cppcheck", "Cppcheck-GUI", &app);
// Set data dir..
foreach(const QString arg, app.arguments()) {
foreach (const QString arg, app.arguments()) {
if (arg.startsWith("--data-dir=")) {
settings->setValue("DATADIR", arg.mid(11));
return 0;

View File

@ -499,7 +499,7 @@ void MainWindow::CheckDirectory()
void MainWindow::AddIncludeDirs(const QStringList &includeDirs, Settings &result)
{
QString dir;
foreach(dir, includeDirs) {
foreach (dir, includeDirs) {
QString incdir;
if (!QDir::isAbsolutePath(dir))
incdir = mCurrentDirectory + "/";
@ -560,14 +560,14 @@ Settings MainWindow::GetCppcheckSettings()
QStringList defines = pfile->GetDefines();
QString define;
foreach(define, defines) {
foreach (define, defines) {
if (!result.userDefines.empty())
result.userDefines += ";";
result.userDefines += define.toStdString();
}
QStringList libraries = pfile->GetLibraries();
foreach(QString library, libraries) {
foreach (QString library, libraries) {
const QString filename = library + ".cfg";
const Library::Error error = LoadLibrary(&result.library, filename);
if (error.errorcode != Library::ErrorCode::OK) {
@ -604,7 +604,7 @@ Settings MainWindow::GetCppcheckSettings()
}
QStringList suppressions = pfile->GetSuppressions();
foreach(QString suppression, suppressions) {
foreach (QString suppression, suppressions) {
result.nomsg.addSuppressionLine(suppression.toStdString());
}

View File

@ -79,7 +79,8 @@ public:
* @brief Return current project file.
* @return project file.
*/
ProjectFile * GetProjectFile() const {
ProjectFile * GetProjectFile() const
{
return mPFile;
}

View File

@ -119,7 +119,7 @@ bool ProjectFile::Read(const QString &filename)
insideProject = false;
break;
// Not handled
// Not handled
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
@ -143,7 +143,7 @@ bool ProjectFile::Read(const QString &filename)
QStringList ProjectFile::GetIncludeDirs() const
{
QStringList dirs;
foreach(QString path, mIncludeDirs) {
foreach (QString path, mIncludeDirs) {
dirs << QDir::fromNativeSeparators(path);
}
return dirs;
@ -157,7 +157,7 @@ QStringList ProjectFile::GetDefines() const
QStringList ProjectFile::GetCheckPaths() const
{
QStringList paths;
foreach(QString path, mPaths) {
foreach (QString path, mPaths) {
paths << QDir::fromNativeSeparators(path);
}
return paths;
@ -166,7 +166,7 @@ QStringList ProjectFile::GetCheckPaths() const
QStringList ProjectFile::GetExcludedPaths() const
{
QStringList paths;
foreach(QString path, mExcludedPaths) {
foreach (QString path, mExcludedPaths) {
paths << QDir::fromNativeSeparators(path);
}
return paths;
@ -175,7 +175,7 @@ QStringList ProjectFile::GetExcludedPaths() const
QStringList ProjectFile::GetLibraries() const
{
QStringList libraries;
foreach(QString library, mLibraries) {
foreach (QString library, mLibraries) {
libraries << library;
}
return libraries;
@ -184,7 +184,7 @@ QStringList ProjectFile::GetLibraries() const
QStringList ProjectFile::GetSuppressions() const
{
QStringList suppressions;
foreach(QString suppression, mSuppressions) {
foreach (QString suppression, mSuppressions) {
suppressions << suppression;
}
return suppressions;
@ -221,7 +221,7 @@ void ProjectFile::ReadIncludeDirs(QXmlStreamReader &reader)
allRead = true;
break;
// Not handled
// Not handled
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
@ -258,7 +258,7 @@ void ProjectFile::ReadDefines(QXmlStreamReader &reader)
allRead = true;
break;
// Not handled
// Not handled
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
@ -296,7 +296,7 @@ void ProjectFile::ReadCheckPaths(QXmlStreamReader &reader)
allRead = true;
break;
// Not handled
// Not handled
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
@ -342,7 +342,7 @@ void ProjectFile::ReadExcludes(QXmlStreamReader &reader)
allRead = true;
break;
// Not handled
// Not handled
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
@ -381,7 +381,7 @@ void ProjectFile::ReadStringList(QStringList &stringlist, QXmlStreamReader &read
allRead = true;
break;
// Not handled
// Not handled
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
@ -449,7 +449,7 @@ bool ProjectFile::Write(const QString &filename)
if (!mIncludeDirs.isEmpty()) {
xmlWriter.writeStartElement(IncludeDirElementName);
foreach(QString incdir, mIncludeDirs) {
foreach (QString incdir, mIncludeDirs) {
xmlWriter.writeStartElement(DirElementName);
xmlWriter.writeAttribute(DirNameAttrib, incdir);
xmlWriter.writeEndElement();
@ -459,7 +459,7 @@ bool ProjectFile::Write(const QString &filename)
if (!mDefines.isEmpty()) {
xmlWriter.writeStartElement(DefinesElementName);
foreach(QString define, mDefines) {
foreach (QString define, mDefines) {
xmlWriter.writeStartElement(DefineName);
xmlWriter.writeAttribute(DefineNameAttrib, define);
xmlWriter.writeEndElement();
@ -469,7 +469,7 @@ bool ProjectFile::Write(const QString &filename)
if (!mPaths.isEmpty()) {
xmlWriter.writeStartElement(PathsElementName);
foreach(QString path, mPaths) {
foreach (QString path, mPaths) {
xmlWriter.writeStartElement(PathName);
xmlWriter.writeAttribute(PathNameAttrib, path);
xmlWriter.writeEndElement();
@ -479,7 +479,7 @@ bool ProjectFile::Write(const QString &filename)
if (!mExcludedPaths.isEmpty()) {
xmlWriter.writeStartElement(ExcludeElementName);
foreach(QString path, mExcludedPaths) {
foreach (QString path, mExcludedPaths) {
xmlWriter.writeStartElement(ExcludePathName);
xmlWriter.writeAttribute(ExcludePathNameAttrib, path);
xmlWriter.writeEndElement();
@ -508,7 +508,7 @@ void ProjectFile::WriteStringList(QXmlStreamWriter &xmlWriter, const QStringList
return;
xmlWriter.writeStartElement(startelementname);
foreach(QString str, stringlist) {
foreach (QString str, stringlist) {
xmlWriter.writeStartElement(stringelementname);
xmlWriter.writeCharacters(str);
xmlWriter.writeEndElement();

View File

@ -50,7 +50,8 @@ public:
* @brief Get project root path.
* @return project root path.
*/
QString GetRootPath() const {
QString GetRootPath() const
{
return mRootPath;
}
@ -94,7 +95,8 @@ public:
* @brief Get filename for the project file.
* @return file name.
*/
QString GetFilename() const {
QString GetFilename() const
{
return mFilename;
}
@ -102,7 +104,8 @@ public:
* @brief Set project root path.
* @param rootpath new project root path.
*/
void SetRootPath(const QString &rootpath) {
void SetRootPath(const QString &rootpath)
{
mRootPath = rootpath;
}
@ -161,7 +164,8 @@ public:
* @brief Set filename for the project file.
* @param filename Filename to use.
*/
void SetFilename(const QString &filename) {
void SetFilename(const QString &filename)
{
mFilename = filename;
}

View File

@ -53,12 +53,12 @@ ProjectFileDialog::ProjectFileDialog(const QString &path, QWidget *parent)
if (!datadir.isEmpty())
searchPaths << datadir << datadir + "/cfg";
QStringList libs;
foreach(const QString sp, searchPaths) {
foreach (const QString sp, searchPaths) {
QDir dir(sp);
dir.setSorting(QDir::Name);
dir.setNameFilters(QStringList("*.cfg"));
dir.setFilter(QDir::Files | QDir::NoDotAndDotDot);
foreach(QFileInfo item, dir.entryInfoList()) {
foreach (QFileInfo item, dir.entryInfoList()) {
QString library = item.fileName();
{
Library lib;
@ -75,7 +75,7 @@ ProjectFileDialog::ProjectFileDialog(const QString &path, QWidget *parent)
}
}
qSort(libs);
foreach(const QString library, libs) {
foreach (const QString library, libs) {
QCheckBox *checkbox = new QCheckBox(this);
checkbox->setText(library);
mUI.librariesLayout->addWidget(checkbox);
@ -208,7 +208,7 @@ QStringList ProjectFileDialog::GetExcludedPaths() const
QStringList ProjectFileDialog::GetLibraries() const
{
QStringList libraries;
foreach(const QCheckBox *checkbox, mLibraryCheckboxes) {
foreach (const QCheckBox *checkbox, mLibraryCheckboxes) {
if (checkbox->isChecked())
libraries << checkbox->text();
}
@ -234,7 +234,7 @@ void ProjectFileDialog::SetRootPath(const QString &root)
void ProjectFileDialog::SetIncludepaths(const QStringList &includes)
{
foreach(QString dir, includes) {
foreach (QString dir, includes) {
AddIncludeDir(dir);
}
}
@ -243,7 +243,7 @@ void ProjectFileDialog::SetDefines(const QStringList &defines)
{
QString definestr;
QString define;
foreach(define, defines) {
foreach (define, defines) {
definestr += define;
definestr += ";";
}
@ -255,14 +255,14 @@ void ProjectFileDialog::SetDefines(const QStringList &defines)
void ProjectFileDialog::SetPaths(const QStringList &paths)
{
foreach(QString path, paths) {
foreach (QString path, paths) {
AddPath(path);
}
}
void ProjectFileDialog::SetExcludedPaths(const QStringList &paths)
{
foreach(QString path, paths) {
foreach (QString path, paths) {
AddExcludePath(path);
}
}
@ -397,7 +397,8 @@ void ProjectFileDialog::AddSuppression()
class QErrorLogger : public ErrorLogger {
public:
virtual void reportOut(const std::string &/*outmsg*/) {}
virtual void reportErr(const ErrorLogger::ErrorMessage &msg) {
virtual void reportErr(const ErrorLogger::ErrorMessage &msg)
{
errorIds << QString::fromStdString(msg._id);
}
QStringList errorIds;

View File

@ -756,7 +756,7 @@ void ResultsTree::HideResult()
QModelIndexList selectedRows = mSelectionModel->selectedRows();
QModelIndex index;
foreach(index, selectedRows) {
foreach (index, selectedRows) {
QStandardItem *item = mModel.itemFromIndex(index);
//Set the "hide" flag for this item
QVariantMap data = item->data().toMap();

View File

@ -147,7 +147,8 @@ public:
/**
* @brief Returns true if column "Id" is shown
*/
bool ShowIdColumn() const {
bool ShowIdColumn() const
{
return mShowErrorId;
}

View File

@ -297,7 +297,7 @@ void ResultsView::ReadErrorsXml(const QString &filename)
}
ErrorItem item;
foreach(item, errors) {
foreach (item, errors) {
mUI.mTree->AddErrorItem(item);
}
mUI.mTree->SetCheckDirectory("");

View File

@ -151,7 +151,8 @@ public:
* @brief Return checking statistics.
* @return Pointer to checking statistics.
*/
CheckStatistics *GetStatistics() const {
CheckStatistics *GetStatistics() const
{
return mStatistics;
}
@ -159,7 +160,8 @@ public:
* @brief Return Showtypes.
* @return Pointer to Showtypes.
*/
ShowTypes * GetShowTypes() const {
ShowTypes * GetShowTypes() const
{
return &mUI.mTree->mShowSeverities;
}

View File

@ -106,7 +106,7 @@ void SettingsDialog::InitIncludepathsList()
QSettings settings;
const QString allPaths = settings.value(SETTINGS_GLOBAL_INCLUDE_PATHS).toString();
const QStringList paths = allPaths.split(";", QString::SkipEmptyParts);
foreach(QString path, paths) {
foreach (QString path, paths) {
AddIncludePath(path);
}
}
@ -115,7 +115,7 @@ void SettingsDialog::InitTranslationsList()
{
const QString current = mTranslator->GetCurrentLanguage();
QList<TranslationInfo> translations = mTranslator->GetTranslations();
foreach(TranslationInfo translation, translations) {
foreach (TranslationInfo translation, translations) {
QListWidgetItem *item = new QListWidgetItem;
item->setText(translation.mName);
item->setData(LangCodeRole, QVariant(translation.mCode));
@ -211,7 +211,7 @@ void SettingsDialog::AddApplication()
void SettingsDialog::RemoveApplication()
{
QList<QListWidgetItem *> selected = mUI.mListWidget->selectedItems();
foreach(QListWidgetItem *item, selected) {
foreach (QListWidgetItem *item, selected) {
const int removeIndex = mUI.mListWidget->row(item);
const int currentDefault = mTempApplications->GetDefaultApplication();
mTempApplications->RemoveApplication(removeIndex);
@ -230,7 +230,7 @@ void SettingsDialog::EditApplication()
{
QList<QListWidgetItem *> selected = mUI.mListWidget->selectedItems();
QListWidgetItem *item = 0;
foreach(item, selected) {
foreach (item, selected) {
int row = mUI.mListWidget->row(item);
Application& app = mTempApplications->GetApplication(row);
ApplicationDialog dialog(tr("Modify an application"), app, this);

View File

@ -31,8 +31,10 @@ private slots:
private:
// Empty implementations of ErrorLogger methods.
// We don't care about the output in the benchmark tests.
void reportOut(const std::string & outmsg) {
void reportOut(const std::string & outmsg)
{
}
void reportErr(const ErrorLogger::ErrorMessage &msg) {
void reportErr(const ErrorLogger::ErrorMessage &msg)
{
}
};

View File

@ -988,7 +988,8 @@ public:
ScopeInfo(const Token *token, ScopeInfo *parent_) : _token(token), _parent(parent_) { }
~ScopeInfo();
ScopeInfo *parent() {
ScopeInfo *parent()
{
return _parent;
}
ScopeInfo *addChild(const Token *token);
@ -1053,17 +1054,20 @@ public:
_read(read),
_write(write),
_modified(modified),
_allocateMemory(allocateMemory) {
_allocateMemory(allocateMemory)
{
}
/** variable is used.. set both read+write */
void use() {
void use()
{
_read = true;
_write = true;
}
/** is variable unused? */
bool unused() const {
bool unused() const
{
return (_read == false && _write == false);
}
@ -1080,10 +1084,12 @@ public:
typedef std::map<unsigned int, VariableUsage> VariableMap;
void clear() {
void clear()
{
_varUsage.clear();
}
VariableMap &varUsage() {
VariableMap &varUsage()
{
return _varUsage;
}
void addVar(const Token *name, VariableType type, ScopeInfo *scope, bool write_);
@ -1098,7 +1104,8 @@ public:
void modified(unsigned int varid);
VariableUsage *find(unsigned int varid);
void alias(unsigned int varid1, unsigned int varid2, bool replace);
void erase(unsigned int varid) {
void erase(unsigned int varid)
{
_varUsage.erase(varid);
}
void eraseAliases(unsigned int varid);

View File

@ -109,7 +109,7 @@ void ThreadResult::SetFiles(const QStringList &files)
// Determine the total size of all of the files to check, so that we can
// show an accurate progress estimate
quint64 sizeOfFiles = 0;
foreach(const QString& file, files) {
foreach (const QString& file, files) {
sizeOfFiles += QFile(file).size();
}
mMaxProgress = sizeOfFiles;

View File

@ -63,7 +63,7 @@ TranslationHandler::~TranslationHandler()
const QStringList TranslationHandler::GetNames() const
{
QStringList names;
foreach(TranslationInfo translation, mTranslations) {
foreach (TranslationInfo translation, mTranslations) {
names.append(translation.mName);
}
return names;

View File

@ -76,7 +76,8 @@ public:
* @return List of available translations.
*
*/
QList<TranslationInfo> GetTranslations() const {
QList<TranslationInfo> GetTranslations() const
{
return mTranslations;
}

View File

@ -75,7 +75,7 @@ int XmlReport::determineVersion(const QString &filename)
}
break;
// Not handled
// Not handled
case QXmlStreamReader::EndElement:
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:

View File

@ -132,7 +132,7 @@ QList<ErrorItem> XmlReportV1::Read()
insideResults = false;
break;
// Not handled
// Not handled
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:

View File

@ -157,7 +157,7 @@ QList<ErrorItem> XmlReportV2::Read()
insideResults = false;
break;
// Not handled
// Not handled
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
@ -220,7 +220,7 @@ ErrorItem XmlReportV2::ReadError(QXmlStreamReader *reader)
errorRead = true;
break;
// Not handled
// Not handled
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:

View File

@ -44,22 +44,26 @@ public:
/** This constructor is used when running checks. */
Check(const std::string &aname, const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: _tokenizer(tokenizer), _settings(settings), _errorLogger(errorLogger), _name(aname) {
: _tokenizer(tokenizer), _settings(settings), _errorLogger(errorLogger), _name(aname)
{
}
virtual ~Check() {
virtual ~Check()
{
if (!_tokenizer)
instances().remove(this);
}
/** List of registered check classes. This is used by Cppcheck to run checks and generate documentation */
static std::list<Check *> &instances() {
static std::list<Check *> &instances()
{
static std::list<Check *> _instances;
return _instances;
}
/** run checks, the token list is not simplified */
virtual void runChecks(const Tokenizer *, const Settings *, ErrorLogger *) {
virtual void runChecks(const Tokenizer *, const Settings *, ErrorLogger *)
{
}
/** run checks, the token list is simplified */
@ -69,7 +73,8 @@ public:
virtual void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const = 0;
/** class name, used to generate documentation */
const std::string& name() const {
const std::string& name() const
{
return _name;
}
@ -83,7 +88,8 @@ public:
*/
static void reportError(const ErrorLogger::ErrorMessage &errmsg);
bool inconclusiveFlag() const {
bool inconclusiveFlag() const
{
return _settings && _settings->inconclusive;
}
@ -94,13 +100,15 @@ public:
virtual ~FileInfo() {}
};
virtual FileInfo * getFileInfo(const Tokenizer *tokenizer, const Settings *settings) const {
virtual FileInfo * getFileInfo(const Tokenizer *tokenizer, const Settings *settings) const
{
(void)tokenizer;
(void)settings;
return nullptr;
}
virtual void analyseWholeProgram(const std::list<FileInfo*> &fileInfo, ErrorLogger &errorLogger) {
virtual void analyseWholeProgram(const std::list<FileInfo*> &fileInfo, ErrorLogger &errorLogger)
{
(void)fileInfo;
(void)errorLogger;
}
@ -112,14 +120,16 @@ protected:
/** report an error */
template<typename T, typename U>
void reportError(const Token *tok, const Severity::SeverityType severity, const T id, const U msg, bool inconclusive = false) {
void reportError(const Token *tok, const Severity::SeverityType severity, const T id, const U msg, bool inconclusive = false)
{
std::list<const Token *> callstack(1, tok);
reportError(callstack, severity, id, msg, inconclusive);
}
/** report an error */
template<typename T, typename U>
void reportError(const std::list<const Token *> &callstack, Severity::SeverityType severity, const T id, const U msg, bool inconclusive = false) {
void reportError(const std::list<const Token *> &callstack, Severity::SeverityType severity, const T id, const U msg, bool inconclusive = false)
{
ErrorLogger::ErrorMessage errmsg(callstack, _tokenizer?&_tokenizer->list:0, severity, id, msg, inconclusive);
if (_errorLogger)
_errorLogger->reportErr(errmsg);

View File

@ -36,22 +36,26 @@
class CPPCHECKLIB Check64BitPortability : public Check {
public:
/** This constructor is used when registering the Check64BitPortability */
Check64BitPortability() : Check(myName()) {
Check64BitPortability() : Check(myName())
{
}
/** This constructor is used when running checks. */
Check64BitPortability(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {
: Check(myName(), tokenizer, settings, errorLogger)
{
}
/** @brief Run checks against the normal token list */
void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) {
void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
{
Check64BitPortability check64BitPortability(tokenizer, settings, errorLogger);
check64BitPortability.pointerassignment();
}
/** @brief Run checks against the simplified token list */
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) {
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
{
(void)tokenizer;
(void)settings;
(void)errorLogger;
@ -67,7 +71,8 @@ private:
void returnIntegerError(const Token *tok);
void returnPointerError(const Token *tok);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const {
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const
{
Check64BitPortability c(0, settings, errorLogger);
c.assignmentAddressToIntegerError(0);
c.assignmentIntegerToAddressError(0);
@ -75,11 +80,13 @@ private:
c.returnPointerError(0);
}
static std::string myName() {
static std::string myName()
{
return "64-bit portability";
}
std::string classInfo() const {
std::string classInfo() const
{
return "Check if there is 64-bit portability issues:\n"
"- assign address to/from int/long\n"
"- casting address from/to integer when returning from function\n";

View File

@ -34,14 +34,17 @@
class CPPCHECKLIB CheckAssert : public Check {
public:
CheckAssert() : Check(myName()) {
CheckAssert() : Check(myName())
{
}
CheckAssert(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {
: Check(myName(), tokenizer, settings, errorLogger)
{
}
virtual void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) {
virtual void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
{
CheckAssert check(tokenizer, settings, errorLogger);
check.assertWithSideEffects();
}
@ -56,17 +59,20 @@ private:
void sideEffectInAssertError(const Token *tok, const std::string& functionName);
void assignmentInAssertError(const Token *tok, const std::string &varname);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const {
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const
{
CheckAssert c(0, settings, errorLogger);
c.sideEffectInAssertError(0, "function");
c.assignmentInAssertError(0, "var");
}
static std::string myName() {
static std::string myName()
{
return "Assert";
}
std::string classInfo() const {
std::string classInfo() const
{
return "Warn if there are side effects in assert statements (since this cause different behaviour in debug/release builds).\n";
}
};

View File

@ -33,22 +33,26 @@
class CPPCHECKLIB CheckAutoVariables : public Check {
public:
/** This constructor is used when registering the CheckClass */
CheckAutoVariables() : Check(myName()) {
CheckAutoVariables() : Check(myName())
{
}
/** This constructor is used when running checks. */
CheckAutoVariables(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {
: Check(myName(), tokenizer, settings, errorLogger)
{
}
/** @brief Run checks against the normal token list */
void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) {
void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
{
CheckAutoVariables checkAutoVariables(tokenizer, settings, errorLogger);
checkAutoVariables.assignFunctionArg();
checkAutoVariables.returnReference();
}
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) {
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
{
CheckAutoVariables checkAutoVariables(tokenizer, settings, errorLogger);
checkAutoVariables.autoVariables();
checkAutoVariables.returnPointerToLocalArray();
@ -90,7 +94,8 @@ private:
void errorUselessAssignmentArg(const Token *tok);
void errorUselessAssignmentPtrArg(const Token *tok);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const {
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const
{
CheckAutoVariables c(0,settings,errorLogger);
c.errorAutoVariableAssignment(0, false);
c.errorReturnAddressToAutoVariable(0);
@ -103,11 +108,13 @@ private:
c.errorUselessAssignmentPtrArg(0);
}
static std::string myName() {
static std::string myName()
{
return "Auto Variables";
}
std::string classInfo() const {
std::string classInfo() const
{
return "A pointer to a variable is only valid as long as the variable is in scope.\n"
"Check:\n"
"- returning a pointer to auto or temporary variable\n"

View File

@ -37,16 +37,19 @@ class Variable;
class CPPCHECKLIB CheckBool : public Check {
public:
/** @brief This constructor is used when registering the CheckClass */
CheckBool() : Check(myName()) {
CheckBool() : Check(myName())
{
}
/** @brief This constructor is used when running checks. */
CheckBool(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {
: Check(myName(), tokenizer, settings, errorLogger)
{
}
/** @brief Run checks against the normal token list */
void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) {
void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
{
CheckBool checkBool(tokenizer, settings, errorLogger);
// Checks
@ -57,7 +60,8 @@ public:
}
/** @brief Run checks against the simplified token list */
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) {
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
{
CheckBool checkBool(tokenizer, settings, errorLogger);
// Checks
@ -110,7 +114,8 @@ private:
void comparisonOfBoolExpressionWithIntError(const Token *tok, bool n0o1);
void pointerArithBoolError(const Token *tok);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const {
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const
{
CheckBool c(0, settings, errorLogger);
c.assignBoolToPointerError(0);
@ -124,11 +129,13 @@ private:
c.pointerArithBoolError(0);
}
static std::string myName() {
static std::string myName()
{
return "Boolean";
}
std::string classInfo() const {
std::string classInfo() const
{
return "Boolean type checks\n"
"- using increment on boolean\n"
"- comparison of a boolean with a non-zero integer\n"

View File

@ -35,16 +35,19 @@ class Token;
class CPPCHECKLIB CheckBoost : public Check {
public:
/** This constructor is used when registering the CheckClass */
CheckBoost() : Check(myName()) {
CheckBoost() : Check(myName())
{
}
/** This constructor is used when running checks. */
CheckBoost(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {
: Check(myName(), tokenizer, settings, errorLogger)
{
}
/** Simplified checks. The token list is simplified. */
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) {
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
{
if (!tokenizer->isCPP())
return;
@ -59,16 +62,19 @@ public:
private:
void boostForeachError(const Token *tok);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const {
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const
{
CheckBoost c(0, settings, errorLogger);
c.boostForeachError(0);
}
static std::string myName() {
static std::string myName()
{
return "Boost usage";
}
std::string classInfo() const {
std::string classInfo() const
{
return "Check for invalid usage of Boost:\n"
"- container modification during BOOST_FOREACH\n";
}

View File

@ -47,15 +47,18 @@ class CPPCHECKLIB CheckBufferOverrun : public Check {
public:
/** This constructor is used when registering the CheckClass */
CheckBufferOverrun() : Check(myName()) {
CheckBufferOverrun() : Check(myName())
{
}
/** This constructor is used when running checks. */
CheckBufferOverrun(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {
: Check(myName(), tokenizer, settings, errorLogger)
{
}
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) {
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
{
CheckBufferOverrun checkBufferOverrun(tokenizer, settings, errorLogger);
checkBufferOverrun.bufferOverrun();
checkBufferOverrun.bufferOverrun2();
@ -140,36 +143,44 @@ public:
ArrayInfo limit(MathLib::bigint value) const;
/** array sizes */
const std::vector<MathLib::bigint> &num() const {
const std::vector<MathLib::bigint> &num() const
{
return _num;
}
/** array size */
MathLib::bigint num(std::size_t index) const {
MathLib::bigint num(std::size_t index) const
{
return _num[index];
}
void num(std::size_t index, MathLib::bigint number) {
void num(std::size_t index, MathLib::bigint number)
{
_num[index] = number;
}
/** size of each element */
MathLib::bigint element_size() const {
MathLib::bigint element_size() const
{
return _element_size;
}
/** Variable name */
unsigned int declarationId() const {
unsigned int declarationId() const
{
return _declarationId;
}
void declarationId(unsigned int id) {
void declarationId(unsigned int id)
{
_declarationId = id;
}
/** Variable name */
const std::string &varname() const {
const std::string &varname() const
{
return _varname;
}
void varname(const std::string &name) {
void varname(const std::string &name)
{
_varname = name;
}
};
@ -250,7 +261,8 @@ private:
void valueFlowCheckArrayIndex(const Token * const tok, const ArrayInfo &arrayInfo);
public:
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const {
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const
{
CheckBufferOverrun c(0, settings, errorLogger);
std::vector<MathLib::bigint> indexes;
indexes.push_back(2);
@ -274,11 +286,13 @@ public:
}
private:
static std::string myName() {
static std::string myName()
{
return "Bounds checking";
}
std::string classInfo() const {
std::string classInfo() const
{
return "Out of bounds checking:\n"
"- Array index out of bounds detection by value flow analysis\n"
"- Dangerous usage of strncat()\n"

View File

@ -35,14 +35,16 @@ class Function;
class CPPCHECKLIB CheckClass : public Check {
public:
/** @brief This constructor is used when registering the CheckClass */
CheckClass() : Check(myName()), symbolDatabase(NULL) {
CheckClass() : Check(myName()), symbolDatabase(NULL)
{
}
/** @brief This constructor is used when running checks. */
CheckClass(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger);
/** @brief Run checks on the normal token list */
void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) {
void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
{
if (tokenizer->isC())
return;
@ -53,7 +55,8 @@ public:
}
/** @brief Run checks on the simplified token list */
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) {
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
{
if (tokenizer->isC())
return;
@ -160,7 +163,8 @@ private:
void callsPureVirtualFunctionError(const Function & scopeFunction, const std::list<const Token *> & tokStack, const std::string &purefuncname);
void duplInheritedMembersError(const Token* tok1, const Token* tok2, const std::string &derivedname, const std::string &basename, const std::string &variablename, bool derivedIsStruct, bool baseIsStruct);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const {
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const
{
CheckClass c(0, settings, errorLogger);
c.noConstructorError(0, "classname", false);
//c.copyConstructorMallocError(0, 0, "var");
@ -187,11 +191,13 @@ private:
c.duplInheritedMembersError(0, 0, "class", "class", "variable", false, false);
}
static std::string myName() {
static std::string myName()
{
return "Class";
}
std::string classInfo() const {
std::string classInfo() const
{
return "Check the code for each class.\n"
"- Missing constructors and copy constructors\n"
//"- Missing allocation of memory in copy constructor\n"

View File

@ -36,22 +36,26 @@
class CPPCHECKLIB CheckCondition : public Check {
public:
/** This constructor is used when registering the CheckAssignIf */
CheckCondition() : Check(myName()) {
CheckCondition() : Check(myName())
{
}
/** This constructor is used when running checks. */
CheckCondition(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {
: Check(myName(), tokenizer, settings, errorLogger)
{
}
void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) {
void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
{
CheckCondition checkCondition(tokenizer, settings, errorLogger);
checkCondition.multiCondition();
checkCondition.clarifyCondition(); // not simplified because ifAssign
}
/** @brief Run checks against the simplified token list */
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) {
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
{
CheckCondition checkCondition(tokenizer, settings, errorLogger);
checkCondition.assignIf();
checkCondition.comparison();
@ -110,7 +114,8 @@ private:
void clarifyConditionError(const Token *tok, bool assign, bool boolop);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const {
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const
{
CheckCondition c(0, settings, errorLogger);
c.assignIfError(0, 0, "", false);
@ -124,11 +129,13 @@ private:
c.clarifyConditionError(0, true, false);
}
static std::string myName() {
static std::string myName()
{
return "Condition";
}
std::string classInfo() const {
std::string classInfo() const
{
return "Match conditions with assignments and other conditions:\n"
"- Mismatching assignment and comparison => comparison is always true/false\n"
"- Mismatching lhs and rhs in comparison => comparison is always true/false\n"

View File

@ -40,16 +40,19 @@
class CPPCHECKLIB CheckExceptionSafety : public Check {
public:
/** This constructor is used when registering the CheckClass */
CheckExceptionSafety() : Check(myName()) {
CheckExceptionSafety() : Check(myName())
{
}
/** This constructor is used when running checks. */
CheckExceptionSafety(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {
: Check(myName(), tokenizer, settings, errorLogger)
{
}
/** Checks that uses the simplified token list */
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) {
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
{
if (tokenizer->isC())
return;
@ -82,7 +85,8 @@ public:
private:
/** Don't throw exceptions in destructors */
void destructorsError(const Token * const tok, const std::string &className) {
void destructorsError(const Token * const tok, const std::string &className)
{
reportError(tok, Severity::warning, "exceptThrowInDestructor",
"Class " + className + " is not safe, destructor throws exception\n"
"The class " + className + " is not safe because its destructor "
@ -90,19 +94,22 @@ private:
"is thrown that is caught in an outer scope the program will terminate.");
}
void deallocThrowError(const Token * const tok, const std::string &varname) {
void deallocThrowError(const Token * const tok, const std::string &varname)
{
reportError(tok, Severity::warning, "exceptDeallocThrow", "Exception thrown in invalid state, '" +
varname + "' points at deallocated memory.");
}
void rethrowCopyError(const Token * const tok, const std::string &varname) {
void rethrowCopyError(const Token * const tok, const std::string &varname)
{
reportError(tok, Severity::style, "exceptRethrowCopy",
"Throwing a copy of the caught exception instead of rethrowing the original exception.\n"
"Rethrowing an exception with 'throw " + varname + ";' creates an unnecessary copy of '" + varname + "'. "
"To rethrow the caught exception without unnecessary copying or slicing, use a bare 'throw;'.");
}
void catchExceptionByValueError(const Token *tok) {
void catchExceptionByValueError(const Token *tok)
{
reportError(tok, Severity::style,
"catchExceptionByValue", "Exception should be caught by reference.\n"
"The exception is caught by value. It could be caught "
@ -110,27 +117,32 @@ private:
}
/** Don't throw exceptions in noexcept functions */
void noexceptThrowError(const Token * const tok) {
void noexceptThrowError(const Token * const tok)
{
reportError(tok, Severity::error, "exceptThrowInNoexecptFunction", "Exception thrown in noexcept function.");
}
/** Don't throw exceptions in throw() functions */
void nothrowThrowError(const Token * const tok) {
void nothrowThrowError(const Token * const tok)
{
reportError(tok, Severity::error, "exceptThrowInNoThrowFunction", "Exception thrown in throw() function.");
}
/** Don't throw exceptions in __attribute__((nothrow)) functions */
void nothrowAttributeThrowError(const Token * const tok) {
void nothrowAttributeThrowError(const Token * const tok)
{
reportError(tok, Severity::error, "exceptThrowInAttributeNoThrowFunction", "Exception thrown in __attribute__((nothrow)) function.");
}
/** Don't throw exceptions in __declspec(nothrow) functions */
void nothrowDeclspecThrowError(const Token * const tok) {
void nothrowDeclspecThrowError(const Token * const tok)
{
reportError(tok, Severity::error, "exceptThrowInDeclspecNoThrowFunction", "Exception thrown in __declspec(nothrow) function.");
}
/** Missing exception specification */
void unhandledExceptionSpecificationError(const Token * const tok1, const Token * const tok2, const std::string & funcname) {
void unhandledExceptionSpecificationError(const Token * const tok1, const Token * const tok2, const std::string & funcname)
{
std::string str1(tok1 ? tok1->str() : "foo");
std::list<const Token*> locationList;
locationList.push_back(tok1);
@ -142,7 +154,8 @@ private:
}
/** Generate all possible errors (for --errorlist) */
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const {
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const
{
CheckExceptionSafety c(0, settings, errorLogger);
c.destructorsError(0, "Class");
c.deallocThrowError(0, "p");
@ -156,12 +169,14 @@ private:
}
/** Short description of class (for --doc) */
static std::string myName() {
static std::string myName()
{
return "Exception Safety";
}
/** wiki formatted description of the class (for --doc) */
std::string classInfo() const {
std::string classInfo() const
{
return "Checking exception safety\n"
"- Throwing exceptions in destructors\n"
"- Throwing exception during invalid state\n"

View File

@ -33,16 +33,19 @@
class CPPCHECKLIB CheckInternal : public Check {
public:
/** This constructor is used when registering the CheckClass */
CheckInternal() : Check(myName()) {
CheckInternal() : Check(myName())
{
}
/** This constructor is used when running checks. */
CheckInternal(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {
: Check(myName(), tokenizer, settings, errorLogger)
{
}
/** Simplified checks. The token list is simplified. */
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) {
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
{
if (!settings->isEnabled("internal"))
return;
@ -79,7 +82,8 @@ private:
void redundantNextPreviousError(const Token* tok, const std::string& func1, const std::string& func2);
void orInComplexPattern(const Token *tok, const std::string &pattern, const std::string &funcname);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const {
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const
{
CheckInternal c(0, settings, errorLogger);
c.multiComparePatternError(0, ";|%type%", "Match");
c.simplePatternError(0, "class {", "Match");
@ -90,11 +94,13 @@ private:
c.orInComplexPattern(0, "||", "Match");
}
static std::string myName() {
static std::string myName()
{
return "cppcheck internal API usage";
}
std::string classInfo() const {
std::string classInfo() const
{
// Don't include these checks on the WIKI where people can read what
// checks there are. These checks are not intended for users.
return "";

View File

@ -89,7 +89,8 @@ struct Filepointer {
enum AppendMode { UNKNOWN_AM, APPEND, APPEND_EX };
AppendMode append_mode;
explicit Filepointer(OpenMode mode_ = UNKNOWN_OM)
: mode(mode_), mode_indent(0), lastOperation(NONE), op_indent(0), append_mode(UNKNOWN_AM) {
: mode(mode_), mode_indent(0), lastOperation(NONE), op_indent(0), append_mode(UNKNOWN_AM)
{
}
};
@ -1004,7 +1005,7 @@ void CheckIO::checkWrongPrintfScanfArguments()
case 'l':
if (i+1 != formatString.end() && *(i+1) == *i)
specifier += *i++;
// fallthrough
// fallthrough
case 'j':
case 'q':
case 't':
@ -1306,7 +1307,7 @@ void CheckIO::checkWrongPrintfScanfArguments()
specifier += *i++;
specifier += *i++;
}
// fallthrough
// fallthrough
case 'j': // intmax_t or uintmax_t
case 'z': // size_t
case 't': // ptrdiff_t

View File

@ -31,23 +31,27 @@
class CPPCHECKLIB CheckIO : public Check {
public:
/** @brief This constructor is used when registering CheckIO */
CheckIO() : Check(myName()) {
CheckIO() : Check(myName())
{
}
/** @brief This constructor is used when running checks. */
CheckIO(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {
: Check(myName(), tokenizer, settings, errorLogger)
{
}
/** @brief Run checks on the normal token list */
void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) {
void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
{
CheckIO checkIO(tokenizer, settings, errorLogger);
checkIO.checkWrongPrintfScanfArguments();
}
/** @brief Run checks on the simplified token list */
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) {
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
{
CheckIO checkIO(tokenizer, settings, errorLogger);
checkIO.checkCoutCerrMisusage();
@ -122,7 +126,8 @@ private:
void invalidScanfFormatWidthError(const Token* tok, unsigned int numFormat, int width, const Variable *var);
static void argumentType(std::ostream & s, const ArgumentInfo * argInfo);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const {
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const
{
CheckIO c(0, settings, errorLogger);
c.coutCerrMisusageError(0, "cout");
@ -149,11 +154,13 @@ private:
c.wrongPrintfScanfPosixParameterPositionError(0, "printf", 2, 1);
}
static std::string myName() {
static std::string myName()
{
return "IO using format string";
}
std::string classInfo() const {
std::string classInfo() const
{
return "Check format string input/output operations.\n"
"- Bad usage of the function 'sprintf' (overlapping data)\n"
"- Missing or wrong width specifiers in 'scanf' format string\n"

View File

@ -36,20 +36,23 @@ public:
std::set<unsigned int> conditionalAlloc;
std::set<unsigned int> referenced;
void clear() {
void clear()
{
alloctype.clear();
possibleUsage.clear();
conditionalAlloc.clear();
referenced.clear();
}
void erase(unsigned int varid) {
void erase(unsigned int varid)
{
alloctype.erase(varid);
possibleUsage.erase(varid);
conditionalAlloc.erase(varid);
}
void swap(VarInfo &other) {
void swap(VarInfo &other)
{
alloctype.swap(other.alloctype);
possibleUsage.swap(other.possibleUsage);
conditionalAlloc.swap(other.conditionalAlloc);
@ -73,16 +76,19 @@ public:
class CPPCHECKLIB CheckLeakAutoVar : public Check {
public:
/** This constructor is used when registering the CheckLeakAutoVar */
CheckLeakAutoVar() : Check(myName()) {
CheckLeakAutoVar() : Check(myName())
{
}
/** This constructor is used when running checks. */
CheckLeakAutoVar(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {
: Check(myName(), tokenizer, settings, errorLogger)
{
}
/** @brief Run checks against the simplified token list */
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) {
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
{
CheckLeakAutoVar checkLeakAutoVar(tokenizer, settings, errorLogger);
checkLeakAutoVar.check();
}
@ -114,17 +120,20 @@ private:
/** message: user configuration is needed to complete analysis */
void configurationInfo(const Token* tok, const std::string &functionName);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const {
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const
{
CheckLeakAutoVar c(0, settings, errorLogger);
c.deallocReturnError(0, "p");
c.configurationInfo(0, "f"); // user configuration is needed to complete analysis
}
static std::string myName() {
static std::string myName()
{
return "Leaks (auto variables)";
}
std::string classInfo() const {
std::string classInfo() const
{
return "Detect when a auto variable is allocated but not deallocated.\n";
}
};

View File

@ -86,7 +86,8 @@ private:
public:
CheckMemoryLeak(const Tokenizer *t, ErrorLogger *e, const Settings *s)
: tokenizer(t), errorLogger(e), settings1(s) {
: tokenizer(t), errorLogger(e), settings1(s)
{
}
/** @brief What type of allocation are used.. the "Many" means that several types of allocation and deallocation are used */
@ -181,12 +182,14 @@ public:
class CPPCHECKLIB CheckMemoryLeakInFunction : private Check, public CheckMemoryLeak {
public:
/** @brief This constructor is used when registering this class */
CheckMemoryLeakInFunction() : Check(myName()), CheckMemoryLeak(0, 0, 0), symbolDatabase(NULL) {
CheckMemoryLeakInFunction() : Check(myName()), CheckMemoryLeak(0, 0, 0), symbolDatabase(NULL)
{
}
/** @brief This constructor is used when running checks */
CheckMemoryLeakInFunction(const Tokenizer *tokenizr, const Settings *settings, ErrorLogger *errLog)
: Check(myName(), tokenizr, settings, errLog), CheckMemoryLeak(tokenizr, errLog, settings) {
: Check(myName(), tokenizr, settings, errLog), CheckMemoryLeak(tokenizr, errLog, settings)
{
// get the symbol database
if (tokenizr)
symbolDatabase = tokenizr->getSymbolDatabase();
@ -195,7 +198,8 @@ public:
}
/** @brief run all simplified checks */
void runSimplifiedChecks(const Tokenizer *tokenizr, const Settings *settings, ErrorLogger *errLog) {
void runSimplifiedChecks(const Tokenizer *tokenizr, const Settings *settings, ErrorLogger *errLog)
{
CheckMemoryLeakInFunction checkMemoryLeak(tokenizr, settings, errLog);
checkMemoryLeak.checkReallocUsage();
checkMemoryLeak.check();
@ -298,7 +302,8 @@ public:
private:
/** Report all possible errors (for the --errorlist) */
void getErrorMessages(ErrorLogger *e, const Settings *settings) const {
void getErrorMessages(ErrorLogger *e, const Settings *settings) const
{
CheckMemoryLeakInFunction c(0, settings, e);
c.memleakError(0, "varname");
@ -316,7 +321,8 @@ private:
* Get name of class (--doc)
* @return name of class
*/
static std::string myName() {
static std::string myName()
{
return "Memory leaks (function variables)";
}
@ -324,7 +330,8 @@ private:
* Get class information (--doc)
* @return Wiki formatted information about this class
*/
std::string classInfo() const {
std::string classInfo() const
{
return "Is there any allocated memory when a function goes out of scope\n";
}
@ -339,14 +346,17 @@ private:
class CPPCHECKLIB CheckMemoryLeakInClass : private Check, private CheckMemoryLeak {
public:
CheckMemoryLeakInClass() : Check(myName()), CheckMemoryLeak(0, 0, 0) {
CheckMemoryLeakInClass() : Check(myName()), CheckMemoryLeak(0, 0, 0)
{
}
CheckMemoryLeakInClass(const Tokenizer *tokenizr, const Settings *settings, ErrorLogger *errLog)
: Check(myName(), tokenizr, settings, errLog), CheckMemoryLeak(tokenizr, errLog, settings) {
: Check(myName(), tokenizr, settings, errLog), CheckMemoryLeak(tokenizr, errLog, settings)
{
}
void runSimplifiedChecks(const Tokenizer *tokenizr, const Settings *settings, ErrorLogger *errLog) {
void runSimplifiedChecks(const Tokenizer *tokenizr, const Settings *settings, ErrorLogger *errLog)
{
if (!tokenizr->isCPP())
return;
@ -365,17 +375,20 @@ private:
void unsafeClassError(const Token *tok, const std::string &classname, const std::string &varname);
void getErrorMessages(ErrorLogger *e, const Settings *settings) const {
void getErrorMessages(ErrorLogger *e, const Settings *settings) const
{
CheckMemoryLeakInClass c(0, settings, e);
c.publicAllocationError(0, "varname");
c.unsafeClassError(0, "class", "class::varname");
}
static std::string myName() {
static std::string myName()
{
return "Memory leaks (class variables)";
}
std::string classInfo() const {
std::string classInfo() const
{
return "If the constructor allocate memory then the destructor must deallocate it.\n";
}
};
@ -386,14 +399,17 @@ private:
class CPPCHECKLIB CheckMemoryLeakStructMember : private Check, private CheckMemoryLeak {
public:
CheckMemoryLeakStructMember() : Check(myName()), CheckMemoryLeak(0, 0, 0) {
CheckMemoryLeakStructMember() : Check(myName()), CheckMemoryLeak(0, 0, 0)
{
}
CheckMemoryLeakStructMember(const Tokenizer *tokenizr, const Settings *settings, ErrorLogger *errLog)
: Check(myName(), tokenizr, settings, errLog), CheckMemoryLeak(tokenizr, errLog, settings) {
: Check(myName(), tokenizr, settings, errLog), CheckMemoryLeak(tokenizr, errLog, settings)
{
}
void runSimplifiedChecks(const Tokenizer *tokenizr, const Settings *settings, ErrorLogger *errLog) {
void runSimplifiedChecks(const Tokenizer *tokenizr, const Settings *settings, ErrorLogger *errLog)
{
CheckMemoryLeakStructMember checkMemoryLeak(tokenizr, settings, errLog);
checkMemoryLeak.check();
}
@ -407,14 +423,17 @@ private:
void checkStructVariable(const Variable * const variable);
void getErrorMessages(ErrorLogger * /*errorLogger*/, const Settings * /*settings*/) const {
void getErrorMessages(ErrorLogger * /*errorLogger*/, const Settings * /*settings*/) const
{
}
static std::string myName() {
static std::string myName()
{
return "Memory leaks (struct members)";
}
std::string classInfo() const {
std::string classInfo() const
{
return "Don't forget to deallocate struct members\n";
}
};
@ -425,14 +444,17 @@ private:
class CPPCHECKLIB CheckMemoryLeakNoVar : private Check, private CheckMemoryLeak {
public:
CheckMemoryLeakNoVar() : Check(myName()), CheckMemoryLeak(0, 0, 0) {
CheckMemoryLeakNoVar() : Check(myName()), CheckMemoryLeak(0, 0, 0)
{
}
CheckMemoryLeakNoVar(const Tokenizer *tokenizr, const Settings *settings, ErrorLogger *errLog)
: Check(myName(), tokenizr, settings, errLog), CheckMemoryLeak(tokenizr, errLog, settings) {
: Check(myName(), tokenizr, settings, errLog), CheckMemoryLeak(tokenizr, errLog, settings)
{
}
void runSimplifiedChecks(const Tokenizer *tokenizr, const Settings *settings, ErrorLogger *errLog) {
void runSimplifiedChecks(const Tokenizer *tokenizr, const Settings *settings, ErrorLogger *errLog)
{
CheckMemoryLeakNoVar checkMemoryLeak(tokenizr, settings, errLog);
checkMemoryLeak.check();
}
@ -449,18 +471,21 @@ private:
void functionCallLeak(const Token *loc, const std::string &alloc, const std::string &functionCall);
void returnValueNotUsedError(const Token* tok, const std::string &alloc);
void getErrorMessages(ErrorLogger *e, const Settings *settings) const {
void getErrorMessages(ErrorLogger *e, const Settings *settings) const
{
CheckMemoryLeakNoVar c(0, settings, e);
c.functionCallLeak(0, "funcName", "funcName");
c.returnValueNotUsedError(0, "funcName");
}
static std::string myName() {
static std::string myName()
{
return "Memory leaks (address not taken)";
}
std::string classInfo() const {
std::string classInfo() const
{
return "Not taking the address to allocated memory\n";
}
};

View File

@ -37,17 +37,20 @@
class CPPCHECKLIB CheckNonReentrantFunctions : public Check {
public:
/** This constructor is used when registering the CheckNonReentrantFunctions */
CheckNonReentrantFunctions() : Check(myName()) {
CheckNonReentrantFunctions() : Check(myName())
{
initNonReentrantFunctions();
}
/** This constructor is used when running checks. */
CheckNonReentrantFunctions(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {
: Check(myName(), tokenizer, settings, errorLogger)
{
initNonReentrantFunctions();
}
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) {
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
{
CheckNonReentrantFunctions checkNonReentrantFunctions(tokenizer, settings, errorLogger);
checkNonReentrantFunctions.nonReentrantFunctions();
}
@ -61,7 +64,8 @@ private:
std::map<std::string,std::string> _nonReentrantFunctions;
/** init nonreentrant functions list ' */
void initNonReentrantFunctions() {
void initNonReentrantFunctions()
{
static const char * const non_reentrant_functions_list[] = {
"localtime", "gmtime", "strtok", "gethostbyname", "gethostbyaddr", "getservbyname"
, "getservbyport", "crypt", "ttyname", "gethostbyname2"
@ -82,7 +86,8 @@ private:
}
}
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const {
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const
{
CheckNonReentrantFunctions c(0, settings, errorLogger);
std::map<std::string,std::string>::const_iterator it(_nonReentrantFunctions.begin()), itend(_nonReentrantFunctions.end());
@ -91,11 +96,13 @@ private:
}
}
static std::string myName() {
static std::string myName()
{
return "Non reentrant functions";
}
std::string classInfo() const {
std::string classInfo() const
{
std::string info = "Warn if any of these non reentrant functions are used:\n";
std::map<std::string,std::string>::const_iterator it(_nonReentrantFunctions.begin()), itend(_nonReentrantFunctions.end());
for (; it!=itend; ++it) {

View File

@ -35,22 +35,26 @@
class CPPCHECKLIB CheckNullPointer : public Check {
public:
/** @brief This constructor is used when registering the CheckNullPointer */
CheckNullPointer() : Check(myName()) {
CheckNullPointer() : Check(myName())
{
}
/** @brief This constructor is used when running checks. */
CheckNullPointer(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {
: Check(myName(), tokenizer, settings, errorLogger)
{
}
/** @brief Run checks against the normal token list */
void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) {
void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
{
CheckNullPointer checkNullPointer(tokenizer, settings, errorLogger);
checkNullPointer.nullPointer();
}
/** @brief Run checks against the simplified token list */
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) {
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
{
CheckNullPointer checkNullPointer(tokenizer, settings, errorLogger);
checkNullPointer.nullConstantDereference();
}
@ -92,18 +96,21 @@ public:
private:
/** Get error messages. Used by --errorlist */
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const {
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const
{
CheckNullPointer c(0, settings, errorLogger);
c.nullPointerError(0, "pointer");
}
/** Name of check */
static std::string myName() {
static std::string myName()
{
return "Null pointer";
}
/** class info in WIKI format. Used by --doc */
std::string classInfo() const {
std::string classInfo() const
{
return "Null pointers\n"
"- null pointer dereferencing\n";
}

View File

@ -38,17 +38,20 @@
class CPPCHECKLIB CheckObsoleteFunctions : public Check {
public:
/** This constructor is used when registering the CheckObsoleteFunctions */
CheckObsoleteFunctions() : Check(myName()) {
CheckObsoleteFunctions() : Check(myName())
{
initObsoleteFunctions();
}
/** This constructor is used when running checks. */
CheckObsoleteFunctions(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {
: Check(myName(), tokenizer, settings, errorLogger)
{
initObsoleteFunctions();
}
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) {
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
{
CheckObsoleteFunctions checkObsoleteFunctions(tokenizer, settings, errorLogger);
checkObsoleteFunctions.obsoleteFunctions();
}
@ -63,7 +66,8 @@ private:
std::map<std::string, std::string> _obsoleteC99Functions;
/** init obsolete functions list ' */
void initObsoleteFunctions() {
void initObsoleteFunctions()
{
// Obsolete posix functions, which messages suggest only one alternative and doesn't contain additional information.
const struct {
const char* bad;
@ -122,7 +126,8 @@ private:
//_obsoleteC99Functions["ctime"] = "Obsolete function 'ctime' called. It is recommended to use the function 'strftime' instead.";
}
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const {
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const
{
CheckObsoleteFunctions c(0, settings, errorLogger);
std::map<std::string,std::string>::const_iterator it(_obsoletePosixFunctions.begin()), itend(_obsoletePosixFunctions.end());
@ -131,11 +136,13 @@ private:
}
}
static std::string myName() {
static std::string myName()
{
return "Obsolete functions";
}
std::string classInfo() const {
std::string classInfo() const
{
std::string info = "Warn if any of these obsolete functions are used:\n";
std::map<std::string,std::string>::const_iterator it(_obsoletePosixFunctions.begin()), itend(_obsoletePosixFunctions.end());
for (; it!=itend; ++it) {

View File

@ -44,16 +44,19 @@ bool astIsFloat(const Token *tok, bool unknown);
class CPPCHECKLIB CheckOther : public Check {
public:
/** @brief This constructor is used when registering the CheckClass */
CheckOther() : Check(myName()) {
CheckOther() : Check(myName())
{
}
/** @brief This constructor is used when running checks. */
CheckOther(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {
: Check(myName(), tokenizer, settings, errorLogger)
{
}
/** @brief Run checks against the normal token list */
void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) {
void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
{
CheckOther checkOther(tokenizer, settings, errorLogger);
// Checks
@ -77,7 +80,8 @@ public:
}
/** @brief Run checks against the simplified token list */
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) {
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
{
CheckOther checkOther(tokenizer, settings, errorLogger);
// Checks
@ -288,7 +292,8 @@ private:
void commaSeparatedReturnError(const Token *tok);
void ignoredReturnValueError(const Token* tok, const std::string& function);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const {
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const
{
CheckOther c(0, settings, errorLogger);
// error
@ -345,11 +350,13 @@ private:
c.ignoredReturnValueError(0, "malloc");
}
static std::string myName() {
static std::string myName()
{
return "Other";
}
std::string classInfo() const {
std::string classInfo() const
{
return "Other checks\n"
// error

View File

@ -35,15 +35,18 @@
class CPPCHECKLIB CheckPostfixOperator : public Check {
public:
/** This constructor is used when registering the CheckPostfixOperator */
CheckPostfixOperator() : Check(myName()) {
CheckPostfixOperator() : Check(myName())
{
}
/** This constructor is used when running checks. */
CheckPostfixOperator(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {
: Check(myName(), tokenizer, settings, errorLogger)
{
}
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) {
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
{
if (tokenizer->isC())
return;
@ -58,16 +61,19 @@ private:
/** Report Error */
void postfixOperatorError(const Token *tok);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const {
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const
{
CheckPostfixOperator c(0, settings, errorLogger);
c.postfixOperatorError(0);
}
static std::string myName() {
static std::string myName()
{
return "Using postfix operators";
}
std::string classInfo() const {
std::string classInfo() const
{
return "Warn if using postfix operators ++ or -- rather than prefix operator\n";
}
};

View File

@ -37,16 +37,19 @@ class Variable;
class CPPCHECKLIB CheckSizeof : public Check {
public:
/** @brief This constructor is used when registering the CheckClass */
CheckSizeof() : Check(myName()) {
CheckSizeof() : Check(myName())
{
}
/** @brief This constructor is used when running checks. */
CheckSizeof(const Tokenizer* tokenizer, const Settings* settings, ErrorLogger* errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {
: Check(myName(), tokenizer, settings, errorLogger)
{
}
/** @brief Run checks against the normal token list */
void runChecks(const Tokenizer* tokenizer, const Settings* settings, ErrorLogger* errorLogger) {
void runChecks(const Tokenizer* tokenizer, const Settings* settings, ErrorLogger* errorLogger)
{
CheckSizeof checkSizeof(tokenizer, settings, errorLogger);
// Checks
@ -60,7 +63,8 @@ public:
}
/** @brief Run checks against the simplified token list */
void runSimplifiedChecks(const Tokenizer*, const Settings*, ErrorLogger*) {
void runSimplifiedChecks(const Tokenizer*, const Settings*, ErrorLogger*)
{
}
/** @brief %Check for 'sizeof sizeof ..' */
@ -98,7 +102,8 @@ private:
void sizeofDereferencedVoidPointerError(const Token *tok, const std::string &varname);
void arithOperationsOnVoidPointerError(const Token* tok, const std::string &varname, const std::string &vartype);
void getErrorMessages(ErrorLogger* errorLogger, const Settings* settings) const {
void getErrorMessages(ErrorLogger* errorLogger, const Settings* settings) const
{
CheckSizeof c(0, settings, errorLogger);
c.sizeofForArrayParameterError(0);
@ -114,11 +119,13 @@ private:
c.arithOperationsOnVoidPointerError(0, "varname", "vartype");
}
static std::string myName() {
static std::string myName()
{
return "Sizeof";
}
std::string classInfo() const {
std::string classInfo() const
{
return "sizeof() usage checks\n"
"- sizeof for array given as function argument\n"
"- sizeof for numeric given as function argument\n"

View File

@ -363,7 +363,8 @@ void CheckStl::stlOutOfBoundsError(const Token *tok, const std::string &num, con
*/
class EraseCheckLoop : public ExecutionPath {
public:
static void checkScope(CheckStl *checkStl, const Token *it) {
static void checkScope(CheckStl *checkStl, const Token *it)
{
const Token *tok = it;
// Search for the start of the loop body..
@ -397,7 +398,8 @@ public:
private:
/** Startup constructor */
EraseCheckLoop(Check *o, unsigned int varid, const Token* usetoken)
: ExecutionPath(o, varid), eraseToken(0), useToken(usetoken) {
: ExecutionPath(o, varid), eraseToken(0), useToken(usetoken)
{
}
/** @brief token where iterator is erased (non-zero => the iterator is invalid) */
@ -407,18 +409,21 @@ private:
const Token* useToken;
/** @brief Copy this check. Called from the ExecutionPath baseclass. */
ExecutionPath *copy() {
ExecutionPath *copy()
{
return new EraseCheckLoop(*this);
}
/** @brief is another execution path equal? */
bool is_equal(const ExecutionPath *e) const {
bool is_equal(const ExecutionPath *e) const
{
const EraseCheckLoop *c = static_cast<const EraseCheckLoop *>(e);
return (eraseToken == c->eraseToken);
}
/** @brief parse tokens */
const Token *parse(const Token &tok, std::list<ExecutionPath *> &checks) const {
const Token *parse(const Token &tok, std::list<ExecutionPath *> &checks) const
{
// bail out if there are assignments. We don't check the assignments properly.
if (Token::Match(&tok, "[;{}] %var% =") || Token::Match(&tok, "= %var% ;")) {
ExecutionPath::bailOutVar(checks, tok.next()->varId());
@ -471,7 +476,8 @@ private:
* @param checks The execution paths. All execution paths in the list are executed in the current scope
* @return true => bail out all checking
**/
bool parseCondition(const Token &tok, std::list<ExecutionPath *> &checks) {
bool parseCondition(const Token &tok, std::list<ExecutionPath *> &checks)
{
// no checking of conditions.
(void)tok;
(void)checks;
@ -479,7 +485,8 @@ private:
}
/** @brief going out of scope - all execution paths end */
void end(const std::list<ExecutionPath *> &checks, const Token * /*tok*/) const {
void end(const std::list<ExecutionPath *> &checks, const Token * /*tok*/) const
{
// check if there are any invalid iterators. If so there is an error.
for (std::list<ExecutionPath *>::const_iterator it = checks.begin(); it != checks.end(); ++it) {
EraseCheckLoop *c = dynamic_cast<EraseCheckLoop *>(*it);

View File

@ -34,16 +34,19 @@
class CPPCHECKLIB CheckStl : public Check {
public:
/** This constructor is used when registering the CheckClass */
CheckStl() : Check(myName()) {
CheckStl() : Check(myName())
{
}
/** This constructor is used when running checks. */
CheckStl(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {
: Check(myName(), tokenizer, settings, errorLogger)
{
}
/** Simplified checks. The token list is simplified. */
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) {
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
{
if (!tokenizer->isCPP())
return;
@ -189,7 +192,8 @@ private:
void readingEmptyStlContainerError(const Token *tok);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const {
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const
{
CheckStl c(0, settings, errorLogger);
c.invalidIteratorError(0, "iterator");
c.iteratorsError(0, "container1", "container2");
@ -219,11 +223,13 @@ private:
c.readingEmptyStlContainerError(0);
}
static std::string myName() {
static std::string myName()
{
return "STL usage";
}
std::string classInfo() const {
std::string classInfo() const
{
return "Check for invalid usage of STL:\n"
"- out of bounds errors\n"
"- misuse of iterators when iterating through a container\n"

View File

@ -34,16 +34,19 @@
class CPPCHECKLIB CheckString : public Check {
public:
/** @brief This constructor is used when registering the CheckClass */
CheckString() : Check(myName()) {
CheckString() : Check(myName())
{
}
/** @brief This constructor is used when running checks. */
CheckString(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {
: Check(myName(), tokenizer, settings, errorLogger)
{
}
/** @brief Run checks against the normal token list */
void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) {
void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
{
CheckString checkString(tokenizer, settings, errorLogger);
// Checks
@ -52,7 +55,8 @@ public:
}
/** @brief Run checks against the simplified token list */
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) {
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
{
CheckString checkString(tokenizer, settings, errorLogger);
// Checks
@ -86,7 +90,8 @@ private:
void suspiciousStringCompareError(const Token* tok, const std::string& var);
void suspiciousStringCompareError_char(const Token* tok, const std::string& var);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const {
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const
{
CheckString c(0, settings, errorLogger);
c.sprintfOverlappingDataError(0, "varname");
@ -99,11 +104,13 @@ private:
c.alwaysTrueStringVariableCompareError(0, "varname1", "varname2");
}
static std::string myName() {
static std::string myName()
{
return "String";
}
std::string classInfo() const {
std::string classInfo() const
{
return "Detect misusage of C-style strings:\n"
"- overlapping buffers passed to sprintf as source and destination\n"
"- incorrect length arguments for 'substr' and 'strncmp'\n"

View File

@ -34,16 +34,19 @@
class CPPCHECKLIB CheckType : public Check {
public:
/** @brief This constructor is used when registering the CheckClass */
CheckType() : Check(myName()) {
CheckType() : Check(myName())
{
}
/** @brief This constructor is used when running checks. */
CheckType(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {
: Check(myName(), tokenizer, settings, errorLogger)
{
}
/** @brief Run checks against the normal token list */
void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) {
void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
{
// These are not "simplified" because casts can't be ignored
CheckType checkType(tokenizer, settings, errorLogger);
checkType.checkTooBigBitwiseShift();
@ -52,7 +55,8 @@ public:
}
/** @brief Run checks against the simplified token list */
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) {
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
{
(void)tokenizer;
(void)settings;
(void)errorLogger;
@ -76,18 +80,21 @@ private:
void integerOverflowError(const Token *tok, const ValueFlow::Value &value);
void signConversionError(const Token *tok);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const {
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const
{
CheckType c(0, settings, errorLogger);
c.tooBigBitwiseShiftError(0, 32, ValueFlow::Value(64));
c.integerOverflowError(0, ValueFlow::Value(1LL<<32));
c.signConversionError(0);
}
static std::string myName() {
static std::string myName()
{
return "Type";
}
std::string classInfo() const {
std::string classInfo() const
{
return "Type checks\n"
"- bitwise shift by too many bits (only enabled when --platform is used)\n"
"- signed integer overflow (only enabled when --platform is used)\n"

View File

@ -56,22 +56,26 @@ class UninitVar : public ExecutionPath {
public:
/** Startup constructor */
explicit UninitVar(Check *c, const SymbolDatabase* db, const Library *lib, bool isc)
: ExecutionPath(c, 0), symbolDatabase(db), library(lib), isC(isc), var(0), alloc(false), strncpy_(false), memset_nonzero(false) {
: ExecutionPath(c, 0), symbolDatabase(db), library(lib), isC(isc), var(0), alloc(false), strncpy_(false), memset_nonzero(false)
{
}
private:
/** Create a copy of this check */
ExecutionPath *copy() {
ExecutionPath *copy()
{
return new UninitVar(*this);
}
/** internal constructor for creating extra checks */
UninitVar(Check *c, const Variable* v, const SymbolDatabase* db, const Library *lib, bool isc)
: ExecutionPath(c, v->declarationId()), symbolDatabase(db), library(lib), isC(isc), var(v), alloc(false), strncpy_(false), memset_nonzero(false) {
: ExecutionPath(c, v->declarationId()), symbolDatabase(db), library(lib), isC(isc), var(v), alloc(false), strncpy_(false), memset_nonzero(false)
{
}
/** is other execution path equal? */
bool is_equal(const ExecutionPath *e) const {
bool is_equal(const ExecutionPath *e) const
{
const UninitVar *c = static_cast<const UninitVar *>(e);
return (var == c->var && alloc == c->alloc && strncpy_ == c->strncpy_ && memset_nonzero == c->memset_nonzero);
}
@ -97,7 +101,8 @@ private:
bool memset_nonzero;
/** allocating pointer. For example : p = malloc(10); */
static void alloc_pointer(std::list<ExecutionPath *> &checks, unsigned int varid) {
static void alloc_pointer(std::list<ExecutionPath *> &checks, unsigned int varid)
{
// loop through the checks and perform a allocation if the
// variable id matches
std::list<ExecutionPath *>::const_iterator it;
@ -114,7 +119,8 @@ private:
}
/** Initializing a pointer value. For example: *p = 0; */
static void init_pointer(std::list<ExecutionPath *> &checks, const Token *tok) {
static void init_pointer(std::list<ExecutionPath *> &checks, const Token *tok)
{
const unsigned int varid(tok->varId());
if (!varid)
return;
@ -139,7 +145,8 @@ private:
}
/** Deallocate a pointer. For example: free(p); */
static void dealloc_pointer(std::list<ExecutionPath *> &checks, const Token *tok) {
static void dealloc_pointer(std::list<ExecutionPath *> &checks, const Token *tok)
{
const unsigned int varid(tok->varId());
if (!varid)
return;
@ -170,7 +177,8 @@ private:
* \param tok1 the "p" token
* \param tok2 the "x" token
*/
static void pointer_assignment(std::list<ExecutionPath *> &checks, const Token *tok1, const Token *tok2) {
static void pointer_assignment(std::list<ExecutionPath *> &checks, const Token *tok1, const Token *tok2)
{
// Variable id for "left hand side" variable
const unsigned int varid1(tok1->varId());
if (varid1 == 0)
@ -204,7 +212,8 @@ private:
/** Initialize an array with strncpy. */
static void init_strncpy(std::list<ExecutionPath *> &checks, const Token *tok) {
static void init_strncpy(std::list<ExecutionPath *> &checks, const Token *tok)
{
const unsigned int varid(tok->varId());
if (!varid)
return;
@ -219,7 +228,8 @@ private:
}
/** Initialize an array with memset (not zero). */
static void init_memset_nonzero(std::list<ExecutionPath *> &checks, const Token *tok) {
static void init_memset_nonzero(std::list<ExecutionPath *> &checks, const Token *tok)
{
const unsigned int varid(tok->varId());
if (!varid)
return;
@ -242,7 +252,8 @@ private:
* @param mode specific behaviour
* @return if error is found, true is returned
*/
static bool use(std::list<ExecutionPath *> &checks, const Token *tok, const int mode) {
static bool use(std::list<ExecutionPath *> &checks, const Token *tok, const int mode)
{
const unsigned int varid(tok->varId());
if (varid == 0)
return false;
@ -306,7 +317,8 @@ private:
* @param tok variable token
* @return if error is found, true is returned
*/
static bool use(std::list<ExecutionPath *> &checks, const Token *tok) {
static bool use(std::list<ExecutionPath *> &checks, const Token *tok)
{
return use(checks, tok, 0);
}
@ -315,7 +327,8 @@ private:
* @param checks all available checks
* @param tok variable token
*/
static void use_array(std::list<ExecutionPath *> &checks, const Token *tok) {
static void use_array(std::list<ExecutionPath *> &checks, const Token *tok)
{
use(checks, tok, 1);
}
@ -324,7 +337,8 @@ private:
* @param checks all available checks
* @param tok variable token
*/
static void use_array_mem(std::list<ExecutionPath *> &checks, const Token *tok) {
static void use_array_mem(std::list<ExecutionPath *> &checks, const Token *tok)
{
use(checks, tok, 2);
}
@ -334,7 +348,8 @@ private:
* @param tok variable token
* @return if error is found, true is returned
*/
static bool use_pointer(std::list<ExecutionPath *> &checks, const Token *tok) {
static bool use_pointer(std::list<ExecutionPath *> &checks, const Token *tok)
{
return use(checks, tok, 3);
}
@ -344,7 +359,8 @@ private:
* @param tok variable token
* @return if error is found, true is returned
*/
static bool use_dead_pointer(std::list<ExecutionPath *> &checks, const Token *tok) {
static bool use_dead_pointer(std::list<ExecutionPath *> &checks, const Token *tok)
{
return use(checks, tok, 4);
}
@ -355,7 +371,8 @@ private:
* @param tok variable token
* @return if error is found, true is returned
*/
static bool use_array_or_pointer_data(std::list<ExecutionPath *> &checks, const Token *tok) {
static bool use_array_or_pointer_data(std::list<ExecutionPath *> &checks, const Token *tok)
{
return use(checks, tok, 5);
}
@ -364,7 +381,8 @@ private:
* @param tok2 start token of rhs
* @param checks the execution paths
*/
static void parserhs(const Token *tok2, std::list<ExecutionPath *> &checks) {
static void parserhs(const Token *tok2, std::list<ExecutionPath *> &checks)
{
// check variable usages in rhs/index
while (nullptr != (tok2 = tok2->next())) {
if (Token::Match(tok2, "[;)=]"))
@ -407,7 +425,8 @@ private:
}
/** parse tokens. @sa ExecutionPath::parse */
const Token *parse(const Token &tok, std::list<ExecutionPath *> &checks) const {
const Token *parse(const Token &tok, std::list<ExecutionPath *> &checks) const
{
// Variable declaration..
if (tok.varId() && Token::Match(&tok, "%var% [[;]")) {
const Variable* var2 = tok.variable();
@ -873,7 +892,8 @@ private:
return &tok;
}
bool parseCondition(const Token &tok, std::list<ExecutionPath *> &checks) {
bool parseCondition(const Token &tok, std::list<ExecutionPath *> &checks)
{
if (tok.varId() && Token::Match(&tok, "%var% <|<=|==|!=|)"))
use(checks, &tok);
@ -901,7 +921,8 @@ private:
return ExecutionPath::parseCondition(tok, checks);
}
void parseLoopBody(const Token *tok, std::list<ExecutionPath *> &checks) const {
void parseLoopBody(const Token *tok, std::list<ExecutionPath *> &checks) const
{
while (tok) {
if (tok->str() == "{" || tok->str() == "}" || tok->str() == "for")
return;
@ -920,7 +941,8 @@ private:
public:
static void analyseFunctions(const Token * const tokens, std::set<std::string> &func) {
static void analyseFunctions(const Token * const tokens, std::set<std::string> &func)
{
for (const Token *tok = tokens; tok; tok = tok->next()) {
if (tok->str() == "{") {
tok = tok->link();

View File

@ -37,16 +37,19 @@ class Variable;
class CPPCHECKLIB CheckUninitVar : public Check {
public:
/** @brief This constructor is used when registering the CheckUninitVar */
CheckUninitVar() : Check(myName()), testrunner(false) {
CheckUninitVar() : Check(myName()), testrunner(false)
{
}
/** @brief This constructor is used when running checks. */
CheckUninitVar(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger), testrunner(false) {
: Check(myName(), tokenizer, settings, errorLogger), testrunner(false)
{
}
/** @brief Run checks against the simplified token list */
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) {
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
{
CheckUninitVar checkUninitVar(tokenizer, settings, errorLogger);
checkUninitVar.executionPaths();
checkUninitVar.check();
@ -99,7 +102,8 @@ public:
bool testrunner;
private:
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const {
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const
{
CheckUninitVar c(0, settings, errorLogger);
// error
@ -110,11 +114,13 @@ private:
c.deadPointerError(0,0);
}
static std::string myName() {
static std::string myName()
{
return "Uninitialized variables";
}
std::string classInfo() const {
std::string classInfo() const
{
return "Uninitialized variables\n"
"- using uninitialized local variables\n"
"- using allocated data before it has been initialized\n"

View File

@ -32,12 +32,14 @@
class CPPCHECKLIB CheckUnusedFunctions : public Check {
public:
/** @brief This constructor is used when registering the CheckUnusedFunctions */
CheckUnusedFunctions() : Check(myName()) {
CheckUnusedFunctions() : Check(myName())
{
}
/** @brief This constructor is used when running checks. */
CheckUnusedFunctions(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {
: Check(myName(), tokenizer, settings, errorLogger)
{
}
// Parse current tokens and determine..
@ -52,7 +54,8 @@ public:
private:
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const {
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const
{
CheckUnusedFunctions c(0, settings, errorLogger);
c.unusedFunctionError(errorLogger, "", 0, "funcName");
}
@ -69,17 +72,20 @@ private:
*/
void runSimplifiedChecks(const Tokenizer *, const Settings *, ErrorLogger *) {}
static std::string myName() {
static std::string myName()
{
return "Unused functions";
}
std::string classInfo() const {
std::string classInfo() const
{
return "Check for functions that are never called\n";
}
class FunctionUsage {
public:
FunctionUsage() : lineNumber(0), usedSameFile(false), usedOtherFile(false) {
FunctionUsage() : lineNumber(0), usedSameFile(false), usedOtherFile(false)
{
}
std::string filename;

View File

@ -52,18 +52,21 @@ public:
_read(read),
_write(write),
_modified(modified),
_allocateMemory(allocateMemory) {
_allocateMemory(allocateMemory)
{
}
/** variable is used.. set both read+write */
void use(std::list<std::set<unsigned int> > & varReadInScope) {
void use(std::list<std::set<unsigned int> > & varReadInScope)
{
varReadInScope.back().insert(_var->declarationId());
_read = true;
_write = true;
}
/** is variable unused? */
bool unused() const {
bool unused() const
{
return (_read == false && _write == false);
}
@ -84,11 +87,13 @@ public:
ScopeGuard(Variables & guarded,
bool insideLoop)
:_guarded(guarded),
_insideLoop(insideLoop) {
_insideLoop(insideLoop)
{
_guarded.enterScope();
}
~ScopeGuard() {
~ScopeGuard()
{
_guarded.leaveScope(_insideLoop);
}
@ -97,10 +102,12 @@ public:
bool _insideLoop;
};
void clear() {
void clear()
{
_varUsage.clear();
}
const std::map<unsigned int, VariableUsage> &varUsage() const {
const std::map<unsigned int, VariableUsage> &varUsage() const
{
return _varUsage;
}
void addVar(const Variable *var, VariableType type, bool write_);
@ -115,14 +122,16 @@ public:
void modified(unsigned int varid, const Token* tok);
VariableUsage *find(unsigned int varid);
void alias(unsigned int varid1, unsigned int varid2, bool replace);
void erase(unsigned int varid) {
void erase(unsigned int varid)
{
_varUsage.erase(varid);
}
void eraseAliases(unsigned int varid);
void eraseAll(unsigned int varid);
void clearAliases(unsigned int varid);
ScopeGuard newScope(bool insideLoop) {
ScopeGuard newScope(bool insideLoop)
{
return ScopeGuard(*this, insideLoop);
}

View File

@ -39,16 +39,19 @@ class Variables;
class CPPCHECKLIB CheckUnusedVar : public Check {
public:
/** @brief This constructor is used when registering the CheckClass */
CheckUnusedVar() : Check(myName()) {
CheckUnusedVar() : Check(myName())
{
}
/** @brief This constructor is used when running checks. */
CheckUnusedVar(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {
: Check(myName(), tokenizer, settings, errorLogger)
{
}
/** @brief Run checks against the normal token list */
void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) {
void runChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
{
CheckUnusedVar checkUnusedVar(tokenizer, settings, errorLogger);
// Coding style checks
@ -57,7 +60,8 @@ public:
}
/** @brief Run checks against the simplified token list */
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) {
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
{
(void)tokenizer;
(void)settings;
(void)errorLogger;
@ -82,7 +86,8 @@ private:
void unreadVariableError(const Token *tok, const std::string &varname);
void unassignedVariableError(const Token *tok, const std::string &varname);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const {
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const
{
CheckUnusedVar c(0, settings, errorLogger);
// style/warning
@ -93,11 +98,13 @@ private:
c.unusedStructMemberError(0, "structname", "variable");
}
static std::string myName() {
static std::string myName()
{
return "UnusedVar";
}
std::string classInfo() const {
std::string classInfo() const
{
return "UnusedVar checks\n"
// style

View File

@ -34,14 +34,17 @@
class CPPCHECKLIB CheckVaarg : public Check {
public:
CheckVaarg() : Check(myName()) {
CheckVaarg() : Check(myName())
{
}
CheckVaarg(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {
: Check(myName(), tokenizer, settings, errorLogger)
{
}
virtual void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) {
virtual void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
{
CheckVaarg check(tokenizer, settings, errorLogger);
check.va_start_argument();
check.va_list_usage();
@ -57,7 +60,8 @@ private:
void va_list_usedBeforeStartedError(const Token *tok, const std::string& varname);
void va_start_subsequentCallsError(const Token *tok, const std::string& varname);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const {
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const
{
CheckVaarg c(0, settings, errorLogger);
c.wrongParameterTo_va_start_error(0, "arg1", "arg2");
c.referenceAs_va_start_error(0, "arg1");
@ -66,11 +70,13 @@ private:
c.va_start_subsequentCallsError(0, "vl");
}
static std::string myName() {
static std::string myName()
{
return "Vaarg";
}
std::string classInfo() const {
std::string classInfo() const
{
return "Check for misusage of variable argument lists:\n"
"- Wrong parameter passed to va_start()\n"
"- Reference passed to va_start()\n"

View File

@ -107,7 +107,8 @@ public:
/**
* @brief Terminate checking. The checking will be terminated as soon as possible.
*/
void terminate() {
void terminate()
{
_settings.terminate();
}
@ -125,7 +126,8 @@ public:
void tooManyConfigsError(const std::string &file, const std::size_t numberOfConfigurations);
void purgedConfigurationMessage(const std::string &file, const std::string& configuration);
void dontSimplify() {
void dontSimplify()
{
_simplify = false;
}

View File

@ -34,11 +34,13 @@ const // this is a const object...
class {
public:
template<class T> // convertible to any type
operator T*() const { // of null non-member
operator T*() const // of null non-member
{
return 0; // pointer...
}
template<class C, class T> // or any type of null
operator T C::*() const { // member pointer...
operator T C::*() const // member pointer...
{
return 0;
}
private:

View File

@ -100,7 +100,8 @@ public:
debug
};
static std::string toString(SeverityType severity) {
static std::string toString(SeverityType severity)
{
switch (severity) {
case none:
return "";
@ -121,7 +122,8 @@ public:
};
throw InternalError(NULL, "Unknown severity");
}
static SeverityType fromString(const std::string &severity) {
static SeverityType fromString(const std::string &severity)
{
if (severity.empty())
return none;
if (severity == "none")
@ -164,11 +166,13 @@ public:
class CPPCHECKLIB FileLocation {
public:
FileLocation()
: line(0) {
: line(0)
{
}
FileLocation(const std::string &file, unsigned int aline)
: line(aline), _file(file) {
: line(aline), _file(file)
{
}
FileLocation(const Token* tok, const TokenList* list);
@ -236,12 +240,14 @@ public:
void setmsg(const std::string &msg);
/** Short message (single line short message) */
const std::string &shortMessage() const {
const std::string &shortMessage() const
{
return _shortMessage;
}
/** Verbose message (may be the same as the short message) */
const std::string &verboseMessage() const {
const std::string &verboseMessage() const
{
return _verboseMessage;
}
@ -287,7 +293,8 @@ public:
* @param stage for example preprocess / tokenize / simplify / check
* @param value progress value (0-100)
*/
virtual void reportProgress(const std::string &filename, const char stage[], const std::size_t value) {
virtual void reportProgress(const std::string &filename, const char stage[], const std::size_t value)
{
(void)filename;
(void)stage;
(void)value;
@ -297,7 +304,8 @@ public:
* Output information messages.
* @param msg Location and other information about the found error.
*/
virtual void reportInfo(const ErrorLogger::ErrorMessage &msg) {
virtual void reportInfo(const ErrorLogger::ErrorMessage &msg)
{
reportErr(msg);
}

View File

@ -44,10 +44,12 @@ protected:
virtual bool is_equal(const ExecutionPath *) const = 0;
public:
ExecutionPath(Check *c, unsigned int id) : owner(c), numberOfIf(0), varId(id) {
ExecutionPath(Check *c, unsigned int id) : owner(c), numberOfIf(0), varId(id)
{
}
virtual ~ExecutionPath() {
virtual ~ExecutionPath()
{
}
/** Implement this in each derived class. This function must create a copy of the current instance */
@ -65,7 +67,8 @@ public:
* bail out all execution paths
* @param checks the execution paths to bail out on
**/
static void bailOut(std::list<ExecutionPath *> &checks) {
static void bailOut(std::list<ExecutionPath *> &checks)
{
while (!checks.empty()) {
delete checks.back();
checks.pop_back();
@ -77,7 +80,8 @@ public:
* @param checks the execution paths to bail out on
* @param varid the specific variable id
**/
static void bailOutVar(std::list<ExecutionPath *> &checks, const unsigned int varid) {
static void bailOutVar(std::list<ExecutionPath *> &checks, const unsigned int varid)
{
if (varid == 0)
return;
@ -113,16 +117,19 @@ public:
* @param tok the first token in the loop body (the token after the {)
* @param checks The execution paths
*/
virtual void parseLoopBody(const Token *tok, std::list<ExecutionPath *> &checks) const {
virtual void parseLoopBody(const Token *tok, std::list<ExecutionPath *> &checks) const
{
(void)tok;
(void)checks;
}
/** going out of scope - all execution paths end */
virtual void end(const std::list<ExecutionPath *> & /*checks*/, const Token * /*tok*/) const {
virtual void end(const std::list<ExecutionPath *> & /*checks*/, const Token * /*tok*/) const
{
}
bool operator==(const ExecutionPath &e) const {
bool operator==(const ExecutionPath &e) const
{
return bool(varId == e.varId && is_equal(&e));
}

View File

@ -64,58 +64,70 @@ public:
bool loadxmldata(const char xmldata[], std::size_t len);
/** get allocation id for function by name */
int alloc(const char name[]) const {
int alloc(const char name[]) const
{
return getid(_alloc, name);
}
/** get allocation id for function */
int alloc(const Token *tok) const {
int alloc(const Token *tok) const
{
return tok->function() ? 0 : getid(_alloc, tok->str());
}
/** get deallocation id for function */
int dealloc(const Token *tok) const {
int dealloc(const Token *tok) const
{
return tok->function() ? 0 : getid(_dealloc, tok->str());
}
/** get deallocation id for function by name */
int dealloc(const char name[]) const {
int dealloc(const char name[]) const
{
return getid(_dealloc, name);
}
/** set allocation id for function */
void setalloc(const std::string &functionname, int id) {
void setalloc(const std::string &functionname, int id)
{
_alloc[functionname] = id;
}
void setdealloc(const std::string &functionname, int id) {
void setdealloc(const std::string &functionname, int id)
{
_dealloc[functionname] = id;
}
/** add noreturn function setting */
void setnoreturn(const std::string& funcname, bool noreturn) {
void setnoreturn(const std::string& funcname, bool noreturn)
{
_noreturn[funcname] = noreturn;
}
/** is allocation type memory? */
static bool ismemory(int id) {
static bool ismemory(int id)
{
return ((id > 0) && ((id & 1) == 0));
}
/** is allocation type resource? */
static bool isresource(int id) {
static bool isresource(int id)
{
return ((id > 0) && ((id & 1) == 1));
}
bool formatstr_function(const std::string& funcname) const {
bool formatstr_function(const std::string& funcname) const
{
return _formatstr.find(funcname) != _formatstr.end();
}
bool formatstr_scan(const std::string& funcname) const {
bool formatstr_scan(const std::string& funcname) const
{
return _formatstr.at(funcname).first;
}
bool formatstr_secure(const std::string& funcname) const {
bool formatstr_secure(const std::string& funcname) const
{
return _formatstr.at(funcname).second;
}
@ -125,12 +137,14 @@ public:
std::set<std::string> functionpure;
std::set<std::string> useretval;
bool isnoreturn(const std::string &name) const {
bool isnoreturn(const std::string &name) const
{
std::map<std::string, bool>::const_iterator it = _noreturn.find(name);
return (it != _noreturn.end() && it->second);
}
bool isnotnoreturn(const std::string &name) const {
bool isnotnoreturn(const std::string &name) const
{
std::map<std::string, bool>::const_iterator it = _noreturn.find(name);
return (it != _noreturn.end() && !it->second);
}
@ -144,7 +158,8 @@ public:
notnull(false),
notuninit(false),
formatstr(false),
strz(false) {
strz(false)
{
}
bool notbool;
@ -168,39 +183,46 @@ public:
// function name, argument nr => argument data
std::map<std::string, std::map<int, ArgumentChecks> > argumentChecks;
bool isboolargbad(const std::string &functionName, int argnr) const {
bool isboolargbad(const std::string &functionName, int argnr) const
{
const ArgumentChecks *arg = getarg(functionName, argnr);
return arg && arg->notbool;
}
bool isnullargbad(const std::string &functionName, int argnr) const {
bool isnullargbad(const std::string &functionName, int argnr) const
{
const ArgumentChecks *arg = getarg(functionName, argnr);
return arg && arg->notnull;
}
bool isuninitargbad(const std::string &functionName, int argnr) const {
bool isuninitargbad(const std::string &functionName, int argnr) const
{
const ArgumentChecks *arg = getarg(functionName, argnr);
return arg && arg->notuninit;
}
bool isargformatstr(const std::string &functionName, int argnr) const {
bool isargformatstr(const std::string &functionName, int argnr) const
{
const ArgumentChecks *arg = getarg(functionName, argnr);
return arg && arg->formatstr;
}
bool isargstrz(const std::string &functionName, int argnr) const {
bool isargstrz(const std::string &functionName, int argnr) const
{
const ArgumentChecks *arg = getarg(functionName, argnr);
return arg && arg->strz;
}
bool isargvalid(const std::string &functionName, int argnr, const MathLib::bigint argvalue) const;
const std::string& validarg(const std::string &functionName, int argnr) const {
const std::string& validarg(const std::string &functionName, int argnr) const
{
const ArgumentChecks *arg = getarg(functionName, argnr);
return arg ? arg->valid : emptyString;
}
bool hasminsize(const std::string &functionName) const {
bool hasminsize(const std::string &functionName) const
{
std::map<std::string, std::map<int, ArgumentChecks> >::const_iterator it1;
it1 = argumentChecks.find(functionName);
if (it1 == argumentChecks.end())
@ -213,39 +235,47 @@ public:
return false;
}
const std::list<ArgumentChecks::MinSize> *argminsizes(const std::string &functionName, int argnr) const {
const std::list<ArgumentChecks::MinSize> *argminsizes(const std::string &functionName, int argnr) const
{
const ArgumentChecks *arg = getarg(functionName, argnr);
return arg ? &arg->minsizes : nullptr;
}
bool markupFile(const std::string &path) const {
bool markupFile(const std::string &path) const
{
return _markupExtensions.find(Path::getFilenameExtensionInLowerCase(path)) != _markupExtensions.end();
}
bool processMarkupAfterCode(const std::string &path) const {
bool processMarkupAfterCode(const std::string &path) const
{
const std::map<std::string, bool>::const_iterator it = _processAfterCode.find(Path::getFilenameExtensionInLowerCase(path));
return (it == _processAfterCode.end() || it->second);
}
const std::set<std::string> &markupExtensions() const {
const std::set<std::string> &markupExtensions() const
{
return _markupExtensions;
}
bool reportErrors(const std::string &path) const {
bool reportErrors(const std::string &path) const
{
const std::map<std::string, bool>::const_iterator it = _reporterrors.find(Path::getFilenameExtensionInLowerCase(path));
return (it == _reporterrors.end() || it->second);
}
bool ignorefunction(const std::string &function) const {
bool ignorefunction(const std::string &function) const
{
return (_ignorefunction.find(function) != _ignorefunction.end());
}
bool isexecutableblock(const std::string &file, const std::string &token) const {
bool isexecutableblock(const std::string &file, const std::string &token) const
{
const std::map<std::string, CodeBlock>::const_iterator it = _executableblocks.find(Path::getFilenameExtensionInLowerCase(file));
return (it != _executableblocks.end() && it->second.isBlock(token));
}
int blockstartoffset(const std::string &file) const {
int blockstartoffset(const std::string &file) const
{
int offset = -1;
const std::map<std::string, CodeBlock>::const_iterator map_it
= _executableblocks.find(Path::getFilenameExtensionInLowerCase(file));
@ -256,7 +286,8 @@ public:
return offset;
}
const std::string& blockstart(const std::string &file) const {
const std::string& blockstart(const std::string &file) const
{
const std::map<std::string, CodeBlock>::const_iterator map_it
= _executableblocks.find(Path::getFilenameExtensionInLowerCase(file));
@ -266,7 +297,8 @@ public:
return emptyString;
}
const std::string& blockend(const std::string &file) const {
const std::string& blockend(const std::string &file) const
{
const std::map<std::string, CodeBlock>::const_iterator map_it
= _executableblocks.find(Path::getFilenameExtensionInLowerCase(file));
@ -276,39 +308,46 @@ public:
return emptyString;
}
bool iskeyword(const std::string &file, const std::string &keyword) const {
bool iskeyword(const std::string &file, const std::string &keyword) const
{
const std::map<std::string, std::set<std::string> >::const_iterator it =
_keywords.find(Path::getFilenameExtensionInLowerCase(file));
return (it != _keywords.end() && it->second.count(keyword));
}
bool isexporter(const std::string &prefix) const {
bool isexporter(const std::string &prefix) const
{
return _exporters.find(prefix) != _exporters.end();
}
bool isexportedprefix(const std::string &prefix, const std::string &token) const {
bool isexportedprefix(const std::string &prefix, const std::string &token) const
{
const std::map<std::string, ExportedFunctions>::const_iterator it = _exporters.find(prefix);
return (it != _exporters.end() && it->second.isPrefix(token));
}
bool isexportedsuffix(const std::string &prefix, const std::string &token) const {
bool isexportedsuffix(const std::string &prefix, const std::string &token) const
{
const std::map<std::string, ExportedFunctions>::const_iterator it = _exporters.find(prefix);
return (it != _exporters.end() && it->second.isSuffix(token));
}
bool isimporter(const std::string& file, const std::string &importer) const {
bool isimporter(const std::string& file, const std::string &importer) const
{
const std::map<std::string, std::set<std::string> >::const_iterator it =
_importers.find(Path::getFilenameExtensionInLowerCase(file));
return (it != _importers.end() && it->second.count(importer) > 0);
}
bool isreflection(const std::string &token) const {
bool isreflection(const std::string &token) const
{
const std::map<std::string,int>::const_iterator it
= _reflection.find(token);
return it != _reflection.end();
}
int reflectionArgument(const std::string &token) const {
int reflectionArgument(const std::string &token) const
{
int argIndex = -1;
const std::map<std::string,int>::const_iterator it
= _reflection.find(token);
@ -337,9 +376,11 @@ public:
, _long(false)
, _pointer(false)
, _ptr_ptr(false)
, _const_ptr(false) {
, _const_ptr(false)
{
}
bool operator == (const PlatformType & type) const {
bool operator == (const PlatformType & type) const
{
return (_type == type._type &&
_signed == type._signed &&
_unsigned == type._unsigned &&
@ -348,7 +389,8 @@ public:
_ptr_ptr == type._ptr_ptr &&
_const_ptr == type._const_ptr);
}
bool operator != (const PlatformType & type) const {
bool operator != (const PlatformType & type) const
{
return !(*this == type);
}
std::string _type;
@ -361,14 +403,16 @@ public:
};
struct Platform {
const PlatformType *platform_type(const std::string &name) const {
const PlatformType *platform_type(const std::string &name) const
{
const std::map<std::string, struct PlatformType>::const_iterator it = _platform_types.find(name);
return (it != _platform_types.end()) ? &(it->second) : nullptr;
}
std::map<std::string, PlatformType> _platform_types;
};
const PlatformType *platform_type(const std::string &name, const std::string & platform) const {
const PlatformType *platform_type(const std::string &name, const std::string & platform) const
{
const std::map<std::string, Platform>::const_iterator it = platforms.find(platform);
if (it != platforms.end()) {
@ -386,16 +430,20 @@ public:
private:
class ExportedFunctions {
public:
void addPrefix(const std::string& prefix) {
void addPrefix(const std::string& prefix)
{
_prefixes.insert(prefix);
}
void addSuffix(const std::string& suffix) {
void addSuffix(const std::string& suffix)
{
_suffixes.insert(suffix);
}
bool isPrefix(const std::string& prefix) const {
bool isPrefix(const std::string& prefix) const
{
return (_prefixes.find(prefix) != _prefixes.end());
}
bool isSuffix(const std::string& suffix) const {
bool isSuffix(const std::string& suffix) const
{
return (_suffixes.find(suffix) != _suffixes.end());
}
@ -407,28 +455,36 @@ private:
public:
CodeBlock() : _offset(0) {}
void setStart(const std::string& s) {
void setStart(const std::string& s)
{
_start = s;
}
void setEnd(const std::string& e) {
void setEnd(const std::string& e)
{
_end = e;
}
void setOffset(const int o) {
void setOffset(const int o)
{
_offset = o;
}
void addBlock(const std::string& blockName) {
void addBlock(const std::string& blockName)
{
_blocks.insert(blockName);
}
const std::string& start() const {
const std::string& start() const
{
return _start;
}
const std::string& end() const {
const std::string& end() const
{
return _end;
}
int offset() const {
int offset() const
{
return _offset;
}
bool isBlock(const std::string& blockName) const {
bool isBlock(const std::string& blockName) const
{
return _blocks.find(blockName) != _blocks.end();
}
@ -459,7 +515,8 @@ private:
const ArgumentChecks * getarg(const std::string &functionName, int argnr) const;
static int getid(const std::map<std::string,int> &data, const std::string &name) {
static int getid(const std::map<std::string,int> &data, const std::string &name)
{
const std::map<std::string,int>::const_iterator it = data.find(name);
return (it == data.end()) ? 0 : it->second;
}

View File

@ -39,7 +39,8 @@ public:
static bigint toLongNumber(const std::string & str);
static biguint toULongNumber(const std::string & str);
template<class T> static std::string toString(T value) {
template<class T> static std::string toString(T value)
{
std::ostringstream result;
result << value;
return result.str();

View File

@ -117,7 +117,8 @@ public:
* @param filename filename to check. path info is optional
* @return true if the file extension indicates it should be checked
*/
static bool acceptFile(const std::string &filename) {
static bool acceptFile(const std::string &filename)
{
const std::set<std::string> extra;
return acceptFile(filename, extra);
}

View File

@ -2542,7 +2542,8 @@ private:
/** @brief expand inner macro */
std::vector<std::string> expandInnerMacros(const std::vector<std::string> &params1,
const std::map<std::string, PreprocessorMacro *> &macros) const {
const std::map<std::string, PreprocessorMacro *> &macros) const
{
std::string innerMacroName;
// Is there an inner macro..
@ -2600,7 +2601,8 @@ public:
* e.g. "A(x) foo(x);"
*/
explicit PreprocessorMacro(const std::string &macro)
: _macro(macro), _prefix("__cppcheck__") {
: _macro(macro), _prefix("__cppcheck__")
{
tokenizer.setSettings(&settings);
// Tokenize the macro to make it easier to handle
@ -2641,27 +2643,32 @@ public:
}
/** return tokens of this macro */
const Token *tokens() const {
const Token *tokens() const
{
return tokenizer.tokens();
}
/** read parameters of this macro */
const std::vector<std::string> &params() const {
const std::vector<std::string> &params() const
{
return _params;
}
/** check if this is macro has a variable number of parameters */
bool variadic() const {
bool variadic() const
{
return _variadic;
}
/** Check if this macro has parentheses but no parameters */
bool nopar() const {
bool nopar() const
{
return _nopar;
}
/** name of macro */
const std::string &name() const {
const std::string &name() const
{
return _name;
}
@ -2672,7 +2679,8 @@ public:
* @param macrocode output string
* @return true if the expanding was successful
*/
bool code(const std::vector<std::string> &params2, const std::map<std::string, PreprocessorMacro *> &macros, std::string &macrocode) const {
bool code(const std::vector<std::string> &params2, const std::map<std::string, PreprocessorMacro *> &macros, std::string &macrocode) const
{
if (_nopar || (_params.empty() && _variadic)) {
macrocode = _macro.substr(1 + _macro.find(")"));
if (macrocode.empty())

View File

@ -247,7 +247,8 @@ public:
*/
std::string handleIncludes(const std::string &code, const std::string &filePath, const std::list<std::string> &includePaths, std::map<std::string,std::string> &defs, std::set<std::string> &pragmaOnce, std::list<std::string> includes);
void setFile0(const std::string &f) {
void setFile0(const std::string &f)
{
file0 = f;
}

View File

@ -90,12 +90,14 @@ public:
bool _verbose;
/** @brief Request termination of checking */
void terminate() {
void terminate()
{
_terminate = true;
}
/** @brief termination requested? */
bool terminated() const {
bool terminated() const
{
return _terminate;
}
@ -153,7 +155,8 @@ public:
* @return true if the check is enabled.
*/
template<typename T>
bool isEnabled(T&& str) const {
bool isEnabled(T&& str) const
{
return bool(_enabled.find(str) != _enabled.end());
}
@ -168,7 +171,8 @@ public:
/**
* @brief Disables all severities, except from error.
*/
void clearEnabled() {
void clearEnabled()
{
_enabled.clear();
}
@ -210,7 +214,8 @@ public:
Rule()
: tokenlist("simple") // use simple tokenlist
, id("rule") // default id
, severity("style") { // default severity
, severity("style") // default severity
{
}
std::string tokenlist;
@ -269,7 +274,8 @@ public:
* @brief Returns true if platform type is Windows
* @return true if Windows platform type.
*/
bool isWindowsPlatform() const {
bool isWindowsPlatform() const
{
return platformType == Win32A ||
platformType == Win32W ||
platformType == Win64;
@ -279,7 +285,8 @@ public:
* @brief return true if a file is to be excluded from configuration checking
* @return true for the file to be excluded.
*/
bool configurationExcluded(const std::string &file) const {
bool configurationExcluded(const std::string &file) const
{
for (std::set<std::string>::const_iterator i=configExcludePaths.begin(); i!=configExcludePaths.end(); ++i) {
if (file.length()>=i->length() && file.compare(0,i->length(),*i)==0) {
return true;

View File

@ -121,7 +121,8 @@ public:
struct SuppressionEntry {
SuppressionEntry(const std::string &aid, const std::string &afile, unsigned int aline)
: id(aid), file(afile), line(aline) {
: id(aid), file(afile), line(aline)
{
}
std::string id;

View File

@ -68,7 +68,8 @@ public:
class BaseInfo {
public:
BaseInfo() :
type(NULL), nameTok(NULL), access(Public), isVirtual(false) {
type(NULL), nameTok(NULL), access(Public), isVirtual(false)
{
}
std::string name;
@ -77,14 +78,16 @@ public:
AccessControl access; // public/protected/private
bool isVirtual;
// allow ordering within containers
bool operator<(const BaseInfo& rhs) const {
bool operator<(const BaseInfo& rhs) const
{
return this->type < rhs.type;
}
};
struct FriendInfo {
FriendInfo() :
nameStart(NULL), nameEnd(NULL), type(NULL) {
nameStart(NULL), nameEnd(NULL), type(NULL)
{
}
const Token* nameStart;
@ -100,10 +103,12 @@ public:
classDef(classDef_),
classScope(classScope_),
enclosingScope(enclosingScope_),
needInitialization(Unknown) {
needInitialization(Unknown)
{
}
const std::string& name() const {
const std::string& name() const
{
const Token* next = classDef->next();
if (next->isName())
return next->str();
@ -147,7 +152,8 @@ class CPPCHECKLIB Variable {
* @param flag_ flag to get state of
* @return true if flag set or false in flag not set
*/
bool getFlag(int flag_) const {
bool getFlag(int flag_) const
{
return bool((_flags & flag_) != 0);
}
@ -156,7 +162,8 @@ class CPPCHECKLIB Variable {
* @param flag_ flag to set state
* @param state_ new state of flag
*/
void setFlag(int flag_, bool state_) {
void setFlag(int flag_, bool state_)
{
_flags = state_ ? _flags | flag_ : _flags & ~flag_;
}
@ -179,7 +186,8 @@ public:
_access(access_),
_flags(0),
_type(type_),
_scope(scope_) {
_scope(scope_)
{
evaluate();
}
@ -187,7 +195,8 @@ public:
* Get name token.
* @return name token
*/
const Token *nameToken() const {
const Token *nameToken() const
{
return _name;
}
@ -199,7 +208,8 @@ public:
* type start token ^
* @return type start token
*/
const Token *typeStartToken() const {
const Token *typeStartToken() const
{
return _start;
}
@ -211,7 +221,8 @@ public:
* type end token ^
* @return type end token
*/
const Token *typeEndToken() const {
const Token *typeEndToken() const
{
return _end;
}
@ -228,7 +239,8 @@ public:
* Get name string.
* @return name string
*/
const std::string &name() const {
const std::string &name() const
{
// name may not exist for function arguments
if (_name)
return _name->str();
@ -240,7 +252,8 @@ public:
* Get declaration ID (varId used for variable in its declaration).
* @return declaration ID
*/
unsigned int declarationId() const {
unsigned int declarationId() const
{
// name may not exist for function arguments
if (_name)
return _name->varId();
@ -252,7 +265,8 @@ public:
* Get index of variable in declared order.
* @return variable index
*/
std::size_t index() const {
std::size_t index() const
{
return _index;
}
@ -260,7 +274,8 @@ public:
* Is variable public.
* @return true if public, false if not
*/
bool isPublic() const {
bool isPublic() const
{
return _access == Public;
}
@ -268,7 +283,8 @@ public:
* Is variable protected.
* @return true if protected, false if not
*/
bool isProtected() const {
bool isProtected() const
{
return _access == Protected;
}
@ -276,7 +292,8 @@ public:
* Is variable private.
* @return true if private, false if not
*/
bool isPrivate() const {
bool isPrivate() const
{
return _access == Private;
}
@ -284,7 +301,8 @@ public:
* Is variable global.
* @return true if global, false if not
*/
bool isGlobal() const {
bool isGlobal() const
{
return _access == Global;
}
@ -292,7 +310,8 @@ public:
* Is variable in a namespace.
* @return true if in a namespace, false if not
*/
bool isNamespace() const {
bool isNamespace() const
{
return _access == Namespace;
}
@ -300,7 +319,8 @@ public:
* Is variable a function argument.
* @return true if a function argument, false if not
*/
bool isArgument() const {
bool isArgument() const
{
return _access == Argument;
}
@ -308,7 +328,8 @@ public:
* Is variable local.
* @return true if local, false if not
*/
bool isLocal() const {
bool isLocal() const
{
return (_access == Local) && !isExtern();
}
@ -316,7 +337,8 @@ public:
* Is variable mutable.
* @return true if mutable, false if not
*/
bool isMutable() const {
bool isMutable() const
{
return getFlag(fIsMutable);
}
@ -324,7 +346,8 @@ public:
* Is variable static.
* @return true if static, false if not
*/
bool isStatic() const {
bool isStatic() const
{
return getFlag(fIsStatic);
}
@ -332,7 +355,8 @@ public:
* Is variable extern.
* @return true if extern, false if not
*/
bool isExtern() const {
bool isExtern() const
{
return getFlag(fIsExtern);
}
@ -340,7 +364,8 @@ public:
* Is variable const.
* @return true if const, false if not
*/
bool isConst() const {
bool isConst() const
{
return getFlag(fIsConst);
}
@ -348,7 +373,8 @@ public:
* Is variable a throw type.
* @return true if throw type, false if not
*/
bool isThrow() const {
bool isThrow() const
{
return _access == Throw;
}
@ -356,7 +382,8 @@ public:
* Is variable a user defined (or unknown) type.
* @return true if user defined type, false if not
*/
bool isClass() const {
bool isClass() const
{
return getFlag(fIsClass);
}
@ -364,7 +391,8 @@ public:
* Is variable an array.
* @return true if array, false if not
*/
bool isArray() const {
bool isArray() const
{
return getFlag(fIsArray);
}
@ -372,7 +400,8 @@ public:
* Is pointer variable.
* @return true if pointer, false otherwise
*/
bool isPointer() const {
bool isPointer() const
{
return getFlag(fIsPointer);
}
@ -380,7 +409,8 @@ public:
* Is array or pointer variable.
* @return true if pointer or array, false otherwise
*/
bool isArrayOrPointer() const {
bool isArrayOrPointer() const
{
return getFlag(fIsArray) || getFlag(fIsPointer);
}
@ -388,7 +418,8 @@ public:
* Is reference variable.
* @return true if reference, false otherwise
*/
bool isReference() const {
bool isReference() const
{
return getFlag(fIsReference);
}
@ -396,7 +427,8 @@ public:
* Is reference variable.
* @return true if reference, false otherwise
*/
bool isRValueReference() const {
bool isRValueReference() const
{
return getFlag(fIsRValueRef);
}
@ -404,7 +436,8 @@ public:
* Does variable have a default value.
* @return true if has a default falue, false if not
*/
bool hasDefault() const {
bool hasDefault() const
{
return getFlag(fHasDefault);
}
@ -412,7 +445,8 @@ public:
* Get Type pointer of known type.
* @return pointer to type if known, NULL if not known
*/
const Type *type() const {
const Type *type() const
{
return _type;
}
@ -420,7 +454,8 @@ public:
* Get Scope pointer of known type.
* @return pointer to type scope if known, NULL if not known
*/
const Scope *typeScope() const {
const Scope *typeScope() const
{
return _type ? _type->classScope : 0;
}
@ -428,7 +463,8 @@ public:
* Get Scope pointer of enclosing scope.
* @return pointer to enclosing scope
*/
const Scope *scope() const {
const Scope *scope() const
{
return _scope;
}
@ -436,7 +472,8 @@ public:
* Get array dimensions.
* @return array dimensions vector
*/
const std::vector<Dimension> &dimensions() const {
const std::vector<Dimension> &dimensions() const
{
return _dimensions;
}
@ -444,7 +481,8 @@ public:
* Get array dimension length.
* @return length of dimension
*/
MathLib::bigint dimension(std::size_t index_) const {
MathLib::bigint dimension(std::size_t index_) const
{
return _dimensions[index_].num;
}
@ -452,7 +490,8 @@ public:
* Get array dimension known.
* @return length of dimension known
*/
bool dimensionKnown(std::size_t index_) const {
bool dimensionKnown(std::size_t index_) const
{
return _dimensions[index_].known;
}
@ -464,7 +503,8 @@ public:
* sVar->isStlType() == true
* @return true if it is an stl type and its type matches any of the types in 'stlTypes'
*/
bool isStlType() const {
bool isStlType() const
{
return getFlag(fIsStlType);
}
@ -476,7 +516,8 @@ public:
* sVar->isStlType() == true
* @return true if it is an stl type and its type matches any of the types in 'stlTypes'
*/
bool isStlStringType() const {
bool isStlStringType() const
{
return getFlag(fIsStlString);
}
@ -491,7 +532,8 @@ public:
* @return true if it is an stl type and its type matches any of the types in 'stlTypes'
*/
template <std::size_t array_length>
bool isStlType(const char* const(&stlTypes)[array_length]) const {
bool isStlType(const char* const(&stlTypes)[array_length]) const
{
return isStlType() && std::binary_search(stlTypes, stlTypes + array_length, _start->strAt(2));
}
@ -499,7 +541,8 @@ public:
* Determine whether it's a floating number type
* @return true if the type is known and it's a floating type (float, double and long double) or a pointer/array to it
*/
bool isFloatingType() const {
bool isFloatingType() const
{
return getFlag(fIsFloatType);
}
@ -507,7 +550,8 @@ public:
* Determine whether it's an integral number type
* @return true if the type is known and it's an integral type (bool, char, short, int, long long and their unsigned counter parts) or a pointer/array to it
*/
bool isIntegralType() const {
bool isIntegralType() const
{
return getFlag(fIsIntType);
}
@ -520,7 +564,8 @@ private:
* Set Type pointer to known type.
* @param t type
*/
void type(const Type * t) {
void type(const Type * t)
{
_type = t;
}
@ -585,52 +630,65 @@ public:
isThrow(false),
isOperator(false),
noexceptArg(nullptr),
throwArg(nullptr) {
throwArg(nullptr)
{
}
const std::string &name() const {
const std::string &name() const
{
return tokenDef->str();
}
std::size_t argCount() const {
std::size_t argCount() const
{
return argumentList.size();
}
std::size_t minArgCount() const {
std::size_t minArgCount() const
{
return argumentList.size() - initArgCount;
}
const Variable* getArgumentVar(std::size_t num) const;
unsigned int initializedArgCount() const {
unsigned int initializedArgCount() const
{
return initArgCount;
}
void addArguments(const SymbolDatabase *symbolDatabase, const Scope *scope);
/** @brief check if this function is virtual in the base classes */
bool isImplicitlyVirtual(bool defaultVal = false) const;
bool isConstructor() const {
bool isConstructor() const
{
return type==eConstructor ||
type==eCopyConstructor ||
type==eMoveConstructor;
}
bool isDestructor() const {
bool isDestructor() const
{
return type==eDestructor;
}
bool isAttributeConstructor() const {
bool isAttributeConstructor() const
{
return tokenDef->isAttributeConstructor();
}
bool isAttributeDestructor() const {
bool isAttributeDestructor() const
{
return tokenDef->isAttributeDestructor();
}
bool isAttributePure() const {
bool isAttributePure() const
{
return tokenDef->isAttributePure();
}
bool isAttributeConst() const {
bool isAttributeConst() const
{
return tokenDef->isAttributeConst();
}
bool isAttributeNothrow() const {
bool isAttributeNothrow() const
{
return tokenDef->isAttributeNothrow();
}
bool isDeclspecNothrow() const {
bool isDeclspecNothrow() const
{
return tokenDef->isDeclspecNothrow();
}
@ -703,15 +761,18 @@ public:
const Scope *functionOf; // scope this function belongs to
Function *function; // function info for this function
bool isClassOrStruct() const {
bool isClassOrStruct() const
{
return (type == eClass || type == eStruct);
}
bool isExecutable() const {
bool isExecutable() const
{
return type != eClass && type != eStruct && type != eUnion && type != eGlobal && type != eNamespace;
}
bool isLocal() const {
bool isLocal() const
{
return (type == eIf || type == eElse ||
type == eFor || type == eWhile || type == eDo ||
type == eSwitch || type == eUnconditional ||
@ -732,12 +793,14 @@ public:
Scope *findInNestedList(const std::string & name);
const Scope *findRecordInNestedList(const std::string & name) const;
Scope *findRecordInNestedList(const std::string & name) {
Scope *findRecordInNestedList(const std::string & name)
{
return const_cast<Scope *>(static_cast<const Scope *>(this)->findRecordInNestedList(name));
}
const Type* findType(const std::string& name) const;
Type* findType(const std::string& name) {
Type* findType(const std::string& name)
{
return const_cast<Type*>(static_cast<const Scope *>(this)->findType(name));
}
@ -749,7 +812,8 @@ public:
void addVariable(const Token *token_, const Token *start_,
const Token *end_, AccessControl access_, const Type *type_,
const Scope *scope_) {
const Scope *scope_)
{
varlist.push_back(Variable(token_, start_, end_, varlist.size(),
access_,
type_, scope_));
@ -835,27 +899,32 @@ public:
const Scope *findScopeByName(const std::string& name) const;
const Type* findType(const Token *tok, const Scope *startScope) const;
Type* findType(const Token *tok, Scope *startScope) const {
Type* findType(const Token *tok, Scope *startScope) const
{
return const_cast<Type*>(this->findType(tok, static_cast<const Scope *>(startScope)));
}
const Scope *findScope(const Token *tok, const Scope *startScope) const;
Scope *findScope(const Token *tok, Scope *startScope) const {
Scope *findScope(const Token *tok, Scope *startScope) const
{
return const_cast<Scope *>(this->findScope(tok, static_cast<const Scope *>(startScope)));
}
bool isClassOrStruct(const std::string &type) const {
bool isClassOrStruct(const std::string &type) const
{
for (std::list<Type>::const_iterator i = typeList.begin(); i != typeList.end(); ++i)
if (i->name() == type)
return true;
return false;
}
const Variable *getVariableFromVarId(std::size_t varId) const {
const Variable *getVariableFromVarId(std::size_t varId) const
{
return _variableList[varId];
}
std::size_t getVariableListSize() const {
std::size_t getVariableListSize() const
{
return _variableList.size();
}

View File

@ -45,10 +45,12 @@ struct TimerResultsData {
TimerResultsData()
: _clocks(0)
, _numberOfResults(0) {
, _numberOfResults(0)
{
}
double seconds() const {
double seconds() const
{
double ret = (double)((unsigned long)_clocks) / (double)CLOCKS_PER_SEC;
return ret;
}
@ -56,7 +58,8 @@ struct TimerResultsData {
class CPPCHECKLIB TimerResults : public TimerResultsIntf {
public:
TimerResults() {
TimerResults()
{
}
void ShowResults(SHOWTIME_MODES mode) const;

View File

@ -70,7 +70,8 @@ public:
~Token();
template<typename T>
void str(T&& s) {
void str(T&& s)
{
_str = s;
_varId = 0;
@ -83,7 +84,8 @@ public:
*/
void concatStr(std::string const& b);
const std::string &str() const {
const std::string &str() const
{
return _str;
}
@ -98,7 +100,8 @@ public:
* would return next from that one.
*/
const Token *tokAt(int index) const;
Token *tokAt(int index) {
Token *tokAt(int index)
{
return const_cast<Token *>(static_cast<const Token *>(this)->tokAt(index));
}
@ -107,7 +110,8 @@ public:
* For example index 1 would return the link to next token.
*/
const Token *linkAt(int index) const;
Token *linkAt(int index) {
Token *linkAt(int index)
{
return const_cast<Token *>(static_cast<const Token *>(this)->linkAt(index));
}
@ -216,149 +220,193 @@ public:
**/
static std::string getCharAt(const Token *tok, std::size_t index);
Type type() const {
Type type() const
{
return _type;
}
void type(Type t) {
void type(Type t)
{
_type = t;
}
void isKeyword(bool kwd) {
void isKeyword(bool kwd)
{
if (kwd)
_type = eKeyword;
else if (_type == eKeyword)
_type = eName;
}
bool isKeyword() const {
bool isKeyword() const
{
return _type == eKeyword;
}
bool isName() const {
bool isName() const
{
return _type == eName || _type == eType || _type == eVariable || _type == eFunction || _type == eKeyword ||
_type == eBoolean; // TODO: "true"/"false" aren't really a name...
}
bool isUpperCaseName() const;
bool isLiteral() const {
bool isLiteral() const
{
return _type == eNumber || _type == eString || _type == eChar ||
_type == eBoolean || _type == eLiteral;
}
bool isNumber() const {
bool isNumber() const
{
return _type == eNumber;
}
bool isOp() const {
bool isOp() const
{
return (isConstOp() ||
isAssignmentOp() ||
_type == eIncDecOp);
}
bool isConstOp() const {
bool isConstOp() const
{
return (isArithmeticalOp() ||
_type == eLogicalOp ||
_type == eComparisonOp ||
_type == eBitOp);
}
bool isExtendedOp() const {
bool isExtendedOp() const
{
return isConstOp() ||
_type == eExtendedOp;
}
bool isArithmeticalOp() const {
bool isArithmeticalOp() const
{
return _type == eArithmeticalOp;
}
bool isComparisonOp() const {
bool isComparisonOp() const
{
return _type == eComparisonOp;
}
bool isAssignmentOp() const {
bool isAssignmentOp() const
{
return _type == eAssignmentOp;
}
bool isBoolean() const {
bool isBoolean() const
{
return _type == eBoolean;
}
unsigned int flags() const {
unsigned int flags() const
{
return _flags;
}
void flags(unsigned int flags_) {
void flags(unsigned int flags_)
{
_flags = flags_;
}
bool isUnsigned() const {
bool isUnsigned() const
{
return getFlag(fIsUnsigned);
}
void isUnsigned(bool sign) {
void isUnsigned(bool sign)
{
setFlag(fIsUnsigned, sign);
}
bool isSigned() const {
bool isSigned() const
{
return getFlag(fIsSigned);
}
void isSigned(bool sign) {
void isSigned(bool sign)
{
setFlag(fIsSigned, sign);
}
bool isPointerCompare() const {
bool isPointerCompare() const
{
return getFlag(fIsPointerCompare);
}
void isPointerCompare(bool b) {
void isPointerCompare(bool b)
{
setFlag(fIsPointerCompare, b);
}
bool isLong() const {
bool isLong() const
{
return getFlag(fIsLong);
}
void isLong(bool size) {
void isLong(bool size)
{
setFlag(fIsLong, size);
}
bool isStandardType() const {
bool isStandardType() const
{
return getFlag(fIsStandardType);
}
void isStandardType(bool b) {
void isStandardType(bool b)
{
setFlag(fIsStandardType, b);
}
bool isExpandedMacro() const {
bool isExpandedMacro() const
{
return getFlag(fIsExpandedMacro);
}
void isExpandedMacro(bool m) {
void isExpandedMacro(bool m)
{
setFlag(fIsExpandedMacro, m);
}
bool isAttributeConstructor() const {
bool isAttributeConstructor() const
{
return getFlag(fIsAttributeConstructor);
}
void isAttributeConstructor(bool ac) {
void isAttributeConstructor(bool ac)
{
setFlag(fIsAttributeConstructor, ac);
}
bool isAttributeDestructor() const {
bool isAttributeDestructor() const
{
return getFlag(fIsAttributeDestructor);
}
void isAttributeDestructor(bool value) {
void isAttributeDestructor(bool value)
{
setFlag(fIsAttributeDestructor, value);
}
bool isAttributeUnused() const {
bool isAttributeUnused() const
{
return getFlag(fIsAttributeUnused);
}
void isAttributeUnused(bool unused) {
void isAttributeUnused(bool unused)
{
setFlag(fIsAttributeUnused, unused);
}
bool isAttributeUsed() const {
bool isAttributeUsed() const
{
return getFlag(fIsAttributeUsed);
}
void isAttributeUsed(bool unused) {
void isAttributeUsed(bool unused)
{
setFlag(fIsAttributeUsed, unused);
}
bool isAttributePure() const {
bool isAttributePure() const
{
return getFlag(fIsAttributePure);
}
void isAttributePure(bool value) {
void isAttributePure(bool value)
{
setFlag(fIsAttributePure, value);
}
bool isAttributeConst() const {
bool isAttributeConst() const
{
return getFlag(fIsAttributeConst);
}
void isAttributeConst(bool value) {
void isAttributeConst(bool value)
{
setFlag(fIsAttributeConst, value);
}
bool isAttributeNothrow() const {
bool isAttributeNothrow() const
{
return getFlag(fIsAttributeNothrow);
}
void isAttributeNothrow(bool value) {
void isAttributeNothrow(bool value)
{
setFlag(fIsAttributeNothrow, value);
}
bool isDeclspecNothrow() const {
bool isDeclspecNothrow() const
{
return getFlag(fIsDeclspecNothrow);
}
void isDeclspecNothrow(bool value) {
void isDeclspecNothrow(bool value)
{
setFlag(fIsDeclspecNothrow, value);
}
@ -366,16 +414,20 @@ public:
static const Token *findsimplematch(const Token *tok, const char pattern[], const Token *end);
static const Token *findmatch(const Token *tok, const char pattern[], unsigned int varId = 0);
static const Token *findmatch(const Token *tok, const char pattern[], const Token *end, unsigned int varId = 0);
static Token *findsimplematch(Token *tok, const char pattern[]) {
static Token *findsimplematch(Token *tok, const char pattern[])
{
return const_cast<Token *>(findsimplematch(static_cast<const Token *>(tok), pattern));
}
static Token *findsimplematch(Token *tok, const char pattern[], const Token *end) {
static Token *findsimplematch(Token *tok, const char pattern[], const Token *end)
{
return const_cast<Token *>(findsimplematch(static_cast<const Token *>(tok), pattern, end));
}
static Token *findmatch(Token *tok, const char pattern[], unsigned int varId = 0) {
static Token *findmatch(Token *tok, const char pattern[], unsigned int varId = 0)
{
return const_cast<Token *>(findmatch(static_cast<const Token *>(tok), pattern, varId));
}
static Token *findmatch(Token *tok, const char pattern[], const Token *end, unsigned int varId = 0) {
static Token *findmatch(Token *tok, const char pattern[], const Token *end, unsigned int varId = 0)
{
return const_cast<Token *>(findmatch(static_cast<const Token *>(tok), pattern, end, varId));
}
@ -395,21 +447,26 @@ public:
*/
static int multiCompare(const Token *needle, const char *haystack, unsigned int varid);
unsigned int linenr() const {
unsigned int linenr() const
{
return _linenr;
}
void linenr(unsigned int lineNumber) {
void linenr(unsigned int lineNumber)
{
_linenr = lineNumber;
}
unsigned int fileIndex() const {
unsigned int fileIndex() const
{
return _fileIndex;
}
void fileIndex(unsigned int indexOfFile) {
void fileIndex(unsigned int indexOfFile)
{
_fileIndex = indexOfFile;
}
Token *next() const {
Token *next() const
{
return _next;
}
@ -434,15 +491,18 @@ public:
void insertToken(const std::string &tokenStr, const std::string &originalNameStr, bool prepend=false);
Token *previous() const {
Token *previous() const
{
return _previous;
}
unsigned int varId() const {
unsigned int varId() const
{
return _varId;
}
void varId(unsigned int id) {
void varId(unsigned int id)
{
_varId = id;
if (id != 0)
_type = eVariable;
@ -516,7 +576,8 @@ public:
* @param linkToToken The token where this token should link
* to.
*/
void link(Token *linkToToken) {
void link(Token *linkToToken)
{
_link = linkToToken;
if (_str == "<" || _str == ">")
update_property_info();
@ -531,7 +592,8 @@ public:
*
* @return The token where this token links to.
*/
Token *link() const {
Token *link() const
{
return _link;
}
@ -539,14 +601,16 @@ public:
* Associate this token with given scope
* @param s Scope to be associated
*/
void scope(const Scope *s) {
void scope(const Scope *s)
{
_scope = s;
}
/**
* @return a pointer to the scope containing this token.
*/
const Scope *scope() const {
const Scope *scope() const
{
return _scope;
}
@ -554,7 +618,8 @@ public:
* Associate this token with given function
* @param f Function to be associated
*/
void function(const Function *f) {
void function(const Function *f)
{
_function = f;
if (f)
_type = eFunction;
@ -565,7 +630,8 @@ public:
/**
* @return a pointer to the Function associated with this token.
*/
const Function *function() const {
const Function *function() const
{
return _type == eFunction ? _function : 0;
}
@ -573,7 +639,8 @@ public:
* Associate this token with given variable
* @param v Variable to be associated
*/
void variable(const Variable *v) {
void variable(const Variable *v)
{
_variable = v;
if (v || _varId)
_type = eVariable;
@ -584,7 +651,8 @@ public:
/**
* @return a pointer to the variable associated with this token.
*/
const Variable *variable() const {
const Variable *variable() const
{
return _type == eVariable ? _variable : 0;
}
@ -611,7 +679,8 @@ public:
static void move(Token *srcStart, Token *srcEnd, Token *newLocation);
/** Get progressValue */
unsigned int progressValue() const {
unsigned int progressValue() const
{
return _progressValue;
}
@ -643,7 +712,8 @@ public:
/**
* @return the original name.
*/
const std::string & originalName() const {
const std::string & originalName() const
{
return _originalName ? *_originalName : emptyString;
}
@ -651,7 +721,8 @@ public:
* Sets the original name.
*/
template<typename T>
void originalName(T&& name) {
void originalName(T&& name)
{
if (!_originalName)
_originalName = new std::string(name);
else
@ -661,7 +732,8 @@ public:
/** Values of token */
std::list<ValueFlow::Value> values;
const ValueFlow::Value * getValue(const MathLib::bigint val) const {
const ValueFlow::Value * getValue(const MathLib::bigint val) const
{
std::list<ValueFlow::Value>::const_iterator it;
for (it = values.begin(); it != values.end(); ++it) {
if (it->intvalue == val && !it->tokvalue)
@ -670,7 +742,8 @@ public:
return NULL;
}
const ValueFlow::Value * getMaxValue(bool condition) const {
const ValueFlow::Value * getMaxValue(bool condition) const
{
const ValueFlow::Value *ret = nullptr;
std::list<ValueFlow::Value>::const_iterator it;
for (it = values.begin(); it != values.end(); ++it) {
@ -693,10 +766,12 @@ public:
private:
void next(Token *nextToken) {
void next(Token *nextToken)
{
_next = nextToken;
}
void previous(Token *previousToken) {
void previous(Token *previousToken)
{
_previous = previousToken;
}
@ -770,7 +845,8 @@ private:
* @param flag_ flag to get state of
* @return true if flag set or false in flag not set
*/
bool getFlag(unsigned int flag_) const {
bool getFlag(unsigned int flag_) const
{
return bool((_flags & flag_) != 0);
}
@ -779,7 +855,8 @@ private:
* @param flag_ flag to set state
* @param state_ new state of flag
*/
void setFlag(unsigned int flag_, bool state_) {
void setFlag(unsigned int flag_, bool state_)
{
_flags = state_ ? _flags | flag_ : _flags & ~flag_;
}
@ -802,16 +879,20 @@ public:
void astOperand1(Token *tok);
void astOperand2(Token *tok);
const Token * astOperand1() const {
const Token * astOperand1() const
{
return _astOperand1;
}
const Token * astOperand2() const {
const Token * astOperand2() const
{
return _astOperand2;
}
const Token * astParent() const {
const Token * astParent() const
{
return _astParent;
}
const Token *astTop() const {
const Token *astTop() const
{
const Token *ret = this;
while (ret->_astParent)
ret = ret->_astParent;
@ -827,11 +908,13 @@ public:
*/
bool isCalculation() const;
void clearAst() {
void clearAst()
{
_astOperand1 = _astOperand2 = _astParent = NULL;
}
std::string astString(const char *sep = "") const {
std::string astString(const char *sep = "") const
{
std::string ret;
if (_astOperand1)
ret = _astOperand1->astString(sep);

View File

@ -7407,12 +7407,15 @@ public:
name(nullptr),
value(nullptr),
start(nullptr),
end(nullptr) {
end(nullptr)
{
}
EnumValue(const EnumValue &ev) {
EnumValue(const EnumValue &ev)
{
*this = ev;
}
EnumValue& operator=(const EnumValue& ev) {
EnumValue& operator=(const EnumValue& ev)
{
name=ev.name;
value=ev.value;
start=ev.start;
@ -7423,10 +7426,12 @@ public:
name(name_),
value(value_),
start(start_),
end(end_) {
end(end_)
{
}
void simplify(const std::map<std::string, EnumValue> &enumValues) {
void simplify(const std::map<std::string, EnumValue> &enumValues)
{
for (Token *tok = start; tok; tok = tok->next()) {
std::map<std::string, EnumValue>::const_iterator it = enumValues.find(tok->str());
if (it != enumValues.end()) {

View File

@ -44,17 +44,20 @@ public:
Tokenizer(const Settings * settings, ErrorLogger *errorLogger);
~Tokenizer();
void setTimerResults(TimerResults *tr) {
void setTimerResults(TimerResults *tr)
{
m_timerResults = tr;
}
/** Is the code C. Used for bailouts */
bool isC() const {
bool isC() const
{
return list.isC();
}
/** Is the code CPP. Used for bailouts */
bool isCPP() const {
bool isCPP() const
{
return list.isCPP();
}
@ -701,16 +704,19 @@ public:
void unsupportedTypedef(const Token *tok) const;
/** Was there templates in the code? */
bool codeWithTemplates() const {
bool codeWithTemplates() const
{
return _codeWithTemplates;
}
void setSettings(const Settings *settings) {
void setSettings(const Settings *settings)
{
_settings = settings;
list.setSettings(settings);
}
const SymbolDatabase *getSymbolDatabase() const {
const SymbolDatabase *getSymbolDatabase() const
{
return _symbolDatabase;
}
void createSymbolDatabase();
@ -726,7 +732,8 @@ public:
* Get variable count.
* @return number of variables
*/
unsigned int varIdCount() const {
unsigned int varIdCount() const
{
return _varId;
}
@ -747,7 +754,8 @@ public:
*/
TokenList list;
// Implement tokens() as a wrapper for convinience when using the TokenList
const Token* tokens() const {
const Token* tokens() const
{
return list.front();
}
@ -798,7 +806,8 @@ private:
Tokenizer &operator=(const Tokenizer &);
static Token * startOfFunction(Token * tok);
static Token * startOfExecutableScope(Token * tok) {
static Token * startOfExecutableScope(Token * tok)
{
return const_cast<Token*>(startOfExecutableScope(const_cast<const Token *>(tok)));
}

View File

@ -36,7 +36,8 @@ public:
TokenList(const Settings* settings);
~TokenList();
void setSettings(const Settings *settings) {
void setSettings(const Settings *settings)
{
_settings = settings;
}
@ -44,12 +45,14 @@ public:
const std::string& getSourceFilePath() const;
/** Is the code C. Used for bailouts */
bool isC() const {
bool isC() const
{
return _isC;
}
/** Is the code CPP. Used for bailouts */
bool isCPP() const {
bool isCPP() const
{
return _isCPP;
}
@ -82,18 +85,22 @@ public:
unsigned int appendFileIfNew(const std::string &file);
/** get first token of list */
const Token *front() const {
const Token *front() const
{
return _front;
}
Token *front() {
Token *front()
{
return _front;
}
/** get last token of list */
const Token *back() const {
const Token *back() const
{
return _back;
}
Token *back() {
Token *back()
{
return _back;
}
@ -102,7 +109,8 @@ public:
* The first filename is the filename for the sourcefile
* @return vector with filenames
*/
const std::vector<std::string>& getFiles() const {
const std::vector<std::string>& getFiles() const
{
return _files;
}

View File

@ -29,7 +29,8 @@ extern std::ostringstream output;
class RedirectOutputError {
public:
/** Set up redirection, flushing anything in the pipes. */
RedirectOutputError() {
RedirectOutputError()
{
// flush all old output
std::cout.flush();
std::cerr.flush();
@ -42,7 +43,8 @@ public:
}
/** Revert cout and cerr behaviour */
~RedirectOutputError() {
~RedirectOutputError()
{
std::cout.rdbuf(_oldCout); // restore cout's original streambuf
std::cerr.rdbuf(_oldCerr); // restore cerrs's original streambuf
@ -51,24 +53,28 @@ public:
}
/** Return what would be printed to cout. See also clearOutput() */
std::string getOutput() const {
std::string getOutput() const
{
return _out.str();
}
/** Normally called after getOutput() to prevent same text to be returned
twice. */
void clearOutput() {
void clearOutput()
{
_out.str("");
}
/** Return what would be printed to cerr. See also clearErrout() */
std::string getErrout() const {
std::string getErrout() const
{
return _err.str();
}
/** Normally called after getErrout() to prevent same text to be returned
twice. */
void clearErrout() {
void clearErrout()
{
_err.str("");
}

View File

@ -26,13 +26,15 @@ extern std::ostringstream errout;
class Test64BitPortability : public TestFixture {
public:
Test64BitPortability() : TestFixture("Test64BitPortability") {
Test64BitPortability() : TestFixture("Test64BitPortability")
{
}
private:
void run() {
void run()
{
TEST_CASE(novardecl);
TEST_CASE(functionpar);
TEST_CASE(structmember);
@ -41,7 +43,8 @@ private:
TEST_CASE(returnIssues);
}
void check(const char code[]) {
void check(const char code[])
{
// Clear the error buffer..
errout.str("");
@ -58,7 +61,8 @@ private:
check64BitPortability.pointerassignment();
}
void novardecl() {
void novardecl()
{
// if the variable declarations can't be seen then skip the warning
check("void foo()\n"
"{\n"
@ -67,7 +71,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void functionpar() {
void functionpar()
{
check("int foo(int *p)\n"
"{\n"
" int a = p;\n"
@ -102,7 +107,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void structmember() {
void structmember()
{
check("struct Foo { int *p; };\n"
"void f(struct Foo *foo) {\n"
" int i = foo->p;\n"
@ -110,7 +116,8 @@ private:
ASSERT_EQUALS("[test.cpp:3]: (portability) Assigning a pointer to an integer is not portable.\n", errout.str());
}
void ptrcompare() {
void ptrcompare()
{
// Ticket #2892
check("void foo(int *p) {\n"
" int a = (p != NULL);\n"
@ -118,7 +125,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void ptrarithmetic() {
void ptrarithmetic()
{
// #3073
check("void foo(int *p) {\n"
" int x = 10;\n"
@ -145,7 +153,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void returnIssues() {
void returnIssues()
{
check("void* foo(int i) {\n"
" return i;\n"
"}");

View File

@ -30,7 +30,8 @@ public:
private:
void check(
const char code[],
const char *filename = NULL) {
const char *filename = NULL)
{
// Clear the error buffer..
errout.str("");
@ -47,7 +48,8 @@ private:
checkAssert.runSimplifiedChecks(&tokenizer, &settings, this);
}
void run() {
void run()
{
TEST_CASE(assignmentInAssert);
TEST_CASE(functionCallInAssert);
TEST_CASE(memberFunctionCallInAssert);
@ -55,7 +57,8 @@ private:
}
void safeFunctionCallInAssert() {
void safeFunctionCallInAssert()
{
check(
"int a;\n"
"bool b = false;\n"
@ -77,7 +80,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void functionCallInAssert() {
void functionCallInAssert()
{
check(
"int a;\n"
"int foo() {\n"
@ -134,7 +138,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void memberFunctionCallInAssert() {
void memberFunctionCallInAssert()
{
check("struct SquarePack {\n"
" void Foo();\n"
"};\n"
@ -167,7 +172,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void assignmentInAssert() {
void assignmentInAssert()
{
check("void f() {\n"
" int a; a = 0;\n"
" assert(a = 2);\n"

View File

@ -27,14 +27,16 @@ extern std::ostringstream errout;
class TestAutoVariables : public TestFixture {
public:
TestAutoVariables() : TestFixture("TestAutoVariables") {
TestAutoVariables() : TestFixture("TestAutoVariables")
{
}
private:
void check(const char code[], bool inconclusive=false, bool runSimpleChecks=true, const char* filename=nullptr) {
void check(const char code[], bool inconclusive=false, bool runSimpleChecks=true, const char* filename=nullptr)
{
// Clear the error buffer..
errout.str("");
@ -65,7 +67,8 @@ private:
}
}
void run() {
void run()
{
TEST_CASE(testautovar1);
TEST_CASE(testautovar2);
TEST_CASE(testautovar3); // ticket #2925
@ -118,7 +121,8 @@ private:
void testautovar1() {
void testautovar1()
{
check("void func1(int **res)\n"
"{\n"
" int num = 2;\n"
@ -141,7 +145,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void testautovar2() {
void testautovar2()
{
check("class Fred {\n"
" void func1(int **res);\n"
"}\n"
@ -173,7 +178,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void testautovar3() { // ticket #2925
void testautovar3() // ticket #2925
{
check("void foo(int **p)\n"
"{\n"
" int x[100];\n"
@ -182,7 +188,8 @@ private:
ASSERT_EQUALS("[test.cpp:4]: (error) Address of local auto-variable assigned to a function parameter.\n", errout.str());
}
void testautovar4() { // ticket #2928
void testautovar4() // ticket #2928
{
check("void foo(int **p)\n"
"{\n"
" static int x[100];\n"
@ -191,7 +198,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void testautovar5() { // ticket #2926
void testautovar5() // ticket #2926
{
check("void foo(struct AB *ab)\n"
"{\n"
" char a;\n"
@ -207,7 +215,8 @@ private:
ASSERT_EQUALS("[test.cpp:4]: (error, inconclusive) Address of local auto-variable assigned to a function parameter.\n", errout.str());
}
void testautovar6() { // ticket #2931
void testautovar6() // ticket #2931
{
check("void foo(struct X *x)\n"
"{\n"
" char a[10];\n"
@ -223,7 +232,8 @@ private:
ASSERT_EQUALS("[test.cpp:4]: (error, inconclusive) Address of local auto-variable assigned to a function parameter.\n", errout.str());
}
void testautovar7() { // ticket #3066
void testautovar7() // ticket #3066
{
check("struct txt_scrollpane_s * TXT_NewScrollPane(struct txt_widget_s * target)\n"
"{\n"
" struct txt_scrollpane_s * scrollpane;\n"
@ -233,7 +243,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void testautovar8() {
void testautovar8()
{
check("void foo(int*& p) {\n"
" int i = 0;\n"
" p = &i;\n"
@ -246,7 +257,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void testautovar9() {
void testautovar9()
{
check("struct FN {int i;};\n"
"struct FP {FN* f};\n"
"void foo(int*& p, FN* p_fp) {\n"
@ -259,7 +271,8 @@ private:
ASSERT_EQUALS("[test.cpp:6]: (error) Address of local auto-variable assigned to a function parameter.\n", errout.str());
}
void testautovar10() { // #2930 - assignment of function parameter
void testautovar10() // #2930 - assignment of function parameter
{
check("void foo(char* p) {\n"
" p = 0;\n"
"}");
@ -327,7 +340,8 @@ private:
ASSERT_EQUALS("[test.cpp:2]: (warning) Assignment of function parameter has no effect outside the function. Did you forget dereferencing it?\n", errout.str());
}
void testautovar11() { // #4641 - fp, assign local struct member address to function parameter
void testautovar11() // #4641 - fp, assign local struct member address to function parameter
{
check("struct A {\n"
" char *data[10];\n"
"};\n"
@ -360,7 +374,8 @@ private:
ASSERT_EQUALS("[test.cpp:3]: (error) Address of local auto-variable assigned to a function parameter.\n", errout.str());
}
void testautovar12() { // Ticket #5024, #5050 - Crash on invalid input
void testautovar12() // Ticket #5024, #5050 - Crash on invalid input
{
check("void f(int* a) { a = }");
check("struct custom_type { custom_type(int) {} };\n"
"void func(int) {}\n"
@ -369,7 +384,8 @@ private:
"UNKNOWN_MACRO_EXPANDING_TO_SIGNATURE { custom_type a(var); }");
}
void testautovar13() { // Ticket #5537
void testautovar13() // Ticket #5537
{
check("class FileManager {\n"
" FileManager() : UniqueRealDirs(*new UniqueDirContainer())\n"
" {}\n"
@ -379,7 +395,8 @@ private:
"};\n");
}
void testautovar14() { // Ticket #4776
void testautovar14() // Ticket #4776
{
check("void f(int x) {\n"
"label:"
" if (x>0) {\n"
@ -390,7 +407,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void testautovar_array1() {
void testautovar_array1()
{
check("void func1(int* arr[2])\n"
"{\n"
" int num=2;"
@ -399,7 +417,8 @@ private:
ASSERT_EQUALS("[test.cpp:3]: (error) Address of local auto-variable assigned to a function parameter.\n", errout.str());
}
void testautovar_array2() {
void testautovar_array2()
{
check("class Fred {\n"
" void func1(int* arr[2]);\n"
"}\n"
@ -411,7 +430,8 @@ private:
ASSERT_EQUALS("[test.cpp:6]: (error) Address of local auto-variable assigned to a function parameter.\n", errout.str());
}
void testautovar_return1() {
void testautovar_return1()
{
check("int* func1()\n"
"{\n"
" int num=2;"
@ -420,7 +440,8 @@ private:
ASSERT_EQUALS("[test.cpp:3]: (error) Address of an auto-variable returned.\n", errout.str());
}
void testautovar_return2() {
void testautovar_return2()
{
check("class Fred {\n"
" int* func1()\n"
"}\n"
@ -432,7 +453,8 @@ private:
ASSERT_EQUALS("[test.cpp:6]: (error) Address of an auto-variable returned.\n", errout.str());
}
void testautovar_return3() {
void testautovar_return3()
{
// #2975 - FP
check("void** f()\n"
"{\n"
@ -442,7 +464,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void testautovar_return4() {
void testautovar_return4()
{
// #3030
check("char *foo()\n"
"{\n"
@ -459,7 +482,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void testautovar_extern() {
void testautovar_extern()
{
check("struct foo *f()\n"
"{\n"
" extern struct foo f;\n"
@ -468,7 +492,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void testinvaliddealloc() {
void testinvaliddealloc()
{
check("void func1() {\n"
" char tmp1[256];\n"
" free(tmp1);\n"
@ -552,7 +577,8 @@ private:
}
void testinvaliddealloc_C() {
void testinvaliddealloc_C()
{
// #5691
check("void svn_repos_dir_delta2() {\n"
" struct context c;\n"
@ -561,7 +587,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void testassign1() { // Ticket #1819
void testassign1() // Ticket #1819
{
check("void f(EventPtr *eventP, ActionPtr **actionsP) {\n"
" EventPtr event = *eventP;\n"
" *actionsP = &event->actions;\n"
@ -569,7 +596,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void testassign2() { // Ticket #2765
void testassign2() // Ticket #2765
{
check("static void function(unsigned long **datap) {\n"
" struct my_s *mr = global_structure_pointer;\n"
" *datap = &mr->value;\n"
@ -577,7 +605,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void returnLocalVariable1() {
void returnLocalVariable1()
{
check("char *foo()\n"
"{\n"
" char str[100] = {0};\n"
@ -596,7 +625,8 @@ private:
ASSERT_EQUALS("[test.cpp:7]: (error) Pointer to local array variable returned.\n", errout.str());
}
void returnLocalVariable2() {
void returnLocalVariable2()
{
check("std::string foo()\n"
"{\n"
" char str[100] = {0};\n"
@ -615,7 +645,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void returnReference1() {
void returnReference1()
{
check("std::string &foo()\n"
"{\n"
" std::string s;\n"
@ -712,7 +743,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void returnReference2() {
void returnReference2()
{
check("class Fred {\n"
" std::string &foo();\n"
"}\n"
@ -802,7 +834,8 @@ private:
"}");
}
void returnReference3() {
void returnReference3()
{
check("double & f(double & rd) {\n"
" double ret = getValue();\n"
" rd = ret;\n"
@ -812,7 +845,8 @@ private:
}
// Returning reference to global variable
void returnReference4() {
void returnReference4()
{
check("double a;\n"
"double & f() {\n"
" return a;\n"
@ -820,7 +854,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void returnReference5() {
void returnReference5()
{
check("struct A {\n"
" int i;\n"
"};\n"
@ -840,7 +875,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void returnReference6() {
void returnReference6()
{
check("Fred & create() {\n"
" Fred &fred(*new Fred);\n"
" return fred;\n"
@ -848,7 +884,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void returnReference7() { // 3791 - false positive for overloaded function
void returnReference7() // 3791 - false positive for overloaded function
{
check("std::string a();\n"
"std::string &a(int);\n"
"std::string &b() {\n"
@ -864,7 +901,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void returnReferenceLiteral() {
void returnReferenceLiteral()
{
check("const std::string &a() {\n"
" return \"foo\";\n"
"}");
@ -876,7 +914,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void returnReferenceCalculation() {
void returnReferenceCalculation()
{
check("const std::string &a(const std::string& str) {\n"
" return \"foo\" + str;\n"
"}");
@ -914,7 +953,8 @@ private:
}
void testglobalnamespace() {
void testglobalnamespace()
{
check("class SharedPtrHolder\n"
"{\n"
" ::std::tr1::shared_ptr<int> pNum;\n"
@ -928,7 +968,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void returnParameterAddress() {
void returnParameterAddress()
{
check("int* foo(int y)\n"
"{\n"
" return &y;\n"
@ -951,7 +992,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void testconstructor() { // Ticket #5478 - crash while checking a constructor
void testconstructor() // Ticket #5478 - crash while checking a constructor
{
check("class const_tree_iterator {\n"
" const_tree_iterator(bool (*_incream)(node_type*&)) {}\n"
" const_tree_iterator& parent() {\n"
@ -960,7 +1002,8 @@ private:
"};");
}
void variableIsUsedInScope() {
void variableIsUsedInScope()
{
check("void removed_cb (GList *uids) {\n"
"for (; uids; uids = uids->next) {\n"
"}\n"

View File

@ -26,13 +26,15 @@ extern std::ostringstream errout;
class TestBool : public TestFixture {
public:
TestBool() : TestFixture("TestBool") {
TestBool() : TestFixture("TestBool")
{
}
private:
void run() {
void run()
{
TEST_CASE(bitwiseOnBoolean); // if (bool & bool)
TEST_CASE(incrementBoolean);
TEST_CASE(assignBoolToPointer);
@ -63,7 +65,8 @@ private:
TEST_CASE(pointerArithBool1);
}
void check(const char code[], bool experimental = false, const char filename[] = "test.cpp") {
void check(const char code[], bool experimental = false, const char filename[] = "test.cpp")
{
// Clear the error buffer..
errout.str("");
@ -86,7 +89,8 @@ private:
}
void assignBoolToPointer() {
void assignBoolToPointer()
{
check("void foo(bool *p) {\n"
" p = false;\n"
@ -140,7 +144,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void assignBoolToFloat() {
void assignBoolToFloat()
{
check("void foo1() {\n"
" double d = false;\n"
"}");
@ -163,7 +168,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void comparisonOfBoolExpressionWithInt1() {
void comparisonOfBoolExpressionWithInt1()
{
check("void f(int x) {\n"
" if ((x && 0x0f)==6)\n"
" a++;\n"
@ -376,7 +382,8 @@ private:
ASSERT_EQUALS("",errout.str());
}
void comparisonOfBoolExpressionWithInt2() {
void comparisonOfBoolExpressionWithInt2()
{
check("void f(int x) {\n"
" if (!x == 10) {\n"
" printf(\"x not equal to 10\");\n"
@ -456,14 +463,16 @@ private:
ASSERT_EQUALS("[test.cpp:1]: (warning) Comparison of a boolean expression with an integer other than 0 or 1.\n",errout.str());
}
void comparisonOfBoolExpressionWithInt3() {
void comparisonOfBoolExpressionWithInt3()
{
check("int f(int x) {\n"
" return t<0>() && x;\n"
"}");
ASSERT_EQUALS("", errout.str());
}
void comparisonOfBoolExpressionWithInt4() {
void comparisonOfBoolExpressionWithInt4()
{
// #5016
check("void f() {\n"
" for(int i = 4; i > -1 < 5 ; --i) {}\n"
@ -499,7 +508,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void checkComparisonOfFuncReturningBool1() {
void checkComparisonOfFuncReturningBool1()
{
check("void f(){\n"
" int temp = 4;\n"
" if(compare1(temp) > compare2(temp)){\n"
@ -523,7 +533,8 @@ private:
ASSERT_EQUALS("[test.cpp:3]: (style) Comparison of two functions returning boolean value using relational (<, >, <= or >=) operator.\n", errout.str());
}
void checkComparisonOfFuncReturningBool2() {
void checkComparisonOfFuncReturningBool2()
{
check("void f(){\n"
" int temp = 4;\n"
" bool a = true;\n"
@ -541,7 +552,8 @@ private:
ASSERT_EQUALS("[test.cpp:4]: (style) Comparison of a function returning boolean value using relational (<, >, <= or >=) operator.\n", errout.str());
}
void checkComparisonOfFuncReturningBool3() {
void checkComparisonOfFuncReturningBool3()
{
check("void f(){\n"
" int temp = 4;\n"
" if(compare(temp) > temp){\n"
@ -558,7 +570,8 @@ private:
ASSERT_EQUALS("[test.cpp:3]: (style) Comparison of a function returning boolean value using relational (<, >, <= or >=) operator.\n", errout.str());
}
void checkComparisonOfFuncReturningBool4() {
void checkComparisonOfFuncReturningBool4()
{
check("void f(){\n"
" int temp = 4;\n"
" bool b = compare2(6);\n"
@ -583,7 +596,8 @@ private:
ASSERT_EQUALS("[test.cpp:4]: (style) Comparison of a function returning boolean value using relational (<, >, <= or >=) operator.\n", errout.str());
}
void checkComparisonOfFuncReturningBool5() {
void checkComparisonOfFuncReturningBool5()
{
check("void f(){\n"
" int temp = 4;\n"
" if(compare1(temp) > !compare2(temp)){\n"
@ -607,7 +621,8 @@ private:
ASSERT_EQUALS("[test.cpp:3]: (style) Comparison of two functions returning boolean value using relational (<, >, <= or >=) operator.\n", errout.str());
}
void checkComparisonOfFuncReturningBool6() {
void checkComparisonOfFuncReturningBool6()
{
check("int compare1(int temp);\n"
"namespace Foo {\n"
" bool compare1(int temp);\n"
@ -666,7 +681,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void checkComparisonOfBoolWithBool() {
void checkComparisonOfBoolWithBool()
{
const char code[] = "void f(){\n"
" int temp = 4;\n"
" bool b = compare2(6);\n"
@ -695,7 +711,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void bitwiseOnBoolean() { // 3062
void bitwiseOnBoolean() // 3062
{
check("void f(_Bool a, _Bool b) {\n"
" if(a & b) {}\n"
"}");
@ -761,7 +778,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void incrementBoolean() {
void incrementBoolean()
{
check("bool bValue = true;\n"
"void f() { bValue++; }");
ASSERT_EQUALS("[test.cpp:2]: (style) Incrementing a variable of type 'bool' with postfix operator++ is deprecated by the C++ Standard. You should assign it the value 'true' instead.\n", errout.str());
@ -777,7 +795,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void comparisonOfBoolWithInt1() {
void comparisonOfBoolWithInt1()
{
check("void f(bool x) {\n"
" if (x < 10) {\n"
" printf(\"foo\");\n"
@ -830,7 +849,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void comparisonOfBoolWithInt2() {
void comparisonOfBoolWithInt2()
{
check("void f(bool x, int y) {\n"
" if (x == y) {\n"
" printf(\"foo\");\n"
@ -860,7 +880,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void comparisonOfBoolWithInt3() {
void comparisonOfBoolWithInt3()
{
check("void f(int y) {\n"
" if (y > false) {\n"
" printf(\"foo\");\n"
@ -890,14 +911,16 @@ private:
ASSERT_EQUALS("[test.cpp:2]: (warning) Comparison of a boolean with an integer.\n", errout.str());
}
void comparisonOfBoolWithInt4() {
void comparisonOfBoolWithInt4()
{
check("void f(int x) {\n"
" if (!x == 1) { }\n"
"}");
ASSERT_EQUALS("", errout.str());
}
void comparisonOfBoolWithInt5() {
void comparisonOfBoolWithInt5()
{
check("void SetVisible(int index, bool visible) {\n"
" bool (SciTEBase::*ischarforsel)(char ch);\n"
" if (visible != GetVisible(index)) { }\n"
@ -905,21 +928,24 @@ private:
ASSERT_EQUALS("", errout.str());
}
void comparisonOfBoolWithInt6() { // #4224 - integer is casted to bool
void comparisonOfBoolWithInt6() // #4224 - integer is casted to bool
{
check("void SetVisible(bool b, int i) {\n"
" if (b == (bool)i) { }\n"
"}");
ASSERT_EQUALS("", errout.str());
}
void comparisonOfBoolWithInt7() { // #4846 - (!x==true)
void comparisonOfBoolWithInt7() // #4846 - (!x==true)
{
check("void f(int x) {\n"
" if (!x == true) { }\n"
"}");
ASSERT_EQUALS("", errout.str());
}
void pointerArithBool1() { // #5126
void pointerArithBool1() // #5126
{
check("void f(char *p) {\n"
" if (p+1){}\n"
"}");

View File

@ -27,15 +27,18 @@ extern std::ostringstream errout;
class TestBoost : public TestFixture {
public:
TestBoost() : TestFixture("TestBoost") {
TestBoost() : TestFixture("TestBoost")
{
}
private:
void run() {
void run()
{
TEST_CASE(BoostForeachContainerModification)
}
void check(const char code[]) {
void check(const char code[])
{
// Clear the error buffer..
errout.str("");
@ -58,7 +61,8 @@ private:
checkBoost.runSimplifiedChecks(&tokenizer, &settings, this);
}
void BoostForeachContainerModification() {
void BoostForeachContainerModification()
{
check("void f() {\n"
" vector<int> data;\n"
" BOOST_FOREACH(int i, data) {\n"

File diff suppressed because it is too large Load Diff

View File

@ -26,13 +26,15 @@ extern std::ostringstream errout;
class TestCharVar : public TestFixture {
public:
TestCharVar() : TestFixture("TestCharVar") {
TestCharVar() : TestFixture("TestCharVar")
{
}
private:
void run() {
void run()
{
TEST_CASE(array_index_1);
TEST_CASE(array_index_2);
TEST_CASE(array_index_3);
@ -46,7 +48,8 @@ private:
TEST_CASE(pointer);
}
void check(const char code[]) {
void check(const char code[])
{
// Clear the error buffer..
errout.str("");
@ -63,7 +66,8 @@ private:
checkOther.checkCharVariable();
}
void array_index_1() {
void array_index_1()
{
check("int buf[256];\n"
"void foo()\n"
"{\n"
@ -102,7 +106,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void array_index_2() {
void array_index_2()
{
// #3282 - False positive
check("void foo(char i);\n"
"void bar(int i) {\n"
@ -112,7 +117,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void array_index_3() {
void array_index_3()
{
// only write error message when array is more than
// 0x80 elements in size. Otherwise the full valid
// range is accessible with a char.
@ -135,7 +141,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void bitop1() {
void bitop1()
{
check("void foo()\n"
"{\n"
" int result = 0;\n"
@ -145,7 +152,8 @@ private:
ASSERT_EQUALS("[test.cpp:5]: (warning) When using 'char' variables in bit operations, sign extension can generate unexpected results.\n", errout.str());
}
void bitop2() {
void bitop2()
{
check("void foo()\n"
"{\n"
" char ch;\n"
@ -154,14 +162,16 @@ private:
ASSERT_EQUALS("", errout.str());
}
void bitop3() {
void bitop3()
{
check("void f(int& i, char& c) {\n"
" i &= c;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) When using 'char' variables in bit operations, sign extension can generate unexpected results.\n", errout.str());
}
void bitop4() {
void bitop4()
{
check("long f(char c) {\n"
" long a;\n"
" a = (long)&c;\n"
@ -170,7 +180,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void return1() {
void return1()
{
check("void foo()\n"
"{\n"
" char c;\n"
@ -180,7 +191,8 @@ private:
}
void assignChar() {
void assignChar()
{
check("void foo()\n"
"{\n"
" char c;\n"
@ -189,7 +201,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void and03() {
void and03()
{
check("void foo()\n"
"{\n"
" char c;\n"
@ -198,7 +211,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void pointer() {
void pointer()
{
// ticket #2866
check("void f(char *p) {\n"
" int ret = 0;\n"

File diff suppressed because it is too large Load Diff

View File

@ -26,14 +26,16 @@ class TestCmdlineParser : public TestFixture {
public:
TestCmdlineParser()
: TestFixture("TestCmdlineParser")
, defParser(&settings) {
, defParser(&settings)
{
}
private:
Settings settings;
CmdLineParser defParser;
void run() {
void run()
{
TEST_CASE(nooptions);
TEST_CASE(helpshort);
TEST_CASE(helplong);
@ -142,7 +144,8 @@ private:
}
void nooptions() {
void nooptions()
{
REDIRECT;
const char *argv[] = {"cppcheck"};
CmdLineParser parser(&settings);
@ -150,7 +153,8 @@ private:
ASSERT_EQUALS(true, parser.GetShowHelp());
}
void helpshort() {
void helpshort()
{
REDIRECT;
const char *argv[] = {"cppcheck", "-h"};
CmdLineParser parser(&settings);
@ -158,7 +162,8 @@ private:
ASSERT_EQUALS(true, parser.GetShowHelp());
}
void helplong() {
void helplong()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--help"};
CmdLineParser parser(&settings);
@ -166,7 +171,8 @@ private:
ASSERT_EQUALS(true, parser.GetShowHelp());
}
void showversion() {
void showversion()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--version"};
CmdLineParser parser(&settings);
@ -174,7 +180,8 @@ private:
ASSERT_EQUALS(true, parser.GetShowVersion());
}
void onefile() {
void onefile()
{
REDIRECT;
const char *argv[] = {"cppcheck", "file.cpp"};
CmdLineParser parser(&settings);
@ -183,7 +190,8 @@ private:
ASSERT_EQUALS("file.cpp", parser.GetPathNames().at(0));
}
void onepath() {
void onepath()
{
REDIRECT;
const char *argv[] = {"cppcheck", "src"};
CmdLineParser parser(&settings);
@ -192,7 +200,8 @@ private:
ASSERT_EQUALS("src", parser.GetPathNames().at(0));
}
void optionwithoutfile() {
void optionwithoutfile()
{
REDIRECT;
const char *argv[] = {"cppcheck", "-v"};
CmdLineParser parser(&settings);
@ -200,7 +209,8 @@ private:
ASSERT_EQUALS(0, (int)parser.GetPathNames().size());
}
void verboseshort() {
void verboseshort()
{
REDIRECT;
const char *argv[] = {"cppcheck", "-v", "file.cpp"};
settings._verbose = false;
@ -208,7 +218,8 @@ private:
ASSERT_EQUALS(true, settings._verbose);
}
void verboselong() {
void verboselong()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--verbose", "file.cpp"};
settings._verbose = false;
@ -216,7 +227,8 @@ private:
ASSERT_EQUALS(true, settings._verbose);
}
void debug() {
void debug()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--debug", "file.cpp"};
settings.debug = false;
@ -224,7 +236,8 @@ private:
ASSERT_EQUALS(true, settings.debug);
}
void debugwarnings() {
void debugwarnings()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--debug-warnings", "file.cpp"};
settings.debugwarnings = false;
@ -232,7 +245,8 @@ private:
ASSERT_EQUALS(true, settings.debugwarnings);
}
void forceshort() {
void forceshort()
{
REDIRECT;
const char *argv[] = {"cppcheck", "-f", "file.cpp"};
settings._force = false;
@ -240,7 +254,8 @@ private:
ASSERT_EQUALS(true, settings._force);
}
void forcelong() {
void forcelong()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--force", "file.cpp"};
settings._force = false;
@ -248,7 +263,8 @@ private:
ASSERT_EQUALS(true, settings._force);
}
void relativePaths() {
void relativePaths()
{
REDIRECT;
settings._relativePaths = false;
@ -283,7 +299,8 @@ private:
ASSERT_EQUALS("C:/bar", settings._basePaths[1]);
}
void quietshort() {
void quietshort()
{
REDIRECT;
const char *argv[] = {"cppcheck", "-q", "file.cpp"};
settings._errorsOnly = false;
@ -291,7 +308,8 @@ private:
ASSERT_EQUALS(true, settings._errorsOnly);
}
void quietlong() {
void quietlong()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--quiet", "file.cpp"};
settings._errorsOnly = false;
@ -299,28 +317,32 @@ private:
ASSERT_EQUALS(true, settings._errorsOnly);
}
void defines_noarg() {
void defines_noarg()
{
REDIRECT;
const char *argv[] = {"cppcheck", "-D"};
// Fails since -D has no param
ASSERT_EQUALS(false, defParser.ParseFromArgs(2, argv));
}
void defines_noarg2() {
void defines_noarg2()
{
REDIRECT;
const char *argv[] = {"cppcheck", "-D", "-v", "file.cpp"};
// Fails since -D has no param
ASSERT_EQUALS(false, defParser.ParseFromArgs(4, argv));
}
void defines_noarg3() {
void defines_noarg3()
{
REDIRECT;
const char *argv[] = {"cppcheck", "-D", "--quiet", "file.cpp"};
// Fails since -D has no param
ASSERT_EQUALS(false, defParser.ParseFromArgs(4, argv));
}
void defines() {
void defines()
{
REDIRECT;
const char *argv[] = {"cppcheck", "-D_WIN32", "file.cpp"};
settings.userDefines.clear();
@ -328,7 +350,8 @@ private:
ASSERT_EQUALS("_WIN32=1", settings.userDefines);
}
void defines2() {
void defines2()
{
REDIRECT;
const char *argv[] = {"cppcheck", "-D_WIN32", "-DNODEBUG", "file.cpp"};
settings.userDefines.clear();;
@ -336,7 +359,8 @@ private:
ASSERT_EQUALS("_WIN32=1;NODEBUG=1", settings.userDefines);
}
void defines3() {
void defines3()
{
REDIRECT;
const char *argv[] = {"cppcheck", "-D", "DEBUG", "file.cpp"};
settings.userDefines.clear();
@ -344,7 +368,8 @@ private:
ASSERT_EQUALS("DEBUG=1", settings.userDefines);
}
void defines4() {
void defines4()
{
REDIRECT;
const char *argv[] = {"cppcheck", "-DDEBUG=", "file.cpp"}; // #5137 - defining empty macro
settings.userDefines.clear();
@ -352,7 +377,8 @@ private:
ASSERT_EQUALS("DEBUG=", settings.userDefines);
}
void enforceLanguage() {
void enforceLanguage()
{
REDIRECT;
{
const char *argv[] = {"cppcheck", "file.cpp"};
@ -392,14 +418,16 @@ private:
}
}
void includesnopath() {
void includesnopath()
{
REDIRECT;
const char *argv[] = {"cppcheck", "-I"};
// Fails since -I has no param
ASSERT_EQUALS(false, defParser.ParseFromArgs(2, argv));
}
void includes() {
void includes()
{
REDIRECT;
const char *argv[] = {"cppcheck", "-I", "include", "file.cpp"};
settings._includePaths.clear();
@ -407,7 +435,8 @@ private:
ASSERT_EQUALS("include/", settings._includePaths.front());
}
void includesslash() {
void includesslash()
{
REDIRECT;
const char *argv[] = {"cppcheck", "-I", "include/", "file.cpp"};
settings._includePaths.clear();
@ -415,7 +444,8 @@ private:
ASSERT_EQUALS("include/", settings._includePaths.front());
}
void includesbackslash() {
void includesbackslash()
{
REDIRECT;
const char *argv[] = {"cppcheck", "-I", "include\\", "file.cpp"};
settings._includePaths.clear();
@ -423,7 +453,8 @@ private:
ASSERT_EQUALS("include/", settings._includePaths.front());
}
void includesnospace() {
void includesnospace()
{
REDIRECT;
const char *argv[] = {"cppcheck", "-Iinclude", "file.cpp"};
settings._includePaths.clear();
@ -431,7 +462,8 @@ private:
ASSERT_EQUALS("include/", settings._includePaths.front());
}
void includes2() {
void includes2()
{
REDIRECT;
const char *argv[] = {"cppcheck", "-I", "include/", "-I", "framework/", "file.cpp"};
settings._includePaths.clear();
@ -441,7 +473,8 @@ private:
ASSERT_EQUALS("framework/", settings._includePaths.front());
}
void includesFile() {
void includesFile()
{
// TODO: Fails since cannot open the file
REDIRECT;
const char *argv[] = {"cppcheck", "--includes-file=inclpaths.txt", "file.cpp"};
@ -449,7 +482,8 @@ private:
ASSERT_EQUALS(true, defParser.ParseFromArgs(3, argv));
}
void enabledAll() {
void enabledAll()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--enable=all", "file.cpp"};
settings = Settings();
@ -461,7 +495,8 @@ private:
ASSERT(!settings.isEnabled("internal"));
}
void enabledStyle() {
void enabledStyle()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--enable=style", "file.cpp"};
settings = Settings();
@ -474,7 +509,8 @@ private:
ASSERT(!settings.isEnabled("missingInclude"));
}
void enabledPerformance() {
void enabledPerformance()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--enable=performance", "file.cpp"};
settings = Settings();
@ -487,7 +523,8 @@ private:
ASSERT(!settings.isEnabled("missingInclude"));
}
void enabledPortability() {
void enabledPortability()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--enable=portability", "file.cpp"};
settings = Settings();
@ -500,7 +537,8 @@ private:
ASSERT(!settings.isEnabled("missingInclude"));
}
void enabledUnusedFunction() {
void enabledUnusedFunction()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--enable=unusedFunction", "file.cpp"};
settings = Settings();
@ -508,7 +546,8 @@ private:
ASSERT(settings.isEnabled("unusedFunction"));
}
void enabledMissingInclude() {
void enabledMissingInclude()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--enable=missingInclude", "file.cpp"};
settings = Settings();
@ -517,7 +556,8 @@ private:
}
#ifdef CHECK_INTERNAL
void enabledInternal() {
void enabledInternal()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--enable=internal", "file.cpp"};
settings = Settings();
@ -526,7 +566,8 @@ private:
}
#endif
void enabledMultiple() {
void enabledMultiple()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--enable=missingInclude,portability,warning", "file.cpp"};
settings = Settings();
@ -539,7 +580,8 @@ private:
ASSERT(settings.isEnabled("missingInclude"));
}
void inconclusive() {
void inconclusive()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--inconclusive"};
settings.inconclusive = false;
@ -547,7 +589,8 @@ private:
ASSERT_EQUALS(true, settings.inconclusive);
}
void errorExitcode() {
void errorExitcode()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--error-exitcode=5", "file.cpp"};
settings._exitCode = 0;
@ -555,7 +598,8 @@ private:
ASSERT_EQUALS(5, settings._exitCode);
}
void errorExitcodeMissing() {
void errorExitcodeMissing()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--error-exitcode=", "file.cpp"};
settings._exitCode = 0;
@ -563,7 +607,8 @@ private:
ASSERT_EQUALS(false, defParser.ParseFromArgs(3, argv));
}
void errorExitcodeStr() {
void errorExitcodeStr()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--error-exitcode=foo", "file.cpp"};
settings._exitCode = 0;
@ -571,7 +616,8 @@ private:
ASSERT_EQUALS(false, defParser.ParseFromArgs(3, argv));
}
void exitcodeSuppressionsOld() {
void exitcodeSuppressionsOld()
{
// TODO: Fails since cannot open the file
REDIRECT;
const char *argv[] = {"cppcheck", "--exitcode-suppressions", "suppr.txt", "file.cpp"};
@ -579,7 +625,8 @@ private:
TODO_ASSERT_EQUALS(true, false, defParser.ParseFromArgs(4, argv));
}
void exitcodeSuppressions() {
void exitcodeSuppressions()
{
// TODO: Fails since cannot open the file
REDIRECT;
const char *argv[] = {"cppcheck", "--exitcode-suppressions=suppr.txt", "file.cpp"};
@ -587,7 +634,8 @@ private:
TODO_ASSERT_EQUALS(true, false, defParser.ParseFromArgs(3, argv));
}
void exitcodeSuppressionsNoFile() {
void exitcodeSuppressionsNoFile()
{
// TODO: Fails since cannot open the file
REDIRECT;
const char *argv[] = {"cppcheck", "--exitcode-suppressions", "file.cpp"};
@ -595,7 +643,8 @@ private:
TODO_ASSERT_EQUALS(true, false, defParser.ParseFromArgs(3, argv));
}
void fileList() {
void fileList()
{
// TODO: Fails since cannot open the file
REDIRECT;
const char *argv[] = {"cppcheck", "--file-list", "files.txt", "file.cpp"};
@ -610,13 +659,15 @@ private:
TODO_ASSERT_EQUALS(true, false, defParser.ParseFromArgs(3, argv));
} */
void inlineSuppr() {
void inlineSuppr()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--inline-suppr", "file.cpp"};
ASSERT(defParser.ParseFromArgs(3, argv));
}
void jobs() {
void jobs()
{
REDIRECT;
const char *argv[] = {"cppcheck", "-j", "3", "file.cpp"};
settings._jobs = 0;
@ -624,7 +675,8 @@ private:
ASSERT_EQUALS(3, settings._jobs);
}
void jobsMissingCount() {
void jobsMissingCount()
{
REDIRECT;
const char *argv[] = {"cppcheck", "-j", "file.cpp"};
settings._jobs = 0;
@ -632,7 +684,8 @@ private:
ASSERT_EQUALS(false, defParser.ParseFromArgs(3, argv));
}
void jobsInvalid() {
void jobsInvalid()
{
REDIRECT;
const char *argv[] = {"cppcheck", "-j", "e", "file.cpp"};
settings._jobs = 0;
@ -640,7 +693,8 @@ private:
ASSERT_EQUALS(false, defParser.ParseFromArgs(4, argv));
}
void maxConfigs() {
void maxConfigs()
{
REDIRECT;
const char *argv[] = {"cppcheck", "-f", "--max-configs=12", "file.cpp"};
settings._force = false;
@ -650,28 +704,32 @@ private:
ASSERT_EQUALS(false, settings._force);
}
void maxConfigsMissingCount() {
void maxConfigsMissingCount()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--max-configs=", "file.cpp"};
// Fails since --max-configs= is missing limit
ASSERT_EQUALS(false, defParser.ParseFromArgs(3, argv));
}
void maxConfigsInvalid() {
void maxConfigsInvalid()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--max-configs=e", "file.cpp"};
// Fails since invalid count given for --max-configs=
ASSERT_EQUALS(false, defParser.ParseFromArgs(3, argv));
}
void maxConfigsTooSmall() {
void maxConfigsTooSmall()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--max-configs=0", "file.cpp"};
// Fails since limit must be greater than 0
ASSERT_EQUALS(false, defParser.ParseFromArgs(3, argv));
}
void reportProgressTest() {
void reportProgressTest()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--report-progress", "file.cpp"};
settings.reportProgress = false;
@ -679,7 +737,8 @@ private:
ASSERT(settings.reportProgress);
}
void stdposix() {
void stdposix()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--std=posix", "file.cpp"};
settings.standards.posix = false;
@ -687,7 +746,8 @@ private:
ASSERT(settings.standards.posix);
}
void stdc99() {
void stdc99()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--std=c99", "file.cpp"};
settings.standards.c = Standards::C89;
@ -695,7 +755,8 @@ private:
ASSERT(settings.standards.c == Standards::C99);
}
void stdcpp11() {
void stdcpp11()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--std=c++11", "file.cpp"};
settings.standards.cpp = Standards::CPP03;
@ -703,7 +764,8 @@ private:
ASSERT(settings.standards.cpp == Standards::CPP11);
}
void platform() {
void platform()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--platform=win64", "file.cpp"};
settings.platform(Settings::Unspecified);
@ -711,21 +773,24 @@ private:
ASSERT(settings.platformType == Settings::Win64);
}
void suppressionsOld() {
void suppressionsOld()
{
// TODO: Fails because there is no suppr.txt file!
REDIRECT;
const char *argv[] = {"cppcheck", "--suppressions", "suppr.txt", "file.cpp"};
ASSERT(!defParser.ParseFromArgs(4, argv));
}
void suppressions() {
void suppressions()
{
// TODO: Fails because there is no suppr.txt file!
REDIRECT;
const char *argv[] = {"cppcheck", "--suppressions-list=suppr.txt", "file.cpp"};
TODO_ASSERT_EQUALS(true, false, defParser.ParseFromArgs(3, argv));
}
void suppressionsNoFile() {
void suppressionsNoFile()
{
REDIRECT;
{
CLEAR_REDIRECT_OUTPUT;
@ -749,7 +814,8 @@ private:
}
}
void suppressionSingle() {
void suppressionSingle()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--suppress=uninitvar", "file.cpp"};
settings = Settings();
@ -757,7 +823,8 @@ private:
ASSERT_EQUALS(true, settings.nomsg.isSuppressed("uninitvar", "file.cpp", 1U));
}
void suppressionSingleFile() {
void suppressionSingleFile()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--suppress=uninitvar:file.cpp", "file.cpp"};
settings = Settings();
@ -765,7 +832,8 @@ private:
ASSERT_EQUALS(true, settings.nomsg.isSuppressed("uninitvar", "file.cpp", 1U));
}
void suppressionTwo() {
void suppressionTwo()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--suppress=uninitvar,unnecessaryQualification", "file.cpp"};
settings = Settings();
@ -774,7 +842,8 @@ private:
TODO_ASSERT_EQUALS(true, false, settings.nomsg.isSuppressed("unnecessaryQualification", "file.cpp", 1U));
}
void suppressionTwoSeparate() {
void suppressionTwoSeparate()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--suppress=uninitvar", "--suppress=unnecessaryQualification", "file.cpp"};
settings = Settings();
@ -783,7 +852,8 @@ private:
ASSERT_EQUALS(true, settings.nomsg.isSuppressed("unnecessaryQualification", "file.cpp", 1U));
}
void templates() {
void templates()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--template", "{file}:{line},{severity},{id},{message}", "file.cpp"};
settings._outputFormat.clear();
@ -791,7 +861,8 @@ private:
ASSERT_EQUALS("{file}:{line},{severity},{id},{message}", settings._outputFormat);
}
void templatesGcc() {
void templatesGcc()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--template", "gcc", "file.cpp"};
settings._outputFormat.clear();
@ -799,7 +870,8 @@ private:
ASSERT_EQUALS("{file}:{line}: {severity}: {message}", settings._outputFormat);
}
void templatesVs() {
void templatesVs()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--template", "vs", "file.cpp"};
settings._outputFormat.clear();
@ -807,7 +879,8 @@ private:
ASSERT_EQUALS("{file}({line}): {severity}: {message}", settings._outputFormat);
}
void templatesEdit() {
void templatesEdit()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--template", "edit", "file.cpp"};
settings._outputFormat.clear();
@ -815,7 +888,8 @@ private:
ASSERT_EQUALS("{file} +{line}: {severity}: {message}", settings._outputFormat);
}
void xml() {
void xml()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--xml", "file.cpp"};
settings._xml_version = 1;
@ -825,7 +899,8 @@ private:
ASSERT_EQUALS(1, settings._xml_version);
}
void xmlver1() {
void xmlver1()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--xml-version=1", "file.cpp"};
settings._xml_version = 1;
@ -835,7 +910,8 @@ private:
ASSERT_EQUALS(1, settings._xml_version);
}
void xmlver2() {
void xmlver2()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--xml-version=2", "file.cpp"};
settings._xml_version = 1;
@ -845,7 +921,8 @@ private:
ASSERT_EQUALS(2, settings._xml_version);
}
void xmlver2both() {
void xmlver2both()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--xml", "--xml-version=2", "file.cpp"};
settings._xml_version = 1;
@ -855,7 +932,8 @@ private:
ASSERT_EQUALS(2, settings._xml_version);
}
void xmlver2both2() {
void xmlver2both2()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--xml-version=2", "--xml", "file.cpp"};
settings._xml_version = 1;
@ -865,28 +943,32 @@ private:
ASSERT_EQUALS(2, settings._xml_version);
}
void xmlverunknown() {
void xmlverunknown()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--xml", "--xml-version=3", "file.cpp"};
// FAils since unknown XML format version
ASSERT_EQUALS(false, defParser.ParseFromArgs(4, argv));
}
void xmlverinvalid() {
void xmlverinvalid()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--xml", "--xml-version=a", "file.cpp"};
// FAils since unknown XML format version
ASSERT_EQUALS(false, defParser.ParseFromArgs(4, argv));
}
void doc() {
void doc()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--doc"};
ASSERT(defParser.ParseFromArgs(2, argv));
ASSERT(defParser.ExitAfterPrinting());
}
void showtime() {
void showtime()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--showtime=summary"};
settings._showtime = SHOWTIME_NONE;
@ -894,14 +976,16 @@ private:
ASSERT(settings._showtime == SHOWTIME_SUMMARY);
}
void errorlist1() {
void errorlist1()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--errorlist"};
ASSERT(defParser.ParseFromArgs(2, argv));
ASSERT(defParser.GetShowErrorMessages());
}
void errorlistverbose1() {
void errorlistverbose1()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--verbose", "--errorlist"};
settings._verbose = false;
@ -909,7 +993,8 @@ private:
ASSERT(settings._verbose);
}
void errorlistverbose2() {
void errorlistverbose2()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--errorlist", "--verbose"};
settings._verbose = false;
@ -917,7 +1002,8 @@ private:
ASSERT(settings._verbose);
}
void ignorepathsnopath() {
void ignorepathsnopath()
{
REDIRECT;
const char *argv[] = {"cppcheck", "-i"};
CmdLineParser parser(&settings);
@ -926,7 +1012,8 @@ private:
ASSERT_EQUALS(0, parser.GetIgnoredPaths().size());
}
void ignorepaths1() {
void ignorepaths1()
{
REDIRECT;
const char *argv[] = {"cppcheck", "-isrc", "file.cpp"};
CmdLineParser parser(&settings);
@ -935,7 +1022,8 @@ private:
ASSERT_EQUALS("src/", parser.GetIgnoredPaths()[0]);
}
void ignorepaths2() {
void ignorepaths2()
{
REDIRECT;
const char *argv[] = {"cppcheck", "-i", "src", "file.cpp"};
CmdLineParser parser(&settings);
@ -944,7 +1032,8 @@ private:
ASSERT_EQUALS("src/", parser.GetIgnoredPaths()[0]);
}
void ignorepaths3() {
void ignorepaths3()
{
REDIRECT;
const char *argv[] = {"cppcheck", "-isrc", "-imodule", "file.cpp"};
CmdLineParser parser(&settings);
@ -954,7 +1043,8 @@ private:
ASSERT_EQUALS("module/", parser.GetIgnoredPaths()[1]);
}
void ignorepaths4() {
void ignorepaths4()
{
REDIRECT;
const char *argv[] = {"cppcheck", "-i", "src", "-i", "module", "file.cpp"};
CmdLineParser parser(&settings);
@ -964,7 +1054,8 @@ private:
ASSERT_EQUALS("module/", parser.GetIgnoredPaths()[1]);
}
void ignorefilepaths1() {
void ignorefilepaths1()
{
REDIRECT;
const char *argv[] = {"cppcheck", "-ifoo.cpp", "file.cpp"};
CmdLineParser parser(&settings);
@ -973,7 +1064,8 @@ private:
ASSERT_EQUALS("foo.cpp", parser.GetIgnoredPaths()[0]);
}
void ignorefilepaths2() {
void ignorefilepaths2()
{
REDIRECT;
const char *argv[] = {"cppcheck", "-isrc/foo.cpp", "file.cpp"};
CmdLineParser parser(&settings);
@ -982,7 +1074,8 @@ private:
ASSERT_EQUALS("src/foo.cpp", parser.GetIgnoredPaths()[0]);
}
void checkconfig() {
void checkconfig()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--check-config", "file.cpp"};
settings.checkConfiguration = false;
@ -990,13 +1083,15 @@ private:
ASSERT_EQUALS(true, settings.checkConfiguration);
}
void unknownParam() {
void unknownParam()
{
REDIRECT;
const char *argv[] = {"cppcheck", "--foo", "file.cpp"};
ASSERT(!defParser.ParseFromArgs(3, argv));
}
void undefs() {
void undefs()
{
REDIRECT;
const char *argv[] = {"cppcheck", "-U_WIN32", "file.cpp"};
settings = Settings();
@ -1005,7 +1100,8 @@ private:
ASSERT(settings.userUndefs.find("_WIN32") != settings.userUndefs.end());
}
void undefs2() {
void undefs2()
{
REDIRECT;
const char *argv[] = {"cppcheck", "-U_WIN32", "-UNODEBUG", "file.cpp"};
settings = Settings();
@ -1015,21 +1111,24 @@ private:
ASSERT(settings.userUndefs.find("NODEBUG") != settings.userUndefs.end());
}
void undefs_noarg() {
void undefs_noarg()
{
REDIRECT;
const char *argv[] = {"cppcheck", "-U"};
// Fails since -U has no param
ASSERT_EQUALS(false, defParser.ParseFromArgs(2, argv));
}
void undefs_noarg2() {
void undefs_noarg2()
{
REDIRECT;
const char *argv[] = {"cppcheck", "-U", "-v", "file.cpp"};
// Fails since -U has no param
ASSERT_EQUALS(false, defParser.ParseFromArgs(4, argv));
}
void undefs_noarg3() {
void undefs_noarg3()
{
REDIRECT;
const char *argv[] = {"cppcheck", "-U", "--quiet", "file.cpp"};
// Fails since -U has no param

View File

@ -26,13 +26,15 @@ extern std::ostringstream errout;
class TestCondition : public TestFixture {
public:
TestCondition() : TestFixture("TestCondition") {
TestCondition() : TestFixture("TestCondition")
{
}
private:
void run() {
void run()
{
TEST_CASE(assignAndCompare); // assignment and comparison don't match
TEST_CASE(mismatchingBitAnd); // overlapping bitmasks
TEST_CASE(compare); // mismatching LHS/RHS in comparison
@ -62,7 +64,8 @@ private:
TEST_CASE(clarifyCondition6); // #3818
}
void check(const char code[], bool validate=true, const char* filename = "test.cpp") {
void check(const char code[], bool validate=true, const char* filename = "test.cpp")
{
// Clear the error buffer..
errout.str("");
@ -88,7 +91,8 @@ private:
}
}
void assignAndCompare() {
void assignAndCompare()
{
// &
check("void foo(int x)\n"
"{\n"
@ -256,7 +260,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void mismatchingBitAnd() {
void mismatchingBitAnd()
{
check("void f(int a) {\n"
" int b = a & 0xf0;\n"
" b &= 1;\n"
@ -279,7 +284,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void compare() {
void compare()
{
check("void foo(int x)\n"
"{\n"
" if ((x & 4) == 3);\n"
@ -305,7 +311,8 @@ private:
ASSERT_EQUALS("[test.cpp:3]: (style) Expression '(X & 0x4) == 0x3' is always false.\n", errout.str());
}
void multicompare() {
void multicompare()
{
check("void foo(int x)\n"
"{\n"
" if (x & 7);\n"
@ -321,7 +328,8 @@ private:
ASSERT_EQUALS("[test.cpp:4]: (style) Expression is always false because 'else if' condition matches previous condition at line 3.\n", errout.str());
}
void duplicateIf() {
void duplicateIf()
{
check("void f(int a, int &b) {\n"
" if (a) { b = 1; }\n"
" else { if (a) { b = 2; } }\n"
@ -403,7 +411,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void invalidMissingSemicolon() {
void invalidMissingSemicolon()
{
// simply survive - a syntax error would be even better
check("void f(int x) {\n"
" x = 42\n"
@ -412,7 +421,8 @@ private:
}
void incorrectLogicOperator1() {
void incorrectLogicOperator1()
{
check("void f(int x) {\n"
" if ((x != 1) || (x != 3))\n"
" a++;\n"
@ -507,7 +517,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void incorrectLogicOperator2() {
void incorrectLogicOperator2()
{
check("void f(float x) {\n"
" if ((x == 1) && (x == 1.0))\n"
" a++;\n"
@ -727,7 +738,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void incorrectLogicOperator3() {
void incorrectLogicOperator3()
{
check("void f(int x, bool& b) {\n"
" b = x > 5 && x == 1;\n"
" c = x < 1 && x == 3;\n"
@ -740,21 +752,24 @@ private:
"[test.cpp:5]: (warning) Logical conjunction always evaluates to false: x <= 1 && x == 3.\n", errout.str());
}
void incorrectLogicOperator4() {
void incorrectLogicOperator4()
{
check("void f(int x) {\n"
" if (x && x != $0) {}\n"
"}");
ASSERT_EQUALS("", errout.str());
}
void incorrectLogicOperator5() { // complex expressions
void incorrectLogicOperator5() // complex expressions
{
check("void f(int x) {\n"
" if (x+3 > 2 || x+3 < 10) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical disjunction always evaluates to true: EXPR > 2 || EXPR < 10.\n", errout.str());
}
void incorrectLogicOperator6() { // char literals
void incorrectLogicOperator6() // char literals
{
check("void f(char x) {\n"
" if (x == '1' || x == '2') {}\n"
"}");
@ -766,14 +781,16 @@ private:
TODO_ASSERT_EQUALS("error", "", errout.str());
}
void incorrectLogicOperator7() { // opposite expressions
void incorrectLogicOperator7() // opposite expressions
{
check("void f(int i) {\n"
" if (i || !i) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical disjunction always evaluates to true: i||!i.\n", errout.str());
}
void secondAlwaysTrueFalseWhenFirstTrueError() {
void secondAlwaysTrueFalseWhenFirstTrueError()
{
check("void f(int x) {\n"
" if (x > 5 && x != 1)\n"
" a++;\n"
@ -836,7 +853,8 @@ private:
"[test.cpp:5]: (style) Redundant condition: If x < 5, the comparison x < 6 is always true.\n", errout.str());
}
void incorrectLogicOp_condSwapping() {
void incorrectLogicOp_condSwapping()
{
check("void f(int x) {\n"
" if (x < 1 && x > 3)\n"
" a++;\n"
@ -886,7 +904,8 @@ private:
ASSERT_EQUALS("[test.cpp:2]: (warning) Logical conjunction always evaluates to false: x > 3 && x < 1.\n", errout.str());
}
void modulo() {
void modulo()
{
check("bool f(bool& b1, bool& b2, bool& b3) {\n"
" b1 = a % 5 == 4;\n"
" b2 = a % c == 100000;\n"
@ -926,7 +945,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void oppositeInnerCondition() {
void oppositeInnerCondition()
{
check("void foo(int a, int b) {\n"
" if(a==b)\n"
" if(a!=b)\n"
@ -1092,7 +1112,8 @@ private:
}
// clarify conditions with = and comparison
void clarifyCondition1() {
void clarifyCondition1()
{
check("void f() {\n"
" if (x = b() < 0) {}\n" // don't simplify and verify this code
"}", false);
@ -1111,7 +1132,8 @@ private:
}
// clarify conditions with bitwise operator and comparison
void clarifyCondition2() {
void clarifyCondition2()
{
check("void f() {\n"
" if (x & 3 == 2) {}\n"
"}");
@ -1124,7 +1146,8 @@ private:
}
// clarify condition that uses ! operator and then bitwise operator
void clarifyCondition3() {
void clarifyCondition3()
{
check("void f(int w) {\n"
" if(!w & 0x8000) {}\n"
"}");
@ -1153,7 +1176,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void clarifyCondition4() { // ticket #3110
void clarifyCondition4() // ticket #3110
{
check("typedef double SomeType;\n"
"typedef std::pair<std::string,SomeType> PairType;\n"
"struct S\n"
@ -1168,12 +1192,14 @@ private:
ASSERT_EQUALS("", errout.str());
}
void clarifyCondition5() { // ticket #3609 (using | in template instantiation)
void clarifyCondition5() // ticket #3609 (using | in template instantiation)
{
check("CWinTraits<WS_CHILD|WS_VISIBLE>::GetWndStyle(0);");
ASSERT_EQUALS("", errout.str());
}
void clarifyCondition6() {
void clarifyCondition6()
{
check("template<class Y>\n"
"SharedPtr& operator=( SharedPtr<Y> const & r ) {\n"
" px = r.px;\n"

File diff suppressed because it is too large Load Diff

View File

@ -32,7 +32,8 @@ extern std::ostringstream output;
class TestCppcheck : public TestFixture {
public:
TestCppcheck() : TestFixture("TestCppcheck") {
TestCppcheck() : TestFixture("TestCppcheck")
{
}
private:
@ -41,21 +42,25 @@ private:
public:
std::list<std::string> id;
void reportOut(const std::string & /*outmsg*/) {
void reportOut(const std::string & /*outmsg*/)
{
}
void reportErr(const ErrorLogger::ErrorMessage &msg) {
void reportErr(const ErrorLogger::ErrorMessage &msg)
{
id.push_back(msg._id);
}
};
void run() {
void run()
{
TEST_CASE(instancesSorted);
TEST_CASE(classInfoFormat);
TEST_CASE(getErrorMessages);
}
void instancesSorted() const {
void instancesSorted() const
{
for (std::list<Check *>::const_iterator i = Check::instances().begin(); i != Check::instances().end(); ++i) {
std::list<Check *>::const_iterator j = i;
++j;
@ -65,7 +70,8 @@ private:
}
}
void classInfoFormat() const {
void classInfoFormat() const
{
for (std::list<Check *>::const_iterator i = Check::instances().begin(); i != Check::instances().end(); ++i) {
const std::string info = (*i)->classInfo();
if (!info.empty()) {
@ -77,7 +83,8 @@ private:
}
}
void getErrorMessages() const {
void getErrorMessages() const
{
ErrorLogger2 errorLogger;
CppCheck cppCheck(errorLogger, true);
cppCheck.getErrorMessages();

View File

@ -23,14 +23,16 @@
class TestErrorLogger : public TestFixture {
public:
TestErrorLogger() : TestFixture("TestErrorLogger"), fooCpp5("foo.cpp", 5), barCpp8("bar.cpp", 8) {
TestErrorLogger() : TestFixture("TestErrorLogger"), fooCpp5("foo.cpp", 5), barCpp8("bar.cpp", 8)
{
}
private:
const ErrorLogger::ErrorMessage::FileLocation fooCpp5;
const ErrorLogger::ErrorMessage::FileLocation barCpp8;
void run() {
void run()
{
TEST_CASE(FileLocationDefaults);
TEST_CASE(FileLocationSetFile);
TEST_CASE(ErrorMessageConstruct);
@ -57,20 +59,23 @@ private:
TEST_CASE(suppressUnmatchedSuppressions);
}
void FileLocationDefaults() const {
void FileLocationDefaults() const
{
ErrorLogger::ErrorMessage::FileLocation loc;
ASSERT_EQUALS("", loc.getfile());
ASSERT_EQUALS(0, loc.line);
}
void FileLocationSetFile() const {
void FileLocationSetFile() const
{
ErrorLogger::ErrorMessage::FileLocation loc;
loc.setfile("foo.cpp");
ASSERT_EQUALS("foo.cpp", loc.getfile());
ASSERT_EQUALS(0, loc.line);
}
void ErrorMessageConstruct() const {
void ErrorMessageConstruct() const
{
std::list<ErrorLogger::ErrorMessage::FileLocation> locs(1, fooCpp5);
ErrorMessage msg(locs, Severity::error, "Programming error.", "errorId", false);
ASSERT_EQUALS(1, (int)msg._callStack.size());
@ -80,7 +85,8 @@ private:
ASSERT_EQUALS("[foo.cpp:5]: (error) Programming error.", msg.toString(true));
}
void ErrorMessageConstructLocations() const {
void ErrorMessageConstructLocations() const
{
std::list<ErrorLogger::ErrorMessage::FileLocation> locs;
locs.push_back(fooCpp5);
locs.push_back(barCpp8);
@ -92,7 +98,8 @@ private:
ASSERT_EQUALS("[foo.cpp:5] -> [bar.cpp:8]: (error) Programming error.", msg.toString(true));
}
void ErrorMessageVerbose() const {
void ErrorMessageVerbose() const
{
std::list<ErrorLogger::ErrorMessage::FileLocation> locs(1, fooCpp5);
ErrorMessage msg(locs, Severity::error, "Programming error.\nVerbose error", "errorId", false);
ASSERT_EQUALS(1, (int)msg._callStack.size());
@ -102,7 +109,8 @@ private:
ASSERT_EQUALS("[foo.cpp:5]: (error) Verbose error", msg.toString(true));
}
void ErrorMessageVerboseLocations() const {
void ErrorMessageVerboseLocations() const
{
std::list<ErrorLogger::ErrorMessage::FileLocation> locs;
locs.push_back(fooCpp5);
locs.push_back(barCpp8);
@ -114,7 +122,8 @@ private:
ASSERT_EQUALS("[foo.cpp:5] -> [bar.cpp:8]: (error) Verbose error", msg.toString(true));
}
void CustomFormat() const {
void CustomFormat() const
{
std::list<ErrorLogger::ErrorMessage::FileLocation> locs(1, fooCpp5);
ErrorMessage msg(locs, Severity::error, "Programming error.\nVerbose error", "errorId", false);
ASSERT_EQUALS(1, (int)msg._callStack.size());
@ -124,7 +133,8 @@ private:
ASSERT_EQUALS("foo.cpp:5,error,errorId,Verbose error", msg.toString(true, "{file}:{line},{severity},{id},{message}"));
}
void CustomFormat2() const {
void CustomFormat2() const
{
std::list<ErrorLogger::ErrorMessage::FileLocation> locs(1, fooCpp5);
ErrorMessage msg(locs, Severity::error, "Programming error.\nVerbose error", "errorId", false);
ASSERT_EQUALS(1, (int)msg._callStack.size());
@ -134,7 +144,8 @@ private:
ASSERT_EQUALS("Verbose error - foo.cpp(5):(error,errorId)", msg.toString(true, "{message} - {file}({line}):({severity},{id})"));
}
void CustomFormatLocations() const {
void CustomFormatLocations() const
{
// Check that first location from location stack is used in template
std::list<ErrorLogger::ErrorMessage::FileLocation> locs;
locs.push_back(fooCpp5);
@ -147,7 +158,8 @@ private:
ASSERT_EQUALS("Verbose error - bar.cpp(8):(error,errorId)", msg.toString(true, "{message} - {file}({line}):({severity},{id})"));
}
void ToXml() const {
void ToXml() const
{
std::list<ErrorLogger::ErrorMessage::FileLocation> locs(1, fooCpp5);
ErrorMessage msg(locs, Severity::error, "Programming error.\nVerbose error", "errorId", false);
ASSERT_EQUALS("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<results>", ErrorLogger::ErrorMessage::getXMLHeader(1));
@ -155,7 +167,8 @@ private:
ASSERT_EQUALS(" <error file=\"foo.cpp\" line=\"5\" id=\"errorId\" severity=\"error\" msg=\"Programming error.\"/>", msg.toXML(false,1));
}
void ToXmlLocations() const {
void ToXmlLocations() const
{
std::list<ErrorLogger::ErrorMessage::FileLocation> locs;
locs.push_back(fooCpp5);
locs.push_back(barCpp8);
@ -165,7 +178,8 @@ private:
ASSERT_EQUALS(" <error file=\"bar.cpp\" line=\"8\" id=\"errorId\" severity=\"error\" msg=\"Programming error.\"/>", msg.toXML(false,1));
}
void ToVerboseXml() const {
void ToVerboseXml() const
{
std::list<ErrorLogger::ErrorMessage::FileLocation> locs(1, fooCpp5);
ErrorMessage msg(locs, Severity::error, "Programming error.\nVerbose error", "errorId", false);
ASSERT_EQUALS("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<results>", ErrorLogger::ErrorMessage::getXMLHeader(1));
@ -173,7 +187,8 @@ private:
ASSERT_EQUALS(" <error file=\"foo.cpp\" line=\"5\" id=\"errorId\" severity=\"error\" msg=\"Verbose error\"/>", msg.toXML(true,1));
}
void ToVerboseXmlLocations() const {
void ToVerboseXmlLocations() const
{
std::list<ErrorLogger::ErrorMessage::FileLocation> locs;
locs.push_back(fooCpp5);
locs.push_back(barCpp8);
@ -183,7 +198,8 @@ private:
ASSERT_EQUALS(" <error file=\"bar.cpp\" line=\"8\" id=\"errorId\" severity=\"error\" msg=\"Verbose error\"/>", msg.toXML(true,1));
}
void ToXmlV2() const {
void ToXmlV2() const
{
std::list<ErrorLogger::ErrorMessage::FileLocation> locs(1, fooCpp5);
ErrorMessage msg(locs, Severity::error, "Programming error.\nVerbose error", "errorId", false);
std::string header("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<results version=\"2\">\n");
@ -198,7 +214,8 @@ private:
ASSERT_EQUALS(message, msg.toXML(false, 2));
}
void ToXmlV2Locations() const {
void ToXmlV2Locations() const
{
std::list<ErrorLogger::ErrorMessage::FileLocation> locs;
locs.push_back(fooCpp5);
locs.push_back(barCpp8);
@ -216,14 +233,16 @@ private:
ASSERT_EQUALS(message, msg.toXML(false, 2));
}
void ToXmlV2Encoding() const {
void ToXmlV2Encoding() const
{
std::list<ErrorLogger::ErrorMessage::FileLocation> locs;
ErrorMessage msg(locs, Severity::error, "Programming error.\nComparing \"\203\" with \"\003\"", "errorId", false);
const std::string message(" <error id=\"errorId\" severity=\"error\" msg=\"Programming error.\" verbose=\"Comparing &quot;\\203&quot; with &quot;\\003&quot;\"/>");
ASSERT_EQUALS(message, msg.toXML(false, 2));
}
void InconclusiveXml() const {
void InconclusiveXml() const
{
// Location
std::list<ErrorLogger::ErrorMessage::FileLocation> locs(1, fooCpp5);
@ -240,7 +259,8 @@ private:
msg.toXML(false, 2));
}
void SerializeInconclusiveMessage() const {
void SerializeInconclusiveMessage() const
{
// Inconclusive error message
std::list<ErrorLogger::ErrorMessage::FileLocation> locs;
ErrorMessage msg(locs, Severity::error, "Programming error", "errorId", true);
@ -260,7 +280,8 @@ private:
ASSERT_EQUALS("Programming error", msg2.verboseMessage());
}
void suppressUnmatchedSuppressions() {
void suppressUnmatchedSuppressions()
{
std::list<Suppressions::SuppressionEntry> suppressions;
// No unmatched suppression

View File

@ -26,12 +26,14 @@ extern std::ostringstream errout;
class TestExceptionSafety : public TestFixture {
public:
TestExceptionSafety() : TestFixture("TestExceptionSafety") {
TestExceptionSafety() : TestFixture("TestExceptionSafety")
{
}
private:
void run() {
void run()
{
TEST_CASE(destructors);
TEST_CASE(deallocThrow1);
TEST_CASE(deallocThrow2);
@ -51,7 +53,8 @@ private:
TEST_CASE(nothrowDeclspecThrow);
}
void check(const char code[], bool inconclusive = false) {
void check(const char code[], bool inconclusive = false)
{
// Clear the error buffer..
errout.str("");
@ -69,7 +72,8 @@ private:
checkExceptionSafety.runSimplifiedChecks(&tokenizer, &settings, this);
}
void destructors() {
void destructors()
{
check("class x {\n"
" ~x() {\n"
" throw e;\n"
@ -111,7 +115,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void deallocThrow1() {
void deallocThrow1()
{
check("int * p;\n"
"void f(int x) {\n"
" delete p;\n"
@ -131,7 +136,8 @@ private:
ASSERT_EQUALS("[test.cpp:5]: (warning) Exception thrown in invalid state, 'p' points at deallocated memory.\n", errout.str());
}
void deallocThrow2() {
void deallocThrow2()
{
check("void f() {\n"
" int* p = 0;\n"
" delete p;\n"
@ -150,7 +156,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void deallocThrow3() {
void deallocThrow3()
{
check("void f() {\n"
" static int* p = 0;\n"
" delete p;\n"
@ -166,7 +173,8 @@ private:
ASSERT_EQUALS("[test.cpp:4]: (warning) Exception thrown in invalid state, 'p' points at deallocated memory.\n", errout.str());
}
void rethrowCopy1() {
void rethrowCopy1()
{
check("void f() {\n"
" try\n"
" {\n"
@ -180,7 +188,8 @@ private:
ASSERT_EQUALS("[test.cpp:8]: (style) Throwing a copy of the caught exception instead of rethrowing the original exception.\n", errout.str());
}
void rethrowCopy2() {
void rethrowCopy2()
{
check("void f() {\n"
" try\n"
" {\n"
@ -194,7 +203,8 @@ private:
ASSERT_EQUALS("[test.cpp:8]: (style) Throwing a copy of the caught exception instead of rethrowing the original exception.\n", errout.str());
}
void rethrowCopy3() {
void rethrowCopy3()
{
check("void f() {\n"
" try {\n"
" foo();\n"
@ -206,7 +216,8 @@ private:
ASSERT_EQUALS("[test.cpp:6]: (style) Throwing a copy of the caught exception instead of rethrowing the original exception.\n", errout.str());
}
void rethrowCopy4() {
void rethrowCopy4()
{
check("void f() {\n"
" try\n"
" {\n"
@ -221,7 +232,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void rethrowCopy5() {
void rethrowCopy5()
{
check("void f() {\n"
" try {\n"
" foo();\n"
@ -253,7 +265,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void catchExceptionByValue() {
void catchExceptionByValue()
{
check("void f() {\n"
" try {\n"
" bar();\n"
@ -325,7 +338,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void noexceptThrow() {
void noexceptThrow()
{
check("void func1() noexcept(false) { throw 1; }\n"
"void func2() noexcept { throw 1; }\n"
"void func3() noexcept(true) { throw 1; }\n"
@ -341,7 +355,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void nothrowThrow() {
void nothrowThrow()
{
check("void func1() throw(int) { throw 1; }\n"
"void func2() throw() { throw 1; }\n"
"void func3() throw(int) { throw 1; }\n"
@ -355,7 +370,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void unhandledExceptionSpecification1() { // #4800
void unhandledExceptionSpecification1() // #4800
{
check("void myThrowingFoo() throw(MyException) {\n"
" throw MyException();\n"
"}\n"
@ -370,7 +386,8 @@ private:
ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:1]: (style, inconclusive) Unhandled exception specification when calling function myThrowingFoo().\n", errout.str());
}
void unhandledExceptionSpecification2() {
void unhandledExceptionSpecification2()
{
check("void f() const throw (std::runtime_error);\n"
"int main()\n"
"{\n"
@ -379,7 +396,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void nothrowAttributeThrow() {
void nothrowAttributeThrow()
{
check("void func1() throw(int) { throw 1; }\n"
"void func2() __attribute((nothrow)); void func2() { throw 1; }\n"
"void func3() __attribute((nothrow)); void func3() { func1(); }\n");
@ -391,7 +409,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void nothrowAttributeThrow2() {
void nothrowAttributeThrow2()
{
check("class foo {\n"
" void copyMemberValues() throw () {\n"
" copyMemberValues();\n"
@ -400,7 +419,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void nothrowDeclspecThrow() {
void nothrowDeclspecThrow()
{
check("void func1() throw(int) { throw 1; }\n"
"void __declspec(nothrow) func2() { throw 1; }\n"
"void __declspec(nothrow) func3() { func1(); }\n");

View File

@ -32,11 +32,13 @@
class TestFileLister: public TestFixture {
public:
TestFileLister()
:TestFixture("TestFileLister") {
:TestFixture("TestFileLister")
{
}
private:
void run() {
void run()
{
// bail out if the tests are not executed from the base folder
{
std::ifstream fin("test/testfilelister.cpp");
@ -51,13 +53,15 @@ private:
TEST_CASE(recursiveAddFiles);
}
void isDirectory() const {
void isDirectory() const
{
ASSERT_EQUALS(false, FileLister::isDirectory("readme.txt"));
ASSERT_EQUALS(true, FileLister::isDirectory("lib"));
}
#ifndef _WIN32
void absolutePath() const {
void absolutePath() const
{
std::vector<char> current_dir;
#ifdef PATH_MAX
current_dir.resize(PATH_MAX);
@ -73,7 +77,8 @@ private:
}
#endif
void recursiveAddFiles() const {
void recursiveAddFiles() const
{
// Recursively add add files..
std::map<std::string, std::size_t> files;
std::set<std::string> extra;

View File

@ -27,12 +27,14 @@ extern std::ostringstream errout;
class TestGarbage : public TestFixture {
public:
TestGarbage() : TestFixture("TestGarbage") {
TestGarbage() : TestFixture("TestGarbage")
{
}
private:
void run() {
void run()
{
// don't freak out when the syntax is wrong
TEST_CASE(wrong_syntax1);
TEST_CASE(wrong_syntax2);
@ -70,7 +72,8 @@ private:
TEST_CASE(garbageAST);
}
std::string checkCode(const char code[], const char filename[] = "test.cpp") {
std::string checkCode(const char code[], const char filename[] = "test.cpp")
{
errout.str("");
Settings settings;
@ -101,7 +104,8 @@ private:
return tokenizer.tokens()->stringifyList(false, false, false, true, false, 0, 0);
}
void wrong_syntax1() {
void wrong_syntax1()
{
{
const char code[] ="TR(kvmpio, PROTO(int rw), ARGS(rw), TP_(aa->rw;))";
ASSERT_EQUALS("TR ( kvmpio , PROTO ( int rw ) , ARGS ( rw ) , TP_ ( aa . rw ; ) )", checkCode(code));
@ -126,7 +130,8 @@ private:
}
}
void wrong_syntax2() { // #3504
void wrong_syntax2() // #3504
{
const char code[] = "void f() {\n"
" X<int> x;\n"
" Y<int, int, int, int, int, char> y;\n"
@ -138,7 +143,8 @@ private:
checkCode(code);
}
void wrong_syntax3() { // #3544
void wrong_syntax3() // #3544
{
const char code[] = "X #define\n"
"{\n"
" (\n"
@ -160,13 +166,15 @@ private:
}
}
void wrong_syntax4() { // #3618
void wrong_syntax4() // #3618
{
const char code[] = "typedef void (x) (int); return x&";
ASSERT_THROW(checkCode(code), InternalError);
}
void wrong_syntax_if_macro() {
void wrong_syntax_if_macro()
{
// #2518 #4171
ASSERT_THROW(checkCode("void f() { if MACRO(); }"), InternalError);
@ -177,7 +185,8 @@ private:
ASSERT_THROW(checkCode("void f() { if (x) MACRO() else ; }"), InternalError);
}
void wrong_syntax_class_x_y() {
void wrong_syntax_class_x_y()
{
// #3585
const char code[] = "class x y { };";
@ -193,7 +202,8 @@ private:
ASSERT_EQUALS("[test.c:1]: (information) The code 'class x y {' is not handled. You can use -I or --include to add handling of this code.\n", errout.str());
}
void syntax_case_default() {
void syntax_case_default()
{
ASSERT_THROW(checkCode("void f() {switch (n) { case: z(); break;}}"), InternalError);
ASSERT_THROW(checkCode("void f() {switch (n) { case;: z(); break;}}"), InternalError);
@ -213,37 +223,45 @@ private:
ASSERT_THROW(checkCode("f ( ) { switch break; { switch ( x ) { case } case break; -6: ( ) ; } }"), InternalError);
}
void garbageCode1() {
void garbageCode1()
{
checkCode("struct x foo_t; foo_t typedef y;");
}
void garbageCode2() { //#4300 (segmentation fault)
void garbageCode2() //#4300 (segmentation fault)
{
ASSERT_THROW(checkCode("enum { D = 1 struct { } ; } s.b = D;"), InternalError);
}
void garbageCode3() { //#4849 (segmentation fault in Tokenizer::simplifyStructDecl (invalid code))
void garbageCode3() //#4849 (segmentation fault in Tokenizer::simplifyStructDecl (invalid code))
{
ASSERT_THROW(checkCode("enum { D = 2 s ; struct y { x } ; } { s.a = C ; s.b = D ; }"), InternalError);
}
void garbageCode4() { // #4887
void garbageCode4() // #4887
{
ASSERT_THROW(checkCode("void f ( ) { = a ; if ( 1 ) if = ( 0 ) ; }"), InternalError);
}
void garbageCode5() { // #5168
void garbageCode5() // #5168
{
checkCode("( asm : ; void : );");
}
void garbageCode6() { // #5214
void garbageCode6() // #5214
{
checkCode("int b = ( 0 ? ? ) 1 : 0 ;");
checkCode("int a = int b = ( 0 ? ? ) 1 : 0 ;");
}
void garbageCode7() {
void garbageCode7()
{
ASSERT_THROW(checkCode("1 (int j) { return return (c) * sizeof } y[1];"), InternalError);
checkCode("foo(Args&&...) fn void = { } auto template<typename... bar(Args&&...)");
}
void garbageCode8() { // #5604
void garbageCode8() // #5604
{
ASSERT_THROW(checkCode("{ enum struct : };"), InternalError);
ASSERT_THROW(checkCode("int ScopedEnum{ template<typename T> { { e = T::error }; };\n"
"ScopedEnum1<int> se1; { enum class E : T { e = 0 = e ScopedEnum2<void*> struct UnscopedEnum3 { T{ e = 4 }; };\n"
@ -255,59 +273,72 @@ private:
"E::e; } int test2 = g<int>(); }"), InternalError);
}
void garbageCode9() {
void garbageCode9()
{
ASSERT_THROW(checkCode("enum { e = { } } ( ) { { enum { } } } { e } "), InternalError);
}
void garbageCode10() { // #6127
void garbageCode10() // #6127
{
checkCode("for( rl=reslist; rl!=NULL; rl=rl->next )");
}
void garbageCode11() { // do not crash
void garbageCode11() // do not crash
{
checkCode("( ) &");
}
void garbageCode12() { // do not crash
void garbageCode12() // do not crash
{
checkCode("{ g; S (void) { struct } { } int &g; }");
}
void garbageCode13() {
void garbageCode13()
{
checkCode("struct C {} {} x");
}
void garbageCode14() {
void garbageCode14()
{
checkCode("static f() { int i; int source[1] = { 1 }; for (i = 0; i < 4; i++) (u, if (y u.x e)) }"); // Garbage code
}
void garbageCode15() { // Ticket #5203
void garbageCode15() // Ticket #5203
{
checkCode("int f ( int* r ) { { int s[2] ; f ( s ) ; if ( ) } }");
}
void garbageCode16() {
void garbageCode16()
{
checkCode("{ } A() { delete }"); // #6080
}
void garbageCode17() {
void garbageCode17()
{
ASSERT_THROW(checkCode("void h(int l) {\n"
" while\n" // Don't crash (#3870)
"}"), InternalError);
}
void garbageCode18() {
void garbageCode18()
{
ASSERT_THROW(checkCode("switch(){case}"), InternalError);
}
void garbageCode19() {
void garbageCode19()
{
// ticket #3512 - Don't crash on garbage code
ASSERT_EQUALS("p = const", checkCode("1 *p = const"));
}
void garbageCode20() {
void garbageCode20()
{
// #3953 (valgrind errors on garbage code)
ASSERT_EQUALS("void f ( 0 * ) ;", checkCode("void f ( 0 * ) ;"));
}
void garbageCode21() {
void garbageCode21()
{
// Ticket #3486 - Don't crash garbage code
checkCode("void f()\n"
"{\n"
@ -318,7 +349,8 @@ private:
"}");
}
void garbageCode22() {
void garbageCode22()
{
// Ticket #3480 - Don't crash garbage code
ASSERT_THROW(checkCode("int f()\n"
"{\n"
@ -326,7 +358,8 @@ private:
"}"), InternalError);
}
void garbageCode23() {
void garbageCode23()
{
//garbage code : don't crash (#3481)
checkCode("{\n"
" if (1) = x\n"
@ -335,7 +368,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void garbageValueFlow() {
void garbageValueFlow()
{
// #6089
const char* code = "{} int foo(struct, x1, struct x2, x3, int, x5, x6, x7)\n"
"{\n"
@ -352,7 +386,8 @@ private:
checkCode(code);
}
void garbageSymbolDatabase() {
void garbageSymbolDatabase()
{
checkCode("void f( { u = 1 ; } ) { }");
checkCode("{ }; void namespace A::f; { g() { int } }");
@ -366,7 +401,8 @@ private:
"} }"), InternalError); // #5663
}
void garbageAST() {
void garbageAST()
{
checkCode("--"); // don't crash
checkCode("N 1024 float a[N], b[N + 3], c[N]; void N; (void) i;\n"

View File

@ -31,11 +31,13 @@ extern std::ostringstream errout;
class TestIncompleteStatement : public TestFixture {
public:
TestIncompleteStatement() : TestFixture("TestIncompleteStatement") {
TestIncompleteStatement() : TestFixture("TestIncompleteStatement")
{
}
private:
void check(const char code[]) {
void check(const char code[])
{
// Clear the error buffer..
errout.str("");
@ -53,7 +55,8 @@ private:
checkOther.checkIncompleteStatement();
}
void run() {
void run()
{
TEST_CASE(test1);
TEST_CASE(test2);
TEST_CASE(test3);
@ -73,7 +76,8 @@ private:
TEST_CASE(block); // ({ do_something(); 0; })
}
void test1() {
void test1()
{
check("void foo()\n"
"{\n"
" const char def[] =\n"
@ -83,7 +87,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void test2() {
void test2()
{
check("void foo()\n"
"{\n"
" \"abc\";\n"
@ -92,7 +97,8 @@ private:
ASSERT_EQUALS("[test.cpp:3]: (warning) Redundant code: Found a statement that begins with string constant.\n", errout.str());
}
void test3() {
void test3()
{
check("void foo()\n"
"{\n"
" const char *str[] = { \"abc\" };\n"
@ -101,7 +107,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void test4() {
void test4()
{
check("void foo()\n"
"{\n"
"const char *a =\n"
@ -115,7 +122,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void test5() {
void test5()
{
check("void foo()\n"
"{\n"
" 50;\n"
@ -124,7 +132,8 @@ private:
ASSERT_EQUALS("[test.cpp:3]: (warning) Redundant code: Found a statement that begins with numeric constant.\n", errout.str());
}
void test6() {
void test6()
{
// dont crash
check("void f() {\n"
" 1 == (two + three);\n"
@ -133,7 +142,8 @@ private:
"}");
}
void test_numeric() {
void test_numeric()
{
check("struct P\n"
"{\n"
"double a;\n"
@ -150,12 +160,14 @@ private:
ASSERT_EQUALS("", errout.str());
}
void intarray() {
void intarray()
{
check("int arr[] = { 100/2, 1*100 };");
ASSERT_EQUALS("", errout.str());
}
void structarraynull() {
void structarraynull()
{
check("struct st arr[] = {\n"
" { 100/2, 1*100 }\n"
" { 90, 70 }\n"
@ -163,7 +175,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void structarray() {
void structarray()
{
check("struct st arr[] = {\n"
" { 100/2, 1*100 }\n"
" { 90, 70 }\n"
@ -171,14 +184,16 @@ private:
ASSERT_EQUALS("", errout.str());
}
void conditionalcall() {
void conditionalcall()
{
check("void f() {\n"
" 0==x ? X() : Y();\n"
"}");
ASSERT_EQUALS("", errout.str());
}
void structinit() {
void structinit()
{
// #2462 - C++11 struct initialization
check("void f() {\n"
" ABC abc{1,2,3};\n"
@ -210,7 +225,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void returnstruct() {
void returnstruct()
{
check("struct s foo() {\n"
" return (struct s){0,0};\n"
"}");
@ -226,14 +242,16 @@ private:
ASSERT_EQUALS("", errout.str());
}
void cast() {
void cast()
{
check("void f() {\n"
" ((struct foo *)(0x1234))->xy = 1;\n"
"}");
ASSERT_EQUALS("", errout.str());
}
void increment() {
void increment()
{
check("void f() {\n"
" int x = 1;\n"
" x++, x++;\n"
@ -241,14 +259,16 @@ private:
ASSERT_EQUALS("", errout.str());
}
void cpp11init() {
void cpp11init()
{
check("void f() {\n"
" int x{1};\n"
"}");
ASSERT_EQUALS("", errout.str());
}
void block() {
void block()
{
check("void f() {\n"
" ({ do_something(); 0; });\n"
"}");

View File

@ -27,11 +27,13 @@ extern std::ostringstream errout;
class TestInternal : public TestFixture {
public:
TestInternal() : TestFixture("TestInternal") {
TestInternal() : TestFixture("TestInternal")
{
}
private:
void run() {
void run()
{
TEST_CASE(simplePatternInTokenMatch)
TEST_CASE(complexPatternInTokenSimpleMatch)
TEST_CASE(simplePatternSquareBrackets)
@ -44,7 +46,8 @@ private:
TEST_CASE(orInComplexPattern);
}
void check(const char code[]) {
void check(const char code[])
{
// Clear the error buffer..
errout.str("");
@ -62,7 +65,8 @@ private:
checkInternal.runSimplifiedChecks(&tokenizer, &settings, this);
}
void simplePatternInTokenMatch() {
void simplePatternInTokenMatch()
{
check("void f() {\n"
" const Token *tok;\n"
" Token::Match(tok, \";\");\n"
@ -82,7 +86,8 @@ private:
ASSERT_EQUALS("[test.cpp:3]: (warning) Found simple pattern inside Token::findmatch() call: \";\"\n", errout.str());
}
void complexPatternInTokenSimpleMatch() {
void complexPatternInTokenSimpleMatch()
{
check("void f() {\n"
" const Token *tok;\n"
" Token::simpleMatch(tok, \"%type%\");\n"
@ -114,7 +119,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void simplePatternSquareBrackets() {
void simplePatternSquareBrackets()
{
check("void f() {\n"
" const Token *tok;\n"
" Token::simpleMatch(tok, \"[\");\n"
@ -152,7 +158,8 @@ private:
ASSERT_EQUALS("[test.cpp:3]: (error) Found complex pattern inside Token::simpleMatch() call: \"[.,;]\"\n", errout.str());
}
void simplePatternAlternatives() {
void simplePatternAlternatives()
{
check("void f() {\n"
" const Token *tok;\n"
" Token::simpleMatch(tok, \"||\");\n"
@ -184,7 +191,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void missingPercentCharacter() {
void missingPercentCharacter()
{
check("void f() {\n"
" const Token *tok;\n"
" Token::Match(tok, \"%type%\");\n"
@ -242,7 +250,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void unknownPattern() {
void unknownPattern()
{
check("void f() {\n"
" Token::Match(tok, \"%typ%\");\n"
"}");
@ -255,7 +264,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void redundantNextPrevious() {
void redundantNextPrevious()
{
check("void f() {\n"
" return tok->next()->previous();\n"
"}");
@ -307,7 +317,8 @@ private:
ASSERT_EQUALS("[test.cpp:2]: (style) Call to 'Token::next()' followed by 'Token::str()' can be simplified.\n", errout.str());
}
void internalError() {
void internalError()
{
// Make sure cppcheck does not raise an internal error of Token::Match ( Ticket #3727 )
check("class DELPHICLASS X;\n"
"class Y {\n"
@ -323,7 +334,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void invalidMultiCompare() {
void invalidMultiCompare()
{
// #5310
check("void f() {\n"
" const Token *tok;\n"
@ -344,7 +356,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void orInComplexPattern() {
void orInComplexPattern()
{
check("void f() {\n"
" Token::Match(tok, \"||\");\n"
"}");

View File

@ -25,13 +25,15 @@ extern std::ostringstream errout;
class TestIO : public TestFixture {
public:
TestIO() : TestFixture("TestIO") {
TestIO() : TestFixture("TestIO")
{
}
private:
Settings settings;
void run() {
void run()
{
LOAD_LIB_2(settings.library, "std.cfg");
LOAD_LIB_2(settings.library, "windows.cfg");
@ -62,7 +64,8 @@ private:
TEST_CASE(testTernary); // ticket #6182
}
void check(const char code[], bool inconclusive = false, bool portability = false, Settings::PlatformType platform = Settings::Unspecified) {
void check(const char code[], bool inconclusive = false, bool portability = false, Settings::PlatformType platform = Settings::Unspecified)
{
// Clear the error buffer..
errout.str("");
@ -93,7 +96,8 @@ private:
void coutCerrMisusage() {
void coutCerrMisusage()
{
check(
"void foo() {\n"
" std::cout << std::cout;\n"
@ -146,7 +150,8 @@ private:
void wrongMode_simple() {
void wrongMode_simple()
{
// Read mode
check("void foo(FILE*& f) {\n"
" f = fopen(name, \"r\");\n"
@ -347,7 +352,8 @@ private:
check("void fopen(std::string const &filepath, std::string const &mode);"); // #3832
}
void wrongMode_complex() {
void wrongMode_complex()
{
check("void foo(FILE* f) {\n"
" if(a) f = fopen(name, \"w\");\n"
" else f = fopen(name, \"r\");\n"
@ -373,7 +379,8 @@ private:
ASSERT_EQUALS("[test.cpp:4]: (error) Read operation on a file that was opened only for writing.\n", errout.str());
}
void useClosedFile() {
void useClosedFile()
{
check("void foo(FILE*& f) {\n"
" fclose(f);\n"
" fwrite(buffer, 5, 6, f);\n"
@ -498,7 +505,8 @@ private:
ASSERT_EQUALS("[test.cpp:3]: (error) Used file that is not opened.\n", errout.str());
}
void fileIOwithoutPositioning() {
void fileIOwithoutPositioning()
{
check("void foo(FILE* f) {\n"
" fwrite(buffer, 5, 6, f);\n"
" fread(buffer, 5, 6, f);\n"
@ -555,7 +563,8 @@ private:
ASSERT_EQUALS("[test.cpp:4]: (error) Read and write operations without a call to a positioning function (fseek, fsetpos or rewind) or fflush in between result in undefined behaviour.\n", errout.str());
}
void seekOnAppendedFile() {
void seekOnAppendedFile()
{
check("void foo() {\n"
" FILE* f = fopen(\"\", \"a+\");\n"
" fseek(f, 0, SEEK_SET);\n"
@ -581,7 +590,8 @@ private:
ASSERT_EQUALS("", errout.str()); // #5578
}
void fflushOnInputStream() {
void fflushOnInputStream()
{
check("void foo()\n"
"{\n"
" fflush(stdin);\n"
@ -615,7 +625,8 @@ private:
void testScanf1() {
void testScanf1()
{
check("void foo() {\n"
" int a, b;\n"
" FILE *file = fopen(\"test\", \"r\");\n"
@ -633,7 +644,8 @@ private:
"[test.cpp:8]: (warning) scanf without field width limits can crash with huge input data.\n", errout.str());
}
void testScanf2() {
void testScanf2()
{
check("void foo() {\n"
" scanf(\"%5s\", bar);\n" // Width specifier given
" scanf(\"%5[^~]\", bar);\n" // Width specifier given
@ -645,7 +657,8 @@ private:
ASSERT_EQUALS("[test.cpp:4]: (warning) scanf format string requires 0 parameters but 1 is given.\n", errout.str());
}
void testScanf3() {
void testScanf3()
{
check("void foo() {\n"
" scanf(\"%d\", &a);\n"
" scanf(\"%n\", &a);\n" // No warning on %n, since it doesn't expect user input
@ -659,7 +672,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void testScanf4() { // ticket #2553
void testScanf4() // ticket #2553
{
check("void f()\n"
"{\n"
" char str [8];\n"
@ -671,7 +685,8 @@ private:
void testScanfArgument() {
void testScanfArgument()
{
check("void foo() {\n"
" scanf(\"%1d\", &foo);\n"
" sscanf(bar, \"%1d\", &foo);\n"
@ -2271,7 +2286,8 @@ private:
}
void testPrintfArgument() {
void testPrintfArgument()
{
check("void foo() {\n"
" printf(\"%u\");\n"
" printf(\"%u%s\", 123);\n"
@ -3115,7 +3131,8 @@ private:
}
void testPosixPrintfScanfParameterPosition() { // #4900 - No support for parameters in format strings
void testPosixPrintfScanfParameterPosition() // #4900 - No support for parameters in format strings
{
check("void foo() {"
" int bar;"
" printf(\"%1$d\", 1);"
@ -3139,7 +3156,8 @@ private:
}
void testMicrosoftPrintfArgument() {
void testMicrosoftPrintfArgument()
{
check("void foo() {\n"
" size_t s;\n"
" ptrdiff_t p;\n"
@ -3240,7 +3258,8 @@ private:
}
void testMicrosoftScanfArgument() {
void testMicrosoftScanfArgument()
{
check("void foo() {\n"
" size_t s;\n"
" ptrdiff_t p;\n"
@ -3317,7 +3336,8 @@ private:
"[test.cpp:17]: (warning) 'I64' in format string (no. 1) is a length modifier and cannot be used without a conversion specifier.\n", errout.str());
}
void testMicrosoftCStringFormatArguments() { // ticket #4920
void testMicrosoftCStringFormatArguments() // ticket #4920
{
check("void foo() {\n"
" unsigned __int32 u32;\n"
" String string;\n"
@ -3344,7 +3364,8 @@ private:
"[test.cpp:5]: (warning) %I32d in format string (no. 1) requires '__int32' but the argument type is 'unsigned __int32 {aka unsigned int}'.\n", errout.str());
}
void testMicrosoftSecurePrintfArgument() {
void testMicrosoftSecurePrintfArgument()
{
check("void foo() {\n"
" int i;\n"
" unsigned int u;\n"
@ -3534,7 +3555,8 @@ private:
}
void testMicrosoftSecureScanfArgument() {
void testMicrosoftSecureScanfArgument()
{
check("void foo() {\n"
" int i;\n"
" unsigned int u;\n"
@ -3666,7 +3688,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void testTernary() { // ticket #6182
void testTernary() // ticket #6182
{
check("void test(const std::string &val) {\n"
" printf(\"%s\n\", val.empty() ? \"I like to eat bananas\" : val.c_str());\n"
"}\n");

View File

@ -26,12 +26,14 @@ extern std::ostringstream errout;
class TestLeakAutoVar : public TestFixture {
public:
TestLeakAutoVar() : TestFixture("TestLeakAutoVar") {
TestLeakAutoVar() : TestFixture("TestLeakAutoVar")
{
}
private:
void run() {
void run()
{
// Assign
TEST_CASE(assign1);
TEST_CASE(assign2);
@ -113,7 +115,8 @@ private:
TEST_CASE(nestedAllocation);
}
void check(const char code[]) {
void check(const char code[])
{
// Clear the error buffer..
errout.str("");
@ -138,7 +141,8 @@ private:
c.runSimplifiedChecks(&tokenizer, &settings, this);
}
void checkcpp(const char code[]) {
void checkcpp(const char code[])
{
// Clear the error buffer..
errout.str("");
@ -163,7 +167,8 @@ private:
c.runSimplifiedChecks(&tokenizer, &settings, this);
}
void assign1() {
void assign1()
{
check("void f() {\n"
" char *p = malloc(10);\n"
" p = NULL;\n"
@ -172,7 +177,8 @@ private:
ASSERT_EQUALS("[test.c:3]: (error) Memory leak: p\n", errout.str());
}
void assign2() {
void assign2()
{
check("void f() {\n"
" char *p = malloc(10);\n"
" char *q = p;\n"
@ -181,7 +187,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void assign3() {
void assign3()
{
check("void f() {\n"
" char *p = malloc(10);\n"
" char *q = p + 1;\n"
@ -190,7 +197,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void assign4() {
void assign4()
{
check("void f() {\n"
" char *a = malloc(10);\n"
" a += 10;\n"
@ -199,7 +207,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void assign5() {
void assign5()
{
check("void foo()\n"
"{\n"
" char *p = new char[100];\n"
@ -208,7 +217,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void assign6() { // #2806 - FP when there is redundant assignment
void assign6() // #2806 - FP when there is redundant assignment
{
check("void foo() {\n"
" char *p = malloc(10);\n"
" p = strcpy(p,q);\n"
@ -217,7 +227,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void assign7() {
void assign7()
{
check("void foo(struct str *d) {\n"
" struct str *p = malloc(10);\n"
" d->p = p;\n"
@ -225,7 +236,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void assign8() { // linux list
void assign8() // linux list
{
check("void foo(struct str *d) {\n"
" struct str *p = malloc(10);\n"
" d->p = &p->x;\n"
@ -233,7 +245,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void assign9() {
void assign9()
{
check("void foo() {\n"
" char *p = x();\n"
" free(p);\n"
@ -242,7 +255,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void assign10() {
void assign10()
{
check("void foo() {\n"
" char *p;\n"
" if (x) { p = malloc(10); }\n"
@ -252,7 +266,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void assign11() { // #3942 - FP for x = a(b(p));
void assign11() // #3942 - FP for x = a(b(p));
{
check("void f() {\n"
" char *p = malloc(10);\n"
" x = a(b(p));\n"
@ -260,7 +275,8 @@ private:
ASSERT_EQUALS("[test.c:4]: (information) --check-library: Function b() should have <use>/<ignore> configuration\n", errout.str());
}
void assign12() { // #4236: FP. bar(&x)
void assign12() // #4236: FP. bar(&x)
{
check("void f() {\n"
" char *p = malloc(10);\n"
" free(p);\n"
@ -270,7 +286,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void assign13() { // #4237: FP. char *&ref=p; p=malloc(10); free(ref);
void assign13() // #4237: FP. char *&ref=p; p=malloc(10); free(ref);
{
check("void f() {\n"
" char *p;\n"
" char * &ref = p;\n"
@ -280,7 +297,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void deallocuse1() {
void deallocuse1()
{
check("void f(char *p) {\n"
" free(p);\n"
" *p = 0;\n"
@ -294,7 +312,8 @@ private:
ASSERT_EQUALS("[test.c:3]: (error) Dereferencing 'p' after it is deallocated / released\n", errout.str());
}
void deallocuse2() {
void deallocuse2()
{
check("void f(char *p) {\n"
" free(p);\n"
" strcpy(a, p);\n"
@ -308,7 +327,8 @@ private:
TODO_ASSERT_EQUALS("", "[test.c:3]: (information) --check-library: Function strcpy() should have <noreturn> configuration\n", errout.str());
}
void deallocuse3() {
void deallocuse3()
{
check("void f(struct str *p) {\n"
" free(p);\n"
" p = p->next;\n"
@ -316,7 +336,8 @@ private:
ASSERT_EQUALS("[test.c:3]: (error) Dereferencing 'p' after it is deallocated / released\n", errout.str());
}
void deallocuse4() {
void deallocuse4()
{
check("void f(char *p) {\n"
" free(p);\n"
" return p;\n"
@ -324,7 +345,8 @@ private:
ASSERT_EQUALS("[test.c:3]: (error) Returning/dereferencing 'p' after it is deallocated / released\n", errout.str());
}
void deallocuse5() { // #4018
void deallocuse5() // #4018
{
check("void f(char *p) {\n"
" free(p), p = 0;\n"
" *p = 0;\n" // <- Make sure pointer info is reset. It is NOT a freed pointer dereference
@ -332,7 +354,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void deallocuse6() { // #4034
void deallocuse6() // #4034
{
check("void f(char *p) {\n"
" free(p);\n"
" x = p = foo();\n" // <- p is not dereferenced
@ -340,7 +363,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void doublefree1() { // #3895
void doublefree1() // #3895
{
check("void f(char *p) {\n"
" if (x)\n"
" free(p);\n"
@ -351,7 +375,8 @@ private:
ASSERT_EQUALS("[test.c:6]: (error) Memory pointed to by 'p' is freed twice.\n", errout.str());
}
void doublefree2() { // #3891
void doublefree2() // #3891
{
check("void *f(int a) {\n"
" char *p = malloc(10);\n"
" if (a == 2) { free(p); return ((void*)1); }\n"
@ -361,7 +386,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void doublefree3() { // #4914
void doublefree3() // #4914
{
check("void foo() {\n"
" bool done = false;\n"
" do {\n"
@ -379,7 +405,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void doublefree4() { // #5451 - exit
void doublefree4() // #5451 - exit
{
check("void f(char *p) {\n"
" if (x) {\n"
" free(p);\n"
@ -390,7 +417,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void exit1() {
void exit1()
{
check("void f() {\n"
" char *p = malloc(10);\n"
" exit(0);\n"
@ -398,7 +426,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void exit2() {
void exit2()
{
check("void f() {\n"
" char *p = malloc(10);\n"
" fatal_error();\n"
@ -408,7 +437,8 @@ private:
errout.str());
}
void goto1() {
void goto1()
{
check("static void f() {\n"
" int err = -ENOMEM;\n"
" char *reg = malloc(100);\n"
@ -419,7 +449,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void goto2() { // #4231
void goto2() // #4231
{
check("static char * f() {\n"
"x:\n"
" char *p = malloc(100);\n"
@ -432,7 +463,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void ifelse1() {
void ifelse1()
{
check("int f() {\n"
" char *p = NULL;\n"
" if (x) { p = malloc(10); }\n"
@ -442,7 +474,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void ifelse2() {
void ifelse2()
{
check("int f() {\n"
" char *p = NULL;\n"
" if (x) { p = malloc(10); }\n"
@ -451,7 +484,8 @@ private:
ASSERT_EQUALS("[test.c:5]: (error) Memory leak: p\n", errout.str());
}
void ifelse3() {
void ifelse3()
{
check("void f() {\n"
" char *p = malloc(10);\n"
" if (!p) { return; }\n"
@ -475,7 +509,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void ifelse4() {
void ifelse4()
{
check("void f(int x) {\n"
" char *p;\n"
" if (x) { p = malloc(10); }\n"
@ -492,7 +527,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void ifelse5() {
void ifelse5()
{
check("void f() {\n"
" char *p = malloc(10);\n"
" if (!p && x) { p = malloc(10); }\n"
@ -501,7 +537,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void ifelse6() { // #3370
void ifelse6() // #3370
{
check("void f(int x) {\n"
" int *a = malloc(20);\n"
" if (x)\n"
@ -512,7 +549,8 @@ private:
ASSERT_EQUALS("[test.c:6]: (error) Memory leak: a\n", errout.str());
}
void ifelse7() { // #5576
void ifelse7() // #5576
{
check("void f() {\n"
" int x = malloc(20);\n"
" if (x < 0)\n" // assume negative value indicates its unallocated
@ -522,7 +560,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void ifelse8() { // #5747
void ifelse8() // #5747
{
check("void f() {\n"
" int fd = socket(AF_INET, SOCK_PACKET, 0 );\n"
" if (fd == -1)\n"
@ -531,7 +570,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void switch1() {
void switch1()
{
check("void f() {\n"
" char *p = 0;\n"
" switch (x) {\n"
@ -543,7 +583,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void loop1() {
void loop1()
{
// test the handling of { }
check("void f() {\n"
" char *p;\n"
@ -554,7 +595,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void mismatch_fopen_free() {
void mismatch_fopen_free()
{
check("void f() {\n"
" FILE*f=fopen(fname,a);\n"
" free(f);\n"
@ -562,7 +604,8 @@ private:
ASSERT_EQUALS("[test.c:3]: (error) Mismatching allocation and deallocation: f\n", errout.str());
}
void return1() {
void return1()
{
check("int f() {\n"
" char *p = malloc(100);\n"
" return 123;\n"
@ -570,7 +613,8 @@ private:
ASSERT_EQUALS("[test.c:3]: (error) Memory leak: p\n", errout.str());
}
void return2() {
void return2()
{
check("char *f() {\n"
" char *p = malloc(100);\n"
" return p;\n"
@ -578,7 +622,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void return3() {
void return3()
{
check("struct dev * f() {\n"
" struct ABC *abc = malloc(100);\n"
" return &abc->dev;\n"
@ -586,7 +631,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void return4() { // ticket #3862
void return4() // ticket #3862
{
// avoid false positives
check("void f(char *p, int x) {\n"
" if (x==12) {\n"
@ -616,14 +662,16 @@ private:
ASSERT_EQUALS("", errout.str());
}
void test1() { // 3809
void test1() // 3809
{
check("void f(double*&p) {\n"
" p = malloc(0x100);\n"
"}");
ASSERT_EQUALS("", errout.str());
}
void test2() { // 3899
void test2() // 3899
{
check("struct Fred {\n"
" char *p;\n"
" void f1() { free(p); }\n"
@ -631,7 +679,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void test3() { // 3954 - reference pointer
void test3() // 3954 - reference pointer
{
check("void f() {\n"
" char *&p = x();\n"
" p = malloc(10);\n"
@ -639,7 +688,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void test4() { // 5923 - static pointer
void test4() // 5923 - static pointer
{
check("void f() {\n"
" static char *p;\n"
" if (!p) p = malloc(10);\n"
@ -648,7 +698,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void test5() { // unknown type
void test5() // unknown type
{
checkcpp("void f() { Fred *p = malloc(10); }");
ASSERT_EQUALS("", errout.str());
@ -656,7 +707,8 @@ private:
ASSERT_EQUALS("[test.c:1]: (error) Memory leak: p\n", errout.str());
}
void throw1() { // 3987 - Execution reach a 'throw'
void throw1() // 3987 - Execution reach a 'throw'
{
check("void f() {\n"
" char *p = malloc(10);\n"
" throw 123;\n"
@ -674,7 +726,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void configuration1() {
void configuration1()
{
// Possible leak => configuration is required for complete analysis
// The user should be able to "white list" and "black list" functions.
@ -689,7 +742,8 @@ private:
errout.str());
}
void configuration2() {
void configuration2()
{
// possible leak. If the function 'x' deallocates the pointer or
// takes the address, there is no leak.
check("void f() {\n"
@ -701,7 +755,8 @@ private:
errout.str());
}
void configuration3() {
void configuration3()
{
check("void f() {\n"
" char *p = malloc(10);\n"
" if (set_data(p)) { }\n"
@ -717,7 +772,8 @@ private:
, errout.str());
}
void configuration4() {
void configuration4()
{
check("void f() {\n"
" char *p = malloc(10);\n"
" int ret = set_data(p);\n"
@ -726,14 +782,16 @@ private:
ASSERT_EQUALS("[test.c:4]: (information) --check-library: Function set_data() should have <use>/<ignore> configuration\n", errout.str());
}
void ptrptr() {
void ptrptr()
{
check("void f() {\n"
" char **p = malloc(10);\n"
"}");
ASSERT_EQUALS("[test.c:3]: (error) Memory leak: p\n", errout.str());
}
void nestedAllocation() {
void nestedAllocation()
{
check("void QueueDSMCCPacket(unsigned char *data, int length) {\n"
" unsigned char *dataCopy = malloc(length * sizeof(unsigned char));\n"
" m_dsmccQueue.enqueue(new DSMCCPacket(dataCopy));\n"

View File

@ -28,7 +28,8 @@ public:
private:
void run() {
void run()
{
TEST_CASE(empty);
TEST_CASE(function);
TEST_CASE(function_arg);
@ -42,7 +43,8 @@ private:
TEST_CASE(version);
}
void empty() const {
void empty() const
{
const char xmldata[] = "<?xml version=\"1.0\"?>\n<def/>";
tinyxml2::XMLDocument doc;
doc.Parse(xmldata, sizeof(xmldata));
@ -54,7 +56,8 @@ private:
ASSERT(library.argumentChecks.empty());
}
void function() const {
void function() const
{
const char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <function name=\"foo\">\n"
@ -72,7 +75,8 @@ private:
ASSERT(library.isnotnoreturn("foo"));
}
void function_arg() const {
void function_arg() const
{
const char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <function name=\"foo\">\n"
@ -95,7 +99,8 @@ private:
ASSERT_EQUALS(true, library.argumentChecks["foo"][5].notbool);
}
void function_arg_any() const {
void function_arg_any() const
{
const char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
"<function name=\"foo\">\n"
@ -110,7 +115,8 @@ private:
ASSERT_EQUALS(true, library.argumentChecks["foo"][-1].notuninit);
}
void function_arg_valid() const {
void function_arg_valid() const
{
const char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <function name=\"foo\">\n"
@ -160,7 +166,8 @@ private:
ASSERT_EQUALS(false, library.isargvalid("foo", 5, 2));
}
void function_arg_minsize() const {
void function_arg_minsize() const
{
const char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <function name=\"foo\">\n"
@ -195,7 +202,8 @@ private:
}
}
void memory() const {
void memory() const
{
const char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <memory>\n"
@ -215,7 +223,8 @@ private:
ASSERT(Library::ismemory(library.alloc("CreateX")));
ASSERT_EQUALS(library.alloc("CreateX"), library.dealloc("DeleteX"));
}
void memory2() const {
void memory2() const
{
const char xmldata1[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <memory>\n"
@ -239,7 +248,8 @@ private:
ASSERT_EQUALS(library.dealloc("free"), library.alloc("foo"));
}
void resource() const {
void resource() const
{
const char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <resource>\n"
@ -260,7 +270,8 @@ private:
ASSERT_EQUALS(library.alloc("CreateX"), library.dealloc("DeleteX"));
}
void podtype() const {
void podtype() const
{
const char xmldata[] = "<?xml version=\"1.0\"?>\n"
"<def>\n"
" <podtype name=\"s16\" sizeof=\"2\"/>\n"
@ -276,7 +287,8 @@ private:
ASSERT_EQUALS(0, type ? type->sign : '?');
}
void version() const {
void version() const
{
{
const char xmldata [] = "<?xml version=\"1.0\"?>\n"
"<def>\n"

View File

@ -23,12 +23,14 @@
class TestMathLib : public TestFixture {
public:
TestMathLib() : TestFixture("TestMathLib") {
TestMathLib() : TestFixture("TestMathLib")
{
}
private:
void run() {
void run()
{
TEST_CASE(isint);
TEST_CASE(isbin);
TEST_CASE(isdec);
@ -55,42 +57,49 @@ private:
TEST_CASE(abs);
}
void isGreater() const {
void isGreater() const
{
ASSERT_EQUALS(true , MathLib::isGreater("1.0", "0.001"));
ASSERT_EQUALS(false, MathLib::isGreater("-1.0", "0.001"));
}
void isGreaterEqual() const {
void isGreaterEqual() const
{
ASSERT_EQUALS(true , MathLib::isGreaterEqual("1.00", "1.0"));
ASSERT_EQUALS(true , MathLib::isGreaterEqual("1.001", "1.0"));
ASSERT_EQUALS(true , MathLib::isGreaterEqual("1.0", "0.001"));
ASSERT_EQUALS(false, MathLib::isGreaterEqual("-1.0", "0.001"));
}
void isEqual() const {
void isEqual() const
{
ASSERT_EQUALS(true , MathLib::isEqual("1.0", "1.0"));
ASSERT_EQUALS(false , MathLib::isEqual("1.", "1.01"));
ASSERT_EQUALS(true , MathLib::isEqual("0.1","1.0E-1"));
}
void isNotEqual() const {
void isNotEqual() const
{
ASSERT_EQUALS(false , MathLib::isNotEqual("1.0", "1.0"));
ASSERT_EQUALS(true , MathLib::isNotEqual("1.", "1.01"));
}
void isLess() const {
void isLess() const
{
ASSERT_EQUALS(false , MathLib::isLess("1.0", "0.001"));
ASSERT_EQUALS(true , MathLib::isLess("-1.0", "0.001"));
}
void isLessEqual() const {
void isLessEqual() const
{
ASSERT_EQUALS(true , MathLib::isLessEqual("1.00", "1.0"));
ASSERT_EQUALS(false , MathLib::isLessEqual("1.001", "1.0"));
ASSERT_EQUALS(false , MathLib::isLessEqual("1.0", "0.001"));
ASSERT_EQUALS(true , MathLib::isLessEqual("-1.0", "0.001"));
}
void calculate() const {
void calculate() const
{
// addition
ASSERT_EQUALS("256", MathLib::add("0xff", "1"));
ASSERT_EQUALS("249", MathLib::add("250", "-1"));
@ -143,7 +152,8 @@ private:
ASSERT_THROW(MathLib::calculate("1","2",'j'),InternalError);
}
void calculate1() const {
void calculate1() const
{
ASSERT_EQUALS("0" , MathLib::calculate("2" , "1" , '%'));
ASSERT_EQUALS("0.0" , MathLib::calculate("2.0" , "1.0" , '%'));
ASSERT_EQUALS("2" , MathLib::calculate("12" , "5" , '%'));
@ -158,7 +168,8 @@ private:
ASSERT_EQUALS("3" , MathLib::calculate("2" , "1" , '^'));
}
void convert() const {
void convert() const
{
// ------------------
// tolong conversion:
// ------------------
@ -248,7 +259,8 @@ private:
ASSERT_EQUALS("0.0" , MathLib::toString(MathLib::toDoubleNumber("+0.0")));
}
void isint() const {
void isint() const
{
// zero tests
ASSERT_EQUALS(true , MathLib::isInt("0"));
ASSERT_EQUALS(false, MathLib::isInt("0."));
@ -337,7 +349,8 @@ private:
ASSERT_EQUALS(false, MathLib::isInt(""));
}
void isbin() const {
void isbin() const
{
// positive testing
ASSERT_EQUALS(true, MathLib::isBin("0b0"));
ASSERT_EQUALS(true, MathLib::isBin("0b1"));
@ -377,7 +390,8 @@ private:
ASSERT_EQUALS(false, MathLib::isBin(""));
}
void isnegative() const {
void isnegative() const
{
ASSERT_EQUALS(true , MathLib::isNegative("-1"));
ASSERT_EQUALS(true , MathLib::isNegative("-1."));
ASSERT_EQUALS(true , MathLib::isNegative("-1.0"));
@ -393,7 +407,8 @@ private:
ASSERT_EQUALS(false, MathLib::isNegative(""));
}
void isoct() const {
void isoct() const
{
// octal number format: [+|-]0[0-7][suffix]
// positive testing
ASSERT_EQUALS(true, MathLib::isOct("010"));
@ -455,7 +470,8 @@ private:
ASSERT_EQUALS(false, MathLib::isOct("+042LUL+0"));
}
void ishex() const {
void ishex() const
{
// hex number syntax: [sign]0x[hexnumbers][suffix]
// positive testing
@ -517,7 +533,8 @@ private:
ASSERT_EQUALS(false, MathLib::isHex(""));
}
void ispositive() const {
void ispositive() const
{
ASSERT_EQUALS(false, MathLib::isPositive("-1"));
ASSERT_EQUALS(false, MathLib::isPositive("-1."));
ASSERT_EQUALS(false, MathLib::isPositive("-1.0"));
@ -534,7 +551,8 @@ private:
ASSERT_EQUALS(true, MathLib::isPositive("")); // because it has opposite result to MathLib::isNegative
}
void isfloat() const {
void isfloat() const
{
ASSERT_EQUALS(false, MathLib::isFloat(""));
ASSERT_EQUALS(false, MathLib::isFloat("."));
ASSERT_EQUALS(false, MathLib::isFloat("..."));
@ -628,7 +646,8 @@ private:
ASSERT_EQUALS(true , MathLib::isFloat("-1.0E+1"));
}
void naninf() const {
void naninf() const
{
ASSERT_EQUALS("nan.0", MathLib::divide("0.0", "0.0")); // nan
ASSERT_EQUALS("nan.0", MathLib::divide("0.0", "0.f")); // nan (#5875)
ASSERT_EQUALS("nan.0", MathLib::divide("-0.0", "0.f")); // nan (#5875)
@ -644,7 +663,8 @@ private:
ASSERT_EQUALS("inf.0", MathLib::divide("-3.0", "-0.0f")); // inf (#5142)
}
void isdec(void) {
void isdec(void)
{
// positive testing
ASSERT_EQUALS(true, MathLib::isDec("1"));
ASSERT_EQUALS(true, MathLib::isDec("+1"));
@ -661,7 +681,8 @@ private:
ASSERT_EQUALS(false, MathLib::isDec("x"));
}
void isNullValue() const {
void isNullValue() const
{
// inter zero value
ASSERT_EQUALS(true, MathLib::isNullValue("0"));
ASSERT_EQUALS(true, MathLib::isNullValue("+0"));
@ -830,7 +851,8 @@ private:
ASSERT_EQUALS(false, MathLib::isNullValue("UL"));
}
void incdec() {
void incdec()
{
// increment
{
MathLib::biguint num = ~10U;
@ -851,16 +873,20 @@ private:
ASSERT_THROW(MathLib::incdec("1", "x"), InternalError); // throw
}
void sin() {
void sin()
{
ASSERT_EQUALS("0.0" , MathLib::sin("0"));
}
void cos() {
void cos()
{
ASSERT_EQUALS("1.0" , MathLib::cos("0"));
}
void tan() {
void tan()
{
ASSERT_EQUALS("0.0" , MathLib::tan("0"));
}
void abs() {
void abs()
{
ASSERT_EQUALS("0.0" , MathLib::abs("0"));
ASSERT_EQUALS("0.0" , MathLib::abs("+0"));
ASSERT_EQUALS("0.0" , MathLib::abs("-0"));

File diff suppressed because it is too large Load Diff

View File

@ -27,17 +27,20 @@ extern std::ostringstream errout;
class TestNonReentrantFunctions : public TestFixture {
public:
TestNonReentrantFunctions() : TestFixture("TestNonReentrantFunctions") {
TestNonReentrantFunctions() : TestFixture("TestNonReentrantFunctions")
{
}
private:
void run() {
void run()
{
TEST_CASE(test_crypt);
TEST_CASE(test_namespace_handling);
}
void check(const char code[]) {
void check(const char code[])
{
// Clear the error buffer..
errout.str("");
@ -56,7 +59,8 @@ private:
checkNonReentrantFunctions.nonReentrantFunctions();
}
void test_crypt() {
void test_crypt()
{
check("void f(char *pwd)\n"
"{\n"
" char *cpwd;"
@ -80,7 +84,8 @@ private:
ASSERT_EQUALS("", errout.str());
}
void test_namespace_handling() {
void test_namespace_handling()
{
check("int f()\n"
"{\n"
" time_t t = 0;"

Some files were not shown because too many files have changed in this diff Show More