astyle formatting

This commit is contained in:
Daniel Marjamäki 2014-11-20 14:20:09 +01:00
parent 9cbab3d8f1
commit 051d42ae6b
132 changed files with 3690 additions and 7333 deletions

View File

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

View File

@ -37,8 +37,7 @@ public:
* @param files output map that associates the size of each file with its name * @param files output map that associates the size of each file with its name
* @param path root path * @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; const std::set<std::string> extra;
recursiveAddFiles(files, path, extra); recursiveAddFiles(files, path, extra);
} }

View File

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

View File

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

View File

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

View File

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

View File

@ -37,13 +37,11 @@ class ErrorLine;
*/ */
class GuiSeverity { class GuiSeverity {
public: public:
static QString toString(Severity::SeverityType severity) static QString toString(Severity::SeverityType severity) {
{
return QString(Severity::toString(severity).c_str()); 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()); 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); dir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot);
QFileInfoList list = dir.entryInfoList(); QFileInfoList list = dir.entryInfoList();
QFileInfo item; QFileInfo item;
foreach (item, list) { foreach(item, list) {
const QString path = item.canonicalFilePath(); const QString path = item.canonicalFilePath();
AddDirectory(path, recursive); AddDirectory(path, recursive);
} }
@ -78,7 +78,7 @@ void FileList::AddDirectory(const QString &directory, bool recursive)
void FileList::AddPathList(const QStringList &paths) void FileList::AddPathList(const QStringList &paths)
{ {
QString path; QString path;
foreach (path, paths) { foreach(path, paths) {
QFileInfo inf(path); QFileInfo inf(path);
if (inf.isFile()) if (inf.isFile())
AddFile(path); AddFile(path);
@ -91,7 +91,7 @@ QStringList FileList::GetFileList() const
{ {
if (mExcludedPaths.empty()) { if (mExcludedPaths.empty()) {
QStringList names; QStringList names;
foreach (QFileInfo item, mFileList) { foreach(QFileInfo item, mFileList) {
QString name = QDir::fromNativeSeparators(item.canonicalFilePath()); QString name = QDir::fromNativeSeparators(item.canonicalFilePath());
names << name; names << name;
} }
@ -109,7 +109,7 @@ void FileList::AddExcludeList(const QStringList &paths)
QStringList FileList::ApplyExcludeList() const QStringList FileList::ApplyExcludeList() const
{ {
QStringList paths; QStringList paths;
foreach (QFileInfo item, mFileList) { foreach(QFileInfo item, mFileList) {
QString name = QDir::fromNativeSeparators(item.canonicalFilePath()); QString name = QDir::fromNativeSeparators(item.canonicalFilePath());
if (!Match(name)) if (!Match(name))
paths << name; paths << name;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -31,10 +31,8 @@ private slots:
private: private:
// Empty implementations of ErrorLogger methods. // Empty implementations of ErrorLogger methods.
// We don't care about the output in the benchmark tests. // 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,8 +988,7 @@ public:
ScopeInfo(const Token *token, ScopeInfo *parent_) : _token(token), _parent(parent_) { } ScopeInfo(const Token *token, ScopeInfo *parent_) : _token(token), _parent(parent_) { }
~ScopeInfo(); ~ScopeInfo();
ScopeInfo *parent() ScopeInfo *parent() {
{
return _parent; return _parent;
} }
ScopeInfo *addChild(const Token *token); ScopeInfo *addChild(const Token *token);
@ -1054,20 +1053,17 @@ public:
_read(read), _read(read),
_write(write), _write(write),
_modified(modified), _modified(modified),
_allocateMemory(allocateMemory) _allocateMemory(allocateMemory) {
{
} }
/** variable is used.. set both read+write */ /** variable is used.. set both read+write */
void use() void use() {
{
_read = true; _read = true;
_write = true; _write = true;
} }
/** is variable unused? */ /** is variable unused? */
bool unused() const bool unused() const {
{
return (_read == false && _write == false); return (_read == false && _write == false);
} }
@ -1084,12 +1080,10 @@ public:
typedef std::map<unsigned int, VariableUsage> VariableMap; typedef std::map<unsigned int, VariableUsage> VariableMap;
void clear() void clear() {
{
_varUsage.clear(); _varUsage.clear();
} }
VariableMap &varUsage() VariableMap &varUsage() {
{
return _varUsage; return _varUsage;
} }
void addVar(const Token *name, VariableType type, ScopeInfo *scope, bool write_); void addVar(const Token *name, VariableType type, ScopeInfo *scope, bool write_);
@ -1104,8 +1098,7 @@ public:
void modified(unsigned int varid); void modified(unsigned int varid);
VariableUsage *find(unsigned int varid); VariableUsage *find(unsigned int varid);
void alias(unsigned int varid1, unsigned int varid2, bool replace); void alias(unsigned int varid1, unsigned int varid2, bool replace);
void erase(unsigned int varid) void erase(unsigned int varid) {
{
_varUsage.erase(varid); _varUsage.erase(varid);
} }
void eraseAliases(unsigned int 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 // Determine the total size of all of the files to check, so that we can
// show an accurate progress estimate // show an accurate progress estimate
quint64 sizeOfFiles = 0; quint64 sizeOfFiles = 0;
foreach (const QString& file, files) { foreach(const QString& file, files) {
sizeOfFiles += QFile(file).size(); sizeOfFiles += QFile(file).size();
} }
mMaxProgress = sizeOfFiles; mMaxProgress = sizeOfFiles;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -39,8 +39,7 @@ public:
static bigint toLongNumber(const std::string & str); static bigint toLongNumber(const std::string & str);
static biguint toULongNumber(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; std::ostringstream result;
result << value; result << value;
return result.str(); return result.str();

View File

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

View File

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

View File

@ -247,8 +247,7 @@ 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); 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; file0 = f;
} }

View File

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

View File

@ -121,8 +121,7 @@ public:
struct SuppressionEntry { struct SuppressionEntry {
SuppressionEntry(const std::string &aid, const std::string &afile, unsigned int aline) 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; std::string id;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -23,14 +23,12 @@
class TestMathLib : public TestFixture { class TestMathLib : public TestFixture {
public: public:
TestMathLib() : TestFixture("TestMathLib") TestMathLib() : TestFixture("TestMathLib") {
{
} }
private: private:
void run() void run() {
{
TEST_CASE(isint); TEST_CASE(isint);
TEST_CASE(isbin); TEST_CASE(isbin);
TEST_CASE(isdec); TEST_CASE(isdec);
@ -58,49 +56,42 @@ private:
TEST_CASE(abs); TEST_CASE(abs);
} }
void isGreater() const void isGreater() const {
{
ASSERT_EQUALS(true , MathLib::isGreater("1.0", "0.001")); ASSERT_EQUALS(true , MathLib::isGreater("1.0", "0.001"));
ASSERT_EQUALS(false, 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.00", "1.0"));
ASSERT_EQUALS(true , MathLib::isGreaterEqual("1.001", "1.0")); ASSERT_EQUALS(true , MathLib::isGreaterEqual("1.001", "1.0"));
ASSERT_EQUALS(true , MathLib::isGreaterEqual("1.0", "0.001")); ASSERT_EQUALS(true , MathLib::isGreaterEqual("1.0", "0.001"));
ASSERT_EQUALS(false, 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(true , MathLib::isEqual("1.0", "1.0"));
ASSERT_EQUALS(false , MathLib::isEqual("1.", "1.01")); ASSERT_EQUALS(false , MathLib::isEqual("1.", "1.01"));
ASSERT_EQUALS(true , MathLib::isEqual("0.1","1.0E-1")); 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(false , MathLib::isNotEqual("1.0", "1.0"));
ASSERT_EQUALS(true , MathLib::isNotEqual("1.", "1.01")); 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(false , MathLib::isLess("1.0", "0.001"));
ASSERT_EQUALS(true , 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(true , MathLib::isLessEqual("1.00", "1.0"));
ASSERT_EQUALS(false , MathLib::isLessEqual("1.001", "1.0")); ASSERT_EQUALS(false , MathLib::isLessEqual("1.001", "1.0"));
ASSERT_EQUALS(false , MathLib::isLessEqual("1.0", "0.001")); ASSERT_EQUALS(false , MathLib::isLessEqual("1.0", "0.001"));
ASSERT_EQUALS(true , MathLib::isLessEqual("-1.0", "0.001")); ASSERT_EQUALS(true , MathLib::isLessEqual("-1.0", "0.001"));
} }
void calculate() const void calculate() const {
{
// addition // addition
ASSERT_EQUALS("256", MathLib::add("0xff", "1")); ASSERT_EQUALS("256", MathLib::add("0xff", "1"));
ASSERT_EQUALS("249", MathLib::add("250", "-1")); ASSERT_EQUALS("249", MathLib::add("250", "-1"));
@ -153,8 +144,7 @@ private:
ASSERT_THROW(MathLib::calculate("1","2",'j'),InternalError); ASSERT_THROW(MathLib::calculate("1","2",'j'),InternalError);
} }
void calculate1() const void calculate1() const {
{
ASSERT_EQUALS("0" , MathLib::calculate("2" , "1" , '%')); ASSERT_EQUALS("0" , MathLib::calculate("2" , "1" , '%'));
ASSERT_EQUALS("0.0" , MathLib::calculate("2.0" , "1.0" , '%')); ASSERT_EQUALS("0.0" , MathLib::calculate("2.0" , "1.0" , '%'));
ASSERT_EQUALS("2" , MathLib::calculate("12" , "5" , '%')); ASSERT_EQUALS("2" , MathLib::calculate("12" , "5" , '%'));
@ -169,8 +159,7 @@ private:
ASSERT_EQUALS("3" , MathLib::calculate("2" , "1" , '^')); ASSERT_EQUALS("3" , MathLib::calculate("2" , "1" , '^'));
} }
void convert() const void convert() const {
{
// ------------------ // ------------------
// tolong conversion: // tolong conversion:
// ------------------ // ------------------
@ -260,8 +249,7 @@ private:
ASSERT_EQUALS("0.0" , MathLib::toString(MathLib::toDoubleNumber("+0.0"))); ASSERT_EQUALS("0.0" , MathLib::toString(MathLib::toDoubleNumber("+0.0")));
} }
void isint() const void isint() const {
{
// zero tests // zero tests
ASSERT_EQUALS(true , MathLib::isInt("0")); ASSERT_EQUALS(true , MathLib::isInt("0"));
ASSERT_EQUALS(false, MathLib::isInt("0.")); ASSERT_EQUALS(false, MathLib::isInt("0."));
@ -350,8 +338,7 @@ private:
ASSERT_EQUALS(false, MathLib::isInt("")); ASSERT_EQUALS(false, MathLib::isInt(""));
} }
void isbin() const void isbin() const {
{
// positive testing // positive testing
ASSERT_EQUALS(true, MathLib::isBin("0b0")); ASSERT_EQUALS(true, MathLib::isBin("0b0"));
ASSERT_EQUALS(true, MathLib::isBin("0b1")); ASSERT_EQUALS(true, MathLib::isBin("0b1"));
@ -391,8 +378,7 @@ private:
ASSERT_EQUALS(false, MathLib::isBin("")); 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.")); ASSERT_EQUALS(true , MathLib::isNegative("-1."));
ASSERT_EQUALS(true , MathLib::isNegative("-1.0")); ASSERT_EQUALS(true , MathLib::isNegative("-1.0"));
@ -408,8 +394,7 @@ private:
ASSERT_EQUALS(false, MathLib::isNegative("")); ASSERT_EQUALS(false, MathLib::isNegative(""));
} }
void isoct() const void isoct() const {
{
// octal number format: [+|-]0[0-7][suffix] // octal number format: [+|-]0[0-7][suffix]
// positive testing // positive testing
ASSERT_EQUALS(true, MathLib::isOct("010")); ASSERT_EQUALS(true, MathLib::isOct("010"));
@ -471,8 +456,7 @@ private:
ASSERT_EQUALS(false, MathLib::isOct("+042LUL+0")); ASSERT_EQUALS(false, MathLib::isOct("+042LUL+0"));
} }
void ishex() const void ishex() const {
{
// hex number syntax: [sign]0x[hexnumbers][suffix] // hex number syntax: [sign]0x[hexnumbers][suffix]
// positive testing // positive testing
@ -534,8 +518,7 @@ private:
ASSERT_EQUALS(false, MathLib::isHex("")); ASSERT_EQUALS(false, MathLib::isHex(""));
} }
void isValidSuffix(void) void isValidSuffix(void) {
{
// negative testing // negative testing
std::string value = "ux"; std::string value = "ux";
ASSERT_EQUALS(false, MathLib::isValidSuffix(value.begin(), value.end())); ASSERT_EQUALS(false, MathLib::isValidSuffix(value.begin(), value.end()));
@ -605,8 +588,7 @@ private:
ASSERT_EQUALS(true, MathLib::isValidSuffix(value.begin(), value.end())); ASSERT_EQUALS(true, MathLib::isValidSuffix(value.begin(), value.end()));
} }
void ispositive() const void ispositive() const {
{
ASSERT_EQUALS(false, MathLib::isPositive("-1")); ASSERT_EQUALS(false, MathLib::isPositive("-1"));
ASSERT_EQUALS(false, MathLib::isPositive("-1.")); ASSERT_EQUALS(false, MathLib::isPositive("-1."));
ASSERT_EQUALS(false, MathLib::isPositive("-1.0")); ASSERT_EQUALS(false, MathLib::isPositive("-1.0"));
@ -623,8 +605,7 @@ private:
ASSERT_EQUALS(true, MathLib::isPositive("")); // because it has opposite result to MathLib::isNegative 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(".")); ASSERT_EQUALS(false, MathLib::isFloat("."));
ASSERT_EQUALS(false, MathLib::isFloat("...")); ASSERT_EQUALS(false, MathLib::isFloat("..."));
@ -718,8 +699,7 @@ private:
ASSERT_EQUALS(true , MathLib::isFloat("-1.0E+1")); 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.0")); // nan
ASSERT_EQUALS("nan.0", MathLib::divide("0.0", "0.f")); // nan (#5875) ASSERT_EQUALS("nan.0", MathLib::divide("0.0", "0.f")); // nan (#5875)
ASSERT_EQUALS("nan.0", MathLib::divide("-0.0", "0.f")); // nan (#5875) ASSERT_EQUALS("nan.0", MathLib::divide("-0.0", "0.f")); // nan (#5875)
@ -735,8 +715,7 @@ private:
ASSERT_EQUALS("inf.0", MathLib::divide("-3.0", "-0.0f")); // inf (#5142) ASSERT_EQUALS("inf.0", MathLib::divide("-3.0", "-0.0f")); // inf (#5142)
} }
void isdec(void) void isdec(void) {
{
// positive testing // positive testing
ASSERT_EQUALS(true, MathLib::isDec("1")); ASSERT_EQUALS(true, MathLib::isDec("1"));
ASSERT_EQUALS(true, MathLib::isDec("+1")); ASSERT_EQUALS(true, MathLib::isDec("+1"));
@ -753,8 +732,7 @@ private:
ASSERT_EQUALS(false, MathLib::isDec("x")); ASSERT_EQUALS(false, MathLib::isDec("x"));
} }
void isNullValue() const void isNullValue() const {
{
// inter zero value // inter zero value
ASSERT_EQUALS(true, MathLib::isNullValue("0")); ASSERT_EQUALS(true, MathLib::isNullValue("0"));
ASSERT_EQUALS(true, MathLib::isNullValue("+0")); ASSERT_EQUALS(true, MathLib::isNullValue("+0"));
@ -923,8 +901,7 @@ private:
ASSERT_EQUALS(false, MathLib::isNullValue("UL")); ASSERT_EQUALS(false, MathLib::isNullValue("UL"));
} }
void incdec() void incdec() {
{
// increment // increment
{ {
MathLib::biguint num = ~10U; MathLib::biguint num = ~10U;
@ -945,20 +922,16 @@ private:
ASSERT_THROW(MathLib::incdec("1", "x"), InternalError); // throw ASSERT_THROW(MathLib::incdec("1", "x"), InternalError); // throw
} }
void sin() void sin() {
{
ASSERT_EQUALS("0.0" , MathLib::sin("0")); ASSERT_EQUALS("0.0" , MathLib::sin("0"));
} }
void cos() void cos() {
{
ASSERT_EQUALS("1.0" , MathLib::cos("0")); ASSERT_EQUALS("1.0" , MathLib::cos("0"));
} }
void tan() void tan() {
{
ASSERT_EQUALS("0.0" , MathLib::tan("0")); 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")); 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,20 +27,17 @@ extern std::ostringstream errout;
class TestNonReentrantFunctions : public TestFixture { class TestNonReentrantFunctions : public TestFixture {
public: public:
TestNonReentrantFunctions() : TestFixture("TestNonReentrantFunctions") TestNonReentrantFunctions() : TestFixture("TestNonReentrantFunctions") {
{
} }
private: private:
void run() void run() {
{
TEST_CASE(test_crypt); TEST_CASE(test_crypt);
TEST_CASE(test_namespace_handling); TEST_CASE(test_namespace_handling);
} }
void check(const char code[]) void check(const char code[]) {
{
// Clear the error buffer.. // Clear the error buffer..
errout.str(""); errout.str("");
@ -59,8 +56,7 @@ private:
checkNonReentrantFunctions.nonReentrantFunctions(); checkNonReentrantFunctions.nonReentrantFunctions();
} }
void test_crypt() void test_crypt() {
{
check("void f(char *pwd)\n" check("void f(char *pwd)\n"
"{\n" "{\n"
" char *cpwd;" " char *cpwd;"
@ -84,8 +80,7 @@ private:
ASSERT_EQUALS("", errout.str()); ASSERT_EQUALS("", errout.str());
} }
void test_namespace_handling() void test_namespace_handling() {
{
check("int f()\n" check("int f()\n"
"{\n" "{\n"
" time_t t = 0;" " time_t t = 0;"

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