From 0cad22314efc920af371fd911066ff18a63f7c30 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?= Date: Fri, 2 Apr 2010 07:30:58 +0200 Subject: [PATCH] Reverted 'astyle fix'. Those changes are not in sync with my astyle configuration/setup. --- cli/cppcheckexecutor.cpp | 22 +- cli/threadexecutor.cpp | 40 +- gui/aboutdialog.cpp | 2 +- gui/applicationdialog.cpp | 8 +- gui/applicationlist.cpp | 22 +- gui/checkthread.cpp | 12 +- gui/csvreport.cpp | 4 +- gui/fileviewdialog.cpp | 6 +- gui/mainwindow.cpp | 88 +- gui/projectfile.cpp | 42 +- gui/report.cpp | 8 +- gui/resultstree.cpp | 144 +- gui/resultsview.cpp | 25 +- gui/settingsdialog.cpp | 24 +- gui/threadhandler.cpp | 28 +- gui/threadresult.cpp | 8 +- gui/translationhandler.cpp | 44 +- gui/txtreport.cpp | 10 +- gui/xmlreport.cpp | 4 +- lib/check.h | 16 +- lib/checkautovariables.cpp | 156 +- lib/checkautovariables.h | 2 +- lib/checkbufferoverrun.cpp | 440 +++--- lib/checkbufferoverrun.h | 2 +- lib/checkclass.cpp | 742 ++++----- lib/checkclass.h | 16 +- lib/checkdangerousfunctions.cpp | 8 +- lib/checkdangerousfunctions.h | 4 +- lib/checkexceptionsafety.cpp | 172 +-- lib/checkexceptionsafety.h | 2 +- lib/checkheaders.cpp | 88 +- lib/checkmemoryleak.cpp | 1032 ++++++------- lib/checkmemoryleak.h | 8 +- lib/checkother.cpp | 984 ++++++------ lib/checkother.h | 18 +- lib/checkstl.cpp | 292 ++-- lib/checkstl.h | 6 +- lib/checkunusedfunctions.cpp | 74 +- lib/cppcheck.cpp | 312 ++-- lib/errorlogger.cpp | 56 +- lib/errorlogger.h | 2 +- lib/executionpath.cpp | 106 +- lib/executionpath.h | 8 +- lib/filelister.cpp | 34 +- lib/filelister_unix.cpp | 12 +- lib/filelister_win32.cpp | 20 +- lib/mathlib.cpp | 108 +- lib/mathlib.h | 4 +- lib/preprocessor.cpp | 676 ++++---- lib/settings.cpp | 48 +- lib/token.cpp | 234 +-- lib/tokenize.cpp | 2556 +++++++++++++++---------------- test/testbufferoverrun.cpp | 4 +- test/testmathlib.cpp | 20 +- test/testmemleak.cpp | 20 +- test/testother.cpp | 14 +- test/testsimplifytokens.cpp | 58 +- test/teststl.cpp | 9 +- test/testsuite.cpp | 32 +- test/testtoken.cpp | 4 +- test/testtokenize.cpp | 82 +- test/testunusedvar.cpp | 2 +- tools/dmake.cpp | 42 +- tools/extracttests.cpp | 122 +- 64 files changed, 4593 insertions(+), 4595 deletions(-) mode change 100644 => 100755 lib/settings.cpp diff --git a/cli/cppcheckexecutor.cpp b/cli/cppcheckexecutor.cpp index d754afcd3..a1d0a52de 100644 --- a/cli/cppcheckexecutor.cpp +++ b/cli/cppcheckexecutor.cpp @@ -41,25 +41,25 @@ int CppCheckExecutor::check(int argc, const char* const argv[]) { cppCheck.parseFromArgs(argc, argv); } - catch(std::runtime_error &e) + catch (std::runtime_error &e) { std::cerr << e.what() << std::endl; return EXIT_FAILURE; } _settings = cppCheck.settings(); - if(_settings._xml) + if (_settings._xml) { reportErr(ErrorLogger::ErrorMessage::getXMLHeader()); } unsigned int returnValue = 0; - if(_settings._jobs == 1) + if (_settings._jobs == 1) { // Single process returnValue = cppCheck.check(); } - else if(!ThreadExecutor::isEnabled()) + else if (!ThreadExecutor::isEnabled()) { std::cout << "No thread support yet implemented for this platform." << std::endl; } @@ -72,12 +72,12 @@ int CppCheckExecutor::check(int argc, const char* const argv[]) returnValue = executor.check(); } - if(_settings._xml) + if (_settings._xml) { reportErr(ErrorLogger::ErrorMessage::getXMLFooter()); } - if(returnValue) + if (returnValue) return _settings._exitCode; else return 0; @@ -95,20 +95,20 @@ void CppCheckExecutor::reportOut(const std::string &outmsg) void CppCheckExecutor::reportStatus(unsigned int index, unsigned int max) { - if(max > 1 && !_settings._errorsOnly) + if (max > 1 && !_settings._errorsOnly) { std::ostringstream oss; oss << index << "/" << max - << " files checked " << - static_cast(static_cast(index) / max * 100) - << "% done"; + << " files checked " << + static_cast(static_cast(index) / max*100) + << "% done"; std::cout << oss.str() << std::endl; } } void CppCheckExecutor::reportErr(const ErrorLogger::ErrorMessage &msg) { - if(_settings._xml) + if (_settings._xml) { reportErr(msg.toXML()); } diff --git a/cli/threadexecutor.cpp b/cli/threadexecutor.cpp index fa1a81fac..7ac40f2ce 100644 --- a/cli/threadexecutor.cpp +++ b/cli/threadexecutor.cpp @@ -30,7 +30,7 @@ #endif ThreadExecutor::ThreadExecutor(const std::vector &filenames, const Settings &settings, ErrorLogger &errorLogger) - : _filenames(filenames), _settings(settings), _errorLogger(errorLogger), _fileCount(0) + : _filenames(filenames), _settings(settings), _errorLogger(errorLogger), _fileCount(0) { } @@ -49,49 +49,49 @@ ThreadExecutor::~ThreadExecutor() bool ThreadExecutor::handleRead(unsigned int &result) { char type = 0; - if(read(_pipe[0], &type, 1) <= 0) + if (read(_pipe[0], &type, 1) <= 0) { return false; } - if(type != '1' && type != '2' && type != '3') + if (type != '1' && type != '2' && type != '3') { std::cerr << "#### You found a bug from cppcheck.\nThreadExecutor::handleRead error, type was:" << type << std::endl; exit(0); } unsigned int len = 0; - if(read(_pipe[0], &len, sizeof(len)) <= 0) + if (read(_pipe[0], &len, sizeof(len)) <= 0) { std::cerr << "#### You found a bug from cppcheck.\nThreadExecutor::handleRead error, type was:" << type << std::endl; exit(0); } char *buf = new char[len]; - if(read(_pipe[0], buf, len) <= 0) + if (read(_pipe[0], buf, len) <= 0) { std::cerr << "#### You found a bug from cppcheck.\nThreadExecutor::handleRead error, type was:" << type << std::endl; exit(0); } - if(type == '1') + if (type == '1') { _errorLogger.reportOut(buf); } - else if(type == '2') + else if (type == '2') { ErrorLogger::ErrorMessage msg; msg.deserialize(buf); // Alert only about unique errors std::string errmsg = msg.toText(); - if(std::find(_errorList.begin(), _errorList.end(), errmsg) == _errorList.end()) + if (std::find(_errorList.begin(), _errorList.end(), errmsg) == _errorList.end()) { _errorList.push_back(errmsg); _errorLogger.reportErr(msg); } } - else if(type == '3') + else if (type == '3') { _fileCount++; std::istringstream iss(buf); @@ -109,32 +109,32 @@ unsigned int ThreadExecutor::check() { _fileCount = 0; unsigned int result = 0; - if(pipe(_pipe) == -1) + if (pipe(_pipe) == -1) { perror("pipe"); exit(1); } int flags = 0; - if((flags = fcntl(_pipe[0], F_GETFL, 0)) < 0) + if ((flags = fcntl(_pipe[0], F_GETFL, 0)) < 0) { perror("fcntl"); exit(1); } - if(fcntl(_pipe[0], F_SETFL, flags | O_NONBLOCK) < 0) + if (fcntl(_pipe[0], F_SETFL, flags | O_NONBLOCK) < 0) { perror("fcntl"); exit(1); } unsigned int childCount = 0; - for(unsigned int i = 0; i < _filenames.size(); i++) + for (unsigned int i = 0; i < _filenames.size(); i++) { // Keep only wanted amount of child processes running at a time. - if(childCount >= _settings._jobs) + if (childCount >= _settings._jobs) { - while(handleRead(result)) + while (handleRead(result)) { } @@ -145,13 +145,13 @@ unsigned int ThreadExecutor::check() } pid_t pid = fork(); - if(pid < 0) + if (pid < 0) { // Error std::cerr << "Failed to create child process" << std::endl; exit(EXIT_FAILURE); } - else if(pid == 0) + else if (pid == 0) { CppCheck fileChecker(*this); fileChecker.settings(_settings); @@ -166,14 +166,14 @@ unsigned int ThreadExecutor::check() ++childCount; } - while(childCount > 0) + while (childCount > 0) { int stat = 0; waitpid(0, &stat, 0); --childCount; } - while(handleRead(result)) + while (handleRead(result)) { } @@ -188,7 +188,7 @@ void ThreadExecutor::writeToPipe(char type, const std::string &data) out[0] = type; std::memcpy(&(out[1]), &len, sizeof(len)); std::memcpy(&(out[1+sizeof(len)]), data.c_str(), len); - if(write(_pipe[1], out, len + 1 + sizeof(len)) <= 0) + if (write(_pipe[1], out, len + 1 + sizeof(len)) <= 0) { delete [] out; out = 0; diff --git a/gui/aboutdialog.cpp b/gui/aboutdialog.cpp index 820e550a8..ffaf39bef 100644 --- a/gui/aboutdialog.cpp +++ b/gui/aboutdialog.cpp @@ -23,7 +23,7 @@ #include "aboutdialog.h" AboutDialog::AboutDialog(const QString &version, QWidget *parent) - : QDialog(parent) + : QDialog(parent) { mUI.setupUi(this); diff --git a/gui/applicationdialog.cpp b/gui/applicationdialog.cpp index 7fab211c4..bd05b88dd 100644 --- a/gui/applicationdialog.cpp +++ b/gui/applicationdialog.cpp @@ -30,7 +30,7 @@ ApplicationDialog::ApplicationDialog(const QString &name, const QString &path, const QString &title, QWidget *parent) : - QDialog(parent) + QDialog(parent) { mUI.setupUi(this); @@ -61,13 +61,13 @@ void ApplicationDialog::Browse() QString(), filter); - if(!selectedFile.isEmpty()) + if (!selectedFile.isEmpty()) { QString path(QDir::toNativeSeparators(selectedFile)); // In Windows we must surround paths including spaces with quotation marks. #ifdef Q_WS_WIN - if(path.indexOf(" ") > -1) + if (path.indexOf(" ") > -1) { path.insert(0, "\""); path.append("\""); @@ -91,7 +91,7 @@ QString ApplicationDialog::GetPath() void ApplicationDialog::Ok() { - if(mUI.mName->text().isEmpty() || mUI.mPath->text().isEmpty()) + if (mUI.mName->text().isEmpty() || mUI.mPath->text().isEmpty()) { QMessageBox msg(QMessageBox::Warning, tr("Cppcheck"), diff --git a/gui/applicationlist.cpp b/gui/applicationlist.cpp index 910a8883c..3ec874a1d 100644 --- a/gui/applicationlist.cpp +++ b/gui/applicationlist.cpp @@ -21,7 +21,7 @@ #include "common.h" ApplicationList::ApplicationList(QObject *parent) : - QObject(parent) + QObject(parent) { //ctor } @@ -37,9 +37,9 @@ void ApplicationList::LoadSettings(QSettings *programSettings) QStringList names = programSettings->value(SETTINGS_APPLICATION_NAMES, QStringList()).toStringList(); QStringList paths = programSettings->value(SETTINGS_APPLICATION_PATHS, QStringList()).toStringList(); - if(names.size() == paths.size()) + if (names.size() == paths.size()) { - for(int i = 0; i < names.size(); i++) + for (int i = 0; i < names.size(); i++) { AddApplicationType(names[i], paths[i]); } @@ -51,7 +51,7 @@ void ApplicationList::SaveSettings(QSettings *programSettings) QStringList names; QStringList paths; - for(int i = 0; i < GetApplicationCount(); i++) + for (int i = 0; i < GetApplicationCount(); i++) { names << GetApplicationName(i); paths << GetApplicationPath(i); @@ -69,7 +69,7 @@ int ApplicationList::GetApplicationCount() const QString ApplicationList::GetApplicationName(const int index) const { - if(index >= 0 && index < mApplications.size()) + if (index >= 0 && index < mApplications.size()) { return mApplications[index].Name; } @@ -79,7 +79,7 @@ QString ApplicationList::GetApplicationName(const int index) const QString ApplicationList::GetApplicationPath(const int index) const { - if(index >= 0 && index < mApplications.size()) + if (index >= 0 && index < mApplications.size()) { return mApplications[index].Path; } @@ -93,7 +93,7 @@ void ApplicationList::SetApplicationType(const int index, const QString &name, const QString &path) { - if(index >= 0 && index < mApplications.size()) + if (index >= 0 && index < mApplications.size()) { mApplications[index].Name = name; mApplications[index].Path = path; @@ -102,7 +102,7 @@ void ApplicationList::SetApplicationType(const int index, void ApplicationList::AddApplicationType(const QString &name, const QString &path) { - if(name.isEmpty() || path.isEmpty()) + if (name.isEmpty() || path.isEmpty()) { return; } @@ -121,7 +121,7 @@ void ApplicationList::RemoveApplication(const int index) void ApplicationList::MoveFirst(const int index) { - if(index < mApplications.size() && index > 0) + if (index < mApplications.size() && index > 0) { mApplications.move(index, 0); } @@ -130,13 +130,13 @@ void ApplicationList::MoveFirst(const int index) void ApplicationList::Copy(ApplicationList *list) { - if(!list) + if (!list) { return; } Clear(); - for(int i = 0; i < list->GetApplicationCount(); i++) + for (int i = 0; i < list->GetApplicationCount(); i++) { AddApplicationType(list->GetApplicationName(i), list->GetApplicationPath(i)); } diff --git a/gui/checkthread.cpp b/gui/checkthread.cpp index b23308677..5bf68a8e9 100644 --- a/gui/checkthread.cpp +++ b/gui/checkthread.cpp @@ -21,9 +21,9 @@ #include CheckThread::CheckThread(ThreadResult &result) : - mState(Ready), - mResult(result), - mCppcheck(result) + mState(Ready), + mResult(result), + mCppcheck(result) { //ctor } @@ -45,7 +45,7 @@ void CheckThread::run() QString file; file = mResult.GetNextFile(); - while(!file.isEmpty() && mState == Running) + while (!file.isEmpty() && mState == Running) { qDebug() << "Checking file" << file; mCppcheck.addFile(file.toStdString()); @@ -53,10 +53,10 @@ void CheckThread::run() mCppcheck.clearFiles(); emit FileChecked(file); - if(mState == Running) + if (mState == Running) file = mResult.GetNextFile(); } - if(mState == Running) + if (mState == Running) mState = Ready; else mState = Stopped; diff --git a/gui/csvreport.cpp b/gui/csvreport.cpp index 8eedb640b..241bb7011 100644 --- a/gui/csvreport.cpp +++ b/gui/csvreport.cpp @@ -21,7 +21,7 @@ #include "csvreport.h" CsvReport::CsvReport(const QString &filename, QObject * parent) : - Report(filename, parent) + Report(filename, parent) { } @@ -33,7 +33,7 @@ CsvReport::~CsvReport() bool CsvReport::Create() { bool success = false; - if(Report::Create()) + if (Report::Create()) { mTxtWriter.setDevice(Report::GetFile()); success = true; diff --git a/gui/fileviewdialog.cpp b/gui/fileviewdialog.cpp index 05119f8b4..183d90a69 100644 --- a/gui/fileviewdialog.cpp +++ b/gui/fileviewdialog.cpp @@ -29,7 +29,7 @@ FileViewDialog::FileViewDialog(const QString &file, const QString &title, QWidget *parent) - : QDialog(parent) + : QDialog(parent) { mUI.setupUi(this); @@ -42,7 +42,7 @@ FileViewDialog::FileViewDialog(const QString &file, void FileViewDialog::LoadTextFile(const QString &filename, QTextEdit *edit) { QFile file(filename); - if(!file.exists()) + if (!file.exists()) { QString msg(tr("Could not find the file: %1")); msg = msg.arg(filename); @@ -57,7 +57,7 @@ void FileViewDialog::LoadTextFile(const QString &filename, QTextEdit *edit) } file.open(QIODevice::ReadOnly | QIODevice::Text); - if(!file.isReadable()) + if (!file.isReadable()) { QString msg(tr("Could not read the file: %1")); msg = msg.arg(filename); diff --git a/gui/mainwindow.cpp b/gui/mainwindow.cpp index 701a38d01..1508f62bb 100644 --- a/gui/mainwindow.cpp +++ b/gui/mainwindow.cpp @@ -41,10 +41,10 @@ #endif MainWindow::MainWindow() : - mSettings(new QSettings("Cppcheck", "Cppcheck-GUI", this)), - mApplications(new ApplicationList(this)), - mTranslation(new TranslationHandler(this)), - mLanguages(new QActionGroup(this)) + mSettings(new QSettings("Cppcheck", "Cppcheck-GUI", this)), + mApplications(new ApplicationList(this)), + mTranslation(new TranslationHandler(this)), + mLanguages(new QActionGroup(this)) { mUI.setupUi(this); mUI.mResults->Initialize(mSettings, mApplications); @@ -102,7 +102,7 @@ MainWindow::MainWindow() : QStringList args = QCoreApplication::arguments(); //Remove the application itself args.removeFirst(); - if(!args.isEmpty()) + if (!args.isEmpty()) { DoCheckFiles(args); } @@ -116,7 +116,7 @@ void MainWindow::CreateLanguageMenuItems() { QStringList languages = mTranslation->GetNames(); - for(int i = 0; i < languages.size(); i++) + for (int i = 0; i < languages.size(); i++) { //Create an action for each language //Language name is pre translated @@ -131,7 +131,7 @@ void MainWindow::CreateLanguageMenuItems() mLanguages->addAction(temp); //Check it if it's the value stored to settings - if(i == mSettings->value(SETTINGS_LANGUAGE, 0).toInt()) + if (i == mSettings->value(SETTINGS_LANGUAGE, 0).toInt()) { temp->setChecked(true); } @@ -147,7 +147,7 @@ void MainWindow::CreateLanguageMenuItems() void MainWindow::LoadSettings() { - if(mSettings->value(SETTINGS_WINDOW_MAXIMIZED, false).toBool()) + if (mSettings->value(SETTINGS_WINDOW_MAXIMIZED, false).toBool()) { showMaximized(); } @@ -198,7 +198,7 @@ void MainWindow::SaveSettings() void MainWindow::DoCheckFiles(const QStringList &files) { - if(files.isEmpty()) + if (files.isEmpty()) { return; } @@ -215,7 +215,7 @@ void MainWindow::DoCheckFiles(const QStringList &files) mUI.mResults->Clear(); mThread->ClearFiles(); - if(fileNames.isEmpty()) + if (fileNames.isEmpty()) { QMessageBox msg(QMessageBox::Warning, tr("Cppcheck"), @@ -248,12 +248,12 @@ QStringList MainWindow::SelectFilesToCheck(QFileDialog::FileMode mode) // NOTE: we use QFileDialog::getOpenFileNames() and // QFileDialog::getExistingDirectory() because they show native Windows // selection dialog which is a lot more usable than QT:s own dialog. - if(mode == QFileDialog::ExistingFiles) + if (mode == QFileDialog::ExistingFiles) { selected = QFileDialog::getOpenFileNames(this, tr("Select files to check"), mSettings->value(SETTINGS_CHECK_PATH, "").toString()); - if(selected.isEmpty()) + if (selected.isEmpty()) mCurrentDirectory.clear(); else { @@ -262,12 +262,12 @@ QStringList MainWindow::SelectFilesToCheck(QFileDialog::FileMode mode) } FormatAndSetTitle(); } - else if(mode == QFileDialog::DirectoryOnly) + else if (mode == QFileDialog::DirectoryOnly) { QString dir = QFileDialog::getExistingDirectory(this, tr("Select directory to check"), mSettings->value(SETTINGS_CHECK_PATH, "").toString()); - if(!dir.isEmpty()) + if (!dir.isEmpty()) { mCurrentDirectory = dir; selected.append(dir); @@ -294,20 +294,20 @@ Settings MainWindow::GetCppcheckSettings() ProjectFile pfile; Settings result; - if(!mCurrentDirectory.isEmpty()) + if (!mCurrentDirectory.isEmpty()) { // Format project filename (directory name + .cppcheck) and load // the project file if it is found. QStringList parts = mCurrentDirectory.split("/"); QString projfile = mCurrentDirectory + "/" + parts[parts.count() - 1] + ".cppcheck"; bool projectRead = false; - if(QFile::exists(projfile)) + if (QFile::exists(projfile)) { qDebug() << "Reading project file " << projfile; projectRead = pfile.Read(projfile); } - if(projectRead) + if (projectRead) { QStringList classes = pfile.GetDeAllocatedClasses(); QString classname; @@ -321,13 +321,13 @@ Settings MainWindow::GetCppcheckSettings() foreach(dir, dirs) { QString incdir; - if(!QDir::isAbsolutePath(dir)) + if (!QDir::isAbsolutePath(dir)) incdir = mCurrentDirectory + "/"; incdir += dir; incdir = QDir::cleanPath(incdir); // include paths must end with '/' - if(!incdir.endsWith("/")) + if (!incdir.endsWith("/")) incdir += "/"; result._includePaths.push_back(incdir.toStdString()); } @@ -343,7 +343,7 @@ Settings MainWindow::GetCppcheckSettings() result._xml = false; result._jobs = mSettings->value(SETTINGS_CHECK_THREADS, 1).toInt(); - if(result._jobs <= 0) + if (result._jobs <= 0) { result._jobs = 1; } @@ -356,11 +356,11 @@ QStringList MainWindow::GetFilesRecursively(const QString &path) QFileInfo info(path); QStringList list; - if(info.isDir()) + if (info.isDir()) { QDirIterator it(path, QDirIterator::Subdirectories); - while(it.hasNext()) + while (it.hasNext()) { list << it.next(); } @@ -379,7 +379,7 @@ QStringList MainWindow::RemoveUnacceptedFiles(const QStringList &list) QString str; foreach(str, list) { - if(getFileLister()->acceptFile(str.toStdString())) + if (getFileLister()->acceptFile(str.toStdString())) { result << str; } @@ -392,7 +392,7 @@ void MainWindow::CheckDone() { EnableCheckButtons(true); mUI.mActionSettings->setEnabled(true); - if(mUI.mResults->HasResults()) + if (mUI.mResults->HasResults()) { mUI.mActionClearResults->setEnabled(true); mUI.mActionSave->setEnabled(true); @@ -405,7 +405,7 @@ void MainWindow::CheckDone() void MainWindow::ProgramSettings() { SettingsDialog dialog(mSettings, mApplications, this); - if(dialog.exec() == QDialog::Accepted) + if (dialog.exec() == QDialog::Accepted) { dialog.SaveCheckboxValues(); mUI.mResults->UpdateSettings(dialog.ShowFullPath(), @@ -434,7 +434,7 @@ void MainWindow::EnableCheckButtons(bool enable) mUI.mActionStop->setEnabled(!enable); mUI.mActionCheckFiles->setEnabled(enable); - if(!enable || mThread->HasPreviousFiles()) + if (!enable || mThread->HasPreviousFiles()) mUI.mActionRecheck->setEnabled(enable); mUI.mActionCheckDirectory->setEnabled(enable); @@ -473,7 +473,7 @@ void MainWindow::UncheckAll() void MainWindow::closeEvent(QCloseEvent *event) { // Check that we aren't checking files - if(!mThread->IsChecking()) + if (!mThread->IsChecking()) { SaveSettings(); event->accept(); @@ -539,34 +539,34 @@ void MainWindow::Save() filter, &selectedFilter); - if(!selectedFile.isEmpty()) + if (!selectedFile.isEmpty()) { Report::Type type = Report::TXT; - if(selectedFilter == tr("XML files (*.xml)")) + if (selectedFilter == tr("XML files (*.xml)")) { type = Report::XML; - if(!selectedFile.endsWith(".xml", Qt::CaseInsensitive)) + if (!selectedFile.endsWith(".xml", Qt::CaseInsensitive)) selectedFile += ".xml"; } - else if(selectedFilter == tr("Text files (*.txt)")) + else if (selectedFilter == tr("Text files (*.txt)")) { type = Report::TXT; - if(!selectedFile.endsWith(".txt", Qt::CaseInsensitive)) + if (!selectedFile.endsWith(".txt", Qt::CaseInsensitive)) selectedFile += ".txt"; } - else if(selectedFilter == tr("CSV files (*.csv)")) + else if (selectedFilter == tr("CSV files (*.csv)")) { type = Report::CSV; - if(!selectedFile.endsWith(".csv", Qt::CaseInsensitive)) + if (!selectedFile.endsWith(".csv", Qt::CaseInsensitive)) selectedFile += ".csv"; } else { - if(selectedFile.endsWith(".xml", Qt::CaseInsensitive)) + if (selectedFile.endsWith(".xml", Qt::CaseInsensitive)) type = Report::XML; - else if(selectedFile.endsWith(".txt", Qt::CaseInsensitive)) + else if (selectedFile.endsWith(".txt", Qt::CaseInsensitive)) type = Report::TXT; - else if(selectedFile.endsWith(".csv", Qt::CaseInsensitive)) + else if (selectedFile.endsWith(".csv", Qt::CaseInsensitive)) type = Report::CSV; } @@ -586,7 +586,7 @@ void MainWindow::ToggleToolbar() void MainWindow::FormatAndSetTitle(const QString &text) { QString title; - if(text.isEmpty()) + if (text.isEmpty()) title = tr("Cppcheck"); else title = QString(tr("Cppcheck - %1")).arg(text); @@ -596,13 +596,13 @@ void MainWindow::FormatAndSetTitle(const QString &text) void MainWindow::SetLanguage(int index) { - if(mTranslation->GetCurrentLanguage() == index) + if (mTranslation->GetCurrentLanguage() == index) { return; } QString error; - if(!mTranslation->SetLanguage(index, error)) + if (!mTranslation->SetLanguage(index, error)) { QMessageBox msg(QMessageBox::Critical, tr("Cppcheck"), @@ -620,9 +620,9 @@ void MainWindow::SetLanguage(int index) QStringList languages = mTranslation->GetNames(); QList actions = mLanguages->actions(); - if(languages.size() <= actions.size()) + if (languages.size() <= actions.size()) { - for(int i = 0; i < languages.size(); i++) + for (int i = 0; i < languages.size(); i++) { actions[i]->setText(tr(languages[i].toLatin1())); } @@ -634,9 +634,9 @@ void MainWindow::MapLanguage(QAction *action) { //Find the action that has the language that user clicked QList actions = mLanguages->actions(); - for(int i = 0; i < actions.size(); i++) + for (int i = 0; i < actions.size(); i++) { - if(actions[i] == action) + if (actions[i] == action) { SetLanguage(i); } diff --git a/gui/projectfile.cpp b/gui/projectfile.cpp index 39f023b03..2d637ba77 100644 --- a/gui/projectfile.cpp +++ b/gui/projectfile.cpp @@ -31,45 +31,45 @@ static const char DirElementName[] = "dir"; static const char DirNameAttrib[] = "name"; ProjectFile::ProjectFile(QObject *parent) : - QObject(parent) + QObject(parent) { } ProjectFile::ProjectFile(const QString &filename, QObject *parent) : - QObject(parent), - mFilename(filename) + QObject(parent), + mFilename(filename) { } bool ProjectFile::Read(const QString &filename) { - if(!filename.isEmpty()) + if (!filename.isEmpty()) mFilename = filename; QFile file(mFilename); - if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) + if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return false; QXmlStreamReader xmlReader(&file); bool insideProject = false; - while(!xmlReader.atEnd()) + while (!xmlReader.atEnd()) { - switch(xmlReader.readNext()) + switch (xmlReader.readNext()) { case QXmlStreamReader::StartElement: - if(xmlReader.name() == ProjectElementName) + if (xmlReader.name() == ProjectElementName) insideProject = true; // Find allocelement from inside project element - if(insideProject && xmlReader.name() == AllocElementName) + if (insideProject && xmlReader.name() == AllocElementName) ReadAutoAllocClasses(xmlReader); - if(insideProject && xmlReader.name() == IncludDirElementName) + if (insideProject && xmlReader.name() == IncludDirElementName) ReadIncludeDirs(xmlReader); break; case QXmlStreamReader::EndElement: - if(xmlReader.name() == ProjectElementName) + if (xmlReader.name() == ProjectElementName) insideProject = false; break; @@ -108,22 +108,22 @@ void ProjectFile::ReadAutoAllocClasses(QXmlStreamReader &reader) do { type = reader.readNext(); - switch(type) + switch (type) { case QXmlStreamReader::StartElement: // Read class-elements - if(reader.name().toString() == ClassElementName) + if (reader.name().toString() == ClassElementName) { QXmlStreamAttributes attribs = reader.attributes(); QString name = attribs.value("", ClassNameAttrib).toString(); - if(!name.isEmpty()) + if (!name.isEmpty()) mDeAllocatedClasses << name; } break; case QXmlStreamReader::EndElement: - if(reader.name().toString() == AllocElementName) + if (reader.name().toString() == AllocElementName) allRead = true; break; @@ -140,7 +140,7 @@ void ProjectFile::ReadAutoAllocClasses(QXmlStreamReader &reader) break; } } - while(!allRead); + while (!allRead); } void ProjectFile::ReadIncludeDirs(QXmlStreamReader &reader) @@ -150,22 +150,22 @@ void ProjectFile::ReadIncludeDirs(QXmlStreamReader &reader) do { type = reader.readNext(); - switch(type) + switch (type) { case QXmlStreamReader::StartElement: // Read dir-elements - if(reader.name().toString() == DirElementName) + if (reader.name().toString() == DirElementName) { QXmlStreamAttributes attribs = reader.attributes(); QString name = attribs.value("", DirNameAttrib).toString(); - if(!name.isEmpty()) + if (!name.isEmpty()) mIncludeDirs << name; } break; case QXmlStreamReader::EndElement: - if(reader.name().toString() == IncludDirElementName) + if (reader.name().toString() == IncludDirElementName) allRead = true; break; @@ -182,5 +182,5 @@ void ProjectFile::ReadIncludeDirs(QXmlStreamReader &reader) break; } } - while(!allRead); + while (!allRead); } diff --git a/gui/report.cpp b/gui/report.cpp index 76c68e4f5..4d263bb7c 100644 --- a/gui/report.cpp +++ b/gui/report.cpp @@ -20,8 +20,8 @@ #include "report.h" Report::Report(const QString &filename, QObject * parent) : - QObject(parent), - mFilename(filename) + QObject(parent), + mFilename(filename) { } @@ -33,7 +33,7 @@ Report::~Report() bool Report::Create() { bool succeed = false; - if(!mFile.isOpen()) + if (!mFile.isOpen()) { mFile.setFileName(mFilename); succeed = mFile.open(QIODevice::WriteOnly | QIODevice::Text); @@ -43,7 +43,7 @@ bool Report::Create() void Report::Close() { - if(mFile.isOpen()) + if (mFile.isOpen()) mFile.close(); } diff --git a/gui/resultstree.cpp b/gui/resultstree.cpp index f387e08ce..15644588f 100644 --- a/gui/resultstree.cpp +++ b/gui/resultstree.cpp @@ -29,12 +29,12 @@ #include "xmlreport.h" ResultsTree::ResultsTree(QWidget * parent) : - QTreeView(parent), - mContextItem(0), - mCheckPath(""), - mVisibleErrors(false) + QTreeView(parent), + mContextItem(0), + mCheckPath(""), + mVisibleErrors(false) { - for(int i = 0; i < SHOW_NONE; i++) + for (int i = 0; i < SHOW_NONE; i++) mShowTypes[i] = false; setModel(&mModel); @@ -76,14 +76,14 @@ void ResultsTree::AddErrorItem(const QString &file, { Q_UNUSED(file); - if(files.isEmpty()) + if (files.isEmpty()) { return; } QString realfile = StripPath(files[0], false); - if(realfile.isEmpty()) + if (realfile.isEmpty()) { realfile = tr("Undefined file"); } @@ -91,7 +91,7 @@ void ResultsTree::AddErrorItem(const QString &file, bool hide = !mShowTypes[SeverityToShowType(severity)]; //if there is at least one error that is not hidden, we have a visible error - if(!hide) + if (!hide) { mVisibleErrors = true; } @@ -106,7 +106,7 @@ void ResultsTree::AddErrorItem(const QString &file, hide, SeverityToIcon(severity)); - if(!item) + if (!item) return; //Add user data to that item @@ -119,7 +119,7 @@ void ResultsTree::AddErrorItem(const QString &file, item->setData(QVariant(data)); //Add backtrace files as children - for(int i = 1; i < files.size() && i < lines.size(); i++) + for (int i = 1; i < files.size() && i < lines.size(); i++) { QStandardItem *child_item; @@ -143,7 +143,7 @@ void ResultsTree::AddErrorItem(const QString &file, //TODO just hide/show current error and it's file //since this does a lot of unnecessary work - if(!hide) + if (!hide) { ShowFileItem(realfile); } @@ -158,7 +158,7 @@ QStandardItem *ResultsTree::AddBacktraceFiles(QStandardItem *parent, const QString &icon) { - if(!parent) + if (!parent) { return 0; } @@ -172,18 +172,18 @@ QStandardItem *ResultsTree::AddBacktraceFiles(QStandardItem *parent, list << CreateItem(tr(message.toLatin1())); // Check for duplicate rows and don't add them if found - for(int i = 0; i < parent->rowCount(); i++) + for (int i = 0; i < parent->rowCount(); i++) { // the first column is the file name and is always the same so skip it // the third column is the line number so check it first - if(parent->child(i, 2)->text() == list[2]->text()) + if (parent->child(i, 2)->text() == list[2]->text()) { // the second column is the severity so check it next - if(parent->child(i, 1)->text() == list[1]->text()) + if (parent->child(i, 1)->text() == list[1]->text()) { // the forth column is the message so check it last - if(parent->child(i, 3)->text() == list[3]->text()) + if (parent->child(i, 3)->text() == list[3]->text()) { // this row matches so don't add it return 0; @@ -196,7 +196,7 @@ QStandardItem *ResultsTree::AddBacktraceFiles(QStandardItem *parent, setRowHidden(parent->rowCount() - 1, parent->index(), hide); - if(!icon.isEmpty()) + if (!icon.isEmpty()) { list[0]->setIcon(QIcon(icon)); } @@ -209,7 +209,7 @@ QStandardItem *ResultsTree::AddBacktraceFiles(QStandardItem *parent, ShowTypes ResultsTree::VariantToShowType(const QVariant &data) { int value = data.toInt(); - if(value < SHOW_ALL && value > SHOW_ERRORS) + if (value < SHOW_ALL && value > SHOW_ERRORS) { return SHOW_NONE; } @@ -218,13 +218,13 @@ ShowTypes ResultsTree::VariantToShowType(const QVariant &data) ShowTypes ResultsTree::SeverityToShowType(const QString & severity) { - if(severity == "possible error") + if (severity == "possible error") return SHOW_ALL; - if(severity == "error") + if (severity == "error") return SHOW_ERRORS; - if(severity == "style") + if (severity == "style") return SHOW_STYLE; - if(severity == "possible style") + if (severity == "possible style") return SHOW_ALL_STYLE; return SHOW_NONE; @@ -233,7 +233,7 @@ ShowTypes ResultsTree::SeverityToShowType(const QString & severity) QStandardItem *ResultsTree::FindFileItem(const QString &name) { QList list = mModel.findItems(name); - if(list.size() > 0) + if (list.size() > 0) { return list[0]; } @@ -247,7 +247,7 @@ void ResultsTree::Clear() void ResultsTree::LoadSettings() { - for(int i = 0; i < mModel.columnCount(); i++) + for (int i = 0; i < mModel.columnCount(); i++) { //mFileTree.columnWidth(i); QString temp = QString(SETTINGS_RESULT_COLUMN_WIDTH).arg(i); @@ -261,7 +261,7 @@ void ResultsTree::LoadSettings() void ResultsTree::SaveSettings() { - for(int i = 0; i < mModel.columnCount(); i++) + for (int i = 0; i < mModel.columnCount(); i++) { QString temp = QString(SETTINGS_RESULT_COLUMN_WIDTH).arg(i); mSettings->setValue(temp, columnWidth(i)); @@ -270,7 +270,7 @@ void ResultsTree::SaveSettings() void ResultsTree::ShowResults(ShowTypes type, bool show) { - if(type != SHOW_NONE && mShowTypes[type] != show) + if (type != SHOW_NONE && mShowTypes[type] != show) { mShowTypes[type] = show; RefreshTree(); @@ -284,11 +284,11 @@ void ResultsTree::RefreshTree() //Get the amount of files in the tree int filecount = mModel.rowCount(); - for(int i = 0; i < filecount; i++) + for (int i = 0; i < filecount; i++) { //Get file i QStandardItem *file = mModel.item(i, 0); - if(!file) + if (!file) { continue; } @@ -299,11 +299,11 @@ void ResultsTree::RefreshTree() //By default it shouldn't be visible bool show = false; - for(int j = 0; j < errorcount; j++) + for (int j = 0; j < errorcount; j++) { //Get the error itself QStandardItem *child = file->child(j, 0); - if(!child) + if (!child) { continue; } @@ -316,7 +316,7 @@ void ResultsTree::RefreshTree() //Check if this error should be hidden bool hide = !mShowTypes[VariantToShowType(data["severity"])]; - if(!hide) + if (!hide) { mVisibleErrors = true; } @@ -325,7 +325,7 @@ void ResultsTree::RefreshTree() setRowHidden(j, file->index(), hide); //If it was shown then the file itself has to be shown as well - if(!hide) + if (!hide) { show = true; } @@ -341,7 +341,7 @@ QStandardItem *ResultsTree::EnsureFileItem(const QString &fullpath, bool hide) QString name = StripPath(fullpath, false); QStandardItem *item = FindFileItem(name); - if(item) + if (item) { return item; } @@ -363,7 +363,7 @@ QStandardItem *ResultsTree::EnsureFileItem(const QString &fullpath, bool hide) void ResultsTree::ShowFileItem(const QString &name) { QStandardItem *item = FindFileItem(name); - if(item) + if (item) { setRowHidden(0, mModel.indexFromItem(item), false); } @@ -372,7 +372,7 @@ void ResultsTree::ShowFileItem(const QString &name) void ResultsTree::contextMenuEvent(QContextMenuEvent * e) { QModelIndex index = indexAt(e->pos()); - if(index.isValid()) + if (index.isValid()) { mContextItem = mModel.itemFromIndex(index); @@ -386,10 +386,10 @@ void ResultsTree::contextMenuEvent(QContextMenuEvent * e) //member variables QSignalMapper *signalMapper = new QSignalMapper(this); - if(mContextItem && mApplications->GetApplicationCount() > 0 && mContextItem->parent()) + if (mContextItem && mApplications->GetApplicationCount() > 0 && mContextItem->parent()) { //Go through all applications and add them to the context menu - for(int i = 0; i < mApplications->GetApplicationCount(); i++) + for (int i = 0; i < mApplications->GetApplicationCount(); i++) { //Create an action for the application QAction *start = new QAction(mApplications->GetApplicationName(i), &menu); @@ -412,9 +412,9 @@ void ResultsTree::contextMenuEvent(QContextMenuEvent * e) } // Add menuitems to copy full path/filename to clipboard - if(mContextItem) + if (mContextItem) { - if(mApplications->GetApplicationCount() > 0) + if (mApplications->GetApplicationCount() > 0) { menu.addSeparator(); } @@ -436,10 +436,10 @@ void ResultsTree::contextMenuEvent(QContextMenuEvent * e) //Start the menu menu.exec(e->globalPos()); - if(mContextItem && mApplications->GetApplicationCount() > 0 && mContextItem->parent()) + if (mContextItem && mApplications->GetApplicationCount() > 0 && mContextItem->parent()) { //Disconnect all signals - for(int i = 0; i < actions.size(); i++) + for (int i = 0; i < actions.size(); i++) { disconnect(actions[i], SIGNAL(triggered()), signalMapper, SLOT(map())); @@ -457,7 +457,7 @@ void ResultsTree::contextMenuEvent(QContextMenuEvent * e) void ResultsTree::StartApplication(QStandardItem *target, int application) { //If there are now application's specified, tell the user about it - if(mApplications->GetApplicationCount() == 0) + if (mApplications->GetApplicationCount() == 0) { QMessageBox msg(QMessageBox::Information, tr("Cppcheck"), @@ -468,10 +468,10 @@ void ResultsTree::StartApplication(QStandardItem *target, int application) return; } - if(target && application >= 0 && application < mApplications->GetApplicationCount() && target->parent()) + if (target && application >= 0 && application < mApplications->GetApplicationCount() && target->parent()) { // Make sure we are working with the first column - if(target->column() != 0) + if (target->column() != 0) target = target->parent()->child(target->row(), 0); QVariantMap data = target->data().toMap(); @@ -480,7 +480,7 @@ void ResultsTree::StartApplication(QStandardItem *target, int application) //Replace (file) with filename QString file = data["file"].toString(); - if(file.indexOf(" ") > -1) + if (file.indexOf(" ") > -1) { file.insert(0, "\""); file.append("\""); @@ -495,7 +495,7 @@ void ResultsTree::StartApplication(QStandardItem *target, int application) program.replace("(severity)", data["severity"].toString(), Qt::CaseInsensitive); bool success = QProcess::startDetached(program); - if(!success) + if (!success) { QString app = mApplications->GetApplicationName(application); QString text = tr("Could not start %1\n\nPlease check the application path and parameters are correct.").arg(app); @@ -522,10 +522,10 @@ void ResultsTree::CopyFullPath() void ResultsTree::CopyMessage() { - if(mContextItem) + if (mContextItem) { // Make sure we are working with the first column - if(mContextItem->column() != 0) + if (mContextItem->column() != 0) mContextItem = mContextItem->parent()->child(mContextItem->row(), 0); QVariantMap data = mContextItem->data().toMap(); @@ -549,10 +549,10 @@ void ResultsTree::QuickStartApplication(const QModelIndex &index) void ResultsTree::CopyPath(QStandardItem *target, bool fullPath) { - if(target) + if (target) { // Make sure we are working with the first column - if(target->column() != 0) + if (target->column() != 0) target = target->parent()->child(target->row(), 0); QVariantMap data = target->data().toMap(); @@ -561,7 +561,7 @@ void ResultsTree::CopyPath(QStandardItem *target, bool fullPath) //Replace (file) with filename QString file = data["file"].toString(); pathStr = file; - if(!fullPath) + if (!fullPath) { QFileInfo fi(pathStr); pathStr = fi.fileName(); @@ -574,11 +574,11 @@ void ResultsTree::CopyPath(QStandardItem *target, bool fullPath) QString ResultsTree::SeverityToIcon(const QString &severity) { - if(severity == "possible error") + if (severity == "possible error") return ":images/dialog-warning.png"; - if(severity == "error") + if (severity == "error") return ":images/dialog-error.png"; - if(severity == "style" || severity == "possible style") + if (severity == "style" || severity == "possible style") return ":images/dialog-information.png"; return ""; @@ -588,10 +588,10 @@ void ResultsTree::SaveResults(Report *report) { report->WriteHeader(); - for(int i = 0; i < mModel.rowCount(); i++) + for (int i = 0; i < mModel.rowCount(); i++) { QStandardItem *item = mModel.item(i, 0); - if(!isRowHidden(i, item->index())) + if (!isRowHidden(i, item->index())) SaveErrors(report, item); } @@ -600,23 +600,23 @@ void ResultsTree::SaveResults(Report *report) void ResultsTree::SaveErrors(Report *report, QStandardItem *item) { - if(!item) + if (!item) { return; } //qDebug() << item->text() << "has" << item->rowCount() << "errors"; - for(int i = 0; i < item->rowCount(); i++) + for (int i = 0; i < item->rowCount(); i++) { QStandardItem *error = item->child(i, 0); - if(!error) + if (!error) { continue; } - if(isRowHidden(i, item->index()) && !mSaveAllErrors) + if (isRowHidden(i, item->index()) && !mSaveAllErrors) { continue; } @@ -638,7 +638,7 @@ void ResultsTree::SaveErrors(Report *report, QStandardItem *item) files << file; lines << line; - for(int j = 0; j < error->rowCount(); j++) + for (int j = 0; j < error->rowCount(); j++) { QStandardItem *child_error = error->child(j, 0); //Get error's user data @@ -659,7 +659,7 @@ void ResultsTree::SaveErrors(Report *report, QStandardItem *item) QString ResultsTree::ShowTypeToString(ShowTypes type) { - switch(type) + switch (type) { case SHOW_ALL: return tr("possible error"); @@ -689,7 +689,7 @@ void ResultsTree::UpdateSettings(bool showFullPath, bool saveFullPath, bool saveAllErrors) { - if(mShowFullPath != showFullPath) + if (mShowFullPath != showFullPath) { mShowFullPath = showFullPath; RefreshFilePaths(); @@ -706,7 +706,7 @@ void ResultsTree::SetCheckDirectory(const QString &dir) QString ResultsTree::StripPath(const QString &path, bool saving) { - if((!saving && mShowFullPath) || (saving && mSaveFullPath)) + if ((!saving && mShowFullPath) || (saving && mSaveFullPath)) { return QString(path); } @@ -717,7 +717,7 @@ QString ResultsTree::StripPath(const QString &path, bool saving) void ResultsTree::RefreshFilePaths(QStandardItem *item) { - if(!item) + if (!item) { return; } @@ -726,12 +726,12 @@ void ResultsTree::RefreshFilePaths(QStandardItem *item) bool updated = false; //Loop through all errors within this file - for(int i = 0; i < item->rowCount(); i++) + for (int i = 0; i < item->rowCount(); i++) { //Get error i QStandardItem *error = item->child(i, 0); - if(!error) + if (!error) { continue; } @@ -748,14 +748,14 @@ void ResultsTree::RefreshFilePaths(QStandardItem *item) error->setText(StripPath(file, false)); //If this error has backtraces make sure the files list has enough filenames - if(error->hasChildren()) + if (error->hasChildren()) { //Loop through all files within the error - for(int j = 0; j < error->rowCount(); j++) + for (int j = 0; j < error->rowCount(); j++) { //Get file QStandardItem *child = error->child(j, 0); - if(!child) + if (!child) { continue; } @@ -772,7 +772,7 @@ void ResultsTree::RefreshFilePaths(QStandardItem *item) } //if the main file hasn't been updated yet, update it now - if(!updated) + if (!updated) { updated = true; item->setText(error->text()); @@ -786,7 +786,7 @@ void ResultsTree::RefreshFilePaths() qDebug("Refreshing file paths"); //Go through all file items (these are parent items that contain the errors) - for(int i = 0; i < mModel.rowCount(); i++) + for (int i = 0; i < mModel.rowCount(); i++) { RefreshFilePaths(mModel.item(i, 0)); } diff --git a/gui/resultsview.cpp b/gui/resultsview.cpp index eed9c379e..250283dc8 100644 --- a/gui/resultsview.cpp +++ b/gui/resultsview.cpp @@ -27,9 +27,9 @@ #include "csvreport.h" ResultsView::ResultsView(QWidget * parent) : - QWidget(parent), - mErrorsFound(false), - mShowNoErrorsMessage(true) + QWidget(parent), + mErrorsFound(false), + mShowNoErrorsMessage(true) { mUI.setupUi(this); } @@ -67,14 +67,13 @@ void ResultsView::Progress(int value, int max) { mUI.mProgress->setMaximum(max); mUI.mProgress->setValue(value); - if(value >= max) + if (value >= max) { mUI.mProgress->setVisible(false); //Should we inform user of non visible/not found errors? - if(mShowNoErrorsMessage) - { - //Tell user that we found no errors - if(!mErrorsFound) + if (mShowNoErrorsMessage) + { //Tell user that we found no errors + if (!mErrorsFound) { QMessageBox msg(QMessageBox::Information, tr("Cppcheck"), @@ -84,7 +83,7 @@ void ResultsView::Progress(int value, int max) msg.exec(); } //If we have errors but they aren't visible, tell user about it - else if(!mUI.mTree->HasVisibleResults()) + else if (!mUI.mTree->HasVisibleResults()) { QString text = tr("Errors were found, but they are configured to be hidden.\n"\ "To toggle what kind of errors are shown, open view menu."); @@ -134,7 +133,7 @@ void ResultsView::ExpandAllResults() void ResultsView::Save(const QString &filename, Report::Type type) { - if(!mErrorsFound) + if (!mErrorsFound) { QMessageBox msgBox; msgBox.setText(tr("No errors found, nothing to save.")); @@ -144,7 +143,7 @@ void ResultsView::Save(const QString &filename, Report::Type type) Report *report = NULL; - switch(type) + switch (type) { case Report::CSV: report = new CsvReport(filename, this); @@ -157,9 +156,9 @@ void ResultsView::Save(const QString &filename, Report::Type type) break; } - if(report) + if (report) { - if(report->Create()) + if (report->Create()) mUI.mTree->SaveResults(report); else { diff --git a/gui/settingsdialog.cpp b/gui/settingsdialog.cpp index c43215a70..f997372df 100644 --- a/gui/settingsdialog.cpp +++ b/gui/settingsdialog.cpp @@ -29,10 +29,10 @@ SettingsDialog::SettingsDialog(QSettings *programSettings, ApplicationList *list, QWidget *parent) : - QDialog(parent), - mSettings(programSettings), - mApplications(list), - mTempApplications(new ApplicationList(this)) + QDialog(parent), + mSettings(programSettings), + mApplications(list), + mTempApplications(new ApplicationList(this)) { mUI.setupUi(this); mTempApplications->Copy(list); @@ -77,7 +77,7 @@ SettingsDialog::~SettingsDialog() Qt::CheckState SettingsDialog::BoolToCheckState(bool yes) { - if(yes) + if (yes) { return Qt::Checked; } @@ -86,7 +86,7 @@ Qt::CheckState SettingsDialog::BoolToCheckState(bool yes) bool SettingsDialog::CheckStateToBool(Qt::CheckState state) { - if(state == Qt::Checked) + if (state == Qt::Checked) { return true; } @@ -109,7 +109,7 @@ void SettingsDialog::SaveSettings() void SettingsDialog::SaveCheckboxValues() { int jobs = mUI.mJobs->text().toInt(); - if(jobs <= 0) + if (jobs <= 0) { jobs = 1; } @@ -131,7 +131,7 @@ void SettingsDialog::AddApplication() { ApplicationDialog dialog("", "", tr("Add a new application"), this); - if(dialog.exec() == QDialog::Accepted) + if (dialog.exec() == QDialog::Accepted) { mTempApplications->AddApplicationType(dialog.GetName(), dialog.GetPath()); mUI.mListWidget->addItem(dialog.GetName()); @@ -164,7 +164,7 @@ void SettingsDialog::ModifyApplication() mTempApplications->GetApplicationPath(row), tr("Modify an application")); - if(dialog.exec() == QDialog::Accepted) + if (dialog.exec() == QDialog::Accepted) { mTempApplications->SetApplicationType(row, dialog.GetName(), dialog.GetPath()); item->setText(dialog.GetName()); @@ -175,7 +175,7 @@ void SettingsDialog::ModifyApplication() void SettingsDialog::DefaultApplication() { QList selected = mUI.mListWidget->selectedItems(); - if(selected.size() > 0) + if (selected.size() > 0) { int index = mUI.mListWidget->row(selected[0]); mTempApplications->MoveFirst(index); @@ -186,13 +186,13 @@ void SettingsDialog::DefaultApplication() void SettingsDialog::PopulateListWidget() { - for(int i = 0; i < mTempApplications->GetApplicationCount(); i++) + for (int i = 0; i < mTempApplications->GetApplicationCount(); i++) { mUI.mListWidget->addItem(mTempApplications->GetApplicationName(i)); } // If list contains items select first item - if(mTempApplications->GetApplicationCount()) + if (mTempApplications->GetApplicationCount()) { mUI.mListWidget->setCurrentRow(0); } diff --git a/gui/threadhandler.cpp b/gui/threadhandler.cpp index c2fc79ae3..8f6ea916c 100644 --- a/gui/threadhandler.cpp +++ b/gui/threadhandler.cpp @@ -21,8 +21,8 @@ #include ThreadHandler::ThreadHandler(QObject *parent) : - QObject(parent), - mRunningThreadCount(0) + QObject(parent), + mRunningThreadCount(0) { SetThreadCount(1); } @@ -46,12 +46,12 @@ void ThreadHandler::SetFiles(const QStringList &files) void ThreadHandler::Check(Settings settings, bool recheck) { - if(recheck && mRunningThreadCount == 0) + if (recheck && mRunningThreadCount == 0) { mResults.SetFiles(mLastFiles); } - if(mResults.GetFileCount() == 0 || mRunningThreadCount > 0 || settings._jobs <= 0) + if (mResults.GetFileCount() == 0 || mRunningThreadCount > 0 || settings._jobs <= 0) { qDebug() << "Can't start checking if there's no files to check or if check is in progress."; emit Done(); @@ -62,12 +62,12 @@ void ThreadHandler::Check(Settings settings, bool recheck) mRunningThreadCount = mThreads.size(); - if(mResults.GetFileCount() < mRunningThreadCount) + if (mResults.GetFileCount() < mRunningThreadCount) { mRunningThreadCount = mResults.GetFileCount(); } - for(int i = 0; i < mRunningThreadCount; i++) + for (int i = 0; i < mRunningThreadCount; i++) { mThreads[i]->Check(settings); } @@ -80,9 +80,9 @@ bool ThreadHandler::IsChecking() const void ThreadHandler::SetThreadCount(const int count) { - if(mRunningThreadCount > 0 || - count == mThreads.size() || - count <= 0) + if (mRunningThreadCount > 0 || + count == mThreads.size() || + count <= 0) { return; } @@ -90,7 +90,7 @@ void ThreadHandler::SetThreadCount(const int count) //Remove unused old threads RemoveThreads(); //Create new threads - for(int i = mThreads.size(); i < count; i++) + for (int i = mThreads.size(); i < count; i++) { mThreads << new CheckThread(mResults); connect(mThreads.last(), SIGNAL(Done()), @@ -104,7 +104,7 @@ void ThreadHandler::SetThreadCount(const int count) void ThreadHandler::RemoveThreads() { - for(int i = 0; i < mThreads.size(); i++) + for (int i = 0; i < mThreads.size(); i++) { mThreads[i]->terminate(); disconnect(mThreads.last(), SIGNAL(Done()), @@ -121,7 +121,7 @@ void ThreadHandler::RemoveThreads() void ThreadHandler::ThreadDone() { mRunningThreadCount--; - if(mRunningThreadCount == 0) + if (mRunningThreadCount == 0) { emit Done(); } @@ -129,7 +129,7 @@ void ThreadHandler::ThreadDone() void ThreadHandler::Stop() { - for(int i = 0; i < mThreads.size(); i++) + for (int i = 0; i < mThreads.size(); i++) { mThreads[i]->stop(); } @@ -168,7 +168,7 @@ void ThreadHandler::SaveSettings(QSettings &settings) bool ThreadHandler::HasPreviousFiles() const { - if(mLastFiles.size() > 0) + if (mLastFiles.size() > 0) return true; return false; diff --git a/gui/threadresult.cpp b/gui/threadresult.cpp index 261ab0891..11b211297 100644 --- a/gui/threadresult.cpp +++ b/gui/threadresult.cpp @@ -50,9 +50,9 @@ void ThreadResult::reportErr(const ErrorLogger::ErrorMessage &msg) QVariantList lines; QStringList files; - for(std::list::const_iterator tok = msg._callStack.begin(); - tok != msg._callStack.end(); - ++tok) + for (std::list::const_iterator tok = msg._callStack.begin(); + tok != msg._callStack.end(); + ++tok) { files << QString((*tok).file.c_str()); lines << (*tok).line; @@ -72,7 +72,7 @@ void ThreadResult::reportErr(const ErrorLogger::ErrorMessage &msg) QString ThreadResult::GetNextFile() { QMutexLocker locker(&mutex); - if(mFiles.size() == 0) + if (mFiles.size() == 0) { return ""; } diff --git a/gui/translationhandler.cpp b/gui/translationhandler.cpp index 5228b6377..930ed2ced 100644 --- a/gui/translationhandler.cpp +++ b/gui/translationhandler.cpp @@ -24,30 +24,30 @@ #include TranslationHandler::TranslationHandler(QObject *parent) : - QObject(parent), - mCurrentLanguage(-1), - mTranslator(new QTranslator(this)) + QObject(parent), + mCurrentLanguage(-1), + mTranslator(new QTranslator(this)) { //Add our default languages mNames << QT_TRANSLATE_NOOP("MainWindow", "English") - << QT_TRANSLATE_NOOP("MainWindow", "Dutch") - << QT_TRANSLATE_NOOP("MainWindow", "Finnish") - << QT_TRANSLATE_NOOP("MainWindow", "Swedish") - << QT_TRANSLATE_NOOP("MainWindow", "German") - << QT_TRANSLATE_NOOP("MainWindow", "Russian") - << QT_TRANSLATE_NOOP("MainWindow", "Polish"); + << QT_TRANSLATE_NOOP("MainWindow", "Dutch") + << QT_TRANSLATE_NOOP("MainWindow", "Finnish") + << QT_TRANSLATE_NOOP("MainWindow", "Swedish") + << QT_TRANSLATE_NOOP("MainWindow", "German") + << QT_TRANSLATE_NOOP("MainWindow", "Russian") + << QT_TRANSLATE_NOOP("MainWindow", "Polish"); mFiles << "cppcheck_en" - << "cppcheck_nl" - << "cppcheck_fi" - << "cppcheck_se" - << "cppcheck_de" - << "cppcheck_ru" - << "cppcheck_pl"; + << "cppcheck_nl" + << "cppcheck_fi" + << "cppcheck_se" + << "cppcheck_de" + << "cppcheck_ru" + << "cppcheck_pl"; //Load english as a fallback language QTranslator *english = new QTranslator(); - if(english->load("cppcheck_en")) + if (english->load("cppcheck_en")) { qApp->installTranslator(english); } @@ -75,10 +75,10 @@ const QStringList TranslationHandler::GetFiles() bool TranslationHandler::SetLanguage(const int index, QString &error) { //If english is the language - if(index == 0) + if (index == 0) { //Just remove all extra translators - if(mTranslator) + if (mTranslator) { qApp->removeTranslator(mTranslator); } @@ -88,17 +88,17 @@ bool TranslationHandler::SetLanguage(const int index, QString &error) } //Make sure the translator is otherwise valid - if(index >= mNames.size()) + if (index >= mNames.size()) { error = QObject::tr("Incorrect language specified!"); return false; } //Load the new language - if(!mTranslator->load(mFiles[index])) + if (!mTranslator->load(mFiles[index])) { //If it failed, lets check if the default file exists - if(!QFile::exists(mFiles[index] + ".qm")) + if (!QFile::exists(mFiles[index] + ".qm")) { error = QObject::tr("Language file %1 not found!"); error = error.arg(mFiles[index] + ".qm"); @@ -144,7 +144,7 @@ int TranslationHandler::SuggestLanguage() const int index = mFiles.indexOf(file); //If nothing found, return english - if(index < 0) + if (index < 0) { return 0; } diff --git a/gui/txtreport.cpp b/gui/txtreport.cpp index d445e1ba7..852a1b8f7 100644 --- a/gui/txtreport.cpp +++ b/gui/txtreport.cpp @@ -21,7 +21,7 @@ #include "txtreport.h" TxtReport::TxtReport(const QString &filename, QObject * parent) : - Report(filename, parent) + Report(filename, parent) { } @@ -33,7 +33,7 @@ TxtReport::~TxtReport() bool TxtReport::Create() { bool success = false; - if(Report::Create()) + if (Report::Create()) { mTxtWriter.setDevice(Report::GetFile()); success = true; @@ -63,15 +63,15 @@ void TxtReport::WriteError(const QStringList &files, const QStringList &lines, QString line; - for(int i = 0; i < lines.size(); i++) + for (int i = 0; i < lines.size(); i++) { line += QString("[%1:%2]").arg(files[i]).arg(lines[i]); - if(i < lines.size() - 1 && lines.size() > 0) + if (i < lines.size() - 1 && lines.size() > 0) { line += " -> "; } - if(i == lines.size() - 1) + if (i == lines.size() - 1) { line += ": "; } diff --git a/gui/xmlreport.cpp b/gui/xmlreport.cpp index 022d5b004..22e9b6ca3 100644 --- a/gui/xmlreport.cpp +++ b/gui/xmlreport.cpp @@ -21,7 +21,7 @@ #include "xmlreport.h" XmlReport::XmlReport(const QString &filename, QObject * parent) : - Report(filename, parent) + Report(filename, parent) { } @@ -33,7 +33,7 @@ XmlReport::~XmlReport() bool XmlReport::Create() { bool success = false; - if(Report::Create()) + if (Report::Create()) { mXmlWriter.setDevice(Report::GetFile()); success = true; diff --git a/lib/check.h b/lib/check.h index 158f448d0..ec6a45d31 100644 --- a/lib/check.h +++ b/lib/check.h @@ -39,7 +39,7 @@ class Check public: /** This constructor is used when registering the CheckClass */ Check() - : _tokenizer(0), _settings(0), _errorLogger(0) + : _tokenizer(0), _settings(0), _errorLogger(0) { instances().push_back(this); instances().sort(); @@ -47,7 +47,7 @@ public: /** This constructor is used when running checks. */ Check(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) - : _tokenizer(tokenizer), _settings(settings), _errorLogger(errorLogger) + : _tokenizer(tokenizer), _settings(settings), _errorLogger(errorLogger) { } virtual ~Check() @@ -99,7 +99,7 @@ protected: void reportError(const Token *tok, const Severity::e severity, const std::string &id, const std::string &msg) { std::list callstack; - if(tok) + if (tok) callstack.push_back(tok); reportError(callstack, severity, id, msg); } @@ -108,18 +108,18 @@ protected: void reportError(const std::list &callstack, const Severity::e severity, const std::string &id, std::string msg) { // If the verbose flag hasn't been given, don't show verbose information - if(!_settings || !_settings->_verbose) + if (!_settings || !_settings->_verbose) { std::string::size_type pos = msg.find("\n"); - if(pos != std::string::npos) + if (pos != std::string::npos) msg.erase(pos); } std::list locationList; - for(std::list::const_iterator it = callstack.begin(); it != callstack.end(); ++it) + for (std::list::const_iterator it = callstack.begin(); it != callstack.end(); ++it) { // --errorlist can provide null values here - if(!(*it)) + if (!(*it)) continue; ErrorLogger::ErrorMessage::FileLocation loc; @@ -129,7 +129,7 @@ protected: } const ErrorLogger::ErrorMessage errmsg(locationList, Severity::stringify(severity), msg, id); - if(_errorLogger) + if (_errorLogger) _errorLogger->reportErr(errmsg); else reportError(errmsg); diff --git a/lib/checkautovariables.cpp b/lib/checkautovariables.cpp index 73c6e2087..fc27070a5 100644 --- a/lib/checkautovariables.cpp +++ b/lib/checkautovariables.cpp @@ -41,7 +41,7 @@ static CheckAutoVariables instance; bool CheckAutoVariables::errorAv(const Token* left, const Token* right) { - if(fp_list.find(left->str()) == fp_list.end()) + if (fp_list.find(left->str()) == fp_list.end()) { return false; } @@ -51,7 +51,7 @@ bool CheckAutoVariables::errorAv(const Token* left, const Token* right) bool CheckAutoVariables::isAutoVar(unsigned int varId) { - if(varId == 0) + if (varId == 0) { return false; } @@ -61,7 +61,7 @@ bool CheckAutoVariables::isAutoVar(unsigned int varId) bool CheckAutoVariables::isAutoVarArray(unsigned int varId) { - if(varId == 0) + if (varId == 0) { return false; } @@ -73,7 +73,7 @@ void print(const Token *tok, int num) { const Token *t = tok; std::cout << tok->linenr() << " PRINT "; - for(int i = 0; i < num; i++) + for (int i = 0; i < num; i++) { std::cout << " [" << t->str() << "] "; t = t->next(); @@ -86,7 +86,7 @@ bool isTypeName(const Token *tok) bool ret = false; const std::string _str(tok->str()); static const char * const type[] = {"case", "return", "delete", 0}; - for(int i = 0; type[i]; i++) + for (int i = 0; type[i]; i++) { ret |= (_str == type[i]); } @@ -97,15 +97,15 @@ bool isExternOrStatic(const Token *tok) { bool res = false; - if(Token::Match(tok->tokAt(-1), "extern|static")) + if (Token::Match(tok->tokAt(-1), "extern|static")) { res = true; } - else if(Token::Match(tok->tokAt(-2), "extern|static")) + else if (Token::Match(tok->tokAt(-2), "extern|static")) { res = true; } - else if(Token::Match(tok->tokAt(-3), "extern|static")) + else if (Token::Match(tok->tokAt(-3), "extern|static")) { res = true; } @@ -117,7 +117,7 @@ bool isExternOrStatic(const Token *tok) void CheckAutoVariables::addVD(unsigned int varId) { - if(varId > 0) + if (varId > 0) { vd_list.insert(varId); } @@ -125,7 +125,7 @@ void CheckAutoVariables::addVD(unsigned int varId) void CheckAutoVariables::addVDA(unsigned int varId) { - if(varId > 0) + if (varId > 0) { vda_list.insert(varId); } @@ -137,82 +137,82 @@ void CheckAutoVariables::autoVariables() bool begin_function_decl = false; int bindent = 0; - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { - if(Token::Match(tok, "%type% *|::| %var% (")) + if (Token::Match(tok, "%type% *|::| %var% (")) { begin_function = true; fp_list.clear(); vd_list.clear(); vda_list.clear(); } - else if(begin_function && begin_function_decl && Token::Match(tok, "%type% * * %var%")) + else if (begin_function && begin_function_decl && Token::Match(tok, "%type% * * %var%")) { fp_list.insert(tok->tokAt(3)->str()); } - else if(begin_function && begin_function_decl && Token::Match(tok, "%type% * %var% [")) + else if (begin_function && begin_function_decl && Token::Match(tok, "%type% * %var% [")) { fp_list.insert(tok->tokAt(2)->str()); } - else if(begin_function && tok->str() == "(") + else if (begin_function && tok->str() == "(") { begin_function_decl = true; } - else if(begin_function && tok->str() == ")") + else if (begin_function && tok->str() == ")") { begin_function_decl = false; } - else if(begin_function && tok->str() == "{") + else if (begin_function && tok->str() == "{") { bindent++; } - else if(begin_function && tok->str() == "}") + else if (begin_function && tok->str() == "}") { bindent--; } - else if(bindent <= 0) + else if (bindent <= 0) { continue; } // Inside a function body - if(Token::Match(tok, "%type% :: %any%") && !isExternOrStatic(tok)) + if (Token::Match(tok, "%type% :: %any%") && !isExternOrStatic(tok)) { addVD(tok->tokAt(2)->varId()); } - else if(Token::Match(tok, "%type% %var% [")) + else if (Token::Match(tok, "%type% %var% [")) { addVDA(tok->next()->varId()); } - else if(Token::Match(tok, "%var% %var% ;") && !isExternOrStatic(tok) && isTypeName(tok)) + else if (Token::Match(tok, "%var% %var% ;") && !isExternOrStatic(tok) && isTypeName(tok)) { addVD(tok->next()->varId()); } - else if(Token::Match(tok, "const %var% %var% ;") && !isExternOrStatic(tok) && isTypeName(tok->next())) + else if (Token::Match(tok, "const %var% %var% ;") && !isExternOrStatic(tok) && isTypeName(tok->next())) { addVD(tok->tokAt(2)->varId()); } //Critical assignment - else if(Token::Match(tok, "[;{}] %var% = & %var%") && errorAv(tok->tokAt(1), tok->tokAt(4))) + else if (Token::Match(tok, "[;{}] %var% = & %var%") && errorAv(tok->tokAt(1), tok->tokAt(4))) { errorAutoVariableAssignment(tok); } - else if(Token::Match(tok, "[;{}] * %var% = & %var%") && errorAv(tok->tokAt(2), tok->tokAt(5))) + else if (Token::Match(tok, "[;{}] * %var% = & %var%") && errorAv(tok->tokAt(2), tok->tokAt(5))) { errorAutoVariableAssignment(tok); } - else if(Token::Match(tok, "[;{}] %var% [ %any% ] = & %var%") && errorAv(tok->tokAt(1), tok->tokAt(7))) + else if (Token::Match(tok, "[;{}] %var% [ %any% ] = & %var%") && errorAv(tok->tokAt(1), tok->tokAt(7))) { errorAutoVariableAssignment(tok); } // Critical return - else if(Token::Match(tok, "return & %var% ;") && isAutoVar(tok->tokAt(2)->varId())) + else if (Token::Match(tok, "return & %var% ;") && isAutoVar(tok->tokAt(2)->varId())) { reportError(tok, Severity::error, "autoVariables", "Return of the address of an auto-variable"); } // Invalid pointer deallocation - else if(Token::Match(tok, "free ( %var% ) ;") && isAutoVarArray(tok->tokAt(2)->varId())) + else if (Token::Match(tok, "free ( %var% ) ;") && isAutoVarArray(tok->tokAt(2)->varId())) { reportError(tok, Severity::error, "autoVariables", "Invalid deallocation"); } @@ -231,20 +231,20 @@ void CheckAutoVariables::returnPointerToLocalArray() bool infunc = false; int indentlevel = 0; std::set arrayVar; - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { // Is there a function declaration for a function that returns a pointer? - if(!infunc && (Token::Match(tok, "%type% * %var% (") || Token::Match(tok, "%type% * %var% :: %var% ("))) + if (!infunc && (Token::Match(tok, "%type% * %var% (") || Token::Match(tok, "%type% * %var% :: %var% ("))) { - for(const Token *tok2 = tok; tok2; tok2 = tok2->next()) + for (const Token *tok2 = tok; tok2; tok2 = tok2->next()) { - if(tok2->str() == ")") + if (tok2->str() == ")") { tok = tok2; break; } } - if(Token::simpleMatch(tok, ") {")) + if (Token::simpleMatch(tok, ") {")) { infunc = true; indentlevel = 0; @@ -253,16 +253,16 @@ void CheckAutoVariables::returnPointerToLocalArray() } // Parsing a function that returns a pointer.. - if(infunc) + if (infunc) { - if(tok->str() == "{") + if (tok->str() == "{") { ++indentlevel; } - else if(tok->str() == "}") + else if (tok->str() == "}") { --indentlevel; - if(indentlevel <= 0) + if (indentlevel <= 0) { infunc = false; } @@ -270,20 +270,20 @@ void CheckAutoVariables::returnPointerToLocalArray() } // Declaring a local array.. - if(Token::Match(tok, "[;{}] %type% %var% [")) + if (Token::Match(tok, "[;{}] %type% %var% [")) { const unsigned int varid = tok->tokAt(2)->varId(); - if(varid > 0) + if (varid > 0) { arrayVar.insert(varid); } } // Return pointer to local array variable.. - if(Token::Match(tok, "return %var% ;")) + if (Token::Match(tok, "return %var% ;")) { const unsigned int varid = tok->next()->varId(); - if(varid > 0 && arrayVar.find(varid) != arrayVar.end()) + if (varid > 0 && arrayVar.find(varid) != arrayVar.end()) { errorReturnPointerToLocalArray(tok); } @@ -311,7 +311,7 @@ void CheckAutoVariables::errorAutoVariableAssignment(const Token *tok) // return temporary? bool CheckAutoVariables::returnTemporary(const Token *tok) const { - if(!Token::Match(tok, "return %var% (")) + if (!Token::Match(tok, "return %var% (")) return false; return bool(0 != Token::findmatch(_tokenizer->tokens(), ("std :: string " + tok->next()->str() + " (").c_str())); } @@ -320,21 +320,21 @@ bool CheckAutoVariables::returnTemporary(const Token *tok) const void CheckAutoVariables::returnReference() { // locate function that returns a reference.. - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { // Skip executable scopes.. - if(Token::Match(tok, ") const| {")) + if (Token::Match(tok, ") const| {")) { tok = tok->next(); - if(tok->str() == "const") + if (tok->str() == "const") tok = tok->next(); tok = tok->link(); continue; } // have we reached a function that returns a reference? - if(Token::Match(tok, "%type% & %var% (") || - Token::Match(tok, "> & %var% (")) + if (Token::Match(tok, "%type% & %var% (") || + Token::Match(tok, "> & %var% (")) { // go to the '(' const Token *tok2 = tok->tokAt(3); @@ -343,49 +343,49 @@ void CheckAutoVariables::returnReference() tok2 = tok2->link(); // is this a function implementation? - if(Token::Match(tok2, ") const| {")) + if (Token::Match(tok2, ") const| {")) { unsigned int indentlevel = 0; std::set localvar; // local variables in function - while(0 != (tok2 = tok2->next())) + while (0 != (tok2 = tok2->next())) { // indentlevel.. - if(tok2->str() == "{") + if (tok2->str() == "{") ++indentlevel; - else if(tok2->str() == "}") + else if (tok2->str() == "}") { - if(indentlevel <= 1) + if (indentlevel <= 1) break; --indentlevel; } // declare local variable.. - if(Token::Match(tok2, "[{};] %type%") && tok2->next()->str() != "return") + if (Token::Match(tok2, "[{};] %type%") && tok2->next()->str() != "return") { // goto next token.. tok2 = tok2->next(); // skip "const" - if(Token::Match(tok2, "const %type%")) + if (Token::Match(tok2, "const %type%")) tok2 = tok2->next(); // skip "std::" if it is seen - if(Token::simpleMatch(tok2, "std ::")) + if (Token::simpleMatch(tok2, "std ::")) tok2 = tok2->tokAt(2); // is it a variable declaration? - if(Token::Match(tok2, "%type% %var% ;")) + if (Token::Match(tok2, "%type% %var% ;")) localvar.insert(tok2->next()->varId()); - else if(Token::Match(tok2, "%type% < %any% > %var% ;")) + else if (Token::Match(tok2, "%type% < %any% > %var% ;")) localvar.insert(tok2->tokAt(4)->varId()); } // return.. - else if(Token::Match(tok2, "return %var% ;")) + else if (Token::Match(tok2, "return %var% ;")) { // is the returned variable a local variable? - if((tok2->next()->varId() > 0) && - (localvar.find(tok2->next()->varId()) != localvar.end())) + if ((tok2->next()->varId() > 0) && + (localvar.find(tok2->next()->varId()) != localvar.end())) { // report error.. errorReturnReference(tok2); @@ -393,7 +393,7 @@ void CheckAutoVariables::returnReference() } // return reference to temporary.. - else if(returnTemporary(tok2)) + else if (returnTemporary(tok2)) { // report error.. errorReturnTempReference(tok2); @@ -419,20 +419,20 @@ void CheckAutoVariables::errorReturnTempReference(const Token *tok) void CheckAutoVariables::returncstr() { // locate function that returns a const char *.. - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { // Skip executable scopes.. - if(Token::Match(tok, ") const| {")) + if (Token::Match(tok, ") const| {")) { tok = tok->next(); - if(tok->str() == "const") + if (tok->str() == "const") tok = tok->next(); tok = tok->link(); continue; } // have we reached a function that returns a reference? - if(Token::Match(tok, "const char * %var% (")) + if (Token::Match(tok, "const char * %var% (")) { // go to the '(' const Token *tok2 = tok->tokAt(4); @@ -441,47 +441,47 @@ void CheckAutoVariables::returncstr() tok2 = tok2->link(); // is this a function implementation? - if(Token::Match(tok2, ") const| {")) + if (Token::Match(tok2, ") const| {")) { unsigned int indentlevel = 0; std::set localvar; // local variables in function - while(0 != (tok2 = tok2->next())) + while (0 != (tok2 = tok2->next())) { // indentlevel.. - if(tok2->str() == "{") + if (tok2->str() == "{") ++indentlevel; - else if(tok2->str() == "}") + else if (tok2->str() == "}") { - if(indentlevel <= 1) + if (indentlevel <= 1) break; --indentlevel; } // declare local variable.. - if(Token::Match(tok2, "[{};] %type%") && tok2->next()->str() != "return") + if (Token::Match(tok2, "[{};] %type%") && tok2->next()->str() != "return") { // goto next token.. tok2 = tok2->next(); // skip "const" - if(Token::Match(tok2, "const %type%")) + if (Token::Match(tok2, "const %type%")) tok2 = tok2->next(); // skip "std::" if it is seen - if(Token::simpleMatch(tok2, "std ::")) + if (Token::simpleMatch(tok2, "std ::")) tok2 = tok2->tokAt(2); // is it a variable declaration? - if(Token::Match(tok2, "%type% %var% ;")) + if (Token::Match(tok2, "%type% %var% ;")) localvar.insert(tok2->next()->varId()); } // return.. - else if(Token::Match(tok2, "return %var% . c_str ( ) ;")) + else if (Token::Match(tok2, "return %var% . c_str ( ) ;")) { // is the returned variable a local variable? - if((tok2->next()->varId() > 0) && - (localvar.find(tok2->next()->varId()) != localvar.end())) + if ((tok2->next()->varId() > 0) && + (localvar.find(tok2->next()->varId()) != localvar.end())) { // report error.. errorReturnAutocstr(tok2); @@ -489,7 +489,7 @@ void CheckAutoVariables::returncstr() } // return pointer to temporary.. - else if(returnTemporary(tok2)) + else if (returnTemporary(tok2)) { // report error.. errorReturnTempPointer(tok2); diff --git a/lib/checkautovariables.h b/lib/checkautovariables.h index 68e09e296..ef958863e 100644 --- a/lib/checkautovariables.h +++ b/lib/checkautovariables.h @@ -39,7 +39,7 @@ public: /** This constructor is used when running checks. */ CheckAutoVariables(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) - : Check(tokenizer, settings, errorLogger) + : Check(tokenizer, settings, errorLogger) { } void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) diff --git a/lib/checkbufferoverrun.cpp b/lib/checkbufferoverrun.cpp index bd591bd04..72bb93912 100644 --- a/lib/checkbufferoverrun.cpp +++ b/lib/checkbufferoverrun.cpp @@ -48,7 +48,7 @@ CheckBufferOverrun instance; void CheckBufferOverrun::arrayIndexOutOfBounds(const Token *tok, int size, int index) { - if(!tok) + if (!tok) arrayIndexOutOfBounds(size, index); else { @@ -61,10 +61,10 @@ void CheckBufferOverrun::arrayIndexOutOfBounds(const Token *tok, int size, int i void CheckBufferOverrun::arrayIndexOutOfBounds(int size, int index) { Severity::e severity; - if(size <= 1 || _callStack.size() > 1) + if (size <= 1 || _callStack.size() > 1) { severity = Severity::possibleError; - if(_settings->_showAll == false) + if (_settings->_showAll == false) return; } else @@ -72,7 +72,7 @@ void CheckBufferOverrun::arrayIndexOutOfBounds(int size, int index) severity = Severity::error; } - if(_callStack.size() == 1) + if (_callStack.size() == 1) { std::ostringstream oss; oss << "Array '" << (*_callStack.begin())->str() << "[" << size << "]' index " << index << " out of bounds"; @@ -85,10 +85,10 @@ void CheckBufferOverrun::arrayIndexOutOfBounds(int size, int index) void CheckBufferOverrun::bufferOverrun(const Token *tok, const std::string &varnames) { Severity::e severity; - if(_callStack.size() > 0) + if (_callStack.size() > 0) { severity = Severity::possibleError; - if(_settings->_showAll == false) + if (_settings->_showAll == false) return; } else @@ -97,11 +97,11 @@ void CheckBufferOverrun::bufferOverrun(const Token *tok, const std::string &varn } std::string v = varnames; - while(v.find(" ") != std::string::npos) + while (v.find(" ") != std::string::npos) v.erase(v.find(" "), 1); std::string errmsg("Buffer access out-of-bounds"); - if(!v.empty()) + if (!v.empty()) errmsg += ": " + v; reportError(tok, severity, "bufferAccessOutOfBounds", errmsg); @@ -109,7 +109,7 @@ void CheckBufferOverrun::bufferOverrun(const Token *tok, const std::string &varn void CheckBufferOverrun::dangerousStdCin(const Token *tok) { - if(_settings && _settings->_showAll == false) + if (_settings && _settings->_showAll == false) return; reportError(tok, Severity::possibleError, "dangerousStdCin", "Dangerous usage of std::cin, possible buffer overrun"); @@ -117,7 +117,7 @@ void CheckBufferOverrun::dangerousStdCin(const Token *tok) void CheckBufferOverrun::strncatUsage(const Token *tok) { - if(_settings && _settings->_showAll == false) + if (_settings && _settings->_showAll == false) return; reportError(tok, Severity::possibleError, "strncatUsage", "Dangerous usage of strncat. Tip: the 3rd parameter means maximum number of characters to append"); @@ -130,7 +130,7 @@ void CheckBufferOverrun::outOfBounds(const Token *tok, const std::string &what) void CheckBufferOverrun::sizeArgumentAsChar(const Token *tok) { - if(_settings && _settings->_showAll == false) + if (_settings && _settings->_showAll == false) return; reportError(tok, Severity::possibleError, "sizeArgumentAsChar", "The size argument is given as a char constant"); @@ -160,7 +160,7 @@ public: * @param str Token::str() is compared against this. */ TokenStrEquals(const std::string &str) - : value(str) + : value(str) { } @@ -180,79 +180,79 @@ private: void CheckBufferOverrun::checkScope(const Token *tok, const std::vector &varname, const int size, const int total_size, unsigned int varid) { std::string varnames; - for(unsigned int i = 0; i < varname.size(); ++i) + for (unsigned int i = 0; i < varname.size(); ++i) varnames += (i == 0 ? "" : " . ") + varname[i]; const unsigned int varc(varname.empty() ? 0 : (varname.size() - 1) * 2); - if(Token::Match(tok, "return")) + if (Token::Match(tok, "return")) { tok = tok->next(); - if(!tok) + if (!tok) return; } // Array index.. - if(varid > 0) + if (varid > 0) { - if(Token::Match(tok, "%varid% [ %num% ]", varid)) + if (Token::Match(tok, "%varid% [ %num% ]", varid)) { int index = MathLib::toLongNumber(tok->strAt(2)); - if(index < 0 || index >= size) + if (index < 0 || index >= size) { arrayIndexOutOfBounds(tok, size, index); } } } - else if(Token::Match(tok, (varnames + " [ %num% ]").c_str())) + else if (Token::Match(tok, (varnames + " [ %num% ]").c_str())) { int index = MathLib::toLongNumber(tok->strAt(2 + varc)); - if(index < 0 || index >= size) + if (index < 0 || index >= size) { arrayIndexOutOfBounds(tok->tokAt(varc), size, index); } } int indentlevel = 0; - for(; tok; tok = tok->next()) + for (; tok; tok = tok->next()) { - if(tok->str() == "{") + if (tok->str() == "{") { ++indentlevel; } - else if(tok->str() == "}") + else if (tok->str() == "}") { --indentlevel; - if(indentlevel < 0) + if (indentlevel < 0) return; } - if(varid != 0 && Token::Match(tok, "%varid% = new|malloc|realloc", varid)) + if (varid != 0 && Token::Match(tok, "%varid% = new|malloc|realloc", varid)) { // Abort break; } // Array index.. - if(varid > 0) + if (varid > 0) { - if(!tok->isName() && !Token::Match(tok, "[.&]") && Token::Match(tok->next(), "%varid% [ %num% ]", varid)) + if (!tok->isName() && !Token::Match(tok, "[.&]") && Token::Match(tok->next(), "%varid% [ %num% ]", varid)) { int index = MathLib::toLongNumber(tok->strAt(3)); - if(index < 0 || index >= size) + if (index < 0 || index >= size) { - if(index > size || !Token::Match(tok->previous(), "& (")) + if (index > size || !Token::Match(tok->previous(), "& (")) { arrayIndexOutOfBounds(tok->next(), size, index); } } } } - else if(!tok->isName() && !Token::Match(tok, "[.&]") && Token::Match(tok->next(), (varnames + " [ %num% ]").c_str())) + else if (!tok->isName() && !Token::Match(tok, "[.&]") && Token::Match(tok->next(), (varnames + " [ %num% ]").c_str())) { int index = MathLib::toLongNumber(tok->strAt(3 + varc)); - if(index < 0 || index >= size) + if (index < 0 || index >= size) { arrayIndexOutOfBounds(tok->tokAt(1 + varc), size, index); } @@ -262,26 +262,26 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vector 0) + if (varid > 0) { - if(_settings->_checkCodingStyle) + if (_settings->_checkCodingStyle) { // check for strncpy which is not terminated - if(Token::Match(tok, "strncpy ( %varid% , %any% , %any% )", varid)) + if (Token::Match(tok, "strncpy ( %varid% , %any% , %any% )", varid)) { const Token *tokSz = tok->tokAt(6); - if(tokSz->isNumber()) + if (tokSz->isNumber()) { // strncpy takes entire variable length as input size const std::string num = tok->strAt(6); - if(MathLib::toLongNumber(num) == total_size) + if (MathLib::toLongNumber(num) == total_size) { const Token *tok2 = tok->next()->link()->next()->next(); - for(; tok2; tok2 = tok2->next()) + for (; tok2; tok2 = tok2->next()) { - if(Token::Match(tok2, "%varid%", tok->tokAt(2)->varId())) + if (Token::Match(tok2, "%varid%", tok->tokAt(2)->varId())) { - if(!Token::Match(tok2, "%varid% [ %any% ] = 0 ;", tok->tokAt(2)->varId())) + if (!Token::Match(tok2, "%varid% [ %any% ] = 0 ;", tok->tokAt(2)->varId())) { terminateStrncpyError(tok); } @@ -295,27 +295,27 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vectortokAt(6); - if(tokSz->str()[0] == '\'') + if (tokSz->str()[0] == '\'') sizeArgumentAsChar(tok); - else if(tokSz->isNumber()) + else if (tokSz->isNumber()) { const std::string num = tok->strAt(6); - if(MathLib::toLongNumber(num) < 0 || MathLib::toLongNumber(num) > total_size) + if (MathLib::toLongNumber(num) < 0 || MathLib::toLongNumber(num) > total_size) { bufferOverrun(tok, varnames); } } } } - else if(Token::Match(tok, ("memset|memcpy|memmove|memcmp|strncpy|fgets ( " + varnames + " , %num% , %num% )").c_str()) || - Token::Match(tok, ("memcpy|memcmp ( %var% , " + varnames + " , %num% )").c_str())) + else if (Token::Match(tok, ("memset|memcpy|memmove|memcmp|strncpy|fgets ( " + varnames + " , %num% , %num% )").c_str()) || + Token::Match(tok, ("memcpy|memcmp ( %var% , " + varnames + " , %num% )").c_str())) { const std::string num = tok->strAt(varc + 6); - if(MathLib::toLongNumber(num) < 0 || MathLib::toLongNumber(num) > total_size) + if (MathLib::toLongNumber(num) < 0 || MathLib::toLongNumber(num) > total_size) { bufferOverrun(tok, varnames); } @@ -323,7 +323,7 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vectortokAt(2); @@ -332,9 +332,9 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vectortokAt(2)->isNumber()) + if (tok2->tokAt(2)->isNumber()) { min_counter_value = tok2->strAt(2); } @@ -342,9 +342,9 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vectorvarId(); tok2 = tok2->tokAt(4); } - else if(Token::Match(tok2, "%type% %var% = %any% ;")) + else if (Token::Match(tok2, "%type% %var% = %any% ;")) { - if(tok2->tokAt(3)->isNumber()) + if (tok2->tokAt(3)->isNumber()) { min_counter_value = tok2->strAt(3); } @@ -352,9 +352,9 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vectornext()->varId(); tok2 = tok2->tokAt(5); } - else if(Token::Match(tok2, "%type% %type% %var% = %any% ;")) + else if (Token::Match(tok2, "%type% %type% %var% = %any% ;")) { - if(tok->tokAt(4)->isNumber()) + if (tok->tokAt(4)->isNumber()) { min_counter_value = tok2->strAt(4); } @@ -366,30 +366,30 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vectorstrAt(2)); max_counter_value = MathLib::toString(value - 1); strindextoken = tok2; } - else if(Token::Match(tok2, "%varid% <= %num% ;", counter_varid)) + else if (Token::Match(tok2, "%varid% <= %num% ;", counter_varid)) { value = MathLib::toLongNumber(tok2->strAt(2)) + 1; max_counter_value = tok2->strAt(2); strindextoken = tok2; } - else if(Token::Match(tok2, " %num% < %varid% ;", counter_varid)) + else if (Token::Match(tok2, " %num% < %varid% ;", counter_varid)) { max_counter_value = min_counter_value; min_counter_value = MathLib::toString(value + 1); value = MathLib::toLongNumber(max_counter_value); strindextoken = tok2->tokAt(2); } - else if(Token::Match(tok2, "%num% <= %varid% ;", counter_varid)) + else if (Token::Match(tok2, "%num% <= %varid% ;", counter_varid)) { max_counter_value = min_counter_value; min_counter_value = tok2->str(); @@ -404,15 +404,15 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vectorstr(); bool condition_out_of_bounds = true; - if(value <= size) + if (value <= size) condition_out_of_bounds = false; const Token *tok3 = tok2->tokAt(4); assert(tok3 != NULL); - if(Token::Match(tok3, "%varid% += %num% )", counter_varid) || - Token::Match(tok3, "%varid% = %num% + %varid% )", counter_varid)) + if (Token::Match(tok3, "%varid% += %num% )", counter_varid) || + Token::Match(tok3, "%varid% = %num% + %varid% )", counter_varid)) { - if(!MathLib::isInt(tok3->strAt(2))) + if (!MathLib::isInt(tok3->strAt(2))) continue; const int num = MathLib::toLongNumber(tok3->strAt(2)); @@ -426,12 +426,12 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vector(max); - if(max <= size) + if (max <= size) condition_out_of_bounds = false; } - else if(Token::Match(tok3, "%varid% = %varid% + %num% )", counter_varid)) + else if (Token::Match(tok3, "%varid% = %varid% + %num% )", counter_varid)) { - if(!MathLib::isInt(tok3->strAt(4))) + if (!MathLib::isInt(tok3->strAt(4))) continue; const int num = MathLib::toLongNumber(tok3->strAt(4)); @@ -439,13 +439,13 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vector(max); - if(max <= size) + if (max <= size) condition_out_of_bounds = false; } - else if(Token::Match(tok3, "%varid% -= %num% )", counter_varid) || - Token::Match(tok3, "%varid% = %num% - %varid% )", counter_varid)) + else if (Token::Match(tok3, "%varid% -= %num% )", counter_varid) || + Token::Match(tok3, "%varid% = %num% - %varid% )", counter_varid)) { - if(!MathLib::isInt(tok3->strAt(2))) + if (!MathLib::isInt(tok3->strAt(2))) continue; const int num = MathLib::toLongNumber(tok3->strAt(2)); @@ -454,12 +454,12 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vector(max); - if(max <= size) + if (max <= size) condition_out_of_bounds = false; } - else if(Token::Match(tok3, "%varid% = %varid% - %num% )", counter_varid)) + else if (Token::Match(tok3, "%varid% = %varid% - %num% )", counter_varid)) { - if(!MathLib::isInt(tok3->strAt(4))) + if (!MathLib::isInt(tok3->strAt(4))) continue; const int num = MathLib::toLongNumber(tok3->strAt(4)); @@ -467,12 +467,12 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vector(max); - if(max <= size) + if (max <= size) condition_out_of_bounds = false; } - else if(Token::Match(tok3, "--| %varid% --| )", counter_varid)) + else if (Token::Match(tok3, "--| %varid% --| )", counter_varid)) { - if(MathLib::toLongNumber(min_counter_value) < MathLib::toLongNumber(max_counter_value)) + if (MathLib::toLongNumber(min_counter_value) < MathLib::toLongNumber(max_counter_value)) { // Code relies on the fact that integer will overflow: // for (unsigned int i = 3; i < 5; --i) @@ -482,26 +482,26 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vectornext()->link(); - if(!tok2 || !tok2->tokAt(5)) + if (!tok2 || !tok2->tokAt(5)) break; // Check is the counter variable increased elsewhere inside the loop or used // for anything else except reading bool bailOut = false; - for(Token *loopTok = tok2->next(); loopTok && loopTok != tok2->next()->link(); loopTok = loopTok->next()) + for (Token *loopTok = tok2->next(); loopTok && loopTok != tok2->next()->link(); loopTok = loopTok->next()) { - if(loopTok->varId() == counter_varid) + if (loopTok->varId() == counter_varid) { // Counter variable used inside loop - if(Token::Match(loopTok->next(), "+=|-=|++|--|=") || - Token::Match(loopTok->previous(), "++|--")) + if (Token::Match(loopTok->next(), "+=|-=|++|--|=") || + Token::Match(loopTok->previous(), "++|--")) { bailOut = true; break; @@ -509,52 +509,52 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vector 0) + if (varid > 0) pattern << "%varid% [ " << strindex << " ]"; else pattern << varnames << " [ " << strindex << " ]"; int indentlevel2 = 0; - while((tok2 = tok2->next()) != 0) + while ((tok2 = tok2->next()) != 0) { - if(tok2->str() == ";" && indentlevel2 == 0) + if (tok2->str() == ";" && indentlevel2 == 0) break; - if(tok2->str() == "{") + if (tok2->str() == "{") ++indentlevel2; - if(tok2->str() == "}") + if (tok2->str() == "}") { --indentlevel2; - if(indentlevel2 <= 0) + if (indentlevel2 <= 0) break; } - if(Token::Match(tok2, "if|switch")) + if (Token::Match(tok2, "if|switch")) { // Bailout break; } - if(condition_out_of_bounds && Token::Match(tok2, pattern.str().c_str(), varid)) + if (condition_out_of_bounds && Token::Match(tok2, pattern.str().c_str(), varid)) { bufferOverrun(tok2, varid > 0 ? "" : varnames.c_str()); break; } - else if(varid > 0 && counter_varid > 0 && !min_counter_value.empty() && !max_counter_value.empty()) + else if (varid > 0 && counter_varid > 0 && !min_counter_value.empty() && !max_counter_value.empty()) { int min_index = 0; int max_index = 0; - if(Token::Match(tok2, "%varid% [ %var% +|-|*|/ %num% ]", varid) && - tok2->tokAt(2)->varId() == counter_varid) + if (Token::Match(tok2, "%varid% [ %var% +|-|*|/ %num% ]", varid) && + tok2->tokAt(2)->varId() == counter_varid) { const char action = tok2->strAt(3)[0]; const std::string &second(tok2->tokAt(4)->str()); @@ -565,8 +565,8 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vectortokAt(4)->varId() == counter_varid) + else if (Token::Match(tok2, "%varid% [ %num% +|-|*|/ %var% ]", varid) && + tok2->tokAt(4)->varId() == counter_varid) { const char action = tok2->strAt(3)[0]; const std::string &first(tok2->tokAt(2)->str()); @@ -579,7 +579,7 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vector= size || max_index >= size) + if (min_index >= size || max_index >= size) { arrayIndexOutOfBounds(tok2, size, min_index > max_index ? min_index : max_index); } @@ -591,11 +591,11 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vector 0 && Token::Match(tok, "strcpy|strcat ( %varid% , %str% )", varid)) || - (varid == 0 && Token::Match(tok, ("strcpy|strcat ( " + varnames + " , %str% )").c_str()))) + if ((varid > 0 && Token::Match(tok, "strcpy|strcat ( %varid% , %str% )", varid)) || + (varid == 0 && Token::Match(tok, ("strcpy|strcat ( " + varnames + " , %str% )").c_str()))) { long len = Token::getStrLength(tok->tokAt(varc + 4)); - if(len < 0 || len >= total_size) + if (len < 0 || len >= total_size) { bufferOverrun(tok, varid > 0 ? "" : varnames.c_str()); continue; @@ -603,12 +603,12 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vector 0 && - Token::Match(tok, "read|write ( %any% , %varid% , %num% )", varid) && - MathLib::isInt(tok->strAt(6))) + if (varid > 0 && + Token::Match(tok, "read|write ( %any% , %varid% , %num% )", varid) && + MathLib::isInt(tok->strAt(6))) { long len = MathLib::toLongNumber(tok->strAt(6)); - if(len < 0 || len > total_size) + if (len < 0 || len > total_size) { bufferOverrun(tok); continue; @@ -616,12 +616,12 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vector 0 && - Token::Match(tok, "fgets ( %varid% , %num% , %any% )", varid) && - MathLib::isInt(tok->strAt(4))) + if (varid > 0 && + Token::Match(tok, "fgets ( %varid% , %num% , %any% )", varid) && + MathLib::isInt(tok->strAt(4))) { long len = MathLib::toLongNumber(tok->strAt(4)); - if(len < 0 || len > total_size) + if (len < 0 || len > total_size) { bufferOverrun(tok); continue; @@ -629,32 +629,32 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vector 0 && Token::Match(tok, "strncat ( %varid% , %any% , %num% )", varid)) + if (varid > 0 && Token::Match(tok, "strncat ( %varid% , %any% , %num% )", varid)) { int n = MathLib::toLongNumber(tok->strAt(6)); - if(n < 0 || n >= total_size) + if (n < 0 || n >= total_size) strncatUsage(tok); } // Dangerous usage of strncpy + strncat.. - if(varid > 0 && Token::Match(tok, "strncpy|strncat ( %varid% , %any% , %num% ) ; strncat ( %varid% , %any% , %num% )", varid)) + if (varid > 0 && Token::Match(tok, "strncpy|strncat ( %varid% , %any% , %num% ) ; strncat ( %varid% , %any% , %num% )", varid)) { int n = MathLib::toLongNumber(tok->strAt(6)) + MathLib::toLongNumber(tok->strAt(15)); - if(n > total_size) + if (n > total_size) strncatUsage(tok->tokAt(9)); } // Detect few strcat() calls - if(varid > 0 && Token::Match(tok, "strcat ( %varid% , %str% ) ;", varid)) + if (varid > 0 && Token::Match(tok, "strcat ( %varid% , %str% ) ;", varid)) { size_t charactersAppend = 0; const Token *tok2 = tok; - while(tok2 && Token::Match(tok2, "strcat ( %varid% , %str% ) ;", varid)) + while (tok2 && Token::Match(tok2, "strcat ( %varid% , %str% ) ;", varid)) { charactersAppend += Token::getStrLength(tok2->tokAt(4)); - if(charactersAppend >= static_cast(total_size)) + if (charactersAppend >= static_cast(total_size)) { bufferOverrun(tok2); break; @@ -664,21 +664,21 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vector 0 && Token::Match(tok, "sprintf ( %varid% , %str% [,)]", varid)) + if (varid > 0 && Token::Match(tok, "sprintf ( %varid% , %str% [,)]", varid)) { checkSprintfCall(tok, total_size); } // snprintf.. - if(varid > 0 && Token::Match(tok, "snprintf ( %varid% , %num% ,", varid)) + if (varid > 0 && Token::Match(tok, "snprintf ( %varid% , %num% ,", varid)) { int n = MathLib::toLongNumber(tok->strAt(4)); - if(n > total_size) + if (n > total_size) outOfBounds(tok->tokAt(4), "snprintf size"); } // cin.. - if(varid > 0 && Token::Match(tok, "cin >> %varid% ;", varid)) + if (varid > 0 && Token::Match(tok, "cin >> %varid% ;", varid)) { dangerousStdCin(tok); } @@ -686,45 +686,45 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vector_showAll) + if (!_settings->_showAll) continue; unsigned int parlevel = 0, par = 0; const Token * tok1 = tok; - for(const Token *tok2 = tok; tok2; tok2 = tok2->next()) + for (const Token *tok2 = tok; tok2; tok2 = tok2->next()) { - if(tok2->str() == "(") + if (tok2->str() == "(") { ++parlevel; } - else if(tok2->str() == ")") + else if (tok2->str() == ")") { --parlevel; - if(parlevel < 1) + if (parlevel < 1) { par = 0; break; } } - else if(parlevel == 1 && (tok2->str() == ",")) + else if (parlevel == 1 && (tok2->str() == ",")) { ++par; } - if(parlevel == 1) + if (parlevel == 1) { - if(varid > 0 && Token::Match(tok2, "[(,] %varid% [,)]", varid)) + if (varid > 0 && Token::Match(tok2, "[(,] %varid% [,)]", varid)) { ++par; tok1 = tok2->next(); break; } - else if(varid == 0 && Token::Match(tok2, ("[(,] " + varnames + " [,)]").c_str())) + else if (varid == 0 && Token::Match(tok2, ("[(,] " + varnames + " [,)]").c_str())) { ++par; tok1 = tok2->tokAt(varc + 1); @@ -733,29 +733,29 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vectorgetFunctionTokenByName(tok->str().c_str()); - if(!ftok) + if (!ftok) continue; // Parse head of function.. ftok = ftok->tokAt(2); parlevel = 1; - while(ftok && parlevel == 1 && par >= 1) + while (ftok && parlevel == 1 && par >= 1) { - if(ftok->str() == "(") + if (ftok->str() == "(") ++parlevel; - else if(ftok->str() == ")") + else if (ftok->str() == ")") --parlevel; - else if(ftok->str() == ",") + else if (ftok->str() == ",") --par; - else if(par == 1 && parlevel == 1 && Token::Match(ftok, "%var% [,)]")) + else if (par == 1 && parlevel == 1 && Token::Match(ftok, "%var% [,)]")) { // Parameter name.. std::vector parname; @@ -764,12 +764,12 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vectorvarId(); // Goto function body.. - while(ftok && (ftok->str() != "{")) + while (ftok && (ftok->str() != "{")) ftok = ftok->next(); ftok = ftok ? ftok->next() : 0; // Don't make recursive checking.. - if(std::find_if(_callStack.begin(), _callStack.end(), TokenStrEquals(tok1->str())) != _callStack.end()) + if (std::find_if(_callStack.begin(), _callStack.end(), TokenStrEquals(tok1->str())) != _callStack.end()) continue; // Check variable usage in the function.. @@ -795,12 +795,12 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vectortokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { - if(tok->str() == "{") + if (tok->str() == "{") ++indentlevel; - else if(tok->str() == "}") + else if (tok->str() == "}") --indentlevel; int size = 0; @@ -809,27 +809,27 @@ void CheckBufferOverrun::checkGlobalAndLocalVariable() int nextTok = 0; // if the previous token exists, it must be either a variable name or "[;{}]" - if(tok->previous() && (!tok->previous()->isName() && !Token::Match(tok->previous(), "[;{}]"))) + if (tok->previous() && (!tok->previous()->isName() && !Token::Match(tok->previous(), "[;{}]"))) continue; - if(Token::Match(tok, "%type% *| %var% [ %num% ] [;=]")) + if (Token::Match(tok, "%type% *| %var% [ %num% ] [;=]")) { unsigned int varpos = 1; - if(tok->next()->str() == "*") + if (tok->next()->str() == "*") ++varpos; size = MathLib::toLongNumber(tok->strAt(varpos + 2)); type = tok->strAt(varpos - 1); varid = tok->tokAt(varpos)->varId(); nextTok = varpos + 5; } - else if(Token::Match(tok, "%type% *| %var% [ %var% ] [;=]")) + else if (Token::Match(tok, "%type% *| %var% [ %var% ] [;=]")) { unsigned int varpos = 1; - if(tok->next()->str() == "*") + if (tok->next()->str() == "*") ++varpos; // make sure the variable is defined - if(tok->tokAt(varpos + 2)->varId() == 0) + if (tok->tokAt(varpos + 2)->varId() == 0) continue; // FIXME we loose the check for negative index when we bail // get maximum size from type @@ -838,43 +838,43 @@ void CheckBufferOverrun::checkGlobalAndLocalVariable() index_type = index_type->previous(); - if(index_type->str() == "char") + if (index_type->str() == "char") { - if(index_type->isUnsigned()) + if (index_type->isUnsigned()) size = UCHAR_MAX + 1; - else if(index_type->isSigned()) + else if (index_type->isSigned()) size = SCHAR_MAX + 1; else size = CHAR_MAX + 1; } - else if(index_type->str() == "short") + else if (index_type->str() == "short") { - if(index_type->isUnsigned()) + if (index_type->isUnsigned()) size = USHRT_MAX + 1; else size = SHRT_MAX + 1; } // checkScope assumes size is signed int so we limit the following sizes to INT_MAX - else if(index_type->str() == "int") + else if (index_type->str() == "int") { - if(index_type->isUnsigned()) + if (index_type->isUnsigned()) size = INT_MAX; // should be UINT_MAX + 1U; else size = INT_MAX; // should be INT_MAX + 1U; } - else if(index_type->str() == "long") + else if (index_type->str() == "long") { - if(index_type->isUnsigned()) + if (index_type->isUnsigned()) { - if(index_type->isLong()) + if (index_type->isLong()) size = INT_MAX; // should be ULLONG_MAX + 1ULL; else size = INT_MAX; // should be ULONG_MAX + 1UL; } else { - if(index_type->isLong()) + if (index_type->isLong()) size = INT_MAX; // should be LLONG_MAX + 1LL; else size = INT_MAX; // should be LONG_MAX + 1L; @@ -885,21 +885,21 @@ void CheckBufferOverrun::checkGlobalAndLocalVariable() varid = tok->tokAt(varpos)->varId(); nextTok = varpos + 5; } - else if(indentlevel > 0 && Token::Match(tok, "[*;{}] %var% = new %type% [ %num% ]")) + else if (indentlevel > 0 && Token::Match(tok, "[*;{}] %var% = new %type% [ %num% ]")) { size = MathLib::toLongNumber(tok->strAt(6)); type = tok->strAt(4); varid = tok->tokAt(1)->varId(); nextTok = 8; } - else if(indentlevel > 0 && Token::Match(tok, "[*;{}] %var% = new %type% ( %num% )")) + else if (indentlevel > 0 && Token::Match(tok, "[*;{}] %var% = new %type% ( %num% )")) { size = 1; type = tok->strAt(4); varid = tok->tokAt(1)->varId(); nextTok = 8; } - else if(indentlevel > 0 && Token::Match(tok, "[*;{}] %var% = malloc ( %num% ) ;")) + else if (indentlevel > 0 && Token::Match(tok, "[*;{}] %var% = malloc ( %num% ) ;")) { size = MathLib::toLongNumber(tok->strAt(5)); type = "char"; @@ -908,14 +908,14 @@ void CheckBufferOverrun::checkGlobalAndLocalVariable() // "int * x ; x = malloc (y);" const Token *declTok = tok->tokAt(-3); - if(varid > 0 && declTok && Token::Match(declTok, "%type% * %varid% ;", varid)) + if (varid > 0 && declTok && Token::Match(declTok, "%type% * %varid% ;", varid)) { type = declTok->strAt(0); // malloc() gets count of bytes and not count of // elements, so we should calculate count of elements // manually unsigned int sizeOfType = _tokenizer->sizeOfType(declTok); - if(sizeOfType > 0) + if (sizeOfType > 0) size /= sizeOfType; } } @@ -924,13 +924,13 @@ void CheckBufferOverrun::checkGlobalAndLocalVariable() continue; } - if(varid == 0) + if (varid == 0) continue; Token sizeTok(0); sizeTok.str(type); int total_size = size * _tokenizer->sizeOfType(&sizeTok); - if(total_size == 0) + if (total_size == 0) continue; // The callstack is empty @@ -949,25 +949,25 @@ void CheckBufferOverrun::checkGlobalAndLocalVariable() void CheckBufferOverrun::checkStructVariable() { const char declstruct[] = "struct|class %var% {"; - for(const Token *tok = Token::findmatch(_tokenizer->tokens(), declstruct); - tok; tok = Token::findmatch(tok->next(), declstruct)) + for (const Token *tok = Token::findmatch(_tokenizer->tokens(), declstruct); + tok; tok = Token::findmatch(tok->next(), declstruct)) { const std::string &structname = tok->next()->str(); // Found a struct declaration. Search for arrays.. - for(const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) + for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) { - if(tok2->str() == "}") + if (tok2->str() == "}") break; int ivar = 0; - if(Token::Match(tok2->next(), "%type% %var% [ %num% ] ;")) + if (Token::Match(tok2->next(), "%type% %var% [ %num% ] ;")) ivar = 2; - else if(Token::Match(tok2->next(), "%type% %type% %var% [ %num% ] ;")) + else if (Token::Match(tok2->next(), "%type% %type% %var% [ %num% ] ;")) ivar = 3; - else if(Token::Match(tok2->next(), "%type% * %var% [ %num% ] ;")) + else if (Token::Match(tok2->next(), "%type% * %var% [ %num% ] ;")) ivar = 3; - else if(Token::Match(tok2->next(), "%type% %type% * %var% [ %num% ] ;")) + else if (Token::Match(tok2->next(), "%type% %type% * %var% [ %num% ] ;")) ivar = 4; else continue; @@ -977,25 +977,25 @@ void CheckBufferOverrun::checkStructVariable() varname[1] = tok2->strAt(ivar); int arrsize = MathLib::toLongNumber(tok2->strAt(ivar + 2)); int total_size = arrsize * _tokenizer->sizeOfType(tok2->tokAt(1)); - if(tok2->tokAt(2)->str() == "*") + if (tok2->tokAt(2)->str() == "*") total_size = arrsize * _tokenizer->sizeOfType(tok2->tokAt(2)); - if(total_size == 0) + if (total_size == 0) continue; // Class member variable => Check functions - if(tok->str() == "class") + if (tok->str() == "class") { std::string func_pattern(structname + " :: %var% ("); const Token *tok3 = Token::findmatch(_tokenizer->tokens(), func_pattern.c_str()); - while(tok3) + while (tok3) { - for(const Token *tok4 = tok3; tok4; tok4 = tok4->next()) + for (const Token *tok4 = tok3; tok4; tok4 = tok4->next()) { - if(Token::Match(tok4, "[;{}]")) + if (Token::Match(tok4, "[;{}]")) break; - if(Token::simpleMatch(tok4, ") {")) + if (Token::simpleMatch(tok4, ") {")) { std::vector v; checkScope(tok4->tokAt(2), v, arrsize, total_size, varId); @@ -1006,17 +1006,17 @@ void CheckBufferOverrun::checkStructVariable() } } - for(const Token *tok3 = _tokenizer->tokens(); tok3; tok3 = tok3->next()) + for (const Token *tok3 = _tokenizer->tokens(); tok3; tok3 = tok3->next()) { - if(tok3->str() != structname) + if (tok3->str() != structname) continue; // Declare variable: Fred fred1; - if(Token::Match(tok3->next(), "%var% ;")) + if (Token::Match(tok3->next(), "%var% ;")) varname[0] = tok3->strAt(1); // Declare pointer: Fred *fred1 - else if(Token::Match(tok3->next(), "* %var% [,);=]")) + else if (Token::Match(tok3->next(), "* %var% [,);=]")) varname[0] = tok3->strAt(2); else @@ -1025,21 +1025,21 @@ void CheckBufferOverrun::checkStructVariable() // Goto end of statement. const Token *CheckTok = NULL; - while(tok3) + while (tok3) { // End of statement. - if(tok3->str() == ";") + if (tok3->str() == ";") { CheckTok = tok3; break; } // End of function declaration.. - if(Token::simpleMatch(tok3, ") ;")) + if (Token::simpleMatch(tok3, ") ;")) break; // Function implementation.. - if(Token::simpleMatch(tok3, ") {")) + if (Token::simpleMatch(tok3, ") {")) { CheckTok = tok3->tokAt(2); break; @@ -1048,10 +1048,10 @@ void CheckBufferOverrun::checkStructVariable() tok3 = tok3->next(); } - if(!tok3) + if (!tok3) break; - if(!CheckTok) + if (!CheckTok) continue; // Check variable usage.. @@ -1079,11 +1079,11 @@ int CheckBufferOverrun::countSprintfLength(const std::string &input_string, cons bool i_d_x_f_found = false; std::list::const_iterator paramIter = parameters.begin(); unsigned int parameterLength = 0; - for(std::string::size_type i = 0; i < input_string.length(); ++i) + for (std::string::size_type i = 0; i < input_string.length(); ++i) { - if(input_string[i] == '\\') + if (input_string[i] == '\\') { - if(input_string[i+1] == '0') + if (input_string[i+1] == '0') break; ++input_string_size; @@ -1091,9 +1091,9 @@ int CheckBufferOverrun::countSprintfLength(const std::string &input_string, cons continue; } - if(percentCharFound) + if (percentCharFound) { - switch(input_string[i]) + switch (input_string[i]) { case 'f': case 'x': @@ -1112,13 +1112,13 @@ int CheckBufferOverrun::countSprintfLength(const std::string &input_string, cons break; case 'd': i_d_x_f_found = true; - if(paramIter != parameters.end() && *paramIter && (*paramIter)->str()[0] != '"') + if (paramIter != parameters.end() && *paramIter && (*paramIter)->str()[0] != '"') parameterLength = (*paramIter)->str().length(); handleNextParameter = true; break; case 's': - if(paramIter != parameters.end() && *paramIter && (*paramIter)->str()[0] == '"') + if (paramIter != parameters.end() && *paramIter && (*paramIter)->str()[0] == '"') parameterLength = Token::getStrLength(*paramIter); handleNextParameter = true; @@ -1126,44 +1126,44 @@ int CheckBufferOverrun::countSprintfLength(const std::string &input_string, cons } } - if(input_string[i] == '%') + if (input_string[i] == '%') percentCharFound = !percentCharFound; - else if(percentCharFound) + else if (percentCharFound) { digits_string.append(1, input_string[i]); } - if(!percentCharFound) + if (!percentCharFound) input_string_size++; - if(handleNextParameter) + if (handleNextParameter) { unsigned int tempDigits = std::abs(std::atoi(digits_string.c_str())); - if(i_d_x_f_found) + if (i_d_x_f_found) tempDigits = std::max(static_cast(tempDigits), 1); - if(digits_string.find('.') != std::string::npos) + if (digits_string.find('.') != std::string::npos) { const std::string endStr = digits_string.substr(digits_string.find('.') + 1); unsigned int maxLen = std::max(std::abs(std::atoi(endStr.c_str())), 1); - if(input_string[i] == 's') + if (input_string[i] == 's') { // For strings, the length after the dot "%.2s" will limit // the length of the string. - if(parameterLength > maxLen) + if (parameterLength > maxLen) parameterLength = maxLen; } else { // For integers, the length after the dot "%.2d" can // increase required length - if(tempDigits < maxLen) + if (tempDigits < maxLen) tempDigits = maxLen; } } - if(tempDigits < parameterLength) + if (tempDigits < parameterLength) input_string_size += parameterLength; else input_string_size += tempDigits; @@ -1173,7 +1173,7 @@ int CheckBufferOverrun::countSprintfLength(const std::string &input_string, cons i_d_x_f_found = false; percentCharFound = false; handleNextParameter = false; - if(paramIter != parameters.end()) + if (paramIter != parameters.end()) ++paramIter; } } @@ -1185,18 +1185,18 @@ int CheckBufferOverrun::countSprintfLength(const std::string &input_string, cons void CheckBufferOverrun::checkSprintfCall(const Token *tok, int size) { std::list parameters; - if(tok->tokAt(5)->str() == ",") + if (tok->tokAt(5)->str() == ",") { const Token *end = tok->next()->link(); - for(const Token *tok2 = tok->tokAt(5); tok2 && tok2 != end; tok2 = tok2->next()) + for (const Token *tok2 = tok->tokAt(5); tok2 && tok2 != end; tok2 = tok2->next()) { - if(Token::Match(tok2, ", %any% [,)]")) + if (Token::Match(tok2, ", %any% [,)]")) { - if(Token::Match(tok2->next(), "%str%")) + if (Token::Match(tok2->next(), "%str%")) parameters.push_back(tok2->next()); - else if(Token::Match(tok2->next(), "%num%")) + else if (Token::Match(tok2->next(), "%num%")) parameters.push_back(tok2->next()); // TODO, get value of the variable if possible and use that instead of 0 @@ -1209,33 +1209,33 @@ void CheckBufferOverrun::checkSprintfCall(const Token *tok, int size) // and skip to next token. parameters.push_back(0); int ind = 0; - for(const Token *tok3 = tok2->next(); tok3; tok3 = tok3->next()) + for (const Token *tok3 = tok2->next(); tok3; tok3 = tok3->next()) { - if(tok3->str() == "(") + if (tok3->str() == "(") ++ind; - else if(tok3->str() == ")") + else if (tok3->str() == ")") { --ind; - if(ind < 0) + if (ind < 0) break; } - else if(ind == 0 && tok3->str() == ",") + else if (ind == 0 && tok3->str() == ",") { tok2 = tok3->previous(); break; } } - if(ind < 0) + if (ind < 0) break; } } } int len = countSprintfLength(tok->tokAt(4)->strValue(), parameters); - if(len > size) + if (len > size) { bufferOverrun(tok); } diff --git a/lib/checkbufferoverrun.h b/lib/checkbufferoverrun.h index a3908b4cb..67d5e0ac3 100644 --- a/lib/checkbufferoverrun.h +++ b/lib/checkbufferoverrun.h @@ -54,7 +54,7 @@ public: /** This constructor is used when running checks. */ CheckBufferOverrun(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) - : Check(tokenizer, settings, errorLogger) + : Check(tokenizer, settings, errorLogger) { } void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) diff --git a/lib/checkclass.cpp b/lib/checkclass.cpp index 4733bd542..d2fb2e3e4 100644 --- a/lib/checkclass.cpp +++ b/lib/checkclass.cpp @@ -47,36 +47,36 @@ CheckClass::Var *CheckClass::getVarList(const Token *tok1, bool withClasses, boo Var *varlist = NULL; unsigned int indentlevel = 0; bool priv = !isStruct; - for(const Token *tok = tok1; tok; tok = tok->next()) + for (const Token *tok = tok1; tok; tok = tok->next()) { - if(!tok->next()) + if (!tok->next()) break; - if(tok->str() == "{") + if (tok->str() == "{") ++indentlevel; - else if(tok->str() == "}") + else if (tok->str() == "}") { - if(indentlevel <= 1) + if (indentlevel <= 1) break; --indentlevel; } - if(indentlevel != 1) + if (indentlevel != 1) continue; // Borland C++: Skip all variables in the __published section. // These are automaticly initialized. - if(tok->str() == "__published:") + if (tok->str() == "__published:") { priv = false; - for(; tok; tok = tok->next()) + for (; tok; tok = tok->next()) { - if(tok->str() == "{") + if (tok->str() == "{") tok = tok->link(); - if(Token::Match(tok->next(), "private:|protected:|public:")) + if (Token::Match(tok->next(), "private:|protected:|public:")) break; } - if(tok) + if (tok) continue; else break; @@ -85,11 +85,11 @@ CheckClass::Var *CheckClass::getVarList(const Token *tok1, bool withClasses, boo // "private:" "public:" "protected:" etc const bool b((tok->str()[0] != ':') && tok->str().find(":") != std::string::npos); - if(b) + if (b) priv = bool(tok->str() == "private:"); // Search for start of statement.. - if(! Token::Match(tok, "[;{}]") && ! b) + if (! Token::Match(tok, "[;{}]") && ! b) continue; // This is the start of a statement @@ -97,93 +97,93 @@ CheckClass::Var *CheckClass::getVarList(const Token *tok1, bool withClasses, boo std::string varname; // If next token contains a ":".. it is not part of a variable declaration - if(next->str().find(":") != std::string::npos) + if (next->str().find(":") != std::string::npos) continue; // Variable declarations that start with "static" shall be ignored.. - if(next->str() == "static") + if (next->str() == "static") continue; // Borland C++: Ignore properties.. - if(next->str() == "__property") + if (next->str() == "__property") continue; // Type definitions shall be ignored.. - if(next->str() == "typedef") + if (next->str() == "typedef") continue; // Is it a mutable variable? bool isMutable = false; - if(next->str() == "mutable") + if (next->str() == "mutable") { isMutable = true; next = next->next(); } // Is it a variable declaration? - if(Token::Match(next, "%type% %var% ;")) + if (Token::Match(next, "%type% %var% ;")) { - if(withClasses) + if (withClasses) varname = next->strAt(1); - else if(next->isStandardType()) + else if (next->isStandardType()) varname = next->strAt(1); - else if(Token::findmatch(_tokenizer->tokens(), ("enum " + next->str()).c_str())) + else if (Token::findmatch(_tokenizer->tokens(), ("enum " + next->str()).c_str())) varname = next->strAt(1); } // Structure? - else if(Token::Match(next, "struct|union %type% %var% ;")) + else if (Token::Match(next, "struct|union %type% %var% ;")) { varname = next->strAt(2); } // Pointer? - else if(Token::Match(next, "%type% * %var% ;")) + else if (Token::Match(next, "%type% * %var% ;")) { varname = next->strAt(2); } // Pointer? - else if(Token::Match(next, "%type% %type% * %var% ;")) + else if (Token::Match(next, "%type% %type% * %var% ;")) { varname = next->strAt(3); } // Array? - else if(Token::Match(next, "%type% %var% [") && next->next()->str() != "operator") + else if (Token::Match(next, "%type% %var% [") && next->next()->str() != "operator") { - if(!withClasses) + if (!withClasses) { - if(Token::findmatch(_tokenizer->tokens(), ("class|struct " + next->str()).c_str())) + if (Token::findmatch(_tokenizer->tokens(), ("class|struct " + next->str()).c_str())) continue; } varname = next->strAt(1); } // Pointer array? - else if(Token::Match(next, "%type% * %var% [")) + else if (Token::Match(next, "%type% * %var% [")) { varname = next->strAt(2); } // std::string.. - else if(withClasses && Token::Match(next, "%type% :: %type% %var% ;")) + else if (withClasses && Token::Match(next, "%type% :: %type% %var% ;")) { varname = next->strAt(3); } // Container.. - else if(withClasses && (Token::Match(next, "%type% :: %type% <") || - Token::Match(next, "%type% <"))) + else if (withClasses && (Token::Match(next, "%type% :: %type% <") || + Token::Match(next, "%type% <"))) { - while(next && next->str() != ">") + while (next && next->str() != ">") next = next->next(); - if(Token::Match(next, "> %var% ;")) + if (Token::Match(next, "> %var% ;")) varname = next->strAt(1); } // If the varname was set in one of the two if-block above, create a entry for this variable.. - if(!varname.empty() && varname != "operator") + if (!varname.empty() && varname != "operator") { Var *var = new Var(varname, false, priv, isMutable, varlist); varlist = var; @@ -196,9 +196,9 @@ CheckClass::Var *CheckClass::getVarList(const Token *tok1, bool withClasses, boo void CheckClass::initVar(Var *varlist, const std::string &varname) { - for(Var *var = varlist; var; var = var->next) + for (Var *var = varlist; var; var = var->next) { - if(var->name == varname) + if (var->name == varname) { var->init = true; return; @@ -212,16 +212,16 @@ void CheckClass::initializeVarList(const Token *tok1, const Token *ftok, Var *va bool Assign = false; unsigned int indentlevel = 0; - for(; ftok; ftok = ftok->next()) + for (; ftok; ftok = ftok->next()) { - if(!ftok->next()) + if (!ftok->next()) break; // Class constructor.. initializing variables like this // clKalle::clKalle() : var(value) { } - if(indentlevel == 0) + if (indentlevel == 0) { - if(Assign && Token::Match(ftok, "%var% (")) + if (Assign && Token::Match(ftok, "%var% (")) { initVar(varlist, ftok->strAt(0)); } @@ -230,73 +230,73 @@ void CheckClass::initializeVarList(const Token *tok1, const Token *ftok, Var *va } - if(ftok->str() == "{") + if (ftok->str() == "{") { ++indentlevel; Assign = false; } - else if(ftok->str() == "}") + else if (ftok->str() == "}") { - if(indentlevel <= 1) + if (indentlevel <= 1) break; --indentlevel; } - if(indentlevel < 1) + if (indentlevel < 1) continue; // Variable getting value from stream? - if(Token::Match(ftok, ">> %var%")) + if (Token::Match(ftok, ">> %var%")) { initVar(varlist, ftok->strAt(1)); } // Before a new statement there is "[{};)=]" or "else" - if(! Token::Match(ftok, "[{};()=]") && ftok->str() != "else") + if (! Token::Match(ftok, "[{};()=]") && ftok->str() != "else") continue; // Using the operator= function to initialize all variables.. - if(Token::simpleMatch(ftok->next(), "* this = ")) + if (Token::simpleMatch(ftok->next(), "* this = ")) { - for(Var *var = varlist; var; var = var->next) + for (Var *var = varlist; var; var = var->next) var->init = true; break; } - if(!Token::Match(ftok->next(), "%var%") && - !Token::Match(ftok->next(), "this . %var%") && - !Token::Match(ftok->next(), "* %var% =") && - !Token::Match(ftok->next(), "( * this ) . %var%")) + if (!Token::Match(ftok->next(), "%var%") && + !Token::Match(ftok->next(), "this . %var%") && + !Token::Match(ftok->next(), "* %var% =") && + !Token::Match(ftok->next(), "( * this ) . %var%")) continue; // Goto the first token in this statement.. ftok = ftok->next(); // Skip "( * this )" - if(Token::simpleMatch(ftok, "( * this ) .")) + if (Token::simpleMatch(ftok, "( * this ) .")) { ftok = ftok->tokAt(5); } // Skip "this->" - if(Token::simpleMatch(ftok, "this .")) + if (Token::simpleMatch(ftok, "this .")) ftok = ftok->tokAt(2); // Skip "classname :: " - if(Token::Match(ftok, "%var% ::")) + if (Token::Match(ftok, "%var% ::")) ftok = ftok->tokAt(2); // Clearing all variables.. - if(Token::simpleMatch(ftok, "memset ( this ,")) + if (Token::simpleMatch(ftok, "memset ( this ,")) { - for(Var *var = varlist; var; var = var->next) + for (Var *var = varlist; var; var = var->next) var->init = true; return; } // Clearing array.. - else if(Token::Match(ftok, "memset ( %var% ,")) + else if (Token::Match(ftok, "memset ( %var% ,")) { initVar(varlist, ftok->strAt(2)); ftok = ftok->next()->link(); @@ -304,28 +304,28 @@ void CheckClass::initializeVarList(const Token *tok1, const Token *ftok, Var *va } // Calling member function? - else if(Token::Match(ftok, "%var% (")) + else if (Token::Match(ftok, "%var% (")) { // Passing "this" => assume that everything is initialized - for(const Token * tok2 = ftok->next()->link(); tok2 && tok2 != ftok; tok2 = tok2->previous()) + for (const Token * tok2 = ftok->next()->link(); tok2 && tok2 != ftok; tok2 = tok2->previous()) { - if(tok2->str() == "this") + if (tok2->str() == "this") { - for(Var *var = varlist; var; var = var->next) + for (Var *var = varlist; var; var = var->next) var->init = true; return; } } - if(ftok->str() == "if") + if (ftok->str() == "if") continue; // No recursive calls! - if(std::find(callstack.begin(), callstack.end(), ftok->str()) == callstack.end()) + if (std::find(callstack.begin(), callstack.end(), ftok->str()) == callstack.end()) { int i = 0; const Token *ftok2 = _tokenizer->findClassFunction(tok1, classname, ftok->strAt(0), i, isStruct); - if(ftok2) + if (ftok2) { callstack.push_back(ftok->str()); initializeVarList(tok1, ftok2, varlist, classname, callstack, isStruct); @@ -335,19 +335,19 @@ void CheckClass::initializeVarList(const Token *tok1, const Token *ftok, Var *va { // check if the function is part of this class.. const Token *tok = Token::findmatch(_tokenizer->tokens(), (std::string("class ") + classname + " {").c_str()); - for(tok = tok ? tok->tokAt(3) : 0; tok; tok = tok->next()) + for (tok = tok ? tok->tokAt(3) : 0; tok; tok = tok->next()) { - if(tok->str() == "{") + if (tok->str() == "{") { tok = tok->link(); - if(!tok) + if (!tok) break; } - else if(tok->str() == "}") + else if (tok->str() == "}") { break; } - else if(tok->str() == ftok->str() || tok->str() == "friend") + else if (tok->str() == ftok->str() || tok->str() == "friend") { tok = 0; break; @@ -355,9 +355,9 @@ void CheckClass::initializeVarList(const Token *tok1, const Token *ftok, Var *va } // bail out.. - if(!tok) + if (!tok) { - for(Var *var = varlist; var; var = var->next) + for (Var *var = varlist; var; var = var->next) var->init = true; break; } @@ -365,17 +365,17 @@ void CheckClass::initializeVarList(const Token *tok1, const Token *ftok, Var *va // the function is external and it's neither friend nor inherited virtual function. // assume all variables that are passed to it are initialized.. unsigned int indentlevel2 = 0; - for(tok = ftok->tokAt(2); tok; tok = tok->next()) + for (tok = ftok->tokAt(2); tok; tok = tok->next()) { - if(tok->str() == "(") + if (tok->str() == "(") ++indentlevel2; - else if(tok->str() == ")") + else if (tok->str() == ")") { - if(indentlevel2 == 0) + if (indentlevel2 == 0) break; --indentlevel2; } - if(tok->isName()) + if (tok->isName()) { initVar(varlist, tok->strAt(0)); } @@ -386,31 +386,31 @@ void CheckClass::initializeVarList(const Token *tok1, const Token *ftok, Var *va } // Assignment of member variable? - else if(Token::Match(ftok, "%var% =")) + else if (Token::Match(ftok, "%var% =")) { initVar(varlist, ftok->strAt(0)); } // Assignment of array item of member variable? - else if(Token::Match(ftok, "%var% [ %any% ] =")) + else if (Token::Match(ftok, "%var% [ %any% ] =")) { initVar(varlist, ftok->strAt(0)); } // Assignment of array item of member variable? - else if(Token::Match(ftok, "%var% [ %any% ] [ %any% ] =")) + else if (Token::Match(ftok, "%var% [ %any% ] [ %any% ] =")) { initVar(varlist, ftok->strAt(0)); } // Assignment of array item of member variable? - else if(Token::Match(ftok, "* %var% =")) + else if (Token::Match(ftok, "* %var% =")) { initVar(varlist, ftok->strAt(1)); } // The functions 'clear' and 'Clear' are supposed to initialize variable. - if(Token::Match(ftok, "%var% . clear|Clear (")) + if (Token::Match(ftok, "%var% . clear|Clear (")) { initVar(varlist, ftok->strAt(0)); } @@ -432,7 +432,7 @@ void CheckClass::constructors() // Locate class const Token *tok1 = Token::findmatch(_tokenizer->tokens(), pattern_class); - while(tok1) + while (tok1) { const std::string className = tok1->strAt(1); const Token *classNameToken = tok1->tokAt(1); @@ -443,30 +443,30 @@ void CheckClass::constructors() { int indentlevel = 0; bool isPrivate = !isStruct; - for(const Token *tok = tok1; tok; tok = tok->next()) + for (const Token *tok = tok1; tok; tok = tok->next()) { // Indentation - if(tok->str() == "{") + if (tok->str() == "{") ++indentlevel; - else if(tok->str() == "}") + else if (tok->str() == "}") { --indentlevel; - if(indentlevel <= 0) + if (indentlevel <= 0) break; } // Parse class contents (indentlevel == 1).. - if(indentlevel == 1) + if (indentlevel == 1) { // What section are we in.. private/non-private - if(tok->str() == "private:") + if (tok->str() == "private:") isPrivate = true; - else if(tok->str() == "protected:" || tok->str() == "public:") + else if (tok->str() == "protected:" || tok->str() == "public:") isPrivate = false; // Is there a private constructor? - else if(isPrivate && Token::simpleMatch(tok, (classNameToken->str() + " (").c_str())) + else if (isPrivate && Token::simpleMatch(tok, (classNameToken->str() + " (").c_str())) { hasPrivateConstructor = true; break; @@ -475,7 +475,7 @@ void CheckClass::constructors() } } - if(hasPrivateConstructor && !_settings->_showAll) + if (hasPrivateConstructor && !_settings->_showAll) { /** @todo Handle private constructors. Right now to avoid * false positives we just bail out */ @@ -486,22 +486,22 @@ void CheckClass::constructors() // Are there a class constructor? std::string tempPattern = "%any% " + classNameToken->str() + " ("; const Token *constructor_token = Token::findmatch(tok1, tempPattern.c_str()); - while(constructor_token && constructor_token->str() == "~") + while (constructor_token && constructor_token->str() == "~") constructor_token = Token::findmatch(constructor_token->next(), tempPattern.c_str()); // There are no constructor. - if(! constructor_token) + if (! constructor_token) { // If "--style" has been given, give a warning - if(_settings->_checkCodingStyle) + if (_settings->_checkCodingStyle) { // Get class variables... Var *varlist = getVarList(tok1, false, isStruct); // If there is a private variable, there should be a constructor.. - for(const Var *var = varlist; var; var = var->next) + for (const Var *var = varlist; var; var = var->next) { - if(var->priv) + if (var->priv) { noConstructorError(tok1, classNameToken->str(), isStruct); break; @@ -509,7 +509,7 @@ void CheckClass::constructors() } // Delete the varlist.. - while(varlist) + while (varlist) { Var *nextvar = varlist->next; delete varlist; @@ -543,48 +543,48 @@ void CheckClass::checkConstructors(const Token *tok1, const std::string &funcnam const Token *constructor_token = _tokenizer->findClassFunction(tok1, className, funcname, indentlevel, isStruct); std::list callstack; initializeVarList(tok1, constructor_token, varlist, className, callstack, isStruct); - while(constructor_token) + while (constructor_token) { // Check if any variables are uninitialized - for(Var *var = varlist; var; var = var->next) + for (Var *var = varlist; var; var = var->next) { - if(var->init) + if (var->init) continue; // Is it a static member variable? std::ostringstream pattern; pattern << className << " :: " << var->name << " ="; - if(Token::findmatch(_tokenizer->tokens(), pattern.str().c_str())) + if (Token::findmatch(_tokenizer->tokens(), pattern.str().c_str())) continue; // It's non-static and it's not initialized => error - if(Token::simpleMatch(constructor_token, "operator = (") || - Token::simpleMatch(constructor_token->tokAt(2), "operator = (")) + if (Token::simpleMatch(constructor_token, "operator = (") || + Token::simpleMatch(constructor_token->tokAt(2), "operator = (")) { const Token *operStart = 0; - if(Token::simpleMatch(constructor_token, "operator = (")) + if (Token::simpleMatch(constructor_token, "operator = (")) operStart = constructor_token->tokAt(2); else operStart = constructor_token->tokAt(4); bool classNameUsed = false; - for(const Token *operTok = operStart; operTok != operStart->link(); operTok = operTok->next()) + for (const Token *operTok = operStart; operTok != operStart->link(); operTok = operTok->next()) { - if(operTok->str() == className) + if (operTok->str() == className) { classNameUsed = true; break; } } - if(classNameUsed) + if (classNameUsed) operatorEqVarError(constructor_token, className, var->name); } else uninitVarError(constructor_token, className, var->name, hasPrivateConstructor); } - for(Var *var = varlist; var; var = var->next) + for (Var *var = varlist; var; var = var->next) var->init = false; constructor_token = _tokenizer->findClassFunction(constructor_token->next(), className, funcname, indentlevel, isStruct); @@ -593,7 +593,7 @@ void CheckClass::checkConstructors(const Token *tok1, const std::string &funcnam } // Delete the varlist.. - while(varlist) + while (varlist) { Var *nextvar = varlist->next; delete varlist; @@ -609,12 +609,12 @@ void CheckClass::checkConstructors(const Token *tok1, const std::string &funcnam void CheckClass::privateFunctions() { // Locate some class - for(const Token *tok1 = Token::findmatch(_tokenizer->tokens(), "class|struct %var% {"); tok1; tok1 = Token::findmatch(tok1->next(), "class|struct %var% {")) + for (const Token *tok1 = Token::findmatch(_tokenizer->tokens(), "class|struct %var% {"); tok1; tok1 = Token::findmatch(tok1->next(), "class|struct %var% {")) { /** @todo check that the whole class implementation is seen */ // until the todo above is fixed we only check classes that are // declared in the source file - if(tok1->fileIndex() != 0) + if (tok1->fileIndex() != 0) continue; const std::string &classname = tok1->next()->str(); @@ -625,50 +625,50 @@ void CheckClass::privateFunctions() bool isStruct = tok1->str() == "struct"; bool priv = !isStruct; unsigned int indent_level = 0; - for(const Token *tok = tok1; tok; tok = tok->next()) + for (const Token *tok = tok1; tok; tok = tok->next()) { - if(Token::Match(tok, "friend %var%")) + if (Token::Match(tok, "friend %var%")) { /** @todo Handle friend classes */ FuncList.clear(); break; } - if(tok->str() == "{") + if (tok->str() == "{") ++indent_level; - else if(tok->str() == "}") + else if (tok->str() == "}") { - if(indent_level <= 1) + if (indent_level <= 1) break; --indent_level; } - else if(indent_level != 1) + else if (indent_level != 1) continue; - else if(tok->str() == "private:") + else if (tok->str() == "private:") priv = true; - else if(tok->str() == "public:") + else if (tok->str() == "public:") priv = false; - else if(tok->str() == "protected:") + else if (tok->str() == "protected:") priv = false; - else if(priv) + else if (priv) { - if(Token::Match(tok, "typedef %type% (")) + if (Token::Match(tok, "typedef %type% (")) tok = tok->tokAt(2)->link(); - else if(Token::Match(tok, "[:,] %var% (")) + else if (Token::Match(tok, "[:,] %var% (")) tok = tok->tokAt(2)->link(); - else if(Token::Match(tok, "%var% (") && - !Token::simpleMatch(tok->next()->link(), ") (") && - !Token::Match(tok, classname.c_str())) + else if (Token::Match(tok, "%var% (") && + !Token::simpleMatch(tok->next()->link(), ") (") && + !Token::Match(tok, classname.c_str())) { FuncList.push_back(tok); } } /** @todo embedded class have access to private functions */ - if(tok->str() == "class") + if (tok->str() == "class") { FuncList.clear(); break; @@ -679,62 +679,62 @@ void CheckClass::privateFunctions() bool HasFuncImpl = false; bool inclass = false; indent_level = 0; - for(const Token *ftok = _tokenizer->tokens(); ftok; ftok = ftok->next()) + for (const Token *ftok = _tokenizer->tokens(); ftok; ftok = ftok->next()) { - if(ftok->str() == "{") + if (ftok->str() == "{") ++indent_level; - else if(ftok->str() == "}") + else if (ftok->str() == "}") { - if(indent_level > 0) + if (indent_level > 0) --indent_level; - if(indent_level == 0) + if (indent_level == 0) inclass = false; } - if(Token::Match(ftok, ("class " + classname + " :|{").c_str())) + if (Token::Match(ftok, ("class " + classname + " :|{").c_str())) { indent_level = 0; inclass = true; } // Check member class functions to see what functions are used.. - if((inclass && indent_level == 1 && Token::Match(ftok, ") const| {")) || - (Token::Match(ftok, (classname + " :: ~| %var% (").c_str()))) + if ((inclass && indent_level == 1 && Token::Match(ftok, ") const| {")) || + (Token::Match(ftok, (classname + " :: ~| %var% (").c_str()))) { - while(ftok && ftok->str() != ")") + while (ftok && ftok->str() != ")") ftok = ftok->next(); - if(!ftok) + if (!ftok) break; - if(Token::Match(ftok, ") : %var% (")) + if (Token::Match(ftok, ") : %var% (")) { - while(!Token::Match(ftok->next(), "[{};]")) + while (!Token::Match(ftok->next(), "[{};]")) ftok = ftok->next(); } - if(!Token::Match(ftok, ") const| {")) + if (!Token::Match(ftok, ") const| {")) continue; - if(ftok->fileIndex() == 0) + if (ftok->fileIndex() == 0) HasFuncImpl = true; // Parse function.. int indentlevel2 = 0; - for(const Token *tok2 = ftok; tok2; tok2 = tok2->next()) + for (const Token *tok2 = ftok; tok2; tok2 = tok2->next()) { - if(tok2->str() == "{") + if (tok2->str() == "{") ++indentlevel2; - else if(tok2->str() == "}") + else if (tok2->str() == "}") { --indentlevel2; - if(indentlevel2 < 1) + if (indentlevel2 < 1) break; } - else if(Token::Match(tok2, "%var% (")) + else if (Token::Match(tok2, "%var% (")) { // Remove function from FuncList std::list::iterator it = FuncList.begin(); - while(it != FuncList.end()) + while (it != FuncList.end()) { - if(tok2->str() == (*it)->str()) + if (tok2->str() == (*it)->str()) FuncList.erase(it++); else it++; @@ -744,11 +744,11 @@ void CheckClass::privateFunctions() } } - while(HasFuncImpl && !FuncList.empty()) + while (HasFuncImpl && !FuncList.empty()) { // Final check; check if the function pointer is used somewhere.. const std::string _pattern("return|(|)|,|= " + FuncList.front()->str()); - if(!Token::findmatch(_tokenizer->tokens(), _pattern.c_str())) + if (!Token::findmatch(_tokenizer->tokens(), _pattern.c_str())) { unusedPrivateFunctionError(FuncList.front(), classname, FuncList.front()->str()); } @@ -764,77 +764,77 @@ void CheckClass::privateFunctions() void CheckClass::noMemset() { // Locate all 'memset' tokens.. - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { - if(!Token::Match(tok, "memset|memcpy|memmove")) + if (!Token::Match(tok, "memset|memcpy|memmove")) continue; std::string type; - if(Token::Match(tok, "memset ( %var% , %num% , sizeof ( %type% ) )")) + if (Token::Match(tok, "memset ( %var% , %num% , sizeof ( %type% ) )")) type = tok->strAt(8); - else if(Token::Match(tok, "memset ( & %var% , %num% , sizeof ( %type% ) )")) + else if (Token::Match(tok, "memset ( & %var% , %num% , sizeof ( %type% ) )")) type = tok->strAt(9); - else if(Token::Match(tok, "memset ( %var% , %num% , sizeof ( struct %type% ) )")) + else if (Token::Match(tok, "memset ( %var% , %num% , sizeof ( struct %type% ) )")) type = tok->strAt(9); - else if(Token::Match(tok, "memset ( & %var% , %num% , sizeof ( struct %type% ) )")) + else if (Token::Match(tok, "memset ( & %var% , %num% , sizeof ( struct %type% ) )")) type = tok->strAt(10); - else if(Token::Match(tok, "%type% ( %var% , %var% , sizeof ( %type% ) )")) + else if (Token::Match(tok, "%type% ( %var% , %var% , sizeof ( %type% ) )")) type = tok->strAt(8); // No type defined => The tokens didn't match - if(type.empty()) + if (type.empty()) continue; // Warn if type is a class or struct that contains any std::* variables const std::string pattern2(std::string("struct|class ") + type + " {"); - for(const Token *tstruct = Token::findmatch(_tokenizer->tokens(), pattern2.c_str()); tstruct; tstruct = tstruct->next()) + for (const Token *tstruct = Token::findmatch(_tokenizer->tokens(), pattern2.c_str()); tstruct; tstruct = tstruct->next()) { - if(tstruct->str() == "}") + if (tstruct->str() == "}") break; // struct with function? skip function body.. - if(Token::simpleMatch(tstruct, ") {")) + if (Token::simpleMatch(tstruct, ") {")) { tstruct = tstruct->next()->link(); - if(!tstruct) + if (!tstruct) break; } // before a statement there must be either: // * private:|protected:|public: // * { } ; - if(Token::Match(tstruct, "[;{}]") || - tstruct->str().find(":") != std::string::npos) + if (Token::Match(tstruct, "[;{}]") || + tstruct->str().find(":") != std::string::npos) { - if(Token::Match(tstruct->next(), "std :: %type% %var% ;")) + if (Token::Match(tstruct->next(), "std :: %type% %var% ;")) memsetStructError(tok, tok->str(), tstruct->strAt(3)); - else if(Token::Match(tstruct->next(), "std :: %type% < ")) + else if (Token::Match(tstruct->next(), "std :: %type% < ")) { // backup the type const std::string typestr(tstruct->strAt(3)); // check if it's a pointer variable.. unsigned int level = 0; - while(0 != (tstruct = tstruct->next())) + while (0 != (tstruct = tstruct->next())) { - if(tstruct->str() == "<") + if (tstruct->str() == "<") ++level; - else if(tstruct->str() == ">") + else if (tstruct->str() == ">") { - if(level <= 1) + if (level <= 1) break; --level; } - else if(tstruct->str() == "(") + else if (tstruct->str() == "(") tstruct = tstruct->link(); } - if(!tstruct) + if (!tstruct) break; // found error => report - if(Token::Match(tstruct, "> %var% ;")) + if (Token::Match(tstruct, "> %var% ;")) memsetStructError(tok, tok->str(), typestr); } } @@ -855,22 +855,22 @@ void CheckClass::operatorEq() const Token *tok2 = _tokenizer->tokens(); const Token *tok; - while((tok = Token::findmatch(tok2, "void operator = ("))) + while ((tok = Token::findmatch(tok2, "void operator = ("))) { const Token *tok1 = tok; - while(tok1 && !Token::Match(tok1, "class|struct %var%")) + while (tok1 && !Token::Match(tok1, "class|struct %var%")) { - if(tok1->str() == "public:") + if (tok1->str() == "public:") { operatorEqReturnError(tok); break; } - if(tok1->str() == "private:" || tok1->str() == "protected:") + if (tok1->str() == "private:" || tok1->str() == "protected:") break; tok1 = tok1->previous(); } - if(tok1 && Token::Match(tok1, "struct %var%")) + if (tok1 && Token::Match(tok1, "struct %var%")) operatorEqReturnError(tok); tok2 = tok->next(); @@ -889,12 +889,12 @@ void CheckClass::operatorEq() // match two lists of tokens static bool nameMatch(const Token * tok1, const Token * tok2, int length) { - for(int i = 0; i < length; i++) + for (int i = 0; i < length; i++) { - if(tok1->tokAt(i) == 0 || tok2->tokAt(i) == 0) + if (tok1->tokAt(i) == 0 || tok2->tokAt(i) == 0) return false; - if(tok1->tokAt(i)->str() != tok2->tokAt(i)->str()) + if (tok1->tokAt(i)->str() != tok2->tokAt(i)->str()) return false; } @@ -904,9 +904,9 @@ static bool nameMatch(const Token * tok1, const Token * tok2, int length) // create a class name from a list of tokens static void nameStr(const Token * name, int length, std::string & str) { - for(int i = 0; i < length; i++) + for (int i = 0; i < length; i++) { - if(i != 0) + if (i != 0) str += " "; str += name->tokAt(i)->str(); @@ -918,11 +918,11 @@ void CheckClass::operatorEqRetRefThis() const Token *tok2 = _tokenizer->tokens(); const Token *tok; - while((tok = Token::findmatch(tok2, "operator = ("))) + while ((tok = Token::findmatch(tok2, "operator = ("))) { const Token *tok1 = tok; - if(tok1->tokAt(-2) && Token::Match(tok1->tokAt(-2), " %type% ::")) + if (tok1->tokAt(-2) && Token::Match(tok1->tokAt(-2), " %type% ::")) { // make sure this is an assignment operator int nameLength = 1; @@ -930,7 +930,7 @@ void CheckClass::operatorEqRetRefThis() tok1 = tok1->tokAt(-2); // check backwards for proper function signature - while(tok1->tokAt(-2) && Token::Match(tok1->tokAt(-2), " %type% ::")) + while (tok1->tokAt(-2) && Token::Match(tok1->tokAt(-2), " %type% ::")) { tok1 = tok1->tokAt(-2); nameLength += 2; @@ -941,35 +941,35 @@ void CheckClass::operatorEqRetRefThis() nameStr(name, nameLength, nameString); - if(tok1->tokAt(-1) && tok1->tokAt(-1)->str() == "&") + if (tok1->tokAt(-1) && tok1->tokAt(-1)->str() == "&") { // check class name - if(tok1->tokAt(-(1 + nameLength)) && nameMatch(name, tok1->tokAt(-(1 + nameLength)), nameLength)) + if (tok1->tokAt(-(1 + nameLength)) && nameMatch(name, tok1->tokAt(-(1 + nameLength)), nameLength)) { // may take overloaded argument types so no need to check them tok1 = tok->tokAt(2)->link(); - if(tok1 && tok1->next() && tok1->next()->str() == "{") + if (tok1 && tok1->next() && tok1->next()->str() == "{") { bool foundReturn = false; const Token *last = tok1->next()->link(); - for(tok1 = tok1->tokAt(2); tok1 && tok1 != last; tok1 = tok1->next()) + for (tok1 = tok1->tokAt(2); tok1 && tok1 != last; tok1 = tok1->next()) { // check for return of reference to this - if(tok1->str() == "return") + if (tok1->str() == "return") { foundReturn = true; std::string cast("( " + name->str() + " & )"); - if(Token::Match(tok1->next(), cast.c_str())) + if (Token::Match(tok1->next(), cast.c_str())) tok1 = tok1->tokAt(4); - if(!(Token::Match(tok1->tokAt(1), "(| * this ;|=") || - Token::Match(tok1->tokAt(1), "(| * this +=") || - Token::Match(tok1->tokAt(1), "operator = ("))) + if (!(Token::Match(tok1->tokAt(1), "(| * this ;|=") || + Token::Match(tok1->tokAt(1), "(| * this +=") || + Token::Match(tok1->tokAt(1), "operator = ("))) operatorEqRetRefThisError(tok); } } - if(!foundReturn) + if (!foundReturn) operatorEqRetRefThisError(tok); } } @@ -981,56 +981,56 @@ void CheckClass::operatorEqRetRefThis() tok1 = tok; // check backwards for proper function signature - if(tok1->tokAt(-1) && tok1->tokAt(-1)->str() == "&") + if (tok1->tokAt(-1) && tok1->tokAt(-1)->str() == "&") { const Token *name = 0; bool isPublic = false; - while(tok1 && !Token::Match(tok1, "class|struct %var%")) + while (tok1 && !Token::Match(tok1, "class|struct %var%")) { - if(!isPublic) + if (!isPublic) { - if(tok1->str() == "public:") + if (tok1->str() == "public:") isPublic = true; } tok1 = tok1->previous(); } - if(tok1 && Token::Match(tok1, "struct %var%")) + if (tok1 && Token::Match(tok1, "struct %var%")) { isPublic = true; name = tok1->tokAt(1); } - else if(tok1 && Token::Match(tok1, "class %var%")) + else if (tok1 && Token::Match(tok1, "class %var%")) { name = tok1->tokAt(1); } - if(tok->tokAt(-2) && tok->tokAt(-2)->str() == name->str()) + if (tok->tokAt(-2) && tok->tokAt(-2)->str() == name->str()) { // may take overloaded argument types so no need to check them tok1 = tok->tokAt(2)->link(); - if(tok1 && tok1->next() && tok1->next()->str() == "{") + if (tok1 && tok1->next() && tok1->next()->str() == "{") { bool foundReturn = false; const Token *last = tok1->next()->link(); - for(tok1 = tok1->tokAt(2); tok1 && tok1 != last; tok1 = tok1->next()) + for (tok1 = tok1->tokAt(2); tok1 && tok1 != last; tok1 = tok1->next()) { // check for return of reference to this - if(tok1->str() == "return") + if (tok1->str() == "return") { foundReturn = true; std::string cast("( " + name->str() + " & )"); - if(Token::Match(tok1->next(), cast.c_str())) + if (Token::Match(tok1->next(), cast.c_str())) tok1 = tok1->tokAt(4); - if(!(Token::Match(tok1->tokAt(1), "(| * this ;|=") || - Token::Match(tok1->tokAt(1), "(| * this +=") || - Token::Match(tok1->tokAt(1), "operator = ("))) + if (!(Token::Match(tok1->tokAt(1), "(| * this ;|=") || + Token::Match(tok1->tokAt(1), "(| * this +=") || + Token::Match(tok1->tokAt(1), "operator = ("))) operatorEqRetRefThisError(tok); } } - if(!foundReturn) + if (!foundReturn) operatorEqRetRefThisError(tok); } } @@ -1068,10 +1068,10 @@ static bool hasDeallocation(const Token * first, const Token * last) // Unfortunately, this is necessary to prevent false positives. // This check needs to do careful analysis someday to get this // correct with a high degree of certainty. - for(const Token * tok = first; tok && (tok != last); tok = tok->next()) + for (const Token * tok = first; tok && (tok != last); tok = tok->next()) { // check for deallocating memory - if(Token::Match(tok, "{|;|, free ( %var%")) + if (Token::Match(tok, "{|;|, free ( %var%")) { const Token * var = tok->tokAt(3); @@ -1079,18 +1079,18 @@ static bool hasDeallocation(const Token * first, const Token * last) const Token * tok1 = tok->tokAt(4); - while(tok1 && (tok1 != last)) + while (tok1 && (tok1 != last)) { - if(Token::Match(tok1, "%var% =")) + if (Token::Match(tok1, "%var% =")) { - if(tok1->str() == var->str()) + if (tok1->str() == var->str()) return true; } tok1 = tok1->next(); } } - else if(Token::Match(tok, "{|;|, delete [ ] %var%")) + else if (Token::Match(tok, "{|;|, delete [ ] %var%")) { const Token * var = tok->tokAt(4); @@ -1098,18 +1098,18 @@ static bool hasDeallocation(const Token * first, const Token * last) const Token * tok1 = tok->tokAt(5); - while(tok1 && (tok1 != last)) + while (tok1 && (tok1 != last)) { - if(Token::Match(tok1, "%var% = new %type% [")) + if (Token::Match(tok1, "%var% = new %type% [")) { - if(tok1->str() == var->str()) + if (tok1->str() == var->str()) return true; } tok1 = tok1->next(); } } - else if(Token::Match(tok, "{|;|, delete %var%")) + else if (Token::Match(tok, "{|;|, delete %var%")) { const Token * var = tok->tokAt(2); @@ -1117,11 +1117,11 @@ static bool hasDeallocation(const Token * first, const Token * last) const Token * tok1 = tok->tokAt(3); - while(tok1 && (tok1 != last)) + while (tok1 && (tok1 != last)) { - if(Token::Match(tok1, "%var% = new")) + if (Token::Match(tok1, "%var% = new")) { - if(tok1->str() == var->str()) + if (tok1->str() == var->str()) return true; } @@ -1135,25 +1135,25 @@ static bool hasDeallocation(const Token * first, const Token * last) static bool hasAssignSelf(const Token * first, const Token * last, const Token * rhs) { - for(const Token * tok = first; tok && tok != last; tok = tok->next()) + for (const Token * tok = first; tok && tok != last; tok = tok->next()) { - if(Token::Match(tok, "if (")) + if (Token::Match(tok, "if (")) { const Token * tok1 = tok->tokAt(2); const Token * tok2 = tok->tokAt(1)->link(); - if(tok1 && tok2) + if (tok1 && tok2) { - for(; tok1 && tok1 != tok2; tok1 = tok1->next()) + for (; tok1 && tok1 != tok2; tok1 = tok1->next()) { - if(Token::Match(tok1, "this ==|!= & %var%")) + if (Token::Match(tok1, "this ==|!= & %var%")) { - if(tok1->tokAt(3)->str() == rhs->str()) + if (tok1->tokAt(3)->str() == rhs->str()) return true; } - else if(Token::Match(tok1, "& %var% ==|!= this")) + else if (Token::Match(tok1, "& %var% ==|!= this")) { - if(tok1->tokAt(1)->str() == rhs->str()) + if (tok1->tokAt(1)->str() == rhs->str()) return true; } } @@ -1166,9 +1166,9 @@ static bool hasAssignSelf(const Token * first, const Token * last, const Token * static bool hasMultipleInheritanceInline(const Token * tok) { - while(tok && tok->str() != "{") + while (tok && tok->str() != "{") { - if(tok->str() == ",") + if (tok->str() == ",") return true; tok = tok->next(); @@ -1184,12 +1184,12 @@ static bool hasMultipleInheritanceGlobal(const Token * start, const std::string std::string className = name; // check for nested classes - while(className.find("::") != std::string::npos) + while (className.find("::") != std::string::npos) { std::string tempName; // there is probably a better way to do this - while(className[0] != ' ') + while (className[0] != ' ') { tempName += className[0]; className.erase(0, 1); @@ -1214,19 +1214,19 @@ void CheckClass::operatorEqToSelf() const Token *tok2 = _tokenizer->tokens(); const Token *tok; - while((tok = Token::findmatch(tok2, "operator = ("))) + while ((tok = Token::findmatch(tok2, "operator = ("))) { const Token *tok1 = tok; // make sure this is an assignment operator - if(tok1->tokAt(-2) && Token::Match(tok1->tokAt(-2), " %type% ::")) + if (tok1->tokAt(-2) && Token::Match(tok1->tokAt(-2), " %type% ::")) { int nameLength = 1; tok1 = tok1->tokAt(-2); // check backwards for proper function signature - while(tok1->tokAt(-2) && Token::Match(tok1->tokAt(-2), " %type% ::")) + while (tok1->tokAt(-2) && Token::Match(tok1->tokAt(-2), " %type% ::")) { tok1 = tok1->tokAt(-2); nameLength += 2; @@ -1237,31 +1237,31 @@ void CheckClass::operatorEqToSelf() nameStr(name, nameLength, nameString); - if(!hasMultipleInheritanceGlobal(_tokenizer->tokens(), nameString)) + if (!hasMultipleInheritanceGlobal(_tokenizer->tokens(), nameString)) { - if(tok1->tokAt(-1) && tok1->tokAt(-1)->str() == "&") + if (tok1->tokAt(-1) && tok1->tokAt(-1)->str() == "&") { // check returned class name - if(tok1->tokAt(-(1 + nameLength)) && nameMatch(name, tok1->tokAt(-(1 + nameLength)), nameLength)) + if (tok1->tokAt(-(1 + nameLength)) && nameMatch(name, tok1->tokAt(-(1 + nameLength)), nameLength)) { // check forward for proper function signature std::string pattern = "const " + nameString + " & %var% )"; - if(Token::Match(tok->tokAt(3), pattern.c_str())) + if (Token::Match(tok->tokAt(3), pattern.c_str())) { const Token * rhs = tok->tokAt(5 + nameLength); - if(nameMatch(name, tok->tokAt(4), nameLength)) + if (nameMatch(name, tok->tokAt(4), nameLength)) { tok1 = tok->tokAt(2)->link(); - if(tok1 && tok1->tokAt(1) && tok1->tokAt(1)->str() == "{" && tok1->tokAt(1)->link()) + if (tok1 && tok1->tokAt(1) && tok1->tokAt(1)->str() == "{" && tok1->tokAt(1)->link()) { const Token *first = tok1->tokAt(1); const Token *last = first->link(); - if(!hasAssignSelf(first, last, rhs)) + if (!hasAssignSelf(first, last, rhs)) { - if(hasDeallocation(first, last)) + if (hasDeallocation(first, last)) operatorEqToSelfError(tok); } } @@ -1276,36 +1276,36 @@ void CheckClass::operatorEqToSelf() tok1 = tok; // check backwards for proper function signature - if(tok1->tokAt(-1) && tok1->tokAt(-1)->str() == "&") + if (tok1->tokAt(-1) && tok1->tokAt(-1)->str() == "&") { const Token *name = 0; - while(tok1 && !Token::Match(tok1, "class|struct %var%")) + while (tok1 && !Token::Match(tok1, "class|struct %var%")) tok1 = tok1->previous(); - if(Token::Match(tok1, "struct|class %var%")) + if (Token::Match(tok1, "struct|class %var%")) name = tok1->tokAt(1); - if(!hasMultipleInheritanceInline(tok1)) + if (!hasMultipleInheritanceInline(tok1)) { - if(Token::simpleMatch(tok->tokAt(-2), name->str().c_str())) + if (Token::simpleMatch(tok->tokAt(-2), name->str().c_str())) { // check forward for proper function signature - if(Token::Match(tok->tokAt(3), "const %type% & %var% )")) + if (Token::Match(tok->tokAt(3), "const %type% & %var% )")) { const Token * rhs = tok->tokAt(6); - if(tok->tokAt(4)->str() == name->str()) + if (tok->tokAt(4)->str() == name->str()) { tok1 = tok->tokAt(2)->link(); - if(tok1 && Token::simpleMatch(tok1->next(), "{")) + if (tok1 && Token::simpleMatch(tok1->next(), "{")) { const Token *first = tok1->next(); const Token *last = first->link(); - if(!hasAssignSelf(first, last, rhs)) + if (!hasAssignSelf(first, last, rhs)) { - if(hasDeallocation(first, last)) + if (hasDeallocation(first, last)) operatorEqToSelfError(tok); } } @@ -1333,7 +1333,7 @@ void CheckClass::virtualDestructor() const char pattern_classdecl[] = "class %var% : %var%"; const Token *derived = _tokenizer->tokens(); - while((derived = Token::findmatch(derived, pattern_classdecl)) != NULL) + while ((derived = Token::findmatch(derived, pattern_classdecl)) != NULL) { // Check that the derived class has a non empty destructor.. { @@ -1342,14 +1342,14 @@ void CheckClass::virtualDestructor() const Token *derived_destructor = Token::findmatch(_tokenizer->tokens(), destructorPattern.str().c_str()); // No destructor.. - if(! derived_destructor) + if (! derived_destructor) { derived = derived->next(); continue; } // Empty destructor.. - if(Token::Match(derived_destructor, "~ %var% ( ) { }")) + if (Token::Match(derived_destructor, "~ %var% ( ) { }")) { derived = derived->next(); continue; @@ -1360,12 +1360,12 @@ void CheckClass::virtualDestructor() // Iterate through each base class... derived = derived->tokAt(3); - while(Token::Match(derived, "%var%")) + while (Token::Match(derived, "%var%")) { bool isPublic(derived->str() == "public"); // What kind of inheritance is it.. public|protected|private - if(Token::Match(derived, "public|protected|private")) + if (Token::Match(derived, "public|protected|private")) derived = derived->next(); // Name of base class.. @@ -1374,10 +1374,10 @@ void CheckClass::virtualDestructor() // Update derived so it's ready for the next loop. do { - if(derived->str() == "{") + if (derived->str() == "{") break; - if(derived->str() == ",") + if (derived->str() == ",") { derived = derived->next(); break; @@ -1385,27 +1385,27 @@ void CheckClass::virtualDestructor() derived = derived->next(); } - while(derived); + while (derived); // If not public inheritance, skip checking of this base class.. - if(! isPublic) + if (! isPublic) continue; // Find the destructor declaration for the base class. const Token *base = Token::findmatch(_tokenizer->tokens(), (std::string("%any% ~ ") + baseName + " (").c_str()); - while(base && base->str() == "::") + while (base && base->str() == "::") base = Token::findmatch(base->next(), (std::string("%any% ~ ") + baseName + " (").c_str()); const Token *reverseTok = base; - while(Token::Match(base, "%var%") && base->str() != "virtual") + while (Token::Match(base, "%var%") && base->str() != "virtual") base = base->previous(); // Check that there is a destructor.. - if(! base) + if (! base) { // Is the class declaration available? base = Token::findmatch(_tokenizer->tokens(), (std::string("class ") + baseName + " {").c_str()); - if(base) + if (base) { virtualDestructorError(base, baseName, derivedClass->str()); } @@ -1414,7 +1414,7 @@ void CheckClass::virtualDestructor() } // There is a destructor. Check that it's virtual.. - else if(base->str() == "virtual") + else if (base->str() == "virtual") continue; // TODO: This is just a temporary fix, better solution is needed. @@ -1423,30 +1423,30 @@ void CheckClass::virtualDestructor() // Proper solution is to check all of the base classes. If base class is not // found or if one of the base classes has virtual destructor, error should not // be printed. See TODO test case "virtualDestructorInherited" - if(!Token::findmatch(_tokenizer->tokens(), (std::string("class ") + baseName + " {").c_str())) + if (!Token::findmatch(_tokenizer->tokens(), (std::string("class ") + baseName + " {").c_str())) continue; // Make sure that the destructor is public (protected or private // would not compile if inheritance is used in a way that would // cause the bug we are trying to find here.) int indent = 0; - while(reverseTok) + while (reverseTok) { - if(reverseTok->str() == "public:") + if (reverseTok->str() == "public:") { virtualDestructorError(base, baseName, derivedClass->str()); break; } - else if(reverseTok->str() == "protected:" || - reverseTok->str() == "private:") + else if (reverseTok->str() == "protected:" || + reverseTok->str() == "private:") { // No bug, protected/private destructor is allowed break; } - else if(reverseTok->str() == "{") + else if (reverseTok->str() == "{") { indent++; - if(indent >= 1) + if (indent >= 1) { // We have found the start of the class without any sign // of "public :" so we can assume that the destructor is not @@ -1454,7 +1454,7 @@ void CheckClass::virtualDestructor() break; } } - else if(reverseTok->str() == "}") + else if (reverseTok->str() == "}") indent--; reverseTok = reverseTok->previous(); @@ -1472,13 +1472,13 @@ void CheckClass::thisSubtractionError(const Token *tok) void CheckClass::thisSubtraction() { const Token *tok = _tokenizer->tokens(); - for(;;) + for (;;) { tok = Token::findmatch(tok, "this - %var%"); - if(!tok) + if (!tok) break; - if(!Token::simpleMatch(tok->previous(), "*")) + if (!Token::simpleMatch(tok->previous(), "*")) thisSubtractionError(tok); tok = tok->next(); @@ -1496,23 +1496,23 @@ struct NestInfo // Can a function be const? void CheckClass::checkConst() { - if(!_settings->_checkCodingStyle) + if (!_settings->_checkCodingStyle) return; std::vector nestInfo; int level = 0; Var *varlist = 0; - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { - if(tok->str() == "{" && !nestInfo.empty()) + if (tok->str() == "{" && !nestInfo.empty()) level++; - else if(tok->str() == "}" && !nestInfo.empty()) + else if (tok->str() == "}" && !nestInfo.empty()) { level--; - if(level == nestInfo.back().levelEnd) + if (level == nestInfo.back().levelEnd) nestInfo.pop_back(); } - else if(Token::Match(tok, "class|struct %var% {")) + else if (Token::Match(tok, "class|struct %var% {")) { const Token *classTok = tok; @@ -1520,9 +1520,9 @@ void CheckClass::checkConst() std::string classname(tok->strAt(1)); // goto initial {' - while(tok && tok->str() != "{") + while (tok && tok->str() != "{") tok = tok->next(); - if(!tok) + if (!tok) break; const Token *classEnd = tok->link(); @@ -1534,7 +1534,7 @@ void CheckClass::checkConst() nestInfo.push_back(info); // Delete the varlist.. - while(varlist) + while (varlist) { Var *nextvar = varlist->next; delete varlist; @@ -1545,90 +1545,90 @@ void CheckClass::checkConst() varlist = getVarList(classTok, true, classTok->str() == "struct"); // parse in this class definition to see if there are any simple getter functions - for(const Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) + for (const Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) { - if(tok2->str() == "{") + if (tok2->str() == "{") tok2 = tok2->link(); - else if(tok2->str() == "}") + else if (tok2->str() == "}") break; // start of statement? - if(!Token::Match(tok2->previous(), "[;{}]")) + if (!Token::Match(tok2->previous(), "[;{}]")) continue; // skip private: public: etc - if(tok2->isName() && tok2->str().find(":") != std::string::npos) + if (tok2->isName() && tok2->str().find(":") != std::string::npos) { - if(tok2->next()->str() == "}") + if (tok2->next()->str() == "}") continue; tok2 = tok2->next(); } // static functions can't be const // virtual functions may be non-const for a reason - if(Token::Match(tok2, "static|virtual")) + if (Token::Match(tok2, "static|virtual")) continue; // don't warn if type is LP.. - if(tok2->str().compare(0, 2, "LP") == 0) + if (tok2->str().compare(0, 2, "LP") == 0) continue; // member function? - if(isMemberFunc(tok2)) + if (isMemberFunc(tok2)) { // goto function name.. - while(tok2->next()->str() != "(") + while (tok2->next()->str() != "(") tok2 = tok2->next(); // get function name const std::string functionName((tok2->isName() ? "" : "operator") + tok2->str()); // skip constructor - if(functionName == classname) + if (functionName == classname) continue; // goto the ')' tok2 = tok2->next()->link(); - if(!tok2) + if (!tok2) break; // is this a non-const function that is implemented inline? - if(Token::simpleMatch(tok2, ") {")) + if (Token::simpleMatch(tok2, ") {")) { const Token *paramEnd = tok2; // if nothing non-const was found. write error.. - if(checkConstFunc(classname, varlist, paramEnd)) + if (checkConstFunc(classname, varlist, paramEnd)) { - for(int i = nestInfo.size() - 2; i >= 0; i--) + for (int i = nestInfo.size() - 2; i >= 0; i--) classname = std::string(nestInfo[i].className + "::" + classname); checkConstError(tok2, classname, functionName); } } - else if(Token::simpleMatch(tok2, ") ;")) // not inline + else if (Token::simpleMatch(tok2, ") ;")) // not inline { - for(int i = nestInfo.size() - 1; i >= 0; i--) + for (int i = nestInfo.size() - 1; i >= 0; i--) { const Token *found = nestInfo[i].classEnd; std::string pattern(functionName + " ("); int level = 0; - for(int j = nestInfo.size() - 1; j >= i; j--, level++) + for (int j = nestInfo.size() - 1; j >= i; j--, level++) pattern = std::string(nestInfo[j].className + " :: " + pattern); - while((found = Token::findmatch(found->next(), pattern.c_str()))) + while ((found = Token::findmatch(found->next(), pattern.c_str()))) { const Token *paramEnd = found->tokAt(1 + (2 * level))->link(); - if(!paramEnd) + if (!paramEnd) break; - if(paramEnd->next()->str() != "{") + if (paramEnd->next()->str() != "{") break; - if(sameFunc(level, tok2, paramEnd)) + if (sameFunc(level, tok2, paramEnd)) { // if nothing non-const was found. write error.. - if(checkConstFunc(classname, varlist, paramEnd)) + if (checkConstFunc(classname, varlist, paramEnd)) { - for(int k = nestInfo.size() - 2; k >= 0; k--) + for (int k = nestInfo.size() - 2; k >= 0; k--) classname = std::string(nestInfo[k].className + "::" + classname); checkConstError2(found, tok2, classname, functionName); @@ -1643,7 +1643,7 @@ void CheckClass::checkConst() } // Delete the varlist.. - while(varlist) + while (varlist) { Var *nextvar = varlist->next; delete varlist; @@ -1660,25 +1660,25 @@ bool CheckClass::sameFunc(int nest, const Token *firstEnd, const Token *secondEn bool firstDone = false; bool secondDone = false; - while(true) + while (true) { firstDone = false; secondDone = false; - if(!firstStart || Token::Match(firstStart, ";|}|{|public:|protected:|private:")) + if (!firstStart || Token::Match(firstStart, ";|}|{|public:|protected:|private:")) firstDone = true; - if(!secondStart || Token::Match(secondStart, ";|}|{|public:|protected:|private:")) + if (!secondStart || Token::Match(secondStart, ";|}|{|public:|protected:|private:")) secondDone = true; - if(firstDone != secondDone) + if (firstDone != secondDone) return false; // both done and match - if(firstDone) + if (firstDone) break; - if(secondStart->str() != firstStart->str()) + if (secondStart->str() != firstStart->str()) return false; firstStart = firstStart->previous(); @@ -1689,53 +1689,53 @@ bool CheckClass::sameFunc(int nest, const Token *firstEnd, const Token *secondEn firstStart = firstEnd->link()->next(); secondStart = secondEnd->link()->next(); - while(true) + while (true) { firstDone = false; secondDone = false; bool again = true; - while(again) + while (again) { again = false; - if(firstStart == firstEnd) + if (firstStart == firstEnd) firstDone = true; - if(secondStart == secondEnd) + if (secondStart == secondEnd) secondDone = true; // possible difference in number of parameters - if(firstDone != secondDone) + if (firstDone != secondDone) { // check for missing names - if(firstDone) + if (firstDone) { - if(secondStart->varId() != 0) + if (secondStart->varId() != 0) again = true; } else { - if(firstStart->varId() != 0) + if (firstStart->varId() != 0) again = true; } - if(!again) + if (!again) return false; } // both done and match - if(firstDone && !again) + if (firstDone && !again) return true; - if(firstStart->varId() != 0) + if (firstStart->varId() != 0) { // skip variable name firstStart = firstStart->next(); again = true; } - if(secondStart->varId() != 0) + if (secondStart->varId() != 0) { // skip variable name secondStart = secondStart->next(); @@ -1743,11 +1743,11 @@ bool CheckClass::sameFunc(int nest, const Token *firstEnd, const Token *secondEn } } - if(firstStart->str() != secondStart->str()) + if (firstStart->str() != secondStart->str()) return false; // retry after skipped variable names - if(!again) + if (!again) { firstStart = firstStart->next(); secondStart = secondStart->next(); @@ -1773,37 +1773,37 @@ bool CheckClass::isMemberFunc(const Token *tok) { bool isConst = false; - if(tok->str() == "const") + if (tok->str() == "const") { isConst = true; tok = tok->next(); } - if(Token::Match(tok, "%type%")) + if (Token::Match(tok, "%type%")) { tok = tok->next(); - if(Token::Match(tok, "%var% (")) + if (Token::Match(tok, "%var% (")) return true; - else if(Token::Match(tok, "operator %any% (")) + else if (Token::Match(tok, "operator %any% (")) return true; - while(Token::Match(tok, ":: %type%")) + while (Token::Match(tok, ":: %type%")) tok = tok->tokAt(2); // template with parameter(s)? - if(Token::Match(tok, "< %type%")) + if (Token::Match(tok, "< %type%")) { unsigned int level = 1; tok = tok->tokAt(2); - while(tok) + while (tok) { - if(tok->str() == "<") + if (tok->str() == "<") level++; - else if(tok->str() == ">") + else if (tok->str() == ">") { level--; - if(level == 0) + if (level == 0) { tok = tok->next(); break; @@ -1814,25 +1814,25 @@ bool CheckClass::isMemberFunc(const Token *tok) } // template with default type - else if(Token::Match(tok, "< >")) + else if (Token::Match(tok, "< >")) tok = tok->tokAt(2); // operator something - else if(Token::Match(tok, "operator %any% (")) + else if (Token::Match(tok, "operator %any% (")) return true; - if(isConst) + if (isConst) { - while(Token::Match(tok, "*|&")) + while (Token::Match(tok, "*|&")) { tok = tok->next(); - if(tok->str() == "const") + if (tok->str() == "const") tok = tok->next(); } } - if(Token::Match(tok, "%var% (")) + if (Token::Match(tok, "%var% (")) return true; } @@ -1841,24 +1841,24 @@ bool CheckClass::isMemberFunc(const Token *tok) bool CheckClass::isMemberVar(const std::string &classname, const Var *varlist, const Token *tok) { - while(tok->previous() && !Token::Match(tok->previous(), "}|{|;|public:|protected:|private:|return|:|?")) + while (tok->previous() && !Token::Match(tok->previous(), "}|{|;|public:|protected:|private:|return|:|?")) { - if(Token::Match(tok->previous(), "* this")) + if (Token::Match(tok->previous(), "* this")) return true; tok = tok->previous(); } - if(tok->str() == "this") + if (tok->str() == "this") return true; // ignore class namespace - if(tok->str() == classname && tok->next()->str() == "::") + if (tok->str() == classname && tok->next()->str() == "::") tok = tok->tokAt(2); - for(const Var *var = varlist; var; var = var->next) + for (const Var *var = varlist; var; var = var->next) { - if(var->name == tok->str()) + if (var->name == tok->str()) { return !var->isMutable; } @@ -1873,23 +1873,23 @@ bool CheckClass::checkConstFunc(const std::string &classname, const Var *varlist // it can be a const function.. unsigned int indentlevel = 0; bool isconst = true; - for(const Token *tok1 = tok; tok1; tok1 = tok1->next()) + for (const Token *tok1 = tok; tok1; tok1 = tok1->next()) { - if(tok1->str() == "{") + if (tok1->str() == "{") ++indentlevel; - else if(tok1->str() == "}") + else if (tok1->str() == "}") { - if(indentlevel <= 1) + if (indentlevel <= 1) break; --indentlevel; } // assignment.. = += |= .. - else if(tok1->str() == "=" || - (tok1->str().find("=") == 1 && - tok1->str().find_first_of("") == std::string::npos)) + else if (tok1->str() == "=" || + (tok1->str().find("=") == 1 && + tok1->str().find_first_of("") == std::string::npos)) { - if(isMemberVar(classname, varlist, tok1->previous())) + if (isMemberVar(classname, varlist, tok1->previous())) { isconst = false; break; @@ -1897,21 +1897,21 @@ bool CheckClass::checkConstFunc(const std::string &classname, const Var *varlist } // increment/decrement (member variable?).. - else if(Token::Match(tok1, "++|--")) + else if (Token::Match(tok1, "++|--")) { isconst = false; break; } // function call.. - else if(tok1->str() != "return" && Token::Match(tok1, "%var% (")) + else if (tok1->str() != "return" && Token::Match(tok1, "%var% (")) { isconst = false; break; } // delete.. - else if(tok1->str() == "delete") + else if (tok1->str() == "delete") { isconst = false; break; diff --git a/lib/checkclass.h b/lib/checkclass.h index 6a7e60ded..a9173c2fd 100644 --- a/lib/checkclass.h +++ b/lib/checkclass.h @@ -40,7 +40,7 @@ public: /** @brief This constructor is used when running checks. */ CheckClass(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) - : Check(tokenizer, settings, errorLogger) + : Check(tokenizer, settings, errorLogger) { } /** @brief Run checks on the normal token list */ @@ -57,13 +57,13 @@ public: { CheckClass checkClass(tokenizer, settings, errorLogger); - if(settings->_checkCodingStyle) + if (settings->_checkCodingStyle) { checkClass.constructors(); checkClass.operatorEq(); checkClass.privateFunctions(); checkClass.operatorEqRetRefThis(); - if(settings->_showAll) + if (settings->_showAll) { checkClass.thisSubtraction(); checkClass.operatorEqToSelf(); @@ -114,11 +114,11 @@ private: { public: Var(const std::string &name_, bool init_ = false, bool priv_ = false, bool mutable_ = false, Var *next_ = 0) - : name(name_), - init(init_), - priv(priv_), - isMutable(mutable_), - next(next_) + : name(name_), + init(init_), + priv(priv_), + isMutable(mutable_), + next(next_) { } diff --git a/lib/checkdangerousfunctions.cpp b/lib/checkdangerousfunctions.cpp index 5edce9849..ef96cb590 100644 --- a/lib/checkdangerousfunctions.cpp +++ b/lib/checkdangerousfunctions.cpp @@ -33,17 +33,17 @@ CheckDangerousFunctions instance; void CheckDangerousFunctions::dangerousFunctions() { - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { - if(Token::simpleMatch(tok, "mktemp (")) + if (Token::simpleMatch(tok, "mktemp (")) { dangerousFunctionmktemp(tok); } - else if(Token::simpleMatch(tok, "gets (")) + else if (Token::simpleMatch(tok, "gets (")) { dangerousFunctiongets(tok); } - else if(Token::simpleMatch(tok, "scanf (")) + else if (Token::simpleMatch(tok, "scanf (")) { dangerousFunctionscanf(tok); } diff --git a/lib/checkdangerousfunctions.h b/lib/checkdangerousfunctions.h index 82dc324d8..7f74cbcd6 100644 --- a/lib/checkdangerousfunctions.h +++ b/lib/checkdangerousfunctions.h @@ -40,13 +40,13 @@ public: /** This constructor is used when running checks. */ CheckDangerousFunctions(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) - : Check(tokenizer, settings, errorLogger) + : Check(tokenizer, settings, errorLogger) { } void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) { CheckDangerousFunctions checkDangerousFunctions(tokenizer, settings, errorLogger); - if(settings->_checkCodingStyle) + if (settings->_checkCodingStyle) { checkDangerousFunctions.dangerousFunctions(); } diff --git a/lib/checkexceptionsafety.cpp b/lib/checkexceptionsafety.cpp index 5ad191f0c..4048eb928 100644 --- a/lib/checkexceptionsafety.cpp +++ b/lib/checkexceptionsafety.cpp @@ -37,35 +37,35 @@ CheckExceptionSafety instance; void CheckExceptionSafety::destructors() { // This is a style error.. - if(!_settings->_checkCodingStyle) + if (!_settings->_checkCodingStyle) return; // Perform check.. - for(const Token * tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token * tok = _tokenizer->tokens(); tok; tok = tok->next()) { - if(Token::simpleMatch(tok, ") {")) + if (Token::simpleMatch(tok, ") {")) tok = tok->next()->link(); - if(!Token::Match(tok, "~ %var% ( ) {")) + if (!Token::Match(tok, "~ %var% ( ) {")) continue; // Inspect this destructor.. unsigned int indentlevel = 0; - for(const Token *tok2 = tok->tokAt(5); tok2; tok2 = tok2->next()) + for (const Token *tok2 = tok->tokAt(5); tok2; tok2 = tok2->next()) { - if(tok2->str() == "{") + if (tok2->str() == "{") { ++indentlevel; } - else if(tok2->str() == "}") + else if (tok2->str() == "}") { - if(indentlevel <= 1) + if (indentlevel <= 1) break; --indentlevel; } - else if(tok2->str() == "throw") + else if (tok2->str() == "throw") { destructorsError(tok2); break; @@ -77,82 +77,82 @@ void CheckExceptionSafety::destructors() void CheckExceptionSafety::unsafeNew() { - if(!_settings->isEnabled("exceptNew")) + if (!_settings->isEnabled("exceptNew")) return; // Inspect initializer lists.. - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { - if(tok->str() != ")") + if (tok->str() != ")") continue; tok = tok->next(); - if(!tok) + if (!tok) break; - if(tok->str() != ":") + if (tok->str() != ":") continue; // multiple "new" in an initializer list.. std::string varname; - for(tok = tok->next(); tok; tok = tok->next()) + for (tok = tok->next(); tok; tok = tok->next()) { - if(!Token::Match(tok, "%var% (")) + if (!Token::Match(tok, "%var% (")) break; tok = tok->next(); - if(Token::Match(tok->next(), "new %type%")) + if (Token::Match(tok->next(), "new %type%")) { - if(!varname.empty()) + if (!varname.empty()) { unsafeNewError(tok->previous(), varname); break; } - if(!_settings->isAutoDealloc(tok->strAt(2))) + if (!_settings->isAutoDealloc(tok->strAt(2))) { varname = tok->strAt(-1); } } tok = tok->link(); tok = tok ? tok->next() : 0; - if(!tok) + if (!tok) break; - if(tok->str() != ",") + if (tok->str() != ",") break; } - if(!tok) + if (!tok) break; } // Inspect constructors.. - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { // match this pattern.. "C :: C ( .. ) {" - if(!tok->next() || tok->next()->str() != "::") + if (!tok->next() || tok->next()->str() != "::") continue; - if(!Token::Match(tok, "%var% :: %var% (")) + if (!Token::Match(tok, "%var% :: %var% (")) continue; - if(tok->str() != tok->strAt(2)) + if (tok->str() != tok->strAt(2)) continue; - if(!Token::simpleMatch(tok->tokAt(3)->link(), ") {")) + if (!Token::simpleMatch(tok->tokAt(3)->link(), ") {")) continue; // inspect the constructor.. std::string varname; - for(tok = tok->tokAt(3)->link()->tokAt(2); tok; tok = tok->next()) + for (tok = tok->tokAt(3)->link()->tokAt(2); tok; tok = tok->next()) { - if(tok->str() == "{" || tok->str() == "}") + if (tok->str() == "{" || tok->str() == "}") break; // some variable declaration.. - if(Token::Match(tok->previous(), "[{;] %type% * %var% ;")) + if (Token::Match(tok->previous(), "[{;] %type% * %var% ;")) break; // allocating with new.. - if(Token::Match(tok, "%var% = new %type%")) + if (Token::Match(tok, "%var% = new %type%")) { - if(!varname.empty()) + if (!varname.empty()) { unsafeNewError(tok, varname); break; } - if(!_settings->isAutoDealloc(tok->strAt(3))) + if (!_settings->isAutoDealloc(tok->strAt(3))) varname = tok->str(); } } @@ -161,50 +161,50 @@ void CheckExceptionSafety::unsafeNew() // allocating multiple local variables.. std::set localVars; std::string varname; - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { - if(tok->str() == "{" || tok->str() == "}") + if (tok->str() == "{" || tok->str() == "}") { localVars.clear(); varname = ""; } - if(Token::Match(tok, "[;{}] %type% * %var% ;") && - !_settings->isAutoDealloc(tok->strAt(1))) + if (Token::Match(tok, "[;{}] %type% * %var% ;") && + !_settings->isAutoDealloc(tok->strAt(1))) { tok = tok->tokAt(3); - if(tok->varId()) + if (tok->varId()) localVars.insert(tok->varId()); } - if(Token::Match(tok, "[;{}] %var% = new %type%")) + if (Token::Match(tok, "[;{}] %var% = new %type%")) { - if(!varname.empty()) + if (!varname.empty()) { unsafeNewError(tok->next(), varname); break; } - if(tok->next()->varId() && localVars.find(tok->next()->varId()) != localVars.end()) + if (tok->next()->varId() && localVars.find(tok->next()->varId()) != localVars.end()) varname = tok->strAt(1); } - else if(Token::Match(tok, "[;{}] %var% (")) + else if (Token::Match(tok, "[;{}] %var% (")) { - for(tok = tok->next(); tok && !Token::Match(tok, "[;{}]"); tok = tok->next()) + for (tok = tok->next(); tok && !Token::Match(tok, "[;{}]"); tok = tok->next()) { - if(tok->str() == varname) + if (tok->str() == varname) { varname = ""; } } - if(!tok) + if (!tok) break; } - else if(tok->str() == "delete") + else if (tok->str() == "delete") { - if(Token::simpleMatch(tok->next(), varname.c_str()) || - Token::simpleMatch(tok->next(), ("[ ] " + varname).c_str())) + if (Token::simpleMatch(tok->next(), varname.c_str()) || + Token::simpleMatch(tok->next(), ("[ ] " + varname).c_str())) { varname = ""; } @@ -215,55 +215,55 @@ void CheckExceptionSafety::unsafeNew() void CheckExceptionSafety::realloc() { - if(!_settings->isEnabled("exceptRealloc")) + if (!_settings->isEnabled("exceptRealloc")) return; - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { - if(Token::simpleMatch(tok, "try {")) + if (Token::simpleMatch(tok, "try {")) { tok = tok->next()->link(); - if(!tok) + if (!tok) break; } - if(!Token::Match(tok, "[{};] delete")) + if (!Token::Match(tok, "[{};] delete")) continue; tok = tok->tokAt(2); - if(Token::simpleMatch(tok, "[ ]")) + if (Token::simpleMatch(tok, "[ ]")) tok = tok->tokAt(2); - if(!tok) + if (!tok) break; // reallocating.. - if(!Token::Match(tok, "%var% ; %var% = new %type%")) + if (!Token::Match(tok, "%var% ; %var% = new %type%")) continue; // variable id of deallocated pointer.. const unsigned int varid(tok->varId()); - if(varid == 0) + if (varid == 0) continue; // variable id of allocated pointer must match.. - if(varid != tok->tokAt(2)->varId()) + if (varid != tok->tokAt(2)->varId()) continue; // is is a class member variable.. const Token *tok1 = Token::findmatch(_tokenizer->tokens(), "%varid%", varid); - while(0 != (tok1 = tok1 ? tok1->previous() : 0)) + while (0 != (tok1 = tok1 ? tok1->previous() : 0)) { - if(tok1->str() == "}") + if (tok1->str() == "}") tok1 = tok1->link(); - else if(tok1->str() == "{") + else if (tok1->str() == "{") { - if(tok1->previous() && tok1->previous()->isName()) + if (tok1->previous() && tok1->previous()->isName()) { - while(0 != (tok1 = tok1 ? tok1->previous() : 0)) + while (0 != (tok1 = tok1 ? tok1->previous() : 0)) { - if(!tok1->isName() && tok1->str() != ":" && tok1->str() != ",") + if (!tok1->isName() && tok1->str() != ":" && tok1->str() != ",") break; - if(tok1->str() == "class") + if (tok1->str() == "class") { reallocError(tok->tokAt(2), tok->str()); break; @@ -279,74 +279,74 @@ void CheckExceptionSafety::realloc() void CheckExceptionSafety::deallocThrow() { - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { - if(tok->str() != "delete") + if (tok->str() != "delete") continue; // Check if this is something similar with: "delete p;" tok = tok->next(); - if(Token::simpleMatch(tok, "[ ]")) + if (Token::simpleMatch(tok, "[ ]")) tok = tok->tokAt(2); - if(!tok) + if (!tok) break; - if(!Token::Match(tok, "%var% ;")) + if (!Token::Match(tok, "%var% ;")) continue; const unsigned int varid(tok->varId()); - if(varid == 0) + if (varid == 0) continue; // is this variable a global variable? { bool globalVar = false; - for(const Token *tok2 = _tokenizer->tokens(); tok2; tok2 = tok2->next()) + for (const Token *tok2 = _tokenizer->tokens(); tok2; tok2 = tok2->next()) { - if(tok->varId() == varid) + if (tok->varId() == varid) { globalVar = true; break; } - if(tok2->str() == "class") + if (tok2->str() == "class") { - while(tok2 && tok2->str() != ";" && tok2->str() != "{") + while (tok2 && tok2->str() != ";" && tok2->str() != "{") tok2 = tok2->next(); tok2 = tok2 ? tok2->next() : 0; - if(!tok2) + if (!tok2) break; } - if(tok2->str() == "{") + if (tok2->str() == "{") { tok2 = tok2->link(); - if(!tok2) + if (!tok2) break; } } - if(!globalVar) + if (!globalVar) continue; } // is there a throw after the deallocation? unsigned int indentlevel = 0; const Token *ThrowToken = 0; - for(const Token *tok2 = tok; tok2; tok2 = tok2->next()) + for (const Token *tok2 = tok; tok2; tok2 = tok2->next()) { - if(tok2->str() == "{") + if (tok2->str() == "{") ++indentlevel; - else if(tok2->str() == "}") + else if (tok2->str() == "}") { - if(indentlevel == 0) + if (indentlevel == 0) break; --indentlevel; } - if(tok2->str() == "throw") + if (tok2->str() == "throw") ThrowToken = tok2; - else if(Token::Match(tok2, "%varid% =", varid)) + else if (Token::Match(tok2, "%varid% =", varid)) { - if(ThrowToken) + if (ThrowToken) deallocThrowError(ThrowToken, tok->str()); break; } diff --git a/lib/checkexceptionsafety.h b/lib/checkexceptionsafety.h index 11fb93e72..dec5fcb42 100644 --- a/lib/checkexceptionsafety.h +++ b/lib/checkexceptionsafety.h @@ -48,7 +48,7 @@ public: /** This constructor is used when running checks. */ CheckExceptionSafety(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) - : Check(tokenizer, settings, errorLogger) + : Check(tokenizer, settings, errorLogger) { } void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) diff --git a/lib/checkheaders.cpp b/lib/checkheaders.cpp index b51438249..36c0cabbf 100644 --- a/lib/checkheaders.cpp +++ b/lib/checkheaders.cpp @@ -50,13 +50,13 @@ CheckHeaders::~CheckHeaders() void CheckHeaders::warningHeaderWithImplementation() { - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { // Only interested in included file - if(tok->fileIndex() == 0) + if (tok->fileIndex() == 0) continue; - if(Token::simpleMatch(tok, ") {")) + if (Token::simpleMatch(tok, ") {")) { std::ostringstream ostr; ostr << _tokenizer->fileLine(tok) << ": Found implementation in header"; @@ -69,7 +69,7 @@ void CheckHeaders::warningHeaderWithImplementation() // _errorLogger->reportErr(empty, "severity", ostr.str(), "id"); // Goto next file.. unsigned int fileindex = tok->fileIndex(); - while(tok->next() && tok->fileIndex() == fileindex) + while (tok->next() && tok->fileIndex() == fileindex) tok = tok->next(); } } @@ -90,21 +90,21 @@ void CheckHeaders::warningHeaderWithImplementation() void CheckHeaders::warningIncludeHeader() { // Including.. - for(const Token *includetok = _tokenizer->tokens(); includetok; includetok = includetok->next()) + for (const Token *includetok = _tokenizer->tokens(); includetok; includetok = includetok->next()) { - if(includetok->str() != "#include") + if (includetok->str() != "#include") continue; // Get fileindex of included file.. unsigned int hfile = 0; const std::string includefile = includetok->strAt(1); - while(hfile < _tokenizer->getFiles()->size()) + while (hfile < _tokenizer->getFiles()->size()) { - if(getFileLister()->sameFileName(_tokenizer->getFiles()->at(hfile), includefile)) + if (getFileLister()->sameFileName(_tokenizer->getFiles()->at(hfile), includefile)) break; ++hfile; } - if(hfile == _tokenizer->getFiles()->size()) + if (hfile == _tokenizer->getFiles()->size()) continue; // This header is needed if: @@ -119,48 +119,48 @@ void CheckHeaders::warningIncludeHeader() // Extract classes and names in the header.. int indentlevel = 0; - for(const Token *tok1 = _tokenizer->tokens(); tok1; tok1 = tok1->next()) + for (const Token *tok1 = _tokenizer->tokens(); tok1; tok1 = tok1->next()) { - if(tok1->fileIndex() != hfile) + if (tok1->fileIndex() != hfile) continue; // I'm only interested in stuff that is declared at indentlevel 0 - if(tok1->str() == "{") + if (tok1->str() == "{") ++indentlevel; - else if(tok1->str() == "}") + else if (tok1->str() == "}") --indentlevel; - if(indentlevel != 0) + if (indentlevel != 0) continue; // Class or namespace declaration.. // -------------------------------------- - if(Token::Match(tok1, "class %var% {") || Token::Match(tok1, "class %var% :") || Token::Match(tok1, "namespace %var% {")) + if (Token::Match(tok1, "class %var% {") || Token::Match(tok1, "class %var% :") || Token::Match(tok1, "namespace %var% {")) classlist.push_back(tok1->strAt(1)); // Variable declaration.. // -------------------------------------- - else if(Token::Match(tok1, "%type% %var% ;") || Token::Match(tok1, "%type% %var% [")) + else if (Token::Match(tok1, "%type% %var% ;") || Token::Match(tok1, "%type% %var% [")) namelist.push_back(tok1->strAt(1)); - else if(Token::Match(tok1, "%type% * %var% ;") || Token::Match(tok1, "%type% * %var% [")) + else if (Token::Match(tok1, "%type% * %var% ;") || Token::Match(tok1, "%type% * %var% [")) namelist.push_back(tok1->strAt(2)); - else if(Token::Match(tok1, "const %type% %var% =") || Token::Match(tok1, "const %type% %var% [")) + else if (Token::Match(tok1, "const %type% %var% =") || Token::Match(tok1, "const %type% %var% [")) namelist.push_back(tok1->strAt(2)); - else if(Token::Match(tok1, "const %type% * %var% =") || Token::Match(tok1, "const %type% * %var% [")) + else if (Token::Match(tok1, "const %type% * %var% =") || Token::Match(tok1, "const %type% * %var% [")) namelist.push_back(tok1->strAt(3)); // enum.. // -------------------------------------- - else if(tok1->str() == "enum") + else if (tok1->str() == "enum") { tok1 = tok1->next(); - while(! Token::Match(tok1, "; %any%")) + while (! Token::Match(tok1, "; %any%")) { - if(tok1->isName()) + if (tok1->isName()) namelist.push_back(tok1->str()); tok1 = tok1->next(); } @@ -168,39 +168,39 @@ void CheckHeaders::warningIncludeHeader() // function.. // -------------------------------------- - else if(Token::Match(tok1, "%type% %var% (")) + else if (Token::Match(tok1, "%type% %var% (")) namelist.push_back(tok1->strAt(1)); - else if(Token::Match(tok1, "%type% * %var% (")) + else if (Token::Match(tok1, "%type% * %var% (")) namelist.push_back(tok1->strAt(2)); - else if(Token::Match(tok1, "const %type% %var% (")) + else if (Token::Match(tok1, "const %type% %var% (")) namelist.push_back(tok1->strAt(2)); - else if(Token::Match(tok1, "const %type% * %var% (")) + else if (Token::Match(tok1, "const %type% * %var% (")) namelist.push_back(tok1->strAt(3)); // typedef.. // -------------------------------------- - else if(tok1->str() == "typedef") + else if (tok1->str() == "typedef") { - if(tok1->strAt(1) == "enum") + if (tok1->strAt(1) == "enum") continue; int parlevel = 0; - while(tok1->next()) + while (tok1->next()) { - if(Token::Match(tok1, "[({]")) + if (Token::Match(tok1, "[({]")) ++parlevel; - else if(Token::Match(tok1, "[)}]")) + else if (Token::Match(tok1, "[)}]")) --parlevel; - else if(parlevel == 0) + else if (parlevel == 0) { - if(tok1->str() == ";") + if (tok1->str() == ";") break; - if(Token::Match(tok1, "%var% ;")) + if (Token::Match(tok1, "%var% ;")) namelist.push_back(tok1->str()); } @@ -213,45 +213,45 @@ void CheckHeaders::warningIncludeHeader() // Check if the extracted names are used... bool Needed = false; bool NeedDeclaration = false; - for(const Token *tok1 = _tokenizer->tokens(); tok1; tok1 = tok1->next()) + for (const Token *tok1 = _tokenizer->tokens(); tok1; tok1 = tok1->next()) { - if(tok1->fileIndex() != includetok->fileIndex()) + if (tok1->fileIndex() != includetok->fileIndex()) continue; - if(Token::Match(tok1, ": %var% {") || Token::Match(tok1, ": %type% %var% {")) + if (Token::Match(tok1, ": %var% {") || Token::Match(tok1, ": %type% %var% {")) { const std::string classname = tok1->strAt(((tok1->strAt(2) != "{")) ? 2 : 1); - if(std::find(classlist.begin(), classlist.end(), classname) != classlist.end()) + if (std::find(classlist.begin(), classlist.end(), classname) != classlist.end()) { Needed = true; break; } } - if(! tok1->isName()) + if (! tok1->isName()) continue; - if(std::find(namelist.begin(), namelist.end(), tok1->str().c_str()) != namelist.end()) + if (std::find(namelist.begin(), namelist.end(), tok1->str().c_str()) != namelist.end()) { Needed = true; break; } - if(! NeedDeclaration) + if (! NeedDeclaration) NeedDeclaration = (std::find(classlist.begin(), classlist.end(), tok1->str().c_str()) != classlist.end()); } // Not a header file? - if(includetok->fileIndex() == 0) + if (includetok->fileIndex() == 0) Needed |= NeedDeclaration; // Not needed! - if(!Needed) + if (!Needed) { std::ostringstream ostr; ostr << _tokenizer->fileLine(includetok) << ": The included header '" << includefile << "' is not needed"; - if(NeedDeclaration) + if (NeedDeclaration) ostr << " (but a forward declaration is needed)"; // TODO, this check is currently not used, but if it is some day diff --git a/lib/checkmemoryleak.cpp b/lib/checkmemoryleak.cpp index 7eb367a59..93b07f9e1 100644 --- a/lib/checkmemoryleak.cpp +++ b/lib/checkmemoryleak.cpp @@ -70,12 +70,12 @@ static int call_func_white_list_compare(const void *a, const void *b) bool CheckMemoryLeak::isclass(const Tokenizer *_tokenizer, const Token *tok) const { - if(tok->isStandardType()) + if (tok->isStandardType()) return false; std::ostringstream pattern; pattern << "struct " << tok->str(); - if(Token::findmatch(_tokenizer->tokens(), pattern.str().c_str())) + if (Token::findmatch(_tokenizer->tokens(), pattern.str().c_str())) return false; return true; @@ -89,14 +89,14 @@ CheckMemoryLeak::AllocType CheckMemoryLeak::getAllocationType(const Token *tok2, // * var = new char[10]; // * var = strdup("hello"); // * var = strndup("hello", 3); - if(tok2 && tok2->str() == "(") + if (tok2 && tok2->str() == "(") { tok2 = tok2->link(); tok2 = tok2 ? tok2->next() : NULL; } - if(! tok2) + if (! tok2) return No; - if(! tok2->isName()) + if (! tok2->isName()) return No; // Does tok2 point on "malloc", "strdup" or "kmalloc".. @@ -109,14 +109,14 @@ CheckMemoryLeak::AllocType CheckMemoryLeak::getAllocationType(const Token *tok2, "kcalloc", 0 }; - for(unsigned int i = 0; mallocfunc[i]; i++) + for (unsigned int i = 0; mallocfunc[i]; i++) { - if(tok2->str() == mallocfunc[i]) + if (tok2->str() == mallocfunc[i]) return Malloc; } // Using realloc.. - if(varid && Token::Match(tok2, "realloc ( %any% ,") && tok2->tokAt(2)->varId() != varid) + if (varid && Token::Match(tok2, "realloc ( %any% ,") && tok2->tokAt(2)->varId() != varid) return Malloc; // Does tok2 point on "g_malloc", "g_strdup", .. @@ -132,37 +132,37 @@ CheckMemoryLeak::AllocType CheckMemoryLeak::getAllocationType(const Token *tok2, "g_strndup", 0 }; - for(unsigned int i = 0; gmallocfunc[i]; i++) + for (unsigned int i = 0; gmallocfunc[i]; i++) { - if(tok2->str() == gmallocfunc[i]) + if (tok2->str() == gmallocfunc[i]) return gMalloc; } - if(Token::Match(tok2, "new %type% [;()]") || - Token::Match(tok2, "new ( std :: nothrow ) %type% [;()]") || - Token::Match(tok2, "new ( nothrow ) %type% [;()]")) + if (Token::Match(tok2, "new %type% [;()]") || + Token::Match(tok2, "new ( std :: nothrow ) %type% [;()]") || + Token::Match(tok2, "new ( nothrow ) %type% [;()]")) return New; - if(Token::Match(tok2, "new %type% [") || - Token::Match(tok2, "new ( std :: nothrow ) %type% [") || - Token::Match(tok2, "new ( nothrow ) %type% [")) + if (Token::Match(tok2, "new %type% [") || + Token::Match(tok2, "new ( std :: nothrow ) %type% [") || + Token::Match(tok2, "new ( nothrow ) %type% [")) return NewArray; - if(Token::Match(tok2, "fopen|tmpfile (")) + if (Token::Match(tok2, "fopen|tmpfile (")) return File; - if(Token::Match(tok2, "open|openat|creat|mkstemp|mkostemp (")) + if (Token::Match(tok2, "open|openat|creat|mkstemp|mkostemp (")) { // is there a user function with this name? - if(tokenizer && Token::findmatch(tokenizer->tokens(), ("%type% *|&| " + tok2->str()).c_str())) + if (tokenizer && Token::findmatch(tokenizer->tokens(), ("%type% *|&| " + tok2->str()).c_str())) return No; return Fd; } - if(Token::simpleMatch(tok2, "popen (")) + if (Token::simpleMatch(tok2, "popen (")) return Pipe; - if(Token::Match(tok2, "opendir|fdopendir (")) + if (Token::Match(tok2, "opendir|fdopendir (")) return Dir; return No; @@ -175,22 +175,22 @@ CheckMemoryLeak::AllocType CheckMemoryLeak::getReallocationType(const Token *tok { // What we may have... // * var = (char *)realloc(..; - if(tok2 && tok2->str() == "(") + if (tok2 && tok2->str() == "(") { tok2 = tok2->link(); tok2 = tok2 ? tok2->next() : NULL; } - if(! tok2) + if (! tok2) return No; - if(! Token::Match(tok2, "%var% ( %varid% [,)]", varid)) + if (! Token::Match(tok2, "%var% ( %varid% [,)]", varid)) return No; - if(tok2->str() == "realloc") + if (tok2->str() == "realloc") return Malloc; // GTK memory reallocation.. - if(Token::Match(tok2, "g_realloc|g_try_realloc|g_renew|g_try_renew")) + if (Token::Match(tok2, "g_realloc|g_try_realloc|g_renew|g_try_renew")) return gMalloc; return No; @@ -199,36 +199,36 @@ CheckMemoryLeak::AllocType CheckMemoryLeak::getReallocationType(const Token *tok CheckMemoryLeak::AllocType CheckMemoryLeak::getDeallocationType(const Token *tok, unsigned int varid) const { - if(Token::Match(tok, "delete %varid% ;", varid)) + if (Token::Match(tok, "delete %varid% ;", varid)) return New; - if(Token::Match(tok, "delete [ ] %varid% ;", varid)) + if (Token::Match(tok, "delete [ ] %varid% ;", varid)) return NewArray; - if(Token::Match(tok, "delete ( %varid% ) ;", varid)) + if (Token::Match(tok, "delete ( %varid% ) ;", varid)) return New; - if(Token::Match(tok, "delete [ ] ( %varid% ) ;", varid)) + if (Token::Match(tok, "delete [ ] ( %varid% ) ;", varid)) return NewArray; - if(Token::Match(tok, "free ( %varid% ) ;", varid) || - Token::Match(tok, "kfree ( %varid% ) ;", varid)) + if (Token::Match(tok, "free ( %varid% ) ;", varid) || + Token::Match(tok, "kfree ( %varid% ) ;", varid)) return Malloc; - if(Token::Match(tok, "g_free ( %varid% ) ;", varid)) + if (Token::Match(tok, "g_free ( %varid% ) ;", varid)) return gMalloc; - if(Token::Match(tok, "fclose ( %varid% )", varid) || - Token::Match(tok, "fcloseall ( )")) + if (Token::Match(tok, "fclose ( %varid% )", varid) || + Token::Match(tok, "fcloseall ( )")) return File; - if(Token::Match(tok, "close ( %varid% )", varid)) + if (Token::Match(tok, "close ( %varid% )", varid)) return Fd; - if(Token::Match(tok, "pclose ( %varid% )", varid)) + if (Token::Match(tok, "pclose ( %varid% )", varid)) return Pipe; - if(Token::Match(tok, "closedir ( %varid% )", varid)) + if (Token::Match(tok, "closedir ( %varid% )", varid)) return Dir; return No; @@ -238,45 +238,45 @@ CheckMemoryLeak::AllocType CheckMemoryLeak::getDeallocationType(const Token *tok { int i = 0; std::string names; - while(varnames[i]) + while (varnames[i]) { - if(i > 0) + if (i > 0) names += " . "; names += varnames[i]; i++; } - if(Token::simpleMatch(tok, std::string("delete " + names + " ;").c_str())) + if (Token::simpleMatch(tok, std::string("delete " + names + " ;").c_str())) return New; - if(Token::simpleMatch(tok, std::string("delete [ ] " + names + " ;").c_str())) + if (Token::simpleMatch(tok, std::string("delete [ ] " + names + " ;").c_str())) return NewArray; - if(Token::simpleMatch(tok, std::string("delete ( " + names + " ) ;").c_str())) + if (Token::simpleMatch(tok, std::string("delete ( " + names + " ) ;").c_str())) return New; - if(Token::simpleMatch(tok, std::string("delete [ ] ( " + names + " ) ;").c_str())) + if (Token::simpleMatch(tok, std::string("delete [ ] ( " + names + " ) ;").c_str())) return NewArray; - if(Token::simpleMatch(tok, std::string("free ( " + names + " ) ;").c_str()) || - Token::simpleMatch(tok, std::string("kfree ( " + names + " ) ;").c_str())) + if (Token::simpleMatch(tok, std::string("free ( " + names + " ) ;").c_str()) || + Token::simpleMatch(tok, std::string("kfree ( " + names + " ) ;").c_str())) return Malloc; - if(Token::simpleMatch(tok, std::string("g_free ( " + names + " ) ;").c_str())) + if (Token::simpleMatch(tok, std::string("g_free ( " + names + " ) ;").c_str())) return gMalloc; - if(Token::simpleMatch(tok, std::string("fclose ( " + names + " )").c_str()) || - Token::simpleMatch(tok, "fcloseall ( )")) + if (Token::simpleMatch(tok, std::string("fclose ( " + names + " )").c_str()) || + Token::simpleMatch(tok, "fcloseall ( )")) return File; - if(Token::simpleMatch(tok, std::string("close ( " + names + " )").c_str())) + if (Token::simpleMatch(tok, std::string("close ( " + names + " )").c_str())) return Fd; - if(Token::simpleMatch(tok, std::string("pclose ( " + names + " )").c_str())) + if (Token::simpleMatch(tok, std::string("pclose ( " + names + " )").c_str())) return Pipe; - if(Token::simpleMatch(tok, std::string("closedir ( " + names + " )").c_str())) + if (Token::simpleMatch(tok, std::string("closedir ( " + names + " )").c_str())) return Dir; return No; @@ -288,10 +288,10 @@ CheckMemoryLeak::AllocType CheckMemoryLeak::getDeallocationType(const Token *tok void CheckMemoryLeak::memoryLeak(const Token *tok, const std::string &varname, AllocType alloctype, bool all) { - if(alloctype == CheckMemoryLeak::File || - alloctype == CheckMemoryLeak::Pipe || - alloctype == CheckMemoryLeak::Fd || - alloctype == CheckMemoryLeak::Dir) + if (alloctype == CheckMemoryLeak::File || + alloctype == CheckMemoryLeak::Pipe || + alloctype == CheckMemoryLeak::Fd || + alloctype == CheckMemoryLeak::Dir) resourceLeakError(tok, varname.c_str(), all); else memleakError(tok, varname.c_str(), all); @@ -303,7 +303,7 @@ void CheckMemoryLeak::reportErr(const Token *tok, Severity::e severity, const st { std::list callstack; - if(tok) + if (tok) callstack.push_back(tok); reportErr(callstack, severity, id, msg); @@ -313,7 +313,7 @@ void CheckMemoryLeak::reportErr(const std::list &callstack, Sever { std::list locations; - for(std::list::const_iterator it = callstack.begin(); it != callstack.end(); ++it) + for (std::list::const_iterator it = callstack.begin(); it != callstack.end(); ++it) { const Token * const tok = *it; @@ -326,7 +326,7 @@ void CheckMemoryLeak::reportErr(const std::list &callstack, Sever const ErrorLogger::ErrorMessage errmsg(locations, Severity::stringify(severity), msg, id); - if(errorLogger) + if (errorLogger) errorLogger->reportErr(errmsg); else std::cout << errmsg.toXML() << std::endl; @@ -340,7 +340,7 @@ void CheckMemoryLeak::memleakError(const Token *tok, const std::string &varname, void CheckMemoryLeak::resourceLeakError(const Token *tok, const std::string &varname, bool all) { std::string errmsg("Resource leak"); - if(!varname.empty()) + if (!varname.empty()) errmsg += ": " + varname; reportErr(tok, all ? Severity::possibleError : Severity::error, "resourceLeak", errmsg); } @@ -369,21 +369,21 @@ CheckMemoryLeak::AllocType CheckMemoryLeak::functionReturnType(const Token *tok) { // Locate the start of the function.. unsigned int parlevel = 0; - while(tok) + while (tok) { - if(tok->str() == "{" || tok->str() == "}") + if (tok->str() == "{" || tok->str() == "}") return No; - if(tok->str() == "(") + if (tok->str() == "(") { - if(parlevel != 0) + if (parlevel != 0) return No; ++parlevel; } - else if(tok->str() == ")") + else if (tok->str() == ")") { - if(parlevel != 1) + if (parlevel != 1) return No; break; } @@ -392,40 +392,40 @@ CheckMemoryLeak::AllocType CheckMemoryLeak::functionReturnType(const Token *tok) } // Is this the start of a function? - if(!Token::Match(tok, ") const| {")) + if (!Token::Match(tok, ") const| {")) return No; - while(tok->str() != "{") + while (tok->str() != "{") tok = tok->next(); tok = tok ? tok->next() : 0; // Inspect the statements.. unsigned int varid = 0; AllocType allocType = No; - while(tok) + while (tok) { // variable declaration.. - if(Token::Match(tok, "%type% * %var% ;")) + if (Token::Match(tok, "%type% * %var% ;")) { tok = tok->tokAt(4); continue; } - if(varid == 0 && tok->varId() && Token::Match(tok, "%var% =")) + if (varid == 0 && tok->varId() && Token::Match(tok, "%var% =")) { varid = tok->varId(); allocType = getAllocationType(tok->tokAt(2), varid); - if(allocType == No) + if (allocType == No) return No; - while(tok && tok->str() != ";") + while (tok && tok->str() != ";") tok = tok->next(); tok = tok ? tok->next() : 0; continue; } - if(tok->str() == "return") + if (tok->str() == "return") { - if(varid > 0 && Token::Match(tok->next(), "%varid% ;", varid)) + if (varid > 0 && Token::Match(tok->next(), "%varid% ;", varid)) return allocType; return getAllocationType(tok->next(), varid); @@ -449,31 +449,31 @@ void CheckMemoryLeakInFunction::parse_noreturn() noreturn.insert("errx"); noreturn.insert("verrx"); - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { - if(tok->str() == "{") + if (tok->str() == "{") tok = tok->link(); - if(tok->str() == "(") + if (tok->str() == "(") { const std::string function_name((tok->previous() && tok->previous()->isName()) ? tok->strAt(-1).c_str() : ""); tok = tok->link(); - if(!function_name.empty() && Token::simpleMatch(tok, ") {")) + if (!function_name.empty() && Token::simpleMatch(tok, ") {")) { // parse this function to check if it contains an "exit" call.. unsigned int indentlevel = 0; - for(const Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) + for (const Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) { - if(tok2->str() == "{") + if (tok2->str() == "{") ++indentlevel; - else if(tok2->str() == "}") + else if (tok2->str() == "}") { - if(indentlevel <= 1) + if (indentlevel <= 1) break; --indentlevel; } - if(Token::Match(tok2, "[;{}] exit (")) + if (Token::Match(tok2, "[;{}] exit (")) { noreturn.insert(function_name); break; @@ -501,26 +501,26 @@ bool CheckMemoryLeakInFunction::notvar(const Token *tok, unsigned int varid, boo static int countParameters(const Token *tok) { - if(!Token::Match(tok, "%var% (")) + if (!Token::Match(tok, "%var% (")) return -1; - if(Token::Match(tok->tokAt(2), "void| )")) + if (Token::Match(tok->tokAt(2), "void| )")) return 0; int numpar = 1; int parlevel = 0; - for(; tok; tok = tok->next()) + for (; tok; tok = tok->next()) { - if(tok->str() == "(") + if (tok->str() == "(") ++parlevel; - else if(tok->str() == ")") + else if (tok->str() == ")") { - if(parlevel <= 1) + if (parlevel <= 1) return numpar; --parlevel; } - else if(parlevel == 1 && tok->str() == ",") + else if (parlevel == 1 && tok->str() == ",") ++numpar; } @@ -536,41 +536,41 @@ bool CheckMemoryLeakInFunction::test_white_list(const std::string &funcname) const char * CheckMemoryLeakInFunction::call_func(const Token *tok, std::list callstack, const unsigned int varid, AllocType &alloctype, AllocType &dealloctype, bool &all, unsigned int sz) { - if(test_white_list(tok->str())) + if (test_white_list(tok->str())) return 0; - if(noreturn.find(tok->str()) != noreturn.end()) + if (noreturn.find(tok->str()) != noreturn.end()) return "exit"; - if(varid > 0 && (getAllocationType(tok, varid) != No || getReallocationType(tok, varid) != No || getDeallocationType(tok, varid) != No)) + if (varid > 0 && (getAllocationType(tok, varid) != No || getReallocationType(tok, varid) != No || getDeallocationType(tok, varid) != No)) return 0; - if(callstack.size() > 2) + if (callstack.size() > 2) return "dealloc_"; const std::string funcname(tok->str()); - for(std::list::const_iterator it = callstack.begin(); it != callstack.end(); ++it) + for (std::list::const_iterator it = callstack.begin(); it != callstack.end(); ++it) { - if((*it) && (*it)->str() == funcname) + if ((*it) && (*it)->str() == funcname) return "recursive"; } callstack.push_back(tok); // lock/unlock.. - if(varid == 0) + if (varid == 0) { const Token *ftok = _tokenizer->getFunctionTokenByName(funcname.c_str()); - while(ftok && (ftok->str() != "{")) + while (ftok && (ftok->str() != "{")) ftok = ftok->next(); - if(!ftok) + if (!ftok) return 0; Token *func = getcode(ftok->tokAt(1), callstack, 0, alloctype, dealloctype, false, all, 1); simplifycode(func, all); const char *ret = 0; - if(Token::simpleMatch(func, "; alloc ; }")) + if (Token::simpleMatch(func, "; alloc ; }")) ret = "alloc"; - else if(Token::simpleMatch(func, "; dealloc ; }")) + else if (Token::simpleMatch(func, "; dealloc ; }")) ret = "dealloc"; Tokenizer::deleteTokens(func); return ret; @@ -580,13 +580,13 @@ const char * CheckMemoryLeakInFunction::call_func(const Token *tok, std::listgetFunctionTokenByName(funcname.c_str()); AllocType a = functionReturnType(ftok); - if(a != No) + if (a != No) return "alloc"; } // how many parameters is there in the function call? int numpar = countParameters(tok); - if(numpar <= 0) + if (numpar <= 0) return "callfunc"; int par = 1; @@ -594,63 +594,63 @@ const char * CheckMemoryLeakInFunction::call_func(const Token *tok, std::listprevious()->str() == "."); - for(; tok; tok = tok->next()) + for (; tok; tok = tok->next()) { - if(tok->str() == "(") + if (tok->str() == "(") ++parlevel; - else if(tok->str() == ")") + else if (tok->str() == ")") { --parlevel; - if(parlevel < 1) + if (parlevel < 1) { return (_settings && _settings->_showAll) ? 0 : "callfunc"; } } - if(parlevel == 1) + if (parlevel == 1) { - if(tok->str() == ",") + if (tok->str() == ",") ++par; - if(varid > 0 && Token::Match(tok, "[,()] %varid% [,()]", varid)) + if (varid > 0 && Token::Match(tok, "[,()] %varid% [,()]", varid)) { - if(dot) + if (dot) return "use"; const Token *ftok = _tokenizer->getFunctionTokenByName(funcname.c_str()); - if(!ftok) + if (!ftok) return "use"; // how many parameters does the function want? - if(numpar != countParameters(ftok)) + if (numpar != countParameters(ftok)) return "recursive"; const char *parname = Tokenizer::getParameterName(ftok, par); - if(! parname) + if (! parname) return "recursive"; unsigned int parameterVarid = 0; { const Token *partok = Token::findmatch(ftok, parname); - if(partok) + if (partok) parameterVarid = partok->varId(); } - if(parameterVarid == 0) + if (parameterVarid == 0) return "recursive"; // Check if the function deallocates the variable.. - while(ftok && (ftok->str() != "{")) + while (ftok && (ftok->str() != "{")) ftok = ftok->next(); Token *func = getcode(ftok->tokAt(1), callstack, parameterVarid, alloctype, dealloctype, false, all, sz); //simplifycode(func, all); const Token *func_ = func; - while(func_ && func_->str() == ";") + while (func_ && func_->str() == ";") func_ = func_->next(); const char *ret = 0; /** @todo handle "goto" */ - if(Token::findmatch(func_, "dealloc")) + if (Token::findmatch(func_, "dealloc")) ret = "dealloc"; - else if(Token::findmatch(func_, "use")) + else if (Token::findmatch(func_, "use")) ret = "use"; - else if(Token::findmatch(func_, "&use")) + else if (Token::findmatch(func_, "&use")) ret = "&use"; Tokenizer::deleteTokens(func); @@ -691,38 +691,38 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::listnext()) + for (; tok; tok = tok->next()) { - if(tok->str() == "{") + if (tok->str() == "{") { addtoken("{"); ++indentlevel; } - else if(tok->str() == "}") + else if (tok->str() == "}") { addtoken("}"); - if(indentlevel <= 0) + if (indentlevel <= 0) break; --indentlevel; } - if(tok->str() == "(") + if (tok->str() == "(") ++parlevel; - else if(tok->str() == ")") + else if (tok->str() == ")") --parlevel; isloop &= (parlevel > 0); - if(parlevel == 0 && tok->str() == ";") + if (parlevel == 0 && tok->str() == ";") addtoken(";"); - if(varid == 0) + if (varid == 0) { - if(!callstack.empty() && Token::Match(tok, "[;{}] __cppcheck_lock|__cppcheck_unlock ( ) ;")) + if (!callstack.empty() && Token::Match(tok, "[;{}] __cppcheck_lock|__cppcheck_unlock ( ) ;")) { // Type of leak = Resource leak alloctype = dealloctype = CheckMemoryLeak::File; - if(tok->next()->str() == "__cppcheck_lock") + if (tok->next()->str() == "__cppcheck_lock") { addtoken("alloc"); } @@ -735,7 +735,7 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::listnext()->link(); @@ -745,21 +745,21 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::listtokAt(4)->link(); continue; } - if(Token::Match(tok->previous(), "[(;{}] %varid% =", varid) || - Token::Match(tok, "asprintf ( & %varid% ,", varid)) + if (Token::Match(tok->previous(), "[(;{}] %varid% =", varid) || + Token::Match(tok, "asprintf ( & %varid% ,", varid)) { CheckMemoryLeak::AllocType alloc; - if(Token::simpleMatch(tok, "asprintf (")) + if (Token::simpleMatch(tok, "asprintf (")) { // todo: check how the return value is used. - if(!Token::Match(tok->previous(), "[;{}]")) + if (!Token::Match(tok->previous(), "[;{}]")) { Tokenizer::deleteTokens(rethead); return 0; @@ -773,17 +773,17 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::list 1 && - Token::Match(tok->tokAt(2), "malloc ( %num% )") && - (MathLib::toLongNumber(tok->strAt(4)) % sz) != 0) + if (sz > 1 && + Token::Match(tok->tokAt(2), "malloc ( %num% )") && + (MathLib::toLongNumber(tok->strAt(4)) % sz) != 0) { mismatchSizeError(tok->tokAt(4), tok->strAt(4)); } - if(alloc == CheckMemoryLeak::No) + if (alloc == CheckMemoryLeak::No) { alloc = getReallocationType(tok->tokAt(2), varid); - if(alloc != CheckMemoryLeak::No) + if (alloc != CheckMemoryLeak::No) { addtoken("realloc"); addtoken(";"); @@ -794,16 +794,16 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::listtokAt(2), "new %type% [(;]")) + if (Token::Match(tok->tokAt(2), "new %type% [(;]")) { - if(isclass(_tokenizer, tok->tokAt(3))) + if (isclass(_tokenizer, tok->tokAt(3))) { - if(_settings->_showAll) + if (_settings->_showAll) { - if(_settings->isAutoDealloc(tok->strAt(3))) + if (_settings->isAutoDealloc(tok->strAt(3))) { // This class has automatic deallocation alloc = No; @@ -820,15 +820,15 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::listtokens(), "%varid%", varid)->str(), false); @@ -838,7 +838,7 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::listprevious(), varid)) + else if (matchFunctionsThatReturnArg(tok->previous(), varid)) { addtoken("use"); } @@ -848,12 +848,12 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::listnext()) + for (const Token *tok2 = tok; tok2; tok2 = tok2->next()) { - if(tok2->str() == ";") + if (tok2->str() == ";") break; - if(Token::Match(tok2, "[=+] %varid%", varid)) + if (Token::Match(tok2, "[=+] %varid%", varid)) { rhs = true; break; @@ -864,22 +864,22 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::listprevious(), "[;{})=] %var%") || - Token::Match(tok->previous(), "|= %var%")) + if (Token::Match(tok->previous(), "[;{})=] %var%") || + Token::Match(tok->previous(), "|= %var%")) { AllocType dealloc = getDeallocationType(tok, varid); - if(dealloc != No && tok->str() == "fcloseall" && alloctype != dealloc) + if (dealloc != No && tok->str() == "fcloseall" && alloctype != dealloc) dealloc = No; - else if(dealloc != No) + else if (dealloc != No) { addtoken("dealloc"); - if(dealloctype != No && dealloctype != dealloc) + if (dealloctype != No && dealloctype != dealloc) dealloc = Many; - if(dealloc != Many && alloctype != No && alloctype != Many && alloctype != dealloc) + if (dealloc != Many && alloctype != No && alloctype != Many && alloctype != dealloc) { callstack.push_back(tok); mismatchAllocDealloc(callstack, Token::findmatch(_tokenizer->tokens(), "%varid%", varid)->str(), false); @@ -891,19 +891,19 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::liststr() == "if") + if (tok->str() == "if") { - if(alloctype == Fd) + if (alloctype == Fd) { - if(Token::Match(tok, "if ( 0 <= %varid% )", varid) || - Token::Match(tok, "if ( %varid% != -1 )", varid)) + if (Token::Match(tok, "if ( 0 <= %varid% )", varid) || + Token::Match(tok, "if ( %varid% != -1 )", varid)) { addtoken("if(var)"); tok = tok->next()->link(); continue; } - else if(Token::Match(tok, "if ( %varid% == -1 )", varid) || - Token::Match(tok, "if ( %varid% < 0 )", varid)) + else if (Token::Match(tok, "if ( %varid% == -1 )", varid) || + Token::Match(tok, "if ( %varid% < 0 )", varid)) { addtoken("if(!var)"); tok = tok->next()->link(); @@ -911,14 +911,14 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::listnext()->link(); } - else if(Token::simpleMatch(tok, "if (") && notvar(tok->tokAt(2), varid, true)) + else if (Token::simpleMatch(tok, "if (") && notvar(tok->tokAt(2), varid, true)) { addtoken("if(!var)"); } @@ -927,46 +927,46 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::listnext()) + for (const Token *tok2 = tok; tok2; tok2 = tok2->next()) { - if(tok2->str() == "(") + if (tok2->str() == "(") ++parlevel; - if(tok2->str() == ")") + if (tok2->str() == ")") { --parlevel; - if(parlevel <= 0) + if (parlevel <= 0) break; } - if(Token::Match(tok2, "close|pclose|fclose|closedir ( %varid% )", varid)) + if (Token::Match(tok2, "close|pclose|fclose|closedir ( %varid% )", varid)) { addtoken("dealloc"); addtoken(";"); dep = true; break; } - if(Token::Match(tok2, ". %varid% !!.", varid)) + if (Token::Match(tok2, ". %varid% !!.", varid)) { dep = true; break; } - if(alloctype == Fd && Token::Match(tok2, "%varid% !=|>=", varid)) + if (alloctype == Fd && Token::Match(tok2, "%varid% !=|>=", varid)) { dep = true; } - if(parlevel > 0 && Token::Match(tok2, "! %varid%", varid)) + if (parlevel > 0 && Token::Match(tok2, "! %varid%", varid)) { dep = true; break; } } - if(Token::Match(tok, "if ( ! %varid% &&", varid)) + if (Token::Match(tok, "if ( ! %varid% &&", varid)) { addtoken("if(!var)"); } - else if(tok->next() && - tok->next()->link() && - Token::Match(tok->next()->link()->tokAt(-3), "&& ! %varid%", varid)) + else if (tok->next() && + tok->next()->link() && + Token::Match(tok->next()->link()->tokAt(-3), "&& ! %varid%", varid)) { addtoken("if(!var)"); } @@ -980,47 +980,47 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::liststr() == "else") || (tok->str() == "switch")) + if ((tok->str() == "else") || (tok->str() == "switch")) { addtoken(tok->str().c_str()); } - else if((tok->str() == "case")) + else if ((tok->str() == "case")) { addtoken("case"); addtoken(";"); } - else if((tok->str() == "default")) + else if ((tok->str() == "default")) { addtoken("default"); addtoken(";"); } // Loops.. - else if((tok->str() == "for") || (tok->str() == "while")) + else if ((tok->str() == "for") || (tok->str() == "while")) { isloop = true; - if(Token::simpleMatch(tok, "while ( true )") || - Token::simpleMatch(tok, "for ( ; ; )")) + if (Token::simpleMatch(tok, "while ( true )") || + Token::simpleMatch(tok, "for ( ; ; )")) { addtoken("while1"); tok = tok->next()->link(); continue; } - else if(alloctype == Fd && varid) + else if (alloctype == Fd && varid) { - if(Token::Match(tok, "while ( 0 <= %varid% )", varid) || - Token::Match(tok, "while ( %varid% != -1 )", varid)) + if (Token::Match(tok, "while ( 0 <= %varid% )", varid) || + Token::Match(tok, "while ( %varid% != -1 )", varid)) { addtoken("while(var)"); tok = tok->next()->link(); continue; } - else if(Token::Match(tok, "while ( %varid% == -1 )", varid) || - Token::Match(tok, "while ( %varid% < 0 )", varid)) + else if (Token::Match(tok, "while ( %varid% == -1 )", varid) || + Token::Match(tok, "while ( %varid% < 0 )", varid)) { addtoken("while(!var)"); tok = tok->next()->link(); @@ -1028,13 +1028,13 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::listnext()->link(); continue; } - else if(varid && Token::simpleMatch(tok, "while (") && notvar(tok->tokAt(2), varid, true)) + else if (varid && Token::simpleMatch(tok, "while (") && notvar(tok->tokAt(2), varid, true)) { addtoken("while(!var)"); tok = tok->next()->link(); @@ -1043,62 +1043,62 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::liststr() == "do")) + else if ((tok->str() == "do")) { addtoken("do"); } - if(varid > 0 && isloop && notvar(tok, varid)) + if (varid > 0 && isloop && notvar(tok, varid)) { addtoken("!var"); } // continue / break.. - if(tok->str() == "continue") + if (tok->str() == "continue") { addtoken("continue"); } - else if(tok->str() == "break") + else if (tok->str() == "break") { addtoken("break"); } - else if(tok->str() == "goto") + else if (tok->str() == "goto") { addtoken("goto"); } // Return.. - else if(tok->str() == "return") + else if (tok->str() == "return") { addtoken("return"); - if(varid == 0) + if (varid == 0) { addtoken(";"); - while(tok && tok->str() != ";") + while (tok && tok->str() != ";") tok = tok->next(); - if(!tok) + if (!tok) break; continue; } // Returning a auto_ptr of this allocated variable.. - if(Token::simpleMatch(tok->next(), "std :: auto_ptr <")) + if (Token::simpleMatch(tok->next(), "std :: auto_ptr <")) { const Token *tok2 = tok->tokAt(5); - while(tok2 && tok2->str() != ">") + while (tok2 && tok2->str() != ">") tok2 = tok2->next(); - if(Token::Match(tok2, "> ( %varid% )", varid)) + if (Token::Match(tok2, "> ( %varid% )", varid)) { addtoken("use"); tok = tok2->tokAt(3); } } - else if(varid && Token::Match(tok, "return &| %varid%", varid)) + else if (varid && Token::Match(tok, "return &| %varid%", varid)) { addtoken("use"); } - else if(varid && Token::Match(tok, "return strcpy|strncpy|memcpy ( %varid%", varid)) + else if (varid && Token::Match(tok, "return strcpy|strncpy|memcpy ( %varid%", varid)) { addtoken("use"); tok = tok->tokAt(2); @@ -1106,12 +1106,12 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::listnext(); tok2; tok2 = tok2->next()) + for (const Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) { - if(tok2->str() == ";") + if (tok2->str() == ";") break; - if(tok2->varId() == varid) + if (tok2->varId() == varid) { addtoken("use"); tok = tok2; @@ -1122,33 +1122,33 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::liststrAt(0)); // Assignment.. - if(varid) + if (varid) { - if(Token::Match(tok, "[)=] %varid% [+;)]", varid) || - Token::Match(tok, "%var% + %varid%", varid) || - Token::Match(tok, "%varid% +=|-=", varid) || - Token::Match(tok, "+=|<< %varid% ;", varid) || - Token::Match(tok, "= strcpy|strcat|memmove|memcpy ( %varid% ,", varid)) + if (Token::Match(tok, "[)=] %varid% [+;)]", varid) || + Token::Match(tok, "%var% + %varid%", varid) || + Token::Match(tok, "%varid% +=|-=", varid) || + Token::Match(tok, "+=|<< %varid% ;", varid) || + Token::Match(tok, "= strcpy|strcat|memmove|memcpy ( %varid% ,", varid)) { addtoken("use"); } - else if(Token::Match(tok->previous(), "[;{}=(,+-*/] %varid% [", varid)) + else if (Token::Match(tok->previous(), "[;{}=(,+-*/] %varid% [", varid)) { addtoken("use_"); } } // Investigate function calls.. - if(Token::Match(tok, "%var% (")) + if (Token::Match(tok, "%var% (")) { // A function call should normally be followed by ";" - if(Token::simpleMatch(tok->next()->link(), ") {")) + if (Token::simpleMatch(tok->next()->link(), ") {")) { - if(!Token::Match(tok, "if|for|while|switch")) + if (!Token::Match(tok, "if|for|while|switch")) { addtoken("exit"); addtoken(";"); @@ -1160,20 +1160,20 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::listtokAt(2); tok2; tok2 = tok2->next()) + for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) { - if(tok2->str() == "(") + if (tok2->str() == "(") ++parlevel; - else if(tok2->str() == ")") + else if (tok2->str() == ")") { --parlevel; - if(parlevel <= 0) + if (parlevel <= 0) break; } - if(tok2->varId() == varid) + if (tok2->varId() == varid) { addtoken("::use"); break; @@ -1183,7 +1183,7 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::list 0 && Token::Match(tok, "%var% ( close|fclose|pclose ( %varid% ) ) ;", varid)) + if (varid > 0 && Token::Match(tok, "%var% ( close|fclose|pclose ( %varid% ) ) ;", varid)) { addtoken("dealloc"); tok = tok->next()->link(); @@ -1191,21 +1191,21 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::listtokAt(-2), "%varid% =", varid)) + else if (str != std::string("alloc") || + Token::Match(tok->tokAt(-2), "%varid% =", varid)) { addtoken(str); } } - else if(varid > 0 && - getReallocationType(tok, varid) != No && - tok->tokAt(2)->varId() == varid) + else if (varid > 0 && + getReallocationType(tok, varid) != No && + tok->tokAt(2)->varId() == varid) { addtoken("if"); addtoken("{"); @@ -1220,20 +1220,20 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::listtokAt(tokIdx), ". %var%")) + while (Token::Match(tok->tokAt(tokIdx), ". %var%")) tokIdx += 2; - if(Token::simpleMatch(tok->tokAt(tokIdx), ") (")) + if (Token::simpleMatch(tok->tokAt(tokIdx), ") (")) { - for(const Token *tok2 = tok->tokAt(tokIdx + 2); tok2; tok2 = tok2->next()) + for (const Token *tok2 = tok->tokAt(tokIdx + 2); tok2; tok2 = tok2->next()) { - if(Token::Match(tok2, "[;{]")) + if (Token::Match(tok2, "[;{]")) break; - else if(tok2->varId() == varid) + else if (tok2->varId() == varid) { addtoken("use"); break; @@ -1243,7 +1243,7 @@ Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::list 0 && Token::Match(tok, "[=(,] & %varid% [.[,)]", varid)) + if (varid > 0 && Token::Match(tok, "[=(,] & %varid% [.[,)]", varid)) { addtoken("&use"); } @@ -1262,61 +1262,61 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok, bool &all) // Replace "throw" that is not in a try block with "return" int indentlevel = 0; int trylevel = -1; - for(Token *tok2 = tok; tok2; tok2 = tok2->next()) + for (Token *tok2 = tok; tok2; tok2 = tok2->next()) { - if(tok2->str() == "{") + if (tok2->str() == "{") ++indentlevel; - else if(tok2->str() == "}") + else if (tok2->str() == "}") { --indentlevel; - if(indentlevel <= trylevel) + if (indentlevel <= trylevel) trylevel = -1; } - else if(trylevel == -1 && tok2->str() == "try") + else if (trylevel == -1 && tok2->str() == "try") trylevel = indentlevel; - else if(trylevel == -1 && tok2->str() == "throw") + else if (trylevel == -1 && tok2->str() == "throw") tok2->str("return"); } // reduce "if callfunc {" => "if {" - for(Token *tok2 = tok; tok2; tok2 = tok2->next()) + for (Token *tok2 = tok; tok2; tok2 = tok2->next()) { - if(Token::Match(tok2, "if|ifv callfunc {")) + if (Token::Match(tok2, "if|ifv callfunc {")) tok2->deleteNext(); } // reduce the code.. bool done = false; - while(! done) + while (! done) { //tok->printOut("simplifycode loop.."); done = true; // simplify "while1" contents.. - for(Token *tok2 = tok; tok2; tok2 = tok2->next()) + for (Token *tok2 = tok; tok2; tok2 = tok2->next()) { - if(Token::simpleMatch(tok2, "while1 {")) + if (Token::simpleMatch(tok2, "while1 {")) { unsigned int indentlevel = 0; - for(Token *tok3 = tok2->tokAt(2); tok3; tok3 = tok3->next()) + for (Token *tok3 = tok2->tokAt(2); tok3; tok3 = tok3->next()) { - if(tok3->str() == "{") + if (tok3->str() == "{") ++indentlevel; - else if(tok3->str() == "}") + else if (tok3->str() == "}") { - if(indentlevel == 0) + if (indentlevel == 0) break; --indentlevel; } - while(indentlevel == 0 && Token::Match(tok3, "[{};] if|ifv|else { continue ; }")) + while (indentlevel == 0 && Token::Match(tok3, "[{};] if|ifv|else { continue ; }")) { Token::eraseTokens(tok3, tok3->tokAt(6)); - if(Token::simpleMatch(tok3->next(), "else")) + if (Token::simpleMatch(tok3->next(), "else")) tok3->deleteNext(); } } - if(Token::Match(tok2, "while1 { if { dealloc ; return ; } }")) + if (Token::Match(tok2, "while1 { if { dealloc ; return ; } }")) { tok2->str(";"); Token::eraseTokens(tok2, tok2->tokAt(4)); @@ -1325,17 +1325,17 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok, bool &all) } } - for(Token *tok2 = tok; tok2; tok2 = tok2 ? tok2->next() : NULL) + for (Token *tok2 = tok; tok2; tok2 = tok2 ? tok2->next() : NULL) { // Delete extra ";" - while(Token::Match(tok2, "[;{}] ;")) + while (Token::Match(tok2, "[;{}] ;")) { tok2->deleteNext(); done = false; } // Replace "{ }" with ";" - if(Token::simpleMatch(tok2->next(), "{ }")) + if (Token::simpleMatch(tok2->next(), "{ }")) { tok2->eraseTokens(tok2, tok2->tokAt(3)); tok2->insertToken(";"); @@ -1343,13 +1343,13 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok, bool &all) } // Delete braces around a single instruction.. - if(Token::Match(tok2->next(), "{ %var% ; }")) + if (Token::Match(tok2->next(), "{ %var% ; }")) { tok2->deleteNext(); Token::eraseTokens(tok2->tokAt(2), tok2->tokAt(4)); done = false; } - if(Token::Match(tok2->next(), "{ %var% %var% ; }")) + if (Token::Match(tok2->next(), "{ %var% %var% ; }")) { tok2->deleteNext(); Token::eraseTokens(tok2->tokAt(3), tok2->tokAt(5)); @@ -1357,52 +1357,52 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok, bool &all) } // reduce "; callfunc ; %var%" - else if(Token::Match(tok2, "; callfunc ; %type%")) + else if (Token::Match(tok2, "; callfunc ; %type%")) { tok2->deleteNext(); done = false; } // Reduce "if if|callfunc" => "if" - else if(Token::Match(tok2, "if if|callfunc")) + else if (Token::Match(tok2, "if if|callfunc")) { tok2->deleteNext(); done = false; } - else if(tok2->next() && tok2->next()->str() == "if") + else if (tok2->next() && tok2->next()->str() == "if") { // Delete empty if that is not followed by an else - if(Token::Match(tok2->next(), "if ; !!else")) + if (Token::Match(tok2->next(), "if ; !!else")) { tok2->deleteNext(); done = false; } // Delete "if ; else ;" - else if(Token::simpleMatch(tok2->next(), "if ; else ;")) + else if (Token::simpleMatch(tok2->next(), "if ; else ;")) { Token::eraseTokens(tok2, tok2->tokAt(4)); done = false; } // Reduce "if X ; else X ;" => "X ;" - else if(Token::Match(tok2->next(), "if %var% ; else %var% ;") && - std::string(tok2->strAt(2)) == std::string(tok2->strAt(5))) + else if (Token::Match(tok2->next(), "if %var% ; else %var% ;") && + std::string(tok2->strAt(2)) == std::string(tok2->strAt(5))) { Token::eraseTokens(tok2, tok2->tokAt(5)); done = false; } // Two "if alloc ;" after one another.. perhaps only one of them can be executed each time - else if(!_settings->_showAll && Token::Match(tok2, "[;{}] if alloc ; if alloc ;")) + else if (!_settings->_showAll && Token::Match(tok2, "[;{}] if alloc ; if alloc ;")) { Token::eraseTokens(tok2, tok2->tokAt(4)); done = false; } - else if(Token::Match(tok2, "; if ; else assign|use ; assign|use") || - Token::Match(tok2, "; if assign|use ; else ; assign|use")) + else if (Token::Match(tok2, "; if ; else assign|use ; assign|use") || + Token::Match(tok2, "; if assign|use ; else ; assign|use")) { Token::eraseTokens(tok2, tok2->tokAt(4)); done = false; @@ -1412,9 +1412,9 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok, bool &all) // Reduce "if assign|dealloc|use ;" that is not followed by an else.. // If "--all" has been given these are deleted // Otherwise, only the "if" will be deleted - else if(Token::Match(tok2, "[;{}] if assign|dealloc|use ; !!else")) + else if (Token::Match(tok2, "[;{}] if assign|dealloc|use ; !!else")) { - if(_settings->_showAll && tok2->tokAt(2)->str() != "assign" && !Token::simpleMatch(tok2->tokAt(2), "dealloc ; dealloc")) + if (_settings->_showAll && tok2->tokAt(2)->str() != "assign" && !Token::simpleMatch(tok2->tokAt(2), "dealloc ; dealloc")) { Token::eraseTokens(tok2, tok2->tokAt(3)); all = true; @@ -1427,14 +1427,14 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok, bool &all) } // Reduce "if return ; alloc ;" => "alloc ;" - else if(Token::Match(tok2, "[;{}] if return ; alloc|return ;")) + else if (Token::Match(tok2, "[;{}] if return ; alloc|return ;")) { Token::eraseTokens(tok2, tok2->tokAt(4)); done = false; } // "[;{}] if alloc ; else return ;" => "[;{}] alloc ;" - else if(Token::Match(tok2, "[;{}] if alloc ; else return ;")) + else if (Token::Match(tok2, "[;{}] if alloc ; else return ;")) { tok2->deleteNext(); // Remove "if" Token::eraseTokens(tok2->next(), tok2->tokAt(5)); // Remove "; else return" @@ -1442,53 +1442,53 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok, bool &all) } // Reduce "if ; else %var% ;" => "if %var% ;" - else if(Token::Match(tok2->next(), "if ; else %var% ;")) + else if (Token::Match(tok2->next(), "if ; else %var% ;")) { Token::eraseTokens(tok2->next(), tok2->tokAt(4)); done = false; } // Reduce "if ; else" => "if" - else if(Token::simpleMatch(tok2->next(), "if ; else")) + else if (Token::simpleMatch(tok2->next(), "if ; else")) { Token::eraseTokens(tok2->next(), tok2->tokAt(4)); done = false; } // Reduce "if return ; else|if return|continue ;" => "if return ;" - else if(Token::Match(tok2->next(), "if return ; else|if return|continue|break ;")) + else if (Token::Match(tok2->next(), "if return ; else|if return|continue|break ;")) { Token::eraseTokens(tok2->tokAt(3), tok2->tokAt(6)); done = false; } // Reduce "if continue|break ; else|if return ;" => "if return ;" - else if(Token::Match(tok2->next(), "if continue|break ; if|else return ;")) + else if (Token::Match(tok2->next(), "if continue|break ; if|else return ;")) { Token::eraseTokens(tok2->next(), tok2->tokAt(5)); done = false; } // Delete "if { dealloc|assign|use ; return ; }" - else if(Token::Match(tok2, "[;{}] if { dealloc|assign|use ; return ; }")) + else if (Token::Match(tok2, "[;{}] if { dealloc|assign|use ; return ; }")) { Token::eraseTokens(tok2, tok2->tokAt(8)); - if(Token::simpleMatch(tok2->next(), "else")) + if (Token::simpleMatch(tok2->next(), "else")) tok2->deleteNext(); done = false; } // Remove "if { dealloc ; callfunc ; } !!else" - else if(Token::Match(tok2->next(), "if { dealloc|assign ; callfunc ; } !!else")) + else if (Token::Match(tok2->next(), "if { dealloc|assign ; callfunc ; } !!else")) { Token::eraseTokens(tok2, tok2->tokAt(8)); done = false; } // Reducing if.. - else if(_settings->_showAll) + else if (_settings->_showAll) { - if(Token::Match(tok2, "[;{}] if { assign|dealloc|use ; return ; } !!else")) + if (Token::Match(tok2, "[;{}] if { assign|dealloc|use ; return ; } !!else")) { all = true; Token::eraseTokens(tok2, tok2->tokAt(8)); @@ -1500,14 +1500,14 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok, bool &all) } // Reduce "alloc while(!var) alloc ;" => "alloc ;" - if(Token::Match(tok2, "[;{}] alloc ; while(!var) alloc ;")) + if (Token::Match(tok2, "[;{}] alloc ; while(!var) alloc ;")) { Token::eraseTokens(tok2, tok2->tokAt(4)); done = false; } // Reduce "ifv return;" => "if return use;" - if(Token::simpleMatch(tok2, "ifv return ;")) + if (Token::simpleMatch(tok2, "ifv return ;")) { tok2->str("if"); tok2->next()->insertToken("use"); @@ -1515,14 +1515,14 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok, bool &all) } // Reduce "if(var) dealloc ;" and "if(var) use ;" that is not followed by an else.. - if(Token::Match(tok2, "[;{}] if(var) assign|dealloc|use ; !!else")) + if (Token::Match(tok2, "[;{}] if(var) assign|dealloc|use ; !!else")) { Token::eraseTokens(tok2, tok2->tokAt(2)); done = false; } // Reduce "; if(!var) alloc ; !!else" => "; dealloc ; alloc ;" - if(Token::Match(tok2, "; if(!var) alloc ; !!else")) + if (Token::Match(tok2, "; if(!var) alloc ; !!else")) { // Remove the "if(!var)" Token::eraseTokens(tok2, tok2->tokAt(2)); @@ -1535,29 +1535,29 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok, bool &all) } // Reduce "; if(!var) exit ;" => ";" - if(Token::Match(tok2, "; if(!var) exit ;")) + if (Token::Match(tok2, "; if(!var) exit ;")) { Token::eraseTokens(tok2, tok2->tokAt(3)); done = false; } // Remove "catch ;" - if(Token::simpleMatch(tok2->next(), "catch ;")) + if (Token::simpleMatch(tok2->next(), "catch ;")) { Token::eraseTokens(tok2, tok2->tokAt(3)); done = false; } // Reduce "if* ;".. - if(Token::Match(tok2->next(), "if(var)|if(!var)|ifv ;")) + if (Token::Match(tok2->next(), "if(var)|if(!var)|ifv ;")) { // Followed by else.. - if(Token::simpleMatch(tok2->tokAt(3), "else")) + if (Token::simpleMatch(tok2->tokAt(3), "else")) { tok2 = tok2->next(); - if(tok2->str() == "if(var)") + if (tok2->str() == "if(var)") tok2->str("if(!var)"); - else if(tok2->str() == "if(!var)") + else if (tok2->str() == "if(!var)") tok2->str("if(var)"); // remove the "; else" @@ -1572,21 +1572,21 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok, bool &all) } // Reduce "else ;" => ";" - if(Token::simpleMatch(tok2->next(), "else ;")) + if (Token::simpleMatch(tok2->next(), "else ;")) { Token::eraseTokens(tok2, tok2->tokAt(2)); done = false; } // Reduce "while1 ;" => "use ;" - if(Token::simpleMatch(tok2, "while1 ;")) + if (Token::simpleMatch(tok2, "while1 ;")) { tok2->str("use"); done = false; } // Reduce "while1 if break ;" => ";" - if(Token::simpleMatch(tok2, "while1 if break ;")) + if (Token::simpleMatch(tok2, "while1 if break ;")) { tok2->str(";"); Token::eraseTokens(tok2, tok2->tokAt(3)); @@ -1594,21 +1594,21 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok, bool &all) } // Delete if block: "alloc; if return use ;" - if(Token::Match(tok2, "alloc ; if return use ; !!else")) + if (Token::Match(tok2, "alloc ; if return use ; !!else")) { Token::eraseTokens(tok2, tok2->tokAt(5)); done = false; } // Reduce "alloc|dealloc|use|callfunc ; exit ;" => "; exit ;" - if(Token::Match(tok2, "[;{}] alloc|dealloc|use|callfunc ; exit ;")) + if (Token::Match(tok2, "[;{}] alloc|dealloc|use|callfunc ; exit ;")) { tok2->deleteNext(); done = false; } // Reduce "if loop ; exit ;" => "; exit ;" - if(Token::Match(tok2, "if loop ; exit ;")) + if (Token::Match(tok2, "if loop ; exit ;")) { tok2->deleteThis(); tok2->deleteThis(); @@ -1616,14 +1616,14 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok, bool &all) } // Reduce "alloc|dealloc|use ; if(var) exit ;" - if(Token::Match(tok2, "alloc|dealloc|use ; if(var) exit ;")) + if (Token::Match(tok2, "alloc|dealloc|use ; if(var) exit ;")) { tok2->deleteThis(); done = false; } // Remove "if exit ;" - if(Token::simpleMatch(tok2, "if exit ;")) + if (Token::simpleMatch(tok2, "if exit ;")) { tok2->deleteThis(); tok2->deleteThis(); @@ -1631,7 +1631,7 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok, bool &all) } // Remove the "if break|continue ;" that follows "dealloc ; alloc ;" - if(! _settings->_showAll && Token::Match(tok2, "dealloc ; alloc ; if break|continue ;")) + if (! _settings->_showAll && Token::Match(tok2, "dealloc ; alloc ; if break|continue ;")) { tok2 = tok2->tokAt(3); Token::eraseTokens(tok2, tok2->tokAt(3)); @@ -1639,7 +1639,7 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok, bool &all) } // Reduce "do { dealloc ; alloc ; } while(var) ;" => ";" - if(Token::simpleMatch(tok2->next(), "do { dealloc ; alloc ; } while(var) ;")) + if (Token::simpleMatch(tok2->next(), "do { dealloc ; alloc ; } while(var) ;")) { Token::eraseTokens(tok2, tok2->tokAt(9)); done = false; @@ -1647,7 +1647,7 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok, bool &all) // Reduce "do { alloc ; } " => "alloc ;" /** @todo If the loop "do { alloc ; }" can be executed twice, reduce it to "loop alloc ;" */ - if(Token::simpleMatch(tok2->next(), "do { alloc ; }")) + if (Token::simpleMatch(tok2->next(), "do { alloc ; }")) { Token::eraseTokens(tok2, tok2->tokAt(3)); Token::eraseTokens(tok2->tokAt(2), tok2->tokAt(4)); @@ -1655,28 +1655,28 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok, bool &all) } // Reduce "loop break ; => ";" - if(Token::Match(tok2->next(), "loop break|continue ;")) + if (Token::Match(tok2->next(), "loop break|continue ;")) { Token::eraseTokens(tok2, tok2->tokAt(3)); done = false; } // Reduce "loop|do ;" => ";" - if(Token::Match(tok2, "loop|do ;")) + if (Token::Match(tok2, "loop|do ;")) { tok2->deleteThis(); done = false; } // Reduce "loop if break ; => ";" - if(Token::Match(tok2->next(), "loop if break|continue ; !!else")) + if (Token::Match(tok2->next(), "loop if break|continue ; !!else")) { Token::eraseTokens(tok2, tok2->tokAt(4)); done = false; } // Reduce "loop { assign|dealloc|use ; alloc ; if break ; }" to "assign|dealloc|use ; alloc ;" - if(Token::Match(tok2->next(), "loop { assign|dealloc|use ; alloc ; if break|continue ; }")) + if (Token::Match(tok2->next(), "loop { assign|dealloc|use ; alloc ; if break|continue ; }")) { // erase "loop {" Token::eraseTokens(tok2, tok2->tokAt(3)); @@ -1687,7 +1687,7 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok, bool &all) } // Replace "loop { X ; break ; }" with "X ;" - if(Token::Match(tok2->next(), "loop { %var% ; break ; }")) + if (Token::Match(tok2->next(), "loop { %var% ; break ; }")) { Token::eraseTokens(tok2, tok2->tokAt(3)); Token::eraseTokens(tok2->tokAt(2), tok2->tokAt(6)); @@ -1695,9 +1695,9 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok, bool &all) } // Replace "do ; loop ;" with ";" - if(Token::Match(tok2->next(), "%any% ; loop ;")) + if (Token::Match(tok2->next(), "%any% ; loop ;")) { - if(tok2->next()->str() == "do") + if (tok2->next()->str() == "do") tok2->deleteNext(); else tok2 = tok2->next(); @@ -1706,9 +1706,9 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok, bool &all) } // Replace "do ; loop !var ;" with ";" - if(Token::Match(tok2->next(), "%any% ; loop !var ;")) + if (Token::Match(tok2->next(), "%any% ; loop !var ;")) { - if(tok2->next()->str() == "do") + if (tok2->next()->str() == "do") tok2->deleteNext(); else tok2 = tok2->next(); @@ -1717,49 +1717,49 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok, bool &all) } // Replace "loop if return ;" with "if return ;" - if(Token::simpleMatch(tok2->next(), "loop if return")) + if (Token::simpleMatch(tok2->next(), "loop if return")) { Token::eraseTokens(tok2, tok2->tokAt(2)); done = false; } // Delete if block in "alloc ; if(!var) return ;" - if(Token::Match(tok2, "alloc ; if(!var) return ;")) + if (Token::Match(tok2, "alloc ; if(!var) return ;")) { Token::eraseTokens(tok2, tok2->tokAt(4)); done = false; } // Delete if block: "alloc; if return use ;" - if(Token::Match(tok2, "alloc ; if return use ; !!else")) + if (Token::Match(tok2, "alloc ; if return use ; !!else")) { Token::eraseTokens(tok2, tok2->tokAt(5)); done = false; } // Reduce "[;{}] return ; %var%" => "[;{}] return ;" - if(Token::Match(tok2, "[;{}] return ; %var%")) + if (Token::Match(tok2, "[;{}] return ; %var%")) { Token::eraseTokens(tok2->tokAt(2), tok2->tokAt(4)); done = false; } // Reduce "[;{}] return use ; %var%" => "[;{}] return use ;" - if(Token::Match(tok2, "[;{}] return use ; %var%")) + if (Token::Match(tok2, "[;{}] return use ; %var%")) { Token::eraseTokens(tok2->tokAt(3), tok2->tokAt(5)); done = false; } // Reduce "if(var) return use ;" => "return use ;" - if(Token::Match(tok2->next(), "if(var) return use ; !!else")) + if (Token::Match(tok2->next(), "if(var) return use ; !!else")) { Token::eraseTokens(tok2, tok2->tokAt(2)); done = false; } // Reduce "if(var) assign|dealloc|use ;" => "assign|dealloc|use ;" - if(Token::Match(tok2->next(), "if(var) assign|dealloc|use ; !!else")) + if (Token::Match(tok2->next(), "if(var) assign|dealloc|use ; !!else")) { Token::eraseTokens(tok2, tok2->tokAt(2)); done = false; @@ -1767,28 +1767,28 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok, bool &all) // malloc - realloc => alloc ; dealloc ; alloc ; // Reduce "[;{}] alloc ; dealloc ; alloc ;" => "[;{}] alloc ;" - if(Token::Match(tok2, "[;{}] alloc ; dealloc ; alloc ;")) + if (Token::Match(tok2, "[;{}] alloc ; dealloc ; alloc ;")) { Token::eraseTokens(tok2->next(), tok2->tokAt(6)); done = false; } // Delete second use in "use ; use ;" - while(Token::Match(tok2, "[;{}] use ; use ;")) + while (Token::Match(tok2, "[;{}] use ; use ;")) { Token::eraseTokens(tok2, tok2->tokAt(3)); done = false; } // Delete first part in "use ; dealloc ;" - if(Token::Match(tok2, "[;{}] use ; dealloc ;")) + if (Token::Match(tok2, "[;{}] use ; dealloc ;")) { Token::eraseTokens(tok2, tok2->tokAt(3)); done = false; } // Delete first part in "use ; return use ;" - if(Token::Match(tok2, "[;{}] use ; return use ;")) + if (Token::Match(tok2, "[;{}] use ; return use ;")) { Token::eraseTokens(tok2, tok2->tokAt(2)); done = false; @@ -1796,67 +1796,67 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok, bool &all) // Delete "callfunc ;" that is followed by "use|if|callfunc" // If the function doesn't throw exception or exit the application, then the "callfunc" is not needed - if(Token::Match(tok2, "callfunc ; use|if|callfunc")) + if (Token::Match(tok2, "callfunc ; use|if|callfunc")) { tok2->deleteThis(); done = false; } // Delete second case in "case ; case ;" - while(Token::simpleMatch(tok2, "case ; case ;")) + while (Token::simpleMatch(tok2, "case ; case ;")) { Token::eraseTokens(tok2, tok2->tokAt(3)); done = false; } // Replace switch with if (if not complicated) - if(Token::simpleMatch(tok2, "switch {")) + if (Token::simpleMatch(tok2, "switch {")) { // Right now, I just handle if there are a few case and perhaps a default. bool valid = false; bool incase = false; - for(const Token * _tok = tok2->tokAt(2); _tok; _tok = _tok->next()) + for (const Token * _tok = tok2->tokAt(2); _tok; _tok = _tok->next()) { - if(_tok->str() == "{") + if (_tok->str() == "{") break; - else if(_tok->str() == "}") + else if (_tok->str() == "}") { valid = true; break; } - else if(_tok->str() == "switch") + else if (_tok->str() == "switch") break; - else if(_tok->str() == "loop") + else if (_tok->str() == "loop") break; - else if(incase && _tok->str() == "case") + else if (incase && _tok->str() == "case") break; - else if(Token::Match(_tok, "return !!;")) + else if (Token::Match(_tok, "return !!;")) break; - if(Token::Match(_tok, "if return|break use| ;")) + if (Token::Match(_tok, "if return|break use| ;")) _tok = _tok->tokAt(2); incase |= (_tok->str() == "case"); incase &= (_tok->str() != "break" && _tok->str() != "return"); } - if(!incase && valid) + if (!incase && valid) { done = false; tok2->str(";"); Token::eraseTokens(tok2, tok2->tokAt(2)); tok2 = tok2->next(); bool first = true; - while(Token::Match(tok2, "case|default")) + while (Token::Match(tok2, "case|default")) { const bool def(tok2->str() == "default"); tok2->str(first ? "if" : "}"); - if(first) + if (first) { first = false; tok2->insertToken("{"); @@ -1865,28 +1865,28 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok, bool &all) { // Insert "else [if] { tok2->insertToken("{"); - if(! def) + if (! def) tok2->insertToken("if"); tok2->insertToken("else"); tok2 = tok2->next(); } - while(tok2) + while (tok2) { - if(tok2->str() == "}") + if (tok2->str() == "}") break; - if(Token::Match(tok2, "break|return ;")) + if (Token::Match(tok2, "break|return ;")) break; - if(Token::Match(tok2, "if return|break use| ;")) + if (Token::Match(tok2, "if return|break use| ;")) tok2 = tok2->tokAt(2); else tok2 = tok2->next(); } - if(Token::simpleMatch(tok2, "break ;")) + if (Token::simpleMatch(tok2, "break ;")) { tok2->str(";"); tok2 = tok2->tokAt(2); } - else if(tok2 && tok2->str() == "return") + else if (tok2 && tok2->str() == "return") { tok2 = tok2->tokAt(2); } @@ -1896,11 +1896,11 @@ void CheckMemoryLeakInFunction::simplifycode(Token *tok, bool &all) } // If "--all" is given, remove all "callfunc".. - if(done && _settings->_showAll) + if (done && _settings->_showAll) { - for(Token *tok2 = tok; tok2; tok2 = tok2->next()) + for (Token *tok2 = tok; tok2; tok2 = tok2->next()) { - if(tok2->str() == "callfunc") + if (tok2->str() == "callfunc") { tok2->deleteThis(); all = true; @@ -1919,57 +1919,57 @@ const Token *CheckMemoryLeakInFunction::findleak(const Token *tokens, bool all) { const Token *result; - if((result = Token::findmatch(tokens, "loop alloc ;")) != NULL) + if ((result = Token::findmatch(tokens, "loop alloc ;")) != NULL) { return result; } - if(Token::Match(tokens, "alloc ; if|if(var)|ifv break|continue|return ;")) + if (Token::Match(tokens, "alloc ; if|if(var)|ifv break|continue|return ;")) { return tokens->tokAt(3); } - if((result = Token::findmatch(tokens, "alloc ; if|if(var)|ifv return ;")) != NULL) + if ((result = Token::findmatch(tokens, "alloc ; if|if(var)|ifv return ;")) != NULL) { return result->tokAt(3); } - if(all && (result = Token::findmatch(tokens, "alloc ; ifv break|continue|return ;")) != NULL) + if (all && (result = Token::findmatch(tokens, "alloc ; ifv break|continue|return ;")) != NULL) { return result->tokAt(3); } - if((result = Token::findmatch(tokens, "alloc ; alloc|assign|return callfunc| ;")) != NULL) + if ((result = Token::findmatch(tokens, "alloc ; alloc|assign|return callfunc| ;")) != NULL) { return result->tokAt(2); } - if((result = Token::findmatch(tokens, "alloc ; if assign ;")) != NULL) + if ((result = Token::findmatch(tokens, "alloc ; if assign ;")) != NULL) { return result->tokAt(3); } - if((result = Token::findmatch(tokens, "alloc ; }")) != NULL) + if ((result = Token::findmatch(tokens, "alloc ; }")) != NULL) { - if(result->tokAt(3) == NULL) + if (result->tokAt(3) == NULL) return result->tokAt(2); } // No deallocation / usage => report leak at the last token - if(!Token::findmatch(tokens, "dealloc|use")) + if (!Token::findmatch(tokens, "dealloc|use")) { const Token *last = tokens; - while(last->next()) + while (last->next()) last = last->next(); // check if we call exit before the end of the funcion Token *tok2 = last->previous(); - if(tok2) + if (tok2) { - if(Token::simpleMatch(tok2, ";")) + if (Token::simpleMatch(tok2, ";")) { const Token *tok3 = tok2->previous(); - if(tok3 && Token::simpleMatch(tok3, "exit")) + if (tok3 && Token::simpleMatch(tok3, "exit")) { return NULL; } @@ -2003,30 +2003,30 @@ void CheckMemoryLeakInFunction::checkScope(const Token *Tok1, const std::string //tok->printOut((std::string("Checkmemoryleak: getcode result for: ") + varname).c_str()); // Simplify the code and check if freed memory is used.. - for(Token *tok2 = tok; tok2; tok2 = tok2->next()) + for (Token *tok2 = tok; tok2; tok2 = tok2->next()) { - while(Token::Match(tok2, "[;{}] ;")) + while (Token::Match(tok2, "[;{}] ;")) Token::eraseTokens(tok2, tok2->tokAt(2)); } - if((result = Token::findmatch(tok, "[;{}] dealloc ; use_ ;")) != NULL) + if ((result = Token::findmatch(tok, "[;{}] dealloc ; use_ ;")) != NULL) { deallocuseError(result->tokAt(3), varname); } // Replace "&use" with "use". Replace "use_" with ";" - for(Token *tok2 = tok; tok2; tok2 = tok2->next()) + for (Token *tok2 = tok; tok2; tok2 = tok2->next()) { - if(tok2->str() == "&use") + if (tok2->str() == "&use") tok2->str("use"); - else if(tok2->str() == "use_") + else if (tok2->str() == "use_") tok2->str(";"); - else if(tok2->str() == "::use") // Some kind of member function usage. Not analyzed very well. + else if (tok2->str() == "::use") // Some kind of member function usage. Not analyzed very well. tok2->str("use"); - else if(tok2->str() == "recursive") + else if (tok2->str() == "recursive") tok2->str("use"); - else if(tok2->str() == "dealloc_") + else if (tok2->str() == "dealloc_") tok2->str("dealloc"); - else if(tok2->str() == "realloc") + else if (tok2->str() == "realloc") { tok2->str("dealloc"); tok2->insertToken("alloc"); @@ -2035,7 +2035,7 @@ void CheckMemoryLeakInFunction::checkScope(const Token *Tok1, const std::string } // If the variable is not allocated at all => no memory leak - if(Token::findmatch(tok, "alloc") == 0) + if (Token::findmatch(tok, "alloc") == 0) { Tokenizer::deleteTokens(tok); return; @@ -2043,40 +2043,40 @@ void CheckMemoryLeakInFunction::checkScope(const Token *Tok1, const std::string simplifycode(tok, all); - if(_settings->_debug && _settings->_verbose) + if (_settings->_debug && _settings->_verbose) { tok->printOut(("Checkmemoryleak: simplifycode result for: " + varname).c_str()); } // If the variable is not allocated at all => no memory leak - if(Token::findmatch(tok, "alloc") == 0) + if (Token::findmatch(tok, "alloc") == 0) { Tokenizer::deleteTokens(tok); return; } /** @todo handle "goto" */ - if(Token::findmatch(tok, "goto")) + if (Token::findmatch(tok, "goto")) { Tokenizer::deleteTokens(tok); return; } - if((result = findleak(tok, _settings->_showAll)) != NULL) + if ((result = findleak(tok, _settings->_showAll)) != NULL) { memoryLeak(result, varname, alloctype, all); } - else if((result = Token::findmatch(tok, "dealloc ; dealloc ;")) != NULL) + else if ((result = Token::findmatch(tok, "dealloc ; dealloc ;")) != NULL) { deallocDeallocError(result->tokAt(2), varname); } // detect cases that "simplifycode" don't handle well.. - else if(_settings->_debug) + else if (_settings->_debug) { Token *first = tok; - while(first && first->str() == ";") + while (first && first->str() == ";") first = first->next(); bool noerr = false; @@ -2092,10 +2092,10 @@ void CheckMemoryLeakInFunction::checkScope(const Token *Tok1, const std::string noerr |= Token::simpleMatch(first, "alloc ; if return ; dealloc; }"); // Unhandled case.. - if(! noerr) + if (! noerr) { std::cout << "Token listing..\n "; - for(const Token *tok2 = tok; tok2; tok2 = tok2->next()) + for (const Token *tok2 = tok; tok2; tok2 = tok2->next()) std::cout << " " << tok2->str(); std::cout << "\n"; } @@ -2126,58 +2126,58 @@ void CheckMemoryLeakInFunction::parseFunctionScope(const Token *tok, const bool unsigned int indentlevel = 0; do { - if(tok->str() == "{") + if (tok->str() == "{") ++indentlevel; - else if(tok->str() == "}") + else if (tok->str() == "}") { - if(indentlevel <= 1) + if (indentlevel <= 1) break; --indentlevel; } // Skip these weird blocks... "( { ... } )" - if(Token::simpleMatch(tok, "( {")) + if (Token::simpleMatch(tok, "( {")) { tok = tok->link(); - if(!tok) + if (!tok) break; continue; } - if(!Token::Match(tok, "[{};] %type%")) + if (!Token::Match(tok, "[{};] %type%")) continue; // Don't check static/extern variables - if(Token::Match(tok->next(), "static|extern")) + if (Token::Match(tok->next(), "static|extern")) continue; // return/else is not part of a variable declaration.. - if(Token::Match(tok->next(), "return|else")) + if (Token::Match(tok->next(), "return|else")) continue; unsigned int sz = _tokenizer->sizeOfType(tok->next()); - if(sz < 1) + if (sz < 1) sz = 1; - if(Token::Match(tok, "[{};] %type% * const| %var% [;=]")) + if (Token::Match(tok, "[{};] %type% * const| %var% [;=]")) { const Token *vartok = tok->tokAt(tok->tokAt(3)->str() != "const" ? 3 : 4); checkScope(tok->next(), vartok->str(), vartok->varId(), classmember, sz); } - else if(Token::Match(tok, "[{};] %type% %type% * const| %var% [;=]")) + else if (Token::Match(tok, "[{};] %type% %type% * const| %var% [;=]")) { const Token *vartok = tok->tokAt(tok->tokAt(4)->str() != "const" ? 4 : 5); checkScope(tok->next(), vartok->str(), vartok->varId(), classmember, sz); } - else if(Token::Match(tok, "[{};] int %var% [;=]")) + else if (Token::Match(tok, "[{};] int %var% [;=]")) { const Token *vartok = tok->tokAt(2); checkScope(tok->next(), vartok->str(), vartok->varId(), classmember, sz); } } - while(0 != (tok = tok->next())); + while (0 != (tok = tok->next())); } void CheckMemoryLeakInFunction::check() @@ -2186,27 +2186,27 @@ void CheckMemoryLeakInFunction::check() parse_noreturn(); bool classmember = false; - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { - if(tok->str() == "(") + if (tok->str() == "(") { tok = tok->link(); } // Found a function scope - if(Token::Match(tok, ") const| {")) + if (Token::Match(tok, ") const| {")) { - while(tok->str() != "{") + while (tok->str() != "{") tok = tok->next(); parseFunctionScope(tok, classmember); tok = tok->link(); continue; } - if(tok->str() == "::") + if (tok->str() == "::") classmember = true; - if(Token::Match(tok, "[;}]")) + if (Token::Match(tok, "[;}]")) classmember = false; } } @@ -2248,12 +2248,12 @@ void CheckMemoryLeakInFunction::check() void CheckMemoryLeakInClass::check() { - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { - if(tok->str() == "{") + if (tok->str() == "{") tok = tok->link(); - else if(Token::Match(tok, "class %var% [{:]")) + else if (Token::Match(tok, "class %var% [{:]")) { std::vector classname; classname.push_back(tok->strAt(1)); @@ -2266,35 +2266,35 @@ void CheckMemoryLeakInClass::check() void CheckMemoryLeakInClass::parseClass(const Token *tok1, std::vector &classname) { // Go into class. - while(tok1 && tok1->str() != "{") + while (tok1 && tok1->str() != "{") tok1 = tok1->next(); tok1 = tok1 ? tok1->next() : 0; unsigned int indentlevel = 0; - for(const Token *tok = tok1; tok; tok = tok->next()) + for (const Token *tok = tok1; tok; tok = tok->next()) { - if(tok->str() == "{") + if (tok->str() == "{") ++indentlevel; - else if(tok->str() == "}") + else if (tok->str() == "}") { - if(indentlevel == 0) + if (indentlevel == 0) return; --indentlevel; } // Only parse this particular class.. not subclasses - if(indentlevel > 0) + if (indentlevel > 0) continue; // skip static variables.. - if(Token::Match(tok, "static %type% * %var% ;")) + if (Token::Match(tok, "static %type% * %var% ;")) { tok = tok->tokAt(4); } // Declaring subclass.. recursive checking - if(Token::Match(tok, "class %var% [{:]")) + if (Token::Match(tok, "class %var% [{:]")) { classname.push_back(tok->strAt(1)); parseClass(tok, classname); @@ -2302,13 +2302,13 @@ void CheckMemoryLeakInClass::parseClass(const Token *tok1, std::vectorprevious(), ";|{|}|private:|protected:|public: %type% * %var% ;")) + if (Token::Match(tok->previous(), ";|{|}|private:|protected:|public: %type% * %var% ;")) { // No false positives for auto deallocated classes.. - if(_settings->isAutoDealloc(tok->str().c_str())) + if (_settings->isAutoDealloc(tok->str().c_str())) continue; - if(_settings->_showAll || !isclass(_tokenizer, tok)) + if (_settings->_showAll || !isclass(_tokenizer, tok)) variable(classname.back(), tok->tokAt(2)); } } @@ -2316,7 +2316,7 @@ void CheckMemoryLeakInClass::parseClass(const Token *tok1, std::vector_showAll) + if (!_settings->_showAll) return; const std::string varname = tokVarname->strAt(0); @@ -2331,47 +2331,47 @@ void CheckMemoryLeakInClass::variable(const std::string &classname, const Token // Loop through all tokens. Inspect member functions int indent_ = 0; const Token *functionToken = _tokenizer->findClassFunction(_tokenizer->tokens(), classname.c_str(), "~| %var%", indent_); - while(functionToken) + while (functionToken) { const bool constructor(Token::Match(functionToken, (classname + " (").c_str()) || Token::Match(functionToken, (classname + " :: " + classname + " (").c_str())); const bool destructor(functionToken->str() == "~" || functionToken->tokAt(2)->str() == "~"); unsigned int indent = 0; bool initlist = false; - for(const Token *tok = functionToken; tok; tok = tok->next()) + for (const Token *tok = functionToken; tok; tok = tok->next()) { - if(tok->str() == "{") + if (tok->str() == "{") ++indent; - else if(tok->str() == "}") + else if (tok->str() == "}") { - if(indent <= 1) + if (indent <= 1) break; --indent; } - else if(indent == 0 && Token::simpleMatch(tok, ") :")) + else if (indent == 0 && Token::simpleMatch(tok, ") :")) initlist = true; - else if(initlist || indent > 0) + else if (initlist || indent > 0) { - if(indent == 0) + if (indent == 0) { - if(!Token::Match(tok, (":|, " + varname + " (").c_str())) + if (!Token::Match(tok, (":|, " + varname + " (").c_str())) continue; } // Allocate.. - if(indent == 0 || Token::Match(tok, (varname + " =").c_str())) + if (indent == 0 || Token::Match(tok, (varname + " =").c_str())) { AllocType alloc = getAllocationType(tok->tokAt((indent > 0) ? 2 : 3), 0); - if(alloc != CheckMemoryLeak::No) + if (alloc != CheckMemoryLeak::No) { - if(constructor) + if (constructor) allocInConstructor = true; - if(Alloc != No && Alloc != alloc) + if (Alloc != No && Alloc != alloc) alloc = CheckMemoryLeak::Many; std::list callstack; - if(alloc != CheckMemoryLeak::Many && Dealloc != CheckMemoryLeak::No && Dealloc != CheckMemoryLeak::Many && Dealloc != alloc) + if (alloc != CheckMemoryLeak::Many && Dealloc != CheckMemoryLeak::No && Dealloc != CheckMemoryLeak::Many && Dealloc != alloc) { callstack.push_back(tok); mismatchAllocDealloc(callstack, classname + "::" + varname, true); @@ -2382,30 +2382,30 @@ void CheckMemoryLeakInClass::variable(const std::string &classname, const Token } } - if(indent == 0) + if (indent == 0) continue; // Deallocate.. const char *varnames[3] = { "var", 0, 0 }; varnames[0] = varname.c_str(); AllocType dealloc = getDeallocationType(tok, varnames); - if(dealloc == No) + if (dealloc == No) { varnames[0] = "this"; varnames[1] = varname.c_str(); dealloc = getDeallocationType(tok, varnames); } - if(dealloc != CheckMemoryLeak::No) + if (dealloc != CheckMemoryLeak::No) { - if(destructor) + if (destructor) deallocInDestructor = true; // several types of allocation/deallocation? - if(Dealloc != CheckMemoryLeak::No && Dealloc != dealloc) + if (Dealloc != CheckMemoryLeak::No && Dealloc != dealloc) dealloc = CheckMemoryLeak::Many; std::list callstack; - if(dealloc != CheckMemoryLeak::Many && Alloc != CheckMemoryLeak::No && Alloc != Many && Alloc != dealloc) + if (dealloc != CheckMemoryLeak::Many && Alloc != CheckMemoryLeak::No && Alloc != Many && Alloc != dealloc) { callstack.push_back(tok); mismatchAllocDealloc(callstack, classname + "::" + varname, true); @@ -2416,11 +2416,11 @@ void CheckMemoryLeakInClass::variable(const std::string &classname, const Token } // Function call in destructor .. possible deallocation - else if(destructor && Token::Match(tok->previous(), "[{};] %var% (")) + else if (destructor && Token::Match(tok->previous(), "[{};] %var% (")) { - if(!std::bsearch(tok->str().c_str(), call_func_white_list, - sizeof(call_func_white_list) / sizeof(call_func_white_list[0]), - sizeof(call_func_white_list[0]), call_func_white_list_compare)) + if (!std::bsearch(tok->str().c_str(), call_func_white_list, + sizeof(call_func_white_list) / sizeof(call_func_white_list[0]), + sizeof(call_func_white_list[0]), call_func_white_list_compare)) { return; } @@ -2431,11 +2431,11 @@ void CheckMemoryLeakInClass::variable(const std::string &classname, const Token functionToken = _tokenizer->Tokenizer::findClassFunction(functionToken->next(), classname.c_str(), "~| %var%", indent_); } - if(allocInConstructor && !deallocInDestructor) + if (allocInConstructor && !deallocInDestructor) { memoryLeak(tokVarname, (classname + "::" + varname).c_str(), Alloc, true); } - else if(Alloc != CheckMemoryLeak::No && Dealloc == CheckMemoryLeak::No) + else if (Alloc != CheckMemoryLeak::No && Dealloc == CheckMemoryLeak::No) { memoryLeak(tokVarname, (classname + "::" + varname).c_str(), Alloc, true); } @@ -2459,18 +2459,18 @@ void CheckMemoryLeakStructMember::check() unsigned int indentlevel1 = 0; - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { - if(tok->str() == "{") + if (tok->str() == "{") ++indentlevel1; - else if(tok->str() == "}") + else if (tok->str() == "}") --indentlevel1; // Locate struct variables.. - if(indentlevel1 > 0 && Token::Match(tok, "struct|;|{|} %type% * %var% [=;]")) + if (indentlevel1 > 0 && Token::Match(tok, "struct|;|{|} %type% * %var% [=;]")) { const Token * const vartok = tok->tokAt(3); - if(vartok->varId() == 0) + if (vartok->varId() == 0) continue; // Check that struct is allocated.. @@ -2478,65 +2478,65 @@ void CheckMemoryLeakStructMember::check() const unsigned int varid(vartok->varId()); bool alloc = false; unsigned int indentlevel2 = 0; - for(const Token *tok2 = vartok; tok2; tok2 = tok2->next()) + for (const Token *tok2 = vartok; tok2; tok2 = tok2->next()) { - if(tok2->str() == "{") + if (tok2->str() == "{") ++indentlevel2; - else if(tok2->str() == "}") + else if (tok2->str() == "}") { - if(indentlevel2 == 0) + if (indentlevel2 == 0) break; --indentlevel2; } - else if(Token::Match(tok2, "= %varid% [;=]", varid)) + else if (Token::Match(tok2, "= %varid% [;=]", varid)) { alloc = false; break; } - else if(Token::Match(tok2, "%varid% = malloc|kmalloc (", varid)) + else if (Token::Match(tok2, "%varid% = malloc|kmalloc (", varid)) { alloc = true; } } - if(!alloc) + if (!alloc) continue; } // Check struct.. unsigned int indentlevel2 = 0; - for(const Token *tok2 = vartok; tok2; tok2 = tok2->next()) + for (const Token *tok2 = vartok; tok2; tok2 = tok2->next()) { - if(tok2->str() == "{") + if (tok2->str() == "{") ++indentlevel2; - else if(tok2->str() == "}") + else if (tok2->str() == "}") { - if(indentlevel2 == 0) + if (indentlevel2 == 0) break; --indentlevel2; } // Unknown usage of struct /** @todo Check how the struct is used. Only bail out if necessary */ - else if(Token::Match(tok2, "[(,] %varid% [,)]", vartok->varId())) + else if (Token::Match(tok2, "[(,] %varid% [,)]", vartok->varId())) break; // Struct member is allocated => check if it is also properly deallocated.. - else if(Token::Match(tok2, "%varid% . %var% = malloc|strdup|kmalloc (", vartok->varId())) + else if (Token::Match(tok2, "%varid% . %var% = malloc|strdup|kmalloc (", vartok->varId())) { const unsigned int structid(vartok->varId()); const unsigned int structmemberid(tok2->tokAt(2)->varId()); // This struct member is allocated.. check that it is deallocated unsigned int indentlevel3 = indentlevel2; - for(const Token *tok3 = tok2; tok3; tok3 = tok3->next()) + for (const Token *tok3 = tok2; tok3; tok3 = tok3->next()) { - if(tok3->str() == "{") + if (tok3->str() == "{") ++indentlevel3; - else if(tok3->str() == "}") + else if (tok3->str() == "}") { - if(indentlevel3 == 0) + if (indentlevel3 == 0) { memoryLeak(tok3, (vartok->str() + "." + tok2->strAt(2)).c_str(), Malloc, false); break; @@ -2545,46 +2545,46 @@ void CheckMemoryLeakStructMember::check() } // Deallocating the struct member.. - else if(Token::Match(tok3, "free|kfree ( %var% . %varid% )", structmemberid)) + else if (Token::Match(tok3, "free|kfree ( %var% . %varid% )", structmemberid)) { // If the deallocation happens at the base level, don't check this member anymore - if(indentlevel3 == 0) + if (indentlevel3 == 0) break; // deallocating and then returning from function in a conditional block => // skip ahead out of the block bool ret = false; - while(tok3) + while (tok3) { // debug info const std::string tok3str_(tok3->str()); - if(tok3->str() == "return") + if (tok3->str() == "return") ret = true; - else if(tok3->str() == "{" || tok3->str() == "}") + else if (tok3->str() == "{" || tok3->str() == "}") break; tok3 = tok3->next(); } - if(!ret || !tok3 || tok3->str() != "}") + if (!ret || !tok3 || tok3->str() != "}") break; --indentlevel3; continue; } // Deallocating the struct.. - else if(indentlevel2 == 0 && Token::Match(tok3, "free|kfree ( %varid% )", structid)) + else if (indentlevel2 == 0 && Token::Match(tok3, "free|kfree ( %varid% )", structid)) { memoryLeak(tok3, (vartok->str() + "." + tok2->strAt(2)).c_str(), Malloc, false); break; } // failed allocation => skip code.. - else if(Token::Match(tok3, "if ( ! %var% . %varid% )", structmemberid)) + else if (Token::Match(tok3, "if ( ! %var% . %varid% )", structmemberid)) { // Goto the ")" tok3 = tok3->next()->link(); // make sure we have ") {".. it should be - if(!Token::simpleMatch(tok3, ") {")) + if (!Token::simpleMatch(tok3, ") {")) break; // Goto the "}" @@ -2592,39 +2592,39 @@ void CheckMemoryLeakStructMember::check() } // succeeded allocation - else if(Token::Match(tok3, "if ( %var% . %varid% ) {", structmemberid)) + else if (Token::Match(tok3, "if ( %var% . %varid% ) {", structmemberid)) { // goto the ")" tok3 = tok3->next()->link(); // check if the variable is deallocated or returned.. unsigned int indentlevel4 = 0; - for(const Token *tok4 = tok3; tok4; tok4 = tok4->next()) + for (const Token *tok4 = tok3; tok4; tok4 = tok4->next()) { - if(tok4->str() == "{") + if (tok4->str() == "{") ++indentlevel4; - else if(tok4->str() == "}") + else if (tok4->str() == "}") { --indentlevel4; - if(indentlevel4 == 0) + if (indentlevel4 == 0) break; } - else if(Token::Match(tok4, "free|kfree ( %var% . %varid% )", structmemberid)) + else if (Token::Match(tok4, "free|kfree ( %var% . %varid% )", structmemberid)) { break; } } // was there a proper deallocation? - if(indentlevel4 > 0) + if (indentlevel4 > 0) break; } // Returning from function.. - else if(tok3->str() == "return") + else if (tok3->str() == "return") { // Returning from function without deallocating struct member? - if(!Token::Match(tok3, "return %varid% ;", structid)) + if (!Token::Match(tok3, "return %varid% ;", structid)) { memoryLeak(tok3, (vartok->str() + "." + tok2->strAt(2)).c_str(), Malloc, false); } @@ -2632,32 +2632,32 @@ void CheckMemoryLeakStructMember::check() } // goto isn't handled well.. bail out even though there might be leaks - else if(tok3->str() == "goto") + else if (tok3->str() == "goto") break; // using struct in a function call.. - else if(Token::Match(tok3, "%var% (")) + else if (Token::Match(tok3, "%var% (")) { // Calling non-function / function that doesn't deallocate? - if(ignoredFunctions.find(tok3->str()) != ignoredFunctions.end()) + if (ignoredFunctions.find(tok3->str()) != ignoredFunctions.end()) continue; // Check if the struct is used.. bool deallocated = false; unsigned int parlevel = 0; - for(const Token *tok4 = tok3; tok4; tok4 = tok4->next()) + for (const Token *tok4 = tok3; tok4; tok4 = tok4->next()) { - if(tok4->str() == "(") + if (tok4->str() == "(") ++parlevel; - else if(tok4->str() == ")") + else if (tok4->str() == ")") { - if(parlevel <= 1) + if (parlevel <= 1) break; --parlevel; } - if(Token::Match(tok4, "[(,] %varid% [,)]", structid)) + if (Token::Match(tok4, "[(,] %varid% [,)]", structid)) { /** @todo check if the function deallocates the memory */ deallocated = true; @@ -2665,7 +2665,7 @@ void CheckMemoryLeakStructMember::check() } } - if(deallocated) + if (deallocated) break; } } @@ -2692,10 +2692,10 @@ public: { std::ostringstream ostr; ostr << "CheckLocalLeaks::printOut" << std::endl; - for(std::list::const_iterator it = checks.begin(); it != checks.end(); ++it) + for (std::list::const_iterator it = checks.begin(); it != checks.end(); ++it) { CheckLocalLeaks *c = dynamic_cast(*it); - if(c) + if (c) { ostr << std::hex << c << ": varId=" << c->varId << " allocated=" << (c->allocated ? "true" : "false") << std::endl; } @@ -2726,14 +2726,14 @@ private: /** Allocation is detected */ static void alloc(std::list &checks, const unsigned int varid) { - if(varid == 0) + if (varid == 0) return; std::list::iterator it; - for(it = checks.begin(); it != checks.end(); ++it) + for (it = checks.begin(); it != checks.end(); ++it) { CheckLocalLeaks *C = dynamic_cast(*it); - if(C && C->varId == varid) + if (C && C->varId == varid) C->allocated = true; } } @@ -2741,14 +2741,14 @@ private: /** Deallocation is detected */ static void dealloc(std::list &checks, const Token *tok) { - if(tok->varId() == 0) + if (tok->varId() == 0) return; std::list::iterator it; - for(it = checks.begin(); it != checks.end(); ++it) + for (it = checks.begin(); it != checks.end(); ++it) { CheckLocalLeaks *C = dynamic_cast(*it); - if(C && C->varId == tok->varId()) + if (C && C->varId == tok->varId()) C->allocated = false; } } @@ -2757,13 +2757,13 @@ private: static void ret(const std::list &checks, const Token *tok, bool &foundError) { std::list::const_iterator it; - for(it = checks.begin(); it != checks.end(); ++it) + for (it = checks.begin(); it != checks.end(); ++it) { CheckLocalLeaks *C = dynamic_cast(*it); - if(C && C->allocated) + if (C && C->allocated) { CheckMemoryLeakInFunction *checkMemleak = reinterpret_cast(C->owner); - if(checkMemleak) + if (checkMemleak) { checkMemleak->memleakError(tok, C->varname, false); foundError = true; @@ -2779,41 +2779,41 @@ private: //std::cout << "CheckLocalLeaks::parse " << tok.str() << std::endl; //printOut(checks); - if(!Token::Match(tok.previous(), "[;{}]")) + if (!Token::Match(tok.previous(), "[;{}]")) return &tok; - if(Token::Match(&tok, "%type% * %var% ;")) + if (Token::Match(&tok, "%type% * %var% ;")) { const Token * vartok = tok.tokAt(2); - if(vartok->varId() != 0) + if (vartok->varId() != 0) checks.push_back(new CheckLocalLeaks(owner, vartok->varId(), vartok->str())); return vartok->next(); } - if(Token::Match(&tok, "%var% = new")) + if (Token::Match(&tok, "%var% = new")) { alloc(checks, tok.varId()); // goto end of statement const Token *tok2 = &tok; - while(tok2 && tok2->str() != ";") + while (tok2 && tok2->str() != ";") tok2 = tok2->next(); return tok2; } - if(Token::Match(&tok, "delete %var% ;")) + if (Token::Match(&tok, "delete %var% ;")) { dealloc(checks, tok.next()); return tok.tokAt(2); } - if(Token::Match(&tok, "delete [ ] %var% ;")) + if (Token::Match(&tok, "delete [ ] %var% ;")) { dealloc(checks, tok.tokAt(3)); return tok.tokAt(4); } - if(tok.str() == "return") + if (tok.str() == "return") { ret(checks, &tok, foundError); } diff --git a/lib/checkmemoryleak.h b/lib/checkmemoryleak.h index fbb25b3e3..a118fa0db 100644 --- a/lib/checkmemoryleak.h +++ b/lib/checkmemoryleak.h @@ -84,7 +84,7 @@ private: public: CheckMemoryLeak(const Tokenizer *t, ErrorLogger *e) - : tokenizer(t), errorLogger(e) + : tokenizer(t), errorLogger(e) { } @@ -172,7 +172,7 @@ public: /** @brief This constructor is used when running checks */ CheckMemoryLeakInFunction(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) - : Check(tokenizer, settings, errorLogger), CheckMemoryLeak(tokenizer, errorLogger) + : Check(tokenizer, settings, errorLogger), CheckMemoryLeak(tokenizer, errorLogger) { } /** @brief run all simplified checks */ @@ -340,7 +340,7 @@ public: { } CheckMemoryLeakInClass(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) - : Check(tokenizer, settings, errorLogger), CheckMemoryLeak(tokenizer, errorLogger) + : Check(tokenizer, settings, errorLogger), CheckMemoryLeak(tokenizer, errorLogger) { } void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) @@ -380,7 +380,7 @@ public: { } CheckMemoryLeakStructMember(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) - : Check(tokenizer, settings, errorLogger), CheckMemoryLeak(tokenizer, errorLogger) + : Check(tokenizer, settings, errorLogger), CheckMemoryLeak(tokenizer, errorLogger) { } void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) diff --git a/lib/checkother.cpp b/lib/checkother.cpp index 83b5a884c..75c6670df 100644 --- a/lib/checkother.cpp +++ b/lib/checkother.cpp @@ -44,23 +44,23 @@ CheckOther instance; void CheckOther::warningOldStylePointerCast() { - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { // Old style pointer casting.. - if(!Token::Match(tok, "( const| %type% * ) %var%") && - !Token::Match(tok, "( const| %type% * ) (| new")) + if (!Token::Match(tok, "( const| %type% * ) %var%") && + !Token::Match(tok, "( const| %type% * ) (| new")) continue; int addToIndex = 0; - if(tok->tokAt(1)->str() == "const") + if (tok->tokAt(1)->str() == "const") addToIndex = 1; - if(tok->tokAt(4 + addToIndex)->str() == "const") + if (tok->tokAt(4 + addToIndex)->str() == "const") continue; // Is "type" a class? const std::string pattern("class " + tok->tokAt(1 + addToIndex)->str()); - if(!Token::findmatch(_tokenizer->tokens(), pattern.c_str())) + if (!Token::findmatch(_tokenizer->tokens(), pattern.c_str())) continue; cstyleCastError(tok); @@ -78,9 +78,9 @@ void CheckOther::warningRedundantCode() { // if (p) delete p - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { - if(! Token::simpleMatch(tok, "if (")) + if (! Token::simpleMatch(tok, "if (")) continue; std::string varname; @@ -95,14 +95,14 @@ void CheckOther::warningRedundantCode() * **/ - while(Token::Match(tok2, "%var% .|::")) + while (Token::Match(tok2, "%var% .|::")) { varname.append(tok2->str()); varname.append(tok2->next()->str()); tok2 = tok2->tokAt(2); } - if(!Token::Match(tok2, "%var% ) {")) + if (!Token::Match(tok2, "%var% ) {")) continue; varname.append(tok2->str()); @@ -124,25 +124,25 @@ void CheckOther::warningRedundantCode() **/ bool funcHasBracket = false; - if(Token::Match(tok2, "free|kfree (")) + if (Token::Match(tok2, "free|kfree (")) { tok2 = tok2->tokAt(2); funcHasBracket = true; } - else if(tok2->str() == "delete") + else if (tok2->str() == "delete") { tok2 = tok2->next(); - if(Token::simpleMatch(tok2, "[ ]")) + if (Token::simpleMatch(tok2, "[ ]")) { tok2 = tok2->tokAt(2); } } std::string varname2; - while(Token::Match(tok2, "%var% ::|.")) + while (Token::Match(tok2, "%var% ::|.")) { varname2.append(tok2->str()); varname2.append(tok2->next()->str()); @@ -150,14 +150,14 @@ void CheckOther::warningRedundantCode() } varname2.append(tok2->str()); - if(Token::Match(tok2, "%var%") && varname == varname2) + if (Token::Match(tok2, "%var%") && varname == varname2) tok2 = tok2->next(); else continue; - if(funcHasBracket) + if (funcHasBracket) { - if(tok2->str() != ")") + if (tok2->str() != ")") { continue; } @@ -167,7 +167,7 @@ void CheckOther::warningRedundantCode() } } - if(!Token::Match(tok2, "; } !!else")) + if (!Token::Match(tok2, "; } !!else")) { continue; } @@ -191,7 +191,7 @@ void CheckOther::redundantCondition2() " %var% . remove ( %any% ) ; " "}|}|"; const Token *tok = Token::findmatch(_tokenizer->tokens(), pattern); - while(tok) + while (tok) { bool b(tok->tokAt(15)->str() == "{"); @@ -203,9 +203,9 @@ void CheckOther::redundantCondition2() const Token *any2 = tok->tokAt(b ? 20 : 19); // Check if all the "%var%" fields are the same and if all the "%any%" are the same.. - if(var1->str() == var2->str() && - var2->str() == var3->str() && - any1->str() == any2->str()) + if (var1->str() == var2->str() && + var2->str() == var3->str() && + any1->str() == any2->str()) { redundantIfRemoveError(tok); } @@ -224,29 +224,29 @@ void CheckOther::redundantCondition2() void CheckOther::invalidFunctionUsage() { // strtol and strtoul.. - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { - if((tok->str() != "strtol") && (tok->str() != "strtoul")) + if ((tok->str() != "strtol") && (tok->str() != "strtoul")) continue; // Locate the third parameter of the function call.. int parlevel = 0; int param = 1; - for(const Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) + for (const Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) { - if(tok2->str() == "(") + if (tok2->str() == "(") ++parlevel; - else if(tok2->str() == ")") + else if (tok2->str() == ")") --parlevel; - else if(parlevel == 1 && tok2->str() == ",") + else if (parlevel == 1 && tok2->str() == ",") { ++param; - if(param == 3) + if (param == 3) { - if(Token::Match(tok2, ", %num% )")) + if (Token::Match(tok2, ", %num% )")) { int radix = MathLib::toLongNumber(tok2->next()->str()); - if(!(radix == 0 || (radix >= 2 && radix <= 36))) + if (!(radix == 0 || (radix >= 2 && radix <= 36))) { dangerousUsageStrtolError(tok2); } @@ -258,38 +258,38 @@ void CheckOther::invalidFunctionUsage() } // sprintf|snprintf overlapping data - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { // Get variable id of target buffer.. unsigned int varid = 0; - if(Token::Match(tok, "sprintf|snprintf ( %var% ,")) + if (Token::Match(tok, "sprintf|snprintf ( %var% ,")) varid = tok->tokAt(2)->varId(); - else if(Token::Match(tok, "sprintf|snprintf ( %var% . %var% ,")) + else if (Token::Match(tok, "sprintf|snprintf ( %var% . %var% ,")) varid = tok->tokAt(4)->varId(); - if(varid == 0) + if (varid == 0) continue; // goto "," const Token *tok2 = tok->tokAt(3); - while(tok2 && tok2->str() != ",") + while (tok2 && tok2->str() != ",") tok2 = tok2->next(); // is any source buffer overlapping the target buffer? int parlevel = 0; - while((tok2 = tok2->next()) != NULL) + while ((tok2 = tok2->next()) != NULL) { - if(tok2->str() == "(") + if (tok2->str() == "(") ++parlevel; - else if(tok2->str() == ")") + else if (tok2->str() == ")") { --parlevel; - if(parlevel < 0) + if (parlevel < 0) break; } - else if(parlevel == 0 && Token::Match(tok2, ", %varid% [,)]", varid)) + else if (parlevel == 0 && Token::Match(tok2, ", %varid% [,)]", varid)) { sprintfOverlappingDataError(tok2->next(), tok2->next()->str()); break; @@ -306,32 +306,32 @@ void CheckOther::invalidFunctionUsage() void CheckOther::checkUnsignedDivision() { - if(!_settings->_showAll || !_settings->_checkCodingStyle) + if (!_settings->_showAll || !_settings->_checkCodingStyle) return; // Check for "ivar / uvar" and "uvar / ivar" std::map varsign; - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { - if(Token::Match(tok, "[{};(,] %type% %var% [;=,)]")) + if (Token::Match(tok, "[{};(,] %type% %var% [;=,)]")) { - if(tok->tokAt(1)->isUnsigned()) + if (tok->tokAt(1)->isUnsigned()) varsign[tok->tokAt(2)->varId()] = 'u'; else varsign[tok->tokAt(2)->varId()] = 's'; } - else if(!Token::Match(tok, "[).]") && - Token::Match(tok->next(), "%var% / %var%") && - tok->tokAt(1)->varId() != 0 && - tok->tokAt(3)->varId() != 0) + else if (!Token::Match(tok, "[).]") && + Token::Match(tok->next(), "%var% / %var%") && + tok->tokAt(1)->varId() != 0 && + tok->tokAt(3)->varId() != 0) { - if(ErrorLogger::udivWarning(*_settings)) + if (ErrorLogger::udivWarning(*_settings)) { char sign1 = varsign[tok->tokAt(1)->varId()]; char sign2 = varsign[tok->tokAt(3)->varId()]; - if(sign1 && sign2 && sign1 != sign2) + if (sign1 && sign2 && sign1 != sign2) { // One of the operands are signed, the other is unsigned.. udivWarning(tok->next()); @@ -339,24 +339,24 @@ void CheckOther::checkUnsignedDivision() } } - else if(!Token::Match(tok, "[).]") && Token::Match(tok->next(), "%var% / %num%")) + else if (!Token::Match(tok, "[).]") && Token::Match(tok->next(), "%var% / %num%")) { - if(tok->strAt(3)[0] == '-' && ErrorLogger::udivError()) + if (tok->strAt(3)[0] == '-' && ErrorLogger::udivError()) { char sign1 = varsign[tok->tokAt(1)->varId()]; - if(sign1 == 'u') + if (sign1 == 'u') { udivError(tok->next()); } } } - else if(Token::Match(tok, "[([=*/+-,] %num% / %var%")) + else if (Token::Match(tok, "[([=*/+-,] %num% / %var%")) { - if(tok->strAt(1)[0] == '-' && ErrorLogger::udivError()) + if (tok->strAt(1)[0] == '-' && ErrorLogger::udivError()) { char sign2 = varsign[tok->tokAt(3)->varId()]; - if(sign2 == 'u') + if (sign2 == 'u') { udivError(tok->next()); } @@ -377,18 +377,18 @@ void CheckOther::checkUnsignedDivision() void CheckOther::unreachableCode() { const Token *tok = _tokenizer->tokens(); - while((tok = Token::findmatch(tok, "[;{}] return"))) + while ((tok = Token::findmatch(tok, "[;{}] return"))) { // Goto the 'return' token tok = tok->next(); // Locate the end of the 'return' statement - while(tok && tok->str() != ";") + while (tok && tok->str() != ";") tok = tok->next(); - while(tok && tok->next() && tok->next()->str() == ";") + while (tok && tok->next() && tok->next()->str() == ";") tok = tok->next(); - if(!tok) + if (!tok) break; // If there is a statement below the return it is unreachable @@ -397,7 +397,7 @@ void CheckOther::unreachableCode() !Token::Match(tok, "; %var% :") && !Token::simpleMatch(tok, "; break")) */ - if(Token::simpleMatch(tok, "; break")) + if (Token::simpleMatch(tok, "; break")) { unreachableCodeError(tok->next()); } @@ -465,10 +465,10 @@ public: void CheckOther::functionVariableUsage() { // Parse all executing scopes.. - for(const Token *token = Token::findmatch(_tokenizer->tokens(), ") const| {"); token;) + for (const Token *token = Token::findmatch(_tokenizer->tokens(), ") const| {"); token;) { // goto "{" - while(token->str() != "{") + while (token->str() != "{") token = token->next(); // First token for the current scope.. @@ -481,93 +481,93 @@ void CheckOther::functionVariableUsage() std::map varUsage; unsigned int indentlevel = 0; - for(const Token *tok = tok1; tok; tok = tok->next()) + for (const Token *tok = tok1; tok; tok = tok->next()) { - if(tok->str() == "{") + if (tok->str() == "{") ++indentlevel; - else if(tok->str() == "}") + else if (tok->str() == "}") { - if(indentlevel <= 1) + if (indentlevel <= 1) break; --indentlevel; } - else if(Token::Match(tok, "struct|union|class {") || - Token::Match(tok, "struct|union|class %type% {")) + else if (Token::Match(tok, "struct|union|class {") || + Token::Match(tok, "struct|union|class %type% {")) { - while(tok->str() != "{") + while (tok->str() != "{") tok = tok->next(); tok = tok->link(); - if(! tok) + if (! tok) break; } - if(Token::Match(tok, "[;{}] asm ( ) ;")) + if (Token::Match(tok, "[;{}] asm ( ) ;")) { varUsage.clear(); break; } - if(Token::Match(tok, "[;{}] %type% %var% ;|=") && tok->next()->isStandardType()) + if (Token::Match(tok, "[;{}] %type% %var% ;|=") && tok->next()->isStandardType()) varUsage[tok->strAt(2)].declare = true; - else if(Token::Match(tok, "[;{}] %type% * %var% ;|=") && tok->next()->isStandardType()) + else if (Token::Match(tok, "[;{}] %type% * %var% ;|=") && tok->next()->isStandardType()) varUsage[tok->strAt(3)].declare = true; - else if(Token::Match(tok, "delete|return %var%")) + else if (Token::Match(tok, "delete|return %var%")) varUsage[tok->strAt(1)].read = true; - else if(Token::Match(tok, "%var% =")) + else if (Token::Match(tok, "%var% =")) varUsage[tok->str()].write = true; - else if(Token::Match(tok, "else %var% =")) + else if (Token::Match(tok, "else %var% =")) varUsage[ tok->strAt(1)].write = true; - else if(Token::Match(tok, ">>|& %var%")) + else if (Token::Match(tok, ">>|& %var%")) varUsage[ tok->strAt(1)].use(); // use = read + write - else if(Token::Match(tok, "[(,] %var% [,)]")) + else if (Token::Match(tok, "[(,] %var% [,)]")) varUsage[ tok->strAt(1)].use(); // use = read + write - else if((Token::Match(tok, "[(=&!]") || isOp(tok)) && Token::Match(tok->next(), "%var%")) + else if ((Token::Match(tok, "[(=&!]") || isOp(tok)) && Token::Match(tok->next(), "%var%")) varUsage[ tok->strAt(1)].read = true; - else if(Token::Match(tok, "-=|+=|*=|/=|&=|^= %var%") || Token::Match(tok, "|= %var%")) + else if (Token::Match(tok, "-=|+=|*=|/=|&=|^= %var%") || Token::Match(tok, "|= %var%")) varUsage[ tok->strAt(1)].read = true; - else if(Token::Match(tok, "%var%") && (tok->next()->str() == ")" || isOp(tok->next()))) + else if (Token::Match(tok, "%var%") && (tok->next()->str() == ")" || isOp(tok->next()))) varUsage[ tok->str()].read = true; - else if(Token::Match(tok, "; %var% ;")) + else if (Token::Match(tok, "; %var% ;")) varUsage[ tok->strAt(1)].read = true; - else if(Token::Match(tok, "++|-- %var%") || - Token::Match(tok, "%var% ++|--")) + else if (Token::Match(tok, "++|-- %var%") || + Token::Match(tok, "%var% ++|--")) varUsage[tok->strAt(1)].use(); } // Check usage of all variables in the current scope.. - for(std::map::const_iterator it = varUsage.begin(); it != varUsage.end(); ++it) + for (std::map::const_iterator it = varUsage.begin(); it != varUsage.end(); ++it) { const std::string &varname = it->first; const VariableUsage &usage = it->second; - if(!std::isalpha(varname[0])) + if (!std::isalpha(varname[0])) continue; - if(!(usage.declare)) + if (!(usage.declare)) continue; - if(usage.unused()) + if (usage.unused()) { unusedVariableError(tok1, varname); } - else if(!(usage.read)) + else if (!(usage.read)) { unreadVariableError(tok1, varname); } - else if(!(usage.write)) + else if (!(usage.write)) { unassignedVariableError(tok1, varname); } @@ -604,69 +604,69 @@ void CheckOther::checkVariableScope() // Walk through all tokens.. bool func = false; int indentlevel = 0; - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { // Skip class and struct declarations.. - if((tok->str() == "class") || (tok->str() == "struct")) + if ((tok->str() == "class") || (tok->str() == "struct")) { - for(const Token *tok2 = tok; tok2; tok2 = tok2->next()) + for (const Token *tok2 = tok; tok2; tok2 = tok2->next()) { - if(tok2->str() == "{") + if (tok2->str() == "{") { tok = tok2->link(); break; } - if(Token::Match(tok2, "[,);]")) + if (Token::Match(tok2, "[,);]")) { break; } } - if(! tok) + if (! tok) break; } - else if(tok->str() == "{") + else if (tok->str() == "{") { ++indentlevel; } - else if(tok->str() == "}") + else if (tok->str() == "}") { --indentlevel; - if(indentlevel == 0) + if (indentlevel == 0) func = false; } - if(indentlevel == 0 && Token::simpleMatch(tok, ") {")) + if (indentlevel == 0 && Token::simpleMatch(tok, ") {")) { func = true; } - if(indentlevel > 0 && func && Token::Match(tok, "[{};]")) + if (indentlevel > 0 && func && Token::Match(tok, "[{};]")) { // First token of statement.. const Token *tok1 = tok->next(); - if(! tok1) + if (! tok1) continue; - if((tok1->str() == "return") || - (tok1->str() == "throw") || - (tok1->str() == "delete") || - (tok1->str() == "goto") || - (tok1->str() == "else")) + if ((tok1->str() == "return") || + (tok1->str() == "throw") || + (tok1->str() == "delete") || + (tok1->str() == "goto") || + (tok1->str() == "else")) continue; // Variable declaration? - if(Token::Match(tok1, "%type% %var% ; %var% = %num% ;")) + if (Token::Match(tok1, "%type% %var% ; %var% = %num% ;")) { // Tokenizer modify "int i = 0;" to "int i; i = 0;", // so to handle this situation we just skip // initialization (see ticket #272). const unsigned int firstVarId = tok1->next()->varId(); const unsigned int secondVarId = tok1->tokAt(3)->varId(); - if(firstVarId > 0 && firstVarId == secondVarId) + if (firstVarId > 0 && firstVarId == secondVarId) { lookupVar(tok1->tokAt(6), tok1->strAt(1)); } } - else if(Token::Match(tok1, "%type% %var% [;=]")) + else if (Token::Match(tok1, "%type% %var% [;=]")) { lookupVar(tok1, tok1->strAt(1)); } @@ -681,7 +681,7 @@ void CheckOther::lookupVar(const Token *tok1, const std::string &varname) const Token *tok = tok1; // Skip the variable declaration.. - while(tok && tok->str() != ";") + while (tok && tok->str() != ";") tok = tok->next(); // Check if the variable is used in this indentlevel.. @@ -690,70 +690,70 @@ void CheckOther::lookupVar(const Token *tok1, const std::string &varname) int indentlevel = 0; int parlevel = 0; bool for_or_while = false; // is sub-scope a "for/while/etc". anything that is not "if" - while(tok) + while (tok) { - if(tok->str() == "{") + if (tok->str() == "{") { ++indentlevel; } - else if(tok->str() == "}") + else if (tok->str() == "}") { - if(indentlevel == 0) + if (indentlevel == 0) break; --indentlevel; - if(indentlevel == 0) + if (indentlevel == 0) { - if(for_or_while && used2) + if (for_or_while && used2) return; used2 |= used1; used1 = false; } } - else if(tok->str() == "(") + else if (tok->str() == "(") { ++parlevel; } - else if(tok->str() == ")") + else if (tok->str() == ")") { --parlevel; } // Bail out if references are used - else if(Token::simpleMatch(tok, (std::string("& ") + varname).c_str())) + else if (Token::simpleMatch(tok, (std::string("& ") + varname).c_str())) { return; } - else if(tok->str() == varname) + else if (tok->str() == varname) { - if(indentlevel == 0) + if (indentlevel == 0) return; used1 = true; - if(for_or_while && !Token::simpleMatch(tok->next(), "=")) + if (for_or_while && !Token::simpleMatch(tok->next(), "=")) used2 = true; - if(used1 && used2) + if (used1 && used2) return; } - else if(indentlevel == 0) + else if (indentlevel == 0) { // %unknown% ( %any% ) { // If %unknown% is anything except if, we assume // that it is a for or while loop or a macro hiding either one - if(Token::simpleMatch(tok->next(), "(") && - Token::simpleMatch(tok->next()->link(), ") {")) + if (Token::simpleMatch(tok->next(), "(") && + Token::simpleMatch(tok->next()->link(), ") {")) { - if(tok->str() != "if") + if (tok->str() != "if") for_or_while = true; } - if(Token::simpleMatch(tok, "do {")) + if (Token::simpleMatch(tok, "do {")) for_or_while = true; - if(parlevel == 0 && (tok->str() == ";")) + if (parlevel == 0 && (tok->str() == ";")) for_or_while = false; } @@ -763,7 +763,7 @@ void CheckOther::lookupVar(const Token *tok1, const std::string &varname) // Warning if this variable: // * not used in this indentlevel // * used in lower indentlevel - if(used1 || used2) + if (used1 || used2) variableScopeError(tok1, varname); } //--------------------------------------------------------------------------- @@ -775,48 +775,48 @@ void CheckOther::lookupVar(const Token *tok1, const std::string &varname) void CheckOther::checkConstantFunctionParameter() { - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { - if(Token::Match(tok, "[,(] const std :: %type% %var% [,)]")) + if (Token::Match(tok, "[,(] const std :: %type% %var% [,)]")) { passedByValueError(tok, tok->strAt(5)); } - else if(Token::Match(tok, "[,(] const std :: %type% < %type% > %var% [,)]")) + else if (Token::Match(tok, "[,(] const std :: %type% < %type% > %var% [,)]")) { passedByValueError(tok, tok->strAt(8)); } - else if(Token::Match(tok, "[,(] const std :: %type% < std :: %type% > %var% [,)]")) + else if (Token::Match(tok, "[,(] const std :: %type% < std :: %type% > %var% [,)]")) { passedByValueError(tok, tok->strAt(10)); } - else if(Token::Match(tok, "[,(] const std :: %type% < std :: %type% , std :: %type% > %var% [,)]")) + else if (Token::Match(tok, "[,(] const std :: %type% < std :: %type% , std :: %type% > %var% [,)]")) { passedByValueError(tok, tok->strAt(14)); } - else if(Token::Match(tok, "[,(] const std :: %type% < %type% , std :: %type% > %var% [,)]")) + else if (Token::Match(tok, "[,(] const std :: %type% < %type% , std :: %type% > %var% [,)]")) { passedByValueError(tok, tok->strAt(12)); } - else if(Token::Match(tok, "[,(] const std :: %type% < std :: %type% , %type% > %var% [,)]")) + else if (Token::Match(tok, "[,(] const std :: %type% < std :: %type% , %type% > %var% [,)]")) { passedByValueError(tok, tok->strAt(12)); } - else if(Token::Match(tok, "[,(] const std :: %type% < %type% , %type% > %var% [,)]")) + else if (Token::Match(tok, "[,(] const std :: %type% < %type% , %type% > %var% [,)]")) { passedByValueError(tok, tok->strAt(10)); } - else if(Token::Match(tok, "[,(] const %type% %var% [,)]")) + else if (Token::Match(tok, "[,(] const %type% %var% [,)]")) { // Check if type is a struct or class. const std::string pattern(std::string("class|struct ") + tok->strAt(2)); - if(Token::findmatch(_tokenizer->tokens(), pattern.c_str())) + if (Token::findmatch(_tokenizer->tokens(), pattern.c_str())) { passedByValueError(tok, tok->strAt(3)); } @@ -833,63 +833,63 @@ void CheckOther::checkConstantFunctionParameter() void CheckOther::checkStructMemberUsage() { std::string structname; - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { - if(tok->fileIndex() != 0) + if (tok->fileIndex() != 0) continue; - if(Token::Match(tok, "struct|union %type% {")) + if (Token::Match(tok, "struct|union %type% {")) { structname = tok->strAt(1); // Bail out if struct/union contain any functions - for(const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) + for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) { - if(tok2->str() == "(") + if (tok2->str() == "(") { structname = ""; break; } - if(tok2->str() == "}") + if (tok2->str() == "}") break; } // Bail out if some data is casted to struct.. const std::string s("( struct| " + tok->next()->str() + " * ) & %var% ["); - if(Token::findmatch(tok, s.c_str())) + if (Token::findmatch(tok, s.c_str())) structname = ""; } - if(tok->str() == "}") + if (tok->str() == "}") structname = ""; - if(!structname.empty() && Token::Match(tok, "[{;]")) + if (!structname.empty() && Token::Match(tok, "[{;]")) { std::string varname; - if(Token::Match(tok->next(), "%type% %var% [;[]")) + if (Token::Match(tok->next(), "%type% %var% [;[]")) varname = tok->strAt(2); - else if(Token::Match(tok->next(), "%type% %type% %var% [;[]")) + else if (Token::Match(tok->next(), "%type% %type% %var% [;[]")) varname = tok->strAt(3); - else if(Token::Match(tok->next(), "%type% * %var% [;[]")) + else if (Token::Match(tok->next(), "%type% * %var% [;[]")) varname = tok->strAt(3); - else if(Token::Match(tok->next(), "%type% %type% * %var% [;[]")) + else if (Token::Match(tok->next(), "%type% %type% * %var% [;[]")) varname = tok->strAt(4); else continue; const std::string usagePattern(". " + varname); bool used = false; - for(const Token *tok2 = _tokenizer->tokens(); tok2; tok2 = tok2->next()) + for (const Token *tok2 = _tokenizer->tokens(); tok2; tok2 = tok2->next()) { - if(Token::simpleMatch(tok2, usagePattern.c_str())) + if (Token::simpleMatch(tok2, usagePattern.c_str())) { used = true; break; } } - if(! used) + if (! used) { unusedStructMemberError(tok->next(), structname, varname); } @@ -907,61 +907,61 @@ void CheckOther::checkStructMemberUsage() void CheckOther::checkCharVariable() { - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { // Declaring the variable.. - if(Token::Match(tok, "[{};(,] char %var% [;=,)]")) + if (Token::Match(tok, "[{};(,] char %var% [;=,)]")) { // Check for unsigned char - if(tok->tokAt(1)->isUnsigned()) + if (tok->tokAt(1)->isUnsigned()) continue; // Set tok to point to the variable name tok = tok->tokAt(2); - if(tok->str() == "char") + if (tok->str() == "char") tok = tok->next(); // Check usage of char variable.. int indentlevel = 0; - for(const Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) + for (const Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) { - if(tok2->str() == "{") + if (tok2->str() == "{") ++indentlevel; - else if(tok2->str() == "}") + else if (tok2->str() == "}") { --indentlevel; - if(indentlevel <= 0) + if (indentlevel <= 0) break; } - else if(tok2->str() == "return") + else if (tok2->str() == "return") continue; std::string temp = "%var% [ " + tok->str() + " ]"; - if((tok2->str() != ".") && Token::Match(tok2->next(), temp.c_str())) + if ((tok2->str() != ".") && Token::Match(tok2->next(), temp.c_str())) { charArrayIndexError(tok2->next()); break; } - if(Token::Match(tok2, "[;{}] %var% = %any% [&|] %any% ;")) + if (Token::Match(tok2, "[;{}] %var% = %any% [&|] %any% ;")) { // is the char variable used in the calculation? - if(tok2->tokAt(3)->varId() != tok->varId() && tok2->tokAt(5)->varId() != tok->varId()) + if (tok2->tokAt(3)->varId() != tok->varId() && tok2->tokAt(5)->varId() != tok->varId()) continue; // it's ok with a bitwise and where the other operand is 0xff or less.. - if(std::string(tok2->strAt(4)) == "&") + if (std::string(tok2->strAt(4)) == "&") { - if(tok2->tokAt(3)->isNumber() && MathLib::isGreater("0x100", tok2->strAt(3))) + if (tok2->tokAt(3)->isNumber() && MathLib::isGreater("0x100", tok2->strAt(3))) continue; - if(tok2->tokAt(5)->isNumber() && MathLib::isGreater("0x100", tok2->strAt(5))) + if (tok2->tokAt(5)->isNumber() && MathLib::isGreater("0x100", tok2->strAt(5))) continue; } // is the result stored in a short|int|long? - if(!Token::findmatch(_tokenizer->tokens(), "short|int|long %varid%", tok2->next()->varId())) + if (!Token::findmatch(_tokenizer->tokens(), "short|int|long %varid%", tok2->next()->varId())) continue; // This is an error.. @@ -987,48 +987,48 @@ void CheckOther::checkIncompleteStatement() { int parlevel = 0; - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { - if(tok->str() == "(") + if (tok->str() == "(") ++parlevel; - else if(tok->str() == ")") + else if (tok->str() == ")") --parlevel; - if(parlevel != 0) + if (parlevel != 0) continue; - if(Token::simpleMatch(tok, "= {")) + if (Token::simpleMatch(tok, "= {")) { /* We are in an assignment, so it's not a statement. * Skip until ";" */ - while(tok->str() != ";") + while (tok->str() != ";") { int level = 0; do { - if(tok->str() == "(" || tok->str() == "{") + if (tok->str() == "(" || tok->str() == "{") ++level; - else if(tok->str() == ")" || tok->str() == "}") + else if (tok->str() == ")" || tok->str() == "}") --level; tok = tok->next(); - if(tok == NULL) + if (tok == NULL) return; } - while(level > 0); + while (level > 0); } continue; } - if(Token::Match(tok, "[;{}] %str%") && !Token::Match(tok->tokAt(2), "[,}]")) + if (Token::Match(tok, "[;{}] %str%") && !Token::Match(tok->tokAt(2), "[,}]")) { constStatementError(tok->next(), "string"); } - if(Token::Match(tok, "[;{}] %num%") && !Token::Match(tok->tokAt(2), "[,}]")) + if (Token::Match(tok, "[;{}] %num%") && !Token::Match(tok->tokAt(2), "[,}]")) { constStatementError(tok->next(), "numeric"); } @@ -1049,27 +1049,27 @@ void CheckOther::strPlusChar() { bool charVars[10000] = {0}; - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { // Declaring char variable.. - if(Token::Match(tok, "char|int|short %var% [;=]")) + if (Token::Match(tok, "char|int|short %var% [;=]")) { unsigned int varid = tok->next()->varId(); - if(varid > 0 && varid < 10000) + if (varid > 0 && varid < 10000) charVars[varid] = true; } // - else if(Token::Match(tok, "[=(] %str% + %any%")) + else if (Token::Match(tok, "[=(] %str% + %any%")) { // char constant.. const std::string s = tok->strAt(3); - if(s[0] == '\'') + if (s[0] == '\'') strPlusChar(tok->next()); // char variable.. unsigned int varid = tok->tokAt(3)->varId(); - if(varid > 0 && varid < 10000 && charVars[varid]) + if (varid > 0 && varid < 10000 && charVars[varid]) strPlusChar(tok->next()); } } @@ -1079,49 +1079,49 @@ void CheckOther::strPlusChar() void CheckOther::nullPointerAfterLoop() { // Locate insufficient null-pointer handling after loop - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { - if(! Token::Match(tok, "while ( %var% )")) + if (! Token::Match(tok, "while ( %var% )")) continue; const unsigned int varid(tok->tokAt(2)->varId()); - if(varid == 0) + if (varid == 0) continue; const std::string varname(tok->strAt(2)); // Locate the end of the while loop.. const Token *tok2 = tok->tokAt(4); - if(tok2->str() == "{") + if (tok2->str() == "{") tok2 = tok2->link(); else { - while(tok2 && tok2->str() != ";") + while (tok2 && tok2->str() != ";") tok2 = tok2->next(); } // Goto next token - if(tok2) + if (tok2) tok2 = tok2->next(); // Check if the variable is dereferenced.. - while(tok2) + while (tok2) { - if(tok2->str() == "{" || tok2->str() == "}" || tok2->str() == "break") + if (tok2->str() == "{" || tok2->str() == "}" || tok2->str() == "break") break; - if(tok2->varId() == varid) + if (tok2->varId() == varid) { - if(tok2->next()->str() == "." || Token::Match(tok2->next(), "= %varid% .", varid)) + if (tok2->next()->str() == "." || Token::Match(tok2->next(), "= %varid% .", varid)) { // Is this variable a pointer? const Token *tok3 = Token::findmatch(_tokenizer->tokens(), "%type% * %varid% [;)=]", varid); - if(!tok3) + if (!tok3) break; - if(!tok3->previous() || - Token::Match(tok3->previous(), "[({};]") || - tok3->previous()->isName()) + if (!tok3->previous() || + Token::Match(tok3->previous(), "[({};]") || + tok3->previous()->isName()) { nullPointerError(tok2, varname); } @@ -1137,75 +1137,75 @@ void CheckOther::nullPointerAfterLoop() void CheckOther::nullPointerLinkedList() { // looping through items in a linked list in a inner loop.. - for(const Token *tok1 = _tokenizer->tokens(); tok1; tok1 = tok1->next()) + for (const Token *tok1 = _tokenizer->tokens(); tok1; tok1 = tok1->next()) { // search for a "for" token.. - if(!Token::simpleMatch(tok1, "for (")) + if (!Token::simpleMatch(tok1, "for (")) continue; - if(!Token::simpleMatch(tok1->next()->link(), ") {")) + if (!Token::simpleMatch(tok1->next()->link(), ") {")) continue; // is there any dereferencing occuring in the for statement.. unsigned int parlevel2 = 1; - for(const Token *tok2 = tok1->tokAt(2); tok2; tok2 = tok2->next()) + for (const Token *tok2 = tok1->tokAt(2); tok2; tok2 = tok2->next()) { // Parantheses.. - if(tok2->str() == "(") + if (tok2->str() == "(") ++parlevel2; - else if(tok2->str() == ")") + else if (tok2->str() == ")") { - if(parlevel2 <= 1) + if (parlevel2 <= 1) break; --parlevel2; } // Dereferencing a variable inside the "for" parantheses.. - else if(Token::Match(tok2, "%var% . %var%")) + else if (Token::Match(tok2, "%var% . %var%")) { const unsigned int varid(tok2->varId()); - if(varid == 0) + if (varid == 0) continue; - if(Token::Match(tok2->tokAt(-2), "%varid% ?", varid)) + if (Token::Match(tok2->tokAt(-2), "%varid% ?", varid)) continue; const std::string varname(tok2->str()); // Check usage of dereferenced variable in the loop.. unsigned int indentlevel3 = 0; - for(const Token *tok3 = tok1->next()->link(); tok3; tok3 = tok3->next()) + for (const Token *tok3 = tok1->next()->link(); tok3; tok3 = tok3->next()) { - if(tok3->str() == "{") + if (tok3->str() == "{") ++indentlevel3; - else if(tok3->str() == "}") + else if (tok3->str() == "}") { - if(indentlevel3 <= 1) + if (indentlevel3 <= 1) break; --indentlevel3; } - else if(Token::Match(tok3, "while ( %varid% &&|)", varid)) + else if (Token::Match(tok3, "while ( %varid% &&|)", varid)) { // Make sure there is a "break" to prevent segmentation faults.. unsigned int indentlevel4 = indentlevel3; - for(const Token *tok4 = tok3->next()->link(); tok4; tok4 = tok4->next()) + for (const Token *tok4 = tok3->next()->link(); tok4; tok4 = tok4->next()) { - if(tok4->str() == "{") + if (tok4->str() == "{") ++indentlevel4; - else if(tok4->str() == "}") + else if (tok4->str() == "}") { - if(indentlevel4 <= 1) + if (indentlevel4 <= 1) { // Is this variable a pointer? const Token *tempTok = Token::findmatch(_tokenizer->tokens(), "%type% * %varid% [;)=]", varid); - if(tempTok) + if (tempTok) nullPointerError(tok1, varname, tok3->linenr()); break; } --indentlevel4; } - else if(tok4->str() == "break") + else if (tok4->str() == "break") break; } } @@ -1219,16 +1219,16 @@ void CheckOther::nullPointerStructByDeRefAndChec() { // Dereferencing a struct pointer and then checking if it's NULL.. - for(const Token *tok1 = _tokenizer->tokens(); tok1; tok1 = tok1->next()) + for (const Token *tok1 = _tokenizer->tokens(); tok1; tok1 = tok1->next()) { - if(Token::Match(tok1, "[{};] %var% = %var% . %var%")) + if (Token::Match(tok1, "[{};] %var% = %var% . %var%")) { - if(std::string(tok1->strAt(1)) == tok1->strAt(3)) + if (std::string(tok1->strAt(1)) == tok1->strAt(3)) continue; tok1 = tok1->tokAt(3); const unsigned int varid1(tok1->varId()); - if(varid1 == 0) + if (varid1 == 0) continue; const std::string varname(tok1->str()); @@ -1236,58 +1236,58 @@ void CheckOther::nullPointerStructByDeRefAndChec() // Checking if the struct pointer is non-null before the assignment.. { const Token *tok2 = _tokenizer->tokens(); - while(tok2) + while (tok2) { - if(tok2 == tok1) + if (tok2 == tok1) break; - if(Token::Match(tok2, "if|while ( !| %varid% )", varid1)) + if (Token::Match(tok2, "if|while ( !| %varid% )", varid1)) break; tok2 = tok2->next(); } - if(tok2 != tok1) + if (tok2 != tok1) continue; } unsigned int indentlevel2 = 0; - for(const Token *tok2 = tok1->tokAt(3); tok2; tok2 = tok2->next()) + for (const Token *tok2 = tok1->tokAt(3); tok2; tok2 = tok2->next()) { - if(tok2->str() == "{") + if (tok2->str() == "{") ++indentlevel2; - else if(tok2->str() == "}") + else if (tok2->str() == "}") { - if(indentlevel2 == 0) + if (indentlevel2 == 0) break; --indentlevel2; } // goto destination.. - else if(tok2->isName() && Token::simpleMatch(tok2->next(), ":")) + else if (tok2->isName() && Token::simpleMatch(tok2->next(), ":")) break; // Reassignment of the struct - else if(tok2->varId() == varid1) + else if (tok2->varId() == varid1) { - if(tok2->next()->str() == "=") + if (tok2->next()->str() == "=") break; - if(Token::Match(tok2->tokAt(-2), "[,(] &")) + if (Token::Match(tok2->tokAt(-2), "[,(] &")) break; } // Loop.. /** @todo don't bail out if the variable is not used in the loop */ - else if(tok2->str() == "do") + else if (tok2->str() == "do") break; // return at base level => stop checking - else if(indentlevel2 == 0 && tok2->str() == "return") + else if (indentlevel2 == 0 && tok2->str() == "return") break; - else if(Token::Match(tok2, "if ( !| %varid% )", varid1)) + else if (Token::Match(tok2, "if ( !| %varid% )", varid1)) { // Is this variable a pointer? const Token *tempTok = Token::findmatch(_tokenizer->tokens(), "%type% * %varid% [;)=]", varid1); - if(tempTok) + if (tempTok) nullPointerError(tok1, varname, tok2->linenr()); break; } @@ -1300,45 +1300,45 @@ void CheckOther::nullPointerStructByDeRefAndChec() void CheckOther::nullPointerByDeRefAndChec() { // Dereferencing a pointer and then checking if it's NULL.. - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { - if(tok->str() == "if" && Token::Match(tok->previous(), "; if ( ! %var% )")) + if (tok->str() == "if" && Token::Match(tok->previous(), "; if ( ! %var% )")) { const unsigned int varid(tok->tokAt(3)->varId()); - if(varid == 0) + if (varid == 0) continue; const std::string varname(tok->strAt(3)); const Token *decltok = Token::findmatch(_tokenizer->tokens(), "%varid%", varid); - if(!Token::Match(decltok->tokAt(-3), "[;,(] %var% *")) + if (!Token::Match(decltok->tokAt(-3), "[;,(] %var% *")) continue; - for(const Token *tok1 = tok->previous(); tok1 && tok1 != decltok; tok1 = tok1->previous()) + for (const Token *tok1 = tok->previous(); tok1 && tok1 != decltok; tok1 = tok1->previous()) { - if(tok1->varId() == varid) + if (tok1->varId() == varid) { - if(Token::Match(tok1->tokAt(-2), "[=;{}] *")) + if (Token::Match(tok1->tokAt(-2), "[=;{}] *")) { nullPointerError(tok1, varname); break; } - else if(tok1->previous() && tok1->previous()->str() == "&") + else if (tok1->previous() && tok1->previous()->str() == "&") { break; } - else if(tok1->next() && tok1->next()->str() == "=") + else if (tok1->next() && tok1->next()->str() == "=") { break; } } - else if(tok1->str() == "{" || - tok1->str() == "}") + else if (tok1->str() == "{" || + tok1->str() == "}") break; // goto destination.. - else if(tok1->isName() && Token::simpleMatch(tok1->next(), ":")) + else if (tok1->isName() && Token::simpleMatch(tok1->next(), ":")) break; } } @@ -1368,7 +1368,7 @@ static void parseFunctionCall(const Token &tok, std::list &var, u // standard functions that dereference first parameter.. // both uninitialized data and null pointers are invalid. static std::set functionNames1; - if(functionNames1.empty()) + if (functionNames1.empty()) { functionNames1.insert("memchr"); functionNames1.insert("memcmp"); @@ -1387,7 +1387,7 @@ static void parseFunctionCall(const Token &tok, std::list &var, u // standard functions that dereference second parameter.. // both uninitialized data and null pointers are invalid. static std::set functionNames2; - if(functionNames2.empty()) + if (functionNames2.empty()) { functionNames2.insert("memcmp"); functionNames2.insert("memcpy"); @@ -1402,20 +1402,20 @@ static void parseFunctionCall(const Token &tok, std::list &var, u } // 1st parameter.. - if(Token::Match(&tok, "%var% ( %var% ,|)") && tok.tokAt(2)->varId() > 0) + if (Token::Match(&tok, "%var% ( %var% ,|)") && tok.tokAt(2)->varId() > 0) { - if(functionNames1.find(tok.str()) != functionNames1.end()) + if (functionNames1.find(tok.str()) != functionNames1.end()) var.push_back(tok.tokAt(2)); - else if(value == 0 && Token::Match(&tok, "memchr|memcmp|memcpy|memmove|memset|strcpy|printf|sprintf|snprintf")) + else if (value == 0 && Token::Match(&tok, "memchr|memcmp|memcpy|memmove|memset|strcpy|printf|sprintf|snprintf")) var.push_back(tok.tokAt(2)); - else if(Token::simpleMatch(&tok, "fflush")) + else if (Token::simpleMatch(&tok, "fflush")) var.push_back(tok.tokAt(2)); } // 2nd parameter.. - if(Token::Match(&tok, "%var% ( %any% , %var% ,|)") && tok.tokAt(4)->varId() > 0) + if (Token::Match(&tok, "%var% ( %any% , %var% ,|)") && tok.tokAt(4)->varId() > 0) { - if(functionNames2.find(tok.str()) != functionNames2.end()) + if (functionNames2.find(tok.str()) != functionNames2.end()) var.push_back(tok.tokAt(4)); } } @@ -1440,9 +1440,9 @@ public: private: /** Create checking of specific variable: */ CheckNullpointer(Check *c, const unsigned int id, const std::string &name) - : ExecutionPath(c, id), - varname(name), - null(false) + : ExecutionPath(c, id), + varname(name), + null(false) { } @@ -1465,10 +1465,10 @@ private: static void setnull(std::list &checks, const unsigned int varid) { std::list::iterator it; - for(it = checks.begin(); it != checks.end(); ++it) + for (it = checks.begin(); it != checks.end(); ++it) { CheckNullpointer *c = dynamic_cast(*it); - if(c && c->varId == varid) + if (c && c->varId == varid) c->null = true; } } @@ -1479,14 +1479,14 @@ private: const unsigned int varid(tok->varId()); std::list::iterator it; - for(it = checks.begin(); it != checks.end(); ++it) + for (it = checks.begin(); it != checks.end(); ++it) { CheckNullpointer *c = dynamic_cast(*it); - if(c && c->varId == varid && c->null) + if (c && c->varId == varid && c->null) { foundError = true; CheckOther *checkOther = dynamic_cast(c->owner); - if(checkOther) + if (checkOther) { checkOther->nullPointerError(tok, c->varname); break; @@ -1498,34 +1498,34 @@ private: /** parse tokens */ const Token *parse(const Token &tok, bool &foundError, std::list &checks) const { - if(Token::Match(tok.previous(), "[;{}] const| %type% * %var% ;")) + if (Token::Match(tok.previous(), "[;{}] const| %type% * %var% ;")) { const Token * vartok = tok.tokAt(2); - if(tok.str() == "const") + if (tok.str() == "const") vartok = vartok->next(); - if(vartok->varId() != 0) + if (vartok->varId() != 0) checks.push_back(new CheckNullpointer(owner, vartok->varId(), vartok->str())); return vartok->next(); } // Template pointer variable.. - if(Token::Match(tok.previous(), "[;{}] %type% ::|<")) + if (Token::Match(tok.previous(), "[;{}] %type% ::|<")) { const Token * vartok = &tok; - while(Token::Match(vartok, "%type% ::")) + while (Token::Match(vartok, "%type% ::")) vartok = vartok->tokAt(2); - if(Token::Match(vartok, "%type% < %type%")) + if (Token::Match(vartok, "%type% < %type%")) { vartok = vartok->tokAt(3); - while(vartok && (vartok->str() == "*" || vartok->isName())) + while (vartok && (vartok->str() == "*" || vartok->isName())) vartok = vartok->next(); - if(Token::Match(vartok, "> * %var% ;|=")) + if (Token::Match(vartok, "> * %var% ;|=")) { vartok = vartok->tokAt(2); checks.push_back(new CheckNullpointer(owner, vartok->varId(), vartok->str())); - if(Token::simpleMatch(vartok->next(), "= 0 ;")) + if (Token::simpleMatch(vartok->next(), "= 0 ;")) setnull(checks, vartok->varId()); return vartok->next(); } @@ -1533,45 +1533,45 @@ private: } - if(Token::Match(&tok, "%var% (")) + if (Token::Match(&tok, "%var% (")) { - if(tok.str() == "sizeof") + if (tok.str() == "sizeof") return tok.next()->link(); // parse usage.. std::list var; parseFunctionCall(tok, var, 0); - for(std::list::const_iterator it = var.begin(); it != var.end(); ++it) + for (std::list::const_iterator it = var.begin(); it != var.end(); ++it) dereference(foundError, checks, *it); } - if(tok.varId() != 0) + if (tok.varId() != 0) { - if(Token::Match(tok.previous(), "[;{}=] %var% = 0 ;")) + if (Token::Match(tok.previous(), "[;{}=] %var% = 0 ;")) setnull(checks, tok.varId()); - else if(Token::Match(tok.tokAt(-2), "[;{}=+-/(,] * %var%")) + else if (Token::Match(tok.tokAt(-2), "[;{}=+-/(,] * %var%")) dereference(foundError, checks, &tok); - else if(Token::Match(tok.tokAt(-2), "return * %var%")) + else if (Token::Match(tok.tokAt(-2), "return * %var%")) dereference(foundError, checks, &tok); - else if(!Token::simpleMatch(tok.tokAt(-2), "& (") && Token::Match(tok.next(), ". %var%")) + else if (!Token::simpleMatch(tok.tokAt(-2), "& (") && Token::Match(tok.next(), ". %var%")) dereference(foundError, checks, &tok); - else if(Token::Match(tok.previous(), "[;{}=+-/(,] %var% [ %any% ]")) + else if (Token::Match(tok.previous(), "[;{}=+-/(,] %var% [ %any% ]")) dereference(foundError, checks, &tok); - else if(Token::Match(tok.previous(), "return %var% [ %any% ]")) + else if (Token::Match(tok.previous(), "return %var% [ %any% ]")) dereference(foundError, checks, &tok); - else if(Token::Match(&tok, "%var% (")) + else if (Token::Match(&tok, "%var% (")) dereference(foundError, checks, &tok); else bailOutVar(checks, tok.varId()); } - if(Token::simpleMatch(&tok, "* 0")) + if (Token::simpleMatch(&tok, "* 0")) { - if(Token::Match(tok.previous(), "[;{}=+-/(,]") || - Token::Match(tok.previous(), "return|<<")) + if (Token::Match(tok.previous(), "[;{}=+-/(,]") || + Token::Match(tok.previous(), "return|<<")) { CheckOther *checkOther = dynamic_cast(owner); - if(checkOther) + if (checkOther) { checkOther->nullPointerError(&tok); foundError = true; @@ -1585,12 +1585,12 @@ private: /** parse condition. @sa ExecutionPath::parseCondition */ bool parseCondition(const Token &tok, std::list &checks) { - if(Token::Match(&tok, "!| %var% (")) + if (Token::Match(&tok, "!| %var% (")) { bool foundError = false; std::list var; parseFunctionCall(tok.str() == "!" ? *tok.next() : tok, var, 0); - for(std::list::const_iterator it = var.begin(); it != var.end(); ++it) + for (std::list::const_iterator it = var.begin(); it != var.end(); ++it) dereference(foundError, checks, *it); } @@ -1607,7 +1607,7 @@ class CheckUninitVar : public ExecutionPath public: /** Startup constructor */ CheckUninitVar(Check *c) - : ExecutionPath(c, 0), pointer(false), array(false), alloc(false), strncpy_(false) + : ExecutionPath(c, 0), pointer(false), array(false), alloc(false), strncpy_(false) { } @@ -1623,7 +1623,7 @@ private: /** internal constructor for creating extra checks */ CheckUninitVar(Check *c, unsigned int v, const std::string &name, bool p, bool a) - : ExecutionPath(c, v), varname(name), pointer(p), array(a), alloc(false), strncpy_(false) + : ExecutionPath(c, v), varname(name), pointer(p), array(a), alloc(false), strncpy_(false) { } @@ -1646,10 +1646,10 @@ private: static void alloc_pointer(std::list &checks, unsigned int varid) { std::list::const_iterator it; - for(it = checks.begin(); it != checks.end(); ++it) + for (it = checks.begin(); it != checks.end(); ++it) { CheckUninitVar *c = dynamic_cast(*it); - if(c && c->varId == varid) + if (c && c->varId == varid) c->alloc = true; } } @@ -1658,16 +1658,16 @@ private: static void init_pointer(bool &foundError, std::list &checks, const Token *tok) { const unsigned int varid(tok->varId()); - if(!varid) + if (!varid) return; std::list::iterator it = checks.begin(); - while(it != checks.end()) + while (it != checks.end()) { CheckUninitVar *c = dynamic_cast(*it); - if(c && c->varId == varid) + if (c && c->varId == varid) { - if(c->alloc || c->array) + if (c->alloc || c->array) { delete c; checks.erase(it++); @@ -1687,19 +1687,19 @@ private: static void dealloc_pointer(bool &foundError, std::list &checks, const Token *tok) { const unsigned int varid(tok->varId()); - if(!varid) + if (!varid) return; std::list::const_iterator it; - for(it = checks.begin(); it != checks.end(); ++it) + for (it = checks.begin(); it != checks.end(); ++it) { CheckUninitVar *c = dynamic_cast(*it); - if(c && c->varId == varid) + if (c && c->varId == varid) { - if(c->pointer && !c->alloc) + if (c->pointer && !c->alloc) { CheckOther *checkOther = dynamic_cast(c->owner); - if(checkOther) + if (checkOther) { foundError = true; checkOther->uninitvarError(tok, c->varname); @@ -1721,20 +1721,20 @@ private: static void pointer_assignment(std::list &checks, const Token *tok1, const Token *tok2) { const unsigned int varid1(tok1->varId()); - if(varid1 == 0) + if (varid1 == 0) return; const unsigned int varid2(tok2->varId()); - if(varid2 == 0) + if (varid2 == 0) return; std::list::const_iterator it; // bail out if first variable is a pointer - for(it = checks.begin(); it != checks.end(); ++it) + for (it = checks.begin(); it != checks.end(); ++it) { CheckUninitVar *c = dynamic_cast(*it); - if(c && c->varId == varid1 && c->pointer) + if (c && c->varId == varid1 && c->pointer) { bailOutVar(checks, varid1); break; @@ -1742,10 +1742,10 @@ private: } // bail out if second variable is a array/pointer - for(it = checks.begin(); it != checks.end(); ++it) + for (it = checks.begin(); it != checks.end(); ++it) { CheckUninitVar *c = dynamic_cast(*it); - if(c && c->varId == varid2 && (c->pointer || c->array)) + if (c && c->varId == varid2 && (c->pointer || c->array)) { bailOutVar(checks, varid2); break; @@ -1758,14 +1758,14 @@ private: static void init_strncpy(std::list &checks, const Token *tok) { const unsigned int varid(tok->varId()); - if(!varid) + if (!varid) return; std::list::const_iterator it; - for(it = checks.begin(); it != checks.end(); ++it) + for (it = checks.begin(); it != checks.end(); ++it) { CheckUninitVar *c = dynamic_cast(*it); - if(c && c->varId == varid) + if (c && c->varId == varid) { c->strncpy_ = true; } @@ -1784,37 +1784,37 @@ private: static void use(bool &foundError, std::list &checks, const Token *tok, const int mode) { const unsigned int varid(tok->varId()); - if(varid == 0) + if (varid == 0) return; std::list::const_iterator it; - for(it = checks.begin(); it != checks.end(); ++it) + for (it = checks.begin(); it != checks.end(); ++it) { CheckUninitVar *c = dynamic_cast(*it); - if(c && c->varId == varid) + if (c && c->varId == varid) { // mode 0 : the variable is used "directly" // example: .. = var; // it is ok to read the address of an uninitialized array. // it is ok to read the address of an allocated pointer - if(mode == 0 && (c->array || (c->pointer && c->alloc))) + if (mode == 0 && (c->array || (c->pointer && c->alloc))) continue; // mode 2 : bad usage of pointer. if it's not a pointer then the usage is ok. // example: ptr->foo(); - if(mode == 2 && !c->pointer) + if (mode == 2 && !c->pointer) continue; // mode 3 : using dead pointer is invalid. - if(mode == 3 && (!c->pointer || c->alloc)) + if (mode == 3 && (!c->pointer || c->alloc)) continue; CheckOther *checkOther = dynamic_cast(c->owner); - if(checkOther) + if (checkOther) { - if(c->strncpy_) + if (c->strncpy_) checkOther->uninitstringError(tok, c->varname); - else if(c->pointer && c->alloc) + else if (c->pointer && c->alloc) checkOther->uninitdataError(tok, c->varname); else checkOther->uninitvarError(tok, c->varname); @@ -1873,18 +1873,18 @@ private: /** declaring a variable */ void declare(std::list &checks, const Token *vartok, const Token &tok, const bool p, const bool a) const { - if(vartok->varId() == 0) + if (vartok->varId() == 0) return; bool isenum = false; - if(!tok.isStandardType()) + if (!tok.isStandardType()) { const std::string pattern("enum " + tok.str()); - for(const Token *tok2 = tok.previous(); tok2; tok2 = tok2->previous()) + for (const Token *tok2 = tok.previous(); tok2; tok2 = tok2->previous()) { - if(tok2->str() != "{") + if (tok2->str() != "{") continue; - if(Token::simpleMatch(tok2->tokAt(-2), pattern.c_str())) + if (Token::simpleMatch(tok2->tokAt(-2), pattern.c_str())) { isenum = true; break; @@ -1893,24 +1893,24 @@ private: } // Suppress warnings if variable in inner scope has same name as variable in outer scope - if(!tok.isStandardType() && !isenum) + if (!tok.isStandardType() && !isenum) { std::set dup; - for(std::list::const_iterator it = checks.begin(); it != checks.end(); ++it) + for (std::list::const_iterator it = checks.begin(); it != checks.end(); ++it) { CheckUninitVar *c = dynamic_cast(*it); - if(c && c->varname == vartok->str() && c->varId != vartok->varId()) + if (c && c->varname == vartok->str() && c->varId != vartok->varId()) dup.insert(c->varId); } - if(!dup.empty()) + if (!dup.empty()) { - for(std::set::const_iterator it = dup.begin(); it != dup.end(); ++it) + for (std::set::const_iterator it = dup.begin(); it != dup.end(); ++it) bailOutVar(checks, *it); return; } } - if(a || p || tok.isStandardType() || isenum) + if (a || p || tok.isStandardType() || isenum) checks.push_back(new CheckUninitVar(owner, vartok->varId(), vartok->str(), p, a)); } @@ -1918,23 +1918,23 @@ private: const Token *parse(const Token &tok, bool &foundError, std::list &checks) const { // Variable declaration.. - if(tok.str() != "return") + if (tok.str() != "return") { - if(Token::Match(&tok, "enum %type% {")) + if (Token::Match(&tok, "enum %type% {")) return tok.tokAt(2)->link(); - if(Token::Match(tok.previous(), "[;{}] %type% *| %var% ;")) + if (Token::Match(tok.previous(), "[;{}] %type% *| %var% ;")) { const Token * vartok = tok.next(); const bool p(vartok->str() == "*"); - if(p) + if (p) vartok = vartok->next(); declare(checks, vartok, tok, p, false); return vartok; } // Variable declaration for array.. - if(Token::Match(tok.previous(), "[;{}] %type% %var% [ %num% ] ;")) + if (Token::Match(tok.previous(), "[;{}] %type% %var% [ %num% ] ;")) { const Token * vartok = tok.next(); declare(checks, vartok, tok, false, true); @@ -1942,17 +1942,17 @@ private: } // Template pointer variable.. - if(Token::Match(tok.previous(), "[;{}] %type% ::|<")) + if (Token::Match(tok.previous(), "[;{}] %type% ::|<")) { const Token * vartok = &tok; - while(Token::Match(vartok, "%type% ::")) + while (Token::Match(vartok, "%type% ::")) vartok = vartok->tokAt(2); - if(Token::Match(vartok, "%type% < %type%")) + if (Token::Match(vartok, "%type% < %type%")) { vartok = vartok->tokAt(3); - while(vartok && (vartok->str() == "*" || vartok->isName())) + while (vartok && (vartok->str() == "*" || vartok->isName())) vartok = vartok->next(); - if(Token::Match(vartok, "> * %var% ;")) + if (Token::Match(vartok, "> * %var% ;")) { declare(checks, vartok->tokAt(2), tok, true, false); return vartok->tokAt(2); @@ -1961,51 +1961,51 @@ private: } } - if(tok.varId()) + if (tok.varId()) { // Used.. - if(Token::Match(tok.previous(), "[[(,+-*/] %var% []),+-*/]")) + if (Token::Match(tok.previous(), "[[(,+-*/] %var% []),+-*/]")) { use(foundError, checks, &tok); return &tok; } - if(Token::Match(tok.previous(), "++|--") || Token::Match(tok.next(), "++|--")) + if (Token::Match(tok.previous(), "++|--") || Token::Match(tok.next(), "++|--")) { use(foundError, checks, &tok); return &tok; } - if(Token::Match(tok.previous(), "[;{}] %var% =")) + if (Token::Match(tok.previous(), "[;{}] %var% =")) { // using same variable rhs? - for(const Token *tok2 = tok.tokAt(2); tok2; tok2 = tok2->next()) + for (const Token *tok2 = tok.tokAt(2); tok2; tok2 = tok2->next()) { - if(Token::Match(tok2, ";|)|=")) + if (Token::Match(tok2, ";|)|=")) break; - if(Token::Match(tok2, "%var% (")) + if (Token::Match(tok2, "%var% (")) break; - if(tok2->varId() && - !Token::Match(tok2->previous(), "&|::") && - !Token::simpleMatch(tok2->next(), "=")) + if (tok2->varId() && + !Token::Match(tok2->previous(), "&|::") && + !Token::simpleMatch(tok2->next(), "=")) use(foundError, checks, tok2); } // pointer aliasing? - if(Token::Match(tok.tokAt(2), "%var% ;")) + if (Token::Match(tok.tokAt(2), "%var% ;")) { pointer_assignment(checks, &tok, tok.tokAt(2)); } } - if(Token::simpleMatch(tok.next(), "(")) + if (Token::simpleMatch(tok.next(), "(")) { use_pointer(foundError, checks, &tok); } - if(Token::Match(tok.tokAt(-2), "[;{}] *")) + if (Token::Match(tok.tokAt(-2), "[;{}] *")) { - if(Token::simpleMatch(tok.next(), "=")) + if (Token::simpleMatch(tok.next(), "=")) init_pointer(foundError, checks, &tok); else use_pointer(foundError, checks, &tok); @@ -2013,63 +2013,63 @@ private: } // += etc - if(Token::Match(tok.previous(), "[;{}]") || Token::Match(tok.tokAt(-2), "[;{}] *")) + if (Token::Match(tok.previous(), "[;{}]") || Token::Match(tok.tokAt(-2), "[;{}] *")) { // goto the equal.. const Token *eq = tok.next(); - if(eq && eq->str() == "[" && eq->link() && eq->link()->next()) + if (eq && eq->str() == "[" && eq->link() && eq->link()->next()) eq = eq->link()->next(); // is it X= - if(Token::Match(eq, "+=|-=|*=|/=|&=|^=") || eq->str() == "|=") + if (Token::Match(eq, "+=|-=|*=|/=|&=|^=") || eq->str() == "|=") { - if(tok.previous()->str() == "*") + if (tok.previous()->str() == "*") use_pointer(foundError, checks, &tok); - else if(tok.next()->str() == "[") + else if (tok.next()->str() == "[") use_array(foundError, checks, &tok); else use(foundError, checks, &tok); } } - if(Token::Match(tok.next(), "= malloc|kmalloc") || Token::simpleMatch(tok.next(), "= new char [")) + if (Token::Match(tok.next(), "= malloc|kmalloc") || Token::simpleMatch(tok.next(), "= new char [")) { alloc_pointer(checks, tok.varId()); - if(tok.tokAt(3)->str() == "(") + if (tok.tokAt(3)->str() == "(") return tok.tokAt(3)->link(); } - else if(Token::simpleMatch(tok.previous(), ">>") || Token::simpleMatch(tok.next(), "=")) + else if (Token::simpleMatch(tok.previous(), ">>") || Token::simpleMatch(tok.next(), "=")) { ExecutionPath::bailOutVar(checks, tok.varId()); return &tok; } - if(Token::simpleMatch(tok.next(), "[")) + if (Token::simpleMatch(tok.next(), "[")) { const Token *tok2 = tok.next()->link(); - if(Token::simpleMatch(tok2 ? tok2->next() : 0, "=")) + if (Token::simpleMatch(tok2 ? tok2->next() : 0, "=")) { ExecutionPath::bailOutVar(checks, tok.varId()); return &tok; } } - if(Token::simpleMatch(tok.previous(), "delete") || - Token::simpleMatch(tok.tokAt(-3), "delete [ ]")) + if (Token::simpleMatch(tok.previous(), "delete") || + Token::simpleMatch(tok.tokAt(-3), "delete [ ]")) { dealloc_pointer(foundError, checks, &tok); return &tok; } } - if(Token::Match(&tok, "%var% (") && uvarFunctions.find(tok.str()) == uvarFunctions.end()) + if (Token::Match(&tok, "%var% (") && uvarFunctions.find(tok.str()) == uvarFunctions.end()) { - if(Token::simpleMatch(&tok, "sizeof (")) + if (Token::simpleMatch(&tok, "sizeof (")) return tok.next()->link(); // deallocate pointer - if(Token::Match(&tok, "free|kfree|fclose ( %var% )")) + if (Token::Match(&tok, "free|kfree|fclose ( %var% )")) { dealloc_pointer(foundError, checks, tok.tokAt(2)); return tok.tokAt(3); @@ -2079,18 +2079,18 @@ private: { std::list var; parseFunctionCall(tok, var, 1); - for(std::list::const_iterator it = var.begin(); it != var.end(); ++it) + for (std::list::const_iterator it = var.begin(); it != var.end(); ++it) use_array(foundError, checks, *it); } // strncpy doesn't 0-terminate first parameter - if(Token::Match(&tok, "strncpy ( %var% ,")) + if (Token::Match(&tok, "strncpy ( %var% ,")) { init_strncpy(checks, tok.tokAt(2)); return tok.next()->link(); } - if(Token::Match(&tok, "asm ( )")) + if (Token::Match(&tok, "asm ( )")) { ExecutionPath::bailOut(checks); return &tok; @@ -2099,28 +2099,28 @@ private: // is the variable passed as a parameter to some function? unsigned int parlevel = 0; std::set bailouts; - for(const Token *tok2 = tok.next(); tok2; tok2 = tok2->next()) + for (const Token *tok2 = tok.next(); tok2; tok2 = tok2->next()) { - if(tok2->str() == "(") + if (tok2->str() == "(") ++parlevel; - else if(tok2->str() == ")") + else if (tok2->str() == ")") { - if(parlevel <= 1) + if (parlevel <= 1) break; --parlevel; } - else if(Token::simpleMatch(tok2, "sizeof (")) + else if (Token::simpleMatch(tok2, "sizeof (")) { tok2 = tok2->next()->link(); - if(!tok2) + if (!tok2) break; } - else if(tok2->varId()) + else if (tok2->varId()) { - if(Token::Match(tok2->tokAt(-2), "[(,] *") || Token::Match(tok2->next(), ". %var%")) + if (Token::Match(tok2->tokAt(-2), "[(,] *") || Token::Match(tok2->next(), ". %var%")) use_dead_pointer(foundError, checks, tok2); // it is possible that the variable is initialized here @@ -2128,28 +2128,28 @@ private: } } - for(std::set::const_iterator it = bailouts.begin(); it != bailouts.end(); ++it) + for (std::set::const_iterator it = bailouts.begin(); it != bailouts.end(); ++it) ExecutionPath::bailOutVar(checks, *it); } // function call via function pointer - if(Token::Match(&tok, "( * %var% ) (")) + if (Token::Match(&tok, "( * %var% ) (")) { // is the variable passed as a parameter to some function? unsigned int parlevel = 0; - for(const Token *tok2 = tok.link()->next(); tok2; tok2 = tok2->next()) + for (const Token *tok2 = tok.link()->next(); tok2; tok2 = tok2->next()) { - if(tok2->str() == "(") + if (tok2->str() == "(") ++parlevel; - else if(tok2->str() == ")") + else if (tok2->str() == ")") { - if(parlevel <= 1) + if (parlevel <= 1) break; --parlevel; } - else if(tok2->varId()) + else if (tok2->varId()) { // it is possible that the variable is initialized here ExecutionPath::bailOutVar(checks, tok2->varId()); @@ -2157,35 +2157,35 @@ private: } } - if(tok.str() == "return") + if (tok.str() == "return") { // Todo: if (!array && .. - if(Token::Match(tok.next(), "%var% ;")) + if (Token::Match(tok.next(), "%var% ;")) { use(foundError, checks, tok.next()); } } - if(tok.varId()) + if (tok.varId()) { - if(Token::simpleMatch(tok.previous(), "=")) + if (Token::simpleMatch(tok.previous(), "=")) { - if(Token::Match(tok.tokAt(-3), "& %var% =")) + if (Token::Match(tok.tokAt(-3), "& %var% =")) { bailOutVar(checks, tok.varId()); return &tok; } - if(!Token::Match(tok.tokAt(-3), ". %var% =")) + if (!Token::Match(tok.tokAt(-3), ". %var% =")) { - if(!Token::Match(tok.tokAt(-3), "[;{}] %var% =")) + if (!Token::Match(tok.tokAt(-3), "[;{}] %var% =")) { use(foundError, checks, &tok); return &tok; } const unsigned int varid2 = tok.tokAt(-2)->varId(); - if(varid2) + if (varid2) { /* const Token *tok2 = Token::findmatch(owner->_tokenizer->tokens(), "%varid%", varid2); @@ -2199,38 +2199,38 @@ private: } } - if(Token::simpleMatch(tok.next(), ".")) + if (Token::simpleMatch(tok.next(), ".")) { const Token *tok2 = tok.next(); - while(Token::Match(tok2, ". %var%")) + while (Token::Match(tok2, ". %var%")) tok2 = tok2->tokAt(2); - if(tok2 && tok2->str() != "=") + if (tok2 && tok2->str() != "=") use_pointer(foundError, checks, &tok); else bailOutVar(checks, tok.varId()); return &tok; } - if(Token::simpleMatch(tok.next(), "[")) + if (Token::simpleMatch(tok.next(), "[")) { ExecutionPath::bailOutVar(checks, tok.varId()); return &tok; } - if(Token::Match(tok.tokAt(-2), "[,(=] *")) + if (Token::Match(tok.tokAt(-2), "[,(=] *")) { use_pointer(foundError, checks, &tok); return &tok; } - if(Token::simpleMatch(tok.previous(), "&")) + if (Token::simpleMatch(tok.previous(), "&")) { ExecutionPath::bailOutVar(checks, tok.varId()); } } // Parse "for" - if(Token::Match(&tok, "[;{}] for (")) + if (Token::Match(&tok, "[;{}] for (")) { // initialized variables std::set varid1; @@ -2240,52 +2240,52 @@ private: const Token *tok2; // parse setup - for(tok2 = tok.tokAt(3); tok2; tok2 = tok2->next()) + for (tok2 = tok.tokAt(3); tok2; tok2 = tok2->next()) { - if(tok2->str() == ";") + if (tok2->str() == ";") break; - if(tok2->varId()) + if (tok2->varId()) varid1.insert(tok2->varId()); } // parse condition - if(Token::Match(tok2, "; %var% <|<=|>=|> %num% ;")) + if (Token::Match(tok2, "; %var% <|<=|>=|> %num% ;")) { // If the variable hasn't been initialized then call "use" - if(varid1.find(tok2->next()->varId()) == varid1.end()) + if (varid1.find(tok2->next()->varId()) == varid1.end()) use(foundError, checks, tok2->next()); } // goto stepcode tok2 = tok2->next(); - while(tok2 && tok2->str() != ";") + while (tok2 && tok2->str() != ";") tok2 = tok2->next(); // parse the stepcode - if(Token::Match(tok2, "; ++|-- %var% ) {") || - Token::Match(tok2, "; %var% ++|-- ) {")) + if (Token::Match(tok2, "; ++|-- %var% ) {") || + Token::Match(tok2, "; %var% ++|-- ) {")) { // get id of variable.. unsigned int varid = tok2->next()->varId(); - if(!varid) + if (!varid) varid = tok2->tokAt(2)->varId(); // Check that the variable hasn't been initialized and // that it isn't initialized in the body.. - if(varid1.find(varid) == varid1.end()) + if (varid1.find(varid) == varid1.end()) { unsigned int indentlevel = 0; - for(const Token *tok3 = tok2->tokAt(5); tok3; tok3 = tok3->next()) + for (const Token *tok3 = tok2->tokAt(5); tok3; tok3 = tok3->next()) { - if(tok3->str() == "{") + if (tok3->str() == "{") ++indentlevel; - else if(tok3->str() == "}") + else if (tok3->str() == "}") { - if(indentlevel == 0) + if (indentlevel == 0) break; --indentlevel; } - if(tok3->varId() == varid) + if (tok3->varId() == varid) { varid = 0; // variable is used.. maybe it's initialized. clear the variable id. break; @@ -2293,11 +2293,11 @@ private: } // If the variable isn't initialized in the body call "use" - if(varid != 0) + if (varid != 0) { // goto variable tok2 = tok2->next(); - if(!tok2->varId()) + if (!tok2->varId()) tok2 = tok2->next(); // call "use" @@ -2314,18 +2314,18 @@ private: { bool foundError = false; - if(tok.varId() && Token::Match(&tok, "%var% <|<=|==|!=|)|[")) + if (tok.varId() && Token::Match(&tok, "%var% <|<=|==|!=|)|[")) use(foundError, checks, &tok); - else if(Token::Match(&tok, "!| %var% (")) + else if (Token::Match(&tok, "!| %var% (")) { std::list var; parseFunctionCall(tok.str() == "!" ? *tok.next() : tok, var, 1); - for(std::list::const_iterator it = var.begin(); it != var.end(); ++it) + for (std::list::const_iterator it = var.begin(); it != var.end(); ++it) use_array(foundError, checks, *it); } - else if(Token::Match(&tok, "! %var% )")) + else if (Token::Match(&tok, "! %var% )")) { use(foundError, checks, &tok); return false; @@ -2341,30 +2341,30 @@ public: static void analyseFunctions(const Token * const tokens, std::set &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(); continue; } - if(tok->str() != "::" && Token::Match(tok->next(), "%var% ( %type%")) + if (tok->str() != "::" && Token::Match(tok->next(), "%var% ( %type%")) { - if(!Token::simpleMatch(tok->tokAt(2)->link(), ") {")) + if (!Token::simpleMatch(tok->tokAt(2)->link(), ") {")) continue; const Token *tok2 = tok->tokAt(3); - while(tok2 && tok2->str() != ")") + while (tok2 && tok2->str() != ")") { - if(tok2->str() == ",") + if (tok2->str() == ",") tok2 = tok2->next(); - if(Token::Match(tok2, "%type% %var% ,|)") && tok2->isStandardType()) + if (Token::Match(tok2, "%type% %var% ,|)") && tok2->isStandardType()) { tok2 = tok2->tokAt(2); continue; } - if(Token::Match(tok2, "const %type% %var% ,|)") && tok2->next()->isStandardType()) + if (Token::Match(tok2, "const %type% %var% ,|)") && tok2->next()->isStandardType()) { tok2 = tok2->tokAt(2); continue; @@ -2374,7 +2374,7 @@ public: } // found simple function.. - if(tok2->link() == tok->tokAt(2)) + if (tok2->link() == tok->tokAt(2)) func.insert(tok->next()->str()); } } @@ -2406,7 +2406,7 @@ void CheckOther::executionPaths() // check if variable is accessed uninitialized.. { // no writing if multiple threads are used (TODO: thread safe analysis?) - if(_settings->_jobs == 1) + if (_settings->_jobs == 1) CheckUninitVar::analyseFunctions(_tokenizer->tokens(), CheckUninitVar::uvarFunctions); CheckUninitVar c(this); @@ -2416,18 +2416,18 @@ void CheckOther::executionPaths() void CheckOther::checkZeroDivision() { - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { - if(Token::Match(tok, "/ %num%") && - MathLib::isInt(tok->next()->str()) && - MathLib::toLongNumber(tok->next()->str()) == 0L) + if (Token::Match(tok, "/ %num%") && + MathLib::isInt(tok->next()->str()) && + MathLib::toLongNumber(tok->next()->str()) == 0L) { zerodivError(tok); } - else if(Token::Match(tok, "div|ldiv|lldiv|imaxdiv ( %num% , %num% )") && - MathLib::isInt(tok->tokAt(4)->str()) && - MathLib::toLongNumber(tok->tokAt(4)->str()) == 0L) + else if (Token::Match(tok, "div|ldiv|lldiv|imaxdiv ( %num% , %num% )") && + MathLib::isInt(tok->tokAt(4)->str()) && + MathLib::toLongNumber(tok->tokAt(4)->str()) == 0L) { zerodivError(tok); } @@ -2437,42 +2437,42 @@ void CheckOther::checkZeroDivision() void CheckOther::checkMathFunctions() { - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { - // case log(-2) - if(Token::Match(tok, "log ( %num% )") && - MathLib::isNegative(tok->tokAt(2)->str()) && - MathLib::isInt(tok->tokAt(2)->str()) && - MathLib::toLongNumber(tok->tokAt(2)->str()) <= 0) - { - mathfunctionCallError(tok); - } - // case log(-2.0) - else if(Token::Match(tok, "log ( %num% )") && - MathLib::isNegative(tok->tokAt(2)->str()) && - MathLib::isFloat(tok->tokAt(2)->str()) && - MathLib::toDoubleNumber(tok->tokAt(2)->str()) <= 0.) + // case log(-2) + if (Token::Match(tok, "log ( %num% )") && + MathLib::isNegative(tok->tokAt(2)->str()) && + MathLib::isInt(tok->tokAt(2)->str()) && + MathLib::toLongNumber(tok->tokAt(2)->str()) <= 0) { mathfunctionCallError(tok); } + // case log(-2.0) + else if (Token::Match(tok, "log ( %num% )") && + MathLib::isNegative(tok->tokAt(2)->str()) && + MathLib::isFloat(tok->tokAt(2)->str()) && + MathLib::toDoubleNumber(tok->tokAt(2)->str()) <= 0.) + { + mathfunctionCallError(tok); + } - // case log(0.0) - else if(Token::Match(tok, "log ( %num% )") && - !MathLib::isNegative(tok->tokAt(2)->str()) && - MathLib::isFloat(tok->tokAt(2)->str()) && - MathLib::toDoubleNumber(tok->tokAt(2)->str()) <= 0.) - { - mathfunctionCallError(tok); - } + // case log(0.0) + else if (Token::Match(tok, "log ( %num% )") && + !MathLib::isNegative(tok->tokAt(2)->str()) && + MathLib::isFloat(tok->tokAt(2)->str()) && + MathLib::toDoubleNumber(tok->tokAt(2)->str()) <= 0.) + { + mathfunctionCallError(tok); + } - // case log(0) - else if(Token::Match(tok, "log ( %num% )") && - !MathLib::isNegative(tok->tokAt(2)->str()) && - MathLib::isInt(tok->tokAt(2)->str()) && - MathLib::toLongNumber(tok->tokAt(2)->str()) <= 0) - { - mathfunctionCallError(tok); - } + // case log(0) + else if (Token::Match(tok, "log ( %num% )") && + !MathLib::isNegative(tok->tokAt(2)->str()) && + MathLib::isInt(tok->tokAt(2)->str()) && + MathLib::toLongNumber(tok->tokAt(2)->str()) <= 0) + { + mathfunctionCallError(tok); + } } } @@ -2480,16 +2480,16 @@ void CheckOther::checkMathFunctions() void CheckOther::postIncrement() { - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { - if(Token::simpleMatch(tok, "for (")) + if (Token::simpleMatch(tok, "for (")) { const Token *tok2 = tok->next()->link(); - if(tok2) + if (tok2) tok2 = tok2->tokAt(-3); - if(Token::Match(tok2, "; %var% ++|-- )")) + if (Token::Match(tok2, "; %var% ++|-- )")) { - if(tok2->next()->varId() == 0) + if (tok2->next()->varId() == 0) continue; // Take a look at the variable declaration @@ -2497,10 +2497,10 @@ void CheckOther::postIncrement() const std::string classDef = std::string("class ") + std::string(decltok->previous()->strAt(0)); // Is the variable an iterator? - if(decltok && Token::Match(decltok->previous(), "iterator|const_iterator")) + if (decltok && Token::Match(decltok->previous(), "iterator|const_iterator")) postIncrementError(tok2, tok2->strAt(1), (std::string("++") == tok2->strAt(2))); // Is the variable a class? - else if(Token::findmatch(_tokenizer->tokens(), classDef.c_str())) + else if (Token::findmatch(_tokenizer->tokens(), classDef.c_str())) postIncrementError(tok2, tok2->strAt(1), (std::string("++") == tok2->strAt(2))); } } @@ -2622,7 +2622,7 @@ void CheckOther::zerodivError(const Token *tok) void CheckOther::mathfunctionCallError(const Token *tok) { - reportError(tok, Severity::error, "wrongmathcall", "Passing value " + tok->tokAt(2)->str() + " to " + tok->str() + "() leads to undefined result"); + reportError(tok, Severity::error, "wrongmathcall","Passing value " + tok->tokAt(2)->str() + " to " + tok->str() + "() leads to undefined result"); } void CheckOther::postIncrementError(const Token *tok, const std::string &var_name, const bool isIncrement) diff --git a/lib/checkother.h b/lib/checkother.h index 8eb71f966..1f4f15aa1 100644 --- a/lib/checkother.h +++ b/lib/checkother.h @@ -42,7 +42,7 @@ public: /** @brief This constructor is used when running checks. */ CheckOther(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) - : Check(tokenizer, settings, errorLogger) + : Check(tokenizer, settings, errorLogger) { } /** @brief Run checks against the normal token list */ @@ -51,7 +51,7 @@ public: CheckOther checkOther(tokenizer, settings, errorLogger); checkOther.nullPointer(); - if(settings->_checkCodingStyle) + if (settings->_checkCodingStyle) { checkOther.warningOldStylePointerCast(); checkOther.checkUnsignedDivision(); @@ -67,13 +67,13 @@ public: { CheckOther checkOther(tokenizer, settings, errorLogger); - if(settings->_checkCodingStyle) + if (settings->_checkCodingStyle) { checkOther.warningRedundantCode(); checkOther.checkConstantFunctionParameter(); checkOther.checkIncompleteStatement(); checkOther.unreachableCode(); - if(settings->_showAll) + if (settings->_showAll) { checkOther.postIncrement(); } @@ -82,7 +82,7 @@ public: checkOther.strPlusChar(); checkOther.invalidFunctionUsage(); checkOther.checkZeroDivision(); - checkOther.checkMathFunctions(); + checkOther.checkMathFunctions(); // New type of check: Check execution paths checkOther.executionPaths(); @@ -151,8 +151,8 @@ public: /** @brief %Check zero division*/ void checkZeroDivision(); - /** @brief %Check for parameters given to math function that do not make sense*/ - void checkMathFunctions(); + /** @brief %Check for parameters given to math function that do not make sense*/ + void checkMathFunctions(); /** @brief %Check for post increment/decrement in for loop*/ void postIncrement(); @@ -188,7 +188,7 @@ public: void uninitdataError(const Token *tok, const std::string &varname); void uninitvarError(const Token *tok, const std::string &varname); void zerodivError(const Token *tok); - void mathfunctionCallError(const Token *tok); + void mathfunctionCallError(const Token *tok); void postIncrementError(const Token *tok, const std::string &var_name, const bool isIncrement); void getErrorMessages() @@ -201,7 +201,7 @@ public: uninitdataError(0, "varname"); uninitvarError(0, "varname"); zerodivError(0); - mathfunctionCallError(0); + mathfunctionCallError(0); // style cstyleCastError(0); diff --git a/lib/checkstl.cpp b/lib/checkstl.cpp index 170d71036..96f25a533 100644 --- a/lib/checkstl.cpp +++ b/lib/checkstl.cpp @@ -43,49 +43,49 @@ void CheckStl::dereferenceErasedError(const Token *tok, const std::string &itern void CheckStl::iterators() { - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { - if(!Token::Match(tok, "%var% = %var% . begin ( ) ;|+")) + if (!Token::Match(tok, "%var% = %var% . begin ( ) ;|+")) continue; const unsigned int iteratorId(tok->varId()); const unsigned int containerId(tok->tokAt(2)->varId()); - if(iteratorId == 0 || containerId == 0) + if (iteratorId == 0 || containerId == 0) continue; bool validIterator = true; - for(const Token *tok2 = tok->tokAt(7); tok2; tok2 = tok2->next()) + for (const Token *tok2 = tok->tokAt(7); tok2; tok2 = tok2->next()) { - if(tok2->str() == "}") + if (tok2->str() == "}") break; - if(Token::Match(tok2, "%varid% != %var% . end ( )", iteratorId) && tok2->tokAt(2)->varId() != containerId) + if (Token::Match(tok2, "%varid% != %var% . end ( )", iteratorId) && tok2->tokAt(2)->varId() != containerId) { iteratorsError(tok2, tok->strAt(2), tok2->strAt(2)); tok2 = tok2->tokAt(6); } - else if(Token::Match(tok2, "%var% . insert|erase ( %varid% )|,", iteratorId)) + else if (Token::Match(tok2, "%var% . insert|erase ( %varid% )|,", iteratorId)) { - if(tok2->varId() != containerId && tok2->tokAt(5)->str() != ".") + if (tok2->varId() != containerId && tok2->tokAt(5)->str() != ".") iteratorsError(tok2, tok->strAt(2), tok2->str()); - else if(tok2->strAt(2) == std::string("erase")) + else if (tok2->strAt(2) == std::string("erase")) validIterator = false; tok2 = tok2->tokAt(4); } - else if(Token::Match(tok2, "%varid% = %var% . erase (", iteratorId)) + else if (Token::Match(tok2, "%varid% = %var% . erase (", iteratorId)) { validIterator = true; tok2 = tok2->tokAt(5)->link(); - if(!tok2) + if (!tok2) break; } - else if(!validIterator && Token::Match(tok2, "* %varid%", iteratorId)) + else if (!validIterator && Token::Match(tok2, "* %varid%", iteratorId)) { dereferenceErasedError(tok2, tok2->strAt(1)); tok2 = tok2->next(); } - else if(!validIterator && Token::Match(tok2, "%varid% . %var%", iteratorId)) + else if (!validIterator && Token::Match(tok2, "%varid% . %var%", iteratorId)) { dereferenceErasedError(tok2, tok2->strAt(0)); tok2 = tok2->tokAt(2); @@ -103,14 +103,14 @@ void CheckStl::mismatchingContainersError(const Token *tok) void CheckStl::mismatchingContainers() { - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { - if(tok->str() != "std") + if (tok->str() != "std") continue; - if(Token::Match(tok, "std :: find|find_if|count|transform|replace|replace_if|sort ( %var% . begin|rbegin ( ) , %var% . end|rend ( ) ,")) + if (Token::Match(tok, "std :: find|find_if|count|transform|replace|replace_if|sort ( %var% . begin|rbegin ( ) , %var% . end|rend ( ) ,")) { - if(tok->tokAt(4)->str() != tok->tokAt(10)->str()) + if (tok->tokAt(4)->str() != tok->tokAt(10)->str()) { mismatchingContainersError(tok); } @@ -121,45 +121,45 @@ void CheckStl::mismatchingContainers() void CheckStl::stlOutOfBounds() { - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { - if(!Token::simpleMatch(tok, "for (")) + if (!Token::simpleMatch(tok, "for (")) continue; unsigned int indent = 0; - for(const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) + for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) { - if(tok2->str() == "(") + if (tok2->str() == "(") ++indent; - else if(tok2->str() == ")") + else if (tok2->str() == ")") { - if(indent == 0) + if (indent == 0) break; --indent; } - if(Token::Match(tok2, "; %var% <= %var% . size ( ) ;")) + if (Token::Match(tok2, "; %var% <= %var% . size ( ) ;")) { unsigned int indent2 = 0; unsigned int numId = tok2->tokAt(1)->varId(); unsigned int varId = tok2->tokAt(3)->varId(); - for(const Token *tok3 = tok2->tokAt(8); tok3; tok3 = tok3->next()) + for (const Token *tok3 = tok2->tokAt(8); tok3; tok3 = tok3->next()) { - if(tok3->str() == "{") + if (tok3->str() == "{") ++indent2; - else if(tok3->str() == "}") + else if (tok3->str() == "}") { - if(indent2 <= 1) + if (indent2 <= 1) break; --indent2; } - else if(tok3->varId() == varId) + else if (tok3->varId() == varId) { - if(Token::simpleMatch(tok3->next(), ". size ( )")) + if (Token::simpleMatch(tok3->next(), ". size ( )")) break; - else if(Token::Match(tok3->next(), "[ %varid% ]", numId)) + else if (Token::Match(tok3->next(), "[ %varid% ]", numId)) stlOutOfBoundsError(tok3, tok3->tokAt(2)->str(), tok3->str()); } } @@ -179,15 +179,15 @@ void CheckStl::stlOutOfBoundsError(const Token *tok, const std::string &num, con void CheckStl::erase() { - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { - if(Token::simpleMatch(tok, "for (")) + if (Token::simpleMatch(tok, "for (")) { - for(const Token *tok2 = tok->tokAt(2); tok2 && tok2->str() != ";"; tok2 = tok2->next()) + for (const Token *tok2 = tok->tokAt(2); tok2 && tok2->str() != ";"; tok2 = tok2->next()) { - if(Token::Match(tok2, "%var% = %var% . begin ( ) ; %var% != %var% . end ( ) ") && - tok2->str() == tok2->tokAt(8)->str() && - tok2->tokAt(2)->str() == tok2->tokAt(10)->str()) + if (Token::Match(tok2, "%var% = %var% . begin ( ) ; %var% != %var% . end ( ) ") && + tok2->str() == tok2->tokAt(8)->str() && + tok2->tokAt(2)->str() == tok2->tokAt(10)->str()) { eraseCheckLoop(tok2); break; @@ -195,7 +195,7 @@ void CheckStl::erase() } } - if(Token::Match(tok, "while ( %var% != %var% . end ( )")) + if (Token::Match(tok, "while ( %var% != %var% . end ( )")) { eraseCheckLoop(tok->tokAt(2)); } @@ -208,44 +208,44 @@ void CheckStl::eraseCheckLoop(const Token *it) // Search for the start of the loop body.. int indentlevel = 1; - while(indentlevel > 0 && 0 != (tok = tok->next())) + while (indentlevel > 0 && 0 != (tok = tok->next())) { - if(tok->str() == "(") + if (tok->str() == "(") ++indentlevel; - else if(tok->str() == ")") + else if (tok->str() == ")") --indentlevel; } - if(! Token::simpleMatch(tok, ") {")) + if (! Token::simpleMatch(tok, ") {")) return; // Parse loop.. // Error if it contains "erase(it)" but neither "break;", "=it" nor "it=" indentlevel = 0; const Token *tok2 = 0; - while(0 != (tok = tok->next())) + while (0 != (tok = tok->next())) { - if(tok->str() == "{") + if (tok->str() == "{") ++indentlevel; - else if(tok->str() == "}") + else if (tok->str() == "}") { --indentlevel; - if(indentlevel <= 0) + if (indentlevel <= 0) break; } - else if(Token::Match(tok, "break|return|goto") || - Token::simpleMatch(tok, (it->str() + " =").c_str()) || - Token::simpleMatch(tok, ("= " + it->str()).c_str())) + else if (Token::Match(tok, "break|return|goto") || + Token::simpleMatch(tok, (it->str() + " =").c_str()) || + Token::simpleMatch(tok, ("= " + it->str()).c_str())) { tok2 = 0; break; } - else if(Token::simpleMatch(tok, ("erase ( " + it->str() + " )").c_str())) + else if (Token::simpleMatch(tok, ("erase ( " + it->str() + " )").c_str())) tok2 = tok; } // Write error message.. - if(tok2) + if (tok2) eraseError(tok2); } @@ -261,39 +261,39 @@ void CheckStl::eraseError(const Token *tok) void CheckStl::pushback() { // Pointer can become invalid after push_back or push_front.. - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { - if(Token::Match(tok, "%var% = & %var% [")) + if (Token::Match(tok, "%var% = & %var% [")) { const unsigned int pointerId(tok->varId()); const unsigned int containerId(tok->tokAt(3)->varId()); - if(pointerId == 0 || containerId == 0) + if (pointerId == 0 || containerId == 0) continue; int indent = 0; bool invalidPointer = false; - for(const Token *tok2 = tok; indent >= 0 && tok2; tok2 = tok2->next()) + for (const Token *tok2 = tok; indent >= 0 && tok2; tok2 = tok2->next()) { - if(tok2->str() == "{" || tok2->str() == "(") + if (tok2->str() == "{" || tok2->str() == "(") ++indent; - else if(tok2->str() == "}" || tok2->str() == ")") + else if (tok2->str() == "}" || tok2->str() == ")") { - if(indent == 0 && Token::simpleMatch(tok2, ") {")) + if (indent == 0 && Token::simpleMatch(tok2, ") {")) tok2 = tok2->next(); else --indent; } // push_back on vector.. - if(Token::Match(tok2, "%varid% . push_front|push_back", containerId)) + if (Token::Match(tok2, "%varid% . push_front|push_back", containerId)) invalidPointer = true; // Using invalid pointer.. - if(invalidPointer && tok2->varId() == pointerId) + if (invalidPointer && tok2->varId() == pointerId) { - if(tok2->previous()->str() == "*") + if (tok2->previous()->str() == "*") invalidPointerError(tok2, tok2->str()); - else if(tok2->next()->str() == ".") + else if (tok2->next()->str() == ".") invalidPointerError(tok2, tok2->str()); break; } @@ -302,31 +302,31 @@ void CheckStl::pushback() } // Iterator becomes invalid after push_back or push_front.. - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { - if(!Token::simpleMatch(tok, "vector <")) + if (!Token::simpleMatch(tok, "vector <")) continue; // if iterator declaration inside for() loop bool iteratorDeclaredInsideLoop = false; - if((tok->tokAt(-2) && Token::simpleMatch(tok->tokAt(-2), "for (")) || - (tok->tokAt(-4) && Token::simpleMatch(tok->tokAt(-4), "for ( std ::"))) + if ((tok->tokAt(-2) && Token::simpleMatch(tok->tokAt(-2), "for (")) || + (tok->tokAt(-4) && Token::simpleMatch(tok->tokAt(-4), "for ( std ::"))) { iteratorDeclaredInsideLoop = true; } - while(tok && tok->str() != ">") + while (tok && tok->str() != ">") tok = tok->next(); - if(!tok) + if (!tok) break; - if(!Token::Match(tok, "> :: iterator|const_iterator %var% =|;")) + if (!Token::Match(tok, "> :: iterator|const_iterator %var% =|;")) continue; const unsigned int iteratorid(tok->tokAt(3)->varId()); - if(iteratorid == 0) + if (iteratorid == 0) continue; - if(iteratorDeclaredInsideLoop && tok->tokAt(4)->str() == "=") + if (iteratorDeclaredInsideLoop && tok->tokAt(4)->str() == "=") { // skip "> :: iterator|const_iterator" tok = tok->tokAt(3); @@ -335,61 +335,61 @@ void CheckStl::pushback() unsigned int vectorid = 0; int indent = 0; std::string invalidIterator; - for(const Token *tok2 = tok; indent >= 0 && tok2; tok2 = tok2->next()) + for (const Token *tok2 = tok; indent >= 0 && tok2; tok2 = tok2->next()) { - if(tok2->str() == "{" || tok2->str() == "(") + if (tok2->str() == "{" || tok2->str() == "(") ++indent; - else if(tok2->str() == "}" || tok2->str() == ")") + else if (tok2->str() == "}" || tok2->str() == ")") { - if(indent == 0 && Token::simpleMatch(tok2, ") {")) + if (indent == 0 && Token::simpleMatch(tok2, ") {")) tok2 = tok2->next(); else --indent; } // Using push_back or push_front inside a loop.. - if(Token::Match(tok2, "for (")) + if (Token::Match(tok2, "for (")) { tok2 = tok2->tokAt(2); } - if(Token::Match(tok2, "%varid% = %var% . begin ( ) ; %varid% != %var% . end ( ) ; ++| %varid% ++| ) {", iteratorid)) + if (Token::Match(tok2, "%varid% = %var% . begin ( ) ; %varid% != %var% . end ( ) ; ++| %varid% ++| ) {", iteratorid)) { const unsigned int vectorid(tok2->tokAt(2)->varId()); - if(vectorid == 0) + if (vectorid == 0) continue; const Token *pushback = 0; unsigned int indent3 = 0; - for(const Token *tok3 = tok2->tokAt(20); tok3; tok3 = tok3->next()) + for (const Token *tok3 = tok2->tokAt(20); tok3; tok3 = tok3->next()) { - if(tok3->str() == "{") + if (tok3->str() == "{") ++indent3; - else if(tok3->str() == "}") + else if (tok3->str() == "}") { - if(indent3 <= 1) + if (indent3 <= 1) break; --indent3; } - else if(tok3->str() == "break") + else if (tok3->str() == "break") { pushback = 0; break; } - else if(Token::Match(tok3, "%varid% . push_front|push_back|insert (", vectorid)) + else if (Token::Match(tok3, "%varid% . push_front|push_back|insert (", vectorid)) { pushback = tok3->tokAt(2); } } - if(pushback) + if (pushback) invalidIteratorError(pushback, pushback->str(), tok2->strAt(0)); } // Assigning iterator.. - if(Token::Match(tok2, "%varid% =", iteratorid)) + if (Token::Match(tok2, "%varid% =", iteratorid)) { - if(Token::Match(tok2->tokAt(2), "%var% . begin|end|rbegin|rend ( )")) + if (Token::Match(tok2->tokAt(2), "%var% . begin|end|rbegin|rend ( )")) { vectorid = tok2->tokAt(2)->varId(); tok2 = tok2->tokAt(6); @@ -402,29 +402,29 @@ void CheckStl::pushback() } // push_back on vector.. - if(vectorid > 0 && Token::Match(tok2, "%varid% . push_front|push_back|insert (", vectorid)) + if (vectorid > 0 && Token::Match(tok2, "%varid% . push_front|push_back|insert (", vectorid)) { - if(!invalidIterator.empty() && Token::Match(tok2->tokAt(2), "insert ( %varid% ,", iteratorid)) + if (!invalidIterator.empty() && Token::Match(tok2->tokAt(2), "insert ( %varid% ,", iteratorid)) { invalidIteratorError(tok2, invalidIterator, tok2->strAt(4)); break; } invalidIterator = tok2->strAt(2); - if(!iteratorDeclaredInsideLoop) + if (!iteratorDeclaredInsideLoop) { tok2 = tok2->tokAt(3)->link(); - if(!tok2) + if (!tok2) break; } } // Using invalid iterator.. - if(!invalidIterator.empty()) + if (!invalidIterator.empty()) { - if(Token::Match(tok2, "++|--|*|+|-|(|,|=|!= %varid%", iteratorid)) + if (Token::Match(tok2, "++|--|*|+|-|(|,|=|!= %varid%", iteratorid)) invalidIteratorError(tok2, invalidIterator, tok2->strAt(1)); - if(Token::Match(tok2, "%varid% ++|--|+|-", iteratorid)) + if (Token::Match(tok2, "%varid% ++|--|+|-", iteratorid)) invalidIteratorError(tok2, invalidIterator, tok2->str()); } } @@ -453,37 +453,37 @@ void CheckStl::stlBoundries() // containers (not the vector).. static const char STL_CONTAINER_LIST[] = "bitset|deque|list|map|multimap|multiset|priority_queue|queue|set|stack|hash_map|hash_multimap|hash_set"; - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { // Declaring iterator.. const std::string checkStr = (std::string(STL_CONTAINER_LIST) + " <"); - if(Token::Match(tok, checkStr.c_str())) + if (Token::Match(tok, checkStr.c_str())) { const std::string container_name(tok->strAt(0)); - while(tok && tok->str() != ">") + while (tok && tok->str() != ">") tok = tok->next(); - if(!tok) + if (!tok) break; - if(Token::Match(tok, "> :: iterator|const_iterator %var% =|;")) + if (Token::Match(tok, "> :: iterator|const_iterator %var% =|;")) { const unsigned int iteratorid(tok->tokAt(3)->varId()); - if(iteratorid == 0) + if (iteratorid == 0) continue; // Using "iterator < ..." is not allowed unsigned int indentlevel = 0; - for(const Token *tok2 = tok; tok2; tok2 = tok2->next()) + for (const Token *tok2 = tok; tok2; tok2 = tok2->next()) { - if(tok2->str() == "{") + if (tok2->str() == "{") ++indentlevel; - else if(tok2->str() == "}") + else if (tok2->str() == "}") { - if(indentlevel == 0) + if (indentlevel == 0) break; --indentlevel; } - else if(Token::Match(tok2, "!!* %varid% <", iteratorid)) + else if (Token::Match(tok2, "!!* %varid% <", iteratorid)) { stlBoundriesError(tok2, container_name); } @@ -503,23 +503,23 @@ void CheckStl::stlBoundriesError(const Token *tok, const std::string &container_ void CheckStl::find() { - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { - if(tok->str() != ";") + if (tok->str() != ";") continue; - if(!Token::Match(tok->next(), "%var% = std :: find (")) + if (!Token::Match(tok->next(), "%var% = std :: find (")) continue; const unsigned int iteratorid = tok->next()->varId(); - if(iteratorid == 0) + if (iteratorid == 0) continue; tok = tok->tokAt(6)->link(); - if(!tok) + if (!tok) break; - for(const Token *tok2 = tok; tok2; tok2 = tok2->next()) + for (const Token *tok2 = tok; tok2; tok2 = tok2->next()) { - if(tok2->str() == "{" || tok2->str() == "}" || tok2->str() == "(" || tok2->str() == ")") + if (tok2->str() == "{" || tok2->str() == "}" || tok2->str() == "(" || tok2->str() == ")") break; - if(tok2->varId() == iteratorid && Token::simpleMatch(tok2->previous(), "*")) + if (tok2->varId() == iteratorid && Token::simpleMatch(tok2->previous(), "*")) findError(tok2); } } @@ -535,42 +535,42 @@ void CheckStl::findError(const Token *tok) void CheckStl::if_find() { - if(!_settings->_checkCodingStyle) + if (!_settings->_checkCodingStyle) return; - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { - if(Token::Match(tok, "if ( !| %var% . find ( %any% ) )")) + if (Token::Match(tok, "if ( !| %var% . find ( %any% ) )")) { // goto %var% tok = tok->tokAt(2); - if(!tok->isName()) + if (!tok->isName()) tok = tok->next(); const unsigned int varid = tok->varId(); - if(varid > 0) + if (varid > 0) { // Is the variable a std::string or STL container? const Token * decl = Token::findmatch(_tokenizer->tokens(), "%varid%", varid); - while(decl && !Token::Match(decl, "[;{}(,]")) + while (decl && !Token::Match(decl, "[;{}(,]")) decl = decl->previous(); decl = decl->next(); // stl container - if(Token::Match(decl, "const| std :: %var% < %type% > &|*| %varid%", varid)) + if (Token::Match(decl, "const| std :: %var% < %type% > &|*| %varid%", varid)) if_findError(tok, false); } } - if(Token::Match(tok, "if ( !| std :: find|find_if (")) + if (Token::Match(tok, "if ( !| std :: find|find_if (")) { // goto '(' for the find tok = tok->tokAt(4); - if(tok->isName()) + if (tok->isName()) tok = tok->next(); // check that result is checked properly - if(Token::simpleMatch(tok->link(), ") )")) + if (Token::simpleMatch(tok->link(), ") )")) { if_findError(tok, false); } @@ -581,7 +581,7 @@ void CheckStl::if_find() void CheckStl::if_findError(const Token *tok, bool str) { - if(str) + if (str) reportError(tok, Severity::possibleStyle, "stlIfStrFind", "Suspicious condition. string::find will return 0 if the string is found at position 0. If this is what you want to check then string::compare is a faster alternative because it doesn't scan through the string."); else reportError(tok, Severity::style, "stlIfFind", "Suspicious condition. The result of find is an iterator, but it is not properly checked."); @@ -592,21 +592,21 @@ void CheckStl::if_findError(const Token *tok, bool str) bool CheckStl::isStlContainer(const Token *tok) { // check if this token is defined - if(tok->varId()) + if (tok->varId()) { // find where this token is defined const Token *type = Token::findmatch(_tokenizer->tokens(), "%varid%", tok->varId()); // find where this tokens type starts - while(type->previous() && !Token::Match(type->previous(), "[;{,(]")) + while (type->previous() && !Token::Match(type->previous(), "[;{,(]")) type = type->previous(); // ignore "const" - if(type->str() == "const") + if (type->str() == "const") type = type->next(); // discard namespace if supplied - if(Token::simpleMatch(type, "std ::")) + if (Token::simpleMatch(type, "std ::")) type = type->next()->next(); // all possible stl containers @@ -616,7 +616,7 @@ bool CheckStl::isStlContainer(const Token *tok) const std::string checkStr(std::string(STL_CONTAINER_LIST) + " <"); // check if it's an stl template - if(Token::Match(type, checkStr.c_str())) + if (Token::Match(type, checkStr.c_str())) return true; } @@ -625,35 +625,35 @@ bool CheckStl::isStlContainer(const Token *tok) void CheckStl::size() { - for(const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) + for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { - if(Token::Match(tok, "%var% . size ( )")) + if (Token::Match(tok, "%var% . size ( )")) { - if(Token::Match(tok->tokAt(5), "==|!=|> 0")) + if (Token::Match(tok->tokAt(5), "==|!=|> 0")) { - if(isStlContainer(tok)) + if (isStlContainer(tok)) sizeError(tok); } - else if((tok->tokAt(5)->str() == ")" || - tok->tokAt(5)->str() == "&&" || - tok->tokAt(5)->str() == "||" || - tok->tokAt(5)->str() == "!") && - (tok->tokAt(-1)->str() == "(" || - tok->tokAt(-1)->str() == "&&" || - tok->tokAt(-1)->str() == "||" || - tok->tokAt(-1)->str() == "!")) + else if ((tok->tokAt(5)->str() == ")" || + tok->tokAt(5)->str() == "&&" || + tok->tokAt(5)->str() == "||" || + tok->tokAt(5)->str() == "!") && + (tok->tokAt(-1)->str() == "(" || + tok->tokAt(-1)->str() == "&&" || + tok->tokAt(-1)->str() == "||" || + tok->tokAt(-1)->str() == "!")) { - if(tok->tokAt(-1)->str() == "(" && - tok->tokAt(5)->str() == ")") + if (tok->tokAt(-1)->str() == "(" && + tok->tokAt(5)->str() == ")") { // check for passing size to function call - if(Token::Match(tok->tokAt(-2), "if|while")) + if (Token::Match(tok->tokAt(-2), "if|while")) { - if(isStlContainer(tok)) + if (isStlContainer(tok)) sizeError(tok); } } - else if(isStlContainer(tok)) + else if (isStlContainer(tok)) sizeError(tok); } } diff --git a/lib/checkstl.h b/lib/checkstl.h index 42d1e1014..ec049fcf8 100644 --- a/lib/checkstl.h +++ b/lib/checkstl.h @@ -40,7 +40,7 @@ public: /** This constructor is used when running checks. */ CheckStl(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) - : Check(tokenizer, settings, errorLogger) + : Check(tokenizer, settings, errorLogger) { } void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) @@ -56,9 +56,9 @@ public: checkStl.find(); checkStl.if_find(); - if(settings->_checkCodingStyle) + if (settings->_checkCodingStyle) { - if(settings->_showAll) + if (settings->_showAll) checkStl.size(); } } diff --git a/lib/checkunusedfunctions.cpp b/lib/checkunusedfunctions.cpp index 9f650c3ac..417ce859b 100644 --- a/lib/checkunusedfunctions.cpp +++ b/lib/checkunusedfunctions.cpp @@ -48,62 +48,62 @@ void CheckUnusedFunctions::setErrorLogger(ErrorLogger *errorLogger) void CheckUnusedFunctions::parseTokens(const Tokenizer &tokenizer) { // Function declarations.. - for(const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) { - if(tok->fileIndex() != 0) + if (tok->fileIndex() != 0) continue; // token contains a ':' => skip to next ; or { - if(tok->str().find(":") != std::string::npos) + if (tok->str().find(":") != std::string::npos) { - while(tok && tok->str().find_first_of(";{")) + while (tok && tok->str().find_first_of(";{")) tok = tok->next(); - if(tok) + if (tok) continue; break; } // If this is a template function, skip it - if(tok->previous() && tok->previous()->str() == ">") + if (tok->previous() && tok->previous()->str() == ">") continue; const Token *funcname = 0; - if(Token::Match(tok, "%type% %var% (")) + if (Token::Match(tok, "%type% %var% (")) funcname = tok->tokAt(1); - else if(Token::Match(tok, "%type% * %var% (")) + else if (Token::Match(tok, "%type% * %var% (")) funcname = tok->tokAt(2); - else if(Token::Match(tok, "%type% :: %var% (") && !Token::Match(tok, tok->strAt(2).c_str())) + else if (Token::Match(tok, "%type% :: %var% (") && !Token::Match(tok, tok->strAt(2).c_str())) funcname = tok->tokAt(2); // Don't assume throw as a function name: void foo() throw () {} - if(Token::Match(tok->previous(), ")|const")) + if (Token::Match(tok->previous(), ")|const")) funcname = 0; // Check that ") {" is found.. - for(const Token *tok2 = funcname; tok2; tok2 = tok2->next()) + for (const Token *tok2 = funcname; tok2; tok2 = tok2->next()) { - if(tok2->str() == ")") + if (tok2->str() == ")") { - if(! Token::simpleMatch(tok2, ") {") && - ! Token::simpleMatch(tok2, ") const {") && - ! Token::simpleMatch(tok2, ") const throw ( ) {") && - ! Token::simpleMatch(tok2, ") throw ( ) {")) + if (! Token::simpleMatch(tok2, ") {") && + ! Token::simpleMatch(tok2, ") const {") && + ! Token::simpleMatch(tok2, ") const throw ( ) {") && + ! Token::simpleMatch(tok2, ") throw ( ) {")) funcname = NULL; break; } } - if(funcname) + if (funcname) { FunctionUsage &func = _functions[ funcname->str()]; // No filename set yet.. - if(func.filename.empty()) + if (func.filename.empty()) func.filename = tokenizer.getFiles()->at(0); // Multiple files => filename = "+" - else if(func.filename != tokenizer.getFiles()->at(0)) + else if (func.filename != tokenizer.getFiles()->at(0)) { func.filename = "+"; func.usedOtherFile |= func.usedSameFile; @@ -112,49 +112,49 @@ void CheckUnusedFunctions::parseTokens(const Tokenizer &tokenizer) } // Function usage.. - for(const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) { const Token *funcname = 0; - if(Token::Match(tok->next(), "%var% (")) + if (Token::Match(tok->next(), "%var% (")) { funcname = tok->next(); } - else if(Token::Match(tok, "[;{}.,()[=+-/&|!?:] %var% [(),;:}]")) + else if (Token::Match(tok, "[;{}.,()[=+-/&|!?:] %var% [(),;:}]")) funcname = tok->next(); - else if(Token::Match(tok, "[=(,] & %var% :: %var% [,);]")) + else if (Token::Match(tok, "[=(,] & %var% :: %var% [,);]")) funcname = tok->tokAt(4); else continue; // funcname ( => Assert that the end paranthesis isn't followed by { - if(Token::Match(funcname, "%var% (")) + if (Token::Match(funcname, "%var% (")) { int parlevel = 0; - for(const Token *tok2 = funcname; tok2; tok2 = tok2->next()) + for (const Token *tok2 = funcname; tok2; tok2 = tok2->next()) { - if(tok2->str() == "(") + if (tok2->str() == "(") ++parlevel; - else if(tok2->str() == ")") + else if (tok2->str() == ")") { --parlevel; - if(parlevel == 0 && (Token::Match(tok2, ") const|{"))) + if (parlevel == 0 && (Token::Match(tok2, ") const|{"))) funcname = NULL; - if(parlevel <= 0) + if (parlevel <= 0) break; } } } - if(funcname) + if (funcname) { FunctionUsage &func = _functions[ funcname->str()]; - if(func.filename.empty() || func.filename == "+") + if (func.filename.empty() || func.filename == "+") func.usedOtherFile = true; else @@ -168,23 +168,23 @@ void CheckUnusedFunctions::parseTokens(const Tokenizer &tokenizer) void CheckUnusedFunctions::check() { - for(std::map::const_iterator it = _functions.begin(); it != _functions.end(); ++it) + for (std::map::const_iterator it = _functions.begin(); it != _functions.end(); ++it) { const FunctionUsage &func = it->second; - if(func.usedOtherFile || func.filename.empty()) + if (func.usedOtherFile || func.filename.empty()) continue; - if(it->first == "main" || it->first == "WinMain" || it->first == "if") + if (it->first == "main" || it->first == "WinMain" || it->first == "if") continue; - if(! func.usedSameFile) + if (! func.usedSameFile) { std::string filename; - if(func.filename == "+") + if (func.filename == "+") filename = ""; else filename = func.filename; _errorLogger->unusedFunction(filename, it->first); } - else if(! func.usedOtherFile) + else if (! func.usedOtherFile) { /** @todo add error message "function is only used in it can be static" */ /* diff --git a/lib/cppcheck.cpp b/lib/cppcheck.cpp index bc5e41005..e9e8d5119 100644 --- a/lib/cppcheck.cpp +++ b/lib/cppcheck.cpp @@ -44,7 +44,7 @@ //--------------------------------------------------------------------------- CppCheck::CppCheck(ErrorLogger &errorLogger) - : _errorLogger(errorLogger) + : _errorLogger(errorLogger) { exitcode = 0; } @@ -94,12 +94,12 @@ static void AddFilesToList(const std::string& FileList, std::vector // we need a good parser then -> suggestion : TinyXml // drawback : creates a dependency std::ifstream Files(FileList.c_str()); - if(Files) + if (Files) { std::string FileName; - while(std::getline(Files, FileName)) // next line + while (std::getline(Files, FileName)) // next line { - if(!FileName.empty()) + if (!FileName.empty()) { PathNames.push_back(FileName); } @@ -111,88 +111,88 @@ void CppCheck::parseFromArgs(int argc, const char* const argv[]) { std::vector pathnames; bool showHelp = false; - for(int i = 1; i < argc; i++) + for (int i = 1; i < argc; i++) { - if(strcmp(argv[i], "--version") == 0) + if (strcmp(argv[i], "--version") == 0) { reportOut(std::string("Cppcheck ") + version()); return; } // Flag used for various purposes during debugging - else if(strcmp(argv[i], "--debug") == 0) + else if (strcmp(argv[i], "--debug") == 0) _settings._debug = true; // Show all messages - else if(strcmp(argv[i], "-a") == 0 || strcmp(argv[i], "--all") == 0) + else if (strcmp(argv[i], "-a") == 0 || strcmp(argv[i], "--all") == 0) _settings.addEnabled("possibleError"); // Only print something when there are errors - else if(strcmp(argv[i], "-q") == 0 || strcmp(argv[i], "--quiet") == 0) + else if (strcmp(argv[i], "-q") == 0 || strcmp(argv[i], "--quiet") == 0) _settings._errorsOnly = true; // Checking coding style - else if(strcmp(argv[i], "-s") == 0 || strcmp(argv[i], "--style") == 0) + else if (strcmp(argv[i], "-s") == 0 || strcmp(argv[i], "--style") == 0) _settings.addEnabled("style"); // Filter errors - else if(strcmp(argv[i], "--suppressions") == 0) + else if (strcmp(argv[i], "--suppressions") == 0) { ++i; - if(i >= argc) + if (i >= argc) throw std::runtime_error("cppcheck: No file specified for the --suppressions option"); std::ifstream f(argv[i]); - if(!f.is_open()) + if (!f.is_open()) throw std::runtime_error("cppcheck: Couldn't open the file \"" + std::string(argv[i]) + "\""); _settings.nomsg.parseFile(f); } // Filter errors - else if(strcmp(argv[i], "--exitcode-suppressions") == 0) + else if (strcmp(argv[i], "--exitcode-suppressions") == 0) { ++i; - if(i >= argc) + if (i >= argc) throw std::runtime_error("cppcheck: No file specified for the --exitcode-suppressions option"); std::ifstream f(argv[i]); - if(!f.is_open()) + if (!f.is_open()) throw std::runtime_error("cppcheck: Couldn't open the file \"" + std::string(argv[i]) + "\""); _settings.nofail.parseFile(f); } // Enables inline suppressions. - else if(strcmp(argv[i], "--inline-suppr") == 0) + else if (strcmp(argv[i], "--inline-suppr") == 0) _settings._inlineSuppressions = true; // Verbose error messages (configuration info) - else if(strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--verbose") == 0) + else if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--verbose") == 0) _settings._verbose = true; // Force checking of files that have "too many" configurations - else if(strcmp(argv[i], "-f") == 0 || strcmp(argv[i], "--force") == 0) + else if (strcmp(argv[i], "-f") == 0 || strcmp(argv[i], "--force") == 0) _settings._force = true; // Write results in results.xml - else if(strcmp(argv[i], "--xml") == 0) + else if (strcmp(argv[i], "--xml") == 0) _settings._xml = true; // Check if there are unused functions - else if(strcmp(argv[i], "--unused-functions") == 0) + else if (strcmp(argv[i], "--unused-functions") == 0) _settings.addEnabled("unusedFunctions"); // Append userdefined code to checked source code - else if(strncmp(argv[i], "--append=", 9) == 0) + else if (strncmp(argv[i], "--append=", 9) == 0) _settings.append(9 + argv[i]); // show timing information.. - else if(strcmp(argv[i], "--showtime") == 0) + else if (strcmp(argv[i], "--showtime") == 0) _settings._showtime = true; // Print help - else if(strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) + else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) { pathnames.clear(); _filenames.clear(); @@ -201,18 +201,18 @@ void CppCheck::parseFromArgs(int argc, const char* const argv[]) } - else if(strncmp(argv[i], "--enable=", 9) == 0) + else if (strncmp(argv[i], "--enable=", 9) == 0) { _settings.addEnabled(argv[i] + 9); } // --error-exitcode=1 - else if(strncmp(argv[i], "--error-exitcode=", 17) == 0) + else if (strncmp(argv[i], "--error-exitcode=", 17) == 0) { std::string temp = argv[i]; temp = temp.substr(17); std::istringstream iss(temp); - if(!(iss >> _settings._exitCode)) + if (!(iss >> _settings._exitCode)) { _settings._exitCode = 0; throw std::runtime_error("cppcheck: Argument must be an integer. Try something like '--error-exitcode=1'"); @@ -220,15 +220,15 @@ void CppCheck::parseFromArgs(int argc, const char* const argv[]) } // Include paths - else if(strcmp(argv[i], "-I") == 0 || strncmp(argv[i], "-I", 2) == 0) + else if (strcmp(argv[i], "-I") == 0 || strncmp(argv[i], "-I", 2) == 0) { std::string path; // "-I path/" - if(strcmp(argv[i], "-I") == 0) + if (strcmp(argv[i], "-I") == 0) { ++i; - if(i >= argc) + if (i >= argc) throw std::runtime_error("cppcheck: argument to '-I' is missing"); path = argv[i]; @@ -242,87 +242,87 @@ void CppCheck::parseFromArgs(int argc, const char* const argv[]) } // If path doesn't end with / or \, add it - if(path[path.length()-1] != '/' && path[path.length()-1] != '\\') + if (path[path.length()-1] != '/' && path[path.length()-1] != '\\') path += '/'; _settings._includePaths.push_back(path); } // file list specified - else if(strncmp(argv[i], "--file-list=", 12) == 0) + else if (strncmp(argv[i], "--file-list=", 12) == 0) { // open this file and read every input file (1 file name per line) AddFilesToList(12 + argv[i], pathnames); } // Output formatter - else if(strcmp(argv[i], "--template") == 0) + else if (strcmp(argv[i], "--template") == 0) { // "--template path/" ++i; - if(i >= argc) + if (i >= argc) throw std::runtime_error("cppcheck: argument to '--template' is missing"); _settings._outputFormat = argv[i]; - if(_settings._outputFormat == "gcc") + if (_settings._outputFormat == "gcc") _settings._outputFormat = "{file}:{line}: {severity}: {message}"; - else if(_settings._outputFormat == "vs") + else if (_settings._outputFormat == "vs") _settings._outputFormat = "{file}({line}): {severity}: {message}"; } // Checking threads - else if(strcmp(argv[i], "-j") == 0 || - strncmp(argv[i], "-j", 2) == 0) + else if (strcmp(argv[i], "-j") == 0 || + strncmp(argv[i], "-j", 2) == 0) { std::string numberString; // "-j 3" - if(strcmp(argv[i], "-j") == 0) + if (strcmp(argv[i], "-j") == 0) { ++i; - if(i >= argc) + if (i >= argc) throw std::runtime_error("cppcheck: argument to '-j' is missing"); numberString = argv[i]; } // "-j3" - else if(strncmp(argv[i], "-j", 2) == 0) + else if (strncmp(argv[i], "-j", 2) == 0) { numberString = argv[i]; numberString = numberString.substr(2); } std::istringstream iss(numberString); - if(!(iss >> _settings._jobs)) + if (!(iss >> _settings._jobs)) throw std::runtime_error("cppcheck: argument to '-j' is not a number"); - if(_settings._jobs > 1000) + if (_settings._jobs > 1000) { throw std::runtime_error("cppcheck: argument for '-j' is allowed to be 1000 at max"); } } // auto deallocated classes.. - else if(strcmp(argv[i], "--auto-dealloc") == 0) + else if (strcmp(argv[i], "--auto-dealloc") == 0) { ++i; - if(i >= argc || !strstr(argv[i], ".lst")) + if (i >= argc || !strstr(argv[i], ".lst")) throw std::runtime_error("cppcheck: No .lst file specified for the --auto-dealloc option"); std::ifstream f(argv[i]); - if(!f.is_open()) + if (!f.is_open()) throw std::runtime_error("cppcheck: couldn't open the file \"" + std::string(argv[i+1]) + "\""); _settings.autoDealloc(f); } // print all possible error messages.. - else if(strcmp(argv[i], "--errorlist") == 0) + else if (strcmp(argv[i], "--errorlist") == 0) { // call all "getErrorMessages" in all registered Check classes std::cout << ErrorLogger::ErrorMessage::getXMLHeader(); - for(std::list::iterator it = Check::instances().begin(); it != Check::instances().end(); ++it) + for (std::list::iterator it = Check::instances().begin(); it != Check::instances().end(); ++it) { (*it)->getErrorMessages(); } @@ -336,25 +336,25 @@ void CppCheck::parseFromArgs(int argc, const char* const argv[]) } // documentation.. - else if(strcmp(argv[i], "--doc") == 0) + else if (strcmp(argv[i], "--doc") == 0) { std::ostringstream doc; // Get documentation.. - for(std::list::iterator it = Check::instances().begin(); it != Check::instances().end(); ++it) + for (std::list::iterator it = Check::instances().begin(); it != Check::instances().end(); ++it) { doc << "===" << (*it)->name() << "===\n" - << (*it)->classInfo() << "\n\n"; + << (*it)->classInfo() << "\n\n"; } doc << "===" << "Unused functions" << "===\n" - << "Check for functions that are never called\n"; + << "Check for functions that are never called\n"; std::string doc2(doc.str()); - while(doc2.find("\n\n\n") != std::string::npos) + while (doc2.find("\n\n\n") != std::string::npos) doc2.erase(doc2.find("\n\n\n"), 1); std::cout << doc2; return; } - else if(strncmp(argv[i], "-", 1) == 0 || strncmp(argv[i], "--", 2) == 0) + else if (strncmp(argv[i], "-", 1) == 0 || strncmp(argv[i], "--", 2) == 0) { throw std::runtime_error("cppcheck: error: unrecognized command line option \"" + std::string(argv[i]) + "\""); } @@ -363,99 +363,99 @@ void CppCheck::parseFromArgs(int argc, const char* const argv[]) pathnames.push_back(argv[i]); } - if(_settings.isEnabled("unusedFunctions") && _settings._jobs > 1) + if (_settings.isEnabled("unusedFunctions") && _settings._jobs > 1) { reportOut("unusedFunctions check can't be used with -j option, so it was disabled."); } - if(!pathnames.empty()) + if (!pathnames.empty()) { // Execute recursiveAddFiles() to each given file parameter std::vector::const_iterator iter; - for(iter = pathnames.begin(); iter != pathnames.end(); ++iter) + for (iter = pathnames.begin(); iter != pathnames.end(); ++iter) getFileLister()->recursiveAddFiles(_filenames, iter->c_str(), true); } - if(argc <= 1 || showHelp) + if (argc <= 1 || showHelp) { std::ostringstream oss; oss << "Cppcheck - A tool for static C/C++ code analysis\n" - "\n" - "Syntax:\n" - " cppcheck [--all] [--append=file] [--auto-dealloc file.lst] [--enable]\n" - " [--error-exitcode=[n]] [--exitcode-suppressions file] [--force]\n" - " [--help] [-Idir] [-j [jobs]] [--quiet] [--style]\n" - " [--suppressions file.txt] [--inline-suppr] [--file-list=file.txt]\n" - " [--verbose] [--version] [--xml] [file or path1] [file or path] ..\n" - "\n" - "If path is given instead of filename, *.cpp, *.cxx, *.cc, *.c++ and *.c files\n" - "are checked recursively from given directory.\n\n" - "Options:\n" - " -a, --all deprecated, use --enable=possibleError\n" - " --append=file This allows you to provide information about\n" - " functions by providing an implementation for these.\n" - " --auto-dealloc file Suppress warnings about classes that have automatic\n" - " deallocation.\n" - " The classnames must be provided in plain text - one\n" - " classname / line - in a .lst file.\n" - " This option can be used several times, allowing you to\n" - " specify several .lst files.\n" - " --enable=id Enable specific checks. The available ids are:\n" - " * all - enable all checks\n" - " * exceptNew - exception safety when using new\n" - " * exceptRealloc - exception safety when reallocating\n" - " * possibleError - Make the checking more sensitive.\n" - " More bugs are detected, but there are also\n" - " more false positives\n" - " * style - Check coding style\n" - " * unusedFunctions - check for unused functions\n" - " Several ids can be given if you separate them with commas\n" - " --error-exitcode=[n] If errors are found, integer [n] is returned instead\n" - " of default 0. EXIT_FAILURE is returned\n" - " if arguments are not valid or if no input files are\n" - " provided. Note that your operating system can\n" - " modify this value, e.g. 256 can become 0.\n" - " --exitcode-suppressions file\n" - " Used when certain messages should be displayed but\n" - " should not cause a non-zero exitcode.\n" - " -f, --force Force checking on files that have \"too many\"\n" - " configurations\n" - " -h, --help Print this help\n" - " -I [dir] Give include path. Give several -I parameters to give\n" - " several paths. First given path is checked first. If\n" - " paths are relative to source files, this is not needed\n" - " -j [jobs] Start [jobs] threads to do the checking simultaneously.\n" - " -q, --quiet Only print error messages\n" - " -s, --style deprecated, use --enable=style\n" - " --suppressions file Suppress warnings listed in the file. Filename and line\n" - " are optional. The format of the single line in file is:\n" - " [error id]:[filename]:[line]\n" - " --inline-suppr Enable inline suppressions. Use them by placing one or\n" - " more comments in the form: // cppcheck-suppress memleak\n" - " on the lines before the warning to suppress.\n" - " --file-list=file Specify the files to check in a text file. One Filename per line.\n" - " --template '[text]' Format the error messages. E.g.\n" - " '{file}:{line},{severity},{id},{message}' or\n" - " '{file}({line}):({severity}) {message}'\n" - " Pre-defined templates: gcc, vs\n" - " --unused-functions deprecated, use --enable=unusedFunctions\n" - " -v, --verbose More detailed error reports\n" - " --version Print out version number\n" - " --xml Write results in xml to error stream.\n" - "\n" - "Example usage:\n" - " # Recursively check the current folder. Print the progress on the screen and\n" - " write errors in a file:\n" - " cppcheck . 2> err.txt\n" - " # Recursively check ../myproject/ and print only most fatal errors:\n" - " cppcheck --quiet ../myproject/\n" - " # Check only files one.cpp and two.cpp and give all information there is:\n" - " cppcheck -v -a -s one.cpp two.cpp\n" - " # Check f.cpp and search include files from inc1/ and inc2/:\n" - " cppcheck -I inc1/ -I inc2/ f.cpp\n"; + "\n" + "Syntax:\n" + " cppcheck [--all] [--append=file] [--auto-dealloc file.lst] [--enable]\n" + " [--error-exitcode=[n]] [--exitcode-suppressions file] [--force]\n" + " [--help] [-Idir] [-j [jobs]] [--quiet] [--style]\n" + " [--suppressions file.txt] [--inline-suppr] [--file-list=file.txt]\n" + " [--verbose] [--version] [--xml] [file or path1] [file or path] ..\n" + "\n" + "If path is given instead of filename, *.cpp, *.cxx, *.cc, *.c++ and *.c files\n" + "are checked recursively from given directory.\n\n" + "Options:\n" + " -a, --all deprecated, use --enable=possibleError\n" + " --append=file This allows you to provide information about\n" + " functions by providing an implementation for these.\n" + " --auto-dealloc file Suppress warnings about classes that have automatic\n" + " deallocation.\n" + " The classnames must be provided in plain text - one\n" + " classname / line - in a .lst file.\n" + " This option can be used several times, allowing you to\n" + " specify several .lst files.\n" + " --enable=id Enable specific checks. The available ids are:\n" + " * all - enable all checks\n" + " * exceptNew - exception safety when using new\n" + " * exceptRealloc - exception safety when reallocating\n" + " * possibleError - Make the checking more sensitive.\n" + " More bugs are detected, but there are also\n" + " more false positives\n" + " * style - Check coding style\n" + " * unusedFunctions - check for unused functions\n" + " Several ids can be given if you separate them with commas\n" + " --error-exitcode=[n] If errors are found, integer [n] is returned instead\n" + " of default 0. EXIT_FAILURE is returned\n" + " if arguments are not valid or if no input files are\n" + " provided. Note that your operating system can\n" + " modify this value, e.g. 256 can become 0.\n" + " --exitcode-suppressions file\n" + " Used when certain messages should be displayed but\n" + " should not cause a non-zero exitcode.\n" + " -f, --force Force checking on files that have \"too many\"\n" + " configurations\n" + " -h, --help Print this help\n" + " -I [dir] Give include path. Give several -I parameters to give\n" + " several paths. First given path is checked first. If\n" + " paths are relative to source files, this is not needed\n" + " -j [jobs] Start [jobs] threads to do the checking simultaneously.\n" + " -q, --quiet Only print error messages\n" + " -s, --style deprecated, use --enable=style\n" + " --suppressions file Suppress warnings listed in the file. Filename and line\n" + " are optional. The format of the single line in file is:\n" + " [error id]:[filename]:[line]\n" + " --inline-suppr Enable inline suppressions. Use them by placing one or\n" + " more comments in the form: // cppcheck-suppress memleak\n" + " on the lines before the warning to suppress.\n" + " --file-list=file Specify the files to check in a text file. One Filename per line.\n" + " --template '[text]' Format the error messages. E.g.\n" + " '{file}:{line},{severity},{id},{message}' or\n" + " '{file}({line}):({severity}) {message}'\n" + " Pre-defined templates: gcc, vs\n" + " --unused-functions deprecated, use --enable=unusedFunctions\n" + " -v, --verbose More detailed error reports\n" + " --version Print out version number\n" + " --xml Write results in xml to error stream.\n" + "\n" + "Example usage:\n" + " # Recursively check the current folder. Print the progress on the screen and\n" + " write errors in a file:\n" + " cppcheck . 2> err.txt\n" + " # Recursively check ../myproject/ and print only most fatal errors:\n" + " cppcheck --quiet ../myproject/\n" + " # Check only files one.cpp and two.cpp and give all information there is:\n" + " cppcheck -v -a -s one.cpp two.cpp\n" + " # Check f.cpp and search include files from inc1/ and inc2/:\n" + " cppcheck -I inc1/ -I inc2/ f.cpp\n"; reportOut(oss.str()); } - else if(_filenames.empty()) + else if (_filenames.empty()) { throw std::runtime_error("cppcheck: No C or C++ source files found."); } @@ -467,15 +467,15 @@ unsigned int CppCheck::check() _checkUnusedFunctions.setErrorLogger(this); std::sort(_filenames.begin(), _filenames.end()); - for(unsigned int c = 0; c < _filenames.size(); c++) + for (unsigned int c = 0; c < _filenames.size(); c++) { _errout.str(""); const std::string fname = _filenames[c]; - if(_settings.terminated()) + if (_settings.terminated()) break; - if(_settings._errorsOnly == false) + if (_settings._errorsOnly == false) _errorLogger.reportOut(std::string("Checking ") + fname + std::string("...")); try @@ -484,7 +484,7 @@ unsigned int CppCheck::check() std::list configurations; std::string filedata = ""; - if(_fileContents.size() > 0 && _fileContents.find(_filenames[c]) != _fileContents.end()) + if (_fileContents.size() > 0 && _fileContents.find(_filenames[c]) != _fileContents.end()) { // File content was given as a string std::istringstream iss(_fileContents[ _filenames[c] ]); @@ -500,13 +500,13 @@ unsigned int CppCheck::check() } int checkCount = 0; - for(std::list::const_iterator it = configurations.begin(); it != configurations.end(); ++it) + for (std::list::const_iterator it = configurations.begin(); it != configurations.end(); ++it) { // Check only 12 first configurations, after that bail out, unless --force // was used. - if(!_settings._force && checkCount > 11) + if (!_settings._force && checkCount > 11) { - if(_settings._errorsOnly == false) + if (_settings._errorsOnly == false) _errorLogger.reportOut(std::string("Bailing out from checking ") + fname + ": Too many configurations. Recheck this file with --force if you want to check them all."); break; @@ -518,14 +518,14 @@ unsigned int CppCheck::check() TIMER_END("Preprocessor::getcode"); // If only errors are printed, print filename after the check - if(_settings._errorsOnly == false && it != configurations.begin()) + if (_settings._errorsOnly == false && it != configurations.begin()) _errorLogger.reportOut(std::string("Checking ") + fname + ": " + cfg + std::string("...")); checkFile(codeWithoutCfg + _settings.append(), _filenames[c].c_str()); ++checkCount; } } - catch(std::runtime_error &e) + catch (std::runtime_error &e) { // Exception was thrown when checking this file.. _errorLogger.reportOut("Bailing out from checking " + fname + ": " + e.what()); @@ -536,10 +536,10 @@ unsigned int CppCheck::check() // This generates false positives - especially for libraries _settings._verbose = false; - if(_settings.isEnabled("unusedFunctions") && _settings._jobs == 1) + if (_settings.isEnabled("unusedFunctions") && _settings._jobs == 1) { _errout.str(""); - if(_settings._errorsOnly == false) + if (_settings._errorsOnly == false) _errorLogger.reportOut("Checking usage of global functions.."); _checkUnusedFunctions.check(); @@ -556,7 +556,7 @@ unsigned int CppCheck::check() void CppCheck::checkFile(const std::string &code, const char FileName[]) { - if(_settings.terminated()) + if (_settings.terminated()) return; Tokenizer _tokenizer(&_settings, this); @@ -565,7 +565,7 @@ void CppCheck::checkFile(const std::string &code, const char FileName[]) { std::istringstream istr(code); TIMER_START(); - if(!_tokenizer.tokenize(istr, FileName, cfg)) + if (!_tokenizer.tokenize(istr, FileName, cfg)) { // File had syntax errors, abort return; @@ -580,9 +580,9 @@ void CppCheck::checkFile(const std::string &code, const char FileName[]) } // call all "runChecks" in all registered Check classes - for(std::list::iterator it = Check::instances().begin(); it != Check::instances().end(); ++it) + for (std::list::iterator it = Check::instances().begin(); it != Check::instances().end(); ++it) { - if(_settings.terminated()) + if (_settings.terminated()) return; TIMER_START(); @@ -594,7 +594,7 @@ void CppCheck::checkFile(const std::string &code, const char FileName[]) TIMER_START(); bool result = _tokenizer.simplifyTokenList(); TIMER_END("Tokenizer::simplifyTokenList"); - if(!result) + if (!result) return; } @@ -604,13 +604,13 @@ void CppCheck::checkFile(const std::string &code, const char FileName[]) TIMER_END("Tokenizer::fillFunctionList"); } - if(_settings.isEnabled("unusedFunctions") && _settings._jobs == 1) + if (_settings.isEnabled("unusedFunctions") && _settings._jobs == 1) _checkUnusedFunctions.parseTokens(_tokenizer); // call all "runSimplifiedChecks" in all registered Check classes - for(std::list::iterator it = Check::instances().begin(); it != Check::instances().end(); ++it) + for (std::list::iterator it = Check::instances().begin(); it != Check::instances().end(); ++it) { - if(_settings.terminated()) + if (_settings.terminated()) return; TIMER_START(); @@ -631,26 +631,26 @@ void CppCheck::reportErr(const ErrorLogger::ErrorMessage &msg) std::string errmsg = msg.toText(); // Alert only about unique errors - if(std::find(_errorList.begin(), _errorList.end(), errmsg) != _errorList.end()) + if (std::find(_errorList.begin(), _errorList.end(), errmsg) != _errorList.end()) return; std::string file; unsigned int line(0); - if(!msg._callStack.empty()) + if (!msg._callStack.empty()) { file = msg._callStack.back().getfile(); line = msg._callStack.back().line; } - if(_settings.nomsg.isSuppressed(msg._id, file, line)) + if (_settings.nomsg.isSuppressed(msg._id, file, line)) return; - if(!_settings.nofail.isSuppressed(msg._id, file, line)) + if (!_settings.nofail.isSuppressed(msg._id, file, line)) exitcode = 1; _errorList.push_back(errmsg); std::string errmsg2(errmsg); - if(_settings._verbose) + if (_settings._verbose) { errmsg2 += "\n Defines=\'" + cfg + "\'\n"; } diff --git a/lib/errorlogger.cpp b/lib/errorlogger.cpp index fb4fbf644..d3c64265b 100644 --- a/lib/errorlogger.cpp +++ b/lib/errorlogger.cpp @@ -43,7 +43,7 @@ std::string ErrorLogger::ErrorMessage::serialize() const oss << _msg.length() << " " << _msg; oss << _callStack.size() << " "; - for(std::list::const_iterator tok = _callStack.begin(); tok != _callStack.end(); ++tok) + for (std::list::const_iterator tok = _callStack.begin(); tok != _callStack.end(); ++tok) { std::ostringstream smallStream; smallStream << (*tok).line << ":" << (*tok).getfile(); @@ -57,22 +57,22 @@ bool ErrorLogger::ErrorMessage::deserialize(const std::string &data) _callStack.clear(); std::istringstream iss(data); std::vector results; - while(iss.good()) + while (iss.good()) { unsigned int len = 0; - if(!(iss >> len)) + if (!(iss >> len)) return false; iss.get(); std::string temp; - for(unsigned int i = 0; i < len && iss.good(); ++i) + for (unsigned int i = 0; i < len && iss.good(); ++i) { char c = static_cast(iss.get()); temp.append(1, c); } results.push_back(temp); - if(results.size() == 3) + if (results.size() == 3) break; } @@ -81,18 +81,18 @@ bool ErrorLogger::ErrorMessage::deserialize(const std::string &data) _msg = results[2]; unsigned int stackSize = 0; - if(!(iss >> stackSize)) + if (!(iss >> stackSize)) return false; - while(iss.good()) + while (iss.good()) { unsigned int len = 0; - if(!(iss >> len)) + if (!(iss >> len)) return false; iss.get(); std::string temp; - for(unsigned int i = 0; i < len && iss.good(); ++i) + for (unsigned int i = 0; i < len && iss.good(); ++i) { char c = static_cast(iss.get()); temp.append(1, c); @@ -106,7 +106,7 @@ bool ErrorLogger::ErrorMessage::deserialize(const std::string &data) _callStack.push_back(loc); - if(_callStack.size() >= stackSize) + if (_callStack.size() >= stackSize) break; } @@ -127,15 +127,15 @@ std::string ErrorLogger::ErrorMessage::getXMLFooter() static std::string stringToXml(std::string s) { std::string::size_type pos = 0; - while((pos = s.find_first_of("<>&\"", pos)) != std::string::npos) + while ((pos = s.find_first_of("<>&\"", pos)) != std::string::npos) { - if(s[pos] == '<') + if (s[pos] == '<') s.insert(pos + 1, "<"); - else if(s[pos] == '>') + else if (s[pos] == '>') s.insert(pos + 1, ">"); - else if(s[pos] == '&') + else if (s[pos] == '&') s.insert(pos + 1, "&"); - else if(s[pos] == '"') + else if (s[pos] == '"') s.insert(pos + 1, """); s.erase(pos, 1); ++pos; @@ -147,7 +147,7 @@ std::string ErrorLogger::ErrorMessage::toXML() const { std::ostringstream xml; xml << " &callstack, const char severity[], const std::string &msg, const std::string &id) { std::list locationList; - for(std::list::const_iterator tok = callstack.begin(); tok != callstack.end(); ++tok) + for (std::list::const_iterator tok = callstack.begin(); tok != callstack.end(); ++tok) { ErrorLogger::ErrorMessage::FileLocation loc; loc.file = tokenizer->file(*tok); @@ -232,7 +232,7 @@ void ErrorLogger::_writemsg(const Tokenizer *tokenizer, const std::list &callStack) { std::ostringstream ostr; - for(std::list::const_iterator tok = callStack.begin(); tok != callStack.end(); ++tok) + for (std::list::const_iterator tok = callStack.begin(); tok != callStack.end(); ++tok) ostr << (tok == callStack.begin() ? "" : " -> ") << "[" << (*tok).getfile() << ":" << (*tok).line << "]"; return ostr.str(); } @@ -244,23 +244,23 @@ std::string ErrorLogger::ErrorMessage::FileLocation::getfile() const // replace "/ab/.." with "/".. std::string::size_type pos = 0; - while((pos = f.find("..", pos + 1)) != std::string::npos) + while ((pos = f.find("..", pos + 1)) != std::string::npos) { // position must be at least 4.. - if(pos < 4) + if (pos < 4) continue; // Previous char must be a separator.. - if(f[pos-1] != '/' && f[pos-2] != '\\') + if (f[pos-1] != '/' && f[pos-2] != '\\') continue; // Next char must be a separator.. - if(f[pos+2] != '/' && f[pos+2] != '\\') + if (f[pos+2] != '/' && f[pos+2] != '\\') continue; // Locate previous separator.. std::string::size_type sep = f.find_last_of("/\\", pos - 2); - if(sep == std::string::npos) + if (sep == std::string::npos) continue; // Delete substring.. diff --git a/lib/errorlogger.h b/lib/errorlogger.h index 3f2245d8e..6dce504b7 100644 --- a/lib/errorlogger.h +++ b/lib/errorlogger.h @@ -359,7 +359,7 @@ public: enum e { error, style, possibleError, possibleStyle }; static std::string stringify(e severity) { - switch(severity) + switch (severity) { case error: return "error"; diff --git a/lib/executionpath.cpp b/lib/executionpath.cpp index d5c6f55ce..abaab0a2c 100644 --- a/lib/executionpath.cpp +++ b/lib/executionpath.cpp @@ -25,27 +25,27 @@ // default : bail out if the condition is has variable handling bool ExecutionPath::parseCondition(const Token &tok, std::list & checks) { - if(Token::Match(tok.tokAt(-3), "!!else if (")) + if (Token::Match(tok.tokAt(-3), "!!else if (")) { ++ifinfo; } unsigned int parlevel = 0; - for(const Token *tok2 = &tok; tok2; tok2 = tok2->next()) + for (const Token *tok2 = &tok; tok2; tok2 = tok2->next()) { - if(tok2->str() == "(") + if (tok2->str() == "(") ++parlevel; - else if(tok2->str() == ")") + else if (tok2->str() == ")") { - if(parlevel == 0) + if (parlevel == 0) break; --parlevel; } - else if(Token::Match(tok2, ";{}")) + else if (Token::Match(tok2, ";{}")) break; - if(tok2->varId() != 0) + if (tok2->varId() != 0) { - if(ifinfo > 1) + if (ifinfo > 1) return true; else bailOutVar(checks, tok2->varId()); @@ -58,33 +58,33 @@ bool ExecutionPath::parseCondition(const Token &tok, std::list static const Token *checkExecutionPaths_(const Token *tok, std::list &checks) { - if(!tok || tok->str() == "}" || checks.empty()) + if (!tok || tok->str() == "}" || checks.empty()) return 0; const std::auto_ptr check(checks.front()->copy()); - for(; tok; tok = tok->next()) + for (; tok; tok = tok->next()) { - if(tok->str() == "}") + if (tok->str() == "}") return 0; - if(Token::simpleMatch(tok, "while (")) + if (Token::simpleMatch(tok, "while (")) { // parse condition - if(checks.size() > 10 || check->parseCondition(*tok->tokAt(2), checks)) + if (checks.size() > 10 || check->parseCondition(*tok->tokAt(2), checks)) { ExecutionPath::bailOut(checks); return 0; } // skip "while (fgets()!=NULL)" - if(Token::simpleMatch(tok, "while ( fgets (")) + if (Token::simpleMatch(tok, "while ( fgets (")) { const Token *tok2 = tok->tokAt(3)->link(); - if(Token::simpleMatch(tok2, ") ) {")) + if (Token::simpleMatch(tok2, ") ) {")) { tok = tok2->tokAt(2)->link(); - if(!tok) + if (!tok) break; continue; } @@ -92,15 +92,15 @@ static const Token *checkExecutionPaths_(const Token *tok, std::listnext(); - if(tok2 && tok2->str() == "(") + if (tok2 && tok2->str() == "(") tok2 = tok2->link(); - if(tok2 && tok2->str() == ")") + if (tok2 && tok2->str() == ")") tok2 = tok2->next(); - if(!tok2 || tok2->str() != "{") + if (!tok2 || tok2->str() != "{") { ExecutionPath::bailOut(checks); return 0; @@ -110,16 +110,16 @@ static const Token *checkExecutionPaths_(const Token *tok, std::listlink(); // if "do { .. } while ( .." , goto end of while.. - if(Token::simpleMatch(tok, "do {") && Token::simpleMatch(tok2, "} while (")) + if (Token::simpleMatch(tok, "do {") && Token::simpleMatch(tok2, "} while (")) tok2 = tok2->tokAt(2)->link(); // bail out all variables if the scope contains a "return" // bail out all variables used in this for/while/switch/do - for(; tok && tok != tok2; tok = tok->next()) + for (; tok && tok != tok2; tok = tok->next()) { - if(tok->str() == "return") + if (tok->str() == "return") ExecutionPath::bailOut(checks); - if(tok->varId()) + if (tok->varId()) ExecutionPath::bailOutVar(checks, tok->varId()); } @@ -127,37 +127,37 @@ static const Token *checkExecutionPaths_(const Token *tok, std::list bail out - if(Token::simpleMatch(tok, ") {")) + if (Token::simpleMatch(tok, ") {")) { ExecutionPath::bailOut(checks); return 0; } - if(Token::Match(tok, "abort|exit (")) + if (Token::Match(tok, "abort|exit (")) { ExecutionPath::bailOut(checks); return 0; } // don't parse into "struct type { .." - if(Token::Match(tok, "struct|union|class %type% {|:")) + if (Token::Match(tok, "struct|union|class %type% {|:")) { - while(tok && tok->str() != "{" && tok->str() != ";") + while (tok && tok->str() != "{" && tok->str() != ";") tok = tok->next(); tok = tok ? tok->link() : 0; } - if(Token::Match(tok, "= {")) + if (Token::Match(tok, "= {")) { // GCC struct initialization.. bail out - if(Token::Match(tok->tokAt(2), ". %var% =")) + if (Token::Match(tok->tokAt(2), ". %var% =")) { ExecutionPath::bailOut(checks); return 0; } tok = tok->next()->link(); - if(!tok) + if (!tok) { ExecutionPath::bailOut(checks); return 0; @@ -166,10 +166,10 @@ static const Token *checkExecutionPaths_(const Token *tok, std::listprevious(), "[;{}] {")) + if (Token::Match(tok->previous(), "[;{}] {")) { const Token *tokerr = checkExecutionPaths_(tok->next(), checks); - if(tokerr) + if (tokerr) { ExecutionPath::bailOut(checks); return tokerr; @@ -178,16 +178,16 @@ static const Token *checkExecutionPaths_(const Token *tok, std::liststr() == "if") + if (tok->str() == "if") { std::list newchecks; - while(tok->str() == "if") + while (tok->str() == "if") { // goto "(" tok = tok->next(); // parse condition - if(checks.size() > 10 || check->parseCondition(*tok->next(), checks)) + if (checks.size() > 10 || check->parseCondition(*tok->next(), checks)) { ExecutionPath::bailOut(checks); ExecutionPath::bailOut(newchecks); @@ -200,7 +200,7 @@ static const Token *checkExecutionPaths_(const Token *tok, std::listnext() : 0; - if(!Token::simpleMatch(tok, "{")) + if (!Token::simpleMatch(tok, "{")) { ExecutionPath::bailOut(checks); ExecutionPath::bailOut(newchecks); @@ -211,16 +211,16 @@ static const Token *checkExecutionPaths_(const Token *tok, std::list c; std::list::iterator it; - for(it = checks.begin(); it != checks.end(); ++it) + for (it = checks.begin(); it != checks.end(); ++it) c.push_back((*it)->copy()); const Token *tokerr = checkExecutionPaths_(tok->next(), c); - if(tokerr) + if (tokerr) { ExecutionPath::bailOut(c); ExecutionPath::bailOut(newchecks); return tokerr; } - while(!c.empty()) + while (!c.empty()) { newchecks.push_back(c.back()); c.pop_back(); @@ -231,24 +231,24 @@ static const Token *checkExecutionPaths_(const Token *tok, std::listlink(); // there is no else => break out - if(Token::Match(tok, "} !!else")) + if (Token::Match(tok, "} !!else")) break; // parse next "if".. tok = tok->tokAt(2); - if(tok->str() == "if") + if (tok->str() == "if") continue; // there is no "if".. const Token *tokerr = checkExecutionPaths_(tok->next(), checks); - if(tokerr) + if (tokerr) { ExecutionPath::bailOut(newchecks); return tokerr; } tok = tok->link(); - if(!tok) + if (!tok) { ExecutionPath::bailOut(newchecks); return 0; @@ -256,7 +256,7 @@ static const Token *checkExecutionPaths_(const Token *tok, std::list::iterator it; - for(it = newchecks.begin(); it != newchecks.end(); ++it) + for (it = newchecks.begin(); it != newchecks.end(); ++it) checks.push_back(*it); } @@ -264,14 +264,14 @@ static const Token *checkExecutionPaths_(const Token *tok, std::listparse(*tok, foundError, checks); - if(checks.empty()) + if (checks.empty()) return 0; - else if(foundError) + else if (foundError) return tok; } // return/throw ends all execution paths - if(tok->str() == "return" || tok->str() == "throw") + if (tok->str() == "return" || tok->str() == "throw") { ExecutionPath::bailOut(checks); } @@ -281,17 +281,17 @@ static const Token *checkExecutionPaths_(const Token *tok, std::listnext()) + for (; tok; tok = tok->next()) { - if(tok->str() != ")") + if (tok->str() != ")") continue; // Start of implementation.. - if(Token::Match(tok, ") const| {")) + if (Token::Match(tok, ") const| {")) { // goto the "{" tok = tok->next(); - if(tok->str() == "const") + if (tok->str() == "const") tok = tok->next(); std::list checks; @@ -300,7 +300,7 @@ void checkExecutionPaths(const Token *tok, ExecutionPath *c) c->end(checks, tok->link()); - while(!checks.empty()) + while (!checks.empty()) { delete checks.back(); checks.pop_back(); diff --git a/lib/executionpath.h b/lib/executionpath.h index 3f8cb24c6..6672baf55 100644 --- a/lib/executionpath.h +++ b/lib/executionpath.h @@ -57,7 +57,7 @@ public: **/ static void bailOut(std::list &checks) { - while(!checks.empty()) + while (!checks.empty()) { delete checks.back(); checks.pop_back(); @@ -71,13 +71,13 @@ public: **/ static void bailOutVar(std::list &checks, const unsigned int varid) { - if(varid == 0) + if (varid == 0) return; std::list::iterator it = checks.begin(); - while(it != checks.end()) + while (it != checks.end()) { - if((*it)->varId == varid) + if ((*it)->varId == varid) { delete *it; checks.erase(it++); diff --git a/lib/filelister.cpp b/lib/filelister.cpp index bc0c43f2d..7ba74d21a 100644 --- a/lib/filelister.cpp +++ b/lib/filelister.cpp @@ -36,7 +36,7 @@ static FileLister *fileLister; FileLister * getFileLister() { - if(fileLister == NULL) + if (fileLister == NULL) { #if defined(_WIN32) fileLister = new FileListerWin32; @@ -52,11 +52,11 @@ std::string FileLister::simplifyPath(const char *originalPath) { std::string subPath = ""; std::vector pathParts; - for(; *originalPath; ++originalPath) + for (; *originalPath; ++originalPath) { - if(*originalPath == '/' || *originalPath == '\\') + if (*originalPath == '/' || *originalPath == '\\') { - if(subPath.length() > 0) + if (subPath.length() > 0) { pathParts.push_back(subPath); subPath = ""; @@ -68,12 +68,12 @@ std::string FileLister::simplifyPath(const char *originalPath) subPath.append(1, *originalPath); } - if(subPath.length() > 0) + if (subPath.length() > 0) pathParts.push_back(subPath); - for(std::vector::size_type i = 0; i < pathParts.size(); ++i) + for (std::vector::size_type i = 0; i < pathParts.size(); ++i) { - if(pathParts[i] == ".." && i > 1 && pathParts.size() > i + 1) + if (pathParts[i] == ".." && i > 1 && pathParts.size() > i + 1) { pathParts.erase(pathParts.begin() + i + 1); pathParts.erase(pathParts.begin() + i); @@ -81,12 +81,12 @@ std::string FileLister::simplifyPath(const char *originalPath) pathParts.erase(pathParts.begin() + i - 2); i = 0; } - else if(i > 0 && pathParts[i] == ".") + else if (i > 0 && pathParts[i] == ".") { pathParts.erase(pathParts.begin() + i); i = 0; } - else if(pathParts[i] == "/" && i > 0 && pathParts[i-1] == "/") + else if (pathParts[i] == "/" && i > 0 && pathParts[i-1] == "/") { pathParts.erase(pathParts.begin() + i - 1); i = 0; @@ -94,7 +94,7 @@ std::string FileLister::simplifyPath(const char *originalPath) } std::ostringstream oss; - for(std::vector::size_type i = 0; i < pathParts.size(); ++i) + for (std::vector::size_type i = 0; i < pathParts.size(); ++i) { oss << pathParts[i]; } @@ -112,18 +112,18 @@ static int tolowerWrapper(int c) bool FileLister::acceptFile(const std::string &filename) { std::string::size_type dotLocation = filename.find_last_of('.'); - if(dotLocation == std::string::npos) + if (dotLocation == std::string::npos) return false; std::string extension = filename.substr(dotLocation); std::transform(extension.begin(), extension.end(), extension.begin(), tolowerWrapper); - if(extension == ".cpp" || - extension == ".cxx" || - extension == ".cc" || - extension == ".c" || - extension == ".c++" || - extension == ".txx") + if (extension == ".cpp" || + extension == ".cxx" || + extension == ".cc" || + extension == ".c" || + extension == ".c++" || + extension == ".txx") { return true; } diff --git a/lib/filelister_unix.cpp b/lib/filelister_unix.cpp index 27a1ba1c5..8e49b964b 100644 --- a/lib/filelister_unix.cpp +++ b/lib/filelister_unix.cpp @@ -41,26 +41,26 @@ void FileListerUnix::recursiveAddFiles(std::vector &filenames, cons { std::ostringstream oss; oss << path; - if(path.length() > 0 && path[path.length()-1] == '/') + if (path.length() > 0 && path[path.length()-1] == '/') oss << "*"; glob_t glob_results; glob(oss.str().c_str(), GLOB_MARK, 0, &glob_results); - for(unsigned int i = 0; i < glob_results.gl_pathc; i++) + for (unsigned int i = 0; i < glob_results.gl_pathc; i++) { std::string filename = glob_results.gl_pathv[i]; - if(filename == "." || filename == ".." || filename.length() == 0) + if (filename == "." || filename == ".." || filename.length() == 0) continue; - if(filename[filename.length()-1] != '/') + if (filename[filename.length()-1] != '/') { // File // If recursive is not used, accept all files given by user - if(!recursive || FileLister::acceptFile(filename)) + if (!recursive || FileLister::acceptFile(filename)) filenames.push_back(filename); } - else if(recursive) + else if (recursive) { // Directory getFileLister()->recursiveAddFiles(filenames, filename, recursive); diff --git a/lib/filelister_win32.cpp b/lib/filelister_win32.cpp index da8c8f001..22767d7ed 100644 --- a/lib/filelister_win32.cpp +++ b/lib/filelister_win32.cpp @@ -107,10 +107,10 @@ void FileListerWin32::recursiveAddFiles(std::vector &filenames, con oss << cleanedPath; - if(MyIsDirectory(cleanedPath.c_str())) + if (MyIsDirectory(cleanedPath.c_str())) { char c = cleanedPath[ cleanedPath.size()-1 ]; - switch(c) + switch (c) { case '\\': oss << '*'; @@ -128,7 +128,7 @@ void FileListerWin32::recursiveAddFiles(std::vector &filenames, con { std::string::size_type pos; pos = cleanedPath.find_last_of('\\'); - if(std::string::npos != pos) + if (std::string::npos != pos) { bdir << cleanedPath.substr(0, pos + 1); } @@ -136,12 +136,12 @@ void FileListerWin32::recursiveAddFiles(std::vector &filenames, con WIN32_FIND_DATA ffd; HANDLE hFind = MyFindFirstFile(oss.str(), &ffd); - if(INVALID_HANDLE_VALUE == hFind) + if (INVALID_HANDLE_VALUE == hFind) return; do { - if(ffd.cFileName[0] == '.' || ffd.cFileName[0] == '\0') + if (ffd.cFileName[0] == '.' || ffd.cFileName[0] == '\0') continue; #if defined(UNICODE) @@ -154,15 +154,15 @@ void FileListerWin32::recursiveAddFiles(std::vector &filenames, con std::ostringstream fname; fname << bdir.str().c_str() << ansiFfd; - if((ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) + if ((ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) { // File // If recursive is not used, accept all files given by user - if(!recursive || FileLister::acceptFile(ansiFfd)) + if (!recursive || FileLister::acceptFile(ansiFfd)) filenames.push_back(fname.str()); } - else if(recursive) + else if (recursive) { // Directory getFileLister()->recursiveAddFiles(filenames, fname.str().c_str(), recursive); @@ -171,9 +171,9 @@ void FileListerWin32::recursiveAddFiles(std::vector &filenames, con delete [] ansiFfd; #endif // defined(UNICODE) } - while(FindNextFile(hFind, &ffd) != FALSE); + while (FindNextFile(hFind, &ffd) != FALSE); - if(INVALID_HANDLE_VALUE != hFind) + if (INVALID_HANDLE_VALUE != hFind) { FindClose(hFind); hFind = INVALID_HANDLE_VALUE; diff --git a/lib/mathlib.cpp b/lib/mathlib.cpp index b99ec9023..436d645bf 100644 --- a/lib/mathlib.cpp +++ b/lib/mathlib.cpp @@ -32,15 +32,15 @@ long MathLib::toLongNumber(const std::string &str) { - if(str.compare(0, 2, "0x") == 0 - || str.compare(0, 3, "+0x") == 0 - || str.compare(0, 3, "-0x") == 0) + if (str.compare(0, 2, "0x") == 0 + || str.compare(0, 3, "+0x") == 0 + || str.compare(0, 3, "-0x") == 0) { return std::strtoul(str.c_str(), '\0', 16); } - if(str.compare(0, 1, "0") == 0 - || str.compare(0, 2, "+0") == 0 - || str.compare(0, 2, "-0") == 0) + if (str.compare(0, 1, "0") == 0 + || str.compare(0, 2, "+0") == 0 + || str.compare(0, 2, "-0") == 0) { return std::strtoul(str.c_str(), '\0', 8); } @@ -51,7 +51,7 @@ long MathLib::toLongNumber(const std::string &str) double MathLib::toDoubleNumber(const std::string &str) { - if(str.compare(0, 2, "0x") == 0) + if (str.compare(0, 2, "0x") == 0) { return std::strtoul(str.c_str(), '\0', 16); } @@ -67,25 +67,25 @@ std::string MathLib::toString(T d) std::ostringstream result; result << d; std::string strResult(result.str()); - if(strResult == "-0" - || strResult == "+0" - || strResult == "-0." - || strResult == "+0.") + if (strResult == "-0" + || strResult == "+0" + || strResult == "-0." + || strResult == "+0.") return std::string("0"); return result.str(); } bool MathLib::isFloat(const std::string &s) { - // every number that contains a . is a float - if(s.find("." , 0) != std::string::npos) - return true; - // scientific notation - else if(s.find("E-", 0) != std::string::npos - || s.find("e-", 0) != std::string::npos) - return true; - - return false; + // every number that contains a . is a float + if (s.find("." , 0) != std::string::npos) + return true; + // scientific notation + else if (s.find("E-", 0) != std::string::npos + || s.find("e-", 0) != std::string::npos) + return true; + + return false; } bool MathLib::isNegative(const std::string &s) @@ -93,12 +93,12 @@ bool MathLib::isNegative(const std::string &s) // remember position unsigned long n = 0; // eat up whitespace - while(std::isspace(s[n])) ++n; - // every negative number has a negative sign - if(s[n] == '-') - return true; - - return false; + while (std::isspace(s[n])) ++n; + // every negative number has a negative sign + if (s[n] == '-') + return true; + + return false; } bool MathLib::isInt(const std::string & s) @@ -106,9 +106,9 @@ bool MathLib::isInt(const std::string & s) // perform prechecks: // ------------------ // first check, if a point is found, it is an floating point value - if(s.find(".", 0) != std::string::npos) return false; + if (s.find(".", 0) != std::string::npos) return false; // check for scientific notation e.g. NumberE-Number this is obvious an floating point value - else if(s.find("E-", 0) != std::string::npos || s.find("e-", 0) != std::string::npos) return false; + else if (s.find("E-", 0) != std::string::npos || s.find("e-", 0) != std::string::npos) return false; // prechecking has nothing found,... @@ -127,70 +127,70 @@ bool MathLib::isInt(const std::string & s) // remember position unsigned long n = 0; // eat up whitespace - while(std::isspace(s[n])) ++n; + while (std::isspace(s[n])) ++n; // determine type - if(s.find("E", 0) != std::string::npos) + if (s.find("E", 0) != std::string::npos) { Mode = eScientific; } - else if(s.find("0x", n, 2) != std::string::npos) + else if (s.find("0x", n, 2) != std::string::npos) { Mode = eHex; } - else if(s.length() > 1 && s[0] == '0' && std::isdigit(s[1])) + else if (s.length() > 1 && s[0] == '0' && std::isdigit(s[1])) { Mode = eOctal; } // check sign - if(s[n] == '-' || s[n] == '+') ++n; + if (s[n] == '-' || s[n] == '+') ++n; // check scientific notation - if(Mode == eScientific) + if (Mode == eScientific) { // check digits - while(std::isdigit(s[n])) ++n; + while (std::isdigit(s[n])) ++n; // check scientific notation - if(std::tolower(s[n]) == 'e') + if (std::tolower(s[n]) == 'e') { ++n; // check positive exponent - if(s[n] == '+') ++n; + if (s[n] == '+') ++n; // floating pointer number e.g. 124E-2 - if(s[n] == '-') return false; + if (s[n] == '-') return false; // check digits of the exponent - while(std::isdigit(s[n])) ++n; + while (std::isdigit(s[n])) ++n; } } // check hex notation - else if(Mode == eHex) + else if (Mode == eHex) { ++n; // 0 ++n; // x - while(std::isxdigit(s[n])) + while (std::isxdigit(s[n])) ++n; } // check octal notation - else if(Mode == eOctal) + else if (Mode == eOctal) { - while(isOctalDigit(s[n])) + while (isOctalDigit(s[n])) ++n; } - else if(Mode == eDefault) + else if (Mode == eDefault) { - while(std::isdigit(s[n])) ++n; + while (std::isdigit(s[n])) ++n; // unsigned or long - while(std::tolower(s[n]) == 'u' || std::tolower(s[n]) == 'l') ++n; + while (std::tolower(s[n]) == 'u' || std::tolower(s[n]) == 'l') ++n; } // eat up whitespace - while(std::isspace(s[n])) + while (std::isspace(s[n])) ++n; // if everything goes good, we are at the end of the string and no digits/character // is here --> return true, but if something was found eg. 12E+12AA return false - if(s[n]) + if (s[n]) return false; return true; @@ -198,7 +198,7 @@ bool MathLib::isInt(const std::string & s) std::string MathLib::add(const std::string & first, const std::string & second) { - if(MathLib::isInt(first) && MathLib::isInt(second)) + if (MathLib::isInt(first) && MathLib::isInt(second)) { return toString(toLongNumber(first) + toLongNumber(second)); } @@ -207,7 +207,7 @@ std::string MathLib::add(const std::string & first, const std::string & second) std::string MathLib::subtract(const std::string &first, const std::string &second) { - if(MathLib::isInt(first) && MathLib::isInt(second)) + if (MathLib::isInt(first) && MathLib::isInt(second)) { return toString(toLongNumber(first) - toLongNumber(second)); } @@ -216,7 +216,7 @@ std::string MathLib::subtract(const std::string &first, const std::string &secon std::string MathLib::divide(const std::string &first, const std::string &second) { - if(MathLib::isInt(first) && MathLib::isInt(second)) + if (MathLib::isInt(first) && MathLib::isInt(second)) { return toString(toLongNumber(first) / toLongNumber(second)); } @@ -225,7 +225,7 @@ std::string MathLib::divide(const std::string &first, const std::string &second) std::string MathLib::multiply(const std::string &first, const std::string &second) { - if(MathLib::isInt(first) && MathLib::isInt(second)) + if (MathLib::isInt(first) && MathLib::isInt(second)) { return toString(toLongNumber(first) * toLongNumber(second)); } @@ -236,7 +236,7 @@ std::string MathLib::calculate(const std::string &first, const std::string &seco { std::string result("0"); - switch(action) + switch (action) { case '+': result = MathLib::add(first, second); @@ -295,7 +295,7 @@ bool MathLib::isGreater(const std::string &first, const std::string &second) bool MathLib::isOctalDigit(char c) { - if(c == '0' || c == '1' || c == '2' || c == '3' || c == '4' || c == '5' || c == '6' || c == '7') + if (c == '0' || c == '1' || c == '2' || c == '3' || c == '4' || c == '5' || c == '6' || c == '7') return true; return false; diff --git a/lib/mathlib.h b/lib/mathlib.h index 6019f3e0f..aa779d955 100644 --- a/lib/mathlib.h +++ b/lib/mathlib.h @@ -37,8 +37,8 @@ public: static std::string toString(T d); static bool isInt(const std::string & str); - static bool isFloat(const std::string &str); - static bool isNegative(const std::string &str); + static bool isFloat(const std::string &str); + static bool isNegative(const std::string &str); static std::string add(const std::string & first, const std::string & second); static std::string subtract(const std::string & first, const std::string & second); diff --git a/lib/preprocessor.cpp b/lib/preprocessor.cpp index d533b310e..262ccec63 100644 --- a/lib/preprocessor.cpp +++ b/lib/preprocessor.cpp @@ -40,7 +40,7 @@ Preprocessor::Preprocessor(Settings *settings, ErrorLogger *errorLogger) : _sett void Preprocessor::writeError(const std::string &fileName, const int linenr, ErrorLogger *errorLogger, const std::string &errorType, const std::string &errorText) { - if(!errorLogger) + if (!errorLogger) return; std::list locationList; @@ -59,10 +59,10 @@ static unsigned char readChar(std::istream &istr) unsigned char ch = (unsigned char)istr.get(); // Handling of newlines.. - if(ch == '\r') + if (ch == '\r') { ch = '\n'; - if((char)istr.peek() == '\n') + if ((char)istr.peek() == '\n') (void)istr.get(); } @@ -84,36 +84,36 @@ std::string Preprocessor::read(std::istream &istr, const std::string &filename, unsigned int newlines = 0; std::ostringstream code; - for(unsigned char ch = readChar(istr); istr.good(); ch = readChar(istr)) + for (unsigned char ch = readChar(istr); istr.good(); ch = readChar(istr)) { // Replace assorted special chars with spaces.. - if(((ch & 0x80) == 0) && (ch != '\n') && (std::isspace(ch) || std::iscntrl(ch))) + if (((ch & 0x80) == 0) && (ch != '\n') && (std::isspace(ch) || std::iscntrl(ch))) ch = ' '; // Skip spaces after ' ' and after '#' - if(ch == ' ' && ignoreSpace) + if (ch == ' ' && ignoreSpace) continue; ignoreSpace = bool(ch == ' ' || ch == '#' || ch == '\n'); - if(needSpace) + if (needSpace) { - if(ch == '(' || ch == '!') + if (ch == '(' || ch == '!') code << " "; - else if(!std::isalpha(ch)) + else if (!std::isalpha(ch)) needSpace = false; } - if(ch == '#') + if (ch == '#') needSpace = true; // .. - if(ch == '\\') + if (ch == '\\') { unsigned char chNext = 0; - for(;;) + for (;;) { chNext = (unsigned char)istr.peek(); - if(chNext != '\n' && chNext != '\r' && - (std::isspace(chNext) || std::iscntrl(chNext))) + if (chNext != '\n' && chNext != '\r' && + (std::isspace(chNext) || std::iscntrl(chNext))) { // Skip whitespace between and (void)readChar(istr); @@ -123,7 +123,7 @@ std::string Preprocessor::read(std::istream &istr, const std::string &filename, break; } - if(chNext == '\n' || chNext == '\r') + if (chNext == '\n' || chNext == '\r') { ++newlines; (void)readChar(istr); // Skip the "" @@ -138,7 +138,7 @@ std::string Preprocessor::read(std::istream &istr, const std::string &filename, code << std::string(1, ch); // if there has been sequences, add extra newlines.. - if(ch == '\n' && newlines > 0) + if (ch == '\n' && newlines > 0) { code << std::string(newlines, '\n'); newlines = 0; @@ -171,25 +171,25 @@ std::string Preprocessor::removeComments(const std::string &str, const std::stri unsigned char previous = 0; std::vector suppressionIDs; - for(std::string::size_type i = hasbom(str) ? 3 : 0; i < str.length(); ++i) + for (std::string::size_type i = hasbom(str) ? 3 : 0; i < str.length(); ++i) { unsigned char ch = str[i]; - if(ch & 0x80) + if (ch & 0x80) { std::ostringstream errmsg; errmsg << "The code contains characters that are unhandled. " - << "Neither unicode nor extended ascii are supported. " - << "(line=" << lineno << ", character code=" << std::hex << (int(ch) & 0xff) << ")"; + << "Neither unicode nor extended ascii are supported. " + << "(line=" << lineno << ", character code=" << std::hex << (int(ch) & 0xff) << ")"; throw std::runtime_error(errmsg.str()); } - if(str.compare(i, 6, "#error") == 0 || str.compare(i, 8, "#warning") == 0) + if (str.compare(i, 6, "#error") == 0 || str.compare(i, 8, "#warning") == 0) { - if(str.compare(i, 6, "#error") == 0) + if (str.compare(i, 6, "#error") == 0) code << "#error"; i = str.find("\n", i); - if(i == std::string::npos) + if (i == std::string::npos) break; --i; @@ -198,32 +198,32 @@ std::string Preprocessor::removeComments(const std::string &str, const std::stri // We have finished a line that didn't contain any comment // (the '\n' is swallowed when a // comment is detected) - if(ch == '\n' && !suppressionIDs.empty()) + if (ch == '\n' && !suppressionIDs.empty()) { // Add the suppressions. - for(size_t j(0); j < suppressionIDs.size(); ++j) + for (size_t j(0); j < suppressionIDs.size(); ++j) settings->nomsg.addSuppression(suppressionIDs[j], filename, lineno); suppressionIDs.clear(); } // Remove comments.. - if(str.compare(i, 2, "//", 0, 2) == 0) + if (str.compare(i, 2, "//", 0, 2) == 0) { size_t commentStart = i + 2; i = str.find('\n', i); - if(i == std::string::npos) + if (i == std::string::npos) break; - if(settings && settings->_inlineSuppressions) + if (settings && settings->_inlineSuppressions) { std::string comment(str, commentStart, i - commentStart); std::istringstream iss(comment); std::string word; iss >> word; - if(word == "cppcheck-suppress") + if (word == "cppcheck-suppress") { iss >> word; - if(iss) + if (iss) suppressionIDs.push_back(word); } } @@ -232,16 +232,16 @@ std::string Preprocessor::removeComments(const std::string &str, const std::stri previous = '\n'; ++lineno; } - else if(str.compare(i, 2, "/*", 0, 2) == 0) + else if (str.compare(i, 2, "/*", 0, 2) == 0) { unsigned char chPrev = 0; ++i; - while(i < str.length() && (chPrev != '*' || ch != '/')) + while (i < str.length() && (chPrev != '*' || ch != '/')) { chPrev = ch; ++i; ch = str[i]; - if(ch == '\n') + if (ch == '\n') { ++newlines; ++lineno; @@ -250,7 +250,7 @@ std::string Preprocessor::removeComments(const std::string &str, const std::stri } // String or char constants.. - else if(ch == '\"' || ch == '\'') + else if (ch == '\"' || ch == '\'') { code << std::string(1, ch); unsigned char chNext; @@ -258,11 +258,11 @@ std::string Preprocessor::removeComments(const std::string &str, const std::stri { ++i; chNext = str[i]; - if(chNext == '\\') + if (chNext == '\\') { ++i; char chSeq = str[i]; - if(chSeq == '\n') + if (chSeq == '\n') ++newlines; else { @@ -277,14 +277,14 @@ std::string Preprocessor::removeComments(const std::string &str, const std::stri previous = chNext; } } - while(i < str.length() && chNext != ch && chNext != '\n'); + while (i < str.length() && chNext != ch && chNext != '\n'); } // Just some code.. else { - if(ch == ' ' && previous == ' ') + if (ch == ' ' && previous == ' ') { // Skip double white space } @@ -296,10 +296,10 @@ std::string Preprocessor::removeComments(const std::string &str, const std::stri // if there has been sequences, add extra newlines.. - if(ch == '\n') + if (ch == '\n') { ++lineno; - if(newlines > 0) + if (newlines > 0) { code << std::string(newlines, '\n'); newlines = 0; @@ -315,37 +315,37 @@ std::string Preprocessor::removeComments(const std::string &str, const std::stri std::string Preprocessor::removeParantheses(const std::string &str) { - if(str.find("\n#if") == std::string::npos && str.compare(0, 3, "#if") != 0) + if (str.find("\n#if") == std::string::npos && str.compare(0, 3, "#if") != 0) return str; std::istringstream istr(str.c_str()); std::ostringstream ret; std::string line; - while(std::getline(istr, line)) + while (std::getline(istr, line)) { - if(line.compare(0, 3, "#if") == 0 || line.compare(0, 5, "#elif") == 0) + if (line.compare(0, 3, "#if") == 0 || line.compare(0, 5, "#elif") == 0) { std::string::size_type pos; pos = 0; - while((pos = line.find(" (", pos)) != std::string::npos) + while ((pos = line.find(" (", pos)) != std::string::npos) line.erase(pos, 1); pos = 0; - while((pos = line.find("( ", pos)) != std::string::npos) + while ((pos = line.find("( ", pos)) != std::string::npos) line.erase(pos + 1, 1); pos = 0; - while((pos = line.find(" )", pos)) != std::string::npos) + while ((pos = line.find(" )", pos)) != std::string::npos) line.erase(pos, 1); pos = 0; - while((pos = line.find(") ", pos)) != std::string::npos) + while ((pos = line.find(") ", pos)) != std::string::npos) line.erase(pos + 1, 1); // Remove inner paranthesis "((..))".. pos = 0; - while((pos = line.find("((", pos)) != std::string::npos) + while ((pos = line.find("((", pos)) != std::string::npos) { ++pos; std::string::size_type pos2 = line.find_first_of("()", pos + 1); - if(pos2 != std::string::npos && line[pos2] == ')') + if (pos2 != std::string::npos && line[pos2] == ')') { line.erase(pos2, 1); line.erase(pos, 1); @@ -353,20 +353,20 @@ std::string Preprocessor::removeParantheses(const std::string &str) } // "#if(A) => #if A", but avoid "#if (defined A) || defined (B)" - if((line.compare(0, 4, "#if(") == 0 || line.compare(0, 6, "#elif(") == 0) && - line[line.length() - 1] == ')') + if ((line.compare(0, 4, "#if(") == 0 || line.compare(0, 6, "#elif(") == 0) && + line[line.length() - 1] == ')') { int ind = 0; - for(std::string::size_type i = 0; i < line.length(); ++i) + for (std::string::size_type i = 0; i < line.length(); ++i) { - if(line[i] == '(') + if (line[i] == '(') ++ind; - else if(line[i] == ')') + else if (line[i] == ')') { --ind; - if(ind == 0) + if (ind == 0) { - if(i == line.length() - 1) + if (i == line.length() - 1) { line[line.find('(')] = ' '; line.erase(line.length() - 1); @@ -377,9 +377,9 @@ std::string Preprocessor::removeParantheses(const std::string &str) } } - if(line.compare(0, 4, "#if(") == 0) + if (line.compare(0, 4, "#if(") == 0) line.insert(3, " "); - else if(line.compare(0, 6, "#elif(") == 0) + else if (line.compare(0, 6, "#elif(") == 0) line.insert(5, " "); } ret << line << "\n"; @@ -396,21 +396,21 @@ static void _removeAsm(std::string &str, const std::string::size_type pos) bool instr = false; int parlevel = 0; std::string::size_type pos2 = pos + 1; - while(pos2 < str.length()) + while (pos2 < str.length()) { - if(str[pos2] == '\"') + if (str[pos2] == '\"') instr = !instr; - else if(str[pos2] == '\n') + else if (str[pos2] == '\n') ++newlines; - else if(!instr) + else if (!instr) { - if(str[pos2] == '(') + if (str[pos2] == '(') ++parlevel; - else if(str[pos2] == ')') + else if (str[pos2] == ')') { - if(parlevel <= 1) + if (parlevel <= 1) break; --parlevel; } @@ -425,25 +425,25 @@ static void _removeAsm(std::string &str, const std::string::size_type pos) void Preprocessor::removeAsm(std::string &str) { std::string::size_type pos = 0; - while((pos = str.find("\nasm(", pos)) != std::string::npos) + while ((pos = str.find("\nasm(", pos)) != std::string::npos) { _removeAsm(str, pos++); str.insert(pos, "asm()"); } pos = 0; - while((pos = str.find("\nasm (", pos)) != std::string::npos) + while ((pos = str.find("\nasm (", pos)) != std::string::npos) { _removeAsm(str, pos++); str.insert(pos, "asm()"); } pos = 0; - while((pos = str.find("\nasm __volatile(", pos)) != std::string::npos) + while ((pos = str.find("\nasm __volatile(", pos)) != std::string::npos) _removeAsm(str, pos); pos = 0; - while((pos = str.find("\nasm __volatile (", pos)) != std::string::npos) + while ((pos = str.find("\nasm __volatile (", pos)) != std::string::npos) _removeAsm(str, pos); } @@ -453,7 +453,7 @@ void Preprocessor::preprocess(std::istream &istr, std::map configs; std::string data; preprocess(istr, data, configs, filename, includePaths); - for(std::list::const_iterator it = configs.begin(); it != configs.end(); ++it) + for (std::list::const_iterator it = configs.begin(); it != configs.end(); ++it) result[ *it ] = Preprocessor::getcode(data, *it, filename, _errorLogger); } @@ -461,13 +461,13 @@ std::string Preprocessor::removeSpaceNearNL(const std::string &str) { std::string tmp; int prev = -1; - for(unsigned int i = 0; i < str.size(); i++) + for (unsigned int i = 0; i < str.size(); i++) { - if(str[i] == ' ' && - ((i > 0 && tmp[prev] == '\n') || - (i + 1 < str.size() && str[i+1] == '\n') + if (str[i] == ' ' && + ((i > 0 && tmp[prev] == '\n') || + (i + 1 < str.size() && str[i+1] == '\n') + ) ) - ) { // Ignore space that has new line in either side of it } @@ -487,12 +487,12 @@ std::string Preprocessor::replaceIfDefined(const std::string &str) std::string::size_type pos; pos = 0; - while((pos = ret.find("#if defined(", pos)) != std::string::npos) + while ((pos = ret.find("#if defined(", pos)) != std::string::npos) { std::string::size_type pos2 = ret.find(")", pos + 9); - if(pos2 > ret.length() - 1) + if (pos2 > ret.length() - 1) break; - if(ret[pos2+1] == '\n') + if (ret[pos2+1] == '\n') { ret.erase(pos2, 1); ret.erase(pos + 3, 9); @@ -502,12 +502,12 @@ std::string Preprocessor::replaceIfDefined(const std::string &str) } pos = 0; - while((pos = ret.find("#if !defined(", pos)) != std::string::npos) + while ((pos = ret.find("#if !defined(", pos)) != std::string::npos) { std::string::size_type pos2 = ret.find(")", pos + 9); - if(pos2 > ret.length() - 1) + if (pos2 > ret.length() - 1) break; - if(ret[pos2+1] == '\n') + if (ret[pos2+1] == '\n') { ret.erase(pos2, 1); ret.erase(pos + 3, 10); @@ -517,12 +517,12 @@ std::string Preprocessor::replaceIfDefined(const std::string &str) } pos = 0; - while((pos = ret.find("#elif defined(", pos)) != std::string::npos) + while ((pos = ret.find("#elif defined(", pos)) != std::string::npos) { std::string::size_type pos2 = ret.find(")", pos + 9); - if(pos2 > ret.length() - 1) + if (pos2 > ret.length() - 1) break; - if(ret[pos2+1] == '\n') + if (ret[pos2+1] == '\n') { ret.erase(pos2, 1); ret.erase(pos + 6, 8); @@ -541,7 +541,7 @@ void Preprocessor::preprocess(std::istream &istr, std::string &processedFile, st std::replace(processedFile.begin(), processedFile.end(), '\t', ' '); // Remove all indentation.. - if(!processedFile.empty() && processedFile[0] == ' ') + if (!processedFile.empty() && processedFile[0] == ' ') processedFile.erase(0, processedFile.find_first_not_of(" ")); // Remove space characters that are after or before new line character @@ -555,16 +555,16 @@ void Preprocessor::preprocess(std::istream &istr, std::string &processedFile, st std::istringstream istr(processedFile.c_str()); std::ostringstream ostr; std::string line; - while(std::getline(istr, line)) + while (std::getline(istr, line)) { - if(line.compare(0, 4, "#if ") == 0 || line.compare(0, 6, "#elif ") == 0) + if (line.compare(0, 4, "#if ") == 0 || line.compare(0, 6, "#elif ") == 0) { std::string::size_type pos = 0; - while((pos = line.find(" defined ")) != std::string::npos) + while ((pos = line.find(" defined ")) != std::string::npos) { line[pos+8] = '('; pos = line.find_first_of(" |&", pos + 8); - if(pos == std::string::npos) + if (pos == std::string::npos) line += ")"; else line.insert(pos, ")"); @@ -589,30 +589,30 @@ void Preprocessor::preprocess(std::istream &istr, std::string &processedFile, st std::string Preprocessor::getdef(std::string line, bool def) { // If def is true, the line must start with "#ifdef" - if(def && line.find("#ifdef ") != 0 && line.find("#if ") != 0 && line.find("#elif ") != 0 && line.find("#if defined ") != 0) + if (def && line.find("#ifdef ") != 0 && line.find("#if ") != 0 && line.find("#elif ") != 0 && line.find("#if defined ") != 0) { return ""; } // If def is false, the line must start with "#ifndef" - if(!def && line.find("#ifndef ") != 0) + if (!def && line.find("#ifndef ") != 0) { return ""; } // Remove the "#ifdef" or "#ifndef" - if(line.find("#if defined ") == 0) + if (line.find("#if defined ") == 0) line.erase(0, 11); else line.erase(0, line.find(" ")); // Remove all spaces. std::string::size_type pos = 0; - while((pos = line.find(" ", pos)) != std::string::npos) + while ((pos = line.find(" ", pos)) != std::string::npos) { const unsigned char chprev = (pos > 0) ? line[pos-1] : (unsigned char)0; const unsigned char chnext = (pos + 1 < line.length()) ? line[pos+1] : (unsigned char)0; - if((std::isalnum(chprev) || chprev == '_') && (std::isalnum(chnext) || chnext == '_')) + if ((std::isalnum(chprev) || chprev == '_') && (std::isalnum(chnext) || chnext == '_')) ++pos; else line.erase(pos, 1); @@ -643,28 +643,28 @@ std::list Preprocessor::getcfgs(const std::string &filedata, const unsigned int linenr = 0; std::istringstream istr(filedata); std::string line; - while(getline(istr, line)) + while (getline(istr, line)) { ++linenr; - if(line.compare(0, 6, "#file ") == 0) + if (line.compare(0, 6, "#file ") == 0) { includeguard = true; ++filelevel; continue; } - else if(line == "#endfile") + else if (line == "#endfile") { includeguard = false; - if(filelevel > 0) + if (filelevel > 0) --filelevel; continue; } - if(line.compare(0, 8, "#define ") == 0 && line.find("(", 8) == std::string::npos) + if (line.compare(0, 8, "#define ") == 0 && line.find("(", 8) == std::string::npos) { - if(line.find(" ", 8) == std::string::npos) + if (line.find(" ", 8) == std::string::npos) defines.insert(line.substr(8)); else { @@ -674,38 +674,38 @@ std::list Preprocessor::getcfgs(const std::string &filedata, const } } - if(!line.empty() && line.compare(0, 3, "#if") != 0) + if (!line.empty() && line.compare(0, 3, "#if") != 0) includeguard = false; - if(includeguard) + if (includeguard) continue; bool from_negation = false; std::string def = getdef(line, true); - if(def.empty()) + if (def.empty()) { def = getdef(line, false); // sub conditionals of ndef blocks need to be // constructed _without_ the negated define - if(!def.empty()) + if (!def.empty()) from_negation = true; } - if(!def.empty()) + if (!def.empty()) { int par = 0; - for(std::string::size_type pos = 0; pos < def.length(); ++pos) + for (std::string::size_type pos = 0; pos < def.length(); ++pos) { - if(def[pos] == '(') + if (def[pos] == '(') ++par; - else if(def[pos] == ')') + else if (def[pos] == ')') { --par; - if(par < 0) + if (par < 0) break; } } - if(par != 0) + if (par != 0) { std::ostringstream line; line << __LINE__; @@ -726,10 +726,10 @@ std::list Preprocessor::getcfgs(const std::string &filedata, const // Replace defined constants { std::map varmap; - for(std::set::const_iterator it = defines.begin(); it != defines.end(); ++it) + for (std::set::const_iterator it = defines.begin(); it != defines.end(); ++it) { std::string::size_type pos = it->find("="); - if(pos == std::string::npos) + if (pos == std::string::npos) continue; const std::string varname(it->substr(0, pos)); const std::string value(it->substr(pos + 1)); @@ -739,27 +739,27 @@ std::list Preprocessor::getcfgs(const std::string &filedata, const simplifyCondition(varmap, def, false); } - if(! deflist.empty() && line.find("#elif ") == 0) + if (! deflist.empty() && line.find("#elif ") == 0) deflist.pop_back(); deflist.push_back(def); def = ""; - for(std::list::const_iterator it = deflist.begin(); it != deflist.end(); ++it) + for (std::list::const_iterator it = deflist.begin(); it != deflist.end(); ++it) { - if(*it == "0") + if (*it == "0") break; - if(*it == "1" || *it == "!") + if (*it == "1" || *it == "!") continue; // don't add "T;T": // treat two and more similar nested conditions as one - if(def != *it) + if (def != *it) { - if(! def.empty()) + if (! def.empty()) def += ";"; def += *it; } } - if(from_negation) + if (from_negation) { ndeflist.push_back(deflist.back()); deflist.pop_back(); @@ -767,15 +767,15 @@ std::list Preprocessor::getcfgs(const std::string &filedata, const deflist.push_back(nmark); } - if(std::find(ret.begin(), ret.end(), def) == ret.end()) + if (std::find(ret.begin(), ret.end(), def) == ret.end()) { ret.push_back(def); } } - else if(line.find("#else") == 0 && ! deflist.empty()) + else if (line.find("#else") == 0 && ! deflist.empty()) { - if(deflist.back() == "!") + if (deflist.back() == "!") { deflist.pop_back(); deflist.push_back(ndeflist.back()); @@ -789,51 +789,51 @@ std::list Preprocessor::getcfgs(const std::string &filedata, const } } - else if(line.find("#endif") == 0 && ! deflist.empty()) + else if (line.find("#endif") == 0 && ! deflist.empty()) { - if(deflist.back() == "!") + if (deflist.back() == "!") ndeflist.pop_back(); deflist.pop_back(); } } // Remove defined constants from ifdef configurations.. - for(std::list::iterator it = ret.begin(); it != ret.end(); ++it) + for (std::list::iterator it = ret.begin(); it != ret.end(); ++it) { std::string cfg(*it); - for(std::set::const_iterator it2 = defines.begin(); it2 != defines.end(); ++it2) + for (std::set::const_iterator it2 = defines.begin(); it2 != defines.end(); ++it2) { std::string::size_type pos = 0; // Get name of define std::string defineName(*it2); - if(defineName.find("=") != std::string::npos) + if (defineName.find("=") != std::string::npos) defineName.erase(defineName.find("=")); // Remove ifdef configurations that match the defineName - while((pos = cfg.find(defineName, pos)) != std::string::npos) + while ((pos = cfg.find(defineName, pos)) != std::string::npos) { std::string::size_type pos1 = pos; ++pos; - if(pos1 > 0 && cfg[pos1-1] != ';') + if (pos1 > 0 && cfg[pos1-1] != ';') continue; std::string::size_type pos2 = pos1 + defineName.length(); - if(pos2 < cfg.length() && cfg[pos2] != ';') + if (pos2 < cfg.length() && cfg[pos2] != ';') continue; --pos; cfg.erase(pos, defineName.length()); } } - if(cfg.length() != it->length()) + if (cfg.length() != it->length()) { - while(cfg.length() > 0 && cfg[0] == ';') + while (cfg.length() > 0 && cfg[0] == ';') cfg.erase(0, 1); - while(cfg.length() > 0 && cfg[cfg.length()-1] == ';') + while (cfg.length() > 0 && cfg[cfg.length()-1] == ';') cfg.erase(cfg.length() - 1); std::string::size_type pos = 0; - while((pos = cfg.find(";;", pos)) != std::string::npos) + while ((pos = cfg.find(";;", pos)) != std::string::npos) cfg.erase(pos, 1); *it = cfg; @@ -841,15 +841,15 @@ std::list Preprocessor::getcfgs(const std::string &filedata, const } // convert configurations: "defined(A) && defined(B)" => "A;B" - for(std::list::iterator it = ret.begin(); it != ret.end(); ++it) + for (std::list::iterator it = ret.begin(); it != ret.end(); ++it) { std::string s(*it); - if(s.find("&&") != std::string::npos) + if (s.find("&&") != std::string::npos) { Tokenizer tokenizer(_settings, _errorLogger); std::istringstream istr(s.c_str()); - if(!tokenizer.tokenize(istr, filename.c_str())) + if (!tokenizer.tokenize(istr, filename.c_str())) { std::ostringstream line; line << __LINE__; @@ -868,18 +868,18 @@ std::list Preprocessor::getcfgs(const std::string &filedata, const const Token *tok = tokenizer.tokens(); std::list varList; - while(tok) + while (tok) { - if(Token::Match(tok, "defined ( %var% )")) + if (Token::Match(tok, "defined ( %var% )")) { varList.push_back(tok->strAt(2)); tok = tok->tokAt(4); - if(tok && tok->str() == "&&") + if (tok && tok->str() == "&&") { tok = tok->next(); } } - else if(Token::Match(tok, "%var% ;")) + else if (Token::Match(tok, "%var% ;")) { varList.push_back(tok->str()); tok = tok->tokAt(2); @@ -892,15 +892,15 @@ std::list Preprocessor::getcfgs(const std::string &filedata, const varList.sort(); s = ""; - for(std::list::iterator varIter = varList.begin(); varIter != varList.end(); ++varIter) + for (std::list::iterator varIter = varList.begin(); varIter != varList.end(); ++varIter) { - if(!s.empty()) + if (!s.empty()) s += ";"; s += *varIter; } - if(!s.empty()) + if (!s.empty()) *it = s; } } @@ -910,31 +910,31 @@ std::list Preprocessor::getcfgs(const std::string &filedata, const ret.unique(); // cleanup unhandled configurations.. - for(std::list::iterator it = ret.begin(); it != ret.end();) + for (std::list::iterator it = ret.begin(); it != ret.end();) { const std::string s(*it + ";"); bool unhandled = false; - for(std::string::size_type pos = 0; pos < s.length(); ++pos) + for (std::string::size_type pos = 0; pos < s.length(); ++pos) { const unsigned char c = s[pos]; // ok with ";" - if(c == ';') + if (c == ';') continue; // identifier.. - if(std::isalpha(c) || c == '_') + if (std::isalpha(c) || c == '_') { - while(std::isalnum(s[pos]) || s[pos] == '_') + while (std::isalnum(s[pos]) || s[pos] == '_') ++pos; - if(s[pos] == '=') + if (s[pos] == '=') { ++pos; - while(std::isdigit(s[pos])) + while (std::isdigit(s[pos])) ++pos; - if(s[pos] != ';') + if (s[pos] != ';') { unhandled = true; break; @@ -953,10 +953,10 @@ std::list Preprocessor::getcfgs(const std::string &filedata, const } } - if(unhandled) + if (unhandled) { // unhandled ifdef configuration.. - if(_errorLogger && _settings && _settings->_debug) + if (_errorLogger && _settings && _settings->_debug) _errorLogger->reportOut("unhandled configuration: " + *it); ret.erase(it++); @@ -977,35 +977,35 @@ void Preprocessor::simplifyCondition(const std::map &v std::istringstream istr(("(" + condition + ")").c_str()); tokenizer.tokenize(istr, ""); - if(Token::Match(tokenizer.tokens(), "( %var% )")) + if (Token::Match(tokenizer.tokens(), "( %var% )")) { - if(variables.find(tokenizer.tokens()->strAt(1)) != variables.end()) + if (variables.find(tokenizer.tokens()->strAt(1)) != variables.end()) condition = "1"; - else if(match) + else if (match) condition = "0"; return; } - if(Token::Match(tokenizer.tokens(), "( ! %var% )")) + if (Token::Match(tokenizer.tokens(), "( ! %var% )")) { - if(variables.find(tokenizer.tokens()->strAt(2)) == variables.end()) + if (variables.find(tokenizer.tokens()->strAt(2)) == variables.end()) condition = "1"; - else if(match) + else if (match) condition = "0"; return; } // replace variable names with values.. - for(Token *tok = const_cast(tokenizer.tokens()); tok; tok = tok->next()) + for (Token *tok = const_cast(tokenizer.tokens()); tok; tok = tok->next()) { - if(!tok->isName()) + if (!tok->isName()) continue; - if(Token::Match(tok, "defined ( %var% )")) + if (Token::Match(tok, "defined ( %var% )")) { - if(variables.find(tok->strAt(2)) != variables.end()) + if (variables.find(tok->strAt(2)) != variables.end()) tok->str("1"); - else if(match) + else if (match) tok->str("0"); else continue; @@ -1015,11 +1015,11 @@ void Preprocessor::simplifyCondition(const std::map &v continue; } - if(Token::Match(tok, "defined %var%")) + if (Token::Match(tok, "defined %var%")) { - if(variables.find(tok->strAt(1)) != variables.end()) + if (variables.find(tok->strAt(1)) != variables.end()) tok->str("1"); - else if(match) + else if (match) tok->str("0"); else continue; @@ -1028,9 +1028,9 @@ void Preprocessor::simplifyCondition(const std::map &v } const std::map::const_iterator it = variables.find(tok->str()); - if(it != variables.end()) + if (it != variables.end()) { - if(it->second.empty()) + if (it->second.empty()) tok->deleteThis(); else tok->str(it->second); @@ -1039,13 +1039,13 @@ void Preprocessor::simplifyCondition(const std::map &v // simplify calculations.. bool modified = true; - while(modified) + while (modified) { modified = false; tokenizer.simplifyCalculations(); - for(Token *tok = const_cast(tokenizer.tokens()); tok; tok = tok->next()) + for (Token *tok = const_cast(tokenizer.tokens()); tok; tok = tok->next()) { - if(Token::Match(tok, "! %num%")) + if (Token::Match(tok, "! %num%")) { tok->deleteThis(); tok->str(tok->str() == "0" ? "1" : "0"); @@ -1054,10 +1054,10 @@ void Preprocessor::simplifyCondition(const std::map &v } } - if(Token::simpleMatch(tokenizer.tokens(), "( 1 )") || - Token::simpleMatch(tokenizer.tokens(), "( 1 ||")) + if (Token::simpleMatch(tokenizer.tokens(), "( 1 )") || + Token::simpleMatch(tokenizer.tokens(), "( 1 ||")) condition = "1"; - else if(Token::simpleMatch(tokenizer.tokens(), "( 0 )")) + else if (Token::simpleMatch(tokenizer.tokens(), "( 0 )")) condition = "0"; } @@ -1068,13 +1068,13 @@ bool Preprocessor::match_cfg_def(const std::map &cfg, simplifyCondition(cfg, def, true); - if(cfg.find(def) != cfg.end()) + if (cfg.find(def) != cfg.end()) return true; - if(def == "0") + if (def == "0") return false; - if(def == "1") + if (def == "1") return true; return false; @@ -1093,15 +1093,15 @@ std::string Preprocessor::getcode(const std::string &filedata, std::string cfg, std::map cfgmap; { std::string::size_type pos = 0; - for(;;) + for (;;) { std::string::size_type pos2 = cfg.find_first_of(";=", pos); - if(pos2 == std::string::npos) + if (pos2 == std::string::npos) { cfgmap[cfg.substr(pos)] = ""; break; } - if(cfg[pos2] == ';') + if (cfg[pos2] == ';') { cfgmap[cfg.substr(pos, pos2-pos)] = ""; } @@ -1109,7 +1109,7 @@ std::string Preprocessor::getcode(const std::string &filedata, std::string cfg, { std::string::size_type pos3 = pos2; pos2 = cfg.find(";", pos2); - if(pos2 == std::string::npos) + if (pos2 == std::string::npos) { cfgmap[cfg.substr(pos, pos3-pos)] = cfg.substr(pos3 + 1); break; @@ -1125,15 +1125,15 @@ std::string Preprocessor::getcode(const std::string &filedata, std::string cfg, std::istringstream istr(filedata); std::string line; - while(getline(istr, line)) + while (getline(istr, line)) { - if(line.compare(0, 11, "#pragma asm") == 0) + if (line.compare(0, 11, "#pragma asm") == 0) { ret << "\n"; bool found_end = false; - while(getline(istr, line)) + while (getline(istr, line)) { - if(line.compare(0, 14, "#pragma endasm") == 0) + if (line.compare(0, 14, "#pragma endasm") == 0) { found_end = true; break; @@ -1141,16 +1141,16 @@ std::string Preprocessor::getcode(const std::string &filedata, std::string cfg, ret << "\n"; } - if(!found_end) + if (!found_end) break; - if(line.find("=") != std::string::npos) + if (line.find("=") != std::string::npos) { Tokenizer tokenizer; line.erase(0, sizeof("#pragma endasm")); std::istringstream istr(line.c_str()); tokenizer.tokenize(istr, ""); - if(Token::Match(tokenizer.tokens(), "( %var% = %any% )")) + if (Token::Match(tokenizer.tokens(), "( %var% = %any% )")) { ret << "asm(" << tokenizer.tokens()->strAt(1) << ");"; } @@ -1164,24 +1164,24 @@ std::string Preprocessor::getcode(const std::string &filedata, std::string cfg, std::string def = getdef(line, true); std::string ndef = getdef(line, false); - if(line.compare(0, 8, "#define ") == 0 && line.find("(", 8) == std::string::npos) + if (line.compare(0, 8, "#define ") == 0 && line.find("(", 8) == std::string::npos) { std::string::size_type pos = line.find(" ", 8); - if(pos == std::string::npos) + if (pos == std::string::npos) cfgmap[line.substr(8)] = ""; else cfgmap[line.substr(8, pos - 8)] = line.substr(pos + 1); } - else if(line.find("#elif ") == 0) + else if (line.find("#elif ") == 0) { - if(matched_ifdef.back()) + if (matched_ifdef.back()) { matching_ifdef.back() = false; } else { - if(match_cfg_def(cfgmap, def)) + if (match_cfg_def(cfgmap, def)) { matching_ifdef.back() = true; matched_ifdef.back() = true; @@ -1189,57 +1189,57 @@ std::string Preprocessor::getcode(const std::string &filedata, std::string cfg, } } - else if(! def.empty()) + else if (! def.empty()) { matching_ifdef.push_back(match_cfg_def(cfgmap, def)); matched_ifdef.push_back(matching_ifdef.back()); } - else if(! ndef.empty()) + else if (! ndef.empty()) { matching_ifdef.push_back(! match_cfg_def(cfgmap, ndef)); matched_ifdef.push_back(matching_ifdef.back()); } - else if(line == "#else") + else if (line == "#else") { - if(! matched_ifdef.empty()) + if (! matched_ifdef.empty()) matching_ifdef.back() = ! matched_ifdef.back(); } - else if(line.compare(0, 6, "#endif") == 0) + else if (line.compare(0, 6, "#endif") == 0) { - if(! matched_ifdef.empty()) + if (! matched_ifdef.empty()) matched_ifdef.pop_back(); - if(! matching_ifdef.empty()) + if (! matching_ifdef.empty()) matching_ifdef.pop_back(); } - if(!line.empty() && line[0] == '#') + if (!line.empty() && line[0] == '#') { match = true; - for(std::list::const_iterator it = matching_ifdef.begin(); it != matching_ifdef.end(); ++it) + for (std::list::const_iterator it = matching_ifdef.begin(); it != matching_ifdef.end(); ++it) match &= bool(*it); } // #error => return "" - if(match && line.compare(0, 6, "#error") == 0) + if (match && line.compare(0, 6, "#error") == 0) return ""; - if(!match && line.compare(0, 8, "#define ") == 0) + if (!match && line.compare(0, 8, "#define ") == 0) { // Remove define that is not part of this configuration line = ""; } - else if(line.compare(0, 7, "#file \"") == 0 || - line.compare(0, 8, "#endfile") == 0 || - line.compare(0, 8, "#define ") == 0 || - line.compare(0, 6, "#undef") == 0) + else if (line.compare(0, 7, "#file \"") == 0 || + line.compare(0, 8, "#endfile") == 0 || + line.compare(0, 8, "#define ") == 0 || + line.compare(0, 6, "#undef") == 0) { // We must not remove #file tags or line numbers // are corrupted. File tags are removed by the tokenizer. } - else if(!match || line.compare(0, 1, "#") == 0) + else if (!match || line.compare(0, 1, "#") == 0) { // Remove #if, #else, #pragma etc, leaving only // #define, #undef, #file and #endfile. and also lines @@ -1257,26 +1257,26 @@ int Preprocessor::getHeaderFileName(std::string &str) { std::string result; std::string::size_type i = str.find_first_of("<\""); - if(i == std::string::npos) + if (i == std::string::npos) { str = ""; return 0; } unsigned char c = str[i]; - if(c == '<') + if (c == '<') c = '>'; - for(i = i + 1; i < str.length(); ++i) + for (i = i + 1; i < str.length(); ++i) { - if(str[i] == c) + if (str[i] == c) break; result.append(1, str[i]); } str = result; - if(c == '"') + if (c == '"') return 1; else return 2; @@ -1302,10 +1302,10 @@ void Preprocessor::handleIncludes(std::string &code, const std::string &filename std::string::size_type endfilePos = 0; std::set handledFiles; endfilePos = pos; - while((pos = code.find("#include", pos)) != std::string::npos) + while ((pos = code.find("#include", pos)) != std::string::npos) { // Accept only includes that are at the start of a line - if(pos > 0 && code[pos-1] != '\n') + if (pos > 0 && code[pos-1] != '\n') { pos += 8; // length of "#include" continue; @@ -1313,7 +1313,7 @@ void Preprocessor::handleIncludes(std::string &code, const std::string &filename // If endfile is encountered, we have moved to a next file in our stack, // so remove last path in our list. - while((endfilePos = code.find("\n#endfile", endfilePos)) != std::string::npos && endfilePos < pos) + while ((endfilePos = code.find("\n#endfile", endfilePos)) != std::string::npos && endfilePos < pos) { paths.pop_back(); endfilePos += 9; // size of #endfile @@ -1327,17 +1327,17 @@ void Preprocessor::handleIncludes(std::string &code, const std::string &filename code.erase(pos, end - pos); int headerType = getHeaderFileName(filename); - if(headerType == 0) + if (headerType == 0) continue; // filename contains now a file name e.g. "menu.h" std::string processedFile; bool fileOpened = false; std::ifstream fin; - for(std::list::const_iterator iter = includePaths.begin(); iter != includePaths.end(); ++iter) + for (std::list::const_iterator iter = includePaths.begin(); iter != includePaths.end(); ++iter) { fin.open((*iter + filename).c_str()); - if(fin.is_open()) + if (fin.is_open()) { filename = *iter + filename; fileOpened = true; @@ -1347,21 +1347,21 @@ void Preprocessor::handleIncludes(std::string &code, const std::string &filename fin.clear(); } - if(headerType == 1 && !fileOpened) + if (headerType == 1 && !fileOpened) { filename = paths.back() + filename; fin.open(filename.c_str()); - if(fin.is_open()) + if (fin.is_open()) { fileOpened = true; } } - if(fileOpened) + if (fileOpened) { std::string tempFile = getFileLister()->simplifyPath(filename.c_str()); std::transform(tempFile.begin(), tempFile.end(), tempFile.begin(), tolowerWrapper); - if(handledFiles.find(tempFile) != handledFiles.end()) + if (handledFiles.find(tempFile) != handledFiles.end()) { // We have processed this file already once, skip // it this time to avoid ethernal loop. @@ -1374,13 +1374,13 @@ void Preprocessor::handleIncludes(std::string &code, const std::string &filename fin.close(); } - if(processedFile.length() > 0) + if (processedFile.length() > 0) { // Replace all tabs with spaces.. std::replace(processedFile.begin(), processedFile.end(), '\t', ' '); // Remove all indentation.. - if(!processedFile.empty() && processedFile[0] == ' ') + if (!processedFile.empty() && processedFile[0] == ' ') processedFile.erase(0, processedFile.find_first_not_of(" ")); // Remove space characters that are after or before new line character @@ -1392,9 +1392,9 @@ void Preprocessor::handleIncludes(std::string &code, const std::string &filename path.erase(1 + path.find_last_of("\\/")); paths.push_back(path); } - else if(!fileOpened) + else if (!fileOpened) { - if(headerType == 1 && _errorLogger && _settings && _settings->_verbose) + if (headerType == 1 && _errorLogger && _settings && _settings->_verbose) { _errorLogger->reportOut("Include file: \"" + filename + "\" not found."); } @@ -1437,43 +1437,43 @@ public: * e.g. "A(x) foo(x);" */ PreprocessorMacro(const std::string ¯o) - : _macro(macro), _prefix("__cppcheck__") + : _macro(macro), _prefix("__cppcheck__") { // Tokenize the macro to make it easier to handle std::istringstream istr(macro.c_str()); tokenizer.createTokens(istr); // macro name.. - if(tokens() && tokens()->isName()) + if (tokens() && tokens()->isName()) _name = tokens()->str(); // initialize parameters to default values _variadic = _nopar = false; std::string::size_type pos = macro.find_first_of(" ("); - if(pos != std::string::npos && macro[pos] == '(') + if (pos != std::string::npos && macro[pos] == '(') { // Extract macro parameters - if(Token::Match(tokens(), "%var% ( %var%")) + if (Token::Match(tokens(), "%var% ( %var%")) { - for(const Token *tok = tokens()->tokAt(2); tok; tok = tok->next()) + for (const Token *tok = tokens()->tokAt(2); tok; tok = tok->next()) { - if(tok->str() == ")") + if (tok->str() == ")") break; - if(Token::simpleMatch(tok, ". . . )")) + if (Token::simpleMatch(tok, ". . . )")) { _variadic = true; break; } - if(tok->isName()) + if (tok->isName()) _params.push_back(tok->str()); } } - else if(Token::Match(tokens(), "%var% ( . . . )")) + else if (Token::Match(tokens(), "%var% ( . . . )")) _variadic = true; - else if(Token::Match(tokens(), "%var% ( )")) + else if (Token::Match(tokens(), "%var% ( )")) _nopar = true; } } @@ -1516,45 +1516,45 @@ public: */ bool code(const std::vector ¶ms2, std::string ¯ocode) const { - if(_nopar) + if (_nopar) { macrocode = _macro.substr(1 + _macro.find(")")); - if(macrocode.empty()) + if (macrocode.empty()) return true; std::string::size_type pos = 0; // Remove leading spaces - if((pos = macrocode.find_first_not_of(" ")) > 0) + if ((pos = macrocode.find_first_not_of(" ")) > 0) macrocode.erase(0, pos); // Remove ending newline - if((pos = macrocode.find_first_of("\r\n")) != std::string::npos) + if ((pos = macrocode.find_first_of("\r\n")) != std::string::npos) macrocode.erase(pos); } - else if(_params.empty() && _variadic) + else if (_params.empty() && _variadic) { std::string s; - for(unsigned int i = 0; i < params2.size(); ++i) + for (unsigned int i = 0; i < params2.size(); ++i) { - if(i > 0) + if (i > 0) s += ","; s += params2[i]; } macrocode = _macro.substr(1 + _macro.find(")")); - if(macrocode.empty()) + if (macrocode.empty()) return true; std::string::size_type pos = 0; // Remove leading spaces - if((pos = macrocode.find_first_not_of(" ")) > 0) + if ((pos = macrocode.find_first_not_of(" ")) > 0) macrocode.erase(0, pos); // Remove ending newline - if((pos = macrocode.find_first_of("\r\n")) != std::string::npos) + if ((pos = macrocode.find_first_of("\r\n")) != std::string::npos) macrocode.erase(pos); // Replace "__VA_ARGS__" with parameters pos = 0; - while((pos = macrocode.find("__VA_ARGS__", pos)) != std::string::npos) + while ((pos = macrocode.find("__VA_ARGS__", pos)) != std::string::npos) { macrocode.erase(pos, 11); macrocode.insert(pos, s); @@ -1562,15 +1562,15 @@ public: } } - else if(_params.empty()) + else if (_params.empty()) { std::string::size_type pos = _macro.find(" "); - if(pos == std::string::npos) + if (pos == std::string::npos) macrocode = ""; else { macrocode = _macro.substr(pos + 1); - if((pos = macrocode.find_first_of("\r\n")) != std::string::npos) + if ((pos = macrocode.find_first_of("\r\n")) != std::string::npos) macrocode.erase(pos); } } @@ -1578,54 +1578,54 @@ public: else { const Token *tok = tokens(); - while(tok && tok->str() != ")") + while (tok && tok->str() != ")") tok = tok->next(); - if(tok) + if (tok) { bool optcomma = false; - while((tok = tok->next()) != NULL) + while ((tok = tok->next()) != NULL) { std::string str = tok->str(); - if(str == "##") + if (str == "##") continue; - if(str[0] == '#' || tok->isName()) + if (str[0] == '#' || tok->isName()) { const bool stringify(str[0] == '#'); - if(stringify) + if (stringify) { str = str.erase(0, 1); } - for(unsigned int i = 0; i < _params.size(); ++i) + for (unsigned int i = 0; i < _params.size(); ++i) { - if(str == _params[i]) + if (str == _params[i]) { - if(_variadic && - (i == _params.size() - 1 || - (params2.size() + 2 == _params.size() && i + 1 == _params.size() - 1))) + if (_variadic && + (i == _params.size() - 1 || + (params2.size() + 2 == _params.size() && i + 1 == _params.size() - 1))) { str = ""; - for(unsigned int j = (unsigned int)_params.size() - 1; j < params2.size(); ++j) + for (unsigned int j = (unsigned int)_params.size() - 1; j < params2.size(); ++j) { - if(optcomma || j > _params.size() - 1) + if (optcomma || j > _params.size() - 1) str += ","; optcomma = false; str += params2[j]; } } - else if(i >= params2.size()) + else if (i >= params2.size()) { // Macro had more parameters than caller used. macrocode = ""; return false; } - else if(stringify) + else if (stringify) { const std::string &s(params2[i]); std::ostringstream ostr; ostr << "\""; - for(std::string::size_type i = 0; i < s.size(); ++i) + for (std::string::size_type i = 0; i < s.size(); ++i) { - if(s[i] == '\\' || s[i] == '\"') + if (s[i] == '\\' || s[i] == '\"') ostr << '\\'; ostr << s[i]; } @@ -1638,15 +1638,15 @@ public: } } } - if(_variadic && tok->str() == "," && tok->next() && tok->next()->str() == "##") + if (_variadic && tok->str() == "," && tok->next() && tok->next()->str() == "##") { optcomma = true; continue; } optcomma = false; macrocode += str; - if(Token::Match(tok, "%var% %var%") || - Token::Match(tok, "> >")) + if (Token::Match(tok, "%var% %var%") || + Token::Match(tok, "> >")) macrocode += " "; } } @@ -1667,9 +1667,9 @@ static void skipstring(const std::string &line, std::string::size_type &pos) const unsigned char ch = line[pos]; ++pos; - while(pos < line.size() && line[pos] != ch) + while (pos < line.size() && line[pos] != ch) { - if(line[pos] == '\\') + if (line[pos] == '\\') ++pos; ++pos; } @@ -1688,51 +1688,51 @@ static void skipstring(const std::string &line, std::string::size_type &pos) */ static bool getlines(std::istream &istr, std::string &line) { - if(!istr.good()) + if (!istr.good()) return false; line = ""; int parlevel = 0; - for(unsigned char ch = (unsigned char)istr.get(); istr.good(); ch = (unsigned char)istr.get()) + for (unsigned char ch = (unsigned char)istr.get(); istr.good(); ch = (unsigned char)istr.get()) { - if(ch == '\'' || ch == '\"') + if (ch == '\'' || ch == '\"') { line += ch; unsigned char c = 0; - while(istr.good() && c != ch) + while (istr.good() && c != ch) { - if(c == '\\') + if (c == '\\') { c = (unsigned char)istr.get(); - if(!istr.good()) + if (!istr.good()) return true; line += c; } c = (unsigned char)istr.get(); - if(!istr.good()) + if (!istr.good()) return true; - if(c == '\n' && line.compare(0, 1, "#") == 0) + if (c == '\n' && line.compare(0, 1, "#") == 0) return true; line += c; } continue; } - if(ch == '(') + if (ch == '(') ++parlevel; - else if(ch == ')') + else if (ch == ')') --parlevel; - else if(ch == '\n') + else if (ch == '\n') { - if(line.compare(0, 1, "#") == 0) + if (line.compare(0, 1, "#") == 0) return true; - if((char)istr.peek() == '#') + if ((char)istr.peek() == '#') { line += ch; return true; } } - else if(line.compare(0, 1, "#") != 0 && parlevel <= 0 && ch == ';') + else if (line.compare(0, 1, "#") != 0 && parlevel <= 0 && ch == ';') { line += ";"; return true; @@ -1763,19 +1763,19 @@ std::string Preprocessor::expandMacros(const std::string &code, std::string file // read code.. std::istringstream istr(code.c_str()); std::string line; - while(getlines(istr, line)) + while (getlines(istr, line)) { // defining a macro.. - if(line.compare(0, 8, "#define ") == 0) + if (line.compare(0, 8, "#define ") == 0) { PreprocessorMacro *macro = new PreprocessorMacro(line.substr(8)); - if(macro->name().empty()) + if (macro->name().empty()) delete macro; else { std::map::iterator it; it = macros.find(macro->name()); - if(it != macros.end()) + if (it != macros.end()) delete it->second; macros[macro->name()] = macro; } @@ -1783,11 +1783,11 @@ std::string Preprocessor::expandMacros(const std::string &code, std::string file } // undefining a macro.. - else if(line.compare(0, 7, "#undef ") == 0) + else if (line.compare(0, 7, "#undef ") == 0) { std::map::iterator it; it = macros.find(line.substr(7)); - if(it != macros.end()) + if (it != macros.end()) { delete it->second; macros.erase(it); @@ -1796,7 +1796,7 @@ std::string Preprocessor::expandMacros(const std::string &code, std::string file } // entering a file, update position.. - else if(line.compare(0, 7, "#file \"") == 0) + else if (line.compare(0, 7, "#file \"") == 0) { fileinfo.push(std::pair(linenr, filename)); filename = line.substr(7, line.length() - 8); @@ -1805,9 +1805,9 @@ std::string Preprocessor::expandMacros(const std::string &code, std::string file } // leaving a file, update position.. - else if(line == "#endfile") + else if (line == "#endfile") { - if(!fileinfo.empty()) + if (!fileinfo.empty()) { linenr = fileinfo.top().first; filename = fileinfo.top().second; @@ -1817,7 +1817,7 @@ std::string Preprocessor::expandMacros(const std::string &code, std::string file } // all other preprocessor directives are just replaced with a newline - else if(line.compare(0, 1, "#") == 0) + else if (line.compare(0, 1, "#") == 0) { line += "\n"; } @@ -1847,20 +1847,20 @@ std::string Preprocessor::expandMacros(const std::string &code, std::string file // scan line to see if there are any macros to expand.. unsigned int tmpLinenr = 0; - while(pos < line.size()) + while (pos < line.size()) { - if(line[pos] == '\n') + if (line[pos] == '\n') ++tmpLinenr; // skip strings.. - if(line[pos] == '\"' || line[pos] == '\'') + if (line[pos] == '\"' || line[pos] == '\'') { const char ch = line[pos]; skipstring(line, pos); ++pos; - if(pos >= line.size()) + if (pos >= line.size()) { writeError(filename, linenr + tmpLinenr, @@ -1869,7 +1869,7 @@ std::string Preprocessor::expandMacros(const std::string &code, std::string file std::string("No pair for character (") + ch + "). Can't process file. File is either invalid or unicode, which is currently not supported."); std::map::iterator it; - for(it = macros.begin(); it != macros.end(); ++it) + for (it = macros.begin(); it != macros.end(); ++it) delete it->second; return ""; @@ -1878,18 +1878,18 @@ std::string Preprocessor::expandMacros(const std::string &code, std::string file continue; } - if(!std::isalpha(line[pos]) && line[pos] != '_') + if (!std::isalpha(line[pos]) && line[pos] != '_') ++pos; // found an identifier.. // the "while" is used in case the expanded macro will immediately call another macro - while(pos < line.length() && (std::isalpha(line[pos]) || line[pos] == '_')) + while (pos < line.length() && (std::isalpha(line[pos]) || line[pos] == '_')) { // pos1 = start position of macro const std::string::size_type pos1 = pos++; // find the end of the identifier - while(pos < line.size() && (std::isalnum(line[pos]) || line[pos] == '_')) + while (pos < line.size() && (std::isalnum(line[pos]) || line[pos] == '_')) ++pos; // get identifier @@ -1898,7 +1898,7 @@ std::string Preprocessor::expandMacros(const std::string &code, std::string file // is there a macro with this name? std::map::const_iterator it; it = macros.find(id); - if(it == macros.end()) + if (it == macros.end()) break; // no macro with this name exist const PreprocessorMacro * const macro = it->second; @@ -1907,26 +1907,26 @@ std::string Preprocessor::expandMacros(const std::string &code, std::string file // macro { const std::map::const_iterator it2 = limits.find(macro); - if(it2 != limits.end() && pos <= line.length() - it2->second) + if (it2 != limits.end() && pos <= line.length() - it2->second) break; } // get parameters from line.. std::vector params; std::string::size_type pos2 = pos; - if(macro->params().size() && pos2 >= line.length()) + if (macro->params().size() && pos2 >= line.length()) break; // number of newlines within macro use unsigned int numberOfNewlines = 0; // if the macro has parantheses, get parameters - if(macro->variadic() || macro->nopar() || macro->params().size()) + if (macro->variadic() || macro->nopar() || macro->params().size()) { - if(line[pos2] == ' ') + if (line[pos2] == ' ') pos2++; - if(line[pos2] != '(') + if (line[pos2] != '(') break; // parantheses level @@ -1939,21 +1939,21 @@ std::string Preprocessor::expandMacros(const std::string &code, std::string file bool endFound = false; // scan for parameters.. - for(; pos2 < line.length(); ++pos2) + for (; pos2 < line.length(); ++pos2) { // increase paranthesis level - if(line[pos2] == '(') + if (line[pos2] == '(') { ++parlevel; - if(parlevel == 1) + if (parlevel == 1) continue; } // decrease paranthesis level - else if(line[pos2] == ')') + else if (line[pos2] == ')') { --parlevel; - if(parlevel <= 0) + if (parlevel <= 0) { endFound = true; params.push_back(par); @@ -1962,63 +1962,63 @@ std::string Preprocessor::expandMacros(const std::string &code, std::string file } // string - else if(line[pos2] == '\"' || line[pos2] == '\'') + else if (line[pos2] == '\"' || line[pos2] == '\'') { const std::string::size_type p = pos2; skipstring(line, pos2); - if(pos2 == line.length()) + if (pos2 == line.length()) break; par += line.substr(p, pos2 + 1 - p); continue; } // count newlines. the expanded macro must have the same number of newlines - else if(line[pos2] == '\n') + else if (line[pos2] == '\n') { ++numberOfNewlines; continue; } // new parameter - if(parlevel == 1 && line[pos2] == ',') + if (parlevel == 1 && line[pos2] == ',') { params.push_back(par); par = ""; } // spaces are only added if needed - else if(line[pos2] == ' ') + else if (line[pos2] == ' ') { // Add space only if it is needed - if(par.size() && std::isalnum(par[par.length()-1])) + if (par.size() && std::isalnum(par[par.length()-1])) { par += ' '; } } // add character to current parameter - else if(parlevel >= 1) + else if (parlevel >= 1) { par.append(1, line[pos2]); } } // something went wrong so bail out - if(!endFound) + if (!endFound) break; } // Just an empty parameter => clear - if(params.size() == 1 && params[0] == "") + if (params.size() == 1 && params[0] == "") params.clear(); // Check that it's the same number of parameters.. - if(!macro->variadic() && params.size() != macro->params().size()) + if (!macro->variadic() && params.size() != macro->params().size()) break; // Create macro code.. std::string tempMacro; - if(!macro->code(params, tempMacro)) + if (!macro->code(params, tempMacro)) { // Syntax error in code writeError(filename, @@ -2028,7 +2028,7 @@ std::string Preprocessor::expandMacros(const std::string &code, std::string file std::string("Syntax error. Not enough parameters for macro '") + macro->name() + "'."); std::map::iterator it; - for(it = macros.begin(); it != macros.end(); ++it) + for (it = macros.begin(); it != macros.end(); ++it) delete it->second; return ""; @@ -2038,14 +2038,14 @@ std::string Preprocessor::expandMacros(const std::string &code, std::string file const std::string macrocode(std::string(numberOfNewlines, '\n') + tempMacro); // Insert macro code.. - if(macro->variadic() || macro->nopar() || !macro->params().empty()) + if (macro->variadic() || macro->nopar() || !macro->params().empty()) ++pos2; // Remove old limits - for(std::map::iterator iter = limits.begin(); - iter != limits.end();) + for (std::map::iterator iter = limits.begin(); + iter != limits.end();) { - if((line.length() - pos1) < iter->second) + if ((line.length() - pos1) < iter->second) { // We have gone past this limit, so just delete it limits.erase(iter++); @@ -2075,16 +2075,16 @@ std::string Preprocessor::expandMacros(const std::string &code, std::string file ostr << line; // update linenr - for(std::string::size_type p = 0; p < line.length(); ++p) + for (std::string::size_type p = 0; p < line.length(); ++p) { - if(line[p] == '\n') + if (line[p] == '\n') ++linenr; } } { std::map::iterator it; - for(it = macros.begin(); it != macros.end(); ++it) + for (it = macros.begin(); it != macros.end(); ++it) delete it->second; } diff --git a/lib/settings.cpp b/lib/settings.cpp old mode 100644 new mode 100755 index 3687e134b..dfeeed57c --- a/lib/settings.cpp +++ b/lib/settings.cpp @@ -49,10 +49,10 @@ Settings::~Settings() void Settings::autoDealloc(std::istream &istr) { std::string line; - while(getline(istr, line)) + while (getline(istr, line)) { // Check if line has a valid classname.. - if(line.empty()) + if (line.empty()) continue; // Add classname to list @@ -63,19 +63,19 @@ void Settings::autoDealloc(std::istream &istr) bool Settings::Suppressions::parseFile(std::istream &istr) { std::string line; - while(getline(istr, line)) + while (getline(istr, line)) { // Skip empty lines - if(line.empty()) + if (line.empty()) continue; std::istringstream lineStream(line); std::string id; std::string file; unsigned int lineNumber = 0; - if(std::getline(lineStream, id, ':')) + if (std::getline(lineStream, id, ':')) { - if(std::getline(lineStream, file, ':')) + if (std::getline(lineStream, file, ':')) { lineStream >> lineNumber; } @@ -96,21 +96,21 @@ void Settings::Suppressions::addSuppression(const std::string &errorId, const st bool Settings::Suppressions::isSuppressed(const std::string &errorId, const std::string &file, unsigned int line) { - if(_suppressions.find(errorId) == _suppressions.end()) + if (_suppressions.find(errorId) == _suppressions.end()) return false; // Check are all errors of this type filtered out - if(_suppressions[errorId].find("") != _suppressions[errorId].end()) + if (_suppressions[errorId].find("") != _suppressions[errorId].end()) return true; - if(_suppressions[errorId].find(file) == _suppressions[errorId].end()) + if (_suppressions[errorId].find(file) == _suppressions[errorId].end()) return false; // Check should all errors in this file be filtered out - if(std::find(_suppressions[errorId][file].begin(), _suppressions[errorId][file].end(), 0) != _suppressions[errorId][file].end()) + if (std::find(_suppressions[errorId][file].begin(), _suppressions[errorId][file].end(), 0) != _suppressions[errorId][file].end()) return true; - if(std::find(_suppressions[errorId][file].begin(), _suppressions[errorId][file].end(), line) == _suppressions[errorId][file].end()) + if (std::find(_suppressions[errorId][file].begin(), _suppressions[errorId][file].end(), line) == _suppressions[errorId][file].end()) return false; return true; @@ -119,19 +119,19 @@ bool Settings::Suppressions::isSuppressed(const std::string &errorId, const std: void Settings::addEnabled(const std::string &str) { // Enable parameters may be comma separated... - if(str.find(",") != std::string::npos) + if (str.find(",") != std::string::npos) { std::string::size_type prevPos = 0; std::string::size_type pos = 0; - while((pos = str.find(",", pos)) != std::string::npos) + while ((pos = str.find(",", pos)) != std::string::npos) { - if(pos == prevPos) + if (pos == prevPos) throw std::runtime_error("cppcheck: --enable parameter is empty"); addEnabled(str.substr(prevPos, pos - prevPos)); ++pos; prevPos = pos; } - if(prevPos >= str.length()) + if (prevPos >= str.length()) throw std::runtime_error("cppcheck: --enable parameter is empty"); addEnabled(str.substr(prevPos)); return; @@ -139,11 +139,11 @@ void Settings::addEnabled(const std::string &str) bool handled = false; - if(str == "all") + if (str == "all") handled = _checkCodingStyle = _showAll = true; - else if(str == "style") + else if (str == "style") handled = _checkCodingStyle = true; - else if(str == "possibleError") + else if (str == "possibleError") handled = _showAll = true; std::set id; @@ -151,19 +151,19 @@ void Settings::addEnabled(const std::string &str) id.insert("exceptRealloc"); id.insert("unusedFunctions"); - if(str == "all") + if (str == "all") { std::set::const_iterator it; - for(it = id.begin(); it != id.end(); ++it) + for (it = id.begin(); it != id.end(); ++it) _enabled[*it] = true; } - else if(id.find(str) != id.end()) + else if (id.find(str) != id.end()) { _enabled[str] = true; } - else if(!handled) + else if (!handled) { - if(str.empty()) + if (str.empty()) throw std::runtime_error("cppcheck: --enable parameter is empty"); else throw std::runtime_error("cppcheck: there is no --enable parameter with the name '" + str + "'"); @@ -191,7 +191,7 @@ void Settings::append(const std::string &filename) _append = "\n"; std::ifstream fin(filename.c_str()); std::string line; - while(std::getline(fin, line)) + while (std::getline(fin, line)) { _append += line + "\n"; } diff --git a/lib/token.cpp b/lib/token.cpp index 4d579ca7c..4d7b4dda5 100644 --- a/lib/token.cpp +++ b/lib/token.cpp @@ -27,20 +27,20 @@ #include Token::Token(Token **t) : - tokensBack(t), - _str(""), - _isName(false), - _isNumber(false), - _isBoolean(false), - _isUnsigned(false), - _isSigned(false), - _isLong(false), - _varId(0), - _next(0), - _previous(0), - _link(0), - _fileIndex(0), - _linenr(0) + tokensBack(t), + _str(""), + _isName(false), + _isNumber(false), + _isBoolean(false), + _isUnsigned(false), + _isSigned(false), + _isLong(false), + _varId(0), + _next(0), + _previous(0), + _link(0), + _fileIndex(0), + _linenr(0) { } @@ -55,14 +55,14 @@ void Token::str(const std::string &s) _isName = bool(_str[0] == '_' || std::isalpha(_str[0])); - if(std::isdigit(_str[0])) + if (std::isdigit(_str[0])) _isNumber = true; - else if(_str.length() > 1 && _str[0] == '-' && std::isdigit(_str[1])) + else if (_str.length() > 1 && _str[0] == '-' && std::isdigit(_str[1])) _isNumber = true; else _isNumber = false; - if(_str == "true" || _str == "false") + if (_str == "true" || _str == "false") _isBoolean = true; else _isBoolean = false; @@ -89,15 +89,15 @@ void Token::deleteNext() Token *n = _next; _next = n->next(); delete n; - if(_next) + if (_next) _next->previous(this); - else if(tokensBack) + else if (tokensBack) *tokensBack = this; } void Token::deleteThis() { - if(_next) + if (_next) { _str = _next->_str; _isName = _next->_isName; @@ -107,12 +107,12 @@ void Token::deleteThis() _fileIndex = _next->_fileIndex; _linenr = _next->_linenr; _link = _next->_link; - if(_link) + if (_link) _link->link(this); deleteNext(); } - else if(_previous) + else if (_previous) { // This should never be used for tokens // at the end of the list @@ -129,25 +129,25 @@ void Token::deleteThis() void Token::replace(Token *replaceThis, Token *start, Token *end) { // Fix the whole in the old location of start and end - if(start->previous()) + if (start->previous()) start->previous()->next(end->next()); - if(end->next()) + if (end->next()) end->next()->previous(start->previous()); // Move start and end to their new location - if(replaceThis->previous()) + if (replaceThis->previous()) replaceThis->previous()->next(start); - if(replaceThis->next()) + if (replaceThis->next()) replaceThis->next()->previous(end); start->previous(replaceThis->previous()); end->next(replaceThis->next()); - if(end->tokensBack && *(end->tokensBack) == end) + if (end->tokensBack && *(end->tokensBack) == end) { - while(end->next()) + while (end->next()) end = end->next(); *(end->tokensBack) = end; } @@ -160,9 +160,9 @@ const Token *Token::tokAt(int index) const { const Token *tok = this; int num = std::abs(index); - while(num > 0 && tok) + while (num > 0 && tok) { - if(index > 0) + if (index > 0) tok = tok->next(); else tok = tok->previous(); @@ -175,9 +175,9 @@ Token *Token::tokAt(int index) { Token *tok = this; int num = std::abs(index); - while(num > 0 && tok) + while (num > 0 && tok) { - if(index > 0) + if (index > 0) tok = tok->next(); else tok = tok->previous(); @@ -197,21 +197,21 @@ int Token::multiCompare(const char *haystack, const char *needle) bool emptyStringFound = false; bool noMatch = false; const char *needlePointer = needle; - for(; *haystack && *haystack != ' '; ++haystack) + for (; *haystack && *haystack != ' '; ++haystack) { - if(*haystack == '|') + if (*haystack == '|') { - if(noMatch) + if (noMatch) { // We didn't have a match at this round noMatch = false; } - else if(*needlePointer == 0) + else if (*needlePointer == 0) { // If needle and haystack are both at the end, we have a match. return 1; } - else if(needlePointer == needle) + else if (needlePointer == needle) { // If needlePointer was not increased at all, we had a empty // string in the haystack @@ -222,12 +222,12 @@ int Token::multiCompare(const char *haystack, const char *needle) continue; } - if(noMatch) + if (noMatch) continue; // If haystack and needle don't share the same character, // find next '|' character. - if(*needlePointer != *haystack) + if (*needlePointer != *haystack) { noMatch = true; continue; @@ -238,14 +238,14 @@ int Token::multiCompare(const char *haystack, const char *needle) } - if(!noMatch) + if (!noMatch) { - if(*needlePointer == 0) + if (*needlePointer == 0) { // If both needle and haystack are at the end, then we have a match. return 1; } - else if(needlePointer == needle) + else if (needlePointer == needle) { // Last string in haystack was empty string e.g. "one|two|" return 0; @@ -253,7 +253,7 @@ int Token::multiCompare(const char *haystack, const char *needle) } // If empty string was found earlier from the haystack - if(emptyStringFound) + if (emptyStringFound) return 0; return -1; @@ -265,21 +265,21 @@ bool Token::simpleMatch(const Token *tok, const char pattern[]) current = pattern; next = strchr(pattern, ' '); - if(!next) + if (!next) next = pattern + strlen(pattern); - while(*current) + while (*current) { size_t length = static_cast(next - current); - if(!tok || length != tok->_str.length() || strncmp(current, tok->_str.c_str(), length)) + if (!tok || length != tok->_str.length() || strncmp(current, tok->_str.c_str(), length)) return false; current = next; - if(*next) + if (*next) { next = strchr(++current, ' '); - if(!next) + if (!next) next = current + strlen(current); } tok = tok->next(); @@ -290,13 +290,13 @@ bool Token::simpleMatch(const Token *tok, const char pattern[]) int Token::firstWordEquals(const char *str, const char *word) { - for(;;) + for (;;) { - if(*str == ' ' && *word == 0) + if (*str == ' ' && *word == 0) return 0; - else if(*str != *word) + else if (*str != *word) return 1; - else if(*str == 0) + else if (*str == 0) break; ++str; @@ -308,12 +308,12 @@ int Token::firstWordEquals(const char *str, const char *word) const char *Token::chrInFirstWord(const char *str, char c) { - for(;;) + for (;;) { - if(*str == ' ' || *str == 0) + if (*str == ' ' || *str == 0) return 0; - if(*str == c) + if (*str == c) return str; ++str; @@ -323,9 +323,9 @@ const char *Token::chrInFirstWord(const char *str, char c) int Token::firstWordLen(const char *str) { int len = 0; - for(;;) + for (;;) { - if(*str == ' ' || *str == 0) + if (*str == ' ' || *str == 0) break; ++len; @@ -340,35 +340,35 @@ bool Token::Match(const Token *tok, const char pattern[], unsigned int varid) const char *p = pattern; bool firstpattern = true; bool first = true; - while(*p) + while (*p) { - if(!first) + if (!first) { - while(*p && *p != ' ') + while (*p && *p != ' ') ++p; } first = false; // Skip spaces in pattern.. - while(*p == ' ') + while (*p == ' ') ++p; // No token => Success! - if(*p == 0) + if (*p == 0) return true; - if(!tok) + if (!tok) { // If we have no tokens, pattern "!!else" should return true - if(p[1] == '!' && p[0] == '!' && p[2] != '\0') + if (p[1] == '!' && p[0] == '!' && p[2] != '\0') continue; else return false; } // If we are in the first token, we skip all initial !! patterns - if(firstpattern && !tok->previous() && tok->next() && p[1] == '!' && p[0] == '!' && p[2] != '\0') + if (firstpattern && !tok->previous() && tok->next() && p[1] == '!' && p[0] == '!' && p[2] != '\0') continue; firstpattern = false; @@ -376,110 +376,110 @@ bool Token::Match(const Token *tok, const char pattern[], unsigned int varid) // Compare the first character of the string for optimization reasons // before doing more detailed checks. bool patternIdentified = false; - if(p[0] == '%') + if (p[0] == '%') { // TODO: %var% should match only for // variables that have varId != 0, but that needs a lot of // work, before that change can be made. // Any symbolname.. - if(firstWordEquals(p, "%var%") == 0) + if (firstWordEquals(p, "%var%") == 0) { - if(!tok->isName()) + if (!tok->isName()) return false; patternIdentified = true; } // Any symbolname.. - if(firstWordEquals(p, "%name%") == 0) + if (firstWordEquals(p, "%name%") == 0) { - if(!tok->isName()) + if (!tok->isName()) return false; patternIdentified = true; } // Type.. - if(firstWordEquals(p, "%type%") == 0) + if (firstWordEquals(p, "%type%") == 0) { - if(!tok->isName()) + if (!tok->isName()) return false; - if(tok->varId() != 0) + if (tok->varId() != 0) return false; - if(tok->str() == "delete") + if (tok->str() == "delete") return false; patternIdentified = true; } // Accept any token - else if(firstWordEquals(p, "%any%") == 0) + else if (firstWordEquals(p, "%any%") == 0) { patternIdentified = true; } - else if(firstWordEquals(p, "%varid%") == 0) + else if (firstWordEquals(p, "%varid%") == 0) { - if(varid == 0) + if (varid == 0) { std::cerr << "\n###### If you see this, there is a bug ######" << std::endl << "Token::Match(\"" << pattern << "\", 0)" << std::endl; } - if(tok->varId() != varid) + if (tok->varId() != varid) return false; patternIdentified = true; } - else if(firstWordEquals(p, "%num%") == 0) + else if (firstWordEquals(p, "%num%") == 0) { - if(!tok->isNumber()) + if (!tok->isNumber()) return false; patternIdentified = true; } - else if(firstWordEquals(p, "%bool%") == 0) + else if (firstWordEquals(p, "%bool%") == 0) { - if(!tok->isBoolean()) + if (!tok->isBoolean()) return false; patternIdentified = true; } - else if(firstWordEquals(p, "%str%") == 0) + else if (firstWordEquals(p, "%str%") == 0) { - if(tok->_str[0] != '\"') + if (tok->_str[0] != '\"') return false; patternIdentified = true; } } - if(patternIdentified) + if (patternIdentified) { // Pattern was identified already above. } // [.. => search for a one-character token.. - else if(p[0] == '[' && chrInFirstWord(p, ']') && tok->_str.length() == 1) + else if (p[0] == '[' && chrInFirstWord(p, ']') && tok->_str.length() == 1) { const char *temp = p + 1; bool chrFound = false; int count = 0; - while(*temp && *temp != ' ') + while (*temp && *temp != ' ') { - if(*temp == ']') + if (*temp == ']') { ++count; ++temp; continue; } - if(*temp == tok->_str[0]) + if (*temp == tok->_str[0]) { chrFound = true; break; @@ -488,26 +488,26 @@ bool Token::Match(const Token *tok, const char pattern[], unsigned int varid) ++temp; } - if(count > 1) + if (count > 1) { - if(tok->_str[0] == ']') + if (tok->_str[0] == ']') chrFound = true; } - if(!chrFound) + if (!chrFound) return false; } // Parse multi options, such as void|int|char (accept token which is one of these 3) - else if(chrInFirstWord(p, '|') && (p[0] != '|' || firstWordLen(p) > 2)) + else if (chrInFirstWord(p, '|') && (p[0] != '|' || firstWordLen(p) > 2)) { int res = multiCompare(p, tok->_str.c_str()); - if(res == 0) + if (res == 0) { // Empty alternative matches, use the same token on next round continue; } - else if(res == -1) + else if (res == -1) { // No match return false; @@ -515,13 +515,13 @@ bool Token::Match(const Token *tok, const char pattern[], unsigned int varid) } // Parse "not" options. Token can be anything except the given one - else if(p[1] == '!' && p[0] == '!' && p[2] != '\0') + else if (p[1] == '!' && p[0] == '!' && p[2] != '\0') { - if(firstWordEquals(&(p[2]), tok->str().c_str()) == 0) + if (firstWordEquals(&(p[2]), tok->str().c_str()) == 0) return false; } - else if(firstWordEquals(p, tok->_str.c_str()) != 0) + else if (firstWordEquals(p, tok->_str.c_str()) != 0) return false; tok = tok->next(); @@ -539,14 +539,14 @@ size_t Token::getStrLength(const Token *tok) const std::string strValue(tok->strValue()); const char *str = strValue.c_str(); - while(*str) + while (*str) { - if(*str == '\\') + if (*str == '\\') { ++str; // string ends at '\0' - if(*str == '0') + if (*str == '0') break; } @@ -561,7 +561,7 @@ bool Token::isStandardType() const { bool ret = false; const char *type[] = {"bool", "char", "short", "int", "long", "float", "double", "size_t", "__int64", 0}; - for(int i = 0; type[i]; i++) + for (int i = 0; type[i]; i++) ret |= (_str == type[i]); return ret; } @@ -570,7 +570,7 @@ bool Token::isIntegerType() const { bool ret = false; const char *type[] = {"char", "short", "int", "long", "size_t", "__int64", 0}; - for(int i = 0; type[i]; i++) + for (int i = 0; type[i]; i++) ret |= (_str == type[i]); return ret; } @@ -596,9 +596,9 @@ void Token::move(Token *srcStart, Token *srcEnd, Token *newLocation) const Token *Token::findmatch(const Token *tok, const char pattern[], unsigned int varId) { - for(; tok; tok = tok->next()) + for (; tok; tok = tok->next()) { - if(Token::Match(tok, pattern, varId)) + if (Token::Match(tok, pattern, varId)) return tok; } return 0; @@ -610,12 +610,12 @@ void Token::insertToken(const std::string &str) newToken->str(str); newToken->_linenr = _linenr; newToken->_fileIndex = _fileIndex; - if(this->next()) + if (this->next()) { newToken->next(this->next()); newToken->next()->previous(newToken); } - else if(tokensBack) + else if (tokensBack) { *tokensBack = newToken; } @@ -626,10 +626,10 @@ void Token::insertToken(const std::string &str) void Token::eraseTokens(Token *begin, const Token *end) { - if(! begin) + if (! begin) return; - while(begin->next() && begin->next() != end) + while (begin->next() && begin->next() != end) { begin->deleteNext(); } @@ -664,25 +664,25 @@ std::string Token::stringifyList(bool varid, const char *title) const std::string Token::stringifyList(bool varid, const char *title, const std::vector &fileNames) const { std::ostringstream ret; - if(title) + if (title) ret << "\n### " << title << " ###\n"; unsigned int linenr = 0; int fileIndex = -1; std::map lineNumbers; - for(const Token *tok = this; tok; tok = tok->next()) + for (const Token *tok = this; tok; tok = tok->next()) { bool fileChange = false; - if(static_cast(tok->_fileIndex) != fileIndex) + if (static_cast(tok->_fileIndex) != fileIndex) { - if(fileIndex != -1) + if (fileIndex != -1) { lineNumbers[fileIndex] = tok->_fileIndex; } fileIndex = static_cast(tok->_fileIndex); ret << "\n\n##file "; - if(fileNames.size() > static_cast(fileIndex)) + if (fileNames.size() > static_cast(fileIndex)) ret << fileNames.at(fileIndex); else ret << fileIndex; @@ -691,9 +691,9 @@ std::string Token::stringifyList(bool varid, const char *title, const std::vecto fileChange = true; } - if(linenr != tok->linenr() || fileChange) + if (linenr != tok->linenr() || fileChange) { - while(linenr < tok->linenr()) + while (linenr < tok->linenr()) { ++linenr; ret << "\n" << linenr << ":"; @@ -702,7 +702,7 @@ std::string Token::stringifyList(bool varid, const char *title, const std::vecto } ret << " " << tok->str(); - if(varid && tok->varId() > 0) + if (varid && tok->varId() > 0) ret << "@" << tok->varId(); } ret << "\n"; diff --git a/lib/tokenize.cpp b/lib/tokenize.cpp index f34d45c27..47f710abf 100644 --- a/lib/tokenize.cpp +++ b/lib/tokenize.cpp @@ -42,14 +42,14 @@ //--------------------------------------------------------------------------- Tokenizer::Tokenizer() - : _settings(0), _errorLogger(0) + : _settings(0), _errorLogger(0) { _tokens = 0; _tokensBack = 0; } Tokenizer::Tokenizer(const Settings *settings, ErrorLogger *errorLogger) - : _settings(settings), _errorLogger(errorLogger) + : _settings(settings), _errorLogger(errorLogger) { _tokens = 0; _tokensBack = 0; @@ -87,12 +87,12 @@ const std::vector *Tokenizer::getFiles() const void Tokenizer::addtoken(const char str[], const unsigned int lineno, const unsigned int fileno) { - if(str[0] == 0) + if (str[0] == 0) return; // Replace hexadecimal value with decimal std::ostringstream str2; - if(strncmp(str, "0x", 2) == 0) + if (strncmp(str, "0x", 2) == 0) { str2 << std::strtoul(str + 2, NULL, 16); } @@ -101,7 +101,7 @@ void Tokenizer::addtoken(const char str[], const unsigned int lineno, const unsi str2 << str; } - if(_tokensBack) + if (_tokensBack) { _tokensBack->insertToken(str2.str().c_str()); } @@ -118,12 +118,12 @@ void Tokenizer::addtoken(const char str[], const unsigned int lineno, const unsi void Tokenizer::addtoken(const Token * tok, const unsigned int lineno, const unsigned int fileno) { - if(tok == 0) + if (tok == 0) return; // Replace hexadecimal value with decimal std::ostringstream str2; - if(strncmp(tok->str().c_str(), "0x", 2) == 0) + if (strncmp(tok->str().c_str(), "0x", 2) == 0) { str2 << std::strtoul(tok->str().c_str() + 2, NULL, 16); } @@ -132,7 +132,7 @@ void Tokenizer::addtoken(const Token * tok, const unsigned int lineno, const uns str2 << tok->str(); } - if(_tokensBack) + if (_tokensBack) { _tokensBack->insertToken(str2.str().c_str()); } @@ -159,20 +159,20 @@ void Tokenizer::addtoken(const Token * tok, const unsigned int lineno, const uns unsigned int Tokenizer::sizeOfType(const Token *type) const { - if(!type || type->str().empty()) + if (!type || type->str().empty()) return 0; - if(type->str()[0] == '"') + if (type->str()[0] == '"') return static_cast(Token::getStrLength(type) + 1); std::map::const_iterator it = _typeSize.find(type->strAt(0)); - if(it == _typeSize.end()) + if (it == _typeSize.end()) return 0; - else if(type->isLong()) + else if (type->isLong()) { - if(type->str() == "double") + if (type->str() == "double") return sizeof(long double); - else if(type->str() == "long") + else if (type->str() == "long") return sizeof(long long); } @@ -186,7 +186,7 @@ unsigned int Tokenizer::sizeOfType(const Token *type) const void Tokenizer::insertTokens(Token *dest, const Token *src, unsigned int n) { - while(n > 0) + while (n > 0) { dest->insertToken(src->str().c_str()); dest = dest->next(); @@ -228,14 +228,14 @@ void Tokenizer::createTokens(std::istream &code) unsigned int FileIndex = 0; // Read one byte at a time from code and create tokens - for(char ch = (char)code.get(); code.good(); ch = (char)code.get()) + for (char ch = (char)code.get(); code.good(); ch = (char)code.get()) { // We are not handling UTF and stuff like that. Code is supposed to plain simple text. - if(ch < 0) + if (ch < 0) continue; // char/string.. - if(ch == '\'' || ch == '\"') + if (ch == '\'' || ch == '\"') { std::string line; @@ -247,11 +247,11 @@ void Tokenizer::createTokens(std::istream &code) // Append token.. line += c; - if(c == '\n') + if (c == '\n') ++lineno; // Special sequence '\.' - if(special) + if (special) special = false; else special = (c == '\\'); @@ -259,11 +259,11 @@ void Tokenizer::createTokens(std::istream &code) // Get next character c = (char)code.get(); } - while(code.good() && (special || c != ch)); + while (code.good() && (special || c != ch)); line += ch; // Handle #file "file.h" - if(CurrentToken == "#file") + if (CurrentToken == "#file") { // Extract the filename line = line.substr(1, line.length() - 2); @@ -272,9 +272,9 @@ void Tokenizer::createTokens(std::istream &code) ++lineno; bool foundOurfile = false; fileIndexes.push_back(FileIndex); - for(unsigned int i = 0; i < _files.size(); i++) + for (unsigned int i = 0; i < _files.size(); i++) { - if(getFileLister()->sameFileName(_files[i].c_str(), line.c_str())) + if (getFileLister()->sameFileName(_files[i].c_str(), line.c_str())) { // Use this index foundOurfile = true; @@ -282,7 +282,7 @@ void Tokenizer::createTokens(std::istream &code) } } - if(!foundOurfile) + if (!foundOurfile) { // The "_files" vector remembers what files have been tokenized.. _files.push_back(getFileLister()->simplifyPath(line.c_str())); @@ -306,31 +306,31 @@ void Tokenizer::createTokens(std::istream &code) continue; } - if(strchr("+-*/%&|^?!=<>[](){};:,.~\n ", ch)) + if (strchr("+-*/%&|^?!=<>[](){};:,.~\n ", ch)) { - if(ch == '.' && - CurrentToken.length() > 0 && - std::isdigit(CurrentToken[0])) + if (ch == '.' && + CurrentToken.length() > 0 && + std::isdigit(CurrentToken[0])) { // Don't separate doubles "5.4" } - else if(strchr("+-", ch) && - CurrentToken.length() > 0 && - std::isdigit(CurrentToken[0]) && - CurrentToken[CurrentToken.length()-1] == 'e') + else if (strchr("+-", ch) && + CurrentToken.length() > 0 && + std::isdigit(CurrentToken[0]) && + CurrentToken[CurrentToken.length()-1] == 'e') { // Don't separate doubles "4.2e+10" } else { - if(CurrentToken == "#file") + if (CurrentToken == "#file") { // Handle this where strings are handled continue; } - else if(CurrentToken == "#endfile") + else if (CurrentToken == "#endfile") { - if(lineNumbers.empty() || fileIndexes.empty()) + if (lineNumbers.empty() || fileIndexes.empty()) { std::cerr << "####### Preprocessor bug! #######\n"; std::exit(0); @@ -345,14 +345,14 @@ void Tokenizer::createTokens(std::istream &code) } // If token contains # characters, split it up - if(CurrentToken.find("##") == std::string::npos) + if (CurrentToken.find("##") == std::string::npos) addtoken(CurrentToken.c_str(), lineno, FileIndex); else { std::string temp; - for(std::string::size_type i = 0; i < CurrentToken.length(); ++i) + for (std::string::size_type i = 0; i < CurrentToken.length(); ++i) { - if(CurrentToken[i] == '#' && CurrentToken.length() + 1 > i && CurrentToken[i+1] == '#') + if (CurrentToken[i] == '#' && CurrentToken.length() + 1 > i && CurrentToken[i+1] == '#') { addtoken(temp.c_str(), lineno, FileIndex); temp.clear(); @@ -367,19 +367,19 @@ void Tokenizer::createTokens(std::istream &code) CurrentToken.clear(); - if(ch == '\n') + if (ch == '\n') { ++lineno; continue; } - else if(ch == ' ') + else if (ch == ' ') { continue; } CurrentToken += ch; // Add "++", "--" or ">>" token - if((ch == '+' || ch == '-' || ch == '>') && (code.peek() == ch)) + if ((ch == '+' || ch == '-' || ch == '>') && (code.peek() == ch)) CurrentToken += (char)code.get(); addtoken(CurrentToken.c_str(), lineno, FileIndex); CurrentToken.clear(); @@ -389,14 +389,14 @@ void Tokenizer::createTokens(std::istream &code) CurrentToken += ch; } - if(CurrentToken.find("##") == std::string::npos) + if (CurrentToken.find("##") == std::string::npos) addtoken(CurrentToken.c_str(), lineno, FileIndex); else { std::string temp; - for(std::string::size_type i = 0; i < CurrentToken.length(); ++i) + for (std::string::size_type i = 0; i < CurrentToken.length(); ++i) { - if(CurrentToken[i] == '#' && CurrentToken.length() + 1 > i && CurrentToken[i+1] == '#') + if (CurrentToken[i] == '#' && CurrentToken.length() + 1 > i && CurrentToken[i+1] == '#') { addtoken(temp.c_str(), lineno, FileIndex); temp.clear(); @@ -412,7 +412,7 @@ void Tokenizer::createTokens(std::istream &code) void Tokenizer::duplicateTypedefError(const Token *tok1, const Token *tok2, const std::string &type) { - if(!(_settings && _settings->_checkCodingStyle)) + if (!(_settings && _settings->_checkCodingStyle)) return; std::list locationList; @@ -427,10 +427,10 @@ void Tokenizer::duplicateTypedefError(const Token *tok1, const Token *tok2, cons const ErrorLogger::ErrorMessage errmsg(locationList, "style", std::string(type + " '" + tok2->str() + - "' hides typedef with same name"), + "' hides typedef with same name"), "variableHidingTypedef"); - if(_errorLogger) + if (_errorLogger) _errorLogger->reportErr(errmsg); else Check::reportError(errmsg); @@ -441,59 +441,59 @@ bool Tokenizer::duplicateTypedef(Token **tokPtr, const Token *name) { // check for an end of definition const Token * tok = *tokPtr; - if(tok && tok->next() && Token::Match(tok->next(), ";|,|[|=|)|>|(")) + if (tok && tok->next() && Token::Match(tok->next(), ";|,|[|=|)|>|(")) { const Token * end = tok->next(); - if(end->str() == "[") + if (end->str() == "[") { end = end->link()->next(); } - else if(end->str() == ",") + else if (end->str() == ",") { // check for derived class - if(Token::Match(tok->previous(), "public|private|protected")) + if (Token::Match(tok->previous(), "public|private|protected")) return false; // find end of definition int level = 0; - while(end && end->next() && (!Token::Match(end->next(), ";|)|>") || - (end->next()->str() == ")" && level == 0))) + while (end && end->next() && (!Token::Match(end->next(), ";|)|>") || + (end->next()->str() == ")" && level == 0))) { - if(end->next()->str() == "(") + if (end->next()->str() == "(") level++; - else if(end->next()->str() == ")") + else if (end->next()->str() == ")") level--; end = end->next(); } end = end->next(); } - else if(end->str() == "(") + else if (end->str() == "(") { - if(tok->previous()->str() == "operator") + if (tok->previous()->str() == "operator") { // conversion operator return false; } - else if(tok->previous()->str() == "typedef") + else if (tok->previous()->str() == "typedef") { // typedef of function returning this type return false; } - else if(Token::Match(tok->previous(), "public:|private:|protected:")) + else if (Token::Match(tok->previous(), "public:|private:|protected:")) { return false; } - else if(tok->previous()->str() == ">") + else if (tok->previous()->str() == ">") { duplicateTypedefError(*tokPtr, name, "Template instantiation"); *tokPtr = end->link(); return true; } - else if(Token::Match(tok->previous(), "%type%")) + else if (Token::Match(tok->previous(), "%type%")) { - if(end->link()->next()->str() == "{") + if (end->link()->next()->str() == "{") { duplicateTypedefError(*tokPtr, name, "Function"); *tokPtr = end->link()->next()->link(); @@ -502,13 +502,13 @@ bool Tokenizer::duplicateTypedef(Token **tokPtr, const Token *name) } } - if(end) + if (end) { - if(Token::Match(end, ") {")) // function parameter ? + if (Token::Match(end, ") {")) // function parameter ? { // look backwards - if(Token::Match(tok->previous(), "%type%") && - !Token::Match(tok->previous(), "return|new|const")) + if (Token::Match(tok->previous(), "%type%") && + !Token::Match(tok->previous(), "return|new|const")) { duplicateTypedefError(*tokPtr, name, "Function parameter"); // duplicate definition so skip entire function @@ -516,16 +516,16 @@ bool Tokenizer::duplicateTypedef(Token **tokPtr, const Token *name) return true; } } - else if(end->str() == ">") // template parameter ? + else if (end->str() == ">") // template parameter ? { // look backwards - if(Token::Match(tok->previous(), "%type%") && - !Token::Match(tok->previous(), "return|new|const|volatile")) + if (Token::Match(tok->previous(), "%type%") && + !Token::Match(tok->previous(), "return|new|const|volatile")) { // duplicate definition so skip entire template - while(end && end->str() != "{") + while (end && end->str() != "{") end = end->next(); - if(end) + if (end) { duplicateTypedefError(*tokPtr, name, "Template parameter"); *tokPtr = end->link(); @@ -536,26 +536,26 @@ bool Tokenizer::duplicateTypedef(Token **tokPtr, const Token *name) else { // look backwards - if(Token::Match(tok->previous(), "typedef|}|>") || - (Token::Match(tok->previous(), "%type%") && - (!Token::Match(tok->previous(), "return|new|const|friend|struct") && - !Token::Match(tok->tokAt(-2), "friend class")))) + if (Token::Match(tok->previous(), "typedef|}|>") || + (Token::Match(tok->previous(), "%type%") && + (!Token::Match(tok->previous(), "return|new|const|friend|struct") && + !Token::Match(tok->tokAt(-2), "friend class")))) { // scan backwards for the end of the previous statement int level = (tok->previous()->str() == "}") ? 1 : 0; - while(tok && tok->previous() && (!Token::Match(tok->previous(), ";|{") || (level != 0))) + while (tok && tok->previous() && (!Token::Match(tok->previous(), ";|{") || (level != 0))) { - if(tok->previous()->str() == "typedef") + if (tok->previous()->str() == "typedef") { duplicateTypedefError(*tokPtr, name, "Typedef"); return true; } - else if(tok->previous()->str() == "enum") + else if (tok->previous()->str() == "enum") { duplicateTypedefError(*tokPtr, name, "Enum"); return true; } - else if(tok->previous()->str() == "{") + else if (tok->previous()->str() == "{") level--; tok = tok->previous(); @@ -584,21 +584,21 @@ void Tokenizer::simplifyTypedef() bool isNamespace = false; std::string className; bool hasClass = false; - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(Token::Match(tok, "class|struct|namespace %any%")) + if (Token::Match(tok, "class|struct|namespace %any%")) { isNamespace = (tok->str() == "namespace"); hasClass = true; className = tok->next()->str(); continue; } - else if(hasClass && tok->str() == ";") + else if (hasClass && tok->str() == ";") { hasClass = false; continue; } - else if(hasClass && tok->str() == "{") + else if (hasClass && tok->str() == "{") { SpaceInfo info; info.isNamespace = isNamespace; @@ -609,30 +609,30 @@ void Tokenizer::simplifyTypedef() hasClass = false; continue; } - else if(!spaceInfo.empty() && tok->str() == "}" && spaceInfo.back().classEnd == tok) + else if (!spaceInfo.empty() && tok->str() == "}" && spaceInfo.back().classEnd == tok) { spaceInfo.pop_back(); continue; } - else if(tok->str() != "typedef") + else if (tok->str() != "typedef") continue; // pull struct, union or enum definition out of typedef // use typedef name for unnamed struct, union or enum - if(Token::Match(tok->next(), "struct|enum|union %type% {") || - Token::Match(tok->next(), "struct|enum|union {")) + if (Token::Match(tok->next(), "struct|enum|union %type% {") || + Token::Match(tok->next(), "struct|enum|union {")) { Token *tok1; std::string name; - if(tok->tokAt(2)->str() == "{") // unnamed + if (tok->tokAt(2)->str() == "{") // unnamed { tok1 = tok->tokAt(2)->link(); - if(tok1 && tok1->next()) + if (tok1 && tok1->next()) { // use typedef name if available - if(Token::Match(tok1->next(), "%type%")) + if (Token::Match(tok1->next(), "%type%")) name = tok1->next()->str(); else // create a unique name { @@ -648,7 +648,7 @@ void Tokenizer::simplifyTypedef() { tok1 = tok->tokAt(3)->link(); - if(!tok1) + if (!tok1) continue; name = tok->tokAt(2)->str(); @@ -679,8 +679,8 @@ void Tokenizer::simplifyTypedef() bool functionPtr = false; bool functionRef = false; - if(Token::Match(tok->next(), "::") || - Token::Match(tok->next(), "%type%")) + if (Token::Match(tok->next(), "::") || + Token::Match(tok->next(), "%type%")) { typeStart = tok->next(); offset = 1; @@ -688,13 +688,13 @@ void Tokenizer::simplifyTypedef() typeEnd = tok->tokAt(offset++); bool atEnd = false; - while(!atEnd) + while (!atEnd) { - if(tok->tokAt(offset) && Token::Match(tok->tokAt(offset), "::")) + if (tok->tokAt(offset) && Token::Match(tok->tokAt(offset), "::")) typeEnd = tok->tokAt(offset++); - if(tok->tokAt(offset) && Token::Match(tok->tokAt(offset), "%type%") && - tok->tokAt(offset + 1) && !Token::Match(tok->tokAt(offset + 1), "[|;|,")) + if (tok->tokAt(offset) && Token::Match(tok->tokAt(offset), "%type%") && + tok->tokAt(offset + 1) && !Token::Match(tok->tokAt(offset + 1), "[|;|,")) typeEnd = tok->tokAt(offset++); else atEnd = true; @@ -704,37 +704,37 @@ void Tokenizer::simplifyTypedef() continue; // invalid input // check for template - if(tok->tokAt(offset)->str() == "<") + if (tok->tokAt(offset)->str() == "<") { int level = 1; int paren = 0; typeEnd = tok->tokAt(offset + 1); - for(; typeEnd ; typeEnd = typeEnd->next()) + for (; typeEnd ; typeEnd = typeEnd->next()) { - if(typeEnd->str() == ">") + if (typeEnd->str() == ">") { - if(paren == 0) + if (paren == 0) { level--; - if(level == 0) + if (level == 0) break; } } - else if(typeEnd->str() == "<") + else if (typeEnd->str() == "<") { - if(paren == 0) + if (paren == 0) level++; } - else if(typeEnd->str() == "(") + else if (typeEnd->str() == "(") paren++; - else if(typeEnd->str() == ")") + else if (typeEnd->str() == ")") paren--; } - while(typeEnd && typeEnd->next() && Token::Match(typeEnd->next(), ":: %type%")) + while (typeEnd && typeEnd->next() && Token::Match(typeEnd->next(), ":: %type%")) typeEnd = typeEnd->tokAt(2); - if(!typeEnd) + if (!typeEnd) { // internal error return; @@ -745,30 +745,30 @@ void Tokenizer::simplifyTypedef() } // check for pointers and references - while(tok->tokAt(offset) && Token::Match(tok->tokAt(offset), "*|&")) + while (tok->tokAt(offset) && Token::Match(tok->tokAt(offset), "*|&")) pointers.push_back(tok->tokAt(offset++)->str()); - if(tok->tokAt(offset) && Token::Match(tok->tokAt(offset), "%type%")) + if (tok->tokAt(offset) && Token::Match(tok->tokAt(offset), "%type%")) { // found the type name typeName = tok->tokAt(offset++); // check for array - if(tok->tokAt(offset) && tok->tokAt(offset)->str() == "[") + if (tok->tokAt(offset) && tok->tokAt(offset)->str() == "[") { arrayStart = tok->tokAt(offset); bool atEnd = false; - while(!atEnd) + while (!atEnd) { - while(tok->tokAt(offset + 1) && !Token::Match(tok->tokAt(offset + 1), ";|,")) + while (tok->tokAt(offset + 1) && !Token::Match(tok->tokAt(offset + 1), ";|,")) offset++; - if(!tok->tokAt(offset + 1)) + if (!tok->tokAt(offset + 1)) return; // invalid input - else if(tok->tokAt(offset + 1)->str() == ";") + else if (tok->tokAt(offset + 1)->str() == ";") atEnd = true; - else if(tok->tokAt(offset)->str() == "]") + else if (tok->tokAt(offset)->str() == "]") atEnd = true; else offset++; @@ -778,7 +778,7 @@ void Tokenizer::simplifyTypedef() } // check for end or another - if(tok->tokAt(offset) && Token::Match(tok->tokAt(offset), ";|,")) + if (tok->tokAt(offset) && Token::Match(tok->tokAt(offset), ";|,")) tok = tok->tokAt(offset); else { @@ -787,9 +787,9 @@ void Tokenizer::simplifyTypedef() continue; } } - else if(tok->tokAt(offset) && Token::Match(tok->tokAt(offset), "( *|& %type% ) (")) + else if (tok->tokAt(offset) && Token::Match(tok->tokAt(offset), "( *|& %type% ) (")) { - if(tok->tokAt(offset + 4)->link()->next()) + if (tok->tokAt(offset + 4)->link()->next()) { functionPtr = tok->tokAt(offset + 1)->str() == "*"; functionRef = tok->tokAt(offset + 1)->str() == "&"; @@ -813,7 +813,7 @@ void Tokenizer::simplifyTypedef() bool done = false; bool ok = true; - while(!done) + while (!done) { std::string pattern; int scope = 0; @@ -824,21 +824,21 @@ void Tokenizer::simplifyTypedef() bool simplifyType = false; unsigned int classLevel = spaceInfo.size(); - for(unsigned int i = classLevel; i < spaceInfo.size(); i++) + for (unsigned int i = classLevel; i < spaceInfo.size(); i++) pattern += (spaceInfo[i].className + " :: "); pattern += typeName->str(); - for(Token *tok2 = tok; tok2; tok2 = tok2->next()) + for (Token *tok2 = tok; tok2; tok2 = tok2->next()) { - if(tok2->str() == "}") + if (tok2->str() == "}") { - if(classLevel > 0 && tok2 == spaceInfo[classLevel - 1].classEnd) + if (classLevel > 0 && tok2 == spaceInfo[classLevel - 1].classEnd) { --classLevel; pattern.clear(); - for(unsigned int i = classLevel; i < spaceInfo.size(); i++) + for (unsigned int i = classLevel; i < spaceInfo.size(); i++) pattern += (spaceInfo[i].className + " :: "); pattern += typeName->str(); @@ -846,37 +846,37 @@ void Tokenizer::simplifyTypedef() else { scope--; - if(scope < 0) + if (scope < 0) inScope = false; - if(exitThisScope) + if (exitThisScope) { - if(scope < exitScope) + if (scope < exitScope) exitThisScope = false; } } } - else if(tok2->str() == "{") + else if (tok2->str() == "{") { scope++; } - else if(Token::Match(tok2, pattern.c_str())) + else if (Token::Match(tok2, pattern.c_str())) { - if(pattern != typeName->str()) // has a "something ::" + if (pattern != typeName->str()) // has a "something ::" { - for(unsigned int i = classLevel; i < spaceInfo.size(); i++) + for (unsigned int i = classLevel; i < spaceInfo.size(); i++) { tok2->deleteNext(); tok2->deleteNext(); } simplifyType = true; } - else if(inScope && !exitThisScope) + else if (inScope && !exitThisScope) { - if(Token::simpleMatch(tok2->previous(), "::")) + if (Token::simpleMatch(tok2->previous(), "::")) { // Don't replace this typename if it's preceded by "::" unless it's a namespace - if(!spaceInfo.empty() && (tok2->tokAt(-2)->str() == spaceInfo[0].className) && spaceInfo[0].isNamespace) + if (!spaceInfo.empty() && (tok2->tokAt(-2)->str() == spaceInfo[0].className) && spaceInfo[0].isNamespace) { tok2 = tok2->tokAt(-3); tok2->deleteNext(); @@ -885,19 +885,19 @@ void Tokenizer::simplifyTypedef() simplifyType = true; } } - else if(duplicateTypedef(&tok2, typeName)) + else if (duplicateTypedef(&tok2, typeName)) { exitScope = scope; // skip to end of scope if not already there - if(tok2->str() != "}") + if (tok2->str() != "}") { int level = 0; - while(tok2->next() && (tok2->next()->str() != "}" || level)) + while (tok2->next() && (tok2->next()->str() != "}" || level)) { - if(tok2->next()->str() == "{") + if (tok2->next()->str() == "{") level++; - else if(tok2->next()->str() == "}") + else if (tok2->next()->str() == "}") level--; tok2 = tok2->next(); @@ -911,27 +911,27 @@ void Tokenizer::simplifyTypedef() } } - if(simplifyType) + if (simplifyType) { bool inCast = false; - if((tok2->previous()->str() == "(" && tok2->next()->str() == ")") || - (Token::Match(tok2->tokAt(-1), "<") && - Token::Match(tok2->next(), "> ("))) + if ((tok2->previous()->str() == "(" && tok2->next()->str() == ")") || + (Token::Match(tok2->tokAt(-1), "<") && + Token::Match(tok2->next(), "> ("))) inCast = true; tok2->str(typeStart->str()); Token * nextToken; std::stack links; - for(nextToken = typeStart->next(); nextToken != typeEnd->next(); nextToken = nextToken->next()) + for (nextToken = typeStart->next(); nextToken != typeEnd->next(); nextToken = nextToken->next()) { tok2->insertToken(nextToken->strAt(0)); tok2 = tok2->next(); // Check for links and fix them up - if(tok2->str() == "(" || tok2->str() == "[") + if (tok2->str() == "(" || tok2->str() == "[") links.push(tok2); - if(tok2->str() == ")" || tok2->str() == "]") + if (tok2->str() == ")" || tok2->str() == "]") { Token * link = links.top(); @@ -942,47 +942,47 @@ void Tokenizer::simplifyTypedef() } } - while(!pointers.empty()) + while (!pointers.empty()) { tok2->insertToken(pointers.front().c_str()); pointers.pop_front(); tok2 = tok2->next(); } - if(functionPtr || functionRef) + if (functionPtr || functionRef) { tok2->insertToken("("); tok2 = tok2->next(); Token *tok3 = tok2; - if(functionPtr) + if (functionPtr) tok2->insertToken("*"); else tok2->insertToken("&"); tok2 = tok2->next(); - if(!inCast) + if (!inCast) { - if(tok2->next()->str() != ")" && tok2->next()->str() != ",") + if (tok2->next()->str() != ")" && tok2->next()->str() != ",") { - if(Token::Match(tok2->next(), "( * %type% ) (")) + if (Token::Match(tok2->next(), "( * %type% ) (")) tok2 = tok2->tokAt(5)->link(); else { - if(tok2->next()->str() == "(") + if (tok2->next()->str() == "(") tok2 = tok2->next()->link(); - else if(tok2->next()->str() != "[") + else if (tok2->next()->str() != "[") { tok2 = tok2->next(); - while(Token::Match(tok2, "*|&") && tok2->next()->str() != ")") + while (Token::Match(tok2, "*|&") && tok2->next()->str() != ")") tok2 = tok2->next(); // skip over typedef parameter - if(tok2->next()->str() == "(") + if (tok2->next()->str() == "(") { tok2 = tok2->next()->link(); - if(tok2->next()->str() == "(") + if (tok2->next()->str() == "(") tok2 = tok2->next()->link(); } } @@ -998,15 +998,15 @@ void Tokenizer::simplifyTypedef() tok3 = tok2; Token * nextToken; std::stack links; - for(nextToken = argStart->next(); nextToken != argEnd; nextToken = nextToken->next()) + for (nextToken = argStart->next(); nextToken != argEnd; nextToken = nextToken->next()) { tok2->insertToken(nextToken->strAt(0)); tok2 = tok2->next(); // Check for links and fix them up - if(tok2->str() == "(" || tok2->str() == "[") + if (tok2->str() == "(" || tok2->str() == "[") links.push(tok2); - if(tok2->str() == ")" || tok2->str() == "]") + if (tok2->str() == ")" || tok2->str() == "]") { Token * link = links.top(); @@ -1021,20 +1021,20 @@ void Tokenizer::simplifyTypedef() Token::createMutualLinks(tok2, tok3); } - if(arrayStart && arrayEnd) + if (arrayStart && arrayEnd) { tok2 = tok2->next(); Token * nextToken; std::stack links; - for(nextToken = arrayStart; nextToken != arrayEnd->next(); nextToken = nextToken->next()) + for (nextToken = arrayStart; nextToken != arrayEnd->next(); nextToken = nextToken->next()) { tok2->insertToken(nextToken->strAt(0)); tok2 = tok2->next(); // Check for links and fix them up - if(tok2->str() == "(" || tok2->str() == "[") + if (tok2->str() == "(" || tok2->str() == "[") links.push(tok2); - if(tok2->str() == ")" || tok2->str() == "]") + if (tok2->str() == ")" || tok2->str() == "]") { Token * link = links.top(); @@ -1051,36 +1051,36 @@ void Tokenizer::simplifyTypedef() } } - if(tok->str() == ";") + if (tok->str() == ";") done = true; - else if(tok->str() == ",") + else if (tok->str() == ",") { arrayStart = 0; arrayEnd = 0; offset = 1; - while(tok->tokAt(offset) && Token::Match(tok->tokAt(offset), "*|&")) + while (tok->tokAt(offset) && Token::Match(tok->tokAt(offset), "*|&")) pointers.push_back(tok->tokAt(offset++)->str()); - if(tok->tokAt(offset) && Token::Match(tok->tokAt(offset), "%type%")) + if (tok->tokAt(offset) && Token::Match(tok->tokAt(offset), "%type%")) { typeName = tok->tokAt(offset++); - if(tok->tokAt(offset) && tok->tokAt(offset)->str() == "[") + if (tok->tokAt(offset) && tok->tokAt(offset)->str() == "[") { arrayStart = tok->tokAt(offset); bool atEnd = false; - while(!atEnd) + while (!atEnd) { - while(tok->tokAt(offset + 1) && !Token::Match(tok->tokAt(offset + 1), ";|,")) + while (tok->tokAt(offset + 1) && !Token::Match(tok->tokAt(offset + 1), ";|,")) offset++; - if(!tok->tokAt(offset + 1)) + if (!tok->tokAt(offset + 1)) return; // invalid input - else if(tok->tokAt(offset + 1)->str() == ";") + else if (tok->tokAt(offset + 1)->str() == ";") atEnd = true; - else if(tok->tokAt(offset)->str() == "]") + else if (tok->tokAt(offset)->str() == "]") atEnd = true; else offset++; @@ -1089,7 +1089,7 @@ void Tokenizer::simplifyTypedef() arrayEnd = tok->tokAt(offset++); } - if(tok->tokAt(offset) && Token::Match(tok->tokAt(offset), ";|,")) + if (tok->tokAt(offset) && Token::Match(tok->tokAt(offset), ";|,")) tok = tok->tokAt(offset); else { @@ -1113,13 +1113,13 @@ void Tokenizer::simplifyTypedef() } } - if(ok) + if (ok) { // remove typedef but leave ; - while(typeDef->next() && typeDef->next() != tok) + while (typeDef->next() && typeDef->next() != tok) typeDef->deleteNext(); - if(typeDef != _tokens) + if (typeDef != _tokens) { tok = typeDef->previous(); tok->deleteNext(); @@ -1142,7 +1142,7 @@ bool Tokenizer::tokenize(std::istream &code, const char FileName[], const std::s createTokens(code); - if(!createLinks()) + if (!createLinks()) { // Source has syntax errors, can't proceed return false; @@ -1158,15 +1158,15 @@ bool Tokenizer::tokenize(std::istream &code, const char FileName[], const std::s simplifyIfAddBraces(); // Combine "- %num%" .. - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(Token::Match(tok, "[([+-*/=,] - %num%") && tok->strAt(2)[0] != '-') + if (Token::Match(tok, "[([+-*/=,] - %num%") && tok->strAt(2)[0] != '-') { tok->next()->str(std::string("-") + tok->strAt(2)); tok->next()->deleteNext(); } - if(Token::Match(tok, "return|case - %num%") && tok->strAt(2)[0] != '-') + if (Token::Match(tok, "return|case - %num%") && tok->strAt(2)[0] != '-') { tok->next()->str(std::string("-") + tok->strAt(2)); tok->next()->deleteNext(); @@ -1174,7 +1174,7 @@ bool Tokenizer::tokenize(std::istream &code, const char FileName[], const std::s } // Combine tokens.. - for(Token *tok = _tokens; tok && tok->next(); tok = tok->next()) + for (Token *tok = _tokens; tok && tok->next(); tok = tok->next()) { static const char * const combineWithNext[][3] = { @@ -1204,9 +1204,9 @@ bool Tokenizer::tokenize(std::istream &code, const char FileName[], const std::s { "__published", ":", "__published:" } }; - for(unsigned ui = 0; ui < sizeof(combineWithNext) / sizeof(combineWithNext[0]); ui++) + for (unsigned ui = 0; ui < sizeof(combineWithNext) / sizeof(combineWithNext[0]); ui++) { - if(tok->str() == combineWithNext[ui][0] && tok->next()->str() == combineWithNext[ui][1]) + if (tok->str() == combineWithNext[ui][0] && tok->next()->str() == combineWithNext[ui][1]) { tok->str(combineWithNext[ui][2]); tok->deleteNext(); @@ -1215,9 +1215,9 @@ bool Tokenizer::tokenize(std::istream &code, const char FileName[], const std::s } // Remove __declspec(dllexport) - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(Token::simpleMatch(tok, "__declspec ( dllexport )")) + if (Token::simpleMatch(tok, "__declspec ( dllexport )")) { Token::eraseTokens(tok, tok->tokAt(4)); tok->deleteThis(); @@ -1231,28 +1231,28 @@ bool Tokenizer::tokenize(std::istream &code, const char FileName[], const std::s simplifyEnum(); // Remove __asm.. - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(Token::Match(tok->next(), "__asm|_asm|asm {") && - tok->tokAt(2)->link() && - tok->tokAt(2)->link()->next()) + if (Token::Match(tok->next(), "__asm|_asm|asm {") && + tok->tokAt(2)->link() && + tok->tokAt(2)->link()->next()) { Token::eraseTokens(tok, tok->tokAt(2)->link()->next()); } - else if(Token::Match(tok->next(), "__asm__ __volatile__ (") && - tok->tokAt(3)->link() && - tok->tokAt(3)->link()->next()) + else if (Token::Match(tok->next(), "__asm__ __volatile__ (") && + tok->tokAt(3)->link() && + tok->tokAt(3)->link()->next()) { Token::eraseTokens(tok, tok->tokAt(3)->link()->next()); } - else if(Token::simpleMatch(tok->next(), "__asm")) + else if (Token::simpleMatch(tok->next(), "__asm")) { const Token *tok2 = tok->next(); - while(tok2 && (tok2->isNumber() || tok2->isName() || tok2->str() == ",")) + while (tok2 && (tok2->isNumber() || tok2->isName() || tok2->str() == ",")) tok2 = tok2->next(); - if(tok2 && tok2->str() == ";") + if (tok2 && tok2->str() == ";") Token::eraseTokens(tok, tok2); else continue; @@ -1270,13 +1270,13 @@ bool Tokenizer::tokenize(std::istream &code, const char FileName[], const std::s } // Remove "volatile" and "inline" - while(Token::Match(_tokens, "volatile|inline")) + while (Token::Match(_tokens, "volatile|inline")) { _tokens->deleteThis(); } - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - while(Token::Match(tok->next(), "volatile|inline")) + while (Token::Match(tok->next(), "volatile|inline")) { tok->deleteNext(); } @@ -1332,7 +1332,7 @@ bool Tokenizer::tokenize(std::istream &code, const char FileName[], const std::s //updateClassList(); setVarId(); - if(!validate()) + if (!validate()) return false; return true; @@ -1343,19 +1343,19 @@ bool Tokenizer::tokenize(std::istream &code, const char FileName[], const std::s void Tokenizer::arraySize() { - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(Token::Match(tok, "%var% [ ] = {")) + if (Token::Match(tok, "%var% [ ] = {")) { unsigned int sz = 1; const Token *tok2 = tok->tokAt(5); - while(Token::Match(tok2, "%any% ,")) + while (Token::Match(tok2, "%any% ,")) { sz++; tok2 = tok2->tokAt(2); } - if(Token::Match(tok2, "%any% } ;")) + if (Token::Match(tok2, "%any% } ;")) tok->next()->insertToken(MathLib::toString(sz)); } } @@ -1365,26 +1365,26 @@ void Tokenizer::arraySize() void Tokenizer::labels() { - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(Token::Match(tok, ") const| {")) + if (Token::Match(tok, ") const| {")) { // Simplify labels in the executable scope.. unsigned int indentlevel = 0; - while(0 != (tok = tok->next())) + while (0 != (tok = tok->next())) { // indentations.. - if(tok->str() == "{") + if (tok->str() == "{") ++indentlevel; - else if(tok->str() == "}") + else if (tok->str() == "}") { - if(indentlevel <= 1) + if (indentlevel <= 1) break; --indentlevel; } // simplify label.. - if(Token::Match(tok, "[;{}] %var% : %var%")) + if (Token::Match(tok, "[;{}] %var% : %var%")) tok->tokAt(2)->insertToken(";"); } } @@ -1400,27 +1400,27 @@ void Tokenizer::labels() */ static bool templateParameters(const Token *tok) { - if(!tok) + if (!tok) return false; - if(tok->str() != "<") + if (tok->str() != "<") return false; tok = tok->next(); - while(tok) + while (tok) { // num/type .. - if(!tok->isNumber() && !tok->isName()) + if (!tok->isNumber() && !tok->isName()) return false; tok = tok->next(); // optional "*" - if(tok->str() == "*") + if (tok->str() == "*") tok = tok->next(); // ,/> - if(tok->str() == ">") + if (tok->str() == ">") return true; - if(tok->str() != ",") + if (tok->str() != ",") break; tok = tok->next(); } @@ -1433,14 +1433,14 @@ static bool templateParameters(const Token *tok) */ static void removeTemplates(Token *tok) { - for(; tok; tok = tok->next()) + for (; tok; tok = tok->next()) { - if(! Token::simpleMatch(tok, "template <")) + if (! Token::simpleMatch(tok, "template <")) continue; - for(const Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) + for (const Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) { - if(tok2->str() == "{") + if (tok2->str() == "{") { tok2 = tok2->link(); tok2 = tok2 ? tok2->next() : 0; @@ -1448,13 +1448,13 @@ static void removeTemplates(Token *tok) tok->str(";"); break; } - if(tok2->str() == "(") + if (tok2->str() == "(") { tok2 = tok2->link(); - if(!tok2) + if (!tok2) break; } - if(tok2->str() == ";") + if (tok2->str() == ";") { Token::eraseTokens(tok, tok2->next()); tok->str(";"); @@ -1467,16 +1467,16 @@ static void removeTemplates(Token *tok) void Tokenizer::simplifyTemplates() { // Remove "typename" unless used in template arguments.. - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(tok->str() == "typename") + if (tok->str() == "typename") tok->deleteThis(); - if(Token::simpleMatch(tok, "template <")) + if (Token::simpleMatch(tok, "template <")) { - while(tok && tok->str() != ">") + while (tok && tok->str() != ">") tok = tok->next(); - if(!tok) + if (!tok) break; } } @@ -1484,23 +1484,23 @@ void Tokenizer::simplifyTemplates() std::set expandedtemplates; // Locate specialized templates.. - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(tok->str() != "template") + if (tok->str() != "template") continue; - if(!Token::simpleMatch(tok->next(), "< >")) + if (!Token::simpleMatch(tok->next(), "< >")) continue; // what kind of template is this? Token *tok2 = tok->tokAt(3); - while(tok2 && (tok2->isName() || tok2->str() == "*")) + while (tok2 && (tok2->isName() || tok2->str() == "*")) tok2 = tok2->next(); - if(!templateParameters(tok2)) + if (!templateParameters(tok2)) continue; // unknown template.. bail out - if(!tok2->previous()->isName()) + if (!tok2->previous()->isName()) continue; tok2 = tok2->previous(); @@ -1508,13 +1508,13 @@ void Tokenizer::simplifyTemplates() { std::ostringstream ostr; const Token *tok3 = tok2; - for(tok3 = tok2; tok3 && tok3->str() != ">"; tok3 = tok3->next()) + for (tok3 = tok2; tok3 && tok3->str() != ">"; tok3 = tok3->next()) { - if(tok3 != tok2) + if (tok3 != tok2) ostr << " "; ostr << tok3->str(); } - if(!Token::Match(tok3, "> (")) + if (!Token::Match(tok3, "> (")) continue; s = ostr.str(); } @@ -1523,7 +1523,7 @@ void Tokenizer::simplifyTemplates() const std::string pattern(s + " > ("); // remove spaces to create new name - while(s.find(" ") != std::string::npos) + while (s.find(" ") != std::string::npos) s.erase(s.find(" "), 1); const std::string name(s + ">"); expandedtemplates.insert(name); @@ -1538,7 +1538,7 @@ void Tokenizer::simplifyTemplates() tok->deleteThis(); // Use this special template in the code.. - while(0 != (tok2 = const_cast(Token::findmatch(tok2, pattern.c_str())))) + while (0 != (tok2 = const_cast(Token::findmatch(tok2, pattern.c_str())))) { Token::eraseTokens(tok2, Token::findmatch(tok2, "(")); tok2->str(name); @@ -1547,18 +1547,18 @@ void Tokenizer::simplifyTemplates() // Locate templates.. std::list templates; - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(Token::simpleMatch(tok, "template <")) + if (Token::simpleMatch(tok, "template <")) { - for(const Token *tok2 = tok; tok2; tok2 = tok2->next()) + for (const Token *tok2 = tok; tok2; tok2 = tok2->next()) { // Just a declaration => ignore this - if(tok2->str() == ";") + if (tok2->str() == ";") break; // Implementation => add to "templates" - if(tok2->str() == "{") + if (tok2->str() == "{") { templates.push_back(tok); break; @@ -1566,7 +1566,7 @@ void Tokenizer::simplifyTemplates() } } } - if(templates.empty()) + if (templates.empty()) { removeTemplates(_tokens); return; @@ -1574,37 +1574,37 @@ void Tokenizer::simplifyTemplates() // Locate possible instantiations of templates.. std::list used; - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { // template definition.. skip it - if(Token::simpleMatch(tok, "template <")) + if (Token::simpleMatch(tok, "template <")) { - for(; tok; tok = tok->next()) + for (; tok; tok = tok->next()) { - if(tok->str() == "{" || tok->str() == "(") + if (tok->str() == "{" || tok->str() == "(") { tok = tok->link(); - if(!tok) + if (!tok) break; - if(tok->str() == "}") + if (tok->str() == "}") break; } - else if(tok->str() == ";") + else if (tok->str() == ";") { break; } } - if(!tok) + if (!tok) break; } - else if(Token::Match(tok->previous(), "[{};=] %var% <") || - Token::Match(tok->tokAt(-2), "[,:] private|protected|public %var% <")) + else if (Token::Match(tok->previous(), "[{};=] %var% <") || + Token::Match(tok->tokAt(-2), "[,:] private|protected|public %var% <")) { - if(templateParameters(tok->next())) + if (templateParameters(tok->next())) used.push_back(tok); } } - if(used.empty()) + if (used.empty()) { removeTemplates(_tokens); return; @@ -1614,56 +1614,56 @@ void Tokenizer::simplifyTemplates() // Template arguments with default values - for(std::list::iterator iter1 = templates.begin(); iter1 != templates.end(); ++iter1) + for (std::list::iterator iter1 = templates.begin(); iter1 != templates.end(); ++iter1) { std::list eq; unsigned int templatepar = 1; std::string classname; - for(Token *tok = *iter1; tok; tok = tok->next()) + for (Token *tok = *iter1; tok; tok = tok->next()) { - if(tok->str() == ">") + if (tok->str() == ">") { - if(Token::Match(tok, "> class %var%")) + if (Token::Match(tok, "> class %var%")) classname = tok->strAt(2); break; } - if(tok->str() == ",") + if (tok->str() == ",") ++templatepar; - else if(tok->str() == "=") + else if (tok->str() == "=") eq.push_back(tok); } - if(eq.empty() || classname.empty()) + if (eq.empty() || classname.empty()) continue; - for(std::list::iterator iter2 = used.begin(); iter2 != used.end(); ++iter2) + for (std::list::iterator iter2 = used.begin(); iter2 != used.end(); ++iter2) { Token *tok = *iter2; - if(!Token::Match(tok, (classname + " < %any%").c_str())) + if (!Token::Match(tok, (classname + " < %any%").c_str())) continue; // count the parameters.. unsigned int usedpar = 1; - for(tok = tok->tokAt(3); tok; tok = tok->tokAt(2)) + for (tok = tok->tokAt(3); tok; tok = tok->tokAt(2)) { - if(tok->str() == ">") + if (tok->str() == ">") break; - if(tok->str() == ",") + if (tok->str() == ",") ++usedpar; else break; } - if(tok && tok->str() == ">") + if (tok && tok->str() == ">") { tok = tok->previous(); std::list::const_iterator it = eq.begin(); - for(unsigned int i = (templatepar - eq.size()); it != eq.end() && i < usedpar; ++i) + for (unsigned int i = (templatepar - eq.size()); it != eq.end() && i < usedpar; ++i) ++it; - while(it != eq.end()) + while (it != eq.end()) { tok->insertToken(","); tok = tok->next(); @@ -1674,7 +1674,7 @@ void Tokenizer::simplifyTemplates() } } - for(std::list::iterator it = eq.begin(); it != eq.end(); ++it) + for (std::list::iterator it = eq.begin(); it != eq.end(); ++it) { (*it)->deleteThis(); (*it)->deleteThis(); @@ -1687,32 +1687,32 @@ void Tokenizer::simplifyTemplates() //while (!done) { done = true; - for(std::list::iterator iter1 = templates.begin(); iter1 != templates.end(); ++iter1) + for (std::list::iterator iter1 = templates.begin(); iter1 != templates.end(); ++iter1) { Token *tok = *iter1; std::vector type; - for(tok = tok->tokAt(2); tok && tok->str() != ">"; tok = tok->next()) + for (tok = tok->tokAt(2); tok && tok->str() != ">"; tok = tok->next()) { - if(Token::Match(tok, "%var% ,|>")) + if (Token::Match(tok, "%var% ,|>")) type.push_back(tok); } // bail out if the end of the file was reached - if(!tok) + if (!tok) break; // get the position of the template name unsigned int namepos = 0; - if(Token::Match(tok, "> class %type% {|:")) + if (Token::Match(tok, "> class %type% {|:")) namepos = 2; - else if(Token::Match(tok, "> %type% *|&| %type% (")) + else if (Token::Match(tok, "> %type% *|&| %type% (")) namepos = 2; - else if(Token::Match(tok, "> %type% %type% *|&| %type% (")) + else if (Token::Match(tok, "> %type% %type% *|&| %type% (")) namepos = 3; else { #ifndef NDEBUG // debug message that we bail out.. - if(_settings && _settings->_debug) + if (_settings && _settings->_debug) { std::cout << "simplifyTemplates debug-information: bailing out: " << file(tok->tokAt(namepos)) @@ -1725,7 +1725,7 @@ void Tokenizer::simplifyTemplates() #endif continue; } - if((tok->tokAt(namepos)->str() == "*" || tok->tokAt(namepos)->str() == "&")) + if ((tok->tokAt(namepos)->str() == "*" || tok->tokAt(namepos)->str() == "&")) ++namepos; // name of template function/class.. @@ -1736,9 +1736,9 @@ void Tokenizer::simplifyTemplates() // locate template usage.. std::string s(name + " <"); - for(unsigned int i = 0; i < type.size(); ++i) + for (unsigned int i = 0; i < type.size(); ++i) { - if(i > 0) + if (i > 0) s += ","; s += " %any% "; } @@ -1747,15 +1747,15 @@ void Tokenizer::simplifyTemplates() std::string::size_type sz1 = used.size(); unsigned int recursiveCount = 0; - for(std::list::iterator iter2 = used.begin(); iter2 != used.end(); ++iter2) + for (std::list::iterator iter2 = used.begin(); iter2 != used.end(); ++iter2) { // If the size of "used" has changed, simplify calculations - if(sz1 != used.size()) + if (sz1 != used.size()) { sz1 = used.size(); simplifyCalculations(); recursiveCount++; - if(recursiveCount > 100) + if (recursiveCount > 100) { // bail out.. break; @@ -1764,41 +1764,41 @@ void Tokenizer::simplifyTemplates() Token * const tok2 = *iter2; - if(tok2->str() != name) + if (tok2->str() != name) continue; - if(Token::Match(tok2->previous(), "[;{}=]") && - !Token::Match(tok2, (pattern + (isfunc ? "(" : "*| %var%")).c_str())) + if (Token::Match(tok2->previous(), "[;{}=]") && + !Token::Match(tok2, (pattern + (isfunc ? "(" : "*| %var%")).c_str())) continue; // New type.. std::vector types2; s = ""; std::string s1(name + " < "); - for(const Token *tok3 = tok2->tokAt(2); tok3 && tok3->str() != ">"; tok3 = tok3->next()) + for (const Token *tok3 = tok2->tokAt(2); tok3 && tok3->str() != ">"; tok3 = tok3->next()) { - if(!tok3->next()) + if (!tok3->next()) { s.clear(); break; } s1 += tok3->str(); s1 += " "; - if(tok3->str() != ",") + if (tok3->str() != ",") types2.push_back(*tok3); // add additional type information - if(tok3->isUnsigned()) + if (tok3->isUnsigned()) s += "unsigned"; - else if(tok3->isSigned()) + else if (tok3->isSigned()) s += "signed"; - if(tok3->isLong()) + if (tok3->isLong()) s += "long"; s += tok3->str(); } s1 += ">"; const std::string type2(s); - if(type2.empty() || type.size() != types2.size()) + if (type2.empty() || type.size() != types2.size()) { #ifndef NDEBUG std::list locationList; @@ -1814,7 +1814,7 @@ void Tokenizer::simplifyTemplates() _errorLogger->reportErr(errmsg); #endif - if(type2.empty()) + if (type2.empty()) continue; break; } @@ -1822,34 +1822,34 @@ void Tokenizer::simplifyTemplates() // New classname/funcname.. const std::string name2(name + "<" + type2 + ">"); - if(expandedtemplates.find(name2) == expandedtemplates.end()) + if (expandedtemplates.find(name2) == expandedtemplates.end()) { expandedtemplates.insert(name2); // Copy template.. int _indentlevel = 0; int _parlevel = 0; - for(const Token *tok3 = _tokens; tok3; tok3 = tok3->next()) + for (const Token *tok3 = _tokens; tok3; tok3 = tok3->next()) { - if(tok3->str() == "{") + if (tok3->str() == "{") ++_indentlevel; - else if(tok3->str() == "}") + else if (tok3->str() == "}") --_indentlevel; - else if(tok3->str() == "(") + else if (tok3->str() == "(") ++_parlevel; - else if(tok3->str() == ")") + else if (tok3->str() == ")") --_parlevel; // Start of template.. - if(tok3 == tok) + if (tok3 == tok) { tok3 = tok3->next(); } // member function implemented outside class definition - else if(_indentlevel == 0 && _parlevel == 0 && Token::Match(tok3, (pattern + " :: %var% (").c_str())) + else if (_indentlevel == 0 && _parlevel == 0 && Token::Match(tok3, (pattern + " :: %var% (").c_str())) { addtoken(name2.c_str(), tok3->linenr(), tok3->fileIndex()); - while(tok3->str() != "::") + while (tok3->str() != "::") tok3 = tok3->next(); } @@ -1862,14 +1862,14 @@ void Tokenizer::simplifyTemplates() std::stack brackets; // holds "(" tokens std::stack brackets2; // holds "[" tokens - for(; tok3; tok3 = tok3->next()) + for (; tok3; tok3 = tok3->next()) { - if(tok3->str() == "{") + if (tok3->str() == "{") ++indentlevel; - else if(tok3->str() == "}") + else if (tok3->str() == "}") { - if(indentlevel <= 1 && brackets.empty() && brackets2.empty()) + if (indentlevel <= 1 && brackets.empty() && brackets2.empty()) { // there is a bug if indentlevel is 0 // the "}" token should only be added if indentlevel is 1 but I add it always intentionally @@ -1884,15 +1884,15 @@ void Tokenizer::simplifyTemplates() } - if(tok3->isName()) + if (tok3->isName()) { // search for this token in the type vector unsigned int itype = 0; - while(itype < type.size() && type[itype]->str() != tok3->str()) + while (itype < type.size() && type[itype]->str() != tok3->str()) ++itype; // replace type with given type.. - if(itype < type.size()) + if (itype < type.size()) { addtoken(&types2[itype], tok3->linenr(), tok3->fileIndex()); continue; @@ -1900,7 +1900,7 @@ void Tokenizer::simplifyTemplates() } // replace name.. - if(Token::Match(tok3, (name + " !!<").c_str())) + if (Token::Match(tok3, (name + " !!<").c_str())) { addtoken(name2.c_str(), tok3->linenr(), tok3->fileIndex()); continue; @@ -1908,39 +1908,39 @@ void Tokenizer::simplifyTemplates() // copy addtoken(tok3, tok3->linenr(), tok3->fileIndex()); - if(Token::Match(tok3, "%type% <")) + if (Token::Match(tok3, "%type% <")) { - if(!Token::Match(tok3, (name + " <").c_str())) + if (!Token::Match(tok3, (name + " <").c_str())) done = false; used.push_back(_tokensBack); } // link() newly tokens manually - if(tok3->str() == "{") + if (tok3->str() == "{") { braces.push(_tokensBack); } - else if(tok3->str() == "}") + else if (tok3->str() == "}") { assert(braces.empty() == false); Token::createMutualLinks(braces.top(), _tokensBack); braces.pop(); } - else if(tok3->str() == "(") + else if (tok3->str() == "(") { brackets.push(_tokensBack); } - else if(tok3->str() == "[") + else if (tok3->str() == "[") { brackets2.push(_tokensBack); } - else if(tok3->str() == ")") + else if (tok3->str() == ")") { assert(brackets.empty() == false); Token::createMutualLinks(brackets.top(), _tokensBack); brackets.pop(); } - else if(tok3->str() == "]") + else if (tok3->str() == "]") { assert(brackets2.empty() == false); Token::createMutualLinks(brackets2.top(), _tokensBack); @@ -1955,20 +1955,20 @@ void Tokenizer::simplifyTemplates() } // Replace all these template usages.. - for(Token *tok4 = tok2; tok4; tok4 = tok4->next()) + for (Token *tok4 = tok2; tok4; tok4 = tok4->next()) { - if(Token::simpleMatch(tok4, s1.c_str())) + if (Token::simpleMatch(tok4, s1.c_str())) { bool match = true; Token * tok5 = tok4->tokAt(2); unsigned int count = 0; - while(tok5->str() != ">") + while (tok5->str() != ">") { - if(tok5->str() != ",") + if (tok5->str() != ",") { - if(tok5->isUnsigned() != types2[count].isUnsigned() || - tok5->isSigned() != types2[count].isSigned() || - tok5->isLong() != types2[count].isLong()) + if (tok5->isUnsigned() != types2[count].isUnsigned() || + tok5->isSigned() != types2[count].isSigned() || + tok5->isLong() != types2[count].isLong()) { match = false; break; @@ -1978,10 +1978,10 @@ void Tokenizer::simplifyTemplates() tok5 = tok5->next(); } - if(match) + if (match) { tok4->str(name2); - while(tok4->next()->str() != ">") + while (tok4->next()->str() != ">") { used.remove(tok4->next()); tok4->deleteNext(); @@ -2001,21 +2001,21 @@ void Tokenizer::simplifyTemplates() void Tokenizer::simplifyTemplates2() { - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(tok->str() == "(") + if (tok->str() == "(") tok = tok->link(); - else if(Token::Match(tok, "; %type% <")) + else if (Token::Match(tok, "; %type% <")) { const Token *tok2 = tok->tokAt(3); std::string type; - while(Token::Match(tok2, "%type% ,") || Token::Match(tok2, "%num% ,")) + while (Token::Match(tok2, "%type% ,") || Token::Match(tok2, "%num% ,")) { type += tok2->str() + ","; tok2 = tok2->tokAt(2); } - if(Token::Match(tok2, "%type% > (") || Token::Match(tok2, "%num% > (")) + if (Token::Match(tok2, "%type% > (") || Token::Match(tok2, "%num% > (")) { type += tok2->str(); tok = tok->next(); @@ -2029,16 +2029,16 @@ void Tokenizer::simplifyTemplates2() std::string Tokenizer::getNameForFunctionParams(const Token *start) { - if(start->next() == start->link()) + if (start->next() == start->link()) return ""; std::string result; bool findNextComma = false; - for(const Token *tok = start->next(); tok && tok != start->link(); tok = tok->next()) + for (const Token *tok = start->next(); tok && tok != start->link(); tok = tok->next()) { - if(findNextComma) + if (findNextComma) { - if(tok->str() == ",") + if (tok->str() == ",") findNextComma = false; continue; @@ -2061,9 +2061,9 @@ void Tokenizer::updateClassList() // Locate implementation tok1 = tokens(); std::map > > implementations; - while((tok1 = Token::findmatch(tok1, "%var% :: ~| %var% (")) != 0) + while ((tok1 = Token::findmatch(tok1, "%var% :: ~| %var% (")) != 0) { - if(tok1->tokAt(2)->str() == "~") + if (tok1->tokAt(2)->str() == "~") implementations[tok1->str()]["~ "+tok1->tokAt(3)->str()][getNameForFunctionParams(tok1->tokAt(4))] = tok1; else implementations[tok1->str()][tok1->tokAt(2)->str()][getNameForFunctionParams(tok1->tokAt(3))] = tok1; @@ -2072,7 +2072,7 @@ void Tokenizer::updateClassList() } tok1 = tokens(); - while((tok1 = Token::findmatch(tok1, "%var% :: operator %any% (")) != 0) + while ((tok1 = Token::findmatch(tok1, "%var% :: operator %any% (")) != 0) { implementations[tok1->str()][tok1->tokAt(2)->str()+" "+tok1->tokAt(3)->str()][getNameForFunctionParams(tok1->tokAt(4))] = tok1; //std::cout <<"3."<< tok1->str() << "," << tok1->tokAt(2)->str()+" "+tok1->tokAt(3)->str() << ","<tokAt(4)); @@ -2080,53 +2080,53 @@ void Tokenizer::updateClassList() } tok1 = tokens(); - while((tok1 = Token::findmatch(tok1, "class|struct %var% [{:]")) != 0) + while ((tok1 = Token::findmatch(tok1, "class|struct %var% [{:]")) != 0) { ClassInfo::MemberType memberType = ClassInfo::PRIVATE; - if(tok1->str() == "struct") + if (tok1->str() == "struct") memberType = ClassInfo::PUBLIC; const std::string className = tok1->strAt(1); tok1 = tok1->next(); int indentlevel = 0; - for(const Token *tok = tok1; tok; tok = tok->next()) + for (const Token *tok = tok1; tok; tok = tok->next()) { // Indentation - if(tok->str() == "{") + if (tok->str() == "{") { ++indentlevel; continue; } - else if(tok->str() == "}") + else if (tok->str() == "}") { --indentlevel; - if(indentlevel <= 0) + if (indentlevel <= 0) break; continue; } // Parse class contents (indentlevel == 1).. - if(indentlevel == 1) + if (indentlevel == 1) { - if(tok->str() == "private:") + if (tok->str() == "private:") memberType = ClassInfo::PRIVATE; - else if(tok->str() == "protected:") + else if (tok->str() == "protected:") memberType = ClassInfo::PROTECTED; - else if(tok->str() == "public:") + else if (tok->str() == "public:") memberType = ClassInfo::PUBLIC; - else if(Token::Match(tok, "typedef %type% (")) + else if (Token::Match(tok, "typedef %type% (")) tok = tok->tokAt(2); - else if(Token::Match(tok, "[:,] %var% (")) + else if (Token::Match(tok, "[:,] %var% (")) tok = tok->tokAt(2); - else if(Token::Match(tok, "%var% (")) + else if (Token::Match(tok, "%var% (")) { ClassInfo::MemberFunctionInfo func; - if(tok->previous()->str() == "~") + if (tok->previous()->str() == "~") { // destructor func._declaration = tok->previous(); @@ -2140,20 +2140,20 @@ void Tokenizer::updateClassList() } func._type = memberType; - if(tok->next()->link()->next()->str() == "{") + if (tok->next()->link()->next()->str() == "{") func._implementation = tok; else func._implementation = implementations[className][func._name][getNameForFunctionParams(tok->next())]; //std::cout <<"\n2."<< className << "," << func._name << ","<next())<<"\n"; _classInfoList[className]._memberFunctions.push_back(func); } - else if(Token::Match(tok, "operator %any% (")) + else if (Token::Match(tok, "operator %any% (")) { ClassInfo::MemberFunctionInfo func; func._declaration = tok; func._name = tok->str() + " " + tok->next()->str(); func._type = memberType; - if(tok->tokAt(2)->link()->next()->str() == "{") + if (tok->tokAt(2)->link()->next()->str() == "{") func._implementation = tok; else func._implementation = implementations[className][func._name][getNameForFunctionParams(tok->tokAt(2))]; @@ -2170,39 +2170,39 @@ void Tokenizer::updateClassList() void Tokenizer::setVarId() { // Clear all variable ids - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) tok->varId(0); // Set variable ids.. unsigned int _varId = 0; - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(tok != _tokens && !Token::Match(tok, "[,;{}(] %type%")) + if (tok != _tokens && !Token::Match(tok, "[,;{}(] %type%")) continue; - if(Token::Match(tok, "[,;{}(] %type%")) + if (Token::Match(tok, "[,;{}(] %type%")) tok = tok->next(); - if(tok->str() == "new") + if (tok->str() == "new") continue; - if(tok->str() == "unsigned") + if (tok->str() == "unsigned") tok = tok->next(); - if(Token::Match(tok, "class|struct %type% :|{|;")) + if (Token::Match(tok, "class|struct %type% :|{|;")) continue; - if(Token::Match(tok, "else|return|typedef|delete|sizeof")) + if (Token::Match(tok, "else|return|typedef|delete|sizeof")) continue; - if(Token::Match(tok, "const|static|extern|public:|private:|protected:")) + if (Token::Match(tok, "const|static|extern|public:|private:|protected:")) tok = tok->next(); - while(Token::Match(tok, "%var% ::")) + while (Token::Match(tok, "%var% ::")) tok = tok->tokAt(2); // Skip template arguments.. - if(Token::Match(tok, "%type% <")) + if (Token::Match(tok, "%type% <")) { int level = 1; bool again; @@ -2212,38 +2212,38 @@ void Tokenizer::setVarId() { again = false; - while(Token::Match(tok2, "%var% ::")) + while (Token::Match(tok2, "%var% ::")) tok2 = tok2->tokAt(2); - if(Token::Match(tok2, "%type% <")) + if (Token::Match(tok2, "%type% <")) { level++; tok2 = tok2->tokAt(2); again = true; } - else if(Token::Match(tok2, "%type% ,")) + else if (Token::Match(tok2, "%type% ,")) { tok2 = tok2->tokAt(2); again = true; } else { - while(tok2 && (tok2->isName() || tok2->isNumber() || tok2->str() == "*" || tok2->str() == ",")) + while (tok2 && (tok2->isName() || tok2->isNumber() || tok2->str() == "*" || tok2->str() == ",")) tok2 = tok2->next(); } } - while(again); + while (again); do // Look for end of templates { again = false; - if(level == 1 && Token::Match(tok2, "> %var%")) + if (level == 1 && Token::Match(tok2, "> %var%")) tok = tok2; - else if(level > 1 && tok2->str() == ">") + else if (level > 1 && tok2->str() == ">") { level--; - if(level == 0) + if (level == 0) tok = tok2; else { @@ -2251,45 +2251,45 @@ void Tokenizer::setVarId() again = true; } } - else if(level == 1 && Token::Match(tok2, "> ::|*|& %var%")) + else if (level == 1 && Token::Match(tok2, "> ::|*|& %var%")) tok = tok2->next(); else continue; // Not code that I understand / not a variable declaration } - while(again); + while (again); } // Determine name of declared variable.. std::string varname; Token *tok2 = tok->tokAt(1); - while(tok2) + while (tok2) { - if(tok2->isName()) + if (tok2->isName()) varname = tok2->str(); - else if(tok2->str() != "*" && tok2->str() != "&") + else if (tok2->str() != "*" && tok2->str() != "&") break; tok2 = tok2->next(); } // End of tokens reached.. - if(!tok2) + if (!tok2) break; - if(varname == "operator" && Token::Match(tok2, "=|+|-|*|/|[| ]| (")) + if (varname == "operator" && Token::Match(tok2, "=|+|-|*|/|[| ]| (")) continue; // Is it a function? - if(tok2->str() == "(") + if (tok2->str() == "(") { // Search for function declaration, e.g. void f(); - if(Token::simpleMatch(tok2->next(), ") ;")) + if (Token::simpleMatch(tok2->next(), ") ;")) continue; // Search for function declaration, e.g. void f( int c ); - if(Token::Match(tok2->next(), "%num%") || - Token::Match(tok2->next(), "%bool%") || - tok2->next()->str()[0] == '"' || - tok2->next()->varId() != 0) + if (Token::Match(tok2->next(), "%num%") || + Token::Match(tok2->next(), "%bool%") || + tok2->next()->str()[0] == '"' || + tok2->next()->varId() != 0) { // This is not a function } @@ -2300,40 +2300,40 @@ void Tokenizer::setVarId() } // Variable declaration found => Set variable ids - if(Token::Match(tok2, "[,();[=]") && !varname.empty()) + if (Token::Match(tok2, "[,();[=]") && !varname.empty()) { ++_varId; int indentlevel = 0; int parlevel = 0; bool dot = false; bool funcDeclaration = false; - for(tok2 = tok->next(); tok2; tok2 = tok2->next()) + for (tok2 = tok->next(); tok2; tok2 = tok2->next()) { - if(!dot && tok2->str() == varname && !Token::Match(tok2->previous(), "struct|union")) + if (!dot && tok2->str() == varname && !Token::Match(tok2->previous(), "struct|union")) tok2->varId(_varId); - else if(tok2->str() == "{") + else if (tok2->str() == "{") ++indentlevel; - else if(tok2->str() == "}") + else if (tok2->str() == "}") { --indentlevel; - if(indentlevel < 0) + if (indentlevel < 0) break; // We have reached the end of a loop: "for( int i;;) { }" - if(funcDeclaration && indentlevel <= 0) + if (funcDeclaration && indentlevel <= 0) break; } - else if(tok2->str() == "(") + else if (tok2->str() == "(") ++parlevel; - else if(tok2->str() == ")") + else if (tok2->str() == ")") { // Is this a function parameter or a variable declared in for example a for loop? - if(parlevel == 0 && indentlevel == 0 && Token::Match(tok2, ") const| {")) + if (parlevel == 0 && indentlevel == 0 && Token::Match(tok2, ") const| {")) funcDeclaration = true; else --parlevel; } - else if(parlevel < 0 && tok2->str() == ";") + else if (parlevel < 0 && tok2->str() == ";") break; dot = bool(tok2->str() == "."); } @@ -2341,20 +2341,20 @@ void Tokenizer::setVarId() } // Struct/Class members - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { // str.clear is a variable // str.clear() is a member function - if(tok->varId() != 0 && - Token::Match(tok->next(), ". %var% !!(") && - tok->tokAt(2)->varId() == 0) + if (tok->varId() != 0 && + Token::Match(tok->next(), ". %var% !!(") && + tok->tokAt(2)->varId() == 0) { ++_varId; const std::string pattern(std::string("%varid% . ") + tok->strAt(2)); - for(Token *tok2 = tok; tok2; tok2 = tok2->next()) + for (Token *tok2 = tok; tok2; tok2 = tok2->next()) { - if(Token::Match(tok2, pattern.c_str(), tok->varId())) + if (Token::Match(tok2, pattern.c_str(), tok->varId())) tok2->tokAt(2)->varId(_varId); } } @@ -2364,22 +2364,22 @@ void Tokenizer::setVarId() std::list allMemberFunctions; std::list allMemberVars; { - for(Token *tok2 = _tokens; tok2; tok2 = tok2->next()) + for (Token *tok2 = _tokens; tok2; tok2 = tok2->next()) { - if(Token::Match(tok2, "%var% :: %var%")) + if (Token::Match(tok2, "%var% :: %var%")) { - if(Token::simpleMatch(tok2->tokAt(3), "(")) + if (Token::simpleMatch(tok2->tokAt(3), "(")) allMemberFunctions.push_back(tok2); - else if(tok2->tokAt(2)->varId() != 0) + else if (tok2->tokAt(2)->varId() != 0) allMemberVars.push_back(tok2); } } } // class members.. - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(Token::Match(tok, "class %var% {")) + if (Token::Match(tok, "class %var% {")) { const std::string &classname(tok->next()->str()); @@ -2388,32 +2388,32 @@ void Tokenizer::setVarId() std::map varlist; { unsigned int indentlevel = 0; - for(const Token *tok2 = tok; tok2; tok2 = tok2->next()) + for (const Token *tok2 = tok; tok2; tok2 = tok2->next()) { // Indentation.. - if(tok2->str() == "{") + if (tok2->str() == "{") ++indentlevel; - else if(tok2->str() == "}") + else if (tok2->str() == "}") { - if(indentlevel <= 1) + if (indentlevel <= 1) break; --indentlevel; } // Found a member variable.. - else if(indentlevel == 1 && tok2->varId() > 0) + else if (indentlevel == 1 && tok2->varId() > 0) varlist[tok2->str()] = tok2->varId(); } } // Are there any member variables in this class? - if(varlist.empty()) + if (varlist.empty()) continue; // Member variables - for(std::list::iterator func = allMemberVars.begin(); func != allMemberVars.end(); ++func) + for (std::list::iterator func = allMemberVars.begin(); func != allMemberVars.end(); ++func) { - if(!Token::simpleMatch(*func, classname.c_str())) + if (!Token::simpleMatch(*func, classname.c_str())) continue; Token *tok2 = *func; @@ -2425,20 +2425,20 @@ void Tokenizer::setVarId() std::list funclist; { const std::string funcpattern(classname + " :: %var% ("); - for(std::list::iterator func = allMemberFunctions.begin(); func != allMemberFunctions.end(); ++func) + for (std::list::iterator func = allMemberFunctions.begin(); func != allMemberFunctions.end(); ++func) { Token *tok2 = *func; // Found a class function.. - if(Token::Match(tok2, funcpattern.c_str())) + if (Token::Match(tok2, funcpattern.c_str())) { // Goto the end paranthesis.. tok2 = tok2->tokAt(3)->link(); - if(!tok2) + if (!tok2) break; // If this is a function implementation.. add it to funclist - if(Token::Match(tok2, ") const|volatile| {")) + if (Token::Match(tok2, ") const|volatile| {")) funclist.push_back(tok2); } } @@ -2446,22 +2446,22 @@ void Tokenizer::setVarId() // Update the variable ids.. // Parse each function.. - for(std::list::iterator func = funclist.begin(); func != funclist.end(); ++func) + for (std::list::iterator func = funclist.begin(); func != funclist.end(); ++func) { unsigned int indentlevel = 0; - for(Token *tok2 = *func; tok2; tok2 = tok2->next()) + for (Token *tok2 = *func; tok2; tok2 = tok2->next()) { - if(tok2->str() == "{") + if (tok2->str() == "{") ++indentlevel; - else if(tok2->str() == "}") + else if (tok2->str() == "}") { - if(indentlevel <= 1) + if (indentlevel <= 1) break; --indentlevel; } - else if(indentlevel > 0 && - tok2->varId() == 0 && - varlist.find(tok2->str()) != varlist.end()) + else if (indentlevel > 0 && + tok2->varId() == 0 && + varlist.find(tok2->str()) != varlist.end()) { tok2->varId(varlist[tok2->str()]); } @@ -2479,25 +2479,25 @@ void Tokenizer::setVarId() void Tokenizer::simplifyNamespaces() { - for(Token *token = _tokens; token; token = token->next()) + for (Token *token = _tokens; token; token = token->next()) { - while(token && token->str() == "namespace" && token->varId() == 0 && - (!token->previous() || token->previous()->str() != "using")) + while (token && token->str() == "namespace" && token->varId() == 0 && + (!token->previous() || token->previous()->str() != "using")) { // Token is namespace and there is no "using" before it. Token *start = token; Token *tok = token->tokAt(2); - if(!tok) + if (!tok) return; tok = tok->link(); - if(tok && tok->str() == "}") + if (tok && tok->str() == "}") { tok = tok->previous(); tok->deleteNext(); start->deleteNext(); start->deleteNext(); - if(start->previous()) + if (start->previous()) { token = start->next(); start = start->previous(); @@ -2516,7 +2516,7 @@ void Tokenizer::simplifyNamespaces() } } - if(!token) + if (!token) break; } } @@ -2527,27 +2527,27 @@ bool Tokenizer::createLinks() std::list links; std::list links2; std::list links3; - for(Token *token = _tokens; token; token = token->next()) + for (Token *token = _tokens; token; token = token->next()) { - if(token->link()) + if (token->link()) { token->link(0); } - if(token->str() == "{") + if (token->str() == "{") { links.push_back(token); type.push_back(token); } - else if(token->str() == "}") + else if (token->str() == "}") { - if(links.empty()) + if (links.empty()) { // Error, { and } don't match. syntaxError(token, '{'); return false; } - if(type.back()->str() != "{") + if (type.back()->str() != "{") { syntaxError(type.back(), type.back()->str()[0]); return false; @@ -2557,20 +2557,20 @@ bool Tokenizer::createLinks() Token::createMutualLinks(links.back(), token); links.pop_back(); } - else if(token->str() == "(") + else if (token->str() == "(") { links2.push_back(token); type.push_back(token); } - else if(token->str() == ")") + else if (token->str() == ")") { - if(links2.empty()) + if (links2.empty()) { // Error, ( and ) don't match. syntaxError(token, '('); return false; } - if(type.back()->str() != "(") + if (type.back()->str() != "(") { syntaxError(type.back(), type.back()->str()[0]); return false; @@ -2580,20 +2580,20 @@ bool Tokenizer::createLinks() Token::createMutualLinks(links2.back(), token); links2.pop_back(); } - else if(token->str() == "[") + else if (token->str() == "[") { links3.push_back(token); type.push_back(token); } - else if(token->str() == "]") + else if (token->str() == "]") { - if(links3.empty()) + if (links3.empty()) { // Error, [ and ] don't match. syntaxError(token, '['); return false; } - if(type.back()->str() != "[") + if (type.back()->str() != "[") { syntaxError(type.back(), type.back()->str()[0]); return false; @@ -2605,21 +2605,21 @@ bool Tokenizer::createLinks() } } - if(!links.empty()) + if (!links.empty()) { // Error, { and } don't match. syntaxError(links.back(), '{'); return false; } - if(!links2.empty()) + if (!links2.empty()) { // Error, ( and ) don't match. syntaxError(links2.back(), '('); return false; } - if(!links3.empty()) + if (!links3.empty()) { // Error, [ and ] don't match. syntaxError(links3.back(), '['); @@ -2642,9 +2642,9 @@ void Tokenizer::simplifySizeof() _typeSize["size_t"] = sizeof(size_t); _typeSize["*"] = sizeof(void *); - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(Token::Match(tok, "class|struct %var%")) + if (Token::Match(tok, "class|struct %var%")) { _typeSize[tok->strAt(1)] = 100; } @@ -2652,18 +2652,18 @@ void Tokenizer::simplifySizeof() // Locate variable declarations and calculate the size std::map sizeOfVar; - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(tok->varId() != 0 && sizeOfVar.find(tok->varId()) == sizeOfVar.end()) + if (tok->varId() != 0 && sizeOfVar.find(tok->varId()) == sizeOfVar.end()) { const unsigned int varId = tok->varId(); - if(Token::Match(tok->tokAt(-3), "[;{}(,] %type% * %var% [;,)]") || - Token::Match(tok->tokAt(-4), "[;{}(,] const %type% * %var% [;),]") || - Token::Match(tok->tokAt(-2), "[;{}(,] %type% %var% [;),]") || - Token::Match(tok->tokAt(-3), "[;{}(,] const %type% %var% [;),]")) + if (Token::Match(tok->tokAt(-3), "[;{}(,] %type% * %var% [;,)]") || + Token::Match(tok->tokAt(-4), "[;{}(,] const %type% * %var% [;),]") || + Token::Match(tok->tokAt(-2), "[;{}(,] %type% %var% [;),]") || + Token::Match(tok->tokAt(-3), "[;{}(,] const %type% %var% [;),]")) { const unsigned int size = sizeOfType(tok->previous()); - if(size == 0) + if (size == 0) { continue; } @@ -2671,28 +2671,28 @@ void Tokenizer::simplifySizeof() sizeOfVar[varId] = MathLib::toString(size); } - else if(Token::Match(tok->tokAt(-1), "%type% %var% [ %num% ] [;=]") || - Token::Match(tok->tokAt(-2), "%type% * %var% [ %num% ] [;=]")) + else if (Token::Match(tok->tokAt(-1), "%type% %var% [ %num% ] [;=]") || + Token::Match(tok->tokAt(-2), "%type% * %var% [ %num% ] [;=]")) { unsigned int size = sizeOfType(tok->tokAt(-1)); - if(size == 0) + if (size == 0) continue; sizeOfVar[varId] = MathLib::toString(size * MathLib::toLongNumber(tok->strAt(2))); } - else if(Token::Match(tok->tokAt(-1), "%type% %var% [ %num% ] [,)]") || - Token::Match(tok->tokAt(-2), "%type% * %var% [ %num% ] [,)]")) + else if (Token::Match(tok->tokAt(-1), "%type% %var% [ %num% ] [,)]") || + Token::Match(tok->tokAt(-2), "%type% * %var% [ %num% ] [,)]")) { Token tempTok(0); tempTok.str("*"); sizeOfVar[varId] = MathLib::toString(sizeOfType(&tempTok)); } - else if(Token::Match(tok->tokAt(-1), "%type% %var% [ ] = %str% ;")) + else if (Token::Match(tok->tokAt(-1), "%type% %var% [ ] = %str% ;")) { unsigned int size = sizeOfType(tok->tokAt(4)); - if(size == 0) + if (size == 0) continue; sizeOfVar[varId] = MathLib::toString(size); @@ -2700,13 +2700,13 @@ void Tokenizer::simplifySizeof() } } - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(tok->str() != "sizeof") + if (tok->str() != "sizeof") continue; // sizeof "text" - if(Token::Match(tok->next(), "%str%")) + if (Token::Match(tok->next(), "%str%")) { tok->deleteThis(); std::ostringstream ostr; @@ -2716,7 +2716,7 @@ void Tokenizer::simplifySizeof() } // sizeof ("text") - if(Token::Match(tok->next(), "( %str% )")) + if (Token::Match(tok->next(), "( %str% )")) { tok->deleteThis(); tok->deleteThis(); @@ -2728,14 +2728,14 @@ void Tokenizer::simplifySizeof() } // sizeof * (...) -> sizeof(*...) - if(Token::simpleMatch(tok->next(), "* (") && !Token::simpleMatch(tok->tokAt(2)->link(), ") .")) + if (Token::simpleMatch(tok->next(), "* (") && !Token::simpleMatch(tok->tokAt(2)->link(), ") .")) { tok->deleteNext(); tok->next()->insertToken("*"); } // sizeof a++ -> sizeof(a++) - if(Token::Match(tok->next(), "++|-- %var% !!.") || Token::Match(tok->next(), "%var% ++|--")) + if (Token::Match(tok->next(), "++|-- %var% !!.") || Token::Match(tok->next(), "%var% ++|--")) { tok->insertToken("("); tok->tokAt(3)->insertToken(")"); @@ -2743,7 +2743,7 @@ void Tokenizer::simplifySizeof() } // sizeof 1 => sizeof ( 1 ) - if(tok->next()->isNumber()) + if (tok->next()->isNumber()) { Token *tok2 = tok->next(); tok->insertToken("("); @@ -2752,37 +2752,37 @@ void Tokenizer::simplifySizeof() } // sizeof int -> sizeof( int ) - else if(tok->next()->str() != "(") + else if (tok->next()->str() != "(") { // Add parenthesis around the sizeof - for(Token *tempToken = tok->next(); tempToken; tempToken = tempToken->next()) + for (Token *tempToken = tok->next(); tempToken; tempToken = tempToken->next()) { - if(Token::Match(tempToken, "%var%")) + if (Token::Match(tempToken, "%var%")) { - while(tempToken->next()->str() == "[") + while (tempToken->next()->str() == "[") { tempToken = tempToken->next()->link(); } - if(tempToken->next()->str() == ".") + if (tempToken->next()->str() == ".") { // We are checking a class or struct, search next varname tempToken = tempToken->tokAt(1); continue; } - else if(Token::simpleMatch(tempToken->next(), "- >")) + else if (Token::simpleMatch(tempToken->next(), "- >")) { // We are checking a class or struct, search next varname tempToken = tempToken->tokAt(2); continue; } - else if(Token::Match(tempToken->next(), "++|--")) + else if (Token::Match(tempToken->next(), "++|--")) { // We have variable++ or variable--, there should be // nothing after this tempToken = tempToken->tokAt(2); } - else if(Token::simpleMatch(tempToken->next(), ") .")) + else if (Token::simpleMatch(tempToken->next(), ") .")) { tempToken = tempToken->tokAt(2); continue; @@ -2798,22 +2798,22 @@ void Tokenizer::simplifySizeof() } // sizeof(type *) => sizeof(*) - if(Token::Match(tok->next(), "( %type% *)")) + if (Token::Match(tok->next(), "( %type% *)")) { tok->next()->deleteNext(); continue; } - if(Token::Match(tok->next(), "( * )")) + if (Token::Match(tok->next(), "( * )")) { tok->str(MathLib::toString(sizeOfType(tok->tokAt(2)))); Token::eraseTokens(tok, tok->tokAt(4)); } // sizeof( a ) - else if(Token::Match(tok->next(), "( %var% )") && tok->tokAt(2)->varId() != 0) + else if (Token::Match(tok->next(), "( %var% )") && tok->tokAt(2)->varId() != 0) { - if(sizeOfVar.find(tok->tokAt(2)->varId()) != sizeOfVar.end()) + if (sizeOfVar.find(tok->tokAt(2)->varId()) != sizeOfVar.end()) { tok->deleteThis(); tok->deleteThis(); @@ -2827,41 +2827,41 @@ void Tokenizer::simplifySizeof() } } - else if(Token::Match(tok, "sizeof ( %type% )")) + else if (Token::Match(tok, "sizeof ( %type% )")) { unsigned int size = sizeOfType(tok->tokAt(2)); - if(size > 0) + if (size > 0) { tok->str(MathLib::toString(size)); Token::eraseTokens(tok, tok->tokAt(4)); } } - else if(Token::Match(tok, "sizeof ( * %var% )") || Token::Match(tok, "sizeof ( %var% [ %num% ] )")) + else if (Token::Match(tok, "sizeof ( * %var% )") || Token::Match(tok, "sizeof ( %var% [ %num% ] )")) { // Some default value.. unsigned int sz = 0; unsigned int varid = tok->tokAt((tok->tokAt(2)->str() == "*") ? 3 : 2)->varId(); - if(varid != 0) + if (varid != 0) { // Try to locate variable declaration.. const Token *decltok = Token::findmatch(_tokens, "%varid%", varid); - if(Token::Match(decltok->previous(), "%type% %var% [")) + if (Token::Match(decltok->previous(), "%type% %var% [")) { sz = sizeOfType(decltok->previous()); } - else if(Token::Match(decltok->previous(), "* %var% [")) + else if (Token::Match(decltok->previous(), "* %var% [")) { sz = sizeOfType(decltok->previous()); } - else if(Token::Match(decltok->tokAt(-2), "%type% * %var%")) + else if (Token::Match(decltok->tokAt(-2), "%type% * %var%")) { sz = sizeOfType(decltok->tokAt(-2)); } } - if(sz > 0) + if (sz > 0) { tok->str(MathLib::toString(sz)); Token::eraseTokens(tok, tok->next()->link()->next()); @@ -2876,23 +2876,23 @@ bool Tokenizer::simplifyTokenList() // clear the _functionList so it can't contain dead pointers _functionList.clear(); - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(Token::simpleMatch(tok, "* const")) + if (Token::simpleMatch(tok, "* const")) tok->deleteNext(); } // Replace NULL with 0.. - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(tok->str() == "NULL" || tok->str() == "'\\0'") + if (tok->str() == "NULL" || tok->str() == "'\\0'") { tok->str("0"); } - else if(tok->isNumber() && - MathLib::isInt(tok->str()) && - MathLib::toLongNumber(tok->str()) == 0) + else if (tok->isNumber() && + MathLib::isInt(tok->str()) && + MathLib::toLongNumber(tok->str()) == 0) { tok->str("0"); } @@ -2908,9 +2908,9 @@ bool Tokenizer::simplifyTokenList() simplifyGoto(); // Combine wide strings - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - while(tok->str() == "L" && tok->next() && tok->next()->str()[0] == '"') + while (tok->str() == "L" && tok->next() && tok->next()->str()[0] == '"') { // Combine 'L "string"' tok->str(tok->next()->str()); @@ -2919,13 +2919,13 @@ bool Tokenizer::simplifyTokenList() } // Combine strings - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(tok->str()[0] != '"') + if (tok->str()[0] != '"') continue; tok->str(simplifyString(tok->str())); - while(tok->next() && tok->next()->str()[0] == '"') + while (tok->next() && tok->next()->str()[0] == '"') { tok->next()->str(simplifyString(tok->next()->str())); @@ -2940,32 +2940,32 @@ bool Tokenizer::simplifyTokenList() // Remove unwanted keywords static const char * const unwantedWords[] = { "unsigned", "unlikely", "likely" }; - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - for(unsigned ui = 0; ui < sizeof(unwantedWords) / sizeof(unwantedWords[0]) && tok->next(); ui++) + for (unsigned ui = 0; ui < sizeof(unwantedWords) / sizeof(unwantedWords[0]) && tok->next(); ui++) { - if(tok->next()->str() == unwantedWords[ui]) + if (tok->next()->str() == unwantedWords[ui]) { tok->deleteNext(); break; } } - if(Token::simpleMatch(tok->next(), "__builtin_expect (")) + if (Token::simpleMatch(tok->next(), "__builtin_expect (")) { unsigned int parlevel = 0; - for(Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) + for (Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) { - if(tok2->str() == "(") + if (tok2->str() == "(") ++parlevel; - else if(tok2->str() == ")") + else if (tok2->str() == ")") { - if(parlevel <= 1) + if (parlevel <= 1) break; --parlevel; } - if(parlevel == 1 && tok2->str() == ",") + if (parlevel == 1 && tok2->str() == ",") { - if(Token::Match(tok2, ", %num% )")) + if (Token::Match(tok2, ", %num% )")) { tok->deleteNext(); Token::eraseTokens(tok2->previous(), tok2->tokAt(2)); @@ -2977,33 +2977,33 @@ bool Tokenizer::simplifyTokenList() } // Convert + + into + and + - into - - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - while(tok->next()) + while (tok->next()) { - if(tok->str() == "+") + if (tok->str() == "+") { - if(tok->next()->str() == "+") + if (tok->next()->str() == "+") { tok->deleteNext(); continue; } - else if(tok->next()->str() == "-") + else if (tok->next()->str() == "-") { tok->str("-"); tok->deleteNext(); continue; } } - else if(tok->str() == "-") + else if (tok->str() == "-") { - if(tok->next()->str() == "-") + if (tok->next()->str() == "-") { tok->str("+"); tok->deleteNext(); continue; } - else if(tok->next()->str() == "+") + else if (tok->next()->str() == "+") { tok->deleteNext(); continue; @@ -3015,9 +3015,9 @@ bool Tokenizer::simplifyTokenList() } // 0[a] -> a[0] - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(Token::Match(tok, "%num% [ %var% ]")) + if (Token::Match(tok, "%num% [ %var% ]")) { const std::string temp = tok->str(); tok->str(tok->tokAt(2)->str()); @@ -3029,9 +3029,9 @@ bool Tokenizer::simplifyTokenList() // replace strlen(str) simplifyKnownVariables(); - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(Token::Match(tok, "strlen ( %str% )")) + if (Token::Match(tok, "strlen ( %str% )")) { std::ostringstream ostr; ostr << Token::getStrLength(tok->tokAt(2)); @@ -3043,9 +3043,9 @@ bool Tokenizer::simplifyTokenList() } // change array to pointer.. - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(Token::Match(tok, "%type% %var% [ ] [,;=]")) + if (Token::Match(tok, "%type% %var% [ ] [,;=]")) { Token::eraseTokens(tok->next(), tok->tokAt(4)); tok->insertToken("*"); @@ -3053,12 +3053,12 @@ bool Tokenizer::simplifyTokenList() } // Replace constants.. - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(Token::Match(tok, "const %type% %var% = %num% ;")) + if (Token::Match(tok, "const %type% %var% = %num% ;")) { unsigned int varId = tok->tokAt(2)->varId(); - if(varId == 0) + if (varId == 0) { tok = tok->tokAt(5); continue; @@ -3066,21 +3066,21 @@ bool Tokenizer::simplifyTokenList() const std::string num = tok->strAt(4); int indent = 1; - for(Token *tok2 = tok->tokAt(6); tok2; tok2 = tok2->next()) + for (Token *tok2 = tok->tokAt(6); tok2; tok2 = tok2->next()) { - if(tok2->str() == "{") + if (tok2->str() == "{") { ++indent; } - else if(tok2->str() == "}") + else if (tok2->str() == "}") { --indent; - if(indent == 0) + if (indent == 0) break; } // Compare constants, but don't touch members of other structures - else if(tok2->varId() == varId) + else if (tok2->varId() == varId) { tok2->str(num); } @@ -3092,9 +3092,9 @@ bool Tokenizer::simplifyTokenList() simplifyCasts(); // simplify "x=realloc(y,0);" => "free(y); x=0;".. - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(Token::Match(tok, "; %var% = realloc ( %var% , 0 ) ;")) + if (Token::Match(tok, "; %var% = realloc ( %var% , 0 ) ;")) { const std::string varname(tok->next()->str()); const unsigned int varid(tok->next()->varId()); @@ -3122,20 +3122,20 @@ bool Tokenizer::simplifyTokenList() } // Simplify simple calculations.. - while(simplifyCalculations()) + while (simplifyCalculations()) ; // Replace "*(str + num)" => "str[num]" - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(! strchr(";{}(=<>", tok->str()[0])) + if (! strchr(";{}(=<>", tok->str()[0])) continue; Token *next = tok->next(); - if(! next) + if (! next) break; - if(Token::Match(next, "* ( %var% + %num% )")) + if (Token::Match(next, "* ( %var% + %num% )")) { // var tok = tok->next(); @@ -3161,10 +3161,10 @@ bool Tokenizer::simplifyTokenList() } // Replace pointer casts of 0.. "(char *)0" => "0" - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(Token::Match(tok->next(), "( %type% * ) 0") || - Token::Match(tok->next(), "( %type% %type% * ) 0")) + if (Token::Match(tok->next(), "( %type% * ) 0") || + Token::Match(tok->next(), "( %type% %type% * ) 0")) { Token::eraseTokens(tok, tok->next()->link()->next()); } @@ -3190,11 +3190,11 @@ bool Tokenizer::simplifyTokenList() simplifyIfAssign(); // could be affected by simplifyIfNot - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(Token::Match(tok, "case %any% : %var%")) + if (Token::Match(tok, "case %any% : %var%")) tok->tokAt(2)->insertToken(";"); - if(Token::Match(tok, "default : %var%")) + if (Token::Match(tok, "default : %var%")) tok->next()->insertToken(";"); } @@ -3202,7 +3202,7 @@ bool Tokenizer::simplifyTokenList() setVarId(); bool modified = true; - while(modified) + while (modified) { modified = false; modified |= simplifyConditions(); @@ -3215,12 +3215,12 @@ bool Tokenizer::simplifyTokenList() } // Remove redundant parantheses in return.. - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - while(Token::simpleMatch(tok, "return (")) + while (Token::simpleMatch(tok, "return (")) { Token *tok2 = tok->next()->link(); - if(Token::simpleMatch(tok2, ") ;")) + if (Token::simpleMatch(tok2, ") ;")) { tok->deleteNext(); tok2->deleteThis(); @@ -3235,7 +3235,7 @@ bool Tokenizer::simplifyTokenList() removeRedundantAssignment(); simplifyComma(); - if(_settings && _settings->_debug) + if (_settings && _settings->_debug) { _tokens->printOut(0, _files); } @@ -3246,51 +3246,51 @@ bool Tokenizer::simplifyTokenList() void Tokenizer::removeRedundantAssignment() { - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(tok->str() == "{") + if (tok->str() == "{") tok = tok->link(); - if(Token::Match(tok, ") const| {")) + if (Token::Match(tok, ") const| {")) { // parse in this function.. std::set localvars; - if(tok->next()->str() == "const") + if (tok->next()->str() == "const") tok = tok->next(); const Token * const end = tok->next()->link(); - for(Token *tok2 = tok->next(); tok2 && tok2 != end; tok2 = tok2->next()) + for (Token *tok2 = tok->next(); tok2 && tok2 != end; tok2 = tok2->next()) { - if(Token::Match(tok2, "[;{}] %type% * %var% ;")) + if (Token::Match(tok2, "[;{}] %type% * %var% ;")) { tok2 = tok2->tokAt(3); localvars.insert(tok2->varId()); } - else if(Token::Match(tok2, "[;{}] %type% %var% ;") && tok2->next()->isStandardType()) + else if (Token::Match(tok2, "[;{}] %type% %var% ;") && tok2->next()->isStandardType()) { tok2 = tok2->tokAt(2); localvars.insert(tok2->varId()); } - else if(tok2->varId() && - !Token::Match(tok2->previous(), "[;{}] %var% = %var% ;") && - !Token::Match(tok2->previous(), "[;{}] %var% = %num% ;")) + else if (tok2->varId() && + !Token::Match(tok2->previous(), "[;{}] %var% = %var% ;") && + !Token::Match(tok2->previous(), "[;{}] %var% = %num% ;")) { localvars.erase(tok2->varId()); } } localvars.erase(0); - if(!localvars.empty()) + if (!localvars.empty()) { - for(Token *tok2 = tok->next(); tok2 && tok2 != end; tok2 = tok2->next()) + for (Token *tok2 = tok->next(); tok2 && tok2 != end; tok2 = tok2->next()) { - if(Token::Match(tok2, "[;{}] %type% %var% ;") && localvars.find(tok2->tokAt(2)->varId()) != localvars.end()) + if (Token::Match(tok2, "[;{}] %type% %var% ;") && localvars.find(tok2->tokAt(2)->varId()) != localvars.end()) { Token::eraseTokens(tok2, tok2->tokAt(3)); } - else if(Token::Match(tok2, "[;{}] %type% * %var% ;") && localvars.find(tok2->tokAt(3)->varId()) != localvars.end()) + else if (Token::Match(tok2, "[;{}] %type% * %var% ;") && localvars.find(tok2->tokAt(3)->varId()) != localvars.end()) { Token::eraseTokens(tok2, tok2->tokAt(4)); } - else if(Token::Match(tok2, "[;{}] %var% = %any% ;") && localvars.find(tok2->next()->varId()) != localvars.end()) + else if (Token::Match(tok2, "[;{}] %var% = %any% ;") && localvars.find(tok2->next()->varId()) != localvars.end()) { Token::eraseTokens(tok2, tok2->tokAt(4)); } @@ -3304,12 +3304,12 @@ bool Tokenizer::removeReduntantConditions() { bool ret = false; - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(tok->str() != "if") + if (tok->str() != "if") continue; - if(!Token::Match(tok->tokAt(1), "( %bool% ) {")) + if (!Token::Match(tok->tokAt(1), "( %bool% ) {")) continue; // Find matching else @@ -3319,16 +3319,16 @@ bool Tokenizer::removeReduntantConditions() elseTag = tok->tokAt(4)->link()->next(); bool boolValue = false; - if(tok->tokAt(2)->str() == "true") + if (tok->tokAt(2)->str() == "true") boolValue = true; // Handle if with else - if(elseTag && elseTag->str() == "else") + if (elseTag && elseTag->str() == "else") { - if(Token::simpleMatch(elseTag->next(), "if (")) + if (Token::simpleMatch(elseTag->next(), "if (")) { // Handle "else if" - if(boolValue == false) + if (boolValue == false) { // Convert "if( false ) {aaa;} else if() {bbb;}" => "if() {bbb;}" Token::eraseTokens(tok, elseTag->tokAt(2)); @@ -3338,19 +3338,19 @@ bool Tokenizer::removeReduntantConditions() { // Keep first if, remove every else if and else after it const Token *lastTagInIf = elseTag->tokAt(2); - while(lastTagInIf) + while (lastTagInIf) { - if(lastTagInIf->str() == "(") + if (lastTagInIf->str() == "(") { lastTagInIf = lastTagInIf->link()->next(); } lastTagInIf = lastTagInIf->link()->next(); - if(!Token::simpleMatch(lastTagInIf, "else")) + if (!Token::simpleMatch(lastTagInIf, "else")) break; lastTagInIf = lastTagInIf->next(); - if(lastTagInIf->str() == "if") + if (lastTagInIf->str() == "if") lastTagInIf = lastTagInIf->next(); } @@ -3361,10 +3361,10 @@ bool Tokenizer::removeReduntantConditions() else { // Handle else - if(boolValue == false) + if (boolValue == false) { // Convert "if( false ) {aaa;} else {bbb;}" => "{bbb;}" or ";{bbb;}" - if(tok->previous()) + if (tok->previous()) tok = tok->previous(); else tok->str(";"); @@ -3373,7 +3373,7 @@ bool Tokenizer::removeReduntantConditions() } else { - if(elseTag->tokAt(1)->str() == "{") + if (elseTag->tokAt(1)->str() == "{") { // Convert "if( true ) {aaa;} else {bbb;}" => "{aaa;}" const Token *end = elseTag->tokAt(1)->link(); @@ -3383,7 +3383,7 @@ bool Tokenizer::removeReduntantConditions() } // Remove "if( true )" - if(tok->previous()) + if (tok->previous()) tok = tok->previous(); else tok->str(";"); @@ -3398,10 +3398,10 @@ bool Tokenizer::removeReduntantConditions() // Handle if without else else { - if(boolValue == false) + if (boolValue == false) { // Remove if and its content - if(tok->previous()) + if (tok->previous()) tok = tok->previous(); else tok->str(";"); @@ -3411,7 +3411,7 @@ bool Tokenizer::removeReduntantConditions() else { // convert "if( true ) {aaa;}" => "{aaa;}" - if(tok->previous()) + if (tok->previous()) tok = tok->previous(); else tok->str(";"); @@ -3429,19 +3429,19 @@ bool Tokenizer::removeReduntantConditions() void Tokenizer::simplifyIfAddBraces() { - for(Token *tok = _tokens; tok; tok = tok ? tok->next() : NULL) + for (Token *tok = _tokens; tok; tok = tok ? tok->next() : NULL) { - if(tok->previous() && !Token::Match(tok->previous(), ";|{|}|else|)|:")) + if (tok->previous() && !Token::Match(tok->previous(), ";|{|}|else|)|:")) continue; - if(Token::Match(tok, "if|for|while (")) + if (Token::Match(tok, "if|for|while (")) { // don't add "{}" around ";" in "do {} while();" (#609) const Token *prev = tok->previous(); - if(Token::simpleMatch(prev, "} while") && - prev->link() && - prev->link()->previous() && - prev->link()->previous()->str() == "do") + if (Token::simpleMatch(prev, "} while") && + prev->link() && + prev->link()->previous() && + prev->link()->previous()->str() == "do") { continue; } @@ -3450,14 +3450,14 @@ void Tokenizer::simplifyIfAddBraces() tok = tok->next()->link(); // ')' should be followed by '{' - if(!tok || Token::simpleMatch(tok, ") {")) + if (!tok || Token::simpleMatch(tok, ") {")) continue; } - else if(tok->str() == "else") + else if (tok->str() == "else") { // An else followed by an if or brace don't need to be processed further - if(Token::Match(tok, "else if|{")) + if (Token::Match(tok, "else if|{")) continue; } @@ -3467,7 +3467,7 @@ void Tokenizer::simplifyIfAddBraces() } // If there is no code after he if(), abort - if(!tok->next()) + if (!tok->next()) return; @@ -3478,7 +3478,7 @@ void Tokenizer::simplifyIfAddBraces() bool innerIf = Token::simpleMatch(tempToken->next(), "if"); - if(Token::simpleMatch(tempToken->next(), "do {")) + if (Token::simpleMatch(tempToken->next(), "do {")) tempToken = tempToken->tokAt(2)->link(); // insert close brace.. @@ -3489,18 +3489,18 @@ void Tokenizer::simplifyIfAddBraces() // * if (cond1) if (cond2) ; else ; int parlevel = 0; int indentlevel = 0; - while((tempToken = tempToken->next()) != NULL) + while ((tempToken = tempToken->next()) != NULL) { - if(tempToken->str() == "{") + if (tempToken->str() == "{") ++indentlevel; - else if(tempToken->str() == "}") + else if (tempToken->str() == "}") { --indentlevel; - if(indentlevel == 0 && parlevel == 0) + if (indentlevel == 0 && parlevel == 0) break; - else if(indentlevel < 0 && parlevel == 0) + else if (indentlevel < 0 && parlevel == 0) { // insert closing brace before this tempToken = tempToken->previous(); @@ -3508,12 +3508,12 @@ void Tokenizer::simplifyIfAddBraces() } } - else if(tempToken->str() == "(") + else if (tempToken->str() == "(") ++parlevel; - else if(tempToken->str() == ")") + else if (tempToken->str() == ")") { - if(parlevel == 0) + if (parlevel == 0) { tok->deleteThis(); tempToken = 0; @@ -3522,21 +3522,21 @@ void Tokenizer::simplifyIfAddBraces() --parlevel; } - else if(indentlevel == 0 && parlevel == 0 && tempToken->str() == ";") + else if (indentlevel == 0 && parlevel == 0 && tempToken->str() == ";") { - if(!innerIf) + if (!innerIf) break; - if(Token::Match(tempToken, "; else if")) + if (Token::Match(tempToken, "; else if")) ; - else if(Token::Match(tempToken, "; else")) + else if (Token::Match(tempToken, "; else")) innerIf = false; else break; } } - if(tempToken) + if (tempToken) { tempToken->insertToken("}"); Token::createMutualLinks(tok, tempToken->next()); @@ -3546,7 +3546,7 @@ void Tokenizer::simplifyIfAddBraces() bool Tokenizer::simplifyDoWhileAddBracesHelper(Token *tok) { - if(Token::Match(tok->next(), "[),]")) + if (Token::Match(tok->next(), "[),]")) { // fix for #988 return false; @@ -3558,26 +3558,26 @@ bool Tokenizer::simplifyDoWhileAddBracesHelper(Token *tok) // skip loop body bool result = false; - while(tok3) + while (tok3) { - if(tok3->str() == "{") + if (tok3->str() == "{") { tok3 = tok3->link(); } - else if(tok3->str() == "while") + else if (tok3->str() == "while") { tok2 = tok3; break; } - else if(Token::Match(tok3, "do {")) + else if (Token::Match(tok3, "do {")) { // Skip do{}while inside the current "do" tok3 = tok3->next()->link(); - if(Token::simpleMatch(tok3->next(), "while")) + if (Token::simpleMatch(tok3->next(), "while")) tok3 = tok3->next(); } - else if(Token::Match(tok3, "do !!{") && - !Token::Match(tok3->next(), "[),]")) + else if (Token::Match(tok3, "do !!{") && + !Token::Match(tok3->next(), "[),]")) { // Handle do-while inside the current "do" // first and return true to get the outer @@ -3589,7 +3589,7 @@ bool Tokenizer::simplifyDoWhileAddBracesHelper(Token *tok) tok3 = tok3->next(); } - if(tok2) + if (tok2) { // insert "{" after "do" tok1->insertToken("{"); @@ -3607,11 +3607,11 @@ bool Tokenizer::simplifyDoWhileAddBracesHelper(Token *tok) void Tokenizer::simplifyDoWhileAddBraces() { - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(Token::Match(tok, "do !!{")) + if (Token::Match(tok, "do !!{")) { - while(simplifyDoWhileAddBracesHelper(tok)) + while (simplifyDoWhileAddBracesHelper(tok)) { // Call until the function returns false to // handle do-while inside do-while @@ -3624,13 +3624,13 @@ void Tokenizer::simplifyDoWhileAddBraces() void Tokenizer::simplifyConditionOperator() { int parlevel = 0; - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(tok->str() == "(") + if (tok->str() == "(") ++parlevel; - else if(tok->str() == ")") + else if (tok->str() == ")") --parlevel; - else if(parlevel == 0 && Token::Match(tok, "; %var% = %var% ? %var% : %var% ;")) + else if (parlevel == 0 && Token::Match(tok, "; %var% = %var% ? %var% : %var% ;")) { const std::string var(tok->strAt(1)); const std::string condition(tok->strAt(3)); @@ -3641,10 +3641,10 @@ void Tokenizer::simplifyConditionOperator() std::string str("if ( " + condition + " ) { " + var + " = " + value1 + " ; } else { " + var + " = " + value2 + " ; }"); std::string::size_type pos1 = 0; - while(pos1 != std::string::npos) + while (pos1 != std::string::npos) { std::string::size_type pos2 = str.find(" ", pos1); - if(pos2 == std::string::npos) + if (pos2 == std::string::npos) { tok->insertToken(str.substr(pos1).c_str()); pos1 = pos2; @@ -3668,11 +3668,11 @@ bool Tokenizer::simplifyConditions() { bool ret = false; - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(Token::Match(tok, "! %num%") || Token::Match(tok, "! %bool%")) + if (Token::Match(tok, "! %num%") || Token::Match(tok, "! %bool%")) { - if(tok->next()->str() == "0" || tok->next()->str() == "false") + if (tok->next()->str() == "0" || tok->next()->str() == "false") tok->str("true"); else tok->str("false"); @@ -3681,34 +3681,34 @@ bool Tokenizer::simplifyConditions() ret = true; } - if(Token::simpleMatch(tok, "( true &&") || - Token::simpleMatch(tok, "&& true &&") || - Token::simpleMatch(tok->next(), "&& true )")) + if (Token::simpleMatch(tok, "( true &&") || + Token::simpleMatch(tok, "&& true &&") || + Token::simpleMatch(tok->next(), "&& true )")) { Token::eraseTokens(tok, tok->tokAt(3)); ret = true; } - else if(Token::simpleMatch(tok, "( false ||") || - Token::simpleMatch(tok, "|| false ||") || - Token::simpleMatch(tok->next(), "|| false )")) + else if (Token::simpleMatch(tok, "( false ||") || + Token::simpleMatch(tok, "|| false ||") || + Token::simpleMatch(tok->next(), "|| false )")) { Token::eraseTokens(tok, tok->tokAt(3)); ret = true; } // Change numeric constant in condition to "true" or "false" - if(Token::Match(tok, "if|while ( %num%") && - (tok->tokAt(3)->str() == ")" || tok->tokAt(3)->str() == "||" || tok->tokAt(3)->str() == "&&")) + if (Token::Match(tok, "if|while ( %num%") && + (tok->tokAt(3)->str() == ")" || tok->tokAt(3)->str() == "||" || tok->tokAt(3)->str() == "&&")) { tok->tokAt(2)->str((tok->tokAt(2)->str() != "0") ? "true" : "false"); ret = true; } Token *tok2 = tok->tokAt(2); - if(tok2 && - (tok->str() == "&&" || tok->str() == "||") && - Token::Match(tok->next(), "%num%") && - (tok2->str() == ")" || tok2->str() == "&&" || tok2->str() == "||")) + if (tok2 && + (tok->str() == "&&" || tok->str() == "||") && + Token::Match(tok->next(), "%num%") && + (tok2->str() == ")" || tok2->str() == "&&" || tok2->str() == "||")) { tok->next()->str((tok->next()->str() != "0") ? "true" : "false"); ret = true; @@ -3716,32 +3716,32 @@ bool Tokenizer::simplifyConditions() // Reduce "(%num% == %num%)" => "(true)"/"(false)" const Token *tok4 = tok->tokAt(4); - if(! tok4) + if (! tok4) break; - if((tok->str() == "&&" || tok->str() == "||" || tok->str() == "(") && - (Token::Match(tok->tokAt(1), "%num% %any% %num%") || - Token::Match(tok->tokAt(1), "%bool% %any% %bool%")) && - (tok4->str() == "&&" || tok4->str() == "||" || tok4->str() == ")" || tok4->str() == "?")) + if ((tok->str() == "&&" || tok->str() == "||" || tok->str() == "(") && + (Token::Match(tok->tokAt(1), "%num% %any% %num%") || + Token::Match(tok->tokAt(1), "%bool% %any% %bool%")) && + (tok4->str() == "&&" || tok4->str() == "||" || tok4->str() == ")" || tok4->str() == "?")) { std::string cmp = tok->strAt(2); bool result = false; - if(Token::Match(tok->tokAt(1), "%num%")) + if (Token::Match(tok->tokAt(1), "%num%")) { // Compare numbers double op1 = MathLib::toDoubleNumber(tok->strAt(1)); double op2 = MathLib::toDoubleNumber(tok->strAt(3)); - if(cmp == "==") + if (cmp == "==") result = (op1 == op2); - else if(cmp == "!=") + else if (cmp == "!=") result = (op1 != op2); - else if(cmp == ">=") + else if (cmp == ">=") result = (op1 >= op2); - else if(cmp == ">") + else if (cmp == ">") result = (op1 > op2); - else if(cmp == "<=") + else if (cmp == "<=") result = (op1 <= op2); - else if(cmp == "<") + else if (cmp == "<") result = (op1 < op2); else cmp = ""; @@ -3752,23 +3752,23 @@ bool Tokenizer::simplifyConditions() bool op1 = (tok->strAt(1) == std::string("true")); bool op2 = (tok->strAt(3) == std::string("true")); - if(cmp == "==") + if (cmp == "==") result = (op1 == op2); - else if(cmp == "!=") + else if (cmp == "!=") result = (op1 != op2); - else if(cmp == ">=") + else if (cmp == ">=") result = (op1 >= op2); - else if(cmp == ">") + else if (cmp == ">") result = (op1 > op2); - else if(cmp == "<=") + else if (cmp == "<=") result = (op1 <= op2); - else if(cmp == "<") + else if (cmp == "<") result = (op1 < op2); else cmp = ""; } - if(! cmp.empty()) + if (! cmp.empty()) { tok = tok->next(); tok->deleteNext(); @@ -3786,47 +3786,47 @@ bool Tokenizer::simplifyConditions() bool Tokenizer::simplifyQuestionMark() { bool ret = false; - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(tok->str() != "?") + if (tok->str() != "?") continue; - if(!tok->tokAt(-2)) + if (!tok->tokAt(-2)) continue; - if(!Token::Match(tok->tokAt(-2), "[=,(]")) + if (!Token::Match(tok->tokAt(-2), "[=,(]")) continue; - if(!Token::Match(tok->previous(), "%bool%") && - !Token::Match(tok->previous(), "%num%")) + if (!Token::Match(tok->previous(), "%bool%") && + !Token::Match(tok->previous(), "%num%")) continue; // Find the ":" token.. Token *semicolon = 0; { unsigned int parlevel = 0; - for(Token *tok2 = tok; tok2; tok2 = tok2->next()) + for (Token *tok2 = tok; tok2; tok2 = tok2->next()) { - if(tok2->str() == "(") + if (tok2->str() == "(") ++parlevel; - else if(tok2->str() == ")") + else if (tok2->str() == ")") { - if(parlevel == 0) + if (parlevel == 0) break; --parlevel; } - else if(parlevel == 0 && tok2->str() == ":") + else if (parlevel == 0 && tok2->str() == ":") { semicolon = tok2; break; } } } - if(!semicolon || !semicolon->next()) + if (!semicolon || !semicolon->next()) continue; - if(tok->previous()->str() == "false" || - tok->previous()->str() == "0") + if (tok->previous()->str() == "false" || + tok->previous()->str() == "0") { // Use code after semicolon, remove code before it. semicolon = semicolon->next(); @@ -3843,10 +3843,10 @@ bool Tokenizer::simplifyQuestionMark() const Token *end = 0; // check the operator after the : - if(Token::simpleMatch(semicolon, ": (")) + if (Token::simpleMatch(semicolon, ": (")) { end = semicolon->next()->link(); - if(!Token::Match(end, ") !!.")) + if (!Token::Match(end, ") !!.")) continue; } @@ -3855,31 +3855,31 @@ bool Tokenizer::simplifyQuestionMark() Token::eraseTokens(tok, tok->tokAt(3)); // delete operator after the : - if(end) + if (end) { Token::eraseTokens(semicolon->previous(), end->next()); continue; } int ind = 0; - for(const Token *end = semicolon; end; end = end->next()) + for (const Token *end = semicolon; end; end = end->next()) { - if(end->str() == ";") + if (end->str() == ";") { Token::eraseTokens(semicolon->previous(), end->next()); ret = true; break; } - else if(Token::Match(end, "[({[]")) + else if (Token::Match(end, "[({[]")) { ++ind; } - else if(Token::Match(end, "[)}]]")) + else if (Token::Match(end, "[)}]]")) { --ind; - if(ind < 0) + if (ind < 0) { Token::eraseTokens(semicolon->previous(), end); ret = true; @@ -3895,21 +3895,21 @@ bool Tokenizer::simplifyQuestionMark() void Tokenizer::simplifyCasts() { - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - while(Token::Match(tok->next(), "( %type% *| ) *|&| %var%") || - Token::Match(tok->next(), "( %type% %type% *| ) *|&| %var%")) + while (Token::Match(tok->next(), "( %type% *| ) *|&| %var%") || + Token::Match(tok->next(), "( %type% %type% *| ) *|&| %var%")) { - if(tok->isName() && tok->str() != "return") + if (tok->isName() && tok->str() != "return") break; - if(Token::simpleMatch(tok->previous(), "operator")) + if (Token::simpleMatch(tok->previous(), "operator")) break; // Remove cast.. Token::eraseTokens(tok, tok->next()->link()->next()); - if(tok->str() == ")" && tok->link()->previous()) + if (tok->str() == ")" && tok->link()->previous()) { // If there was another cast before this, go back // there to check it also. e.g. "(int)(char)x" @@ -3917,27 +3917,27 @@ void Tokenizer::simplifyCasts() } } - if(Token::Match(tok->next(), "dynamic_cast|reinterpret_cast|const_cast|static_cast <")) + if (Token::Match(tok->next(), "dynamic_cast|reinterpret_cast|const_cast|static_cast <")) { Token *tok2 = tok->next(); unsigned int level = 0; - while(tok2) + while (tok2) { - if(tok2->str() == "<") + if (tok2->str() == "<") ++level; - else if(tok2->str() == ">") + else if (tok2->str() == ">") { --level; - if(level == 0) + if (level == 0) break; } tok2 = tok2->next(); } - if(Token::simpleMatch(tok2, "> (")) + if (Token::simpleMatch(tok2, "> (")) { Token *closeBracket = tok2->next()->link(); - if(closeBracket) + if (closeBracket) { Token::eraseTokens(tok, tok2->tokAt(2)); closeBracket->deleteThis(); @@ -3950,18 +3950,18 @@ void Tokenizer::simplifyCasts() void Tokenizer::simplifyFunctionParameters() { - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(tok->str() == "{" || tok->str() == "[" || tok->str() == "(") + if (tok->str() == "{" || tok->str() == "[" || tok->str() == "(") { tok = tok->link(); - if(!tok) + if (!tok) break; continue; } // Find the function e.g. foo( x ) or foo( x, y ) - if(Token::Match(tok, "%var% ( %var% [,)]")) + if (Token::Match(tok, "%var% ( %var% [,)]")) { // We have found old style function, now we need to change it @@ -3971,15 +3971,15 @@ void Tokenizer::simplifyFunctionParameters() // Get list of argument names std::map argumentNames; bool bailOut = false; - for(tok = tok->tokAt(2); tok; tok = tok->tokAt(2)) + for (tok = tok->tokAt(2); tok; tok = tok->tokAt(2)) { - if(!Token::Match(tok, "%var% [,)]")) + if (!Token::Match(tok, "%var% [,)]")) { bailOut = true; break; } - if(argumentNames.find(tok->str()) != argumentNames.end()) + if (argumentNames.find(tok->str()) != argumentNames.end()) { // Invalid code, two arguments with the same name. // TODO, print error perhaps? @@ -3988,31 +3988,31 @@ void Tokenizer::simplifyFunctionParameters() } argumentNames[tok->str()] = tok; - if(tok->next()->str() == ")") + if (tok->next()->str() == ")") { tok = tok->tokAt(2); break; } } - if(bailOut) + if (bailOut) { tok = tok1->link(); - if(!tok) + if (!tok) return; continue; } Token *start = tok; - while(tok && tok->str() != "{") + while (tok && tok->str() != "{") { - if(tok->str() == ";") + if (tok->str() == ";") { tok = tok->previous(); // Move tokens from start to tok into the place of // argumentNames[tok->str()] and remove the ";" - if(argumentNames.find(tok->str()) == argumentNames.end()) + if (argumentNames.find(tok->str()) == argumentNames.end()) { bailOut = true; break; @@ -4034,15 +4034,15 @@ void Tokenizer::simplifyFunctionParameters() } } - if(Token::simpleMatch(tok, "{")) + if (Token::simpleMatch(tok, "{")) tok = tok->link(); - if(tok == NULL) + if (tok == NULL) { break; } - if(bailOut) + if (bailOut) { continue; } @@ -4053,23 +4053,23 @@ void Tokenizer::simplifyFunctionParameters() void Tokenizer:: simplifyFunctionPointers() { - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(tok->previous() && !Token::Match(tok->previous(), "[{};]")) + if (tok->previous() && !Token::Match(tok->previous(), "[{};]")) continue; - if(Token::Match(tok, "%type% *| *| ( * %var% ) (")) + if (Token::Match(tok, "%type% *| *| ( * %var% ) (")) ; - else if(Token::Match(tok, "%type% %type% *| *| ( * %var% ) (")) + else if (Token::Match(tok, "%type% %type% *| *| ( * %var% ) (")) tok = tok->next(); else continue; - while(tok->next()->str() == "*") + while (tok->next()->str() == "*") tok = tok->next(); // check that the declaration ends with ; - if(!Token::simpleMatch(tok->tokAt(5)->link(), ") ;")) + if (!Token::simpleMatch(tok->tokAt(5)->link(), ") ;")) continue; // ok simplify this function pointer to an ordinary pointer @@ -4085,21 +4085,21 @@ bool Tokenizer::simplifyFunctionReturn() { bool ret = false; int indentlevel = 0; - for(const Token *tok = tokens(); tok; tok = tok->next()) + for (const Token *tok = tokens(); tok; tok = tok->next()) { - if(tok->str() == "{") + if (tok->str() == "{") ++indentlevel; - else if(tok->str() == "}") + else if (tok->str() == "}") --indentlevel; - else if(indentlevel == 0 && Token::Match(tok, "%var% ( ) { return %num% ; }")) + else if (indentlevel == 0 && Token::Match(tok, "%var% ( ) { return %num% ; }")) { std::ostringstream pattern; pattern << "[(=+-*/] " << tok->str() << " ( ) [;)+-*/]"; - for(Token *tok2 = _tokens; tok2; tok2 = tok2->next()) + for (Token *tok2 = _tokens; tok2; tok2 = tok2->next()) { - if(Token::Match(tok2, pattern.str().c_str())) + if (Token::Match(tok2, pattern.str().c_str())) { tok2 = tok2->next(); tok2->str(tok->strAt(5)); @@ -4120,9 +4120,9 @@ static void incdec(std::string &value, const std::string &op) int ivalue = 0; std::istringstream istr(value.c_str()); istr >> ivalue; - if(op == "++") + if (op == "++") ++ivalue; - else if(op == "--") + else if (op == "--") --ivalue; std::ostringstream ostr; ostr << ivalue; @@ -4135,22 +4135,22 @@ void Tokenizer::simplifyVarDecl() { // Split up variable declarations.. // "int a=4;" => "int a; a=4;" - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(Token::simpleMatch(tok, "= {")) + if (Token::simpleMatch(tok, "= {")) { tok = tok->next()->link(); - if(!tok) + if (!tok) break; } - if(tok->previous() && !Token::Match(tok->previous(), "[{};)]")) + if (tok->previous() && !Token::Match(tok->previous(), "[{};)]")) continue; Token *type0 = tok; - if(!Token::Match(type0, "%type%")) + if (!Token::Match(type0, "%type%")) continue; - if(Token::Match(type0, "else|return")) + if (Token::Match(type0, "else|return")) continue; bool isconst = false; @@ -4158,12 +4158,12 @@ void Tokenizer::simplifyVarDecl() Token *tok2 = type0; unsigned int typelen = 1; - while(Token::Match(tok2, "%type% %type% *| *| %var%")) + while (Token::Match(tok2, "%type% %type% *| *| %var%")) { - if(tok2->str() == "const") + if (tok2->str() == "const") isconst = true; - else if(tok2->str() == "static") + else if (tok2->str() == "static") isstatic = true; tok2 = tok2->next(); @@ -4171,26 +4171,26 @@ void Tokenizer::simplifyVarDecl() } // Don't split up const declaration.. - if(isconst && Token::Match(tok2, "%type% %var% =")) + if (isconst && Token::Match(tok2, "%type% %var% =")) continue; // strange looking variable declaration => don't split up. - if(Token::Match(tok2, "%type% *| %var% , %type% *| %var%")) + if (Token::Match(tok2, "%type% *| %var% , %type% *| %var%")) continue; - if(Token::Match(tok2, "%type% *| %var% ,|=")) + if (Token::Match(tok2, "%type% *| %var% ,|=")) { const bool isPointer = (tok2->next()->str() == "*"); const Token *varName = tok2->tokAt((isPointer ? 2 : 1)); Token *endDeclaration = varName->next(); - if(varName->str() != "operator") + if (varName->str() != "operator") { tok2 = endDeclaration; // The ',' or '=' token - if(isstatic && tok2->str() == "=") + if (isstatic && tok2->str() == "=") { - if(Token::Match(tok2->next(), "%num% ,")) + if (Token::Match(tok2->next(), "%num% ,")) tok2 = tok2->tokAt(2); else tok2 = NULL; @@ -4200,17 +4200,17 @@ void Tokenizer::simplifyVarDecl() tok2 = NULL; } - else if(Token::Match(tok2, "%type% * * %var% ,|=")) + else if (Token::Match(tok2, "%type% * * %var% ,|=")) { - if(tok2->tokAt(3)->str() != "operator") + if (tok2->tokAt(3)->str() != "operator") tok2 = tok2->tokAt(4); // The ',' token else tok2 = NULL; } - else if(Token::Match(tok2, "%type% * const %var% ,|=")) + else if (Token::Match(tok2, "%type% * const %var% ,|=")) { - if(tok2->tokAt(3)->str() != "operator") + if (tok2->tokAt(3)->str() != "operator") { tok2 = tok2->tokAt(4); // The ',' token } @@ -4220,38 +4220,38 @@ void Tokenizer::simplifyVarDecl() } } - else if(Token::Match(tok2, "%type% %var% [ %num% ] ,|=") || - Token::Match(tok2, "%type% %var% [ %var% ] ,|=")) + else if (Token::Match(tok2, "%type% %var% [ %num% ] ,|=") || + Token::Match(tok2, "%type% %var% [ %var% ] ,|=")) { tok2 = tok2->tokAt(5); // The ',' token - if(tok2->str() == "=") + if (tok2->str() == "=") { - while(tok2 && tok2->str() != ",") + while (tok2 && tok2->str() != ",") { - if(tok2->str() == "{") + if (tok2->str() == "{") tok2 = tok2->link(); tok2 = tok2->next(); - if(tok2->str() == ";") + if (tok2->str() == ";") tok2 = NULL; } } } - else if(Token::Match(tok2, "%type% * %var% [ %num% ] ,") || - Token::Match(tok2, "%type% * %var% [ %var% ] ,")) + else if (Token::Match(tok2, "%type% * %var% [ %num% ] ,") || + Token::Match(tok2, "%type% * %var% [ %var% ] ,")) { tok2 = tok2->tokAt(6); // The ',' token } - else if(Token::Match(tok2, "std :: %type% <") || Token::Match(tok2, "%type% <")) + else if (Token::Match(tok2, "std :: %type% <") || Token::Match(tok2, "%type% <")) { // // Deal with templates and standart types // - if(Token::simpleMatch(tok2, "std ::")) + if (Token::simpleMatch(tok2, "std ::")) { typelen += 2; tok2 = tok2->tokAt(2); @@ -4261,41 +4261,41 @@ void Tokenizer::simplifyVarDecl() tok2 = tok2->tokAt(2); size_t indentlevel = 1; - for(Token *tok3 = tok2; tok3; tok3 = tok3->next()) + for (Token *tok3 = tok2; tok3; tok3 = tok3->next()) { ++typelen; - if(tok3->str() == "<") + if (tok3->str() == "<") { ++indentlevel; } - else if(tok3->str() == ">") + else if (tok3->str() == ">") { --indentlevel; - if(indentlevel == 0) + if (indentlevel == 0) { tok2 = tok3->next(); break; } } - else if(tok3->str() == ";") + else if (tok3->str() == ";") { break; } } - if(Token::Match(tok2, ":: %type%")) + if (Token::Match(tok2, ":: %type%")) { typelen += 2; tok2 = tok2->tokAt(2); } - if(tok2->str() == "*" || tok2->str() == "&") + if (tok2->str() == "*" || tok2->str() == "&") { tok2 = tok2->next(); } - if(Token::Match(tok2, "%var% ,")) + if (Token::Match(tok2, "%var% ,")) { tok2 = tok2->next(); // The ',' token typelen--; @@ -4313,27 +4313,27 @@ void Tokenizer::simplifyVarDecl() } - if(tok2) + if (tok2) { - if(tok2->str() == ",") + if (tok2->str() == ",") { tok2->str(";"); insertTokens(tok2, type0, typelen); std::stack link1; std::stack link2; - while(((typelen--) > 0) && (0 != (tok2 = tok2->next()))) + while (((typelen--) > 0) && (0 != (tok2 = tok2->next()))) { - if(tok2->str() == "(") + if (tok2->str() == "(") link1.push(tok2); - else if(tok2->str() == ")" && !link1.empty()) + else if (tok2->str() == ")" && !link1.empty()) { Token::createMutualLinks(tok2, link1.top()); link1.pop(); } - else if(tok2->str() == "[") + else if (tok2->str() == "[") link2.push(tok2); - else if(tok2->str() == "]" && !link2.empty()) + else if (tok2->str() == "]" && !link2.empty()) { Token::createMutualLinks(tok2, link2.top()); link2.pop(); @@ -4346,31 +4346,31 @@ void Tokenizer::simplifyVarDecl() Token *eq = tok2; int parlevel = 0; - while(tok2) + while (tok2) { - if(Token::Match(tok2, "[{(<]")) + if (Token::Match(tok2, "[{(<]")) { ++parlevel; } - else if(Token::Match(tok2, "[})>]")) + else if (Token::Match(tok2, "[})>]")) { - if(parlevel <= 0) + if (parlevel <= 0) break; --parlevel; } - else if(parlevel == 0 && strchr(";,", tok2->str()[0])) + else if (parlevel == 0 && strchr(";,", tok2->str()[0])) { // "type var =" => "type var; var =" Token *VarTok = type0->tokAt(typelen); - while(Token::Match(VarTok, "*|const")) + while (Token::Match(VarTok, "*|const")) VarTok = VarTok->next(); insertTokens(eq, VarTok, 2); eq->str(";"); // "= x, " => "= x; type " - if(tok2->str() == ",") + if (tok2->str() == ",") { tok2->str(";"); insertTokens(tok2, type0, typelen); @@ -4387,26 +4387,26 @@ void Tokenizer::simplifyVarDecl() void Tokenizer::simplifyStdType() { - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { // long unsigned => unsigned long - if(Token::Match(tok, "long|short|int|char|_int64 unsigned|signed")) + if (Token::Match(tok, "long|short|int|char|_int64 unsigned|signed")) { std::string temp = tok->str(); tok->str(tok->next()->str()); tok->next()->str(temp); } - if(!Token::Match(tok, "unsigned|signed|long|char|short|int|__int64")) + if (!Token::Match(tok, "unsigned|signed|long|char|short|int|__int64")) continue; // check if signed or unsigned specified - if(Token::Match(tok, "unsigned|signed")) + if (Token::Match(tok, "unsigned|signed")) { bool isUnsigned = tok->str() == "unsigned"; // unsigned i => unsigned int i - if(!tok->next()->isIntegerType()) + if (!tok->next()->isIntegerType()) tok->str("int"); else tok->deleteThis(); @@ -4414,31 +4414,31 @@ void Tokenizer::simplifyStdType() tok->isSigned(!isUnsigned); } - if(Token::Match(tok, "__int64")) + if (Token::Match(tok, "__int64")) { tok->str("long"); tok->isLong(true); } - else if(Token::Match(tok, "long")) + else if (Token::Match(tok, "long")) { - if(Token::Match(tok->next(), "long")) + if (Token::Match(tok->next(), "long")) { tok->isLong(true); tok->deleteNext(); } - if(Token::Match(tok->next(), "int")) + if (Token::Match(tok->next(), "int")) tok->deleteNext(); - else if(Token::Match(tok->next(), "double")) + else if (Token::Match(tok->next(), "double")) { tok->str("double"); tok->isLong(true); tok->deleteNext(); } } - else if(Token::Match(tok, "short")) + else if (Token::Match(tok, "short")) { - if(Token::Match(tok->next(), "int")) + if (Token::Match(tok->next(), "int")) tok->deleteNext(); } } @@ -4446,10 +4446,10 @@ void Tokenizer::simplifyStdType() void Tokenizer::simplifyIfAssign() { - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(!Token::Match(tok->next(), "if|while ( !| (| %var% =") && - !Token::Match(tok->next(), "if|while ( !| (| %var% . %var% =")) + if (!Token::Match(tok->next(), "if|while ( !| (| %var% =") && + !Token::Match(tok->next(), "if|while ( !| (| %var% . %var% =")) continue; // simplifying a "while" condition ? @@ -4460,13 +4460,13 @@ void Tokenizer::simplifyIfAssign() // Remember if there is a "!" or not. And delete it if there are. const bool isNot(tok->tokAt(2)->str() == "!"); - if(isNot) + if (isNot) tok->next()->deleteNext(); // Delete paranthesis.. and remember how many there are with // their links. std::list braces; - while(tok->next()->str() == "(") + while (tok->next()->str() == "(") { braces.push_back(tok->next()->link()); tok->deleteNext(); @@ -4475,13 +4475,13 @@ void Tokenizer::simplifyIfAssign() // Skip the "%var% = ..." Token *tok2; unsigned int indentlevel = 0; - for(tok2 = tok->next(); tok2; tok2 = tok2->next()) + for (tok2 = tok->next(); tok2; tok2 = tok2->next()) { - if(tok2->str() == "(") + if (tok2->str() == "(") ++indentlevel; - else if(tok2->str() == ")") + else if (tok2->str() == ")") { - if(indentlevel <= 0) + if (indentlevel <= 0) break; --indentlevel; } @@ -4489,7 +4489,7 @@ void Tokenizer::simplifyIfAssign() // Insert "; if|while ( .." tok2 = tok2->previous(); - if(Token::simpleMatch(tok->tokAt(2), ".")) + if (Token::simpleMatch(tok->tokAt(2), ".")) { tok2->insertToken(tok->strAt(3)); tok2->insertToken(tok->strAt(2)); @@ -4497,41 +4497,41 @@ void Tokenizer::simplifyIfAssign() tok2->insertToken(tok->strAt(1)); tok2->next()->varId(tok->tokAt(1)->varId()); - while(! braces.empty()) + while (! braces.empty()) { tok2->insertToken("("); Token::createMutualLinks(tok2->next(), braces.back()); braces.pop_back(); } - if(isNot) + if (isNot) tok2->next()->insertToken("!"); tok2->insertToken(iswhile ? "while" : "if"); tok2->insertToken(";"); // If it's a while loop.. insert the assignment in the loop - if(iswhile) + if (iswhile) { indentlevel = 0; Token *tok3 = tok2; - for(tok3 = tok2; tok3; tok3 = tok3->next()) + for (tok3 = tok2; tok3; tok3 = tok3->next()) { - if(tok3->str() == "{") + if (tok3->str() == "{") ++indentlevel; - else if(tok3->str() == "}") + else if (tok3->str() == "}") { - if(indentlevel <= 1) + if (indentlevel <= 1) break; --indentlevel; } } - if(tok3 && indentlevel == 1) + if (tok3 && indentlevel == 1) { tok3 = tok3->previous(); std::list braces2; - for(tok2 = tok2->next(); tok2 && tok2 != tok; tok2 = tok2->previous()) + for (tok2 = tok2->next(); tok2 && tok2 != tok; tok2 = tok2->previous()) { tok3->insertToken(tok2->strAt(0)); @@ -4540,20 +4540,20 @@ void Tokenizer::simplifyIfAssign() newTok->linenr(tok2->linenr()); // link() newly tokens manually - if(newTok->str() == ")") + if (newTok->str() == ")") { braces.push_back(newTok); } - else if(newTok->str() == "]") + else if (newTok->str() == "]") { braces2.push_back(newTok); } - else if(newTok->str() == "(") + else if (newTok->str() == "(") { Token::createMutualLinks(newTok, braces.back()); braces.pop_back(); } - else if(newTok->str() == "[") + else if (newTok->str() == "[") { Token::createMutualLinks(newTok, braces2.back()); braces2.pop_back(); @@ -4568,32 +4568,32 @@ void Tokenizer::simplifyIfAssign() void Tokenizer::simplifyIfNot() { - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(tok->str() == "(" || tok->str() == "||" || tok->str() == "&&") + if (tok->str() == "(" || tok->str() == "||" || tok->str() == "&&") { tok = tok->next(); - while(tok && tok->str() == "(") + while (tok && tok->str() == "(") tok = tok->next(); - if(!tok) + if (!tok) break; - if(Token::Match(tok, "0|false == (") || - Token::Match(tok, "0|false == %var%")) + if (Token::Match(tok, "0|false == (") || + Token::Match(tok, "0|false == %var%")) { tok->deleteNext(); tok->str("!"); } - else if(Token::Match(tok, "%var% == 0|false")) + else if (Token::Match(tok, "%var% == 0|false")) { tok->deleteNext(); tok->next()->str(tok->str()); tok->str("!"); } - else if(Token::Match(tok, "%var% .|:: %var% == 0|false")) + else if (Token::Match(tok, "%var% .|:: %var% == 0|false")) { tok = tok->previous(); tok->insertToken("!"); @@ -4601,7 +4601,7 @@ void Tokenizer::simplifyIfNot() Token::eraseTokens(tok, tok->tokAt(3)); } - else if(Token::Match(tok, "* %var% == 0|false")) + else if (Token::Match(tok, "* %var% == 0|false")) { tok = tok->previous(); tok->insertToken("!"); @@ -4610,10 +4610,10 @@ void Tokenizer::simplifyIfNot() } } - else if(tok->link() && Token::Match(tok, ") == 0|false")) + else if (tok->link() && Token::Match(tok, ") == 0|false")) { Token::eraseTokens(tok, tok->tokAt(3)); - if(Token::Match(tok->link()->previous(), "%var%")) + if (Token::Match(tok->link()->previous(), "%var%")) { // if( foo(x) == 0 ) tok->link()->previous()->insertToken(tok->link()->previous()->str().c_str()); @@ -4635,38 +4635,38 @@ void Tokenizer::simplifyIfNot() void Tokenizer::simplifyIfNotNull() { - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { Token *deleteFrom = NULL; - if(tok->str() == "(" || tok->str() == "||" || tok->str() == "&&") + if (tok->str() == "(" || tok->str() == "||" || tok->str() == "&&") { tok = tok->next(); - if(Token::simpleMatch(tok, "0 != (") || - Token::Match(tok, "0 != %var%")) + if (Token::simpleMatch(tok, "0 != (") || + Token::Match(tok, "0 != %var%")) { deleteFrom = tok->previous(); } - else if(Token::Match(tok, "%var% != 0")) + else if (Token::Match(tok, "%var% != 0")) { deleteFrom = tok; } - else if(Token::Match(tok, "%var% .|:: %var% != 0")) + else if (Token::Match(tok, "%var% .|:: %var% != 0")) { tok = tok->tokAt(2); deleteFrom = tok; } } - else if(tok->link() && Token::simpleMatch(tok, ") != 0")) + else if (tok->link() && Token::simpleMatch(tok, ") != 0")) { deleteFrom = tok; } - if(deleteFrom) + if (deleteFrom) { Token::eraseTokens(deleteFrom, deleteFrom->tokAt(3)); tok = deleteFrom; @@ -4678,24 +4678,24 @@ void Tokenizer::simplifyIfNotNull() void Tokenizer::simplifyIfSameInnerCondition() { // same inner condition - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(Token::Match(tok, "if ( %var% ) {")) + if (Token::Match(tok, "if ( %var% ) {")) { const unsigned int varid(tok->tokAt(2)->varId()); - if(!varid) + if (!varid) continue; - for(Token *tok2 = tok->tokAt(5); tok2; tok2 = tok2->next()) + for (Token *tok2 = tok->tokAt(5); tok2; tok2 = tok2->next()) { - if(tok2->str() == "{" || tok2->str() == "}") + if (tok2->str() == "{" || tok2->str() == "}") break; - if(Token::simpleMatch(tok2, "if (")) + if (Token::simpleMatch(tok2, "if (")) { tok2 = tok2->tokAt(2); - if(Token::Match(tok2, "%varid% )", varid)) + if (Token::Match(tok2, "%varid% )", varid)) tok2->str("true"); - else if(Token::Match(tok2, "! %varid% )", varid)) + else if (Token::Match(tok2, "! %varid% )", varid)) tok2->next()->varId(varid); break; } @@ -4709,24 +4709,24 @@ void Tokenizer::simplifyLogicalOperators() { // "if (not p)" => "if (!p)" // "if (p and q)" => "if (p and q)" - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(Token::Match(tok, "if|while ( not %var%")) + if (Token::Match(tok, "if|while ( not %var%")) { tok->tokAt(2)->str("!"); } - else if(Token::Match(tok, "&& not %var%")) + else if (Token::Match(tok, "&& not %var%")) { tok->next()->str("!"); } - else if(Token::Match(tok, "|| not %var%")) + else if (Token::Match(tok, "|| not %var%")) { tok->next()->str("!"); } // "%var%|) and %var%|(" - else if(tok->str() == "and" && - ((Token::Match(tok->previous(), "%var%") || tok->previous()->str() == ")") || - (Token::Match(tok->next(), "%var%") || tok->next()->str() == "("))) + else if (tok->str() == "and" && + ((Token::Match(tok->previous(), "%var%") || tok->previous()->str() == ")") || + (Token::Match(tok->next(), "%var%") || tok->next()->str() == "("))) { tok->str("&&"); } @@ -4736,17 +4736,17 @@ void Tokenizer::simplifyLogicalOperators() void Tokenizer::simplifyInitVar() { - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(Token::Match(tok, "[{};] %type% *| %var% ( %num% ) ;")) + if (Token::Match(tok, "[{};] %type% *| %var% ( %num% ) ;")) { // call constructor of class => no simplification - if(!tok->next()->isStandardType() && tok->tokAt(2)->str() != "*") + if (!tok->next()->isStandardType() && tok->tokAt(2)->str() != "*") continue; // goto variable name.. tok = tok->tokAt(2); - if(tok->str() == "*") + if (tok->str() == "*") tok = tok->next(); // insert '=' @@ -4763,67 +4763,67 @@ void Tokenizer::simplifyInitVar() bool Tokenizer::simplifyKnownVariables() { bool ret = false; - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { // Search for a block of code - if(! Token::Match(tok, ") const| {")) + if (! Token::Match(tok, ") const| {")) continue; // parse the block of code.. int indentlevel = 0; Token *tok2 = tok; - for(; tok2; tok2 = tok2->next()) + for (; tok2; tok2 = tok2->next()) { - if(tok2->str() == "{") + if (tok2->str() == "{") ++indentlevel; - else if(tok2->str() == "}") + else if (tok2->str() == "}") { --indentlevel; - if(indentlevel <= 0) + if (indentlevel <= 0) break; } - else if(tok2->previous()->str() != "*" && - (Token::Match(tok2, "%var% = %num% ;") || - Token::Match(tok2, "%var% = %str% ;") || - Token::Match(tok2, "%var% [ ] = %str% ;") || - Token::Match(tok2, "%var% = %bool% ;") || - Token::Match(tok2, "%var% = %var% ;") || - Token::Match(tok2, "%var% = & %var% ;"))) + else if (tok2->previous()->str() != "*" && + (Token::Match(tok2, "%var% = %num% ;") || + Token::Match(tok2, "%var% = %str% ;") || + Token::Match(tok2, "%var% [ ] = %str% ;") || + Token::Match(tok2, "%var% = %bool% ;") || + Token::Match(tok2, "%var% = %var% ;") || + Token::Match(tok2, "%var% = & %var% ;"))) { const unsigned int varid = tok2->varId(); - if(varid == 0) + if (varid == 0) continue; - if(tok2->str() == tok2->strAt(2)) + if (tok2->str() == tok2->strAt(2)) continue; const bool pointeralias(tok2->tokAt(2)->isName() || tok2->tokAt(2)->str() == "&"); std::string value(tok2->strAt(2)); - if(value == "]") + if (value == "]") value = tok2->strAt(4); - else if(value == "&") + else if (value == "&") value = tok2->strAt(3); Token* bailOutFromLoop = 0; - if(Token::simpleMatch(tok2->next(), "= &")) + if (Token::simpleMatch(tok2->next(), "= &")) tok2 = tok2->tokAt(3); int indentlevel3 = indentlevel; // indentlevel for tok3 - for(Token *tok3 = tok2->next(); tok3; tok3 = tok3->next()) + for (Token *tok3 = tok2->next(); tok3; tok3 = tok3->next()) { - if(tok3->str() == "{") + if (tok3->str() == "{") { ++indentlevel3; } - else if(tok3->str() == "}") + else if (tok3->str() == "}") { --indentlevel3; - if(indentlevel3 < indentlevel) + if (indentlevel3 < indentlevel) { - if(Token::Match(tok2->tokAt(-7), "%type% * %var% ; %var% = & %var% ;") && - tok2->tokAt(-5)->str() == tok2->tokAt(-3)->str()) + if (Token::Match(tok2->tokAt(-7), "%type% * %var% ; %var% = & %var% ;") && + tok2->tokAt(-5)->str() == tok2->tokAt(-3)->str()) { tok2 = tok2->tokAt(-4); Token::eraseTokens(tok2, tok2->tokAt(5)); @@ -4832,39 +4832,39 @@ bool Tokenizer::simplifyKnownVariables() } } - if(pointeralias && Token::Match(tok3, ("!!= " + value).c_str())) + if (pointeralias && Token::Match(tok3, ("!!= " + value).c_str())) break; // Stop if something like 'while (--var)' is found - if(tok3->str() == "while" || tok3->str() == "do") + if (tok3->str() == "while" || tok3->str() == "do") { const Token *endpar = tok3->next()->link(); bool bailout = false; - for(const Token *tok4 = tok3; tok4 && tok4 != endpar; tok4 = tok4->next()) + for (const Token *tok4 = tok3; tok4 && tok4 != endpar; tok4 = tok4->next()) { - if(Token::Match(tok4, "++|-- %varid%", varid) || - Token::Match(tok4, "%varid% ++|--|=", varid)) + if (Token::Match(tok4, "++|-- %varid%", varid) || + Token::Match(tok4, "%varid% ++|--|=", varid)) { bailout = true; break; } } - if(bailout) + if (bailout) break; } - if(bailOutFromLoop) + if (bailOutFromLoop) { // This could be a loop, skip it, but only if it doesn't contain // the variable we are checking for. If it contains the variable // we will bail out. - if(tok3->varId() == varid) + if (tok3->varId() == varid) { // Continue tok2 = bailOutFromLoop; break; } - else if(tok3 == bailOutFromLoop) + else if (tok3 == bailOutFromLoop) { // We have skipped the loop bailOutFromLoop = 0; @@ -4873,29 +4873,29 @@ bool Tokenizer::simplifyKnownVariables() continue; } - else if(tok3->str() == "{" && tok3->previous()->str() == ")") + else if (tok3->str() == "{" && tok3->previous()->str() == ")") { // There is a possible loop after the assignment. Try to skip it. - if(tok3->previous()->link() && - !Token::simpleMatch(tok3->previous()->link()->previous(), "if")) + if (tok3->previous()->link() && + !Token::simpleMatch(tok3->previous()->link()->previous(), "if")) bailOutFromLoop = tok3->link(); continue; } - else if(tok3->str() == "}" && tok3->link() && tok3->link()->previous()->str() == ")") + else if (tok3->str() == "}" && tok3->link() && tok3->link()->previous()->str() == ")") { // Assignment was in the middle of possible loop, bail out. break; } // Variable is used somehow in a non-defined pattern => bail out - if(tok3->varId() == varid) + if (tok3->varId() == varid) break; // Using the variable in condition.. - if(Token::Match(tok3->previous(), "if ( %varid% ==|!=|<|<=|>|>=|)", varid) || - Token::Match(tok3, "( %varid% ==|!=|<|<=|>|>=", varid) || - Token::Match(tok3, "!|==|!=|<|<=|>|>= %varid% ==|!=|<|<=|>|>=|)", varid) || - Token::Match(tok3->previous(), "strlen|free ( %varid% )", varid)) + if (Token::Match(tok3->previous(), "if ( %varid% ==|!=|<|<=|>|>=|)", varid) || + Token::Match(tok3, "( %varid% ==|!=|<|<=|>|>=", varid) || + Token::Match(tok3, "!|==|!=|<|<=|>|>= %varid% ==|!=|<|<=|>|>=|)", varid) || + Token::Match(tok3->previous(), "strlen|free ( %varid% )", varid)) { tok3 = tok3->next(); tok3->str(value); @@ -4903,9 +4903,9 @@ bool Tokenizer::simplifyKnownVariables() } // Variable is used in calculation.. - if(Token::Match(tok3, "[=+-*/[] %varid% [?+-*/;]]", varid) || - Token::Match(tok3, "[=+-*/[] %varid% <<", varid) || - Token::Match(tok3, "<< %varid% [+-*/;]]", varid)) + if (Token::Match(tok3, "[=+-*/[] %varid% [?+-*/;]]", varid) || + Token::Match(tok3, "[=+-*/[] %varid% <<", varid) || + Token::Match(tok3, "<< %varid% [+-*/;]]", varid)) { tok3 = tok3->next(); tok3->str(value); @@ -4913,28 +4913,28 @@ bool Tokenizer::simplifyKnownVariables() } // Using the variable in for-condition.. - if(Token::simpleMatch(tok3, "for (")) + if (Token::simpleMatch(tok3, "for (")) { - for(Token *tok4 = tok3->tokAt(2); tok4; tok4 = tok4->next()) + for (Token *tok4 = tok3->tokAt(2); tok4; tok4 = tok4->next()) { - if(tok4->str() == "(" || tok4->str() == ")") + if (tok4->str() == "(" || tok4->str() == ")") break; // Replace variable used in condition.. - if(Token::Match(tok4, "; %var% <|<=|!= %var% ; ++| %var% ++| )")) + if (Token::Match(tok4, "; %var% <|<=|!= %var% ; ++| %var% ++| )")) { const Token *inctok = tok4->tokAt(5); - if(inctok->str() == "++") + if (inctok->str() == "++") inctok = inctok->next(); - if(inctok->varId() == varid) + if (inctok->varId() == varid) break; - if(tok4->next()->varId() == varid) + if (tok4->next()->varId() == varid) { tok4->next()->str(value); ret = true; } - if(tok4->tokAt(3)->varId() == varid) + if (tok4->tokAt(3)->varId() == varid) { tok4->tokAt(3)->str(value); ret = true; @@ -4942,22 +4942,22 @@ bool Tokenizer::simplifyKnownVariables() } } - if(tok3->next()->varId() == varid) + if (tok3->next()->varId() == varid) { tok3->next()->str(value); ret = true; } - else if(tok3->tokAt(3)->varId() == varid) + else if (tok3->tokAt(3)->varId() == varid) { tok3->tokAt(3)->str(value); ret = true; } } - if(Token::Match(tok3->next(), "%varid% ++|--", varid) && MathLib::isInt(value)) + if (Token::Match(tok3->next(), "%varid% ++|--", varid) && MathLib::isInt(value)) { const std::string op(tok3->strAt(2)); - if(Token::Match(tok3, "[{};] %any% %any% ;")) + if (Token::Match(tok3, "[{};] %any% %any% ;")) { Token::eraseTokens(tok3, tok3->tokAt(3)); } @@ -4972,12 +4972,12 @@ bool Tokenizer::simplifyKnownVariables() ret = true; } - if(Token::Match(tok3->next(), "++|-- %varid%", varid) && MathLib::isInt(value) && - !Token::Match(tok3->tokAt(3), "[.[]")) + if (Token::Match(tok3->next(), "++|-- %varid%", varid) && MathLib::isInt(value) && + !Token::Match(tok3->tokAt(3), "[.[]")) { incdec(value, tok3->strAt(1)); tok2->tokAt(2)->str(value); - if(Token::Match(tok3, "[;{}] %any% %any% ;")) + if (Token::Match(tok3, "[;{}] %any% %any% ;")) { Token::eraseTokens(tok3, tok3->tokAt(3)); } @@ -4991,12 +4991,12 @@ bool Tokenizer::simplifyKnownVariables() } // return variable.. - if(Token::Match(tok3, "return %varid% ;", varid)) + if (Token::Match(tok3, "return %varid% ;", varid)) { tok3->next()->str(value); } - else if(pointeralias && Token::Match(tok3, "return * %varid% ;", varid)) + else if (pointeralias && Token::Match(tok3, "return * %varid% ;", varid)) { tok3->deleteNext(); tok3->next()->str(value); @@ -5005,7 +5005,7 @@ bool Tokenizer::simplifyKnownVariables() } } - if(tok2) + if (tok2) tok = tok2->previous(); } @@ -5015,21 +5015,21 @@ bool Tokenizer::simplifyKnownVariables() void Tokenizer::elseif() { - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(!Token::simpleMatch(tok, "else if")) + if (!Token::simpleMatch(tok, "else if")) continue; int indent = 0; - for(Token *tok2 = tok; indent >= 0 && tok2; tok2 = tok2->next()) + for (Token *tok2 = tok; indent >= 0 && tok2; tok2 = tok2->next()) { - if(Token::Match(tok2, "(|{")) + if (Token::Match(tok2, "(|{")) ++indent; - else if(Token::Match(tok2, ")|}")) + else if (Token::Match(tok2, ")|}")) --indent; - if(indent == 0 && Token::Match(tok2, "}|;")) + if (indent == 0 && Token::Match(tok2, "}|;")) { - if(tok2->next() && tok2->next()->str() != "else") + if (tok2->next() && tok2->next()->str() != "else") { tok->insertToken("{"); tok2->insertToken("}"); @@ -5045,13 +5045,13 @@ void Tokenizer::elseif() bool Tokenizer::simplifyRedundantParanthesis() { bool ret = false; - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(tok->str() != "(") + if (tok->str() != "(") continue; - while(Token::simpleMatch(tok, "( (") && - tok->link()->previous() == tok->next()->link()) + while (Token::simpleMatch(tok, "( (") && + tok->link()->previous() == tok->next()->link()) { // We have "(( *something* ))", remove the inner // paranthesis @@ -5060,8 +5060,8 @@ bool Tokenizer::simplifyRedundantParanthesis() ret = true; } - while(Token::Match(tok->previous(), "[;{] ( %var% (") && - tok->link()->previous() == tok->tokAt(2)->link()) + while (Token::Match(tok->previous(), "[;{] ( %var% (") && + tok->link()->previous() == tok->tokAt(2)->link()) { // We have "( func ( *something* ))", remove the outer // paranthesis @@ -5070,7 +5070,7 @@ bool Tokenizer::simplifyRedundantParanthesis() ret = true; } - while(Token::Match(tok->previous(), "[;{] ( delete %var% ) ;")) + while (Token::Match(tok->previous(), "[;{] ( delete %var% ) ;")) { // We have "( delete var )", remove the outer // paranthesis @@ -5079,7 +5079,7 @@ bool Tokenizer::simplifyRedundantParanthesis() ret = true; } - while(Token::Match(tok->previous(), "[;{] ( delete [ ] %var% ) ;")) + while (Token::Match(tok->previous(), "[;{] ( delete [ ] %var% ) ;")) { // We have "( delete [] var )", remove the outer // paranthesis @@ -5088,7 +5088,7 @@ bool Tokenizer::simplifyRedundantParanthesis() ret = true; } - if(Token::Match(tok->previous(), "[(!*;{}] ( %var% )") && tok->next()->varId() != 0) + if (Token::Match(tok->previous(), "[(!*;{}] ( %var% )") && tok->next()->varId() != 0) { // We have "( var )", remove the paranthesis tok->deleteThis(); @@ -5097,7 +5097,7 @@ bool Tokenizer::simplifyRedundantParanthesis() continue; } - if(Token::Match(tok->previous(), "[(!] ( %var% . %var% )")) + if (Token::Match(tok->previous(), "[(!] ( %var% . %var% )")) { // We have "( var . var )", remove the paranthesis tok->deleteThis(); @@ -5107,8 +5107,8 @@ bool Tokenizer::simplifyRedundantParanthesis() continue; } - if(Token::Match(tok, "( ( %bool% )") || - Token::Match(tok, "( ( %num% )")) + if (Token::Match(tok, "( ( %bool% )") || + Token::Match(tok, "( ( %num% )")) { tok->tokAt(2)->deleteNext(); tok->deleteNext(); @@ -5120,28 +5120,28 @@ bool Tokenizer::simplifyRedundantParanthesis() void Tokenizer::simplifyReference() { - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { // starting executable scope.. - if(Token::Match(tok, ") const| {")) + if (Token::Match(tok, ") const| {")) { // replace references in this scope.. - if(tok->next()->str() != "{") + if (tok->next()->str() != "{") tok = tok->next(); Token * const end = tok->next()->link(); - for(Token *tok2 = tok; tok2 && tok2 != end; tok2 = tok2->next()) + for (Token *tok2 = tok; tok2 && tok2 != end; tok2 = tok2->next()) { // found a reference.. - if(Token::Match(tok2, "[;{}] %type% & %var% (|= %var% )| ;")) + if (Token::Match(tok2, "[;{}] %type% & %var% (|= %var% )| ;")) { const unsigned int ref_id = tok2->tokAt(3)->varId(); - if(!ref_id) + if (!ref_id) continue; // replace reference in the code.. - for(Token *tok3 = tok2->tokAt(7); tok3 && tok3 != end; tok3 = tok3->next()) + for (Token *tok3 = tok2->tokAt(7); tok3 && tok3 != end; tok3 = tok3->next()) { - if(tok3->varId() == ref_id) + if (tok3->varId() == ref_id) { tok3->str(tok2->strAt(5)); tok3->varId(tok2->tokAt(5)->varId()); @@ -5158,38 +5158,38 @@ void Tokenizer::simplifyReference() bool Tokenizer::simplifyCalculations() { bool ret = false; - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(Token::simpleMatch(tok->next(), "* 1") || Token::simpleMatch(tok->next(), "1 *")) + if (Token::simpleMatch(tok->next(), "* 1") || Token::simpleMatch(tok->next(), "1 *")) { Token::eraseTokens(tok, tok->tokAt(3)); ret = true; } // (1-2) - while(Token::Match(tok, "[[,(=<>+-*] %num% [+-*/] %num% [],);=<>+-*/]") || - Token::Match(tok, "<< %num% [+-*/] %num% [],);=<>+-*/]") || - Token::Match(tok, "[[,(=<>+-*] %num% [+-*/] %num% <<") || - Token::Match(tok, "<< %num% [+-*/] %num% <<")) + while (Token::Match(tok, "[[,(=<>+-*] %num% [+-*/] %num% [],);=<>+-*/]") || + Token::Match(tok, "<< %num% [+-*/] %num% [],);=<>+-*/]") || + Token::Match(tok, "[[,(=<>+-*] %num% [+-*/] %num% <<") || + Token::Match(tok, "<< %num% [+-*/] %num% <<")) { tok = tok->next(); // Don't simplify "%num% / 0" - if(Token::simpleMatch(tok->next(), "/ 0")) + if (Token::simpleMatch(tok->next(), "/ 0")) continue; // + and - are calculated after * and / - if(Token::Match(tok->next(), "[+-/]")) + if (Token::Match(tok->next(), "[+-/]")) { - if(tok->previous()->str() == "*") + if (tok->previous()->str() == "*") continue; - if(Token::Match(tok->tokAt(3), "[*/]")) + if (Token::Match(tok->tokAt(3), "[*/]")) continue; } - if(Token::Match(tok->previous(), "- %num% - %num%")) + if (Token::Match(tok->previous(), "- %num% - %num%")) tok->str(MathLib::calculate(tok->str(), tok->tokAt(2)->str(), '+')); - else if(Token::Match(tok->previous(), "- %num% + %num%")) + else if (Token::Match(tok->previous(), "- %num% + %num%")) tok->str(MathLib::calculate(tok->str(), tok->tokAt(2)->str(), '-')); else tok->str(MathLib::calculate(tok->str(), tok->tokAt(2)->str(), tok->strAt(1)[0])); @@ -5199,7 +5199,7 @@ bool Tokenizer::simplifyCalculations() // evaluate "2 + 2 - 2 - 2" // as (((2 + 2) - 2) - 2) = 0 // instead of ((2 + 2) - (2 - 2)) = 4 - if(Token::Match(tok->next(), "[+-*/]")) + if (Token::Match(tok->next(), "[+-*/]")) { tok = tok->previous(); continue; @@ -5209,7 +5209,7 @@ bool Tokenizer::simplifyCalculations() } // Remove parantheses around number.. - if(!tok->isName() && Token::Match(tok->next(), "( %num% )")) + if (!tok->isName() && Token::Match(tok->next(), "( %num% )")) { tok->deleteNext(); tok = tok->next(); @@ -5220,7 +5220,7 @@ bool Tokenizer::simplifyCalculations() // Remove parantheses around variable.. // keep parantheses here: dynamic_cast(p); // keep parantheses here: A operator * (int); - if(!tok->isName() && tok->str() != ">" && Token::Match(tok->next(), "( %var% ) [;),+-*/><]]") && !Token::simpleMatch(tok->previous(), "operator")) + if (!tok->isName() && tok->str() != ">" && Token::Match(tok->next(), "( %var% ) [;),+-*/><]]") && !Token::simpleMatch(tok->previous(), "operator")) { tok->deleteNext(); tok = tok->next(); @@ -5228,22 +5228,22 @@ bool Tokenizer::simplifyCalculations() ret = true; } - if(Token::simpleMatch(tok->previous(), "( 0 ||") || - Token::simpleMatch(tok, "|| 0 )") || - Token::simpleMatch(tok->previous(), "( 1 &&") || - Token::simpleMatch(tok, "&& 1 )")) + if (Token::simpleMatch(tok->previous(), "( 0 ||") || + Token::simpleMatch(tok, "|| 0 )") || + Token::simpleMatch(tok->previous(), "( 1 &&") || + Token::simpleMatch(tok, "&& 1 )")) { tok->deleteThis(); tok->deleteThis(); } - if(Token::Match(tok, "%num% ==|!=|<=|>=|<|> %num%") && - MathLib::isInt(tok->str()) && - MathLib::isInt(tok->tokAt(2)->str())) + if (Token::Match(tok, "%num% ==|!=|<=|>=|<|> %num%") && + MathLib::isInt(tok->str()) && + MathLib::isInt(tok->tokAt(2)->str())) { const std::string prev(tok->previous() ? tok->strAt(-1).c_str() : ""); const std::string after(tok->tokAt(3) ? tok->strAt(3).c_str() : ""); - if((prev == "(" || prev == "&&" || prev == "||") && (after == ")" || after == "&&" || after == "||")) + if ((prev == "(" || prev == "&&" || prev == "||") && (after == ")" || after == "&&" || after == "||")) { const int op1(MathLib::toLongNumber(tok->str())); const std::string &cmp(tok->next()->str()); @@ -5251,17 +5251,17 @@ bool Tokenizer::simplifyCalculations() std::string result; - if(cmp == "==") + if (cmp == "==") result = (op1 == op2) ? "1" : "0"; - else if(cmp == "!=") + else if (cmp == "!=") result = (op1 != op2) ? "1" : "0"; - else if(cmp == "<=") + else if (cmp == "<=") result = (op1 <= op2) ? "1" : "0"; - else if(cmp == ">=") + else if (cmp == ">=") result = (op1 >= op2) ? "1" : "0"; - else if(cmp == "<") + else if (cmp == "<") result = (op1 < op2) ? "1" : "0"; - else if(cmp == ">") + else if (cmp == ">") result = (op1 > op2) ? "1" : "0"; tok->str(result); @@ -5270,13 +5270,13 @@ bool Tokenizer::simplifyCalculations() } } - if(Token::Match(tok, "%num% <<|>> %num%")) + if (Token::Match(tok, "%num% <<|>> %num%")) { const int op1(MathLib::toLongNumber(tok->str())); const int op2(MathLib::toLongNumber(tok->tokAt(2)->str())); int result; - if(tok->next()->str() == "<<") + if (tok->next()->str() == "<<") result = op1 << op2; else result = op1 >> op2; @@ -5300,78 +5300,78 @@ void Tokenizer::simplifyGoto() std::list gotos; unsigned int indentlevel = 0; Token *beginfunction = 0; - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(tok->str() == "{") + if (tok->str() == "{") { - if(beginfunction == 0 && indentlevel == 0 && tok->link()) + if (beginfunction == 0 && indentlevel == 0 && tok->link()) tok = tok->link(); else ++indentlevel; } - else if(tok->str() == "}") + else if (tok->str() == "}") { - if(indentlevel == 0) + if (indentlevel == 0) break; // break out - it seems the code is wrong --indentlevel; - if(indentlevel == 0) + if (indentlevel == 0) { gotos.clear(); beginfunction = 0; } } - else if(indentlevel == 0 && Token::Match(tok, ") const| {")) + else if (indentlevel == 0 && Token::Match(tok, ") const| {")) { gotos.clear(); beginfunction = tok; } - else if(Token::Match(tok, "goto %var% ;")) + else if (Token::Match(tok, "goto %var% ;")) gotos.push_back(tok); - else if(indentlevel == 1 && Token::Match(tok->previous(), "[};] %var% :")) + else if (indentlevel == 1 && Token::Match(tok->previous(), "[};] %var% :")) { // Is this label at the end.. bool end = false; int lev = 0; - for(const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) + for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) { - if(tok2->str() == "}") + if (tok2->str() == "}") { --lev; - if(lev < 0) + if (lev < 0) { end = true; break; } } - else if(tok2->str() == "{") + else if (tok2->str() == "{") { ++lev; } - if(Token::Match(tok2, "%var% :") || tok2->str() == "goto") + if (Token::Match(tok2, "%var% :") || tok2->str() == "goto") { break; } } - if(!end) + if (!end) continue; const std::string name(tok->str()); tok->deleteThis(); tok->deleteThis(); - if(Token::Match(tok, "; %any%")) + if (Token::Match(tok, "; %any%")) tok->deleteThis(); // This label is at the end of the function.. replace all matching goto statements.. - for(std::list::iterator it = gotos.begin(); it != gotos.end(); ++it) + for (std::list::iterator it = gotos.begin(); it != gotos.end(); ++it) { Token *token = *it; - if(token->next()->str() == name) + if (token->next()->str() == name) { // Delete the "goto name;" token = token->previous(); @@ -5386,39 +5386,39 @@ void Tokenizer::simplifyGoto() std::list links2; std::list links3; int lev = 0; - for(const Token *tok2 = tok; tok2; tok2 = tok2->next()) + for (const Token *tok2 = tok; tok2; tok2 = tok2->next()) { - if(tok2->str() == "}") + if (tok2->str() == "}") { --lev; - if(lev < 0) + if (lev < 0) break; } - if(tok2->str() == "{") + if (tok2->str() == "{") { ++lev; } - else if(tok2->str() == "return") + else if (tok2->str() == "return") { ret = true; - if(indentlevel == 1 && lev == 0) + if (indentlevel == 1 && lev == 0) ret2 = true; } token->insertToken(tok2->str().c_str()); token = token->next(); token->linenr(tok2->linenr()); token->varId(tok2->varId()); - if(ret2 && tok2->str() == ";") + if (ret2 && tok2->str() == ";") { break; } - if(token->str() == "(") + if (token->str() == "(") { links.push_back(token); } - else if(token->str() == ")") + else if (token->str() == ")") { - if(links.empty()) + if (links.empty()) { // This should never happen at this point syntaxError(token, ')'); @@ -5428,13 +5428,13 @@ void Tokenizer::simplifyGoto() Token::createMutualLinks(links.back(), token); links.pop_back(); } - else if(token->str() == "{") + else if (token->str() == "{") { links2.push_back(token); } - else if(token->str() == "}") + else if (token->str() == "}") { - if(links2.empty()) + if (links2.empty()) { // This should never happen at this point syntaxError(token, '}'); @@ -5444,13 +5444,13 @@ void Tokenizer::simplifyGoto() Token::createMutualLinks(links2.back(), token); links2.pop_back(); } - else if(token->str() == "[") + else if (token->str() == "[") { links3.push_back(token); } - else if(token->str() == "]") + else if (token->str() == "]") { - if(links3.empty()) + if (links3.empty()) { // This should never happen at this point syntaxError(token, ']'); @@ -5462,7 +5462,7 @@ void Tokenizer::simplifyGoto() } } - if(!ret) + if (!ret) { token->insertToken("return"); token = token->next(); @@ -5482,16 +5482,16 @@ void Tokenizer::simplifyGoto() void Tokenizer::simplifyNestedStrcat() { - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(! Token::Match(tok, "[;{}] strcat ( strcat (")) + if (! Token::Match(tok, "[;{}] strcat ( strcat (")) { continue; } // find inner strcat call Token *tok2 = tok->tokAt(3); - while(Token::simpleMatch(tok2, "strcat ( strcat")) + while (Token::simpleMatch(tok2, "strcat ( strcat")) { tok2 = tok2->tokAt(2); } @@ -5517,7 +5517,7 @@ void Tokenizer::simplifyNestedStrcat() void Tokenizer::duplicateEnumError(const Token * tok1, const Token * tok2, const std::string & type) { - if(!(_settings && _settings->_checkCodingStyle)) + if (!(_settings && _settings->_checkCodingStyle)) return; std::list locationList; @@ -5532,10 +5532,10 @@ void Tokenizer::duplicateEnumError(const Token * tok1, const Token * tok2, const const ErrorLogger::ErrorMessage errmsg(locationList, "style", std::string(type + " '" + tok2->str() + - "' hides enumerator with same name"), + "' hides enumerator with same name"), "variableHidingEnum"); - if(_errorLogger) + if (_errorLogger) _errorLogger->reportErr(errmsg); else Check::reportError(errmsg); @@ -5548,48 +5548,48 @@ bool Tokenizer::duplicateDefinition(Token ** tokPtr, const Token * name) { // check for an end of definition const Token * tok = *tokPtr; - if(tok && tok->next() && Token::Match(tok->next(), ";|,|[|=|)|>")) + if (tok && tok->next() && Token::Match(tok->next(), ";|,|[|=|)|>")) { const Token * end = tok->next(); - if(end->str() == "[") + if (end->str() == "[") { end = end->link()->next(); } - else if(end->str() == ",") + else if (end->str() == ",") { // check for function argument - if(Token::Match(tok->previous(), "(|,")) + if (Token::Match(tok->previous(), "(|,")) return false; // find end of definition int level = 0; - while(end && end->next() && (!Token::Match(end->next(), ";|)|>") || - (end->next()->str() == ")" && level == 0))) + while (end && end->next() && (!Token::Match(end->next(), ";|)|>") || + (end->next()->str() == ")" && level == 0))) { - if(end->next()->str() == "(") + if (end->next()->str() == "(") level++; - else if(end->next()->str() == ")") + else if (end->next()->str() == ")") level--; end = end->next(); } } - else if(end->str() == ")") + else if (end->str() == ")") { // check of function argument - if(tok->previous()->str() == ",") + if (tok->previous()->str() == ",") return false; } - if(end) + if (end) { - if(Token::Match(end, ") {")) // function parameter ? + if (Token::Match(end, ") {")) // function parameter ? { // look backwards - if(tok->previous()->str() == "enum" || - (Token::Match(tok->previous(), "%type%") && - tok->previous()->str() != "return")) + if (tok->previous()->str() == "enum" || + (Token::Match(tok->previous(), "%type%") && + tok->previous()->str() != "return")) { duplicateEnumError(*tokPtr, name, "Function parameter"); // duplicate definition so skip entire function @@ -5597,17 +5597,17 @@ bool Tokenizer::duplicateDefinition(Token ** tokPtr, const Token * name) return true; } } - else if(end->str() == ">") // template parameter ? + else if (end->str() == ">") // template parameter ? { // look backwards - if(tok->previous()->str() == "enum" || - (Token::Match(tok->previous(), "%type%") && - tok->previous()->str() != "return")) + if (tok->previous()->str() == "enum" || + (Token::Match(tok->previous(), "%type%") && + tok->previous()->str() != "return")) { // duplicate definition so skip entire template - while(end && end->str() != "{") + while (end && end->str() != "{") end = end->next(); - if(end) + if (end) { duplicateEnumError(*tokPtr, name, "Template parameter"); *tokPtr = end->link(); @@ -5618,9 +5618,9 @@ bool Tokenizer::duplicateDefinition(Token ** tokPtr, const Token * name) else { // look backwards - if(Token::Match(tok->previous(), "enum|,") || - (Token::Match(tok->previous(), "%type%") && - tok->previous()->str() != "return")) + if (Token::Match(tok->previous(), "enum|,") || + (Token::Match(tok->previous(), "%type%") && + tok->previous()->str() != "return")) { duplicateEnumError(*tokPtr, name, "Variable"); return true; @@ -5635,36 +5635,36 @@ void Tokenizer::simplifyEnum() { std::string className; int classLevel = 0; - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(Token::Match(tok, "class|struct|namespace %any%")) + if (Token::Match(tok, "class|struct|namespace %any%")) { className = tok->next()->str(); classLevel = 0; continue; } - else if(tok->str() == "}") + else if (tok->str() == "}") { --classLevel; - if(classLevel < 0) + if (classLevel < 0) className = ""; continue; } - else if(tok->str() == "{") + else if (tok->str() == "{") { ++classLevel; continue; } - else if(Token::Match(tok, "enum {") || - Token::Match(tok, "enum %type% {")) + else if (Token::Match(tok, "enum {") || + Token::Match(tok, "enum %type% {")) { Token * tok1; Token * start = tok; Token * end; Token * enumType = 0; - if(tok->tokAt(1)->str() == "{") + if (tok->tokAt(1)->str() == "{") tok1 = tok->tokAt(2); else { @@ -5681,20 +5681,20 @@ void Tokenizer::simplifyEnum() // iterate over all enumerators between { and } // Give each enumerator the const value specified or if not specified, 1 + the // previous value or 0 if it is the first one. - for(; tok1 && tok1 != end; tok1 = tok1->next()) + for (; tok1 && tok1 != end; tok1 = tok1->next()) { Token * enumName = 0; Token * enumValue = 0; Token * enumValueStart = 0; Token * enumValueEnd = 0; - if(tok1->str() == "(") + if (tok1->str() == "(") { tok1 = tok1->link(); continue; } - if(Token::Match(tok1->previous(), ",|{ %type% ,|}")) + if (Token::Match(tok1->previous(), ",|{ %type% ,|}")) { // no value specified enumName = tok1; @@ -5702,20 +5702,20 @@ void Tokenizer::simplifyEnum() tok1->insertToken("="); tok1 = tok1->next(); - if(lastEnumValueStart && lastEnumValueEnd) + if (lastEnumValueStart && lastEnumValueEnd) { // previous value was an expression Token * valueStart = tok1; std::stack links; - for(Token *tok2 = lastEnumValueStart; tok2 != lastEnumValueEnd->next(); tok2 = tok2->next()) + for (Token *tok2 = lastEnumValueStart; tok2 != lastEnumValueEnd->next(); tok2 = tok2->next()) { tok1->insertToken(tok2->str()); tok1 = tok1->next(); // Check for links and fix them up - if(tok1->str() == "(" || tok1->str() == "[" || tok1->str() == "{") + if (tok1->str() == "(" || tok1->str() == "[" || tok1->str() == "{") links.push(tok1); - else if(tok1->str() == ")" || tok1->str() == "]" || tok1->str() == "}") + else if (tok1->str() == ")" || tok1->str() == "]" || tok1->str() == "}") { Token * link = links.top(); @@ -5741,7 +5741,7 @@ void Tokenizer::simplifyEnum() enumValue = tok1->next(); } } - else if(Token::Match(tok1->previous(), ",|{ %type% = %num% ,|}")) + else if (Token::Match(tok1->previous(), ",|{ %type% = %num% ,|}")) { // value is specified numeric value enumName = tok1; @@ -5750,7 +5750,7 @@ void Tokenizer::simplifyEnum() lastEnumValueStart = 0; lastEnumValueEnd = 0; } - else if(Token::Match(tok1->previous(), ",|{ %type% = ")) + else if (Token::Match(tok1->previous(), ",|{ %type% = ")) { // value is specified expression enumName = tok1; @@ -5759,20 +5759,20 @@ void Tokenizer::simplifyEnum() enumValueStart = tok1; enumValueEnd = tok1; int level = 0; - if(enumValueEnd->str() == "(" || - enumValueEnd->str() == "[" || - enumValueEnd->str() == "{") + if (enumValueEnd->str() == "(" || + enumValueEnd->str() == "[" || + enumValueEnd->str() == "{") level++; - while(enumValueEnd->next() && - (!Token::Match(enumValueEnd->next(), "}|,") || level)) + while (enumValueEnd->next() && + (!Token::Match(enumValueEnd->next(), "}|,") || level)) { - if(enumValueEnd->next()->str() == "(" || - enumValueEnd->next()->str() == "[" || - enumValueEnd->next()->str() == "{") + if (enumValueEnd->next()->str() == "(" || + enumValueEnd->next()->str() == "[" || + enumValueEnd->next()->str() == "{") level++; - else if(enumValueEnd->next()->str() == ")" || - enumValueEnd->next()->str() == "]" || - enumValueEnd->next()->str() == "}") + else if (enumValueEnd->next()->str() == ")" || + enumValueEnd->next()->str() == "]" || + enumValueEnd->next()->str() == "}") level--; enumValueEnd = enumValueEnd->next(); @@ -5785,7 +5785,7 @@ void Tokenizer::simplifyEnum() } // find all uses of this enumerator and substitute it's value for it's name - if(enumName && (enumValue || (enumValueStart && enumValueEnd))) + if (enumName && (enumValue || (enumValueStart && enumValueEnd))) { const std::string pattern(className.empty() ? "" : (className + " :: " + enumName->str()).c_str()); int level = 1; @@ -5795,37 +5795,37 @@ void Tokenizer::simplifyEnum() int exitScope = 0; bool simplifyEnum = false; bool hasClass = false; - for(Token *tok2 = tok1->next(); tok2; tok2 = tok2->next()) + for (Token *tok2 = tok1->next(); tok2; tok2 = tok2->next()) { - if(tok2->str() == "}") + if (tok2->str() == "}") { --level; - if(level < 0) + if (level < 0) inScope = false; - if(exitThisScope) + if (exitThisScope) { - if(level < exitScope) + if (level < exitScope) exitThisScope = false; } } - else if(tok2->str() == "{") + else if (tok2->str() == "{") { ++level; } - else if(!pattern.empty() && Token::Match(tok2, pattern.c_str())) + else if (!pattern.empty() && Token::Match(tok2, pattern.c_str())) { simplifyEnum = true; hasClass = true; } - else if(inScope && !exitThisScope && tok2->str() == enumName->str()) + else if (inScope && !exitThisScope && tok2->str() == enumName->str()) { - if(Token::simpleMatch(tok2->previous(), "::") || - (tok2->next() && Token::simpleMatch(tok2->next(), "::"))) + if (Token::simpleMatch(tok2->previous(), "::") || + (tok2->next() && Token::simpleMatch(tok2->next(), "::"))) { // Don't replace this enum if it's preceded or followed by "::" } - else if(!duplicateDefinition(&tok2, enumName)) + else if (!duplicateDefinition(&tok2, enumName)) { simplifyEnum = true; hasClass = false; @@ -5837,26 +5837,26 @@ void Tokenizer::simplifyEnum() } } - if(simplifyEnum) + if (simplifyEnum) { - if(enumValue) + if (enumValue) tok2->str(enumValue->strAt(0)); else { std::stack links; tok2->str(enumValueStart->strAt(0)); - if(tok2->str() == "(" || tok2->str() == "[" || tok2->str() == "{") + if (tok2->str() == "(" || tok2->str() == "[" || tok2->str() == "{") links.push(tok2); Token * nextToken = enumValueStart->next(); - for(; nextToken != enumValueEnd->next(); nextToken = nextToken->next()) + for (; nextToken != enumValueEnd->next(); nextToken = nextToken->next()) { tok2->insertToken(nextToken->str()); tok2 = tok2->next(); // Check for links and fix them up - if(tok2->str() == "(" || tok2->str() == "[" || tok2->str() == "{") + if (tok2->str() == "(" || tok2->str() == "[" || tok2->str() == "{") links.push(tok2); - else if(tok2->str() == ")" || tok2->str() == "]" || tok2->str() == "}") + else if (tok2->str() == ")" || tok2->str() == "]" || tok2->str() == "}") { Token * link = links.top(); @@ -5868,7 +5868,7 @@ void Tokenizer::simplifyEnum() } } - if(hasClass) + if (hasClass) { tok2->deleteNext(); tok2->deleteNext(); @@ -5881,7 +5881,7 @@ void Tokenizer::simplifyEnum() } // check for a variable definition: enum {} x; - if(end->next()->str() != ";") + if (end->next()->str() != ";") { Token * tok = end; @@ -5890,7 +5890,7 @@ void Tokenizer::simplifyEnum() tok->insertToken("int"); } - if(enumType) + if (enumType) { const std::string pattern(className.empty() ? "" : (className + " :: " + enumType->str()).c_str()); int level = 0; @@ -5900,47 +5900,47 @@ void Tokenizer::simplifyEnum() int exitScope = 0; bool simplifyEnum = false; bool hasClass = false; - for(Token *tok2 = end->next(); tok2; tok2 = tok2->next()) + for (Token *tok2 = end->next(); tok2; tok2 = tok2->next()) { - if(tok2->str() == "}") + if (tok2->str() == "}") { --level; - if(level < 0) + if (level < 0) inScope = false; - if(exitThisScope) + if (exitThisScope) { - if(level < exitScope) + if (level < exitScope) exitThisScope = false; } } - else if(tok2->str() == "{") + else if (tok2->str() == "{") ++level; - else if(!pattern.empty() && ((Token::Match(tok2, "enum") && Token::Match(tok2->next(), pattern.c_str())) || Token::Match(tok2, pattern.c_str()))) + else if (!pattern.empty() && ((Token::Match(tok2, "enum") && Token::Match(tok2->next(), pattern.c_str())) || Token::Match(tok2, pattern.c_str()))) { simplifyEnum = true; hasClass = true; } - else if(inScope && !exitThisScope && (tok2->str() == enumType->str() || (tok2->str() == "enum" && tok2->next()->str() == enumType->str()))) + else if (inScope && !exitThisScope && (tok2->str() == enumType->str() || (tok2->str() == "enum" && tok2->next()->str() == enumType->str()))) { - if(Token::simpleMatch(tok2->previous(), "::")) + if (Token::simpleMatch(tok2->previous(), "::")) { // Don't replace this enum if it's preceded by "::" } - else if(tok2->next() && tok2->next()->isName()) + else if (tok2->next() && tok2->next()->isName()) { simplifyEnum = true; hasClass = false; } } - if(simplifyEnum) + if (simplifyEnum) { - if(tok2->str() == "enum") + if (tok2->str() == "enum") tok2->deleteNext(); tok2->str("int"); - if(hasClass) + if (hasClass) { tok2->deleteNext(); tok2->deleteNext(); @@ -5952,10 +5952,10 @@ void Tokenizer::simplifyEnum() } tok1 = start; - while(tok1->next() && tok1->next() != end) + while (tok1->next() && tok1->next() != end) tok1->deleteNext(); tok1->deleteNext(); - if(start != _tokens) + if (start != _tokens) { tok1 = start->previous(); tok1->deleteNext(); @@ -5979,13 +5979,13 @@ void Tokenizer::simplifyStd() f.insert("malloc"); f.insert("strdup"); - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(tok->str() != "std") + if (tok->str() != "std") continue; - if(Token::Match(tok->previous(), "[(,{};] std :: %var% (") && - f.find(tok->strAt(2)) != f.end()) + if (Token::Match(tok->previous(), "[(,{};] std :: %var% (") && + f.find(tok->strAt(2)) != f.end()) { tok->deleteNext(); tok->deleteThis(); @@ -6003,9 +6003,9 @@ void Tokenizer::simplifyStd() const Token *Tokenizer::getFunctionTokenByName(const char funcname[]) const { - for(unsigned int i = 0; i < _functionList.size(); ++i) + for (unsigned int i = 0; i < _functionList.size(); ++i) { - if(_functionList[i]->str() == funcname) + if (_functionList[i]->str() == funcname) { return _functionList[i]; } @@ -6018,35 +6018,35 @@ void Tokenizer::fillFunctionList() { _functionList.clear(); - 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(); - if(!tok) + if (!tok) break; continue; } - if(Token::Match(tok, "%var% (")) + if (Token::Match(tok, "%var% (")) { // Check if this is the first token of a function implementation.. - for(const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) + for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) { - if(tok2->str() == ";") + if (tok2->str() == ";") { tok = tok2; break; } - else if(tok2->str() == "{") + else if (tok2->str() == "{") { break; } - else if(tok2->str() == ")") + else if (tok2->str() == ")") { - if(Token::Match(tok2, ") const| {")) + if (Token::Match(tok2, ") const| {")) { _functionList.push_back(tok); tok = tok2; @@ -6054,7 +6054,7 @@ void Tokenizer::fillFunctionList() else { tok = tok2; - while(tok->next() && !Token::Match(tok->next(), "[;{]")) + while (tok->next() && !Token::Match(tok->next(), "[;{]")) tok = tok->next(); } break; @@ -6065,12 +6065,12 @@ void Tokenizer::fillFunctionList() // If the _functionList functions with duplicate names, remove them /** @todo handle when functions with the same name */ - for(unsigned int func1 = 0; func1 < _functionList.size();) + for (unsigned int func1 = 0; func1 < _functionList.size();) { bool hasDuplicates = false; - for(unsigned int func2 = func1 + 1; func2 < _functionList.size();) + for (unsigned int func2 = func1 + 1; func2 < _functionList.size();) { - if(_functionList[func1]->str() == _functionList[func2]->str()) + if (_functionList[func1]->str() == _functionList[func2]->str()) { hasDuplicates = true; _functionList.erase(_functionList.begin() + func2); @@ -6081,7 +6081,7 @@ void Tokenizer::fillFunctionList() } } - if(! hasDuplicates) + if (! hasDuplicates) { ++func1; } @@ -6105,7 +6105,7 @@ void Tokenizer::deallocateTokens() void Tokenizer::deleteTokens(Token *tok) { - while(tok) + while (tok) { Token *next = tok->next(); delete tok; @@ -6118,11 +6118,11 @@ void Tokenizer::deleteTokens(Token *tok) const char *Tokenizer::getParameterName(const Token *ftok, int par) { int _par = 1; - for(; ftok; ftok = ftok->next()) + for (; ftok; ftok = ftok->next()) { - if(ftok->str() == ",") + if (ftok->str() == ",") ++_par; - if(par == _par && Token::Match(ftok, "%var% [,)]")) + if (par == _par && Token::Match(ftok, "%var% [,)]")) return ftok->str().c_str(); } return NULL; @@ -6146,7 +6146,7 @@ std::string Tokenizer::file(const Token *tok) const const Token * Tokenizer::findClassFunction(const Token *tok, const std::string &classname, const std::string &funcname, int &indentlevel, bool isStruct) const { - if(indentlevel < 0 || tok == NULL) + if (indentlevel < 0 || tok == NULL) return NULL; /* // TODO: This is currently commented out as updateClassList doesn't @@ -6182,57 +6182,57 @@ const Token * Tokenizer::findClassFunction(const Token *tok, const std::string & const std::string internalPattern(std::string("!!~ ") + funcname + " ("); const std::string externalPattern(std::string(classname) + " :: " + funcname + " ("); - for(; tok; tok = tok->next()) + for (; tok; tok = tok->next()) { - if(indentlevel == 0 && Token::Match(tok, classPattern.c_str())) + if (indentlevel == 0 && Token::Match(tok, classPattern.c_str())) { - while(tok && tok->str() != "{") + while (tok && tok->str() != "{") tok = tok->next(); - if(tok) + if (tok) tok = tok->next(); - if(! tok) + if (! tok) break; indentlevel = 1; } - if(tok->str() == "{") + if (tok->str() == "{") { // If indentlevel==0 don't go to indentlevel 1. Skip the block. - if(indentlevel > 0) + if (indentlevel > 0) ++indentlevel; else { // skip the block tok = tok->link(); - if(tok == NULL) + if (tok == NULL) return NULL; continue; } } - if(tok->str() == "}") + if (tok->str() == "}") { --indentlevel; - if(indentlevel < 0) + if (indentlevel < 0) return NULL; } - if(indentlevel == 1) + if (indentlevel == 1) { // Member function implemented in the class declaration? - if(Token::Match(tok->previous(), internalPattern.c_str())) + if (Token::Match(tok->previous(), internalPattern.c_str())) { const Token *tok2 = tok; - while(tok2 && tok2->str() != "{" && tok2->str() != ";") + while (tok2 && tok2->str() != "{" && tok2->str() != ";") tok2 = tok2->next(); - if(tok2 && tok2->str() == "{") + if (tok2 && tok2->str() == "{") return tok; } } - else if(indentlevel == 0 && Token::Match(tok, externalPattern.c_str())) + else if (indentlevel == 0 && Token::Match(tok, externalPattern.c_str())) { return tok; } @@ -6246,16 +6246,16 @@ const Token * Tokenizer::findClassFunction(const Token *tok, const std::string & void Tokenizer::syntaxError(const Token *tok, char c) { - if(_settings && _settings->_debug) + if (_settings && _settings->_debug) { _tokens->printOut(); } - if(!_errorLogger && tok) + if (!_errorLogger && tok) { std::ostringstream err; err << "### Unlogged error at Tokenizer::syntaxError: Invalid number of character (" << c << ")"; - if(_settings && _settings->_debug) + if (_settings && _settings->_debug) { throw std::runtime_error(err.str()); } @@ -6267,7 +6267,7 @@ void Tokenizer::syntaxError(const Token *tok, char c) } std::list locationList; - if(tok) + if (tok) { ErrorLogger::ErrorMessage::FileLocation loc; loc.line = tok->linenr(); @@ -6285,7 +6285,7 @@ void Tokenizer::syntaxError(const Token *tok, char c) "'.", "syntaxError"); - if(_errorLogger) + if (_errorLogger) _errorLogger->reportErr(errmsg); else Check::reportError(errmsg); @@ -6294,11 +6294,11 @@ void Tokenizer::syntaxError(const Token *tok, char c) void Tokenizer::cppcheckError(const Token *tok) const { - if(!_errorLogger && tok) + if (!_errorLogger && tok) { std::ostringstream err; err << "### Unlogged error at Tokenizer::cppcheckError"; - if(_settings && _settings->_debug) + if (_settings && _settings->_debug) { throw std::runtime_error(err.str()); } @@ -6310,7 +6310,7 @@ void Tokenizer::cppcheckError(const Token *tok) const } std::list locationList; - if(tok) + if (tok) { ErrorLogger::ErrorMessage::FileLocation loc; loc.line = tok->linenr(); @@ -6323,25 +6323,25 @@ void Tokenizer::cppcheckError(const Token *tok) const "### Internal error in Cppcheck. Please report it.", "cppcheckError"); - if(_errorLogger) + if (_errorLogger) _errorLogger->reportErr(errmsg); } void Tokenizer::simplifyMathFunctions() { - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(Token::Match(tok, "atol ( %str% )")) + if (Token::Match(tok, "atol ( %str% )")) { - if(!MathLib::isInt(tok->tokAt(2)->strValue())) + if (!MathLib::isInt(tok->tokAt(2)->strValue())) { // Ignore strings which we can't convert continue; } - if(tok->previous() && - Token::simpleMatch(tok->previous()->previous(), "std ::")) + if (tok->previous() && + Token::simpleMatch(tok->previous()->previous(), "std ::")) { // Delete "std ::" tok = tok->previous()->previous(); @@ -6364,63 +6364,63 @@ void Tokenizer::simplifyMathFunctions() void Tokenizer::simplifyComma() { - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(Token::simpleMatch(tok, "for (") || - Token::Match(tok, "=|enum {")) + if (Token::simpleMatch(tok, "for (") || + Token::Match(tok, "=|enum {")) { tok = tok->next()->link(); - if(!tok) + if (!tok) break; continue; } - if(tok->str() == "(") + if (tok->str() == "(") { tok = tok->link(); continue; } // Skip unhandled template specifiers.. - if(Token::Match(tok, "%var% <")) + if (Token::Match(tok, "%var% <")) { // Todo.. use the link instead. unsigned int comparelevel = 0; - for(Token *tok2 = tok; tok2; tok2 = tok2->next()) + for (Token *tok2 = tok; tok2; tok2 = tok2->next()) { - if(tok2->str() == "<") + if (tok2->str() == "<") ++comparelevel; - else if(tok2->str() == ">") + else if (tok2->str() == ">") { - if(comparelevel <= 1) + if (comparelevel <= 1) { tok = tok2; break; } ++comparelevel; } - else if(Token::Match(tok2, "[;{}]")) + else if (Token::Match(tok2, "[;{}]")) break; } } // If token after the comma is a constant number, simplification is not required. - if(tok->str() != "," || Token::Match(tok->next(), "%num%")) + if (tok->str() != "," || Token::Match(tok->next(), "%num%")) continue; // We must not accept just any keyword, e.g. accepting int // would cause function parameters to corrupt. - if(Token::Match(tok->next(), "delete")) + if (Token::Match(tok->next(), "delete")) { // Handle "delete a, delete b;" tok->str(";"); } - if(tok->previous() && tok->previous()->previous()) + if (tok->previous() && tok->previous()->previous()) { - if(Token::Match(tok->previous()->previous(), "delete") && - tok->next()->varId() != 0) + if (Token::Match(tok->previous()->previous(), "delete") && + tok->next()->varId() != 0) { // Handle "delete a, b;" tok->str(";"); @@ -6428,22 +6428,22 @@ void Tokenizer::simplifyComma() } else { - for(Token *tok2 = tok->previous(); tok2; tok2 = tok2->previous()) + for (Token *tok2 = tok->previous(); tok2; tok2 = tok2->previous()) { - if(tok2->str() == "=") + if (tok2->str() == "=") { // Handle "a = 0, b = 0;" tok->str(";"); break; } - else if(Token::Match(tok2, "delete %var%") || - Token::Match(tok2, "delete [ ] %var%")) + else if (Token::Match(tok2, "delete %var%") || + Token::Match(tok2, "delete [ ] %var%")) { // Handle "delete a, a = 0;" tok->str(";"); break; } - else if(Token::Match(tok2, "[;,{}()]")) + else if (Token::Match(tok2, "[;,{}()]")) { break; } @@ -6456,14 +6456,14 @@ void Tokenizer::simplifyComma() Token *endAt = NULL; // first ";" token after "; return" // find "; return" pattern before comma - for(Token *tok2 = tok; tok2; tok2 = tok2->previous()) + for (Token *tok2 = tok; tok2; tok2 = tok2->previous()) { - if(Token::Match(tok2, "[;{}]")) + if (Token::Match(tok2, "[;{}]")) { break; } - else if(tok2->str() == "return" && Token::Match(tok2->previous(), "[;{}]")) + else if (tok2->str() == "return" && Token::Match(tok2->previous(), "[;{}]")) { inReturn = true; startFrom = tok2->next(); @@ -6472,36 +6472,36 @@ void Tokenizer::simplifyComma() } // find token where return ends and also count commas - if(inReturn) + if (inReturn) { size_t commaCounter = 0; size_t indentlevel = 0; - for(Token *tok2 = startFrom; tok2; tok2 = tok2->next()) + for (Token *tok2 = startFrom; tok2; tok2 = tok2->next()) { - if(tok2->str() == ";") + if (tok2->str() == ";") { endAt = tok2; break; } - else if(tok2->str() == "(") + else if (tok2->str() == "(") { ++indentlevel; } - else if(tok2->str() == ")") + else if (tok2->str() == ")") { --indentlevel; } - else if(tok2->str() == "," && indentlevel == 0) + else if (tok2->str() == "," && indentlevel == 0) { ++commaCounter; } } - if(commaCounter) + if (commaCounter) { indentlevel = 0; @@ -6509,23 +6509,23 @@ void Tokenizer::simplifyComma() // "; return a ( ) , b ( ) , c ;" // to // "; return a ( ) ; b ( ) ; c ;" - for(Token *tok2 = startFrom; tok2 != endAt; tok2 = tok2->next()) + for (Token *tok2 = startFrom; tok2 != endAt; tok2 = tok2->next()) { - if(tok2->str() == "(") + if (tok2->str() == "(") { ++indentlevel; } - else if(tok2->str() == ")") + else if (tok2->str() == ")") { --indentlevel; } - else if(tok2->str() == "," && indentlevel == 0) + else if (tok2->str() == "," && indentlevel == 0) { tok2->str(";"); --commaCounter; - if(commaCounter == 0) + if (commaCounter == 0) { tok2->insertToken("return"); } @@ -6536,7 +6536,7 @@ void Tokenizer::simplifyComma() startFrom->previous()->deleteThis(); tok = endAt; - if(!tok) + if (!tok) return; } } @@ -6547,25 +6547,25 @@ void Tokenizer::simplifyComma() void Tokenizer::removeExceptionSpecifications(Token *tok) const { - while(tok) + while (tok) { - if(tok->str() == "{") + if (tok->str() == "{") tok = tok->link(); - else if(tok->str() == "}") + else if (tok->str() == "}") break; - else if(Token::simpleMatch(tok, ") throw (")) + else if (Token::simpleMatch(tok, ") throw (")) { Token::eraseTokens(tok, tok->tokAt(2)->link()); tok->deleteNext(); } - else if(Token::Match(tok, "class %type%")) + else if (Token::Match(tok, "class %type%")) { - while(tok && !Token::Match(tok, "[;{]")) + while (tok && !Token::Match(tok, "[;{]")) tok = tok->next(); - if(tok && tok->str() == "{") + if (tok && tok->str() == "{") { removeExceptionSpecifications(tok->next()); tok = tok->link(); @@ -6582,12 +6582,12 @@ bool Tokenizer::validate() const { std::stack linktok; const Token *lastTok = 0; - for(const Token *tok = tokens(); tok; tok = tok->next()) + for (const Token *tok = tokens(); tok; tok = tok->next()) { lastTok = tok; - if(Token::Match(tok, "[{([]")) + if (Token::Match(tok, "[{([]")) { - if(tok->link() == 0) + if (tok->link() == 0) { cppcheckError(tok); return false; @@ -6597,27 +6597,27 @@ bool Tokenizer::validate() const continue; } - else if(Token::Match(tok, "[})]]")) + else if (Token::Match(tok, "[})]]")) { - if(tok->link() == 0) + if (tok->link() == 0) { cppcheckError(tok); return false; } - if(linktok.empty() == true) + if (linktok.empty() == true) { cppcheckError(tok); return false; } - if(tok->link() != linktok.top()) + if (tok->link() != linktok.top()) { cppcheckError(tok); return false; } - if(tok != tok->link()->link()) + if (tok != tok->link()->link()) { cppcheckError(tok); return false; @@ -6627,21 +6627,21 @@ bool Tokenizer::validate() const continue; } - if(tok->link() != 0) + if (tok->link() != 0) { cppcheckError(tok); return false; } } - if(!linktok.empty()) + if (!linktok.empty()) { cppcheckError(linktok.top()); return false; } // Validate that the Tokenizer::_tokensBack is updated correctly during simplifications - if(lastTok != _tokensBack) + if (lastTok != _tokensBack) { cppcheckError(lastTok); return false; @@ -6654,20 +6654,20 @@ std::string Tokenizer::simplifyString(const std::string &source) { std::string str = source; bool escaped = false; - for(std::string::size_type i = 0; i + 2 < str.size(); i++) + for (std::string::size_type i = 0; i + 2 < str.size(); i++) { - if(!escaped) + if (!escaped) { - if(str[i] == '\\') + if (str[i] == '\\') escaped = true; continue; } - if(str[i] == 'x') + if (str[i] == 'x') { // Hex value - if(str[i+1] == '0' && str[i+2] == '0') + if (str[i+1] == '0' && str[i+2] == '0') str.replace(i, 3, "0"); else { @@ -6675,18 +6675,18 @@ std::string Tokenizer::simplifyString(const std::string &source) // If that causes problems in the future, this can // be improved. But for now, this should be OK. int n = 1; - while(n < 2 && std::isxdigit(str[i+1+n])) + while (n < 2 && std::isxdigit(str[i+1+n])) ++n; --i; str.replace(i, 2 + n, "a"); } } - else if(MathLib::isOctalDigit(str[i])) + else if (MathLib::isOctalDigit(str[i])) { - if(MathLib::isOctalDigit(str[i+1]) && - MathLib::isOctalDigit(str[i+2])) + if (MathLib::isOctalDigit(str[i+1]) && + MathLib::isOctalDigit(str[i+2])) { - if(str[i+1] == '0' && str[i+2] == '0') + if (str[i+1] == '0' && str[i+2] == '0') str.replace(i, 3, "0"); else { @@ -6708,47 +6708,47 @@ std::string Tokenizer::simplifyString(const std::string &source) void Tokenizer::simplifyStructInit() { - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(Token::Match(tok, "[;{}] struct| %type% %var% = { . %type% =")) + if (Token::Match(tok, "[;{}] struct| %type% %var% = { . %type% =")) { // Goto "." and check if the initializations have an expected format const Token *tok2 = tok; - while(tok2->str() != ".") + while (tok2->str() != ".") tok2 = tok2->next(); - while(tok2 && tok2->str() == ".") + while (tok2 && tok2->str() == ".") { - if(Token::Match(tok2, ". %type% = %num% [,}]")) + if (Token::Match(tok2, ". %type% = %num% [,}]")) tok2 = tok2->tokAt(4); - else if(Token::Match(tok2, ". %type% = %var% [,}]")) + else if (Token::Match(tok2, ". %type% = %var% [,}]")) tok2 = tok2->tokAt(4); - else if(Token::Match(tok2, ". %type% = & %var% [,}]")) + else if (Token::Match(tok2, ". %type% = & %var% [,}]")) tok2 = tok2->tokAt(5); else break; - if(Token::simpleMatch(tok2, ", .")) + if (Token::simpleMatch(tok2, ", .")) tok2 = tok2->next(); } - if(!Token::Match(tok2, "} ;")) + if (!Token::Match(tok2, "} ;")) continue; // Known expression format => Perform simplification Token *vartok = tok->tokAt(3); - if(vartok->str() == "=") + if (vartok->str() == "=") vartok = vartok->previous(); vartok->next()->str(";"); Token *tok3 = vartok->tokAt(2); tok3->link(0); - while(Token::Match(tok3, "[{,] . %type% =")) + while (Token::Match(tok3, "[{,] . %type% =")) { tok3->str(vartok->str()); tok3->varId(vartok->varId()); tok3 = tok3->tokAt(5); - while(!Token::Match(tok3, "[,}]")) + while (!Token::Match(tok3, "[,}]")) tok3 = tok3->next(); - if(tok3->str() == "}") + if (tok3->str() == "}") { tok3->deleteThis(); break; @@ -6763,23 +6763,23 @@ void Tokenizer::simplifyStructInit() void Tokenizer::simplifyComparisonOrder() { // Use "<" comparison instead of ">" - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(Token::Match(tok, "[;(] %any% >|>= %any% [);]")) + if (Token::Match(tok, "[;(] %any% >|>= %any% [);]")) { - if(!tok->next()->isName() && !tok->next()->isNumber()) + if (!tok->next()->isName() && !tok->next()->isNumber()) continue; const std::string op1(tok->strAt(1)); tok->next()->str(tok->strAt(3)); tok->tokAt(3)->str(op1); - if(tok->tokAt(2)->str() == ">") + if (tok->tokAt(2)->str() == ">") tok->tokAt(2)->str("<"); else tok->tokAt(2)->str("<="); } - else if(Token::Match(tok, "( %num% ==|!= %var% )")) + else if (Token::Match(tok, "( %num% ==|!= %var% )")) { - if(!tok->next()->isName() && !tok->next()->isNumber()) + if (!tok->next()->isName() && !tok->next()->isNumber()) continue; const std::string op1(tok->strAt(1)); tok->next()->str(tok->strAt(3)); @@ -6790,10 +6790,10 @@ void Tokenizer::simplifyComparisonOrder() void Tokenizer::simplifyConst() { - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(Token::Match(tok, "[;{}(,] %type% const") && - tok->next()->str().find(":") == std::string::npos) + if (Token::Match(tok, "[;{}(,] %type% const") && + tok->next()->str().find(":") == std::string::npos) { tok->tokAt(2)->str(tok->tokAt(1)->str()); tok->tokAt(1)->str("const"); @@ -6809,9 +6809,9 @@ void Tokenizer::getErrorMessages() /** find pattern */ static bool findmatch(const Token *tok1, const Token *tok2, const char pattern[]) { - for(const Token *tok = tok1; tok && tok != tok2; tok = tok->next()) + for (const Token *tok = tok1; tok && tok != tok2; tok = tok->next()) { - if(Token::Match(tok, pattern)) + if (Token::Match(tok, pattern)) return true; } return false; @@ -6819,17 +6819,17 @@ static bool findmatch(const Token *tok1, const Token *tok2, const char pattern[] void Tokenizer::simplifyWhile0() { - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(!Token::simpleMatch(tok, "while ( 0 )")) + if (!Token::simpleMatch(tok, "while ( 0 )")) continue; - if(Token::simpleMatch(tok->previous(), "}")) + if (Token::simpleMatch(tok->previous(), "}")) { // find "do" Token *tok2 = tok->previous()->link(); tok2 = tok2 ? tok2->previous() : 0; - if(tok2 && tok2->str() == "do" && !findmatch(tok2, tok, "continue|break")) + if (tok2 && tok2->str() == "do" && !findmatch(tok2, tok, "continue|break")) { // delete "do {" tok2->deleteThis(); @@ -6848,10 +6848,10 @@ void Tokenizer::simplifyWhile0() } // remove "while (0) { .. }" - if(Token::simpleMatch(tok->tokAt(4), "{")) + if (Token::simpleMatch(tok->tokAt(4), "{")) { const Token *end = tok->tokAt(4)->link(); - if(!findmatch(tok, end, "continue|break")) + if (!findmatch(tok, end, "continue|break")) { Token::eraseTokens(tok, end ? end->next() : 0); tok->deleteThis(); // delete "while" @@ -6863,15 +6863,15 @@ void Tokenizer::simplifyWhile0() void Tokenizer::simplifyFuncInWhile() { - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { - if(!Token::Match(tok, "while ( %var% ( %var% ) ) {")) + if (!Token::Match(tok, "while ( %var% ( %var% ) ) {")) continue; Token *func = tok->tokAt(2); Token *var = tok->tokAt(4); Token *end = tok->tokAt(7)->link(); - if(!end) + if (!end) break; tok->str("int"); @@ -6899,21 +6899,21 @@ void Tokenizer::simplifyStructDecl() { unsigned int count = 0; - for(Token *tok = _tokens; tok; tok = tok->next()) + for (Token *tok = _tokens; tok; tok = tok->next()) { // check for named struct/union - if(Token::Match(tok, "struct|union %type% :|{")) + if (Token::Match(tok, "struct|union %type% :|{")) { Token *type = tok->next(); Token *next = tok->tokAt(2); - while(next->str() != "{") + while (next->str() != "{") next = next->next(); tok = next->link(); // check for named type - if(Token::Match(tok->next(), "*|&| %type% ,|;|[")) + if (Token::Match(tok->next(), "*|&| %type% ,|;|[")) { tok->insertToken(";"); tok = tok->next(); @@ -6924,14 +6924,14 @@ void Tokenizer::simplifyStructDecl() } // check for anonymous struct/union - else if(Token::Match(tok, "struct|union {")) + else if (Token::Match(tok, "struct|union {")) { Token *tok1 = tok; tok = tok->next()->link(); // check for named type - if(Token::Match(tok->next(), "*|&| %type% ,|;|[")) + if (Token::Match(tok->next(), "*|&| %type% ,|;|[")) { std::string name; @@ -6943,7 +6943,7 @@ void Tokenizer::simplifyStructDecl() tok = tok->next(); tok->insertToken(name.c_str()); } - else if(tok->next()->str() == ";") + else if (tok->next()->str() == ";") { Token *previous = tok1->previous(); previous->deleteNext(); diff --git a/test/testbufferoverrun.cpp b/test/testbufferoverrun.cpp index f61670c8c..82786c488 100644 --- a/test/testbufferoverrun.cpp +++ b/test/testbufferoverrun.cpp @@ -763,7 +763,7 @@ private: void array_index_24() { // ticket #1492 and #1539 - if(CHAR_MAX == SCHAR_MAX) // plain char is signed + if (CHAR_MAX == SCHAR_MAX) // plain char is signed { check("void f(char n) {\n" " int a[n];\n" // n <= CHAR_MAX @@ -824,7 +824,7 @@ private: ASSERT_EQUALS("[test.cpp:3]: (error) Array 'a[32768]' index -1 out of bounds\n" "[test.cpp:4]: (error) Array 'a[32768]' index 32768 out of bounds\n", errout.str()); - if(sizeof(int) == 4) + if (sizeof(int) == 4) { check("void f(int n) {\n" " int a[n];\n" // n <= INT_MAX diff --git a/test/testmathlib.cpp b/test/testmathlib.cpp index 12a24c304..36b2973e7 100644 --- a/test/testmathlib.cpp +++ b/test/testmathlib.cpp @@ -167,23 +167,23 @@ private: ASSERT_EQUALS(false, MathLib::isInt("+1.E-1")); } - void isnegative() - { - ASSERT_EQUALS(true, MathLib::isNegative("-1")); + void isnegative() + { + 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.0E+2")); ASSERT_EQUALS(true, MathLib::isNegative("-1.0E-2")); - ASSERT_EQUALS(false, MathLib::isNegative("+1")); + ASSERT_EQUALS(false, MathLib::isNegative("+1")); ASSERT_EQUALS(false, MathLib::isNegative("+1.")); ASSERT_EQUALS(false, MathLib::isNegative("+1.0")); ASSERT_EQUALS(false, MathLib::isNegative("+1.0E+2")); - ASSERT_EQUALS(false, MathLib::isNegative("+1.0E-2")); - } + ASSERT_EQUALS(false, MathLib::isNegative("+1.0E-2")); + } - void isfloat() - { + void isfloat() + { ASSERT_EQUALS(false, MathLib::isFloat("0")); ASSERT_EQUALS(true , MathLib::isFloat("0.")); ASSERT_EQUALS(true , MathLib::isFloat("0.0")); @@ -194,7 +194,7 @@ private: ASSERT_EQUALS(true , MathLib::isFloat("+0.0E+1")); ASSERT_EQUALS(true , MathLib::isFloat("+0.0E-1")); ASSERT_EQUALS(true , MathLib::isFloat("-0.0E+1")); - ASSERT_EQUALS(true , MathLib::isFloat("-0.0E-1")); + ASSERT_EQUALS(true , MathLib::isFloat("-0.0E-1")); ASSERT_EQUALS(false , MathLib::isFloat("1")); ASSERT_EQUALS(false , MathLib::isFloat("-1")); @@ -214,7 +214,7 @@ private: ASSERT_EQUALS(true , MathLib::isFloat("1.0E+1")); ASSERT_EQUALS(true , MathLib::isFloat("1.0E-1")); ASSERT_EQUALS(true , MathLib::isFloat("-1.0E+1")); - } + } }; REGISTER_TEST(TestMathLib) diff --git a/test/testmemleak.cpp b/test/testmemleak.cpp index c89f353d4..8fbb303fc 100644 --- a/test/testmemleak.cpp +++ b/test/testmemleak.cpp @@ -407,7 +407,7 @@ private: // stringify.. std::ostringstream ret; - for(const Token *tok = tokens; tok; tok = tok->next()) + for (const Token *tok = tokens; tok; tok = tok->next()) ret << tok->str(); Tokenizer::deleteTokens(tokens); @@ -572,7 +572,7 @@ private: , "sync_file_range", "telldir", "typeid", "while", "write", "writev" }; - for(unsigned int i = 0; i < (sizeof(call_func_white_list) / sizeof(char *)); ++i) + for (unsigned int i = 0; i < (sizeof(call_func_white_list) / sizeof(char *)); ++i) ASSERT_EQUALS(true, CheckMemoryLeakInFunction::test_white_list(call_func_white_list[i])); } @@ -586,15 +586,15 @@ private: Token *tokens = const_cast(tokenizer.tokens()); // replace "if ( ! var )" => "if(!var)" - for(Token *tok = tokens; tok; tok = tok->next()) + for (Token *tok = tokens; tok; tok = tok->next()) { - if(Token::Match(tok, "if|while ( var )")) + if (Token::Match(tok, "if|while ( var )")) { Token::eraseTokens(tok, tok->tokAt(4)); tok->str(tok->str() + "(var)"); } - else if(Token::Match(tok, "if|while ( ! var )")) + else if (Token::Match(tok, "if|while ( ! var )")) { Token::eraseTokens(tok, tok->tokAt(5)); tok->str(tok->str() + "(!var)"); @@ -608,7 +608,7 @@ private: checkMemoryLeak.simplifycode(tokens, all); std::ostringstream ret; - for(const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) ret << (tok->previous() ? " " : "") << tok->str(); return ret.str(); @@ -720,20 +720,20 @@ private: tokenizer.tokenize(istr, "test.cpp"); // replace "if ( ! var )" => "if(!var)" - for(Token *tok = const_cast(tokenizer.tokens()); tok; tok = tok->next()) + for (Token *tok = const_cast(tokenizer.tokens()); tok; tok = tok->next()) { - if(tok->str() == "if_var") + if (tok->str() == "if_var") { tok->str("if(var)"); } - else if(Token::simpleMatch(tok, "if ( var )")) + else if (Token::simpleMatch(tok, "if ( var )")) { Token::eraseTokens(tok, tok->tokAt(4)); tok->str("if(var)"); } - else if(Token::simpleMatch(tok, "if ( ! var )")) + else if (Token::simpleMatch(tok, "if ( ! var )")) { Token::eraseTokens(tok, tok->tokAt(5)); tok->str("if(!var)"); diff --git a/test/testother.cpp b/test/testother.cpp index 67ed50a86..9bae8a41e 100644 --- a/test/testother.cpp +++ b/test/testother.cpp @@ -90,7 +90,7 @@ private: TEST_CASE(passedByValue); - TEST_CASE(mathfunctionCall1); + TEST_CASE(mathfunctionCall1); } void check(const char code[]) @@ -112,7 +112,7 @@ private: checkOther.warningRedundantCode(); checkOther.checkZeroDivision(); checkOther.unreachableCode(); - checkOther.checkMathFunctions(); + checkOther.checkMathFunctions(); } @@ -1837,7 +1837,7 @@ private: CheckOther::analyseFunctions(tokenizer.tokens(), f); std::string ret; - for(std::set::const_iterator it = f.begin(); it != f.end(); ++it) + for (std::set::const_iterator it = f.begin(); it != f.end(); ++it) ret += *it + " "; return ret; } @@ -2158,8 +2158,8 @@ private: ASSERT_EQUALS("[test.cpp:1]: (style) Function parameter 'v' is passed by value. It could be passed by reference instead.\n", errout.str()); } - void mathfunctionCall1() - { + void mathfunctionCall1() + { check("void foo()\n" "{\n" " std::cout << log(-2) << std::endl;\n" @@ -2176,7 +2176,7 @@ private: "{\n" " std::cout << log(-1.0) << std::endl;\n" "}"); - ASSERT_EQUALS("[test.cpp:3]: (error) Passing value -1.0 to log() leads to undefined result\n", errout.str()); + ASSERT_EQUALS("[test.cpp:3]: (error) Passing value -1.0 to log() leads to undefined result\n", errout.str()); check("void foo()\n" "{\n" @@ -2219,7 +2219,7 @@ private: " std::cout << log(1E-3) << std::endl;\n" "}"); TODO_ASSERT_EQUALS("", errout.str()); - } + } }; diff --git a/test/testsimplifytokens.cpp b/test/testsimplifytokens.cpp index d9a1b33ce..35284ef51 100644 --- a/test/testsimplifytokens.cpp +++ b/test/testsimplifytokens.cpp @@ -241,23 +241,23 @@ private: std::istringstream istr(code); tokenizer.tokenize(istr, "test.cpp"); - if(simplify) + if (simplify) tokenizer.simplifyTokenList(); tokenizer.validate(); std::string ret; - for(const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) { - if(tok != tokenizer.tokens()) + if (tok != tokenizer.tokens()) ret += " "; - if(!simplify) + if (!simplify) { - if(tok->isUnsigned()) + if (tok->isUnsigned()) ret += "unsigned "; - else if(tok->isSigned()) + else if (tok->isSigned()) ret += "signed "; } - if(tok->isLong()) + if (tok->isLong()) ret += "long "; ret += tok->str(); } @@ -701,9 +701,9 @@ private: tokenizer.simplifyTokenList(); std::ostringstream ostr; - for(const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) { - if(tok->previous()) + if (tok->previous()) { ostr << " "; } @@ -850,7 +850,7 @@ private: const char code[] = "; const char str[] = \"1\"; sizeof(str);"; std::ostringstream expected; - expected << "; const char * str ; str = \"1\" ; " << sizeofFromTokenizer("char") * 2 << " ;"; + expected << "; const char * str ; str = \"1\" ; " << sizeofFromTokenizer("char")*2 << " ;"; ASSERT_EQUALS(expected.str(), sizeof_(code)); } @@ -879,7 +879,7 @@ private: "{g(sizeof(a),sizeof(b),sizeof(c));}"; std::ostringstream expected; expected << "void f ( char * a , char * b , char * c ) { g ( " << - sizeofFromTokenizer("*") << " , " << sizeofFromTokenizer("*") << " , " << sizeofFromTokenizer("*") << " ) ; }"; + sizeofFromTokenizer("*") << " , " << sizeofFromTokenizer("*") << " , " << sizeofFromTokenizer("*") << " ) ; }"; ASSERT_EQUALS(expected.str(), sizeof_(code)); } @@ -888,7 +888,7 @@ private: "{g(sizeof(a),sizeof(b),sizeof(c));}"; std::ostringstream expected; expected << "void f ( char a , char b , char c ) { g ( " << - sizeofFromTokenizer("char") << " , " << sizeofFromTokenizer("char") << " , " << sizeofFromTokenizer("char") << " ) ; }"; + sizeofFromTokenizer("char") << " , " << sizeofFromTokenizer("char") << " , " << sizeofFromTokenizer("char") << " ) ; }"; ASSERT_EQUALS(expected.str(), sizeof_(code)); } @@ -897,7 +897,7 @@ private: "{g(sizeof(a),sizeof(b),sizeof(c));}"; std::ostringstream expected; expected << "void f ( const char * a , const char * b , const char * c ) { g ( " << - sizeofFromTokenizer("*") << " , " << sizeofFromTokenizer("*") << " , " << sizeofFromTokenizer("*") << " ) ; }"; + sizeofFromTokenizer("*") << " , " << sizeofFromTokenizer("*") << " , " << sizeofFromTokenizer("*") << " ) ; }"; ASSERT_EQUALS(expected.str(), sizeof_(code)); } @@ -906,7 +906,7 @@ private: "{g(sizeof(a),sizeof(b),sizeof(c));}"; std::ostringstream expected; expected << "void f ( char a [ 10 ] , char b [ 10 ] , char c [ 10 ] ) { g ( " << - sizeofFromTokenizer("*") << " , " << sizeofFromTokenizer("*") << " , " << sizeofFromTokenizer("*") << " ) ; }"; + sizeofFromTokenizer("*") << " , " << sizeofFromTokenizer("*") << " , " << sizeofFromTokenizer("*") << " ) ; }"; ASSERT_EQUALS(expected.str(), sizeof_(code)); } @@ -915,9 +915,9 @@ private: "{g(sizeof(a),sizeof(b),sizeof(c));}"; std::ostringstream expected; expected << "void f ( const char a [ 10 ] , " - "const char b [ 10 ] , " - "const char c [ 10 ] ) { g ( " << - sizeofFromTokenizer("*") << " , " << sizeofFromTokenizer("*") << " , " << sizeofFromTokenizer("*") << " ) ; }"; + "const char b [ 10 ] , " + "const char c [ 10 ] ) { g ( " << + sizeofFromTokenizer("*") << " , " << sizeofFromTokenizer("*") << " , " << sizeofFromTokenizer("*") << " ) ; }"; ASSERT_EQUALS(expected.str(), sizeof_(code)); } @@ -926,9 +926,9 @@ private: "{g(sizeof(a),sizeof(b),sizeof(c));}"; std::ostringstream expected; expected << "void f ( const char * a [ 10 ] , " - "const char * b [ 10 ] , " - "const char * c [ 10 ] ) { g ( " << - sizeofFromTokenizer("*") << " , " << sizeofFromTokenizer("*") << " , " << sizeofFromTokenizer("*") << " ) ; }"; + "const char * b [ 10 ] , " + "const char * c [ 10 ] ) { g ( " << + sizeofFromTokenizer("*") << " , " << sizeofFromTokenizer("*") << " , " << sizeofFromTokenizer("*") << " ) ; }"; ASSERT_EQUALS(expected.str(), sizeof_(code)); } @@ -937,7 +937,7 @@ private: "{g(sizeof(a),sizeof(b),sizeof(c));}"; std::ostringstream expected; expected << "void f ( char * a [ 10 ] , char * b [ 10 ] , char * c [ 10 ] ) { g ( " << - sizeofFromTokenizer("*") << " , " << sizeofFromTokenizer("*") << " , " << sizeofFromTokenizer("*") << " ) ; }"; + sizeofFromTokenizer("*") << " , " << sizeofFromTokenizer("*") << " , " << sizeofFromTokenizer("*") << " ) ; }"; ASSERT_EQUALS(expected.str(), sizeof_(code)); } @@ -949,7 +949,7 @@ private: { std::ostringstream expected; - expected << "void f ( ) { char str [ 100 ] = \"100\" ; " << sizeofFromTokenizer("char") * 100 << " }"; + expected << "void f ( ) { char str [ 100 ] = \"100\" ; " << sizeofFromTokenizer("char")*100 << " }"; ASSERT_EQUALS(expected.str(), tok("void f ( ) { char str [ 100 ] = \"100\" ; sizeof ( str ) }")); } } @@ -1092,7 +1092,7 @@ private: void sizeof18() { - if(sizeof(short int) == 2) + if (sizeof(short int) == 2) { { const char code[] = "void f()\n" @@ -1131,7 +1131,7 @@ private: } } - if(sizeof(long long) == 8) + if (sizeof(long long) == 8) { { const char code[] = "void f()\n" @@ -1843,7 +1843,7 @@ private: tokenizer.simplifyIfAssign(); std::ostringstream ostr; - for(const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) ostr << (tok->previous() ? " " : "") << tok->str(); return ostr.str(); @@ -1887,7 +1887,7 @@ private: tokenizer.simplifyIfNot(); std::ostringstream ostr; - for(const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) ostr << (tok->previous() ? " " : "") << tok->str(); return ostr.str(); @@ -1920,7 +1920,7 @@ private: tokenizer.simplifyLogicalOperators(); std::ostringstream ostr; - for(const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) ostr << (tok->previous() ? " " : "") << tok->str(); return ostr.str(); @@ -2482,9 +2482,9 @@ private: tokenizer.simplifyTypedef(); std::string ret; - for(const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) { - if(tok != tokenizer.tokens()) + if (tok != tokenizer.tokens()) ret += " "; ret += tok->str(); } diff --git a/test/teststl.cpp b/test/teststl.cpp index 416019841..aea6a9d61 100644 --- a/test/teststl.cpp +++ b/test/teststl.cpp @@ -597,12 +597,11 @@ private: { const int STL_CONTAINER_LIST = 9; const std::string stlCont[STL_CONTAINER_LIST] = - { - "deque", "list", "set", "multiset", "map", - "multimap", "hash_map", "hash_multimap", "hash_set" - }; + {"deque", "list", "set", "multiset", "map", + "multimap", "hash_map", "hash_multimap", "hash_set" + }; - for(int i = 0; i < STL_CONTAINER_LIST; ++i) + for (int i = 0; i < STL_CONTAINER_LIST; ++i) { check("void f()\n" "{\n" diff --git a/test/testsuite.cpp b/test/testsuite.cpp index 1e137304b..431be1415 100644 --- a/test/testsuite.cpp +++ b/test/testsuite.cpp @@ -75,7 +75,7 @@ TestFixture::TestFixture(const std::string &_name) : classname(_name) bool TestFixture::runTest(const char testname[]) { - if(testToRun.empty() || testToRun == testname) + if (testToRun.empty() || testToRun == testname) { ++countTests; std::cout << classname << "::" << testname << "\n"; @@ -88,14 +88,14 @@ static std::string writestr(const std::string &str) { std::ostringstream ostr; ostr << "\""; - for(unsigned int i = 0; i < str.length(); ++i) + for (unsigned int i = 0; i < str.length(); ++i) { char ch = str[i]; - if(ch == '\n') + if (ch == '\n') ostr << "\\n"; - else if(ch == '\t') + else if (ch == '\t') ostr << "\\t"; - else if(ch == '\"') + else if (ch == '\"') ostr << "\\\""; else ostr << std::string(1, ch); @@ -106,15 +106,15 @@ static std::string writestr(const std::string &str) void TestFixture::assertEquals(const char *filename, int linenr, const std::string &expected, const std::string &actual) { - if(expected != actual) + if (expected != actual) { ++fails_counter; errmsg << "Assertion failed in " << filename << " at line " << linenr << std::endl - << "Expected:" << std::endl - << writestr(expected) << std::endl - << "Actual:" << std::endl - << writestr(actual) << std::endl; + << "Expected:" << std::endl + << writestr(expected) << std::endl + << "Actual:" << std::endl + << writestr(actual) << std::endl; } } @@ -129,7 +129,7 @@ void TestFixture::assertEquals(const char *filename, int linenr, unsigned int ex void TestFixture::todoAssertEquals(const char *filename, int linenr, const std::string &expected, const std::string &actual) { - if(expected == actual) + if (expected == actual) assertEquals(filename, linenr, "TODO assertion", "The assertion succeeded"); else ++todos_counter; @@ -149,14 +149,14 @@ void TestFixture::assertThrowFail(const char *filename, int linenr) ++fails_counter; errmsg << "Assertion failed in " << filename << " at line " << linenr << std::endl - << "The expected exception was not thrown" << std::endl; + << "The expected exception was not thrown" << std::endl; } void TestFixture::printTests() { const std::list &tests = TestRegistry::theInstance().tests(); - for(std::list::const_iterator it = tests.begin(); it != tests.end(); ++it) + for (std::list::const_iterator it = tests.begin(); it != tests.end(); ++it) { std::cout << (*it)->classname << std::endl; } @@ -172,7 +172,7 @@ size_t TestFixture::runTests(const char cmd[]) { std::string classname(cmd ? cmd : ""); std::string testname(""); - if(classname.find("::") != std::string::npos) + if (classname.find("::") != std::string::npos) { testname = classname.substr(classname.find("::") + 2); classname.erase(classname.find("::")); @@ -183,9 +183,9 @@ size_t TestFixture::runTests(const char cmd[]) const std::list &tests = TestRegistry::theInstance().tests(); - for(std::list::const_iterator it = tests.begin(); it != tests.end(); ++it) + for (std::list::const_iterator it = tests.begin(); it != tests.end(); ++it) { - if(classname.empty() || (*it)->classname == classname) + if (classname.empty() || (*it)->classname == classname) { (*it)->run(testname); } diff --git a/test/testtoken.cpp b/test/testtoken.cpp index 6ab060371..b3340213a 100644 --- a/test/testtoken.cpp +++ b/test/testtoken.cpp @@ -51,13 +51,13 @@ private: ASSERT_EQUALS(token->str(), "1"); ASSERT_EQUALS(token->next()->str(), "2"); ASSERT_EQUALS(token->tokAt(2)->str(), "3"); - if(last->next()) + if (last->next()) ASSERT_EQUALS("Null was expected", ""); ASSERT_EQUALS(last->str(), "3"); ASSERT_EQUALS(last->previous()->str(), "2"); ASSERT_EQUALS(last->tokAt(-2)->str(), "1"); - if(token->previous()) + if (token->previous()) ASSERT_EQUALS("Null was expected", ""); Tokenizer::deleteTokens(token); diff --git a/test/testtokenize.cpp b/test/testtokenize.cpp index e83c4620b..ac35d28fa 100644 --- a/test/testtokenize.cpp +++ b/test/testtokenize.cpp @@ -210,9 +210,9 @@ private: bool cmptok(const char *expected[], const Token *actual) { unsigned int i = 0; - for(; expected[i] && actual; ++i, actual = actual->next()) + for (; expected[i] && actual; ++i, actual = actual->next()) { - if(strcmp(expected[i], actual->str().c_str()) != 0) + if (strcmp(expected[i], actual->str().c_str()) != 0) return false; } return (expected[i] == NULL && actual == NULL); @@ -225,29 +225,29 @@ private: Tokenizer tokenizer; std::istringstream istr(code); tokenizer.tokenize(istr, "test.cpp"); - if(simplify) + if (simplify) tokenizer.simplifyTokenList(); std::ostringstream ostr; - for(const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) { - if(!simplify) + if (!simplify) { - if(tok->isUnsigned()) + if (tok->isUnsigned()) ostr << "unsigned "; - else if(tok->isSigned()) + else if (tok->isSigned()) ostr << "signed "; } - if(tok->isLong()) + if (tok->isLong()) ostr << "long "; ostr << tok->str(); // Append newlines - if(tok->next()) + if (tok->next()) { - if(tok->linenr() != tok->next()->linenr()) + if (tok->linenr() != tok->next()->linenr()) { - for(unsigned int i = tok->linenr(); i < tok->next()->linenr(); ++i) + for (unsigned int i = tok->linenr(); i < tok->next()->linenr(); ++i) ostr << "\n"; } else @@ -352,7 +352,7 @@ private: tokenizer.simplifyCasts(); std::ostringstream ostr; - for(const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) ostr << " " << tok->str(); ASSERT_EQUALS(" int * f ( int * ) ;", ostr.str()); } @@ -370,7 +370,7 @@ private: tokenizer.simplifyCasts(); std::ostringstream ostr; - for(const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) ostr << " " << tok->str(); ASSERT_EQUALS(" t = ( & p ) ;", ostr.str()); } @@ -449,7 +449,7 @@ private: tokenizer.fillFunctionList(); ASSERT_EQUALS(3, static_cast(tokenizer._functionList.size())); - if(tokenizer._functionList.size() == 3) + if (tokenizer._functionList.size() == 3) { ASSERT_EQUALS("a", tokenizer._functionList[0]->str()); ASSERT_EQUALS("b", tokenizer._functionList[1]->str()); @@ -712,9 +712,9 @@ private: tokenizer.simplifyKnownVariables(); std::ostringstream ostr; - for(const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) { - if(tok->previous()) + if (tok->previous()) ostr << " "; ostr << tok->str(); } @@ -1171,7 +1171,7 @@ private: std::istringstream istr(code); tokenizer.tokenize(istr, "test.cpp"); - if(simplify) + if (simplify) tokenizer.simplifyTokenList(); // result.. @@ -1919,7 +1919,7 @@ private: std::istringstream istr(code); tokenizer.tokenize(istr, "a"); - for(const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) { std::ostringstream ostr; ostr << char('a' + tok->fileIndex()) << tok->linenr(); @@ -1951,7 +1951,7 @@ private: std::istringstream istr(code); tokenizer.tokenize(istr, "a"); - for(const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) { std::ostringstream ostr; ostr << char('a' + tok->fileIndex()) << tok->linenr(); @@ -1990,7 +1990,7 @@ private: // Stringify the tokens.. std::ostringstream ostr; - for(const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) ostr << tok->str() << " "; ASSERT_EQUALS("TEST ( var , val ) var ## _ ## val = val ", ostr.str()); @@ -2007,7 +2007,7 @@ private: // Stringify the tokens.. std::ostringstream ostr; - for(const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) ostr << tok->str() << " "; ASSERT_EQUALS("DBG ( fmt , args . . . ) printf ( fmt , ## args ) ", ostr.str()); @@ -2060,7 +2060,7 @@ private: tokenizer.simplifyTokenList(); std::ostringstream ostr; - for(const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) ostr << " " << tok->str(); ASSERT_EQUALS(" void foo ( ) { free ( p ) ; }", ostr.str()); } @@ -2081,7 +2081,7 @@ private: tokenizer.simplifyTokenList(); std::ostringstream ostr; - for(const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) ostr << " " << tok->str(); ASSERT_EQUALS(" void foo ( ) { if ( ! s ) { return ; } }", ostr.str()); } @@ -2102,7 +2102,7 @@ private: tokenizer.simplifyTokenList(); std::ostringstream ostr; - for(const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) ostr << " " << tok->str(); ASSERT_EQUALS(" void foo ( ) { { } }", ostr.str()); } @@ -2121,7 +2121,7 @@ private: tokenizer.simplifyTokenList(); std::ostringstream ostr; - for(const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) ostr << " " << tok->str(); ASSERT_EQUALS(" void foo ( ) { { } }", ostr.str()); } @@ -2140,7 +2140,7 @@ private: tokenizer.simplifyTokenList(); std::ostringstream ostr; - for(const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) ostr << " " << tok->str(); ASSERT_EQUALS(" void foo ( ) { if ( g ( 10 ) ) { } }", ostr.str()); } @@ -2162,7 +2162,7 @@ private: tokenizer.simplifyTokenList(); std::ostringstream ostr; - for(const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) ostr << " " << tok->str(); ASSERT_EQUALS(" void foo ( ) { free ( p ) ; }", ostr.str()); } @@ -2184,7 +2184,7 @@ private: tokenizer.simplifyTokenList(); std::ostringstream ostr; - for(const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) ostr << " " << tok->str(); ASSERT_EQUALS(" void foo ( ) { delete p ; }", ostr.str()); } @@ -2204,7 +2204,7 @@ private: tokenizer.simplifyTokenList(); std::ostringstream ostr; - for(const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) ostr << " " << tok->str(); ASSERT_EQUALS(" void foo ( ) { delete [ ] p ; }", ostr.str()); } @@ -2223,7 +2223,7 @@ private: tokenizer.simplifyTokenList(); std::ostringstream ostr; - for(const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) ostr << " " << tok->str(); ASSERT_EQUALS(" ( ! abc . a )", ostr.str()); } @@ -2245,7 +2245,7 @@ private: tokenizer.tokenize(istr, "test.cpp"); std::ostringstream ostr; - for(const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) ostr << " " << tok->str(); ASSERT_EQUALS(" void f ( ) { double a ; a = 4.2 ; float b ; b = 4.2f ; double c ; c = 4.2e+10 ; double d ; d = 4.2e-10 ; int e ; e = 4 + 2 ; }", ostr.str()); } @@ -2269,7 +2269,7 @@ private: tokenizer.simplifyTokenList(); std::ostringstream ostr; - for(const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) ostr << " " << tok->str(); ASSERT_EQUALS(" void f ( ) { const char * a ; a = { \"hello more world\" } ; }", ostr.str()); } @@ -2297,7 +2297,7 @@ private: tokenizer.simplifyTokenList(); std::ostringstream ostr; - for(const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) ostr << " " << tok->str(); ASSERT_EQUALS(" void f ( ) { const int a = 45 ; { ; ; } } void g ( ) { ; ; }", ostr.str()); } @@ -2321,7 +2321,7 @@ private: tokenizer.simplifyTokenList(); std::ostringstream ostr; - for(const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) ostr << " " << tok->str(); std::ostringstream oss; @@ -2758,7 +2758,7 @@ private: tokenizer.tokenize(istr, "test.cpp"); tokenizer.updateClassList(); ASSERT_EQUALS(2, tokenizer._classInfoList["A"]._memberFunctions.size()); - if(tokenizer._classInfoList["A"]._memberFunctions.size() > 1) + if (tokenizer._classInfoList["A"]._memberFunctions.size() > 1) { ASSERT_EQUALS(std::string("f"), tokenizer._classInfoList["A"]._memberFunctions[0]._name); ASSERT_EQUALS(std::string("f"), tokenizer._classInfoList["A"]._memberFunctions[0]._declaration->str()); @@ -2930,13 +2930,13 @@ private: tokenizer.tokenize(istr, "test.cpp"); tokenizer.simplifyFunctionPointers(); std::ostringstream ostr; - for(const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) { - if(tok->isUnsigned()) + if (tok->isUnsigned()) ostr << " unsigned"; - else if(tok->isSigned()) + else if (tok->isSigned()) ostr << " signed"; - if(tok->isLong()) + if (tok->isLong()) ostr << " long"; ostr << (tok->isName() ? " " : "") << tok->str(); } @@ -2982,9 +2982,9 @@ private: tokenizer.tokenize(istr, "test.cpp"); std::ostringstream ostr; - for(const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) { - if(tok->isName()) + if (tok->isName()) ostr << " "; ostr << tok->str(); } diff --git a/test/testunusedvar.cpp b/test/testunusedvar.cpp index c321c0f9d..8ed5fb9ac 100644 --- a/test/testunusedvar.cpp +++ b/test/testunusedvar.cpp @@ -347,7 +347,7 @@ private: void localvarOp() { const char op[] = "+-*/%&|^"; - for(const char *p = op; *p; ++p) + for (const char *p = op; *p; ++p) { std::string code("int main()\n" "{\n" diff --git a/tools/dmake.cpp b/tools/dmake.cpp index 2fa8cef5c..f674c9817 100644 --- a/tools/dmake.cpp +++ b/tools/dmake.cpp @@ -39,34 +39,34 @@ std::string objfile(std::string cppfile) void getDeps(const std::string &filename, std::vector &depfiles) { // Is the dependency already included? - if(std::find(depfiles.begin(), depfiles.end(), filename) != depfiles.end()) + if (std::find(depfiles.begin(), depfiles.end(), filename) != depfiles.end()) return; std::ifstream f(filename.c_str()); - if(! f.is_open()) + if (! f.is_open()) { - if(filename.compare(0, 4, "cli/") == 0 || filename.compare(0, 5, "test/") == 0) + if (filename.compare(0, 4, "cli/") == 0 || filename.compare(0, 5, "test/") == 0) getDeps("lib" + filename.substr(filename.find("/")), depfiles); return; } - if(filename.find(".c") == std::string::npos) + if (filename.find(".c") == std::string::npos) depfiles.push_back(filename); std::string path(filename); - if(path.find("/") != std::string::npos) + if (path.find("/") != std::string::npos) path.erase(1 + path.rfind("/")); std::string line; - while(std::getline(f, line)) + while (std::getline(f, line)) { std::string::size_type pos1 = line.find("#include \""); - if(pos1 == std::string::npos) + if (pos1 == std::string::npos) continue; pos1 += 10; std::string::size_type pos2 = line.find("\"", pos1); std::string hfile(path + line.substr(pos1, pos2 - pos1)); - if(hfile.find("/../") != std::string::npos) // TODO: Ugly fix + if (hfile.find("/../") != std::string::npos) // TODO: Ugly fix hfile.erase(0, 4 + hfile.find("/../")); getDeps(hfile, depfiles); } @@ -74,12 +74,12 @@ void getDeps(const std::string &filename, std::vector &depfiles) static void compilefiles(std::ostream &fout, const std::vector &files) { - for(unsigned int i = 0; i < files.size(); ++i) + for (unsigned int i = 0; i < files.size(); ++i) { fout << objfile(files[i]) << ": " << files[i]; std::vector depfiles; getDeps(files[i], depfiles); - for(unsigned int dep = 0; dep < depfiles.size(); ++dep) + for (unsigned int dep = 0; dep < depfiles.size(); ++dep) fout << " " << depfiles[dep]; fout << "\n\t$(CXX) $(CXXFLAGS) -Ilib -c -o " << objfile(files[i]) << " " << files[i] << "\n\n"; } @@ -89,9 +89,9 @@ static void getCppFiles(std::vector &files, const std::string &path { getFileLister()->recursiveAddFiles(files, path, true); // only get *.cpp files.. - for(std::vector::iterator it = files.begin(); it != files.end();) + for (std::vector::iterator it = files.begin(); it != files.end();) { - if(it->find(".cpp") == std::string::npos) + if (it->find(".cpp") == std::string::npos) it = files.erase(it); else ++it; @@ -116,25 +116,25 @@ int main(int argc, char **argv) // QMAKE - lib/lib.pri { std::ofstream fout1("lib/lib.pri"); - if(fout1.is_open()) + if (fout1.is_open()) { fout1 << "# no manual edits - this file is autogenerated by dmake\n\n"; fout1 << "HEADERS += $$PWD/check.h \\\n"; - for(unsigned int i = 0; i < libfiles.size(); ++i) + for (unsigned int i = 0; i < libfiles.size(); ++i) { std::string fname(libfiles[i].substr(4)); - if(fname.find(".cpp") == std::string::npos) + if (fname.find(".cpp") == std::string::npos) continue; // shouldn't happen fname.erase(fname.find(".cpp")); fout1 << std::string(11, ' ') << "$$PWD/" << fname << ".h"; - if(i < libfiles.size() - 1) + if (i < libfiles.size() - 1) fout1 << " \\\n"; } fout1 << "\n\nSOURCES += "; - for(unsigned int i = 0; i < libfiles.size(); ++i) + for (unsigned int i = 0; i < libfiles.size(); ++i) { fout1 << "$$PWD/" << libfiles[i].substr(4); - if(i < libfiles.size() - 1) + if (i < libfiles.size() - 1) fout1 << " \\\n" << std::string(11, ' '); } fout1 << "\n"; @@ -159,15 +159,15 @@ int main(int argc, char **argv) fout << "\n###### Object Files\n\n"; fout << "LIBOBJ = " << objfile(libfiles[0]); - for(unsigned int i = 1; i < libfiles.size(); ++i) + for (unsigned int i = 1; i < libfiles.size(); ++i) fout << " \\" << std::endl << std::string(14, ' ') << objfile(libfiles[i]); fout << "\n\n"; fout << "CLIOBJ = " << objfile(clifiles[0]); - for(unsigned int i = 1; i < clifiles.size(); ++i) + for (unsigned int i = 1; i < clifiles.size(); ++i) fout << " \\" << std::endl << std::string(14, ' ') << objfile(clifiles[i]); fout << "\n\n"; fout << "TESTOBJ = " << objfile(testfiles[0]); - for(unsigned int i = 1; i < testfiles.size(); ++i) + for (unsigned int i = 1; i < testfiles.size(); ++i) fout << " \\" << std::endl << std::string(14, ' ') << objfile(testfiles[i]); fout << "\n\n"; diff --git a/tools/extracttests.cpp b/tools/extracttests.cpp index bf3d9ef0a..c81a3c191 100644 --- a/tools/extracttests.cpp +++ b/tools/extracttests.cpp @@ -15,7 +15,7 @@ static std::string str(unsigned int value) int main(const int argc, const char * const * const argv) { - if(argc != 2) + if (argc != 2) { std::cerr << "syntax: extracttests testfile" << std::endl; return 0; @@ -26,136 +26,136 @@ int main(const int argc, const char * const * const argv) std::ifstream f(argv[1]); std::string line; - while(std::getline(f, line)) + while (std::getline(f, line)) { { std::string::size_type pos = line.find_first_not_of(" "); - if(pos > 0 && pos != std::string::npos) + if (pos > 0 && pos != std::string::npos) line.erase(0, pos); } - if(line.compare(0, 5, "void ") == 0) + if (line.compare(0, 5, "void ") == 0) { testname = line.substr(5, line.size() - 7); subcount = 0; continue; } - if(line == "}") + if (line == "}") { testname = ""; subcount = 0; continue; } - if(!testname.empty() && line.compare(0, 5, "check") == 0 && line.find("(\"") != std::string::npos) + if (!testname.empty() && line.compare(0, 5, "check") == 0 && line.find("(\"") != std::string::npos) { std::ofstream fout((testname + str(++subcount) + ext).c_str()); fout << "#include " << std::endl; fout << "#include " << std::endl; fout << "#include " << std::endl; - if(testname == "nullpointer1") + if (testname == "nullpointer1") { - if(subcount < 6) + if (subcount < 6) { fout << "class Token\n" - << "{\n" - << "public:\n" - << " const char *str() const;\n" - << " const Token *next() const;\n" - << " unsigned int size() const;\n" - << " char read () const;\n" - << " operator bool() const;\n" - << "};\n" - << "static Token *tokens;\n"; + << "{\n" + << "public:\n" + << " const char *str() const;\n" + << " const Token *next() const;\n" + << " unsigned int size() const;\n" + << " char read () const;\n" + << " operator bool() const;\n" + << "};\n" + << "static Token *tokens;\n"; } else { fout << "struct A\n" - "{\n" - " char b();\n" - " A *next;\n" - "};\n"; + "{\n" + " char b();\n" + " A *next;\n" + "};\n"; } } - if(testname == "nullpointer2") + if (testname == "nullpointer2") { fout << "class Fred\n" - << "{\n" - << "public:\n" - << " void hello() const;\n" - << " operator bool() const;\n" - << "};\n"; + << "{\n" + << "public:\n" + << " void hello() const;\n" + << " operator bool() const;\n" + << "};\n"; } - if(testname == "nullpointer3") + if (testname == "nullpointer3") { fout << "struct DEF { };\n" - << "struct ABC : public DEF\n" - << "{\n" - << " int a,b,c;\n" - << " struct ABC *next;\n" - << "};\n" - << "void bar(int); void f(struct ABC **);\n"; + << "struct ABC : public DEF\n" + << "{\n" + << " int a,b,c;\n" + << " struct ABC *next;\n" + << "};\n" + << "void bar(int); void f(struct ABC **);\n"; } - if(testname == "nullpointer4") + if (testname == "nullpointer4") { fout << "void bar(int);\n" - << "int** f(int **p = 0);\n" - << "extern int x;\n" - << "struct P {\n" - << " bool check() const;\n" - << " P* next() const;\n" - << "};\n"; + << "int** f(int **p = 0);\n" + << "extern int x;\n" + << "struct P {\n" + << " bool check() const;\n" + << " P* next() const;\n" + << "};\n"; } - if(testname == "nullpointer5") + if (testname == "nullpointer5") { fout << "struct A {\n" - << " char c() const;\n" - << " operator bool() const;\n" - << "};\n"; + << " char c() const;\n" + << " operator bool() const;\n" + << "};\n"; } - if(testname == "nullpointer6") + if (testname == "nullpointer6") { fout << "struct Foo {\n" - << " void abcd() const;\n" - << "};\n" - << "struct FooBar : public Foo { };\n" - << "struct FooCar : public Foo { };\n" - << "extern int a;\n"; + << " void abcd() const;\n" + << "};\n" + << "struct FooBar : public Foo { };\n" + << "struct FooCar : public Foo { };\n" + << "extern int a;\n"; } - if(testname == "nullpointer7") + if (testname == "nullpointer7") { fout << "struct wxLongLong {\n" - << " wxLongLong(int) { }\n" - << " long GetValue() const;\n" - << "};\n"; + << " wxLongLong(int) { }\n" + << " long GetValue() const;\n" + << "};\n"; } do { std::string::size_type pos = line.find("\""); - if(pos == std::string::npos) + if (pos == std::string::npos) break; line.erase(0, pos + 1); pos = line.rfind("\""); - if(pos == std::string::npos) + if (pos == std::string::npos) break; const bool lastline(line.find(");", pos) != std::string::npos); line.erase(pos); pos = 0; - while((pos = line.find("\\", pos)) != std::string::npos) + while ((pos = line.find("\\", pos)) != std::string::npos) { line.erase(pos, 1); - if(line[pos] == 'n') + if (line[pos] == 'n') line.erase(pos, 1); else ++pos; @@ -163,10 +163,10 @@ int main(const int argc, const char * const * const argv) fout << line << std::endl; - if(lastline) + if (lastline) break; } - while(std::getline(f, line)); + while (std::getline(f, line)); fout << std::endl; continue; }