astyle fix

This commit is contained in:
Martin Ettl 2010-04-02 02:21:53 +02:00
parent b5fb01c202
commit 193aa7d1d3
64 changed files with 4595 additions and 4593 deletions

View File

@ -41,25 +41,25 @@ int CppCheckExecutor::check(int argc, const char* const argv[])
{ {
cppCheck.parseFromArgs(argc, argv); cppCheck.parseFromArgs(argc, argv);
} }
catch (std::runtime_error &e) catch(std::runtime_error &e)
{ {
std::cerr << e.what() << std::endl; std::cerr << e.what() << std::endl;
return EXIT_FAILURE; return EXIT_FAILURE;
} }
_settings = cppCheck.settings(); _settings = cppCheck.settings();
if (_settings._xml) if(_settings._xml)
{ {
reportErr(ErrorLogger::ErrorMessage::getXMLHeader()); reportErr(ErrorLogger::ErrorMessage::getXMLHeader());
} }
unsigned int returnValue = 0; unsigned int returnValue = 0;
if (_settings._jobs == 1) if(_settings._jobs == 1)
{ {
// Single process // Single process
returnValue = cppCheck.check(); returnValue = cppCheck.check();
} }
else if (!ThreadExecutor::isEnabled()) else if(!ThreadExecutor::isEnabled())
{ {
std::cout << "No thread support yet implemented for this platform." << std::endl; 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(); returnValue = executor.check();
} }
if (_settings._xml) if(_settings._xml)
{ {
reportErr(ErrorLogger::ErrorMessage::getXMLFooter()); reportErr(ErrorLogger::ErrorMessage::getXMLFooter());
} }
if (returnValue) if(returnValue)
return _settings._exitCode; return _settings._exitCode;
else else
return 0; return 0;
@ -95,12 +95,12 @@ void CppCheckExecutor::reportOut(const std::string &outmsg)
void CppCheckExecutor::reportStatus(unsigned int index, unsigned int max) void CppCheckExecutor::reportStatus(unsigned int index, unsigned int max)
{ {
if (max > 1 && !_settings._errorsOnly) if(max > 1 && !_settings._errorsOnly)
{ {
std::ostringstream oss; std::ostringstream oss;
oss << index << "/" << max oss << index << "/" << max
<< " files checked " << << " files checked " <<
static_cast<int>(static_cast<double>(index) / max*100) static_cast<int>(static_cast<double>(index) / max * 100)
<< "% done"; << "% done";
std::cout << oss.str() << std::endl; std::cout << oss.str() << std::endl;
} }
@ -108,7 +108,7 @@ void CppCheckExecutor::reportStatus(unsigned int index, unsigned int max)
void CppCheckExecutor::reportErr(const ErrorLogger::ErrorMessage &msg) void CppCheckExecutor::reportErr(const ErrorLogger::ErrorMessage &msg)
{ {
if (_settings._xml) if(_settings._xml)
{ {
reportErr(msg.toXML()); reportErr(msg.toXML());
} }

View File

@ -49,49 +49,49 @@ ThreadExecutor::~ThreadExecutor()
bool ThreadExecutor::handleRead(unsigned int &result) bool ThreadExecutor::handleRead(unsigned int &result)
{ {
char type = 0; char type = 0;
if (read(_pipe[0], &type, 1) <= 0) if(read(_pipe[0], &type, 1) <= 0)
{ {
return false; 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; std::cerr << "#### You found a bug from cppcheck.\nThreadExecutor::handleRead error, type was:" << type << std::endl;
exit(0); exit(0);
} }
unsigned int len = 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; std::cerr << "#### You found a bug from cppcheck.\nThreadExecutor::handleRead error, type was:" << type << std::endl;
exit(0); exit(0);
} }
char *buf = new char[len]; 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; std::cerr << "#### You found a bug from cppcheck.\nThreadExecutor::handleRead error, type was:" << type << std::endl;
exit(0); exit(0);
} }
if (type == '1') if(type == '1')
{ {
_errorLogger.reportOut(buf); _errorLogger.reportOut(buf);
} }
else if (type == '2') else if(type == '2')
{ {
ErrorLogger::ErrorMessage msg; ErrorLogger::ErrorMessage msg;
msg.deserialize(buf); msg.deserialize(buf);
// Alert only about unique errors // Alert only about unique errors
std::string errmsg = msg.toText(); 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); _errorList.push_back(errmsg);
_errorLogger.reportErr(msg); _errorLogger.reportErr(msg);
} }
} }
else if (type == '3') else if(type == '3')
{ {
_fileCount++; _fileCount++;
std::istringstream iss(buf); std::istringstream iss(buf);
@ -109,32 +109,32 @@ unsigned int ThreadExecutor::check()
{ {
_fileCount = 0; _fileCount = 0;
unsigned int result = 0; unsigned int result = 0;
if (pipe(_pipe) == -1) if(pipe(_pipe) == -1)
{ {
perror("pipe"); perror("pipe");
exit(1); exit(1);
} }
int flags = 0; int flags = 0;
if ((flags = fcntl(_pipe[0], F_GETFL, 0)) < 0) if((flags = fcntl(_pipe[0], F_GETFL, 0)) < 0)
{ {
perror("fcntl"); perror("fcntl");
exit(1); exit(1);
} }
if (fcntl(_pipe[0], F_SETFL, flags | O_NONBLOCK) < 0) if(fcntl(_pipe[0], F_SETFL, flags | O_NONBLOCK) < 0)
{ {
perror("fcntl"); perror("fcntl");
exit(1); exit(1);
} }
unsigned int childCount = 0; 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. // 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(); pid_t pid = fork();
if (pid < 0) if(pid < 0)
{ {
// Error // Error
std::cerr << "Failed to create child process" << std::endl; std::cerr << "Failed to create child process" << std::endl;
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
else if (pid == 0) else if(pid == 0)
{ {
CppCheck fileChecker(*this); CppCheck fileChecker(*this);
fileChecker.settings(_settings); fileChecker.settings(_settings);
@ -166,14 +166,14 @@ unsigned int ThreadExecutor::check()
++childCount; ++childCount;
} }
while (childCount > 0) while(childCount > 0)
{ {
int stat = 0; int stat = 0;
waitpid(0, &stat, 0); waitpid(0, &stat, 0);
--childCount; --childCount;
} }
while (handleRead(result)) while(handleRead(result))
{ {
} }
@ -188,7 +188,7 @@ void ThreadExecutor::writeToPipe(char type, const std::string &data)
out[0] = type; out[0] = type;
std::memcpy(&(out[1]), &len, sizeof(len)); std::memcpy(&(out[1]), &len, sizeof(len));
std::memcpy(&(out[1+sizeof(len)]), data.c_str(), 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; delete [] out;
out = 0; out = 0;

View File

@ -61,13 +61,13 @@ void ApplicationDialog::Browse()
QString(), QString(),
filter); filter);
if (!selectedFile.isEmpty()) if(!selectedFile.isEmpty())
{ {
QString path(QDir::toNativeSeparators(selectedFile)); QString path(QDir::toNativeSeparators(selectedFile));
// In Windows we must surround paths including spaces with quotation marks. // In Windows we must surround paths including spaces with quotation marks.
#ifdef Q_WS_WIN #ifdef Q_WS_WIN
if (path.indexOf(" ") > -1) if(path.indexOf(" ") > -1)
{ {
path.insert(0, "\""); path.insert(0, "\"");
path.append("\""); path.append("\"");
@ -91,7 +91,7 @@ QString ApplicationDialog::GetPath()
void ApplicationDialog::Ok() 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, QMessageBox msg(QMessageBox::Warning,
tr("Cppcheck"), tr("Cppcheck"),

View File

@ -37,9 +37,9 @@ void ApplicationList::LoadSettings(QSettings *programSettings)
QStringList names = programSettings->value(SETTINGS_APPLICATION_NAMES, QStringList()).toStringList(); QStringList names = programSettings->value(SETTINGS_APPLICATION_NAMES, QStringList()).toStringList();
QStringList paths = programSettings->value(SETTINGS_APPLICATION_PATHS, 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]); AddApplicationType(names[i], paths[i]);
} }
@ -51,7 +51,7 @@ void ApplicationList::SaveSettings(QSettings *programSettings)
QStringList names; QStringList names;
QStringList paths; QStringList paths;
for (int i = 0; i < GetApplicationCount(); i++) for(int i = 0; i < GetApplicationCount(); i++)
{ {
names << GetApplicationName(i); names << GetApplicationName(i);
paths << GetApplicationPath(i); paths << GetApplicationPath(i);
@ -69,7 +69,7 @@ int ApplicationList::GetApplicationCount() const
QString ApplicationList::GetApplicationName(const int index) const QString ApplicationList::GetApplicationName(const int index) const
{ {
if (index >= 0 && index < mApplications.size()) if(index >= 0 && index < mApplications.size())
{ {
return mApplications[index].Name; return mApplications[index].Name;
} }
@ -79,7 +79,7 @@ QString ApplicationList::GetApplicationName(const int index) const
QString ApplicationList::GetApplicationPath(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; return mApplications[index].Path;
} }
@ -93,7 +93,7 @@ void ApplicationList::SetApplicationType(const int index,
const QString &name, const QString &name,
const QString &path) const QString &path)
{ {
if (index >= 0 && index < mApplications.size()) if(index >= 0 && index < mApplications.size())
{ {
mApplications[index].Name = name; mApplications[index].Name = name;
mApplications[index].Path = path; mApplications[index].Path = path;
@ -102,7 +102,7 @@ void ApplicationList::SetApplicationType(const int index,
void ApplicationList::AddApplicationType(const QString &name, const QString &path) void ApplicationList::AddApplicationType(const QString &name, const QString &path)
{ {
if (name.isEmpty() || path.isEmpty()) if(name.isEmpty() || path.isEmpty())
{ {
return; return;
} }
@ -121,7 +121,7 @@ void ApplicationList::RemoveApplication(const int index)
void ApplicationList::MoveFirst(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); mApplications.move(index, 0);
} }
@ -130,13 +130,13 @@ void ApplicationList::MoveFirst(const int index)
void ApplicationList::Copy(ApplicationList *list) void ApplicationList::Copy(ApplicationList *list)
{ {
if (!list) if(!list)
{ {
return; return;
} }
Clear(); Clear();
for (int i = 0; i < list->GetApplicationCount(); i++) for(int i = 0; i < list->GetApplicationCount(); i++)
{ {
AddApplicationType(list->GetApplicationName(i), list->GetApplicationPath(i)); AddApplicationType(list->GetApplicationName(i), list->GetApplicationPath(i));
} }

View File

@ -45,7 +45,7 @@ void CheckThread::run()
QString file; QString file;
file = mResult.GetNextFile(); file = mResult.GetNextFile();
while (!file.isEmpty() && mState == Running) while(!file.isEmpty() && mState == Running)
{ {
qDebug() << "Checking file" << file; qDebug() << "Checking file" << file;
mCppcheck.addFile(file.toStdString()); mCppcheck.addFile(file.toStdString());
@ -53,10 +53,10 @@ void CheckThread::run()
mCppcheck.clearFiles(); mCppcheck.clearFiles();
emit FileChecked(file); emit FileChecked(file);
if (mState == Running) if(mState == Running)
file = mResult.GetNextFile(); file = mResult.GetNextFile();
} }
if (mState == Running) if(mState == Running)
mState = Ready; mState = Ready;
else else
mState = Stopped; mState = Stopped;

View File

@ -33,7 +33,7 @@ CsvReport::~CsvReport()
bool CsvReport::Create() bool CsvReport::Create()
{ {
bool success = false; bool success = false;
if (Report::Create()) if(Report::Create())
{ {
mTxtWriter.setDevice(Report::GetFile()); mTxtWriter.setDevice(Report::GetFile());
success = true; success = true;

View File

@ -42,7 +42,7 @@ FileViewDialog::FileViewDialog(const QString &file,
void FileViewDialog::LoadTextFile(const QString &filename, QTextEdit *edit) void FileViewDialog::LoadTextFile(const QString &filename, QTextEdit *edit)
{ {
QFile file(filename); QFile file(filename);
if (!file.exists()) if(!file.exists())
{ {
QString msg(tr("Could not find the file: %1")); QString msg(tr("Could not find the file: %1"));
msg = msg.arg(filename); msg = msg.arg(filename);
@ -57,7 +57,7 @@ void FileViewDialog::LoadTextFile(const QString &filename, QTextEdit *edit)
} }
file.open(QIODevice::ReadOnly | QIODevice::Text); file.open(QIODevice::ReadOnly | QIODevice::Text);
if (!file.isReadable()) if(!file.isReadable())
{ {
QString msg(tr("Could not read the file: %1")); QString msg(tr("Could not read the file: %1"));
msg = msg.arg(filename); msg = msg.arg(filename);

View File

@ -102,7 +102,7 @@ MainWindow::MainWindow() :
QStringList args = QCoreApplication::arguments(); QStringList args = QCoreApplication::arguments();
//Remove the application itself //Remove the application itself
args.removeFirst(); args.removeFirst();
if (!args.isEmpty()) if(!args.isEmpty())
{ {
DoCheckFiles(args); DoCheckFiles(args);
} }
@ -116,7 +116,7 @@ void MainWindow::CreateLanguageMenuItems()
{ {
QStringList languages = mTranslation->GetNames(); 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 //Create an action for each language
//Language name is pre translated //Language name is pre translated
@ -131,7 +131,7 @@ void MainWindow::CreateLanguageMenuItems()
mLanguages->addAction(temp); mLanguages->addAction(temp);
//Check it if it's the value stored to settings //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); temp->setChecked(true);
} }
@ -147,7 +147,7 @@ void MainWindow::CreateLanguageMenuItems()
void MainWindow::LoadSettings() void MainWindow::LoadSettings()
{ {
if (mSettings->value(SETTINGS_WINDOW_MAXIMIZED, false).toBool()) if(mSettings->value(SETTINGS_WINDOW_MAXIMIZED, false).toBool())
{ {
showMaximized(); showMaximized();
} }
@ -198,7 +198,7 @@ void MainWindow::SaveSettings()
void MainWindow::DoCheckFiles(const QStringList &files) void MainWindow::DoCheckFiles(const QStringList &files)
{ {
if (files.isEmpty()) if(files.isEmpty())
{ {
return; return;
} }
@ -215,7 +215,7 @@ void MainWindow::DoCheckFiles(const QStringList &files)
mUI.mResults->Clear(); mUI.mResults->Clear();
mThread->ClearFiles(); mThread->ClearFiles();
if (fileNames.isEmpty()) if(fileNames.isEmpty())
{ {
QMessageBox msg(QMessageBox::Warning, QMessageBox msg(QMessageBox::Warning,
tr("Cppcheck"), tr("Cppcheck"),
@ -248,12 +248,12 @@ QStringList MainWindow::SelectFilesToCheck(QFileDialog::FileMode mode)
// NOTE: we use QFileDialog::getOpenFileNames() and // NOTE: we use QFileDialog::getOpenFileNames() and
// QFileDialog::getExistingDirectory() because they show native Windows // QFileDialog::getExistingDirectory() because they show native Windows
// selection dialog which is a lot more usable than QT:s own dialog. // 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, selected = QFileDialog::getOpenFileNames(this,
tr("Select files to check"), tr("Select files to check"),
mSettings->value(SETTINGS_CHECK_PATH, "").toString()); mSettings->value(SETTINGS_CHECK_PATH, "").toString());
if (selected.isEmpty()) if(selected.isEmpty())
mCurrentDirectory.clear(); mCurrentDirectory.clear();
else else
{ {
@ -262,12 +262,12 @@ QStringList MainWindow::SelectFilesToCheck(QFileDialog::FileMode mode)
} }
FormatAndSetTitle(); FormatAndSetTitle();
} }
else if (mode == QFileDialog::DirectoryOnly) else if(mode == QFileDialog::DirectoryOnly)
{ {
QString dir = QFileDialog::getExistingDirectory(this, QString dir = QFileDialog::getExistingDirectory(this,
tr("Select directory to check"), tr("Select directory to check"),
mSettings->value(SETTINGS_CHECK_PATH, "").toString()); mSettings->value(SETTINGS_CHECK_PATH, "").toString());
if (!dir.isEmpty()) if(!dir.isEmpty())
{ {
mCurrentDirectory = dir; mCurrentDirectory = dir;
selected.append(dir); selected.append(dir);
@ -294,20 +294,20 @@ Settings MainWindow::GetCppcheckSettings()
ProjectFile pfile; ProjectFile pfile;
Settings result; Settings result;
if (!mCurrentDirectory.isEmpty()) if(!mCurrentDirectory.isEmpty())
{ {
// Format project filename (directory name + .cppcheck) and load // Format project filename (directory name + .cppcheck) and load
// the project file if it is found. // the project file if it is found.
QStringList parts = mCurrentDirectory.split("/"); QStringList parts = mCurrentDirectory.split("/");
QString projfile = mCurrentDirectory + "/" + parts[parts.count() - 1] + ".cppcheck"; QString projfile = mCurrentDirectory + "/" + parts[parts.count() - 1] + ".cppcheck";
bool projectRead = false; bool projectRead = false;
if (QFile::exists(projfile)) if(QFile::exists(projfile))
{ {
qDebug() << "Reading project file " << projfile; qDebug() << "Reading project file " << projfile;
projectRead = pfile.Read(projfile); projectRead = pfile.Read(projfile);
} }
if (projectRead) if(projectRead)
{ {
QStringList classes = pfile.GetDeAllocatedClasses(); QStringList classes = pfile.GetDeAllocatedClasses();
QString classname; QString classname;
@ -321,13 +321,13 @@ Settings MainWindow::GetCppcheckSettings()
foreach(dir, dirs) foreach(dir, dirs)
{ {
QString incdir; QString incdir;
if (!QDir::isAbsolutePath(dir)) if(!QDir::isAbsolutePath(dir))
incdir = mCurrentDirectory + "/"; incdir = mCurrentDirectory + "/";
incdir += dir; incdir += dir;
incdir = QDir::cleanPath(incdir); incdir = QDir::cleanPath(incdir);
// include paths must end with '/' // include paths must end with '/'
if (!incdir.endsWith("/")) if(!incdir.endsWith("/"))
incdir += "/"; incdir += "/";
result._includePaths.push_back(incdir.toStdString()); result._includePaths.push_back(incdir.toStdString());
} }
@ -343,7 +343,7 @@ Settings MainWindow::GetCppcheckSettings()
result._xml = false; result._xml = false;
result._jobs = mSettings->value(SETTINGS_CHECK_THREADS, 1).toInt(); result._jobs = mSettings->value(SETTINGS_CHECK_THREADS, 1).toInt();
if (result._jobs <= 0) if(result._jobs <= 0)
{ {
result._jobs = 1; result._jobs = 1;
} }
@ -356,11 +356,11 @@ QStringList MainWindow::GetFilesRecursively(const QString &path)
QFileInfo info(path); QFileInfo info(path);
QStringList list; QStringList list;
if (info.isDir()) if(info.isDir())
{ {
QDirIterator it(path, QDirIterator::Subdirectories); QDirIterator it(path, QDirIterator::Subdirectories);
while (it.hasNext()) while(it.hasNext())
{ {
list << it.next(); list << it.next();
} }
@ -379,7 +379,7 @@ QStringList MainWindow::RemoveUnacceptedFiles(const QStringList &list)
QString str; QString str;
foreach(str, list) foreach(str, list)
{ {
if (getFileLister()->acceptFile(str.toStdString())) if(getFileLister()->acceptFile(str.toStdString()))
{ {
result << str; result << str;
} }
@ -392,7 +392,7 @@ void MainWindow::CheckDone()
{ {
EnableCheckButtons(true); EnableCheckButtons(true);
mUI.mActionSettings->setEnabled(true); mUI.mActionSettings->setEnabled(true);
if (mUI.mResults->HasResults()) if(mUI.mResults->HasResults())
{ {
mUI.mActionClearResults->setEnabled(true); mUI.mActionClearResults->setEnabled(true);
mUI.mActionSave->setEnabled(true); mUI.mActionSave->setEnabled(true);
@ -405,7 +405,7 @@ void MainWindow::CheckDone()
void MainWindow::ProgramSettings() void MainWindow::ProgramSettings()
{ {
SettingsDialog dialog(mSettings, mApplications, this); SettingsDialog dialog(mSettings, mApplications, this);
if (dialog.exec() == QDialog::Accepted) if(dialog.exec() == QDialog::Accepted)
{ {
dialog.SaveCheckboxValues(); dialog.SaveCheckboxValues();
mUI.mResults->UpdateSettings(dialog.ShowFullPath(), mUI.mResults->UpdateSettings(dialog.ShowFullPath(),
@ -434,7 +434,7 @@ void MainWindow::EnableCheckButtons(bool enable)
mUI.mActionStop->setEnabled(!enable); mUI.mActionStop->setEnabled(!enable);
mUI.mActionCheckFiles->setEnabled(enable); mUI.mActionCheckFiles->setEnabled(enable);
if (!enable || mThread->HasPreviousFiles()) if(!enable || mThread->HasPreviousFiles())
mUI.mActionRecheck->setEnabled(enable); mUI.mActionRecheck->setEnabled(enable);
mUI.mActionCheckDirectory->setEnabled(enable); mUI.mActionCheckDirectory->setEnabled(enable);
@ -473,7 +473,7 @@ void MainWindow::UncheckAll()
void MainWindow::closeEvent(QCloseEvent *event) void MainWindow::closeEvent(QCloseEvent *event)
{ {
// Check that we aren't checking files // Check that we aren't checking files
if (!mThread->IsChecking()) if(!mThread->IsChecking())
{ {
SaveSettings(); SaveSettings();
event->accept(); event->accept();
@ -539,34 +539,34 @@ void MainWindow::Save()
filter, filter,
&selectedFilter); &selectedFilter);
if (!selectedFile.isEmpty()) if(!selectedFile.isEmpty())
{ {
Report::Type type = Report::TXT; Report::Type type = Report::TXT;
if (selectedFilter == tr("XML files (*.xml)")) if(selectedFilter == tr("XML files (*.xml)"))
{ {
type = Report::XML; type = Report::XML;
if (!selectedFile.endsWith(".xml", Qt::CaseInsensitive)) if(!selectedFile.endsWith(".xml", Qt::CaseInsensitive))
selectedFile += ".xml"; selectedFile += ".xml";
} }
else if (selectedFilter == tr("Text files (*.txt)")) else if(selectedFilter == tr("Text files (*.txt)"))
{ {
type = Report::TXT; type = Report::TXT;
if (!selectedFile.endsWith(".txt", Qt::CaseInsensitive)) if(!selectedFile.endsWith(".txt", Qt::CaseInsensitive))
selectedFile += ".txt"; selectedFile += ".txt";
} }
else if (selectedFilter == tr("CSV files (*.csv)")) else if(selectedFilter == tr("CSV files (*.csv)"))
{ {
type = Report::CSV; type = Report::CSV;
if (!selectedFile.endsWith(".csv", Qt::CaseInsensitive)) if(!selectedFile.endsWith(".csv", Qt::CaseInsensitive))
selectedFile += ".csv"; selectedFile += ".csv";
} }
else else
{ {
if (selectedFile.endsWith(".xml", Qt::CaseInsensitive)) if(selectedFile.endsWith(".xml", Qt::CaseInsensitive))
type = Report::XML; type = Report::XML;
else if (selectedFile.endsWith(".txt", Qt::CaseInsensitive)) else if(selectedFile.endsWith(".txt", Qt::CaseInsensitive))
type = Report::TXT; type = Report::TXT;
else if (selectedFile.endsWith(".csv", Qt::CaseInsensitive)) else if(selectedFile.endsWith(".csv", Qt::CaseInsensitive))
type = Report::CSV; type = Report::CSV;
} }
@ -586,7 +586,7 @@ void MainWindow::ToggleToolbar()
void MainWindow::FormatAndSetTitle(const QString &text) void MainWindow::FormatAndSetTitle(const QString &text)
{ {
QString title; QString title;
if (text.isEmpty()) if(text.isEmpty())
title = tr("Cppcheck"); title = tr("Cppcheck");
else else
title = QString(tr("Cppcheck - %1")).arg(text); title = QString(tr("Cppcheck - %1")).arg(text);
@ -596,13 +596,13 @@ void MainWindow::FormatAndSetTitle(const QString &text)
void MainWindow::SetLanguage(int index) void MainWindow::SetLanguage(int index)
{ {
if (mTranslation->GetCurrentLanguage() == index) if(mTranslation->GetCurrentLanguage() == index)
{ {
return; return;
} }
QString error; QString error;
if (!mTranslation->SetLanguage(index, error)) if(!mTranslation->SetLanguage(index, error))
{ {
QMessageBox msg(QMessageBox::Critical, QMessageBox msg(QMessageBox::Critical,
tr("Cppcheck"), tr("Cppcheck"),
@ -620,9 +620,9 @@ void MainWindow::SetLanguage(int index)
QStringList languages = mTranslation->GetNames(); QStringList languages = mTranslation->GetNames();
QList<QAction *> actions = mLanguages->actions(); QList<QAction *> 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())); 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 //Find the action that has the language that user clicked
QList<QAction *> actions = mLanguages->actions(); QList<QAction *> 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); SetLanguage(i);
} }

View File

@ -43,33 +43,33 @@ ProjectFile::ProjectFile(const QString &filename, QObject *parent) :
bool ProjectFile::Read(const QString &filename) bool ProjectFile::Read(const QString &filename)
{ {
if (!filename.isEmpty()) if(!filename.isEmpty())
mFilename = filename; mFilename = filename;
QFile file(mFilename); QFile file(mFilename);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
return false; return false;
QXmlStreamReader xmlReader(&file); QXmlStreamReader xmlReader(&file);
bool insideProject = false; bool insideProject = false;
while (!xmlReader.atEnd()) while(!xmlReader.atEnd())
{ {
switch (xmlReader.readNext()) switch(xmlReader.readNext())
{ {
case QXmlStreamReader::StartElement: case QXmlStreamReader::StartElement:
if (xmlReader.name() == ProjectElementName) if(xmlReader.name() == ProjectElementName)
insideProject = true; insideProject = true;
// Find allocelement from inside project element // Find allocelement from inside project element
if (insideProject && xmlReader.name() == AllocElementName) if(insideProject && xmlReader.name() == AllocElementName)
ReadAutoAllocClasses(xmlReader); ReadAutoAllocClasses(xmlReader);
if (insideProject && xmlReader.name() == IncludDirElementName) if(insideProject && xmlReader.name() == IncludDirElementName)
ReadIncludeDirs(xmlReader); ReadIncludeDirs(xmlReader);
break; break;
case QXmlStreamReader::EndElement: case QXmlStreamReader::EndElement:
if (xmlReader.name() == ProjectElementName) if(xmlReader.name() == ProjectElementName)
insideProject = false; insideProject = false;
break; break;
@ -108,22 +108,22 @@ void ProjectFile::ReadAutoAllocClasses(QXmlStreamReader &reader)
do do
{ {
type = reader.readNext(); type = reader.readNext();
switch (type) switch(type)
{ {
case QXmlStreamReader::StartElement: case QXmlStreamReader::StartElement:
// Read class-elements // Read class-elements
if (reader.name().toString() == ClassElementName) if(reader.name().toString() == ClassElementName)
{ {
QXmlStreamAttributes attribs = reader.attributes(); QXmlStreamAttributes attribs = reader.attributes();
QString name = attribs.value("", ClassNameAttrib).toString(); QString name = attribs.value("", ClassNameAttrib).toString();
if (!name.isEmpty()) if(!name.isEmpty())
mDeAllocatedClasses << name; mDeAllocatedClasses << name;
} }
break; break;
case QXmlStreamReader::EndElement: case QXmlStreamReader::EndElement:
if (reader.name().toString() == AllocElementName) if(reader.name().toString() == AllocElementName)
allRead = true; allRead = true;
break; break;
@ -140,7 +140,7 @@ void ProjectFile::ReadAutoAllocClasses(QXmlStreamReader &reader)
break; break;
} }
} }
while (!allRead); while(!allRead);
} }
void ProjectFile::ReadIncludeDirs(QXmlStreamReader &reader) void ProjectFile::ReadIncludeDirs(QXmlStreamReader &reader)
@ -150,22 +150,22 @@ void ProjectFile::ReadIncludeDirs(QXmlStreamReader &reader)
do do
{ {
type = reader.readNext(); type = reader.readNext();
switch (type) switch(type)
{ {
case QXmlStreamReader::StartElement: case QXmlStreamReader::StartElement:
// Read dir-elements // Read dir-elements
if (reader.name().toString() == DirElementName) if(reader.name().toString() == DirElementName)
{ {
QXmlStreamAttributes attribs = reader.attributes(); QXmlStreamAttributes attribs = reader.attributes();
QString name = attribs.value("", DirNameAttrib).toString(); QString name = attribs.value("", DirNameAttrib).toString();
if (!name.isEmpty()) if(!name.isEmpty())
mIncludeDirs << name; mIncludeDirs << name;
} }
break; break;
case QXmlStreamReader::EndElement: case QXmlStreamReader::EndElement:
if (reader.name().toString() == IncludDirElementName) if(reader.name().toString() == IncludDirElementName)
allRead = true; allRead = true;
break; break;
@ -182,5 +182,5 @@ void ProjectFile::ReadIncludeDirs(QXmlStreamReader &reader)
break; break;
} }
} }
while (!allRead); while(!allRead);
} }

View File

@ -33,7 +33,7 @@ Report::~Report()
bool Report::Create() bool Report::Create()
{ {
bool succeed = false; bool succeed = false;
if (!mFile.isOpen()) if(!mFile.isOpen())
{ {
mFile.setFileName(mFilename); mFile.setFileName(mFilename);
succeed = mFile.open(QIODevice::WriteOnly | QIODevice::Text); succeed = mFile.open(QIODevice::WriteOnly | QIODevice::Text);
@ -43,7 +43,7 @@ bool Report::Create()
void Report::Close() void Report::Close()
{ {
if (mFile.isOpen()) if(mFile.isOpen())
mFile.close(); mFile.close();
} }

View File

@ -34,7 +34,7 @@ ResultsTree::ResultsTree(QWidget * parent) :
mCheckPath(""), mCheckPath(""),
mVisibleErrors(false) mVisibleErrors(false)
{ {
for (int i = 0; i < SHOW_NONE; i++) for(int i = 0; i < SHOW_NONE; i++)
mShowTypes[i] = false; mShowTypes[i] = false;
setModel(&mModel); setModel(&mModel);
@ -76,14 +76,14 @@ void ResultsTree::AddErrorItem(const QString &file,
{ {
Q_UNUSED(file); Q_UNUSED(file);
if (files.isEmpty()) if(files.isEmpty())
{ {
return; return;
} }
QString realfile = StripPath(files[0], false); QString realfile = StripPath(files[0], false);
if (realfile.isEmpty()) if(realfile.isEmpty())
{ {
realfile = tr("Undefined file"); realfile = tr("Undefined file");
} }
@ -91,7 +91,7 @@ void ResultsTree::AddErrorItem(const QString &file,
bool hide = !mShowTypes[SeverityToShowType(severity)]; bool hide = !mShowTypes[SeverityToShowType(severity)];
//if there is at least one error that is not hidden, we have a visible error //if there is at least one error that is not hidden, we have a visible error
if (!hide) if(!hide)
{ {
mVisibleErrors = true; mVisibleErrors = true;
} }
@ -106,7 +106,7 @@ void ResultsTree::AddErrorItem(const QString &file,
hide, hide,
SeverityToIcon(severity)); SeverityToIcon(severity));
if (!item) if(!item)
return; return;
//Add user data to that item //Add user data to that item
@ -119,7 +119,7 @@ void ResultsTree::AddErrorItem(const QString &file,
item->setData(QVariant(data)); item->setData(QVariant(data));
//Add backtrace files as children //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; QStandardItem *child_item;
@ -143,7 +143,7 @@ void ResultsTree::AddErrorItem(const QString &file,
//TODO just hide/show current error and it's file //TODO just hide/show current error and it's file
//since this does a lot of unnecessary work //since this does a lot of unnecessary work
if (!hide) if(!hide)
{ {
ShowFileItem(realfile); ShowFileItem(realfile);
} }
@ -158,7 +158,7 @@ QStandardItem *ResultsTree::AddBacktraceFiles(QStandardItem *parent,
const QString &icon) const QString &icon)
{ {
if (!parent) if(!parent)
{ {
return 0; return 0;
} }
@ -172,18 +172,18 @@ QStandardItem *ResultsTree::AddBacktraceFiles(QStandardItem *parent,
list << CreateItem(tr(message.toLatin1())); list << CreateItem(tr(message.toLatin1()));
// Check for duplicate rows and don't add them if found // 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 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 // 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 // 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 // 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 // this row matches so don't add it
return 0; return 0;
@ -196,7 +196,7 @@ QStandardItem *ResultsTree::AddBacktraceFiles(QStandardItem *parent,
setRowHidden(parent->rowCount() - 1, parent->index(), hide); setRowHidden(parent->rowCount() - 1, parent->index(), hide);
if (!icon.isEmpty()) if(!icon.isEmpty())
{ {
list[0]->setIcon(QIcon(icon)); list[0]->setIcon(QIcon(icon));
} }
@ -209,7 +209,7 @@ QStandardItem *ResultsTree::AddBacktraceFiles(QStandardItem *parent,
ShowTypes ResultsTree::VariantToShowType(const QVariant &data) ShowTypes ResultsTree::VariantToShowType(const QVariant &data)
{ {
int value = data.toInt(); int value = data.toInt();
if (value < SHOW_ALL && value > SHOW_ERRORS) if(value < SHOW_ALL && value > SHOW_ERRORS)
{ {
return SHOW_NONE; return SHOW_NONE;
} }
@ -218,13 +218,13 @@ ShowTypes ResultsTree::VariantToShowType(const QVariant &data)
ShowTypes ResultsTree::SeverityToShowType(const QString & severity) ShowTypes ResultsTree::SeverityToShowType(const QString & severity)
{ {
if (severity == "possible error") if(severity == "possible error")
return SHOW_ALL; return SHOW_ALL;
if (severity == "error") if(severity == "error")
return SHOW_ERRORS; return SHOW_ERRORS;
if (severity == "style") if(severity == "style")
return SHOW_STYLE; return SHOW_STYLE;
if (severity == "possible style") if(severity == "possible style")
return SHOW_ALL_STYLE; return SHOW_ALL_STYLE;
return SHOW_NONE; return SHOW_NONE;
@ -233,7 +233,7 @@ ShowTypes ResultsTree::SeverityToShowType(const QString & severity)
QStandardItem *ResultsTree::FindFileItem(const QString &name) QStandardItem *ResultsTree::FindFileItem(const QString &name)
{ {
QList<QStandardItem *> list = mModel.findItems(name); QList<QStandardItem *> list = mModel.findItems(name);
if (list.size() > 0) if(list.size() > 0)
{ {
return list[0]; return list[0];
} }
@ -247,7 +247,7 @@ void ResultsTree::Clear()
void ResultsTree::LoadSettings() void ResultsTree::LoadSettings()
{ {
for (int i = 0; i < mModel.columnCount(); i++) for(int i = 0; i < mModel.columnCount(); i++)
{ {
//mFileTree.columnWidth(i); //mFileTree.columnWidth(i);
QString temp = QString(SETTINGS_RESULT_COLUMN_WIDTH).arg(i); QString temp = QString(SETTINGS_RESULT_COLUMN_WIDTH).arg(i);
@ -261,7 +261,7 @@ void ResultsTree::LoadSettings()
void ResultsTree::SaveSettings() 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); QString temp = QString(SETTINGS_RESULT_COLUMN_WIDTH).arg(i);
mSettings->setValue(temp, columnWidth(i)); mSettings->setValue(temp, columnWidth(i));
@ -270,7 +270,7 @@ void ResultsTree::SaveSettings()
void ResultsTree::ShowResults(ShowTypes type, bool show) void ResultsTree::ShowResults(ShowTypes type, bool show)
{ {
if (type != SHOW_NONE && mShowTypes[type] != show) if(type != SHOW_NONE && mShowTypes[type] != show)
{ {
mShowTypes[type] = show; mShowTypes[type] = show;
RefreshTree(); RefreshTree();
@ -284,11 +284,11 @@ void ResultsTree::RefreshTree()
//Get the amount of files in the tree //Get the amount of files in the tree
int filecount = mModel.rowCount(); int filecount = mModel.rowCount();
for (int i = 0; i < filecount; i++) for(int i = 0; i < filecount; i++)
{ {
//Get file i //Get file i
QStandardItem *file = mModel.item(i, 0); QStandardItem *file = mModel.item(i, 0);
if (!file) if(!file)
{ {
continue; continue;
} }
@ -299,11 +299,11 @@ void ResultsTree::RefreshTree()
//By default it shouldn't be visible //By default it shouldn't be visible
bool show = false; bool show = false;
for (int j = 0; j < errorcount; j++) for(int j = 0; j < errorcount; j++)
{ {
//Get the error itself //Get the error itself
QStandardItem *child = file->child(j, 0); QStandardItem *child = file->child(j, 0);
if (!child) if(!child)
{ {
continue; continue;
} }
@ -316,7 +316,7 @@ void ResultsTree::RefreshTree()
//Check if this error should be hidden //Check if this error should be hidden
bool hide = !mShowTypes[VariantToShowType(data["severity"])]; bool hide = !mShowTypes[VariantToShowType(data["severity"])];
if (!hide) if(!hide)
{ {
mVisibleErrors = true; mVisibleErrors = true;
} }
@ -325,7 +325,7 @@ void ResultsTree::RefreshTree()
setRowHidden(j, file->index(), hide); setRowHidden(j, file->index(), hide);
//If it was shown then the file itself has to be shown as well //If it was shown then the file itself has to be shown as well
if (!hide) if(!hide)
{ {
show = true; show = true;
} }
@ -341,7 +341,7 @@ QStandardItem *ResultsTree::EnsureFileItem(const QString &fullpath, bool hide)
QString name = StripPath(fullpath, false); QString name = StripPath(fullpath, false);
QStandardItem *item = FindFileItem(name); QStandardItem *item = FindFileItem(name);
if (item) if(item)
{ {
return item; return item;
} }
@ -363,7 +363,7 @@ QStandardItem *ResultsTree::EnsureFileItem(const QString &fullpath, bool hide)
void ResultsTree::ShowFileItem(const QString &name) void ResultsTree::ShowFileItem(const QString &name)
{ {
QStandardItem *item = FindFileItem(name); QStandardItem *item = FindFileItem(name);
if (item) if(item)
{ {
setRowHidden(0, mModel.indexFromItem(item), false); setRowHidden(0, mModel.indexFromItem(item), false);
} }
@ -372,7 +372,7 @@ void ResultsTree::ShowFileItem(const QString &name)
void ResultsTree::contextMenuEvent(QContextMenuEvent * e) void ResultsTree::contextMenuEvent(QContextMenuEvent * e)
{ {
QModelIndex index = indexAt(e->pos()); QModelIndex index = indexAt(e->pos());
if (index.isValid()) if(index.isValid())
{ {
mContextItem = mModel.itemFromIndex(index); mContextItem = mModel.itemFromIndex(index);
@ -386,10 +386,10 @@ void ResultsTree::contextMenuEvent(QContextMenuEvent * e)
//member variables //member variables
QSignalMapper *signalMapper = new QSignalMapper(this); 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 //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 //Create an action for the application
QAction *start = new QAction(mApplications->GetApplicationName(i), &menu); 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 // Add menuitems to copy full path/filename to clipboard
if (mContextItem) if(mContextItem)
{ {
if (mApplications->GetApplicationCount() > 0) if(mApplications->GetApplicationCount() > 0)
{ {
menu.addSeparator(); menu.addSeparator();
} }
@ -436,10 +436,10 @@ void ResultsTree::contextMenuEvent(QContextMenuEvent * e)
//Start the menu //Start the menu
menu.exec(e->globalPos()); menu.exec(e->globalPos());
if (mContextItem && mApplications->GetApplicationCount() > 0 && mContextItem->parent()) if(mContextItem && mApplications->GetApplicationCount() > 0 && mContextItem->parent())
{ {
//Disconnect all signals //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())); disconnect(actions[i], SIGNAL(triggered()), signalMapper, SLOT(map()));
@ -457,7 +457,7 @@ void ResultsTree::contextMenuEvent(QContextMenuEvent * e)
void ResultsTree::StartApplication(QStandardItem *target, int application) void ResultsTree::StartApplication(QStandardItem *target, int application)
{ {
//If there are now application's specified, tell the user about it //If there are now application's specified, tell the user about it
if (mApplications->GetApplicationCount() == 0) if(mApplications->GetApplicationCount() == 0)
{ {
QMessageBox msg(QMessageBox::Information, QMessageBox msg(QMessageBox::Information,
tr("Cppcheck"), tr("Cppcheck"),
@ -468,10 +468,10 @@ void ResultsTree::StartApplication(QStandardItem *target, int application)
return; 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 // Make sure we are working with the first column
if (target->column() != 0) if(target->column() != 0)
target = target->parent()->child(target->row(), 0); target = target->parent()->child(target->row(), 0);
QVariantMap data = target->data().toMap(); QVariantMap data = target->data().toMap();
@ -480,7 +480,7 @@ void ResultsTree::StartApplication(QStandardItem *target, int application)
//Replace (file) with filename //Replace (file) with filename
QString file = data["file"].toString(); QString file = data["file"].toString();
if (file.indexOf(" ") > -1) if(file.indexOf(" ") > -1)
{ {
file.insert(0, "\""); file.insert(0, "\"");
file.append("\""); file.append("\"");
@ -495,7 +495,7 @@ void ResultsTree::StartApplication(QStandardItem *target, int application)
program.replace("(severity)", data["severity"].toString(), Qt::CaseInsensitive); program.replace("(severity)", data["severity"].toString(), Qt::CaseInsensitive);
bool success = QProcess::startDetached(program); bool success = QProcess::startDetached(program);
if (!success) if(!success)
{ {
QString app = mApplications->GetApplicationName(application); QString app = mApplications->GetApplicationName(application);
QString text = tr("Could not start %1\n\nPlease check the application path and parameters are correct.").arg(app); 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() void ResultsTree::CopyMessage()
{ {
if (mContextItem) if(mContextItem)
{ {
// Make sure we are working with the first column // Make sure we are working with the first column
if (mContextItem->column() != 0) if(mContextItem->column() != 0)
mContextItem = mContextItem->parent()->child(mContextItem->row(), 0); mContextItem = mContextItem->parent()->child(mContextItem->row(), 0);
QVariantMap data = mContextItem->data().toMap(); QVariantMap data = mContextItem->data().toMap();
@ -549,10 +549,10 @@ void ResultsTree::QuickStartApplication(const QModelIndex &index)
void ResultsTree::CopyPath(QStandardItem *target, bool fullPath) void ResultsTree::CopyPath(QStandardItem *target, bool fullPath)
{ {
if (target) if(target)
{ {
// Make sure we are working with the first column // Make sure we are working with the first column
if (target->column() != 0) if(target->column() != 0)
target = target->parent()->child(target->row(), 0); target = target->parent()->child(target->row(), 0);
QVariantMap data = target->data().toMap(); QVariantMap data = target->data().toMap();
@ -561,7 +561,7 @@ void ResultsTree::CopyPath(QStandardItem *target, bool fullPath)
//Replace (file) with filename //Replace (file) with filename
QString file = data["file"].toString(); QString file = data["file"].toString();
pathStr = file; pathStr = file;
if (!fullPath) if(!fullPath)
{ {
QFileInfo fi(pathStr); QFileInfo fi(pathStr);
pathStr = fi.fileName(); pathStr = fi.fileName();
@ -574,11 +574,11 @@ void ResultsTree::CopyPath(QStandardItem *target, bool fullPath)
QString ResultsTree::SeverityToIcon(const QString &severity) QString ResultsTree::SeverityToIcon(const QString &severity)
{ {
if (severity == "possible error") if(severity == "possible error")
return ":images/dialog-warning.png"; return ":images/dialog-warning.png";
if (severity == "error") if(severity == "error")
return ":images/dialog-error.png"; return ":images/dialog-error.png";
if (severity == "style" || severity == "possible style") if(severity == "style" || severity == "possible style")
return ":images/dialog-information.png"; return ":images/dialog-information.png";
return ""; return "";
@ -588,10 +588,10 @@ void ResultsTree::SaveResults(Report *report)
{ {
report->WriteHeader(); report->WriteHeader();
for (int i = 0; i < mModel.rowCount(); i++) for(int i = 0; i < mModel.rowCount(); i++)
{ {
QStandardItem *item = mModel.item(i, 0); QStandardItem *item = mModel.item(i, 0);
if (!isRowHidden(i, item->index())) if(!isRowHidden(i, item->index()))
SaveErrors(report, item); SaveErrors(report, item);
} }
@ -600,23 +600,23 @@ void ResultsTree::SaveResults(Report *report)
void ResultsTree::SaveErrors(Report *report, QStandardItem *item) void ResultsTree::SaveErrors(Report *report, QStandardItem *item)
{ {
if (!item) if(!item)
{ {
return; return;
} }
//qDebug() << item->text() << "has" << item->rowCount() << "errors"; //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); QStandardItem *error = item->child(i, 0);
if (!error) if(!error)
{ {
continue; continue;
} }
if (isRowHidden(i, item->index()) && !mSaveAllErrors) if(isRowHidden(i, item->index()) && !mSaveAllErrors)
{ {
continue; continue;
} }
@ -638,7 +638,7 @@ void ResultsTree::SaveErrors(Report *report, QStandardItem *item)
files << file; files << file;
lines << line; 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); QStandardItem *child_error = error->child(j, 0);
//Get error's user data //Get error's user data
@ -659,7 +659,7 @@ void ResultsTree::SaveErrors(Report *report, QStandardItem *item)
QString ResultsTree::ShowTypeToString(ShowTypes type) QString ResultsTree::ShowTypeToString(ShowTypes type)
{ {
switch (type) switch(type)
{ {
case SHOW_ALL: case SHOW_ALL:
return tr("possible error"); return tr("possible error");
@ -689,7 +689,7 @@ void ResultsTree::UpdateSettings(bool showFullPath,
bool saveFullPath, bool saveFullPath,
bool saveAllErrors) bool saveAllErrors)
{ {
if (mShowFullPath != showFullPath) if(mShowFullPath != showFullPath)
{ {
mShowFullPath = showFullPath; mShowFullPath = showFullPath;
RefreshFilePaths(); RefreshFilePaths();
@ -706,7 +706,7 @@ void ResultsTree::SetCheckDirectory(const QString &dir)
QString ResultsTree::StripPath(const QString &path, bool saving) QString ResultsTree::StripPath(const QString &path, bool saving)
{ {
if ((!saving && mShowFullPath) || (saving && mSaveFullPath)) if((!saving && mShowFullPath) || (saving && mSaveFullPath))
{ {
return QString(path); return QString(path);
} }
@ -717,7 +717,7 @@ QString ResultsTree::StripPath(const QString &path, bool saving)
void ResultsTree::RefreshFilePaths(QStandardItem *item) void ResultsTree::RefreshFilePaths(QStandardItem *item)
{ {
if (!item) if(!item)
{ {
return; return;
} }
@ -726,12 +726,12 @@ void ResultsTree::RefreshFilePaths(QStandardItem *item)
bool updated = false; bool updated = false;
//Loop through all errors within this file //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 //Get error i
QStandardItem *error = item->child(i, 0); QStandardItem *error = item->child(i, 0);
if (!error) if(!error)
{ {
continue; continue;
} }
@ -748,14 +748,14 @@ void ResultsTree::RefreshFilePaths(QStandardItem *item)
error->setText(StripPath(file, false)); error->setText(StripPath(file, false));
//If this error has backtraces make sure the files list has enough filenames //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 //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 //Get file
QStandardItem *child = error->child(j, 0); QStandardItem *child = error->child(j, 0);
if (!child) if(!child)
{ {
continue; continue;
} }
@ -772,7 +772,7 @@ void ResultsTree::RefreshFilePaths(QStandardItem *item)
} }
//if the main file hasn't been updated yet, update it now //if the main file hasn't been updated yet, update it now
if (!updated) if(!updated)
{ {
updated = true; updated = true;
item->setText(error->text()); item->setText(error->text());
@ -786,7 +786,7 @@ void ResultsTree::RefreshFilePaths()
qDebug("Refreshing file paths"); qDebug("Refreshing file paths");
//Go through all file items (these are parent items that contain the errors) //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)); RefreshFilePaths(mModel.item(i, 0));
} }

View File

@ -67,13 +67,14 @@ void ResultsView::Progress(int value, int max)
{ {
mUI.mProgress->setMaximum(max); mUI.mProgress->setMaximum(max);
mUI.mProgress->setValue(value); mUI.mProgress->setValue(value);
if (value >= max) if(value >= max)
{ {
mUI.mProgress->setVisible(false); mUI.mProgress->setVisible(false);
//Should we inform user of non visible/not found errors? //Should we inform user of non visible/not found errors?
if (mShowNoErrorsMessage) if(mShowNoErrorsMessage)
{ //Tell user that we found no errors {
if (!mErrorsFound) //Tell user that we found no errors
if(!mErrorsFound)
{ {
QMessageBox msg(QMessageBox::Information, QMessageBox msg(QMessageBox::Information,
tr("Cppcheck"), tr("Cppcheck"),
@ -83,7 +84,7 @@ void ResultsView::Progress(int value, int max)
msg.exec(); msg.exec();
} //If we have errors but they aren't visible, tell user about it } //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"\ 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."); "To toggle what kind of errors are shown, open view menu.");
@ -133,7 +134,7 @@ void ResultsView::ExpandAllResults()
void ResultsView::Save(const QString &filename, Report::Type type) void ResultsView::Save(const QString &filename, Report::Type type)
{ {
if (!mErrorsFound) if(!mErrorsFound)
{ {
QMessageBox msgBox; QMessageBox msgBox;
msgBox.setText(tr("No errors found, nothing to save.")); msgBox.setText(tr("No errors found, nothing to save."));
@ -143,7 +144,7 @@ void ResultsView::Save(const QString &filename, Report::Type type)
Report *report = NULL; Report *report = NULL;
switch (type) switch(type)
{ {
case Report::CSV: case Report::CSV:
report = new CsvReport(filename, this); report = new CsvReport(filename, this);
@ -156,9 +157,9 @@ void ResultsView::Save(const QString &filename, Report::Type type)
break; break;
} }
if (report) if(report)
{ {
if (report->Create()) if(report->Create())
mUI.mTree->SaveResults(report); mUI.mTree->SaveResults(report);
else else
{ {

View File

@ -77,7 +77,7 @@ SettingsDialog::~SettingsDialog()
Qt::CheckState SettingsDialog::BoolToCheckState(bool yes) Qt::CheckState SettingsDialog::BoolToCheckState(bool yes)
{ {
if (yes) if(yes)
{ {
return Qt::Checked; return Qt::Checked;
} }
@ -86,7 +86,7 @@ Qt::CheckState SettingsDialog::BoolToCheckState(bool yes)
bool SettingsDialog::CheckStateToBool(Qt::CheckState state) bool SettingsDialog::CheckStateToBool(Qt::CheckState state)
{ {
if (state == Qt::Checked) if(state == Qt::Checked)
{ {
return true; return true;
} }
@ -109,7 +109,7 @@ void SettingsDialog::SaveSettings()
void SettingsDialog::SaveCheckboxValues() void SettingsDialog::SaveCheckboxValues()
{ {
int jobs = mUI.mJobs->text().toInt(); int jobs = mUI.mJobs->text().toInt();
if (jobs <= 0) if(jobs <= 0)
{ {
jobs = 1; jobs = 1;
} }
@ -131,7 +131,7 @@ void SettingsDialog::AddApplication()
{ {
ApplicationDialog dialog("", "", tr("Add a new application"), this); ApplicationDialog dialog("", "", tr("Add a new application"), this);
if (dialog.exec() == QDialog::Accepted) if(dialog.exec() == QDialog::Accepted)
{ {
mTempApplications->AddApplicationType(dialog.GetName(), dialog.GetPath()); mTempApplications->AddApplicationType(dialog.GetName(), dialog.GetPath());
mUI.mListWidget->addItem(dialog.GetName()); mUI.mListWidget->addItem(dialog.GetName());
@ -164,7 +164,7 @@ void SettingsDialog::ModifyApplication()
mTempApplications->GetApplicationPath(row), mTempApplications->GetApplicationPath(row),
tr("Modify an application")); tr("Modify an application"));
if (dialog.exec() == QDialog::Accepted) if(dialog.exec() == QDialog::Accepted)
{ {
mTempApplications->SetApplicationType(row, dialog.GetName(), dialog.GetPath()); mTempApplications->SetApplicationType(row, dialog.GetName(), dialog.GetPath());
item->setText(dialog.GetName()); item->setText(dialog.GetName());
@ -175,7 +175,7 @@ void SettingsDialog::ModifyApplication()
void SettingsDialog::DefaultApplication() void SettingsDialog::DefaultApplication()
{ {
QList<QListWidgetItem *> selected = mUI.mListWidget->selectedItems(); QList<QListWidgetItem *> selected = mUI.mListWidget->selectedItems();
if (selected.size() > 0) if(selected.size() > 0)
{ {
int index = mUI.mListWidget->row(selected[0]); int index = mUI.mListWidget->row(selected[0]);
mTempApplications->MoveFirst(index); mTempApplications->MoveFirst(index);
@ -186,13 +186,13 @@ void SettingsDialog::DefaultApplication()
void SettingsDialog::PopulateListWidget() 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)); mUI.mListWidget->addItem(mTempApplications->GetApplicationName(i));
} }
// If list contains items select first item // If list contains items select first item
if (mTempApplications->GetApplicationCount()) if(mTempApplications->GetApplicationCount())
{ {
mUI.mListWidget->setCurrentRow(0); mUI.mListWidget->setCurrentRow(0);
} }

View File

@ -46,12 +46,12 @@ void ThreadHandler::SetFiles(const QStringList &files)
void ThreadHandler::Check(Settings settings, bool recheck) void ThreadHandler::Check(Settings settings, bool recheck)
{ {
if (recheck && mRunningThreadCount == 0) if(recheck && mRunningThreadCount == 0)
{ {
mResults.SetFiles(mLastFiles); 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."; qDebug() << "Can't start checking if there's no files to check or if check is in progress.";
emit Done(); emit Done();
@ -62,12 +62,12 @@ void ThreadHandler::Check(Settings settings, bool recheck)
mRunningThreadCount = mThreads.size(); mRunningThreadCount = mThreads.size();
if (mResults.GetFileCount() < mRunningThreadCount) if(mResults.GetFileCount() < mRunningThreadCount)
{ {
mRunningThreadCount = mResults.GetFileCount(); mRunningThreadCount = mResults.GetFileCount();
} }
for (int i = 0; i < mRunningThreadCount; i++) for(int i = 0; i < mRunningThreadCount; i++)
{ {
mThreads[i]->Check(settings); mThreads[i]->Check(settings);
} }
@ -80,7 +80,7 @@ bool ThreadHandler::IsChecking() const
void ThreadHandler::SetThreadCount(const int count) void ThreadHandler::SetThreadCount(const int count)
{ {
if (mRunningThreadCount > 0 || if(mRunningThreadCount > 0 ||
count == mThreads.size() || count == mThreads.size() ||
count <= 0) count <= 0)
{ {
@ -90,7 +90,7 @@ void ThreadHandler::SetThreadCount(const int count)
//Remove unused old threads //Remove unused old threads
RemoveThreads(); RemoveThreads();
//Create new threads //Create new threads
for (int i = mThreads.size(); i < count; i++) for(int i = mThreads.size(); i < count; i++)
{ {
mThreads << new CheckThread(mResults); mThreads << new CheckThread(mResults);
connect(mThreads.last(), SIGNAL(Done()), connect(mThreads.last(), SIGNAL(Done()),
@ -104,7 +104,7 @@ void ThreadHandler::SetThreadCount(const int count)
void ThreadHandler::RemoveThreads() void ThreadHandler::RemoveThreads()
{ {
for (int i = 0; i < mThreads.size(); i++) for(int i = 0; i < mThreads.size(); i++)
{ {
mThreads[i]->terminate(); mThreads[i]->terminate();
disconnect(mThreads.last(), SIGNAL(Done()), disconnect(mThreads.last(), SIGNAL(Done()),
@ -121,7 +121,7 @@ void ThreadHandler::RemoveThreads()
void ThreadHandler::ThreadDone() void ThreadHandler::ThreadDone()
{ {
mRunningThreadCount--; mRunningThreadCount--;
if (mRunningThreadCount == 0) if(mRunningThreadCount == 0)
{ {
emit Done(); emit Done();
} }
@ -129,7 +129,7 @@ void ThreadHandler::ThreadDone()
void ThreadHandler::Stop() void ThreadHandler::Stop()
{ {
for (int i = 0; i < mThreads.size(); i++) for(int i = 0; i < mThreads.size(); i++)
{ {
mThreads[i]->stop(); mThreads[i]->stop();
} }
@ -168,7 +168,7 @@ void ThreadHandler::SaveSettings(QSettings &settings)
bool ThreadHandler::HasPreviousFiles() const bool ThreadHandler::HasPreviousFiles() const
{ {
if (mLastFiles.size() > 0) if(mLastFiles.size() > 0)
return true; return true;
return false; return false;

View File

@ -50,7 +50,7 @@ void ThreadResult::reportErr(const ErrorLogger::ErrorMessage &msg)
QVariantList lines; QVariantList lines;
QStringList files; QStringList files;
for (std::list<ErrorLogger::ErrorMessage::FileLocation>::const_iterator tok = msg._callStack.begin(); for(std::list<ErrorLogger::ErrorMessage::FileLocation>::const_iterator tok = msg._callStack.begin();
tok != msg._callStack.end(); tok != msg._callStack.end();
++tok) ++tok)
{ {
@ -72,7 +72,7 @@ void ThreadResult::reportErr(const ErrorLogger::ErrorMessage &msg)
QString ThreadResult::GetNextFile() QString ThreadResult::GetNextFile()
{ {
QMutexLocker locker(&mutex); QMutexLocker locker(&mutex);
if (mFiles.size() == 0) if(mFiles.size() == 0)
{ {
return ""; return "";
} }

View File

@ -47,7 +47,7 @@ TranslationHandler::TranslationHandler(QObject *parent) :
//Load english as a fallback language //Load english as a fallback language
QTranslator *english = new QTranslator(); QTranslator *english = new QTranslator();
if (english->load("cppcheck_en")) if(english->load("cppcheck_en"))
{ {
qApp->installTranslator(english); qApp->installTranslator(english);
} }
@ -75,10 +75,10 @@ const QStringList TranslationHandler::GetFiles()
bool TranslationHandler::SetLanguage(const int index, QString &error) bool TranslationHandler::SetLanguage(const int index, QString &error)
{ {
//If english is the language //If english is the language
if (index == 0) if(index == 0)
{ {
//Just remove all extra translators //Just remove all extra translators
if (mTranslator) if(mTranslator)
{ {
qApp->removeTranslator(mTranslator); qApp->removeTranslator(mTranslator);
} }
@ -88,17 +88,17 @@ bool TranslationHandler::SetLanguage(const int index, QString &error)
} }
//Make sure the translator is otherwise valid //Make sure the translator is otherwise valid
if (index >= mNames.size()) if(index >= mNames.size())
{ {
error = QObject::tr("Incorrect language specified!"); error = QObject::tr("Incorrect language specified!");
return false; return false;
} }
//Load the new language //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 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 = QObject::tr("Language file %1 not found!");
error = error.arg(mFiles[index] + ".qm"); error = error.arg(mFiles[index] + ".qm");
@ -144,7 +144,7 @@ int TranslationHandler::SuggestLanguage() const
int index = mFiles.indexOf(file); int index = mFiles.indexOf(file);
//If nothing found, return english //If nothing found, return english
if (index < 0) if(index < 0)
{ {
return 0; return 0;
} }

View File

@ -33,7 +33,7 @@ TxtReport::~TxtReport()
bool TxtReport::Create() bool TxtReport::Create()
{ {
bool success = false; bool success = false;
if (Report::Create()) if(Report::Create())
{ {
mTxtWriter.setDevice(Report::GetFile()); mTxtWriter.setDevice(Report::GetFile());
success = true; success = true;
@ -63,15 +63,15 @@ void TxtReport::WriteError(const QStringList &files, const QStringList &lines,
QString line; 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]); 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 += " -> "; line += " -> ";
} }
if (i == lines.size() - 1) if(i == lines.size() - 1)
{ {
line += ": "; line += ": ";
} }

View File

@ -33,7 +33,7 @@ XmlReport::~XmlReport()
bool XmlReport::Create() bool XmlReport::Create()
{ {
bool success = false; bool success = false;
if (Report::Create()) if(Report::Create())
{ {
mXmlWriter.setDevice(Report::GetFile()); mXmlWriter.setDevice(Report::GetFile());
success = true; success = true;

View File

@ -99,7 +99,7 @@ protected:
void reportError(const Token *tok, const Severity::e severity, const std::string &id, const std::string &msg) void reportError(const Token *tok, const Severity::e severity, const std::string &id, const std::string &msg)
{ {
std::list<const Token *> callstack; std::list<const Token *> callstack;
if (tok) if(tok)
callstack.push_back(tok); callstack.push_back(tok);
reportError(callstack, severity, id, msg); reportError(callstack, severity, id, msg);
} }
@ -108,18 +108,18 @@ protected:
void reportError(const std::list<const Token *> &callstack, const Severity::e severity, const std::string &id, std::string msg) void reportError(const std::list<const Token *> &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 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"); std::string::size_type pos = msg.find("\n");
if (pos != std::string::npos) if(pos != std::string::npos)
msg.erase(pos); msg.erase(pos);
} }
std::list<ErrorLogger::ErrorMessage::FileLocation> locationList; std::list<ErrorLogger::ErrorMessage::FileLocation> locationList;
for (std::list<const Token *>::const_iterator it = callstack.begin(); it != callstack.end(); ++it) for(std::list<const Token *>::const_iterator it = callstack.begin(); it != callstack.end(); ++it)
{ {
// --errorlist can provide null values here // --errorlist can provide null values here
if (!(*it)) if(!(*it))
continue; continue;
ErrorLogger::ErrorMessage::FileLocation loc; ErrorLogger::ErrorMessage::FileLocation loc;
@ -129,7 +129,7 @@ protected:
} }
const ErrorLogger::ErrorMessage errmsg(locationList, Severity::stringify(severity), msg, id); const ErrorLogger::ErrorMessage errmsg(locationList, Severity::stringify(severity), msg, id);
if (_errorLogger) if(_errorLogger)
_errorLogger->reportErr(errmsg); _errorLogger->reportErr(errmsg);
else else
reportError(errmsg); reportError(errmsg);

View File

@ -41,7 +41,7 @@ static CheckAutoVariables instance;
bool CheckAutoVariables::errorAv(const Token* left, const Token* right) 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; return false;
} }
@ -51,7 +51,7 @@ bool CheckAutoVariables::errorAv(const Token* left, const Token* right)
bool CheckAutoVariables::isAutoVar(unsigned int varId) bool CheckAutoVariables::isAutoVar(unsigned int varId)
{ {
if (varId == 0) if(varId == 0)
{ {
return false; return false;
} }
@ -61,7 +61,7 @@ bool CheckAutoVariables::isAutoVar(unsigned int varId)
bool CheckAutoVariables::isAutoVarArray(unsigned int varId) bool CheckAutoVariables::isAutoVarArray(unsigned int varId)
{ {
if (varId == 0) if(varId == 0)
{ {
return false; return false;
} }
@ -73,7 +73,7 @@ void print(const Token *tok, int num)
{ {
const Token *t = tok; const Token *t = tok;
std::cout << tok->linenr() << " PRINT "; std::cout << tok->linenr() << " PRINT ";
for (int i = 0; i < num; i++) for(int i = 0; i < num; i++)
{ {
std::cout << " [" << t->str() << "] "; std::cout << " [" << t->str() << "] ";
t = t->next(); t = t->next();
@ -86,7 +86,7 @@ bool isTypeName(const Token *tok)
bool ret = false; bool ret = false;
const std::string _str(tok->str()); const std::string _str(tok->str());
static const char * const type[] = {"case", "return", "delete", 0}; 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]); ret |= (_str == type[i]);
} }
@ -97,15 +97,15 @@ bool isExternOrStatic(const Token *tok)
{ {
bool res = false; bool res = false;
if (Token::Match(tok->tokAt(-1), "extern|static")) if(Token::Match(tok->tokAt(-1), "extern|static"))
{ {
res = true; res = true;
} }
else if (Token::Match(tok->tokAt(-2), "extern|static")) else if(Token::Match(tok->tokAt(-2), "extern|static"))
{ {
res = true; res = true;
} }
else if (Token::Match(tok->tokAt(-3), "extern|static")) else if(Token::Match(tok->tokAt(-3), "extern|static"))
{ {
res = true; res = true;
} }
@ -117,7 +117,7 @@ bool isExternOrStatic(const Token *tok)
void CheckAutoVariables::addVD(unsigned int varId) void CheckAutoVariables::addVD(unsigned int varId)
{ {
if (varId > 0) if(varId > 0)
{ {
vd_list.insert(varId); vd_list.insert(varId);
} }
@ -125,7 +125,7 @@ void CheckAutoVariables::addVD(unsigned int varId)
void CheckAutoVariables::addVDA(unsigned int varId) void CheckAutoVariables::addVDA(unsigned int varId)
{ {
if (varId > 0) if(varId > 0)
{ {
vda_list.insert(varId); vda_list.insert(varId);
} }
@ -137,82 +137,82 @@ void CheckAutoVariables::autoVariables()
bool begin_function_decl = false; bool begin_function_decl = false;
int bindent = 0; 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; begin_function = true;
fp_list.clear(); fp_list.clear();
vd_list.clear(); vd_list.clear();
vda_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()); 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()); fp_list.insert(tok->tokAt(2)->str());
} }
else if (begin_function && tok->str() == "(") else if(begin_function && tok->str() == "(")
{ {
begin_function_decl = true; begin_function_decl = true;
} }
else if (begin_function && tok->str() == ")") else if(begin_function && tok->str() == ")")
{ {
begin_function_decl = false; begin_function_decl = false;
} }
else if (begin_function && tok->str() == "{") else if(begin_function && tok->str() == "{")
{ {
bindent++; bindent++;
} }
else if (begin_function && tok->str() == "}") else if(begin_function && tok->str() == "}")
{ {
bindent--; bindent--;
} }
else if (bindent <= 0) else if(bindent <= 0)
{ {
continue; continue;
} }
// Inside a function body // 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()); addVD(tok->tokAt(2)->varId());
} }
else if (Token::Match(tok, "%type% %var% [")) else if(Token::Match(tok, "%type% %var% ["))
{ {
addVDA(tok->next()->varId()); 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()); 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()); addVD(tok->tokAt(2)->varId());
} }
//Critical assignment //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); 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); 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); errorAutoVariableAssignment(tok);
} }
// Critical return // 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"); reportError(tok, Severity::error, "autoVariables", "Return of the address of an auto-variable");
} }
// Invalid pointer deallocation // 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"); reportError(tok, Severity::error, "autoVariables", "Invalid deallocation");
} }
@ -231,20 +231,20 @@ void CheckAutoVariables::returnPointerToLocalArray()
bool infunc = false; bool infunc = false;
int indentlevel = 0; int indentlevel = 0;
std::set<unsigned int> arrayVar; std::set<unsigned int> 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? // 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; tok = tok2;
break; break;
} }
} }
if (Token::simpleMatch(tok, ") {")) if(Token::simpleMatch(tok, ") {"))
{ {
infunc = true; infunc = true;
indentlevel = 0; indentlevel = 0;
@ -253,16 +253,16 @@ void CheckAutoVariables::returnPointerToLocalArray()
} }
// Parsing a function that returns a pointer.. // Parsing a function that returns a pointer..
if (infunc) if(infunc)
{ {
if (tok->str() == "{") if(tok->str() == "{")
{ {
++indentlevel; ++indentlevel;
} }
else if (tok->str() == "}") else if(tok->str() == "}")
{ {
--indentlevel; --indentlevel;
if (indentlevel <= 0) if(indentlevel <= 0)
{ {
infunc = false; infunc = false;
} }
@ -270,20 +270,20 @@ void CheckAutoVariables::returnPointerToLocalArray()
} }
// Declaring a local array.. // Declaring a local array..
if (Token::Match(tok, "[;{}] %type% %var% [")) if(Token::Match(tok, "[;{}] %type% %var% ["))
{ {
const unsigned int varid = tok->tokAt(2)->varId(); const unsigned int varid = tok->tokAt(2)->varId();
if (varid > 0) if(varid > 0)
{ {
arrayVar.insert(varid); arrayVar.insert(varid);
} }
} }
// Return pointer to local array variable.. // 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(); 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); errorReturnPointerToLocalArray(tok);
} }
@ -311,7 +311,7 @@ void CheckAutoVariables::errorAutoVariableAssignment(const Token *tok)
// return temporary? // return temporary?
bool CheckAutoVariables::returnTemporary(const Token *tok) const bool CheckAutoVariables::returnTemporary(const Token *tok) const
{ {
if (!Token::Match(tok, "return %var% (")) if(!Token::Match(tok, "return %var% ("))
return false; return false;
return bool(0 != Token::findmatch(_tokenizer->tokens(), ("std :: string " + tok->next()->str() + " (").c_str())); return bool(0 != Token::findmatch(_tokenizer->tokens(), ("std :: string " + tok->next()->str() + " (").c_str()));
} }
@ -320,20 +320,20 @@ bool CheckAutoVariables::returnTemporary(const Token *tok) const
void CheckAutoVariables::returnReference() void CheckAutoVariables::returnReference()
{ {
// locate function that returns a reference.. // 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.. // Skip executable scopes..
if (Token::Match(tok, ") const| {")) if(Token::Match(tok, ") const| {"))
{ {
tok = tok->next(); tok = tok->next();
if (tok->str() == "const") if(tok->str() == "const")
tok = tok->next(); tok = tok->next();
tok = tok->link(); tok = tok->link();
continue; continue;
} }
// have we reached a function that returns a reference? // have we reached a function that returns a reference?
if (Token::Match(tok, "%type% & %var% (") || if(Token::Match(tok, "%type% & %var% (") ||
Token::Match(tok, "> & %var% (")) Token::Match(tok, "> & %var% ("))
{ {
// go to the '(' // go to the '('
@ -343,48 +343,48 @@ void CheckAutoVariables::returnReference()
tok2 = tok2->link(); tok2 = tok2->link();
// is this a function implementation? // is this a function implementation?
if (Token::Match(tok2, ") const| {")) if(Token::Match(tok2, ") const| {"))
{ {
unsigned int indentlevel = 0; unsigned int indentlevel = 0;
std::set<unsigned int> localvar; // local variables in function std::set<unsigned int> localvar; // local variables in function
while (0 != (tok2 = tok2->next())) while(0 != (tok2 = tok2->next()))
{ {
// indentlevel.. // indentlevel..
if (tok2->str() == "{") if(tok2->str() == "{")
++indentlevel; ++indentlevel;
else if (tok2->str() == "}") else if(tok2->str() == "}")
{ {
if (indentlevel <= 1) if(indentlevel <= 1)
break; break;
--indentlevel; --indentlevel;
} }
// declare local variable.. // declare local variable..
if (Token::Match(tok2, "[{};] %type%") && tok2->next()->str() != "return") if(Token::Match(tok2, "[{};] %type%") && tok2->next()->str() != "return")
{ {
// goto next token.. // goto next token..
tok2 = tok2->next(); tok2 = tok2->next();
// skip "const" // skip "const"
if (Token::Match(tok2, "const %type%")) if(Token::Match(tok2, "const %type%"))
tok2 = tok2->next(); tok2 = tok2->next();
// skip "std::" if it is seen // skip "std::" if it is seen
if (Token::simpleMatch(tok2, "std ::")) if(Token::simpleMatch(tok2, "std ::"))
tok2 = tok2->tokAt(2); tok2 = tok2->tokAt(2);
// is it a variable declaration? // is it a variable declaration?
if (Token::Match(tok2, "%type% %var% ;")) if(Token::Match(tok2, "%type% %var% ;"))
localvar.insert(tok2->next()->varId()); 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()); localvar.insert(tok2->tokAt(4)->varId());
} }
// return.. // return..
else if (Token::Match(tok2, "return %var% ;")) else if(Token::Match(tok2, "return %var% ;"))
{ {
// is the returned variable a local variable? // is the returned variable a local variable?
if ((tok2->next()->varId() > 0) && if((tok2->next()->varId() > 0) &&
(localvar.find(tok2->next()->varId()) != localvar.end())) (localvar.find(tok2->next()->varId()) != localvar.end()))
{ {
// report error.. // report error..
@ -393,7 +393,7 @@ void CheckAutoVariables::returnReference()
} }
// return reference to temporary.. // return reference to temporary..
else if (returnTemporary(tok2)) else if(returnTemporary(tok2))
{ {
// report error.. // report error..
errorReturnTempReference(tok2); errorReturnTempReference(tok2);
@ -419,20 +419,20 @@ void CheckAutoVariables::errorReturnTempReference(const Token *tok)
void CheckAutoVariables::returncstr() void CheckAutoVariables::returncstr()
{ {
// locate function that returns a const char *.. // 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.. // Skip executable scopes..
if (Token::Match(tok, ") const| {")) if(Token::Match(tok, ") const| {"))
{ {
tok = tok->next(); tok = tok->next();
if (tok->str() == "const") if(tok->str() == "const")
tok = tok->next(); tok = tok->next();
tok = tok->link(); tok = tok->link();
continue; continue;
} }
// have we reached a function that returns a reference? // 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 '(' // go to the '('
const Token *tok2 = tok->tokAt(4); const Token *tok2 = tok->tokAt(4);
@ -441,46 +441,46 @@ void CheckAutoVariables::returncstr()
tok2 = tok2->link(); tok2 = tok2->link();
// is this a function implementation? // is this a function implementation?
if (Token::Match(tok2, ") const| {")) if(Token::Match(tok2, ") const| {"))
{ {
unsigned int indentlevel = 0; unsigned int indentlevel = 0;
std::set<unsigned int> localvar; // local variables in function std::set<unsigned int> localvar; // local variables in function
while (0 != (tok2 = tok2->next())) while(0 != (tok2 = tok2->next()))
{ {
// indentlevel.. // indentlevel..
if (tok2->str() == "{") if(tok2->str() == "{")
++indentlevel; ++indentlevel;
else if (tok2->str() == "}") else if(tok2->str() == "}")
{ {
if (indentlevel <= 1) if(indentlevel <= 1)
break; break;
--indentlevel; --indentlevel;
} }
// declare local variable.. // declare local variable..
if (Token::Match(tok2, "[{};] %type%") && tok2->next()->str() != "return") if(Token::Match(tok2, "[{};] %type%") && tok2->next()->str() != "return")
{ {
// goto next token.. // goto next token..
tok2 = tok2->next(); tok2 = tok2->next();
// skip "const" // skip "const"
if (Token::Match(tok2, "const %type%")) if(Token::Match(tok2, "const %type%"))
tok2 = tok2->next(); tok2 = tok2->next();
// skip "std::" if it is seen // skip "std::" if it is seen
if (Token::simpleMatch(tok2, "std ::")) if(Token::simpleMatch(tok2, "std ::"))
tok2 = tok2->tokAt(2); tok2 = tok2->tokAt(2);
// is it a variable declaration? // is it a variable declaration?
if (Token::Match(tok2, "%type% %var% ;")) if(Token::Match(tok2, "%type% %var% ;"))
localvar.insert(tok2->next()->varId()); localvar.insert(tok2->next()->varId());
} }
// return.. // 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? // is the returned variable a local variable?
if ((tok2->next()->varId() > 0) && if((tok2->next()->varId() > 0) &&
(localvar.find(tok2->next()->varId()) != localvar.end())) (localvar.find(tok2->next()->varId()) != localvar.end()))
{ {
// report error.. // report error..
@ -489,7 +489,7 @@ void CheckAutoVariables::returncstr()
} }
// return pointer to temporary.. // return pointer to temporary..
else if (returnTemporary(tok2)) else if(returnTemporary(tok2))
{ {
// report error.. // report error..
errorReturnTempPointer(tok2); errorReturnTempPointer(tok2);

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -57,13 +57,13 @@ public:
{ {
CheckClass checkClass(tokenizer, settings, errorLogger); CheckClass checkClass(tokenizer, settings, errorLogger);
if (settings->_checkCodingStyle) if(settings->_checkCodingStyle)
{ {
checkClass.constructors(); checkClass.constructors();
checkClass.operatorEq(); checkClass.operatorEq();
checkClass.privateFunctions(); checkClass.privateFunctions();
checkClass.operatorEqRetRefThis(); checkClass.operatorEqRetRefThis();
if (settings->_showAll) if(settings->_showAll)
{ {
checkClass.thisSubtraction(); checkClass.thisSubtraction();
checkClass.operatorEqToSelf(); checkClass.operatorEqToSelf();

View File

@ -33,17 +33,17 @@ CheckDangerousFunctions instance;
void CheckDangerousFunctions::dangerousFunctions() 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); dangerousFunctionmktemp(tok);
} }
else if (Token::simpleMatch(tok, "gets (")) else if(Token::simpleMatch(tok, "gets ("))
{ {
dangerousFunctiongets(tok); dangerousFunctiongets(tok);
} }
else if (Token::simpleMatch(tok, "scanf (")) else if(Token::simpleMatch(tok, "scanf ("))
{ {
dangerousFunctionscanf(tok); dangerousFunctionscanf(tok);
} }

View File

@ -46,7 +46,7 @@ public:
void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger) void runSimplifiedChecks(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
{ {
CheckDangerousFunctions checkDangerousFunctions(tokenizer, settings, errorLogger); CheckDangerousFunctions checkDangerousFunctions(tokenizer, settings, errorLogger);
if (settings->_checkCodingStyle) if(settings->_checkCodingStyle)
{ {
checkDangerousFunctions.dangerousFunctions(); checkDangerousFunctions.dangerousFunctions();
} }

View File

@ -37,35 +37,35 @@ CheckExceptionSafety instance;
void CheckExceptionSafety::destructors() void CheckExceptionSafety::destructors()
{ {
// This is a style error.. // This is a style error..
if (!_settings->_checkCodingStyle) if(!_settings->_checkCodingStyle)
return; return;
// Perform check.. // 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(); tok = tok->next()->link();
if (!Token::Match(tok, "~ %var% ( ) {")) if(!Token::Match(tok, "~ %var% ( ) {"))
continue; continue;
// Inspect this destructor.. // Inspect this destructor..
unsigned int indentlevel = 0; 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; ++indentlevel;
} }
else if (tok2->str() == "}") else if(tok2->str() == "}")
{ {
if (indentlevel <= 1) if(indentlevel <= 1)
break; break;
--indentlevel; --indentlevel;
} }
else if (tok2->str() == "throw") else if(tok2->str() == "throw")
{ {
destructorsError(tok2); destructorsError(tok2);
break; break;
@ -77,82 +77,82 @@ void CheckExceptionSafety::destructors()
void CheckExceptionSafety::unsafeNew() void CheckExceptionSafety::unsafeNew()
{ {
if (!_settings->isEnabled("exceptNew")) if(!_settings->isEnabled("exceptNew"))
return; return;
// Inspect initializer lists.. // 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; continue;
tok = tok->next(); tok = tok->next();
if (!tok) if(!tok)
break; break;
if (tok->str() != ":") if(tok->str() != ":")
continue; continue;
// multiple "new" in an initializer list.. // multiple "new" in an initializer list..
std::string varname; 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; break;
tok = tok->next(); 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); unsafeNewError(tok->previous(), varname);
break; break;
} }
if (!_settings->isAutoDealloc(tok->strAt(2))) if(!_settings->isAutoDealloc(tok->strAt(2)))
{ {
varname = tok->strAt(-1); varname = tok->strAt(-1);
} }
} }
tok = tok->link(); tok = tok->link();
tok = tok ? tok->next() : 0; tok = tok ? tok->next() : 0;
if (!tok) if(!tok)
break; break;
if (tok->str() != ",") if(tok->str() != ",")
break; break;
} }
if (!tok) if(!tok)
break; break;
} }
// Inspect constructors.. // 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 ( .. ) {" // match this pattern.. "C :: C ( .. ) {"
if (!tok->next() || tok->next()->str() != "::") if(!tok->next() || tok->next()->str() != "::")
continue; continue;
if (!Token::Match(tok, "%var% :: %var% (")) if(!Token::Match(tok, "%var% :: %var% ("))
continue; continue;
if (tok->str() != tok->strAt(2)) if(tok->str() != tok->strAt(2))
continue; continue;
if (!Token::simpleMatch(tok->tokAt(3)->link(), ") {")) if(!Token::simpleMatch(tok->tokAt(3)->link(), ") {"))
continue; continue;
// inspect the constructor.. // inspect the constructor..
std::string varname; 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; break;
// some variable declaration.. // some variable declaration..
if (Token::Match(tok->previous(), "[{;] %type% * %var% ;")) if(Token::Match(tok->previous(), "[{;] %type% * %var% ;"))
break; break;
// allocating with new.. // 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); unsafeNewError(tok, varname);
break; break;
} }
if (!_settings->isAutoDealloc(tok->strAt(3))) if(!_settings->isAutoDealloc(tok->strAt(3)))
varname = tok->str(); varname = tok->str();
} }
} }
@ -161,49 +161,49 @@ void CheckExceptionSafety::unsafeNew()
// allocating multiple local variables.. // allocating multiple local variables..
std::set<unsigned int> localVars; std::set<unsigned int> localVars;
std::string varname; 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(); localVars.clear();
varname = ""; varname = "";
} }
if (Token::Match(tok, "[;{}] %type% * %var% ;") && if(Token::Match(tok, "[;{}] %type% * %var% ;") &&
!_settings->isAutoDealloc(tok->strAt(1))) !_settings->isAutoDealloc(tok->strAt(1)))
{ {
tok = tok->tokAt(3); tok = tok->tokAt(3);
if (tok->varId()) if(tok->varId())
localVars.insert(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); unsafeNewError(tok->next(), varname);
break; 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); 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 = ""; varname = "";
} }
} }
if (!tok) if(!tok)
break; break;
} }
else if (tok->str() == "delete") else if(tok->str() == "delete")
{ {
if (Token::simpleMatch(tok->next(), varname.c_str()) || if(Token::simpleMatch(tok->next(), varname.c_str()) ||
Token::simpleMatch(tok->next(), ("[ ] " + varname).c_str())) Token::simpleMatch(tok->next(), ("[ ] " + varname).c_str()))
{ {
varname = ""; varname = "";
@ -215,55 +215,55 @@ void CheckExceptionSafety::unsafeNew()
void CheckExceptionSafety::realloc() void CheckExceptionSafety::realloc()
{ {
if (!_settings->isEnabled("exceptRealloc")) if(!_settings->isEnabled("exceptRealloc"))
return; 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(); tok = tok->next()->link();
if (!tok) if(!tok)
break; break;
} }
if (!Token::Match(tok, "[{};] delete")) if(!Token::Match(tok, "[{};] delete"))
continue; continue;
tok = tok->tokAt(2); tok = tok->tokAt(2);
if (Token::simpleMatch(tok, "[ ]")) if(Token::simpleMatch(tok, "[ ]"))
tok = tok->tokAt(2); tok = tok->tokAt(2);
if (!tok) if(!tok)
break; break;
// reallocating.. // reallocating..
if (!Token::Match(tok, "%var% ; %var% = new %type%")) if(!Token::Match(tok, "%var% ; %var% = new %type%"))
continue; continue;
// variable id of deallocated pointer.. // variable id of deallocated pointer..
const unsigned int varid(tok->varId()); const unsigned int varid(tok->varId());
if (varid == 0) if(varid == 0)
continue; continue;
// variable id of allocated pointer must match.. // variable id of allocated pointer must match..
if (varid != tok->tokAt(2)->varId()) if(varid != tok->tokAt(2)->varId())
continue; continue;
// is is a class member variable.. // is is a class member variable..
const Token *tok1 = Token::findmatch(_tokenizer->tokens(), "%varid%", varid); 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(); 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; break;
if (tok1->str() == "class") if(tok1->str() == "class")
{ {
reallocError(tok->tokAt(2), tok->str()); reallocError(tok->tokAt(2), tok->str());
break; break;
@ -279,74 +279,74 @@ void CheckExceptionSafety::realloc()
void CheckExceptionSafety::deallocThrow() 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; continue;
// Check if this is something similar with: "delete p;" // Check if this is something similar with: "delete p;"
tok = tok->next(); tok = tok->next();
if (Token::simpleMatch(tok, "[ ]")) if(Token::simpleMatch(tok, "[ ]"))
tok = tok->tokAt(2); tok = tok->tokAt(2);
if (!tok) if(!tok)
break; break;
if (!Token::Match(tok, "%var% ;")) if(!Token::Match(tok, "%var% ;"))
continue; continue;
const unsigned int varid(tok->varId()); const unsigned int varid(tok->varId());
if (varid == 0) if(varid == 0)
continue; continue;
// is this variable a global variable? // is this variable a global variable?
{ {
bool globalVar = false; 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; globalVar = true;
break; 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->next();
tok2 = tok2 ? tok2->next() : 0; tok2 = tok2 ? tok2->next() : 0;
if (!tok2) if(!tok2)
break; break;
} }
if (tok2->str() == "{") if(tok2->str() == "{")
{ {
tok2 = tok2->link(); tok2 = tok2->link();
if (!tok2) if(!tok2)
break; break;
} }
} }
if (!globalVar) if(!globalVar)
continue; continue;
} }
// is there a throw after the deallocation? // is there a throw after the deallocation?
unsigned int indentlevel = 0; unsigned int indentlevel = 0;
const Token *ThrowToken = 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; ++indentlevel;
else if (tok2->str() == "}") else if(tok2->str() == "}")
{ {
if (indentlevel == 0) if(indentlevel == 0)
break; break;
--indentlevel; --indentlevel;
} }
if (tok2->str() == "throw") if(tok2->str() == "throw")
ThrowToken = tok2; ThrowToken = tok2;
else if (Token::Match(tok2, "%varid% =", varid)) else if(Token::Match(tok2, "%varid% =", varid))
{ {
if (ThrowToken) if(ThrowToken)
deallocThrowError(ThrowToken, tok->str()); deallocThrowError(ThrowToken, tok->str());
break; break;
} }

View File

@ -50,13 +50,13 @@ CheckHeaders::~CheckHeaders()
void CheckHeaders::warningHeaderWithImplementation() 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 // Only interested in included file
if (tok->fileIndex() == 0) if(tok->fileIndex() == 0)
continue; continue;
if (Token::simpleMatch(tok, ") {")) if(Token::simpleMatch(tok, ") {"))
{ {
std::ostringstream ostr; std::ostringstream ostr;
ostr << _tokenizer->fileLine(tok) << ": Found implementation in header"; ostr << _tokenizer->fileLine(tok) << ": Found implementation in header";
@ -69,7 +69,7 @@ void CheckHeaders::warningHeaderWithImplementation()
// _errorLogger->reportErr(empty, "severity", ostr.str(), "id"); // _errorLogger->reportErr(empty, "severity", ostr.str(), "id");
// Goto next file.. // Goto next file..
unsigned int fileindex = tok->fileIndex(); unsigned int fileindex = tok->fileIndex();
while (tok->next() && tok->fileIndex() == fileindex) while(tok->next() && tok->fileIndex() == fileindex)
tok = tok->next(); tok = tok->next();
} }
} }
@ -90,21 +90,21 @@ void CheckHeaders::warningHeaderWithImplementation()
void CheckHeaders::warningIncludeHeader() void CheckHeaders::warningIncludeHeader()
{ {
// Including.. // 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; continue;
// Get fileindex of included file.. // Get fileindex of included file..
unsigned int hfile = 0; unsigned int hfile = 0;
const std::string includefile = includetok->strAt(1); 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; break;
++hfile; ++hfile;
} }
if (hfile == _tokenizer->getFiles()->size()) if(hfile == _tokenizer->getFiles()->size())
continue; continue;
// This header is needed if: // This header is needed if:
@ -119,48 +119,48 @@ void CheckHeaders::warningIncludeHeader()
// Extract classes and names in the header.. // Extract classes and names in the header..
int indentlevel = 0; 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; continue;
// I'm only interested in stuff that is declared at indentlevel 0 // I'm only interested in stuff that is declared at indentlevel 0
if (tok1->str() == "{") if(tok1->str() == "{")
++indentlevel; ++indentlevel;
else if (tok1->str() == "}") else if(tok1->str() == "}")
--indentlevel; --indentlevel;
if (indentlevel != 0) if(indentlevel != 0)
continue; continue;
// Class or namespace declaration.. // 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)); classlist.push_back(tok1->strAt(1));
// Variable declaration.. // 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)); 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)); 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)); 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)); namelist.push_back(tok1->strAt(3));
// enum.. // enum..
// -------------------------------------- // --------------------------------------
else if (tok1->str() == "enum") else if(tok1->str() == "enum")
{ {
tok1 = tok1->next(); tok1 = tok1->next();
while (! Token::Match(tok1, "; %any%")) while(! Token::Match(tok1, "; %any%"))
{ {
if (tok1->isName()) if(tok1->isName())
namelist.push_back(tok1->str()); namelist.push_back(tok1->str());
tok1 = tok1->next(); tok1 = tok1->next();
} }
@ -168,39 +168,39 @@ void CheckHeaders::warningIncludeHeader()
// function.. // function..
// -------------------------------------- // --------------------------------------
else if (Token::Match(tok1, "%type% %var% (")) else if(Token::Match(tok1, "%type% %var% ("))
namelist.push_back(tok1->strAt(1)); 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)); 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)); 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)); namelist.push_back(tok1->strAt(3));
// typedef.. // typedef..
// -------------------------------------- // --------------------------------------
else if (tok1->str() == "typedef") else if(tok1->str() == "typedef")
{ {
if (tok1->strAt(1) == "enum") if(tok1->strAt(1) == "enum")
continue; continue;
int parlevel = 0; int parlevel = 0;
while (tok1->next()) while(tok1->next())
{ {
if (Token::Match(tok1, "[({]")) if(Token::Match(tok1, "[({]"))
++parlevel; ++parlevel;
else if (Token::Match(tok1, "[)}]")) else if(Token::Match(tok1, "[)}]"))
--parlevel; --parlevel;
else if (parlevel == 0) else if(parlevel == 0)
{ {
if (tok1->str() == ";") if(tok1->str() == ";")
break; break;
if (Token::Match(tok1, "%var% ;")) if(Token::Match(tok1, "%var% ;"))
namelist.push_back(tok1->str()); namelist.push_back(tok1->str());
} }
@ -213,45 +213,45 @@ void CheckHeaders::warningIncludeHeader()
// Check if the extracted names are used... // Check if the extracted names are used...
bool Needed = false; bool Needed = false;
bool NeedDeclaration = 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; 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); 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; Needed = true;
break; break;
} }
} }
if (! tok1->isName()) if(! tok1->isName())
continue; 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; Needed = true;
break; break;
} }
if (! NeedDeclaration) if(! NeedDeclaration)
NeedDeclaration = (std::find(classlist.begin(), classlist.end(), tok1->str().c_str()) != classlist.end()); NeedDeclaration = (std::find(classlist.begin(), classlist.end(), tok1->str().c_str()) != classlist.end());
} }
// Not a header file? // Not a header file?
if (includetok->fileIndex() == 0) if(includetok->fileIndex() == 0)
Needed |= NeedDeclaration; Needed |= NeedDeclaration;
// Not needed! // Not needed!
if (!Needed) if(!Needed)
{ {
std::ostringstream ostr; std::ostringstream ostr;
ostr << _tokenizer->fileLine(includetok) << ": The included header '" << includefile << "' is not needed"; ostr << _tokenizer->fileLine(includetok) << ": The included header '" << includefile << "' is not needed";
if (NeedDeclaration) if(NeedDeclaration)
ostr << " (but a forward declaration is needed)"; ostr << " (but a forward declaration is needed)";
// TODO, this check is currently not used, but if it is some day // TODO, this check is currently not used, but if it is some day

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -51,7 +51,7 @@ public:
CheckOther checkOther(tokenizer, settings, errorLogger); CheckOther checkOther(tokenizer, settings, errorLogger);
checkOther.nullPointer(); checkOther.nullPointer();
if (settings->_checkCodingStyle) if(settings->_checkCodingStyle)
{ {
checkOther.warningOldStylePointerCast(); checkOther.warningOldStylePointerCast();
checkOther.checkUnsignedDivision(); checkOther.checkUnsignedDivision();
@ -67,13 +67,13 @@ public:
{ {
CheckOther checkOther(tokenizer, settings, errorLogger); CheckOther checkOther(tokenizer, settings, errorLogger);
if (settings->_checkCodingStyle) if(settings->_checkCodingStyle)
{ {
checkOther.warningRedundantCode(); checkOther.warningRedundantCode();
checkOther.checkConstantFunctionParameter(); checkOther.checkConstantFunctionParameter();
checkOther.checkIncompleteStatement(); checkOther.checkIncompleteStatement();
checkOther.unreachableCode(); checkOther.unreachableCode();
if (settings->_showAll) if(settings->_showAll)
{ {
checkOther.postIncrement(); checkOther.postIncrement();
} }

View File

@ -43,49 +43,49 @@ void CheckStl::dereferenceErasedError(const Token *tok, const std::string &itern
void CheckStl::iterators() 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; continue;
const unsigned int iteratorId(tok->varId()); const unsigned int iteratorId(tok->varId());
const unsigned int containerId(tok->tokAt(2)->varId()); const unsigned int containerId(tok->tokAt(2)->varId());
if (iteratorId == 0 || containerId == 0) if(iteratorId == 0 || containerId == 0)
continue; continue;
bool validIterator = true; 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; 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)); iteratorsError(tok2, tok->strAt(2), tok2->strAt(2));
tok2 = tok2->tokAt(6); 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()); 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; validIterator = false;
tok2 = tok2->tokAt(4); tok2 = tok2->tokAt(4);
} }
else if (Token::Match(tok2, "%varid% = %var% . erase (", iteratorId)) else if(Token::Match(tok2, "%varid% = %var% . erase (", iteratorId))
{ {
validIterator = true; validIterator = true;
tok2 = tok2->tokAt(5)->link(); tok2 = tok2->tokAt(5)->link();
if (!tok2) if(!tok2)
break; break;
} }
else if (!validIterator && Token::Match(tok2, "* %varid%", iteratorId)) else if(!validIterator && Token::Match(tok2, "* %varid%", iteratorId))
{ {
dereferenceErasedError(tok2, tok2->strAt(1)); dereferenceErasedError(tok2, tok2->strAt(1));
tok2 = tok2->next(); 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)); dereferenceErasedError(tok2, tok2->strAt(0));
tok2 = tok2->tokAt(2); tok2 = tok2->tokAt(2);
@ -103,14 +103,14 @@ void CheckStl::mismatchingContainersError(const Token *tok)
void CheckStl::mismatchingContainers() 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; 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); mismatchingContainersError(tok);
} }
@ -121,45 +121,45 @@ void CheckStl::mismatchingContainers()
void CheckStl::stlOutOfBounds() 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; continue;
unsigned int indent = 0; 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; ++indent;
else if (tok2->str() == ")") else if(tok2->str() == ")")
{ {
if (indent == 0) if(indent == 0)
break; break;
--indent; --indent;
} }
if (Token::Match(tok2, "; %var% <= %var% . size ( ) ;")) if(Token::Match(tok2, "; %var% <= %var% . size ( ) ;"))
{ {
unsigned int indent2 = 0; unsigned int indent2 = 0;
unsigned int numId = tok2->tokAt(1)->varId(); unsigned int numId = tok2->tokAt(1)->varId();
unsigned int varId = tok2->tokAt(3)->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; ++indent2;
else if (tok3->str() == "}") else if(tok3->str() == "}")
{ {
if (indent2 <= 1) if(indent2 <= 1)
break; break;
--indent2; --indent2;
} }
else if (tok3->varId() == varId) else if(tok3->varId() == varId)
{ {
if (Token::simpleMatch(tok3->next(), ". size ( )")) if(Token::simpleMatch(tok3->next(), ". size ( )"))
break; 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()); stlOutOfBoundsError(tok3, tok3->tokAt(2)->str(), tok3->str());
} }
} }
@ -179,13 +179,13 @@ void CheckStl::stlOutOfBoundsError(const Token *tok, const std::string &num, con
void CheckStl::erase() 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 ( ) ") && if(Token::Match(tok2, "%var% = %var% . begin ( ) ; %var% != %var% . end ( ) ") &&
tok2->str() == tok2->tokAt(8)->str() && tok2->str() == tok2->tokAt(8)->str() &&
tok2->tokAt(2)->str() == tok2->tokAt(10)->str()) tok2->tokAt(2)->str() == tok2->tokAt(10)->str())
{ {
@ -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)); eraseCheckLoop(tok->tokAt(2));
} }
@ -208,44 +208,44 @@ void CheckStl::eraseCheckLoop(const Token *it)
// Search for the start of the loop body.. // Search for the start of the loop body..
int indentlevel = 1; int indentlevel = 1;
while (indentlevel > 0 && 0 != (tok = tok->next())) while(indentlevel > 0 && 0 != (tok = tok->next()))
{ {
if (tok->str() == "(") if(tok->str() == "(")
++indentlevel; ++indentlevel;
else if (tok->str() == ")") else if(tok->str() == ")")
--indentlevel; --indentlevel;
} }
if (! Token::simpleMatch(tok, ") {")) if(! Token::simpleMatch(tok, ") {"))
return; return;
// Parse loop.. // Parse loop..
// Error if it contains "erase(it)" but neither "break;", "=it" nor "it=" // Error if it contains "erase(it)" but neither "break;", "=it" nor "it="
indentlevel = 0; indentlevel = 0;
const Token *tok2 = 0; const Token *tok2 = 0;
while (0 != (tok = tok->next())) while(0 != (tok = tok->next()))
{ {
if (tok->str() == "{") if(tok->str() == "{")
++indentlevel; ++indentlevel;
else if (tok->str() == "}") else if(tok->str() == "}")
{ {
--indentlevel; --indentlevel;
if (indentlevel <= 0) if(indentlevel <= 0)
break; break;
} }
else if (Token::Match(tok, "break|return|goto") || else if(Token::Match(tok, "break|return|goto") ||
Token::simpleMatch(tok, (it->str() + " =").c_str()) || Token::simpleMatch(tok, (it->str() + " =").c_str()) ||
Token::simpleMatch(tok, ("= " + it->str()).c_str())) Token::simpleMatch(tok, ("= " + it->str()).c_str()))
{ {
tok2 = 0; tok2 = 0;
break; break;
} }
else if (Token::simpleMatch(tok, ("erase ( " + it->str() + " )").c_str())) else if(Token::simpleMatch(tok, ("erase ( " + it->str() + " )").c_str()))
tok2 = tok; tok2 = tok;
} }
// Write error message.. // Write error message..
if (tok2) if(tok2)
eraseError(tok2); eraseError(tok2);
} }
@ -261,39 +261,39 @@ void CheckStl::eraseError(const Token *tok)
void CheckStl::pushback() void CheckStl::pushback()
{ {
// Pointer can become invalid after push_back or push_front.. // 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 pointerId(tok->varId());
const unsigned int containerId(tok->tokAt(3)->varId()); const unsigned int containerId(tok->tokAt(3)->varId());
if (pointerId == 0 || containerId == 0) if(pointerId == 0 || containerId == 0)
continue; continue;
int indent = 0; int indent = 0;
bool invalidPointer = false; 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; ++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(); tok2 = tok2->next();
else else
--indent; --indent;
} }
// push_back on vector.. // 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; invalidPointer = true;
// Using invalid pointer.. // 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()); invalidPointerError(tok2, tok2->str());
else if (tok2->next()->str() == ".") else if(tok2->next()->str() == ".")
invalidPointerError(tok2, tok2->str()); invalidPointerError(tok2, tok2->str());
break; break;
} }
@ -302,31 +302,31 @@ void CheckStl::pushback()
} }
// Iterator becomes invalid after push_back or push_front.. // 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; continue;
// if iterator declaration inside for() loop // if iterator declaration inside for() loop
bool iteratorDeclaredInsideLoop = false; bool iteratorDeclaredInsideLoop = false;
if ((tok->tokAt(-2) && Token::simpleMatch(tok->tokAt(-2), "for (")) || if((tok->tokAt(-2) && Token::simpleMatch(tok->tokAt(-2), "for (")) ||
(tok->tokAt(-4) && Token::simpleMatch(tok->tokAt(-4), "for ( std ::"))) (tok->tokAt(-4) && Token::simpleMatch(tok->tokAt(-4), "for ( std ::")))
{ {
iteratorDeclaredInsideLoop = true; iteratorDeclaredInsideLoop = true;
} }
while (tok && tok->str() != ">") while(tok && tok->str() != ">")
tok = tok->next(); tok = tok->next();
if (!tok) if(!tok)
break; break;
if (!Token::Match(tok, "> :: iterator|const_iterator %var% =|;")) if(!Token::Match(tok, "> :: iterator|const_iterator %var% =|;"))
continue; continue;
const unsigned int iteratorid(tok->tokAt(3)->varId()); const unsigned int iteratorid(tok->tokAt(3)->varId());
if (iteratorid == 0) if(iteratorid == 0)
continue; continue;
if (iteratorDeclaredInsideLoop && tok->tokAt(4)->str() == "=") if(iteratorDeclaredInsideLoop && tok->tokAt(4)->str() == "=")
{ {
// skip "> :: iterator|const_iterator" // skip "> :: iterator|const_iterator"
tok = tok->tokAt(3); tok = tok->tokAt(3);
@ -335,61 +335,61 @@ void CheckStl::pushback()
unsigned int vectorid = 0; unsigned int vectorid = 0;
int indent = 0; int indent = 0;
std::string invalidIterator; 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; ++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(); tok2 = tok2->next();
else else
--indent; --indent;
} }
// Using push_back or push_front inside a loop.. // Using push_back or push_front inside a loop..
if (Token::Match(tok2, "for (")) if(Token::Match(tok2, "for ("))
{ {
tok2 = tok2->tokAt(2); 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()); const unsigned int vectorid(tok2->tokAt(2)->varId());
if (vectorid == 0) if(vectorid == 0)
continue; continue;
const Token *pushback = 0; const Token *pushback = 0;
unsigned int indent3 = 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; ++indent3;
else if (tok3->str() == "}") else if(tok3->str() == "}")
{ {
if (indent3 <= 1) if(indent3 <= 1)
break; break;
--indent3; --indent3;
} }
else if (tok3->str() == "break") else if(tok3->str() == "break")
{ {
pushback = 0; pushback = 0;
break; 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); pushback = tok3->tokAt(2);
} }
} }
if (pushback) if(pushback)
invalidIteratorError(pushback, pushback->str(), tok2->strAt(0)); invalidIteratorError(pushback, pushback->str(), tok2->strAt(0));
} }
// Assigning iterator.. // 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(); vectorid = tok2->tokAt(2)->varId();
tok2 = tok2->tokAt(6); tok2 = tok2->tokAt(6);
@ -402,29 +402,29 @@ void CheckStl::pushback()
} }
// push_back on vector.. // 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)); invalidIteratorError(tok2, invalidIterator, tok2->strAt(4));
break; break;
} }
invalidIterator = tok2->strAt(2); invalidIterator = tok2->strAt(2);
if (!iteratorDeclaredInsideLoop) if(!iteratorDeclaredInsideLoop)
{ {
tok2 = tok2->tokAt(3)->link(); tok2 = tok2->tokAt(3)->link();
if (!tok2) if(!tok2)
break; break;
} }
} }
// Using invalid iterator.. // 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)); invalidIteratorError(tok2, invalidIterator, tok2->strAt(1));
if (Token::Match(tok2, "%varid% ++|--|+|-", iteratorid)) if(Token::Match(tok2, "%varid% ++|--|+|-", iteratorid))
invalidIteratorError(tok2, invalidIterator, tok2->str()); invalidIteratorError(tok2, invalidIterator, tok2->str());
} }
} }
@ -453,37 +453,37 @@ void CheckStl::stlBoundries()
// containers (not the vector).. // 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"; 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.. // Declaring iterator..
const std::string checkStr = (std::string(STL_CONTAINER_LIST) + " <"); 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)); const std::string container_name(tok->strAt(0));
while (tok && tok->str() != ">") while(tok && tok->str() != ">")
tok = tok->next(); tok = tok->next();
if (!tok) if(!tok)
break; 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()); const unsigned int iteratorid(tok->tokAt(3)->varId());
if (iteratorid == 0) if(iteratorid == 0)
continue; continue;
// Using "iterator < ..." is not allowed // Using "iterator < ..." is not allowed
unsigned int indentlevel = 0; 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; ++indentlevel;
else if (tok2->str() == "}") else if(tok2->str() == "}")
{ {
if (indentlevel == 0) if(indentlevel == 0)
break; break;
--indentlevel; --indentlevel;
} }
else if (Token::Match(tok2, "!!* %varid% <", iteratorid)) else if(Token::Match(tok2, "!!* %varid% <", iteratorid))
{ {
stlBoundriesError(tok2, container_name); stlBoundriesError(tok2, container_name);
} }
@ -503,23 +503,23 @@ void CheckStl::stlBoundriesError(const Token *tok, const std::string &container_
void CheckStl::find() 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; continue;
if (!Token::Match(tok->next(), "%var% = std :: find (")) if(!Token::Match(tok->next(), "%var% = std :: find ("))
continue; continue;
const unsigned int iteratorid = tok->next()->varId(); const unsigned int iteratorid = tok->next()->varId();
if (iteratorid == 0) if(iteratorid == 0)
continue; continue;
tok = tok->tokAt(6)->link(); tok = tok->tokAt(6)->link();
if (!tok) if(!tok)
break; 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; break;
if (tok2->varId() == iteratorid && Token::simpleMatch(tok2->previous(), "*")) if(tok2->varId() == iteratorid && Token::simpleMatch(tok2->previous(), "*"))
findError(tok2); findError(tok2);
} }
} }
@ -535,42 +535,42 @@ void CheckStl::findError(const Token *tok)
void CheckStl::if_find() void CheckStl::if_find()
{ {
if (!_settings->_checkCodingStyle) if(!_settings->_checkCodingStyle)
return; 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% // goto %var%
tok = tok->tokAt(2); tok = tok->tokAt(2);
if (!tok->isName()) if(!tok->isName())
tok = tok->next(); tok = tok->next();
const unsigned int varid = tok->varId(); const unsigned int varid = tok->varId();
if (varid > 0) if(varid > 0)
{ {
// Is the variable a std::string or STL container? // Is the variable a std::string or STL container?
const Token * decl = Token::findmatch(_tokenizer->tokens(), "%varid%", varid); const Token * decl = Token::findmatch(_tokenizer->tokens(), "%varid%", varid);
while (decl && !Token::Match(decl, "[;{}(,]")) while(decl && !Token::Match(decl, "[;{}(,]"))
decl = decl->previous(); decl = decl->previous();
decl = decl->next(); decl = decl->next();
// stl container // 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_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 // goto '(' for the find
tok = tok->tokAt(4); tok = tok->tokAt(4);
if (tok->isName()) if(tok->isName())
tok = tok->next(); tok = tok->next();
// check that result is checked properly // check that result is checked properly
if (Token::simpleMatch(tok->link(), ") )")) if(Token::simpleMatch(tok->link(), ") )"))
{ {
if_findError(tok, false); if_findError(tok, false);
} }
@ -581,7 +581,7 @@ void CheckStl::if_find()
void CheckStl::if_findError(const Token *tok, bool str) 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."); 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 else
reportError(tok, Severity::style, "stlIfFind", "Suspicious condition. The result of find is an iterator, but it is not properly checked."); 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) bool CheckStl::isStlContainer(const Token *tok)
{ {
// check if this token is defined // check if this token is defined
if (tok->varId()) if(tok->varId())
{ {
// find where this token is defined // find where this token is defined
const Token *type = Token::findmatch(_tokenizer->tokens(), "%varid%", tok->varId()); const Token *type = Token::findmatch(_tokenizer->tokens(), "%varid%", tok->varId());
// find where this tokens type starts // find where this tokens type starts
while (type->previous() && !Token::Match(type->previous(), "[;{,(]")) while(type->previous() && !Token::Match(type->previous(), "[;{,(]"))
type = type->previous(); type = type->previous();
// ignore "const" // ignore "const"
if (type->str() == "const") if(type->str() == "const")
type = type->next(); type = type->next();
// discard namespace if supplied // discard namespace if supplied
if (Token::simpleMatch(type, "std ::")) if(Token::simpleMatch(type, "std ::"))
type = type->next()->next(); type = type->next()->next();
// all possible stl containers // all possible stl containers
@ -616,7 +616,7 @@ bool CheckStl::isStlContainer(const Token *tok)
const std::string checkStr(std::string(STL_CONTAINER_LIST) + " <"); const std::string checkStr(std::string(STL_CONTAINER_LIST) + " <");
// check if it's an stl template // check if it's an stl template
if (Token::Match(type, checkStr.c_str())) if(Token::Match(type, checkStr.c_str()))
return true; return true;
} }
@ -625,16 +625,16 @@ bool CheckStl::isStlContainer(const Token *tok)
void CheckStl::size() 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); sizeError(tok);
} }
else if ((tok->tokAt(5)->str() == ")" || else if((tok->tokAt(5)->str() == ")" ||
tok->tokAt(5)->str() == "&&" || tok->tokAt(5)->str() == "&&" ||
tok->tokAt(5)->str() == "||" || tok->tokAt(5)->str() == "||" ||
tok->tokAt(5)->str() == "!") && tok->tokAt(5)->str() == "!") &&
@ -643,17 +643,17 @@ void CheckStl::size()
tok->tokAt(-1)->str() == "||" || tok->tokAt(-1)->str() == "||" ||
tok->tokAt(-1)->str() == "!")) tok->tokAt(-1)->str() == "!"))
{ {
if (tok->tokAt(-1)->str() == "(" && if(tok->tokAt(-1)->str() == "(" &&
tok->tokAt(5)->str() == ")") tok->tokAt(5)->str() == ")")
{ {
// check for passing size to function call // 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); sizeError(tok);
} }
} }
else if (isStlContainer(tok)) else if(isStlContainer(tok))
sizeError(tok); sizeError(tok);
} }
} }

View File

@ -56,9 +56,9 @@ public:
checkStl.find(); checkStl.find();
checkStl.if_find(); checkStl.if_find();
if (settings->_checkCodingStyle) if(settings->_checkCodingStyle)
{ {
if (settings->_showAll) if(settings->_showAll)
checkStl.size(); checkStl.size();
} }
} }

View File

@ -48,44 +48,44 @@ void CheckUnusedFunctions::setErrorLogger(ErrorLogger *errorLogger)
void CheckUnusedFunctions::parseTokens(const Tokenizer &tokenizer) void CheckUnusedFunctions::parseTokens(const Tokenizer &tokenizer)
{ {
// Function declarations.. // 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; continue;
// token contains a ':' => skip to next ; or { // 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(); tok = tok->next();
if (tok) if(tok)
continue; continue;
break; break;
} }
// If this is a template function, skip it // If this is a template function, skip it
if (tok->previous() && tok->previous()->str() == ">") if(tok->previous() && tok->previous()->str() == ">")
continue; continue;
const Token *funcname = 0; const Token *funcname = 0;
if (Token::Match(tok, "%type% %var% (")) if(Token::Match(tok, "%type% %var% ("))
funcname = tok->tokAt(1); funcname = tok->tokAt(1);
else if (Token::Match(tok, "%type% * %var% (")) else if(Token::Match(tok, "%type% * %var% ("))
funcname = tok->tokAt(2); 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); funcname = tok->tokAt(2);
// Don't assume throw as a function name: void foo() throw () {} // 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; funcname = 0;
// Check that ") {" is found.. // 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, ") {") && if(! Token::simpleMatch(tok2, ") {") &&
! Token::simpleMatch(tok2, ") const {") && ! Token::simpleMatch(tok2, ") const {") &&
! Token::simpleMatch(tok2, ") const throw ( ) {") && ! Token::simpleMatch(tok2, ") const throw ( ) {") &&
! Token::simpleMatch(tok2, ") throw ( ) {")) ! Token::simpleMatch(tok2, ") throw ( ) {"))
@ -94,16 +94,16 @@ void CheckUnusedFunctions::parseTokens(const Tokenizer &tokenizer)
} }
} }
if (funcname) if(funcname)
{ {
FunctionUsage &func = _functions[ funcname->str()]; FunctionUsage &func = _functions[ funcname->str()];
// No filename set yet.. // No filename set yet..
if (func.filename.empty()) if(func.filename.empty())
func.filename = tokenizer.getFiles()->at(0); func.filename = tokenizer.getFiles()->at(0);
// Multiple files => filename = "+" // Multiple files => filename = "+"
else if (func.filename != tokenizer.getFiles()->at(0)) else if(func.filename != tokenizer.getFiles()->at(0))
{ {
func.filename = "+"; func.filename = "+";
func.usedOtherFile |= func.usedSameFile; func.usedOtherFile |= func.usedSameFile;
@ -112,49 +112,49 @@ void CheckUnusedFunctions::parseTokens(const Tokenizer &tokenizer)
} }
// Function usage.. // 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; const Token *funcname = 0;
if (Token::Match(tok->next(), "%var% (")) if(Token::Match(tok->next(), "%var% ("))
{ {
funcname = tok->next(); funcname = tok->next();
} }
else if (Token::Match(tok, "[;{}.,()[=+-/&|!?:] %var% [(),;:}]")) else if(Token::Match(tok, "[;{}.,()[=+-/&|!?:] %var% [(),;:}]"))
funcname = tok->next(); funcname = tok->next();
else if (Token::Match(tok, "[=(,] & %var% :: %var% [,);]")) else if(Token::Match(tok, "[=(,] & %var% :: %var% [,);]"))
funcname = tok->tokAt(4); funcname = tok->tokAt(4);
else else
continue; continue;
// funcname ( => Assert that the end paranthesis isn't followed by { // funcname ( => Assert that the end paranthesis isn't followed by {
if (Token::Match(funcname, "%var% (")) if(Token::Match(funcname, "%var% ("))
{ {
int parlevel = 0; 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; ++parlevel;
else if (tok2->str() == ")") else if(tok2->str() == ")")
{ {
--parlevel; --parlevel;
if (parlevel == 0 && (Token::Match(tok2, ") const|{"))) if(parlevel == 0 && (Token::Match(tok2, ") const|{")))
funcname = NULL; funcname = NULL;
if (parlevel <= 0) if(parlevel <= 0)
break; break;
} }
} }
} }
if (funcname) if(funcname)
{ {
FunctionUsage &func = _functions[ funcname->str()]; FunctionUsage &func = _functions[ funcname->str()];
if (func.filename.empty() || func.filename == "+") if(func.filename.empty() || func.filename == "+")
func.usedOtherFile = true; func.usedOtherFile = true;
else else
@ -168,23 +168,23 @@ void CheckUnusedFunctions::parseTokens(const Tokenizer &tokenizer)
void CheckUnusedFunctions::check() void CheckUnusedFunctions::check()
{ {
for (std::map<std::string, FunctionUsage>::const_iterator it = _functions.begin(); it != _functions.end(); ++it) for(std::map<std::string, FunctionUsage>::const_iterator it = _functions.begin(); it != _functions.end(); ++it)
{ {
const FunctionUsage &func = it->second; const FunctionUsage &func = it->second;
if (func.usedOtherFile || func.filename.empty()) if(func.usedOtherFile || func.filename.empty())
continue; continue;
if (it->first == "main" || it->first == "WinMain" || it->first == "if") if(it->first == "main" || it->first == "WinMain" || it->first == "if")
continue; continue;
if (! func.usedSameFile) if(! func.usedSameFile)
{ {
std::string filename; std::string filename;
if (func.filename == "+") if(func.filename == "+")
filename = ""; filename = "";
else else
filename = func.filename; filename = func.filename;
_errorLogger->unusedFunction(filename, it->first); _errorLogger->unusedFunction(filename, it->first);
} }
else if (! func.usedOtherFile) else if(! func.usedOtherFile)
{ {
/** @todo add error message "function is only used in <file> it can be static" */ /** @todo add error message "function is only used in <file> it can be static" */
/* /*

View File

@ -94,12 +94,12 @@ static void AddFilesToList(const std::string& FileList, std::vector<std::string>
// we need a good parser then -> suggestion : TinyXml // we need a good parser then -> suggestion : TinyXml
// drawback : creates a dependency // drawback : creates a dependency
std::ifstream Files(FileList.c_str()); std::ifstream Files(FileList.c_str());
if (Files) if(Files)
{ {
std::string FileName; 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); PathNames.push_back(FileName);
} }
@ -111,88 +111,88 @@ void CppCheck::parseFromArgs(int argc, const char* const argv[])
{ {
std::vector<std::string> pathnames; std::vector<std::string> pathnames;
bool showHelp = false; 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()); reportOut(std::string("Cppcheck ") + version());
return; return;
} }
// Flag used for various purposes during debugging // Flag used for various purposes during debugging
else if (strcmp(argv[i], "--debug") == 0) else if(strcmp(argv[i], "--debug") == 0)
_settings._debug = true; _settings._debug = true;
// Show all messages // 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"); _settings.addEnabled("possibleError");
// Only print something when there are errors // 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; _settings._errorsOnly = true;
// Checking coding style // 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"); _settings.addEnabled("style");
// Filter errors // Filter errors
else if (strcmp(argv[i], "--suppressions") == 0) else if(strcmp(argv[i], "--suppressions") == 0)
{ {
++i; ++i;
if (i >= argc) if(i >= argc)
throw std::runtime_error("cppcheck: No file specified for the --suppressions option"); throw std::runtime_error("cppcheck: No file specified for the --suppressions option");
std::ifstream f(argv[i]); 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]) + "\""); throw std::runtime_error("cppcheck: Couldn't open the file \"" + std::string(argv[i]) + "\"");
_settings.nomsg.parseFile(f); _settings.nomsg.parseFile(f);
} }
// Filter errors // Filter errors
else if (strcmp(argv[i], "--exitcode-suppressions") == 0) else if(strcmp(argv[i], "--exitcode-suppressions") == 0)
{ {
++i; ++i;
if (i >= argc) if(i >= argc)
throw std::runtime_error("cppcheck: No file specified for the --exitcode-suppressions option"); throw std::runtime_error("cppcheck: No file specified for the --exitcode-suppressions option");
std::ifstream f(argv[i]); 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]) + "\""); throw std::runtime_error("cppcheck: Couldn't open the file \"" + std::string(argv[i]) + "\"");
_settings.nofail.parseFile(f); _settings.nofail.parseFile(f);
} }
// Enables inline suppressions. // Enables inline suppressions.
else if (strcmp(argv[i], "--inline-suppr") == 0) else if(strcmp(argv[i], "--inline-suppr") == 0)
_settings._inlineSuppressions = true; _settings._inlineSuppressions = true;
// Verbose error messages (configuration info) // 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; _settings._verbose = true;
// Force checking of files that have "too many" configurations // 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; _settings._force = true;
// Write results in results.xml // Write results in results.xml
else if (strcmp(argv[i], "--xml") == 0) else if(strcmp(argv[i], "--xml") == 0)
_settings._xml = true; _settings._xml = true;
// Check if there are unused functions // 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"); _settings.addEnabled("unusedFunctions");
// Append userdefined code to checked source code // 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]); _settings.append(9 + argv[i]);
// show timing information.. // show timing information..
else if (strcmp(argv[i], "--showtime") == 0) else if(strcmp(argv[i], "--showtime") == 0)
_settings._showtime = true; _settings._showtime = true;
// Print help // 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(); pathnames.clear();
_filenames.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); _settings.addEnabled(argv[i] + 9);
} }
// --error-exitcode=1 // --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]; std::string temp = argv[i];
temp = temp.substr(17); temp = temp.substr(17);
std::istringstream iss(temp); std::istringstream iss(temp);
if (!(iss >> _settings._exitCode)) if(!(iss >> _settings._exitCode))
{ {
_settings._exitCode = 0; _settings._exitCode = 0;
throw std::runtime_error("cppcheck: Argument must be an integer. Try something like '--error-exitcode=1'"); 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 // 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; std::string path;
// "-I path/" // "-I path/"
if (strcmp(argv[i], "-I") == 0) if(strcmp(argv[i], "-I") == 0)
{ {
++i; ++i;
if (i >= argc) if(i >= argc)
throw std::runtime_error("cppcheck: argument to '-I' is missing"); throw std::runtime_error("cppcheck: argument to '-I' is missing");
path = argv[i]; 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 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 += '/'; path += '/';
_settings._includePaths.push_back(path); _settings._includePaths.push_back(path);
} }
// file list specified // 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) // open this file and read every input file (1 file name per line)
AddFilesToList(12 + argv[i], pathnames); AddFilesToList(12 + argv[i], pathnames);
} }
// Output formatter // Output formatter
else if (strcmp(argv[i], "--template") == 0) else if(strcmp(argv[i], "--template") == 0)
{ {
// "--template path/" // "--template path/"
++i; ++i;
if (i >= argc) if(i >= argc)
throw std::runtime_error("cppcheck: argument to '--template' is missing"); throw std::runtime_error("cppcheck: argument to '--template' is missing");
_settings._outputFormat = argv[i]; _settings._outputFormat = argv[i];
if (_settings._outputFormat == "gcc") if(_settings._outputFormat == "gcc")
_settings._outputFormat = "{file}:{line}: {severity}: {message}"; _settings._outputFormat = "{file}:{line}: {severity}: {message}";
else if (_settings._outputFormat == "vs") else if(_settings._outputFormat == "vs")
_settings._outputFormat = "{file}({line}): {severity}: {message}"; _settings._outputFormat = "{file}({line}): {severity}: {message}";
} }
// Checking threads // Checking threads
else if (strcmp(argv[i], "-j") == 0 || else if(strcmp(argv[i], "-j") == 0 ||
strncmp(argv[i], "-j", 2) == 0) strncmp(argv[i], "-j", 2) == 0)
{ {
std::string numberString; std::string numberString;
// "-j 3" // "-j 3"
if (strcmp(argv[i], "-j") == 0) if(strcmp(argv[i], "-j") == 0)
{ {
++i; ++i;
if (i >= argc) if(i >= argc)
throw std::runtime_error("cppcheck: argument to '-j' is missing"); throw std::runtime_error("cppcheck: argument to '-j' is missing");
numberString = argv[i]; numberString = argv[i];
} }
// "-j3" // "-j3"
else if (strncmp(argv[i], "-j", 2) == 0) else if(strncmp(argv[i], "-j", 2) == 0)
{ {
numberString = argv[i]; numberString = argv[i];
numberString = numberString.substr(2); numberString = numberString.substr(2);
} }
std::istringstream iss(numberString); std::istringstream iss(numberString);
if (!(iss >> _settings._jobs)) if(!(iss >> _settings._jobs))
throw std::runtime_error("cppcheck: argument to '-j' is not a number"); 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"); throw std::runtime_error("cppcheck: argument for '-j' is allowed to be 1000 at max");
} }
} }
// auto deallocated classes.. // auto deallocated classes..
else if (strcmp(argv[i], "--auto-dealloc") == 0) else if(strcmp(argv[i], "--auto-dealloc") == 0)
{ {
++i; ++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"); throw std::runtime_error("cppcheck: No .lst file specified for the --auto-dealloc option");
std::ifstream f(argv[i]); 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]) + "\""); throw std::runtime_error("cppcheck: couldn't open the file \"" + std::string(argv[i+1]) + "\"");
_settings.autoDealloc(f); _settings.autoDealloc(f);
} }
// print all possible error messages.. // 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 // call all "getErrorMessages" in all registered Check classes
std::cout << ErrorLogger::ErrorMessage::getXMLHeader(); std::cout << ErrorLogger::ErrorMessage::getXMLHeader();
for (std::list<Check *>::iterator it = Check::instances().begin(); it != Check::instances().end(); ++it) for(std::list<Check *>::iterator it = Check::instances().begin(); it != Check::instances().end(); ++it)
{ {
(*it)->getErrorMessages(); (*it)->getErrorMessages();
} }
@ -336,11 +336,11 @@ void CppCheck::parseFromArgs(int argc, const char* const argv[])
} }
// documentation.. // documentation..
else if (strcmp(argv[i], "--doc") == 0) else if(strcmp(argv[i], "--doc") == 0)
{ {
std::ostringstream doc; std::ostringstream doc;
// Get documentation.. // Get documentation..
for (std::list<Check *>::iterator it = Check::instances().begin(); it != Check::instances().end(); ++it) for(std::list<Check *>::iterator it = Check::instances().begin(); it != Check::instances().end(); ++it)
{ {
doc << "===" << (*it)->name() << "===\n" doc << "===" << (*it)->name() << "===\n"
<< (*it)->classInfo() << "\n\n"; << (*it)->classInfo() << "\n\n";
@ -348,13 +348,13 @@ void CppCheck::parseFromArgs(int argc, const char* const argv[])
doc << "===" << "Unused functions" << "===\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()); 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); doc2.erase(doc2.find("\n\n\n"), 1);
std::cout << doc2; std::cout << doc2;
return; 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]) + "\""); throw std::runtime_error("cppcheck: error: unrecognized command line option \"" + std::string(argv[i]) + "\"");
} }
@ -363,20 +363,20 @@ void CppCheck::parseFromArgs(int argc, const char* const argv[])
pathnames.push_back(argv[i]); 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."); 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 // Execute recursiveAddFiles() to each given file parameter
std::vector<std::string>::const_iterator iter; std::vector<std::string>::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); getFileLister()->recursiveAddFiles(_filenames, iter->c_str(), true);
} }
if (argc <= 1 || showHelp) if(argc <= 1 || showHelp)
{ {
std::ostringstream oss; std::ostringstream oss;
oss << "Cppcheck - A tool for static C/C++ code analysis\n" oss << "Cppcheck - A tool for static C/C++ code analysis\n"
@ -455,7 +455,7 @@ void CppCheck::parseFromArgs(int argc, const char* const argv[])
" cppcheck -I inc1/ -I inc2/ f.cpp\n"; " cppcheck -I inc1/ -I inc2/ f.cpp\n";
reportOut(oss.str()); reportOut(oss.str());
} }
else if (_filenames.empty()) else if(_filenames.empty())
{ {
throw std::runtime_error("cppcheck: No C or C++ source files found."); throw std::runtime_error("cppcheck: No C or C++ source files found.");
} }
@ -467,15 +467,15 @@ unsigned int CppCheck::check()
_checkUnusedFunctions.setErrorLogger(this); _checkUnusedFunctions.setErrorLogger(this);
std::sort(_filenames.begin(), _filenames.end()); 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(""); _errout.str("");
const std::string fname = _filenames[c]; const std::string fname = _filenames[c];
if (_settings.terminated()) if(_settings.terminated())
break; break;
if (_settings._errorsOnly == false) if(_settings._errorsOnly == false)
_errorLogger.reportOut(std::string("Checking ") + fname + std::string("...")); _errorLogger.reportOut(std::string("Checking ") + fname + std::string("..."));
try try
@ -484,7 +484,7 @@ unsigned int CppCheck::check()
std::list<std::string> configurations; std::list<std::string> configurations;
std::string filedata = ""; 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 // File content was given as a string
std::istringstream iss(_fileContents[ _filenames[c] ]); std::istringstream iss(_fileContents[ _filenames[c] ]);
@ -500,13 +500,13 @@ unsigned int CppCheck::check()
} }
int checkCount = 0; int checkCount = 0;
for (std::list<std::string>::const_iterator it = configurations.begin(); it != configurations.end(); ++it) for(std::list<std::string>::const_iterator it = configurations.begin(); it != configurations.end(); ++it)
{ {
// Check only 12 first configurations, after that bail out, unless --force // Check only 12 first configurations, after that bail out, unless --force
// was used. // 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."); _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; break;
@ -518,14 +518,14 @@ unsigned int CppCheck::check()
TIMER_END("Preprocessor::getcode"); TIMER_END("Preprocessor::getcode");
// If only errors are printed, print filename after the check // 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("...")); _errorLogger.reportOut(std::string("Checking ") + fname + ": " + cfg + std::string("..."));
checkFile(codeWithoutCfg + _settings.append(), _filenames[c].c_str()); checkFile(codeWithoutCfg + _settings.append(), _filenames[c].c_str());
++checkCount; ++checkCount;
} }
} }
catch (std::runtime_error &e) catch(std::runtime_error &e)
{ {
// Exception was thrown when checking this file.. // Exception was thrown when checking this file..
_errorLogger.reportOut("Bailing out from checking " + fname + ": " + e.what()); _errorLogger.reportOut("Bailing out from checking " + fname + ": " + e.what());
@ -536,10 +536,10 @@ unsigned int CppCheck::check()
// This generates false positives - especially for libraries // This generates false positives - especially for libraries
_settings._verbose = false; _settings._verbose = false;
if (_settings.isEnabled("unusedFunctions") && _settings._jobs == 1) if(_settings.isEnabled("unusedFunctions") && _settings._jobs == 1)
{ {
_errout.str(""); _errout.str("");
if (_settings._errorsOnly == false) if(_settings._errorsOnly == false)
_errorLogger.reportOut("Checking usage of global functions.."); _errorLogger.reportOut("Checking usage of global functions..");
_checkUnusedFunctions.check(); _checkUnusedFunctions.check();
@ -556,7 +556,7 @@ unsigned int CppCheck::check()
void CppCheck::checkFile(const std::string &code, const char FileName[]) void CppCheck::checkFile(const std::string &code, const char FileName[])
{ {
if (_settings.terminated()) if(_settings.terminated())
return; return;
Tokenizer _tokenizer(&_settings, this); Tokenizer _tokenizer(&_settings, this);
@ -565,7 +565,7 @@ void CppCheck::checkFile(const std::string &code, const char FileName[])
{ {
std::istringstream istr(code); std::istringstream istr(code);
TIMER_START(); TIMER_START();
if (!_tokenizer.tokenize(istr, FileName, cfg)) if(!_tokenizer.tokenize(istr, FileName, cfg))
{ {
// File had syntax errors, abort // File had syntax errors, abort
return; return;
@ -580,9 +580,9 @@ void CppCheck::checkFile(const std::string &code, const char FileName[])
} }
// call all "runChecks" in all registered Check classes // call all "runChecks" in all registered Check classes
for (std::list<Check *>::iterator it = Check::instances().begin(); it != Check::instances().end(); ++it) for(std::list<Check *>::iterator it = Check::instances().begin(); it != Check::instances().end(); ++it)
{ {
if (_settings.terminated()) if(_settings.terminated())
return; return;
TIMER_START(); TIMER_START();
@ -594,7 +594,7 @@ void CppCheck::checkFile(const std::string &code, const char FileName[])
TIMER_START(); TIMER_START();
bool result = _tokenizer.simplifyTokenList(); bool result = _tokenizer.simplifyTokenList();
TIMER_END("Tokenizer::simplifyTokenList"); TIMER_END("Tokenizer::simplifyTokenList");
if (!result) if(!result)
return; return;
} }
@ -604,13 +604,13 @@ void CppCheck::checkFile(const std::string &code, const char FileName[])
TIMER_END("Tokenizer::fillFunctionList"); TIMER_END("Tokenizer::fillFunctionList");
} }
if (_settings.isEnabled("unusedFunctions") && _settings._jobs == 1) if(_settings.isEnabled("unusedFunctions") && _settings._jobs == 1)
_checkUnusedFunctions.parseTokens(_tokenizer); _checkUnusedFunctions.parseTokens(_tokenizer);
// call all "runSimplifiedChecks" in all registered Check classes // call all "runSimplifiedChecks" in all registered Check classes
for (std::list<Check *>::iterator it = Check::instances().begin(); it != Check::instances().end(); ++it) for(std::list<Check *>::iterator it = Check::instances().begin(); it != Check::instances().end(); ++it)
{ {
if (_settings.terminated()) if(_settings.terminated())
return; return;
TIMER_START(); TIMER_START();
@ -631,26 +631,26 @@ void CppCheck::reportErr(const ErrorLogger::ErrorMessage &msg)
std::string errmsg = msg.toText(); std::string errmsg = msg.toText();
// Alert only about unique errors // 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; return;
std::string file; std::string file;
unsigned int line(0); unsigned int line(0);
if (!msg._callStack.empty()) if(!msg._callStack.empty())
{ {
file = msg._callStack.back().getfile(); file = msg._callStack.back().getfile();
line = msg._callStack.back().line; line = msg._callStack.back().line;
} }
if (_settings.nomsg.isSuppressed(msg._id, file, line)) if(_settings.nomsg.isSuppressed(msg._id, file, line))
return; return;
if (!_settings.nofail.isSuppressed(msg._id, file, line)) if(!_settings.nofail.isSuppressed(msg._id, file, line))
exitcode = 1; exitcode = 1;
_errorList.push_back(errmsg); _errorList.push_back(errmsg);
std::string errmsg2(errmsg); std::string errmsg2(errmsg);
if (_settings._verbose) if(_settings._verbose)
{ {
errmsg2 += "\n Defines=\'" + cfg + "\'\n"; errmsg2 += "\n Defines=\'" + cfg + "\'\n";
} }

View File

@ -43,7 +43,7 @@ std::string ErrorLogger::ErrorMessage::serialize() const
oss << _msg.length() << " " << _msg; oss << _msg.length() << " " << _msg;
oss << _callStack.size() << " "; oss << _callStack.size() << " ";
for (std::list<ErrorLogger::ErrorMessage::FileLocation>::const_iterator tok = _callStack.begin(); tok != _callStack.end(); ++tok) for(std::list<ErrorLogger::ErrorMessage::FileLocation>::const_iterator tok = _callStack.begin(); tok != _callStack.end(); ++tok)
{ {
std::ostringstream smallStream; std::ostringstream smallStream;
smallStream << (*tok).line << ":" << (*tok).getfile(); smallStream << (*tok).line << ":" << (*tok).getfile();
@ -57,22 +57,22 @@ bool ErrorLogger::ErrorMessage::deserialize(const std::string &data)
_callStack.clear(); _callStack.clear();
std::istringstream iss(data); std::istringstream iss(data);
std::vector<std::string> results; std::vector<std::string> results;
while (iss.good()) while(iss.good())
{ {
unsigned int len = 0; unsigned int len = 0;
if (!(iss >> len)) if(!(iss >> len))
return false; return false;
iss.get(); iss.get();
std::string temp; 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<char>(iss.get()); char c = static_cast<char>(iss.get());
temp.append(1, c); temp.append(1, c);
} }
results.push_back(temp); results.push_back(temp);
if (results.size() == 3) if(results.size() == 3)
break; break;
} }
@ -81,18 +81,18 @@ bool ErrorLogger::ErrorMessage::deserialize(const std::string &data)
_msg = results[2]; _msg = results[2];
unsigned int stackSize = 0; unsigned int stackSize = 0;
if (!(iss >> stackSize)) if(!(iss >> stackSize))
return false; return false;
while (iss.good()) while(iss.good())
{ {
unsigned int len = 0; unsigned int len = 0;
if (!(iss >> len)) if(!(iss >> len))
return false; return false;
iss.get(); iss.get();
std::string temp; 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<char>(iss.get()); char c = static_cast<char>(iss.get());
temp.append(1, c); temp.append(1, c);
@ -106,7 +106,7 @@ bool ErrorLogger::ErrorMessage::deserialize(const std::string &data)
_callStack.push_back(loc); _callStack.push_back(loc);
if (_callStack.size() >= stackSize) if(_callStack.size() >= stackSize)
break; break;
} }
@ -127,15 +127,15 @@ std::string ErrorLogger::ErrorMessage::getXMLFooter()
static std::string stringToXml(std::string s) static std::string stringToXml(std::string s)
{ {
std::string::size_type pos = 0; 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, "&lt;"); s.insert(pos + 1, "&lt;");
else if (s[pos] == '>') else if(s[pos] == '>')
s.insert(pos + 1, "&gt;"); s.insert(pos + 1, "&gt;");
else if (s[pos] == '&') else if(s[pos] == '&')
s.insert(pos + 1, "&amp;"); s.insert(pos + 1, "&amp;");
else if (s[pos] == '"') else if(s[pos] == '"')
s.insert(pos + 1, "&quot;"); s.insert(pos + 1, "&quot;");
s.erase(pos, 1); s.erase(pos, 1);
++pos; ++pos;
@ -147,7 +147,7 @@ std::string ErrorLogger::ErrorMessage::toXML() const
{ {
std::ostringstream xml; std::ostringstream xml;
xml << "<error"; xml << "<error";
if (!_callStack.empty()) if(!_callStack.empty())
{ {
xml << " file=\"" << stringToXml(_callStack.back().getfile()) << "\""; xml << " file=\"" << stringToXml(_callStack.back().getfile()) << "\"";
xml << " line=\"" << _callStack.back().line << "\""; xml << " line=\"" << _callStack.back().line << "\"";
@ -162,7 +162,7 @@ std::string ErrorLogger::ErrorMessage::toXML() const
void ErrorLogger::ErrorMessage::findAndReplace(std::string &source, const std::string &searchFor, const std::string &replaceWith) void ErrorLogger::ErrorMessage::findAndReplace(std::string &source, const std::string &searchFor, const std::string &replaceWith)
{ {
std::string::size_type index = 0; std::string::size_type index = 0;
while ((index = source.find(searchFor, index)) != std::string::npos) while((index = source.find(searchFor, index)) != std::string::npos)
{ {
source.replace(index, searchFor.length(), replaceWith); source.replace(index, searchFor.length(), replaceWith);
index += replaceWith.length() - searchFor.length() + 1; index += replaceWith.length() - searchFor.length() + 1;
@ -171,12 +171,12 @@ void ErrorLogger::ErrorMessage::findAndReplace(std::string &source, const std::s
std::string ErrorLogger::ErrorMessage::toText(const std::string &outputFormat) const std::string ErrorLogger::ErrorMessage::toText(const std::string &outputFormat) const
{ {
if (outputFormat.length() == 0) if(outputFormat.length() == 0)
{ {
std::ostringstream text; std::ostringstream text;
if (!_callStack.empty()) if(!_callStack.empty())
text << callStackToString(_callStack) << ": "; text << callStackToString(_callStack) << ": ";
if (!_severity.empty()) if(!_severity.empty())
text << "(" << _severity << ") "; text << "(" << _severity << ") ";
text << _msg; text << _msg;
return text.str(); return text.str();
@ -188,7 +188,7 @@ std::string ErrorLogger::ErrorMessage::toText(const std::string &outputFormat) c
findAndReplace(result, "{severity}", _severity); findAndReplace(result, "{severity}", _severity);
findAndReplace(result, "{message}", _msg); findAndReplace(result, "{message}", _msg);
if (!_callStack.empty()) if(!_callStack.empty())
{ {
std::ostringstream oss; std::ostringstream oss;
oss << _callStack.back().line; oss << _callStack.back().line;
@ -215,7 +215,7 @@ void ErrorLogger::_writemsg(const Tokenizer *tokenizer, const Token *tok, const
void ErrorLogger::_writemsg(const Tokenizer *tokenizer, const std::list<const Token *> &callstack, const char severity[], const std::string &msg, const std::string &id) void ErrorLogger::_writemsg(const Tokenizer *tokenizer, const std::list<const Token *> &callstack, const char severity[], const std::string &msg, const std::string &id)
{ {
std::list<ErrorLogger::ErrorMessage::FileLocation> locationList; std::list<ErrorLogger::ErrorMessage::FileLocation> locationList;
for (std::list<const Token *>::const_iterator tok = callstack.begin(); tok != callstack.end(); ++tok) for(std::list<const Token *>::const_iterator tok = callstack.begin(); tok != callstack.end(); ++tok)
{ {
ErrorLogger::ErrorMessage::FileLocation loc; ErrorLogger::ErrorMessage::FileLocation loc;
loc.file = tokenizer->file(*tok); loc.file = tokenizer->file(*tok);
@ -232,7 +232,7 @@ void ErrorLogger::_writemsg(const Tokenizer *tokenizer, const std::list<const To
std::string ErrorLogger::callStackToString(const std::list<ErrorLogger::ErrorMessage::FileLocation> &callStack) std::string ErrorLogger::callStackToString(const std::list<ErrorLogger::ErrorMessage::FileLocation> &callStack)
{ {
std::ostringstream ostr; std::ostringstream ostr;
for (std::list<ErrorLogger::ErrorMessage::FileLocation>::const_iterator tok = callStack.begin(); tok != callStack.end(); ++tok) for(std::list<ErrorLogger::ErrorMessage::FileLocation>::const_iterator tok = callStack.begin(); tok != callStack.end(); ++tok)
ostr << (tok == callStack.begin() ? "" : " -> ") << "[" << (*tok).getfile() << ":" << (*tok).line << "]"; ostr << (tok == callStack.begin() ? "" : " -> ") << "[" << (*tok).getfile() << ":" << (*tok).line << "]";
return ostr.str(); return ostr.str();
} }
@ -244,23 +244,23 @@ std::string ErrorLogger::ErrorMessage::FileLocation::getfile() const
// replace "/ab/.." with "/".. // replace "/ab/.." with "/"..
std::string::size_type pos = 0; 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.. // position must be at least 4..
if (pos < 4) if(pos < 4)
continue; continue;
// Previous char must be a separator.. // Previous char must be a separator..
if (f[pos-1] != '/' && f[pos-2] != '\\') if(f[pos-1] != '/' && f[pos-2] != '\\')
continue; continue;
// Next char must be a separator.. // Next char must be a separator..
if (f[pos+2] != '/' && f[pos+2] != '\\') if(f[pos+2] != '/' && f[pos+2] != '\\')
continue; continue;
// Locate previous separator.. // Locate previous separator..
std::string::size_type sep = f.find_last_of("/\\", pos - 2); std::string::size_type sep = f.find_last_of("/\\", pos - 2);
if (sep == std::string::npos) if(sep == std::string::npos)
continue; continue;
// Delete substring.. // Delete substring..

View File

@ -359,7 +359,7 @@ public:
enum e { error, style, possibleError, possibleStyle }; enum e { error, style, possibleError, possibleStyle };
static std::string stringify(e severity) static std::string stringify(e severity)
{ {
switch (severity) switch(severity)
{ {
case error: case error:
return "error"; return "error";

View File

@ -25,27 +25,27 @@
// default : bail out if the condition is has variable handling // default : bail out if the condition is has variable handling
bool ExecutionPath::parseCondition(const Token &tok, std::list<ExecutionPath *> & checks) bool ExecutionPath::parseCondition(const Token &tok, std::list<ExecutionPath *> & checks)
{ {
if (Token::Match(tok.tokAt(-3), "!!else if (")) if(Token::Match(tok.tokAt(-3), "!!else if ("))
{ {
++ifinfo; ++ifinfo;
} }
unsigned int parlevel = 0; 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; ++parlevel;
else if (tok2->str() == ")") else if(tok2->str() == ")")
{ {
if (parlevel == 0) if(parlevel == 0)
break; break;
--parlevel; --parlevel;
} }
else if (Token::Match(tok2, ";{}")) else if(Token::Match(tok2, ";{}"))
break; break;
if (tok2->varId() != 0) if(tok2->varId() != 0)
{ {
if (ifinfo > 1) if(ifinfo > 1)
return true; return true;
else else
bailOutVar(checks, tok2->varId()); bailOutVar(checks, tok2->varId());
@ -58,33 +58,33 @@ bool ExecutionPath::parseCondition(const Token &tok, std::list<ExecutionPath *>
static const Token *checkExecutionPaths_(const Token *tok, std::list<ExecutionPath *> &checks) static const Token *checkExecutionPaths_(const Token *tok, std::list<ExecutionPath *> &checks)
{ {
if (!tok || tok->str() == "}" || checks.empty()) if(!tok || tok->str() == "}" || checks.empty())
return 0; return 0;
const std::auto_ptr<ExecutionPath> check(checks.front()->copy()); const std::auto_ptr<ExecutionPath> check(checks.front()->copy());
for (; tok; tok = tok->next()) for(; tok; tok = tok->next())
{ {
if (tok->str() == "}") if(tok->str() == "}")
return 0; return 0;
if (Token::simpleMatch(tok, "while (")) if(Token::simpleMatch(tok, "while ("))
{ {
// parse condition // 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); ExecutionPath::bailOut(checks);
return 0; return 0;
} }
// skip "while (fgets()!=NULL)" // skip "while (fgets()!=NULL)"
if (Token::simpleMatch(tok, "while ( fgets (")) if(Token::simpleMatch(tok, "while ( fgets ("))
{ {
const Token *tok2 = tok->tokAt(3)->link(); const Token *tok2 = tok->tokAt(3)->link();
if (Token::simpleMatch(tok2, ") ) {")) if(Token::simpleMatch(tok2, ") ) {"))
{ {
tok = tok2->tokAt(2)->link(); tok = tok2->tokAt(2)->link();
if (!tok) if(!tok)
break; break;
continue; continue;
} }
@ -92,15 +92,15 @@ static const Token *checkExecutionPaths_(const Token *tok, std::list<ExecutionPa
} }
// for/while/switch/do .. bail out // for/while/switch/do .. bail out
if (Token::Match(tok, "for|while|switch|do")) if(Token::Match(tok, "for|while|switch|do"))
{ {
// goto { // goto {
const Token *tok2 = tok->next(); const Token *tok2 = tok->next();
if (tok2 && tok2->str() == "(") if(tok2 && tok2->str() == "(")
tok2 = tok2->link(); tok2 = tok2->link();
if (tok2 && tok2->str() == ")") if(tok2 && tok2->str() == ")")
tok2 = tok2->next(); tok2 = tok2->next();
if (!tok2 || tok2->str() != "{") if(!tok2 || tok2->str() != "{")
{ {
ExecutionPath::bailOut(checks); ExecutionPath::bailOut(checks);
return 0; return 0;
@ -110,16 +110,16 @@ static const Token *checkExecutionPaths_(const Token *tok, std::list<ExecutionPa
tok2 = tok2->link(); tok2 = tok2->link();
// if "do { .. } while ( .." , goto end of while.. // 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(); tok2 = tok2->tokAt(2)->link();
// bail out all variables if the scope contains a "return" // bail out all variables if the scope contains a "return"
// bail out all variables used in this for/while/switch/do // 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); ExecutionPath::bailOut(checks);
if (tok->varId()) if(tok->varId())
ExecutionPath::bailOutVar(checks, tok->varId()); ExecutionPath::bailOutVar(checks, tok->varId());
} }
@ -127,37 +127,37 @@ static const Token *checkExecutionPaths_(const Token *tok, std::list<ExecutionPa
} }
// .. ) { ... } => bail out // .. ) { ... } => bail out
if (Token::simpleMatch(tok, ") {")) if(Token::simpleMatch(tok, ") {"))
{ {
ExecutionPath::bailOut(checks); ExecutionPath::bailOut(checks);
return 0; return 0;
} }
if (Token::Match(tok, "abort|exit (")) if(Token::Match(tok, "abort|exit ("))
{ {
ExecutionPath::bailOut(checks); ExecutionPath::bailOut(checks);
return 0; return 0;
} }
// don't parse into "struct type { .." // 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->next();
tok = tok ? tok->link() : 0; tok = tok ? tok->link() : 0;
} }
if (Token::Match(tok, "= {")) if(Token::Match(tok, "= {"))
{ {
// GCC struct initialization.. bail out // GCC struct initialization.. bail out
if (Token::Match(tok->tokAt(2), ". %var% =")) if(Token::Match(tok->tokAt(2), ". %var% ="))
{ {
ExecutionPath::bailOut(checks); ExecutionPath::bailOut(checks);
return 0; return 0;
} }
tok = tok->next()->link(); tok = tok->next()->link();
if (!tok) if(!tok)
{ {
ExecutionPath::bailOut(checks); ExecutionPath::bailOut(checks);
return 0; return 0;
@ -166,10 +166,10 @@ static const Token *checkExecutionPaths_(const Token *tok, std::list<ExecutionPa
} }
// ; { ... } // ; { ... }
if (Token::Match(tok->previous(), "[;{}] {")) if(Token::Match(tok->previous(), "[;{}] {"))
{ {
const Token *tokerr = checkExecutionPaths_(tok->next(), checks); const Token *tokerr = checkExecutionPaths_(tok->next(), checks);
if (tokerr) if(tokerr)
{ {
ExecutionPath::bailOut(checks); ExecutionPath::bailOut(checks);
return tokerr; return tokerr;
@ -178,16 +178,16 @@ static const Token *checkExecutionPaths_(const Token *tok, std::list<ExecutionPa
continue; continue;
} }
if (tok->str() == "if") if(tok->str() == "if")
{ {
std::list<ExecutionPath *> newchecks; std::list<ExecutionPath *> newchecks;
while (tok->str() == "if") while(tok->str() == "if")
{ {
// goto "(" // goto "("
tok = tok->next(); tok = tok->next();
// parse condition // 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(checks);
ExecutionPath::bailOut(newchecks); ExecutionPath::bailOut(newchecks);
@ -200,7 +200,7 @@ static const Token *checkExecutionPaths_(const Token *tok, std::list<ExecutionPa
// goto "{" // goto "{"
tok = tok ? tok->next() : 0; tok = tok ? tok->next() : 0;
if (!Token::simpleMatch(tok, "{")) if(!Token::simpleMatch(tok, "{"))
{ {
ExecutionPath::bailOut(checks); ExecutionPath::bailOut(checks);
ExecutionPath::bailOut(newchecks); ExecutionPath::bailOut(newchecks);
@ -211,16 +211,16 @@ static const Token *checkExecutionPaths_(const Token *tok, std::list<ExecutionPa
{ {
std::list<ExecutionPath *> c; std::list<ExecutionPath *> c;
std::list<ExecutionPath *>::iterator it; std::list<ExecutionPath *>::iterator it;
for (it = checks.begin(); it != checks.end(); ++it) for(it = checks.begin(); it != checks.end(); ++it)
c.push_back((*it)->copy()); c.push_back((*it)->copy());
const Token *tokerr = checkExecutionPaths_(tok->next(), c); const Token *tokerr = checkExecutionPaths_(tok->next(), c);
if (tokerr) if(tokerr)
{ {
ExecutionPath::bailOut(c); ExecutionPath::bailOut(c);
ExecutionPath::bailOut(newchecks); ExecutionPath::bailOut(newchecks);
return tokerr; return tokerr;
} }
while (!c.empty()) while(!c.empty())
{ {
newchecks.push_back(c.back()); newchecks.push_back(c.back());
c.pop_back(); c.pop_back();
@ -231,24 +231,24 @@ static const Token *checkExecutionPaths_(const Token *tok, std::list<ExecutionPa
tok = tok->link(); tok = tok->link();
// there is no else => break out // there is no else => break out
if (Token::Match(tok, "} !!else")) if(Token::Match(tok, "} !!else"))
break; break;
// parse next "if".. // parse next "if"..
tok = tok->tokAt(2); tok = tok->tokAt(2);
if (tok->str() == "if") if(tok->str() == "if")
continue; continue;
// there is no "if".. // there is no "if"..
const Token *tokerr = checkExecutionPaths_(tok->next(), checks); const Token *tokerr = checkExecutionPaths_(tok->next(), checks);
if (tokerr) if(tokerr)
{ {
ExecutionPath::bailOut(newchecks); ExecutionPath::bailOut(newchecks);
return tokerr; return tokerr;
} }
tok = tok->link(); tok = tok->link();
if (!tok) if(!tok)
{ {
ExecutionPath::bailOut(newchecks); ExecutionPath::bailOut(newchecks);
return 0; return 0;
@ -256,7 +256,7 @@ static const Token *checkExecutionPaths_(const Token *tok, std::list<ExecutionPa
} }
std::list<ExecutionPath *>::iterator it; std::list<ExecutionPath *>::iterator it;
for (it = newchecks.begin(); it != newchecks.end(); ++it) for(it = newchecks.begin(); it != newchecks.end(); ++it)
checks.push_back(*it); checks.push_back(*it);
} }
@ -264,14 +264,14 @@ static const Token *checkExecutionPaths_(const Token *tok, std::list<ExecutionPa
{ {
bool foundError = false; bool foundError = false;
tok = check->parse(*tok, foundError, checks); tok = check->parse(*tok, foundError, checks);
if (checks.empty()) if(checks.empty())
return 0; return 0;
else if (foundError) else if(foundError)
return tok; return tok;
} }
// return/throw ends all execution paths // return/throw ends all execution paths
if (tok->str() == "return" || tok->str() == "throw") if(tok->str() == "return" || tok->str() == "throw")
{ {
ExecutionPath::bailOut(checks); ExecutionPath::bailOut(checks);
} }
@ -281,17 +281,17 @@ static const Token *checkExecutionPaths_(const Token *tok, std::list<ExecutionPa
void checkExecutionPaths(const Token *tok, ExecutionPath *c) void checkExecutionPaths(const Token *tok, ExecutionPath *c)
{ {
for (; tok; tok = tok->next()) for(; tok; tok = tok->next())
{ {
if (tok->str() != ")") if(tok->str() != ")")
continue; continue;
// Start of implementation.. // Start of implementation..
if (Token::Match(tok, ") const| {")) if(Token::Match(tok, ") const| {"))
{ {
// goto the "{" // goto the "{"
tok = tok->next(); tok = tok->next();
if (tok->str() == "const") if(tok->str() == "const")
tok = tok->next(); tok = tok->next();
std::list<ExecutionPath *> checks; std::list<ExecutionPath *> checks;
@ -300,7 +300,7 @@ void checkExecutionPaths(const Token *tok, ExecutionPath *c)
c->end(checks, tok->link()); c->end(checks, tok->link());
while (!checks.empty()) while(!checks.empty())
{ {
delete checks.back(); delete checks.back();
checks.pop_back(); checks.pop_back();

View File

@ -57,7 +57,7 @@ public:
**/ **/
static void bailOut(std::list<ExecutionPath *> &checks) static void bailOut(std::list<ExecutionPath *> &checks)
{ {
while (!checks.empty()) while(!checks.empty())
{ {
delete checks.back(); delete checks.back();
checks.pop_back(); checks.pop_back();
@ -71,13 +71,13 @@ public:
**/ **/
static void bailOutVar(std::list<ExecutionPath *> &checks, const unsigned int varid) static void bailOutVar(std::list<ExecutionPath *> &checks, const unsigned int varid)
{ {
if (varid == 0) if(varid == 0)
return; return;
std::list<ExecutionPath *>::iterator it = checks.begin(); std::list<ExecutionPath *>::iterator it = checks.begin();
while (it != checks.end()) while(it != checks.end())
{ {
if ((*it)->varId == varid) if((*it)->varId == varid)
{ {
delete *it; delete *it;
checks.erase(it++); checks.erase(it++);

View File

@ -36,7 +36,7 @@ static FileLister *fileLister;
FileLister * getFileLister() FileLister * getFileLister()
{ {
if (fileLister == NULL) if(fileLister == NULL)
{ {
#if defined(_WIN32) #if defined(_WIN32)
fileLister = new FileListerWin32; fileLister = new FileListerWin32;
@ -52,11 +52,11 @@ std::string FileLister::simplifyPath(const char *originalPath)
{ {
std::string subPath = ""; std::string subPath = "";
std::vector<std::string> pathParts; std::vector<std::string> 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); pathParts.push_back(subPath);
subPath = ""; subPath = "";
@ -68,12 +68,12 @@ std::string FileLister::simplifyPath(const char *originalPath)
subPath.append(1, *originalPath); subPath.append(1, *originalPath);
} }
if (subPath.length() > 0) if(subPath.length() > 0)
pathParts.push_back(subPath); pathParts.push_back(subPath);
for (std::vector<std::string>::size_type i = 0; i < pathParts.size(); ++i) for(std::vector<std::string>::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 + 1);
pathParts.erase(pathParts.begin() + i); pathParts.erase(pathParts.begin() + i);
@ -81,12 +81,12 @@ std::string FileLister::simplifyPath(const char *originalPath)
pathParts.erase(pathParts.begin() + i - 2); pathParts.erase(pathParts.begin() + i - 2);
i = 0; i = 0;
} }
else if (i > 0 && pathParts[i] == ".") else if(i > 0 && pathParts[i] == ".")
{ {
pathParts.erase(pathParts.begin() + i); pathParts.erase(pathParts.begin() + i);
i = 0; 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); pathParts.erase(pathParts.begin() + i - 1);
i = 0; i = 0;
@ -94,7 +94,7 @@ std::string FileLister::simplifyPath(const char *originalPath)
} }
std::ostringstream oss; std::ostringstream oss;
for (std::vector<std::string>::size_type i = 0; i < pathParts.size(); ++i) for(std::vector<std::string>::size_type i = 0; i < pathParts.size(); ++i)
{ {
oss << pathParts[i]; oss << pathParts[i];
} }
@ -112,13 +112,13 @@ static int tolowerWrapper(int c)
bool FileLister::acceptFile(const std::string &filename) bool FileLister::acceptFile(const std::string &filename)
{ {
std::string::size_type dotLocation = filename.find_last_of('.'); std::string::size_type dotLocation = filename.find_last_of('.');
if (dotLocation == std::string::npos) if(dotLocation == std::string::npos)
return false; return false;
std::string extension = filename.substr(dotLocation); std::string extension = filename.substr(dotLocation);
std::transform(extension.begin(), extension.end(), extension.begin(), tolowerWrapper); std::transform(extension.begin(), extension.end(), extension.begin(), tolowerWrapper);
if (extension == ".cpp" || if(extension == ".cpp" ||
extension == ".cxx" || extension == ".cxx" ||
extension == ".cc" || extension == ".cc" ||
extension == ".c" || extension == ".c" ||

View File

@ -41,26 +41,26 @@ void FileListerUnix::recursiveAddFiles(std::vector<std::string> &filenames, cons
{ {
std::ostringstream oss; std::ostringstream oss;
oss << path; oss << path;
if (path.length() > 0 && path[path.length()-1] == '/') if(path.length() > 0 && path[path.length()-1] == '/')
oss << "*"; oss << "*";
glob_t glob_results; glob_t glob_results;
glob(oss.str().c_str(), GLOB_MARK, 0, &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]; std::string filename = glob_results.gl_pathv[i];
if (filename == "." || filename == ".." || filename.length() == 0) if(filename == "." || filename == ".." || filename.length() == 0)
continue; continue;
if (filename[filename.length()-1] != '/') if(filename[filename.length()-1] != '/')
{ {
// File // File
// If recursive is not used, accept all files given by user // 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); filenames.push_back(filename);
} }
else if (recursive) else if(recursive)
{ {
// Directory // Directory
getFileLister()->recursiveAddFiles(filenames, filename, recursive); getFileLister()->recursiveAddFiles(filenames, filename, recursive);

View File

@ -107,10 +107,10 @@ void FileListerWin32::recursiveAddFiles(std::vector<std::string> &filenames, con
oss << cleanedPath; oss << cleanedPath;
if (MyIsDirectory(cleanedPath.c_str())) if(MyIsDirectory(cleanedPath.c_str()))
{ {
char c = cleanedPath[ cleanedPath.size()-1 ]; char c = cleanedPath[ cleanedPath.size()-1 ];
switch (c) switch(c)
{ {
case '\\': case '\\':
oss << '*'; oss << '*';
@ -128,7 +128,7 @@ void FileListerWin32::recursiveAddFiles(std::vector<std::string> &filenames, con
{ {
std::string::size_type pos; std::string::size_type pos;
pos = cleanedPath.find_last_of('\\'); pos = cleanedPath.find_last_of('\\');
if (std::string::npos != pos) if(std::string::npos != pos)
{ {
bdir << cleanedPath.substr(0, pos + 1); bdir << cleanedPath.substr(0, pos + 1);
} }
@ -136,12 +136,12 @@ void FileListerWin32::recursiveAddFiles(std::vector<std::string> &filenames, con
WIN32_FIND_DATA ffd; WIN32_FIND_DATA ffd;
HANDLE hFind = MyFindFirstFile(oss.str(), &ffd); HANDLE hFind = MyFindFirstFile(oss.str(), &ffd);
if (INVALID_HANDLE_VALUE == hFind) if(INVALID_HANDLE_VALUE == hFind)
return; return;
do do
{ {
if (ffd.cFileName[0] == '.' || ffd.cFileName[0] == '\0') if(ffd.cFileName[0] == '.' || ffd.cFileName[0] == '\0')
continue; continue;
#if defined(UNICODE) #if defined(UNICODE)
@ -154,15 +154,15 @@ void FileListerWin32::recursiveAddFiles(std::vector<std::string> &filenames, con
std::ostringstream fname; std::ostringstream fname;
fname << bdir.str().c_str() << ansiFfd; fname << bdir.str().c_str() << ansiFfd;
if ((ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) if((ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
{ {
// File // File
// If recursive is not used, accept all files given by user // 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()); filenames.push_back(fname.str());
} }
else if (recursive) else if(recursive)
{ {
// Directory // Directory
getFileLister()->recursiveAddFiles(filenames, fname.str().c_str(), recursive); getFileLister()->recursiveAddFiles(filenames, fname.str().c_str(), recursive);
@ -171,9 +171,9 @@ void FileListerWin32::recursiveAddFiles(std::vector<std::string> &filenames, con
delete [] ansiFfd; delete [] ansiFfd;
#endif // defined(UNICODE) #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); FindClose(hFind);
hFind = INVALID_HANDLE_VALUE; hFind = INVALID_HANDLE_VALUE;

View File

@ -32,13 +32,13 @@
long MathLib::toLongNumber(const std::string &str) long MathLib::toLongNumber(const std::string &str)
{ {
if (str.compare(0, 2, "0x") == 0 if(str.compare(0, 2, "0x") == 0
|| str.compare(0, 3, "+0x") == 0 || str.compare(0, 3, "+0x") == 0
|| str.compare(0, 3, "-0x") == 0) || str.compare(0, 3, "-0x") == 0)
{ {
return std::strtoul(str.c_str(), '\0', 16); return std::strtoul(str.c_str(), '\0', 16);
} }
if (str.compare(0, 1, "0") == 0 if(str.compare(0, 1, "0") == 0
|| str.compare(0, 2, "+0") == 0 || str.compare(0, 2, "+0") == 0
|| str.compare(0, 2, "-0") == 0) || str.compare(0, 2, "-0") == 0)
{ {
@ -51,7 +51,7 @@ long MathLib::toLongNumber(const std::string &str)
double MathLib::toDoubleNumber(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); return std::strtoul(str.c_str(), '\0', 16);
} }
@ -67,7 +67,7 @@ std::string MathLib::toString(T d)
std::ostringstream result; std::ostringstream result;
result << d; result << d;
std::string strResult(result.str()); std::string strResult(result.str());
if (strResult == "-0" if(strResult == "-0"
|| strResult == "+0" || strResult == "+0"
|| strResult == "-0." || strResult == "-0."
|| strResult == "+0.") || strResult == "+0.")
@ -78,10 +78,10 @@ std::string MathLib::toString(T d)
bool MathLib::isFloat(const std::string &s) bool MathLib::isFloat(const std::string &s)
{ {
// every number that contains a . is a float // every number that contains a . is a float
if (s.find("." , 0) != std::string::npos) if(s.find("." , 0) != std::string::npos)
return true; return true;
// scientific notation // scientific notation
else if (s.find("E-", 0) != std::string::npos else if(s.find("E-", 0) != std::string::npos
|| s.find("e-", 0) != std::string::npos) || s.find("e-", 0) != std::string::npos)
return true; return true;
@ -93,9 +93,9 @@ bool MathLib::isNegative(const std::string &s)
// remember position // remember position
unsigned long n = 0; unsigned long n = 0;
// eat up whitespace // eat up whitespace
while (std::isspace(s[n])) ++n; while(std::isspace(s[n])) ++n;
// every negative number has a negative sign // every negative number has a negative sign
if (s[n] == '-') if(s[n] == '-')
return true; return true;
return false; return false;
@ -106,9 +106,9 @@ bool MathLib::isInt(const std::string & s)
// perform prechecks: // perform prechecks:
// ------------------ // ------------------
// first check, if a point is found, it is an floating point value // 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 // 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,... // prechecking has nothing found,...
@ -127,70 +127,70 @@ bool MathLib::isInt(const std::string & s)
// remember position // remember position
unsigned long n = 0; unsigned long n = 0;
// eat up whitespace // eat up whitespace
while (std::isspace(s[n])) ++n; while(std::isspace(s[n])) ++n;
// determine type // determine type
if (s.find("E", 0) != std::string::npos) if(s.find("E", 0) != std::string::npos)
{ {
Mode = eScientific; Mode = eScientific;
} }
else if (s.find("0x", n, 2) != std::string::npos) else if(s.find("0x", n, 2) != std::string::npos)
{ {
Mode = eHex; 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; Mode = eOctal;
} }
// check sign // check sign
if (s[n] == '-' || s[n] == '+') ++n; if(s[n] == '-' || s[n] == '+') ++n;
// check scientific notation // check scientific notation
if (Mode == eScientific) if(Mode == eScientific)
{ {
// check digits // check digits
while (std::isdigit(s[n])) ++n; while(std::isdigit(s[n])) ++n;
// check scientific notation // check scientific notation
if (std::tolower(s[n]) == 'e') if(std::tolower(s[n]) == 'e')
{ {
++n; ++n;
// check positive exponent // check positive exponent
if (s[n] == '+') ++n; if(s[n] == '+') ++n;
// floating pointer number e.g. 124E-2 // floating pointer number e.g. 124E-2
if (s[n] == '-') return false; if(s[n] == '-') return false;
// check digits of the exponent // check digits of the exponent
while (std::isdigit(s[n])) ++n; while(std::isdigit(s[n])) ++n;
} }
} }
// check hex notation // check hex notation
else if (Mode == eHex) else if(Mode == eHex)
{ {
++n; // 0 ++n; // 0
++n; // x ++n; // x
while (std::isxdigit(s[n])) while(std::isxdigit(s[n]))
++n; ++n;
} }
// check octal notation // check octal notation
else if (Mode == eOctal) else if(Mode == eOctal)
{ {
while (isOctalDigit(s[n])) while(isOctalDigit(s[n]))
++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 // 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 // eat up whitespace
while (std::isspace(s[n])) while(std::isspace(s[n]))
++n; ++n;
// if everything goes good, we are at the end of the string and no digits/character // 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 // is here --> return true, but if something was found eg. 12E+12AA return false
if (s[n]) if(s[n])
return false; return false;
return true; 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) 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<long>(toLongNumber(first) + toLongNumber(second)); return toString<long>(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) 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<long>(toLongNumber(first) - toLongNumber(second)); return toString<long>(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) 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<long>(toLongNumber(first) / toLongNumber(second)); return toString<long>(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) 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<long>(toLongNumber(first) * toLongNumber(second)); return toString<long>(toLongNumber(first) * toLongNumber(second));
} }
@ -236,7 +236,7 @@ std::string MathLib::calculate(const std::string &first, const std::string &seco
{ {
std::string result("0"); std::string result("0");
switch (action) switch(action)
{ {
case '+': case '+':
result = MathLib::add(first, second); 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) 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 true;
return false; return false;

File diff suppressed because it is too large Load Diff

48
lib/settings.cpp Executable file → Normal file
View File

@ -49,10 +49,10 @@ Settings::~Settings()
void Settings::autoDealloc(std::istream &istr) void Settings::autoDealloc(std::istream &istr)
{ {
std::string line; std::string line;
while (getline(istr, line)) while(getline(istr, line))
{ {
// Check if line has a valid classname.. // Check if line has a valid classname..
if (line.empty()) if(line.empty())
continue; continue;
// Add classname to list // Add classname to list
@ -63,19 +63,19 @@ void Settings::autoDealloc(std::istream &istr)
bool Settings::Suppressions::parseFile(std::istream &istr) bool Settings::Suppressions::parseFile(std::istream &istr)
{ {
std::string line; std::string line;
while (getline(istr, line)) while(getline(istr, line))
{ {
// Skip empty lines // Skip empty lines
if (line.empty()) if(line.empty())
continue; continue;
std::istringstream lineStream(line); std::istringstream lineStream(line);
std::string id; std::string id;
std::string file; std::string file;
unsigned int lineNumber = 0; 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; 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) 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; return false;
// Check are all errors of this type filtered out // 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; return true;
if (_suppressions[errorId].find(file) == _suppressions[errorId].end()) if(_suppressions[errorId].find(file) == _suppressions[errorId].end())
return false; return false;
// Check should all errors in this file be filtered out // 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; 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 false;
return true; return true;
@ -119,19 +119,19 @@ bool Settings::Suppressions::isSuppressed(const std::string &errorId, const std:
void Settings::addEnabled(const std::string &str) void Settings::addEnabled(const std::string &str)
{ {
// Enable parameters may be comma separated... // 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 prevPos = 0;
std::string::size_type pos = 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"); throw std::runtime_error("cppcheck: --enable parameter is empty");
addEnabled(str.substr(prevPos, pos - prevPos)); addEnabled(str.substr(prevPos, pos - prevPos));
++pos; ++pos;
prevPos = pos; prevPos = pos;
} }
if (prevPos >= str.length()) if(prevPos >= str.length())
throw std::runtime_error("cppcheck: --enable parameter is empty"); throw std::runtime_error("cppcheck: --enable parameter is empty");
addEnabled(str.substr(prevPos)); addEnabled(str.substr(prevPos));
return; return;
@ -139,11 +139,11 @@ void Settings::addEnabled(const std::string &str)
bool handled = false; bool handled = false;
if (str == "all") if(str == "all")
handled = _checkCodingStyle = _showAll = true; handled = _checkCodingStyle = _showAll = true;
else if (str == "style") else if(str == "style")
handled = _checkCodingStyle = true; handled = _checkCodingStyle = true;
else if (str == "possibleError") else if(str == "possibleError")
handled = _showAll = true; handled = _showAll = true;
std::set<std::string> id; std::set<std::string> id;
@ -151,19 +151,19 @@ void Settings::addEnabled(const std::string &str)
id.insert("exceptRealloc"); id.insert("exceptRealloc");
id.insert("unusedFunctions"); id.insert("unusedFunctions");
if (str == "all") if(str == "all")
{ {
std::set<std::string>::const_iterator it; std::set<std::string>::const_iterator it;
for (it = id.begin(); it != id.end(); ++it) for(it = id.begin(); it != id.end(); ++it)
_enabled[*it] = true; _enabled[*it] = true;
} }
else if (id.find(str) != id.end()) else if(id.find(str) != id.end())
{ {
_enabled[str] = true; _enabled[str] = true;
} }
else if (!handled) else if(!handled)
{ {
if (str.empty()) if(str.empty())
throw std::runtime_error("cppcheck: --enable parameter is empty"); throw std::runtime_error("cppcheck: --enable parameter is empty");
else else
throw std::runtime_error("cppcheck: there is no --enable parameter with the name '" + str + "'"); 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"; _append = "\n";
std::ifstream fin(filename.c_str()); std::ifstream fin(filename.c_str());
std::string line; std::string line;
while (std::getline(fin, line)) while(std::getline(fin, line))
{ {
_append += line + "\n"; _append += line + "\n";
} }

View File

@ -55,14 +55,14 @@ void Token::str(const std::string &s)
_isName = bool(_str[0] == '_' || std::isalpha(_str[0])); _isName = bool(_str[0] == '_' || std::isalpha(_str[0]));
if (std::isdigit(_str[0])) if(std::isdigit(_str[0]))
_isNumber = true; _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; _isNumber = true;
else else
_isNumber = false; _isNumber = false;
if (_str == "true" || _str == "false") if(_str == "true" || _str == "false")
_isBoolean = true; _isBoolean = true;
else else
_isBoolean = false; _isBoolean = false;
@ -89,15 +89,15 @@ void Token::deleteNext()
Token *n = _next; Token *n = _next;
_next = n->next(); _next = n->next();
delete n; delete n;
if (_next) if(_next)
_next->previous(this); _next->previous(this);
else if (tokensBack) else if(tokensBack)
*tokensBack = this; *tokensBack = this;
} }
void Token::deleteThis() void Token::deleteThis()
{ {
if (_next) if(_next)
{ {
_str = _next->_str; _str = _next->_str;
_isName = _next->_isName; _isName = _next->_isName;
@ -107,12 +107,12 @@ void Token::deleteThis()
_fileIndex = _next->_fileIndex; _fileIndex = _next->_fileIndex;
_linenr = _next->_linenr; _linenr = _next->_linenr;
_link = _next->_link; _link = _next->_link;
if (_link) if(_link)
_link->link(this); _link->link(this);
deleteNext(); deleteNext();
} }
else if (_previous) else if(_previous)
{ {
// This should never be used for tokens // This should never be used for tokens
// at the end of the list // at the end of the list
@ -129,25 +129,25 @@ void Token::deleteThis()
void Token::replace(Token *replaceThis, Token *start, Token *end) void Token::replace(Token *replaceThis, Token *start, Token *end)
{ {
// Fix the whole in the old location of start and end // Fix the whole in the old location of start and end
if (start->previous()) if(start->previous())
start->previous()->next(end->next()); start->previous()->next(end->next());
if (end->next()) if(end->next())
end->next()->previous(start->previous()); end->next()->previous(start->previous());
// Move start and end to their new location // Move start and end to their new location
if (replaceThis->previous()) if(replaceThis->previous())
replaceThis->previous()->next(start); replaceThis->previous()->next(start);
if (replaceThis->next()) if(replaceThis->next())
replaceThis->next()->previous(end); replaceThis->next()->previous(end);
start->previous(replaceThis->previous()); start->previous(replaceThis->previous());
end->next(replaceThis->next()); 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 = end->next();
*(end->tokensBack) = end; *(end->tokensBack) = end;
} }
@ -160,9 +160,9 @@ const Token *Token::tokAt(int index) const
{ {
const Token *tok = this; const Token *tok = this;
int num = std::abs(index); int num = std::abs(index);
while (num > 0 && tok) while(num > 0 && tok)
{ {
if (index > 0) if(index > 0)
tok = tok->next(); tok = tok->next();
else else
tok = tok->previous(); tok = tok->previous();
@ -175,9 +175,9 @@ Token *Token::tokAt(int index)
{ {
Token *tok = this; Token *tok = this;
int num = std::abs(index); int num = std::abs(index);
while (num > 0 && tok) while(num > 0 && tok)
{ {
if (index > 0) if(index > 0)
tok = tok->next(); tok = tok->next();
else else
tok = tok->previous(); tok = tok->previous();
@ -197,21 +197,21 @@ int Token::multiCompare(const char *haystack, const char *needle)
bool emptyStringFound = false; bool emptyStringFound = false;
bool noMatch = false; bool noMatch = false;
const char *needlePointer = needle; 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 // We didn't have a match at this round
noMatch = false; noMatch = false;
} }
else if (*needlePointer == 0) else if(*needlePointer == 0)
{ {
// If needle and haystack are both at the end, we have a match. // If needle and haystack are both at the end, we have a match.
return 1; return 1;
} }
else if (needlePointer == needle) else if(needlePointer == needle)
{ {
// If needlePointer was not increased at all, we had a empty // If needlePointer was not increased at all, we had a empty
// string in the haystack // string in the haystack
@ -222,12 +222,12 @@ int Token::multiCompare(const char *haystack, const char *needle)
continue; continue;
} }
if (noMatch) if(noMatch)
continue; continue;
// If haystack and needle don't share the same character, // If haystack and needle don't share the same character,
// find next '|' character. // find next '|' character.
if (*needlePointer != *haystack) if(*needlePointer != *haystack)
{ {
noMatch = true; noMatch = true;
continue; 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. // If both needle and haystack are at the end, then we have a match.
return 1; return 1;
} }
else if (needlePointer == needle) else if(needlePointer == needle)
{ {
// Last string in haystack was empty string e.g. "one|two|" // Last string in haystack was empty string e.g. "one|two|"
return 0; 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 empty string was found earlier from the haystack
if (emptyStringFound) if(emptyStringFound)
return 0; return 0;
return -1; return -1;
@ -265,21 +265,21 @@ bool Token::simpleMatch(const Token *tok, const char pattern[])
current = pattern; current = pattern;
next = strchr(pattern, ' '); next = strchr(pattern, ' ');
if (!next) if(!next)
next = pattern + strlen(pattern); next = pattern + strlen(pattern);
while (*current) while(*current)
{ {
size_t length = static_cast<size_t>(next - current); size_t length = static_cast<size_t>(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; return false;
current = next; current = next;
if (*next) if(*next)
{ {
next = strchr(++current, ' '); next = strchr(++current, ' ');
if (!next) if(!next)
next = current + strlen(current); next = current + strlen(current);
} }
tok = tok->next(); 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) int Token::firstWordEquals(const char *str, const char *word)
{ {
for (;;) for(;;)
{ {
if (*str == ' ' && *word == 0) if(*str == ' ' && *word == 0)
return 0; return 0;
else if (*str != *word) else if(*str != *word)
return 1; return 1;
else if (*str == 0) else if(*str == 0)
break; break;
++str; ++str;
@ -308,12 +308,12 @@ int Token::firstWordEquals(const char *str, const char *word)
const char *Token::chrInFirstWord(const char *str, char c) const char *Token::chrInFirstWord(const char *str, char c)
{ {
for (;;) for(;;)
{ {
if (*str == ' ' || *str == 0) if(*str == ' ' || *str == 0)
return 0; return 0;
if (*str == c) if(*str == c)
return str; return str;
++str; ++str;
@ -323,9 +323,9 @@ const char *Token::chrInFirstWord(const char *str, char c)
int Token::firstWordLen(const char *str) int Token::firstWordLen(const char *str)
{ {
int len = 0; int len = 0;
for (;;) for(;;)
{ {
if (*str == ' ' || *str == 0) if(*str == ' ' || *str == 0)
break; break;
++len; ++len;
@ -340,35 +340,35 @@ bool Token::Match(const Token *tok, const char pattern[], unsigned int varid)
const char *p = pattern; const char *p = pattern;
bool firstpattern = true; bool firstpattern = true;
bool first = true; bool first = true;
while (*p) while(*p)
{ {
if (!first) if(!first)
{ {
while (*p && *p != ' ') while(*p && *p != ' ')
++p; ++p;
} }
first = false; first = false;
// Skip spaces in pattern.. // Skip spaces in pattern..
while (*p == ' ') while(*p == ' ')
++p; ++p;
// No token => Success! // No token => Success!
if (*p == 0) if(*p == 0)
return true; return true;
if (!tok) if(!tok)
{ {
// If we have no tokens, pattern "!!else" should return true // 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; continue;
else else
return false; return false;
} }
// If we are in the first token, we skip all initial !! patterns // 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; continue;
firstpattern = false; 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 // Compare the first character of the string for optimization reasons
// before doing more detailed checks. // before doing more detailed checks.
bool patternIdentified = false; bool patternIdentified = false;
if (p[0] == '%') if(p[0] == '%')
{ {
// TODO: %var% should match only for // TODO: %var% should match only for
// variables that have varId != 0, but that needs a lot of // variables that have varId != 0, but that needs a lot of
// work, before that change can be made. // work, before that change can be made.
// Any symbolname.. // Any symbolname..
if (firstWordEquals(p, "%var%") == 0) if(firstWordEquals(p, "%var%") == 0)
{ {
if (!tok->isName()) if(!tok->isName())
return false; return false;
patternIdentified = true; patternIdentified = true;
} }
// Any symbolname.. // Any symbolname..
if (firstWordEquals(p, "%name%") == 0) if(firstWordEquals(p, "%name%") == 0)
{ {
if (!tok->isName()) if(!tok->isName())
return false; return false;
patternIdentified = true; patternIdentified = true;
} }
// Type.. // Type..
if (firstWordEquals(p, "%type%") == 0) if(firstWordEquals(p, "%type%") == 0)
{ {
if (!tok->isName()) if(!tok->isName())
return false; return false;
if (tok->varId() != 0) if(tok->varId() != 0)
return false; return false;
if (tok->str() == "delete") if(tok->str() == "delete")
return false; return false;
patternIdentified = true; patternIdentified = true;
} }
// Accept any token // Accept any token
else if (firstWordEquals(p, "%any%") == 0) else if(firstWordEquals(p, "%any%") == 0)
{ {
patternIdentified = true; 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 std::cerr << "\n###### If you see this, there is a bug ######" << std::endl
<< "Token::Match(\"" << pattern << "\", 0)" << std::endl; << "Token::Match(\"" << pattern << "\", 0)" << std::endl;
} }
if (tok->varId() != varid) if(tok->varId() != varid)
return false; return false;
patternIdentified = true; patternIdentified = true;
} }
else if (firstWordEquals(p, "%num%") == 0) else if(firstWordEquals(p, "%num%") == 0)
{ {
if (!tok->isNumber()) if(!tok->isNumber())
return false; return false;
patternIdentified = true; patternIdentified = true;
} }
else if (firstWordEquals(p, "%bool%") == 0) else if(firstWordEquals(p, "%bool%") == 0)
{ {
if (!tok->isBoolean()) if(!tok->isBoolean())
return false; return false;
patternIdentified = true; patternIdentified = true;
} }
else if (firstWordEquals(p, "%str%") == 0) else if(firstWordEquals(p, "%str%") == 0)
{ {
if (tok->_str[0] != '\"') if(tok->_str[0] != '\"')
return false; return false;
patternIdentified = true; patternIdentified = true;
} }
} }
if (patternIdentified) if(patternIdentified)
{ {
// Pattern was identified already above. // Pattern was identified already above.
} }
// [.. => search for a one-character token.. // [.. => 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; const char *temp = p + 1;
bool chrFound = false; bool chrFound = false;
int count = 0; int count = 0;
while (*temp && *temp != ' ') while(*temp && *temp != ' ')
{ {
if (*temp == ']') if(*temp == ']')
{ {
++count; ++count;
++temp; ++temp;
continue; continue;
} }
if (*temp == tok->_str[0]) if(*temp == tok->_str[0])
{ {
chrFound = true; chrFound = true;
break; break;
@ -488,26 +488,26 @@ bool Token::Match(const Token *tok, const char pattern[], unsigned int varid)
++temp; ++temp;
} }
if (count > 1) if(count > 1)
{ {
if (tok->_str[0] == ']') if(tok->_str[0] == ']')
chrFound = true; chrFound = true;
} }
if (!chrFound) if(!chrFound)
return false; return false;
} }
// Parse multi options, such as void|int|char (accept token which is one of these 3) // 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()); int res = multiCompare(p, tok->_str.c_str());
if (res == 0) if(res == 0)
{ {
// Empty alternative matches, use the same token on next round // Empty alternative matches, use the same token on next round
continue; continue;
} }
else if (res == -1) else if(res == -1)
{ {
// No match // No match
return false; 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 // 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; return false;
} }
else if (firstWordEquals(p, tok->_str.c_str()) != 0) else if(firstWordEquals(p, tok->_str.c_str()) != 0)
return false; return false;
tok = tok->next(); tok = tok->next();
@ -539,14 +539,14 @@ size_t Token::getStrLength(const Token *tok)
const std::string strValue(tok->strValue()); const std::string strValue(tok->strValue());
const char *str = strValue.c_str(); const char *str = strValue.c_str();
while (*str) while(*str)
{ {
if (*str == '\\') if(*str == '\\')
{ {
++str; ++str;
// string ends at '\0' // string ends at '\0'
if (*str == '0') if(*str == '0')
break; break;
} }
@ -561,7 +561,7 @@ bool Token::isStandardType() const
{ {
bool ret = false; bool ret = false;
const char *type[] = {"bool", "char", "short", "int", "long", "float", "double", "size_t", "__int64", 0}; 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]); ret |= (_str == type[i]);
return ret; return ret;
} }
@ -570,7 +570,7 @@ bool Token::isIntegerType() const
{ {
bool ret = false; bool ret = false;
const char *type[] = {"char", "short", "int", "long", "size_t", "__int64", 0}; 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]); ret |= (_str == type[i]);
return ret; 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) 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 tok;
} }
return 0; return 0;
@ -610,12 +610,12 @@ void Token::insertToken(const std::string &str)
newToken->str(str); newToken->str(str);
newToken->_linenr = _linenr; newToken->_linenr = _linenr;
newToken->_fileIndex = _fileIndex; newToken->_fileIndex = _fileIndex;
if (this->next()) if(this->next())
{ {
newToken->next(this->next()); newToken->next(this->next());
newToken->next()->previous(newToken); newToken->next()->previous(newToken);
} }
else if (tokensBack) else if(tokensBack)
{ {
*tokensBack = newToken; *tokensBack = newToken;
} }
@ -626,10 +626,10 @@ void Token::insertToken(const std::string &str)
void Token::eraseTokens(Token *begin, const Token *end) void Token::eraseTokens(Token *begin, const Token *end)
{ {
if (! begin) if(! begin)
return; return;
while (begin->next() && begin->next() != end) while(begin->next() && begin->next() != end)
{ {
begin->deleteNext(); 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<std::string> &fileNames) const std::string Token::stringifyList(bool varid, const char *title, const std::vector<std::string> &fileNames) const
{ {
std::ostringstream ret; std::ostringstream ret;
if (title) if(title)
ret << "\n### " << title << " ###\n"; ret << "\n### " << title << " ###\n";
unsigned int linenr = 0; unsigned int linenr = 0;
int fileIndex = -1; int fileIndex = -1;
std::map<unsigned int, unsigned int> lineNumbers; std::map<unsigned int, unsigned int> lineNumbers;
for (const Token *tok = this; tok; tok = tok->next()) for(const Token *tok = this; tok; tok = tok->next())
{ {
bool fileChange = false; bool fileChange = false;
if (static_cast<int>(tok->_fileIndex) != fileIndex) if(static_cast<int>(tok->_fileIndex) != fileIndex)
{ {
if (fileIndex != -1) if(fileIndex != -1)
{ {
lineNumbers[fileIndex] = tok->_fileIndex; lineNumbers[fileIndex] = tok->_fileIndex;
} }
fileIndex = static_cast<int>(tok->_fileIndex); fileIndex = static_cast<int>(tok->_fileIndex);
ret << "\n\n##file "; ret << "\n\n##file ";
if (fileNames.size() > static_cast<unsigned int>(fileIndex)) if(fileNames.size() > static_cast<unsigned int>(fileIndex))
ret << fileNames.at(fileIndex); ret << fileNames.at(fileIndex);
else else
ret << fileIndex; ret << fileIndex;
@ -691,9 +691,9 @@ std::string Token::stringifyList(bool varid, const char *title, const std::vecto
fileChange = true; fileChange = true;
} }
if (linenr != tok->linenr() || fileChange) if(linenr != tok->linenr() || fileChange)
{ {
while (linenr < tok->linenr()) while(linenr < tok->linenr())
{ {
++linenr; ++linenr;
ret << "\n" << linenr << ":"; ret << "\n" << linenr << ":";
@ -702,7 +702,7 @@ std::string Token::stringifyList(bool varid, const char *title, const std::vecto
} }
ret << " " << tok->str(); ret << " " << tok->str();
if (varid && tok->varId() > 0) if(varid && tok->varId() > 0)
ret << "@" << tok->varId(); ret << "@" << tok->varId();
} }
ret << "\n"; ret << "\n";

File diff suppressed because it is too large Load Diff

View File

@ -763,7 +763,7 @@ private:
void array_index_24() void array_index_24()
{ {
// ticket #1492 and #1539 // 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" check("void f(char n) {\n"
" int a[n];\n" // n <= CHAR_MAX " 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" 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()); "[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" check("void f(int n) {\n"
" int a[n];\n" // n <= INT_MAX " int a[n];\n" // n <= INT_MAX

View File

@ -407,7 +407,7 @@ private:
// stringify.. // stringify..
std::ostringstream ret; std::ostringstream ret;
for (const Token *tok = tokens; tok; tok = tok->next()) for(const Token *tok = tokens; tok; tok = tok->next())
ret << tok->str(); ret << tok->str();
Tokenizer::deleteTokens(tokens); Tokenizer::deleteTokens(tokens);
@ -572,7 +572,7 @@ private:
, "sync_file_range", "telldir", "typeid", "while", "write", "writev" , "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])); ASSERT_EQUALS(true, CheckMemoryLeakInFunction::test_white_list(call_func_white_list[i]));
} }
@ -586,15 +586,15 @@ private:
Token *tokens = const_cast<Token *>(tokenizer.tokens()); Token *tokens = const_cast<Token *>(tokenizer.tokens());
// replace "if ( ! var )" => "if(!var)" // 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)); Token::eraseTokens(tok, tok->tokAt(4));
tok->str(tok->str() + "(var)"); 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)); Token::eraseTokens(tok, tok->tokAt(5));
tok->str(tok->str() + "(!var)"); tok->str(tok->str() + "(!var)");
@ -608,7 +608,7 @@ private:
checkMemoryLeak.simplifycode(tokens, all); checkMemoryLeak.simplifycode(tokens, all);
std::ostringstream ret; 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(); ret << (tok->previous() ? " " : "") << tok->str();
return ret.str(); return ret.str();
@ -720,20 +720,20 @@ private:
tokenizer.tokenize(istr, "test.cpp"); tokenizer.tokenize(istr, "test.cpp");
// replace "if ( ! var )" => "if(!var)" // replace "if ( ! var )" => "if(!var)"
for (Token *tok = const_cast<Token *>(tokenizer.tokens()); tok; tok = tok->next()) for(Token *tok = const_cast<Token *>(tokenizer.tokens()); tok; tok = tok->next())
{ {
if (tok->str() == "if_var") if(tok->str() == "if_var")
{ {
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)); Token::eraseTokens(tok, tok->tokAt(4));
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(5)); Token::eraseTokens(tok, tok->tokAt(5));
tok->str("if(!var)"); tok->str("if(!var)");

View File

@ -1837,7 +1837,7 @@ private:
CheckOther::analyseFunctions(tokenizer.tokens(), f); CheckOther::analyseFunctions(tokenizer.tokens(), f);
std::string ret; std::string ret;
for (std::set<std::string>::const_iterator it = f.begin(); it != f.end(); ++it) for(std::set<std::string>::const_iterator it = f.begin(); it != f.end(); ++it)
ret += *it + " "; ret += *it + " ";
return ret; return ret;
} }

View File

@ -241,23 +241,23 @@ private:
std::istringstream istr(code); std::istringstream istr(code);
tokenizer.tokenize(istr, "test.cpp"); tokenizer.tokenize(istr, "test.cpp");
if (simplify) if(simplify)
tokenizer.simplifyTokenList(); tokenizer.simplifyTokenList();
tokenizer.validate(); tokenizer.validate();
std::string ret; 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 += " ";
if (!simplify) if(!simplify)
{ {
if (tok->isUnsigned()) if(tok->isUnsigned())
ret += "unsigned "; ret += "unsigned ";
else if (tok->isSigned()) else if(tok->isSigned())
ret += "signed "; ret += "signed ";
} }
if (tok->isLong()) if(tok->isLong())
ret += "long "; ret += "long ";
ret += tok->str(); ret += tok->str();
} }
@ -701,9 +701,9 @@ private:
tokenizer.simplifyTokenList(); tokenizer.simplifyTokenList();
std::ostringstream ostr; 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 << " ";
} }
@ -850,7 +850,7 @@ private:
const char code[] = "; const char str[] = \"1\"; sizeof(str);"; const char code[] = "; const char str[] = \"1\"; sizeof(str);";
std::ostringstream expected; 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)); ASSERT_EQUALS(expected.str(), sizeof_(code));
} }
@ -949,7 +949,7 @@ private:
{ {
std::ostringstream expected; 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 ) }")); ASSERT_EQUALS(expected.str(), tok("void f ( ) { char str [ 100 ] = \"100\" ; sizeof ( str ) }"));
} }
} }
@ -1092,7 +1092,7 @@ private:
void sizeof18() void sizeof18()
{ {
if (sizeof(short int) == 2) if(sizeof(short int) == 2)
{ {
{ {
const char code[] = "void f()\n" 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" const char code[] = "void f()\n"
@ -1843,7 +1843,7 @@ private:
tokenizer.simplifyIfAssign(); tokenizer.simplifyIfAssign();
std::ostringstream ostr; 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(); ostr << (tok->previous() ? " " : "") << tok->str();
return ostr.str(); return ostr.str();
@ -1887,7 +1887,7 @@ private:
tokenizer.simplifyIfNot(); tokenizer.simplifyIfNot();
std::ostringstream ostr; 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(); ostr << (tok->previous() ? " " : "") << tok->str();
return ostr.str(); return ostr.str();
@ -1920,7 +1920,7 @@ private:
tokenizer.simplifyLogicalOperators(); tokenizer.simplifyLogicalOperators();
std::ostringstream ostr; 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(); ostr << (tok->previous() ? " " : "") << tok->str();
return ostr.str(); return ostr.str();
@ -2482,9 +2482,9 @@ private:
tokenizer.simplifyTypedef(); tokenizer.simplifyTypedef();
std::string ret; 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 += " ";
ret += tok->str(); ret += tok->str();
} }

View File

@ -597,11 +597,12 @@ private:
{ {
const int STL_CONTAINER_LIST = 9; const int STL_CONTAINER_LIST = 9;
const std::string stlCont[STL_CONTAINER_LIST] = const std::string stlCont[STL_CONTAINER_LIST] =
{"deque", "list", "set", "multiset", "map", {
"deque", "list", "set", "multiset", "map",
"multimap", "hash_map", "hash_multimap", "hash_set" "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" check("void f()\n"
"{\n" "{\n"

View File

@ -75,7 +75,7 @@ TestFixture::TestFixture(const std::string &_name) : classname(_name)
bool TestFixture::runTest(const char testname[]) bool TestFixture::runTest(const char testname[])
{ {
if (testToRun.empty() || testToRun == testname) if(testToRun.empty() || testToRun == testname)
{ {
++countTests; ++countTests;
std::cout << classname << "::" << testname << "\n"; std::cout << classname << "::" << testname << "\n";
@ -88,14 +88,14 @@ static std::string writestr(const std::string &str)
{ {
std::ostringstream ostr; std::ostringstream ostr;
ostr << "\""; ostr << "\"";
for (unsigned int i = 0; i < str.length(); ++i) for(unsigned int i = 0; i < str.length(); ++i)
{ {
char ch = str[i]; char ch = str[i];
if (ch == '\n') if(ch == '\n')
ostr << "\\n"; ostr << "\\n";
else if (ch == '\t') else if(ch == '\t')
ostr << "\\t"; ostr << "\\t";
else if (ch == '\"') else if(ch == '\"')
ostr << "\\\""; ostr << "\\\"";
else else
ostr << std::string(1, ch); ostr << std::string(1, ch);
@ -106,7 +106,7 @@ static std::string writestr(const std::string &str)
void TestFixture::assertEquals(const char *filename, int linenr, const std::string &expected, const std::string &actual) void TestFixture::assertEquals(const char *filename, int linenr, const std::string &expected, const std::string &actual)
{ {
if (expected != actual) if(expected != actual)
{ {
++fails_counter; ++fails_counter;
@ -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) 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"); assertEquals(filename, linenr, "TODO assertion", "The assertion succeeded");
else else
++todos_counter; ++todos_counter;
@ -156,7 +156,7 @@ void TestFixture::printTests()
{ {
const std::list<TestFixture *> &tests = TestRegistry::theInstance().tests(); const std::list<TestFixture *> &tests = TestRegistry::theInstance().tests();
for (std::list<TestFixture *>::const_iterator it = tests.begin(); it != tests.end(); ++it) for(std::list<TestFixture *>::const_iterator it = tests.begin(); it != tests.end(); ++it)
{ {
std::cout << (*it)->classname << std::endl; std::cout << (*it)->classname << std::endl;
} }
@ -172,7 +172,7 @@ size_t TestFixture::runTests(const char cmd[])
{ {
std::string classname(cmd ? cmd : ""); std::string classname(cmd ? cmd : "");
std::string testname(""); std::string testname("");
if (classname.find("::") != std::string::npos) if(classname.find("::") != std::string::npos)
{ {
testname = classname.substr(classname.find("::") + 2); testname = classname.substr(classname.find("::") + 2);
classname.erase(classname.find("::")); classname.erase(classname.find("::"));
@ -183,9 +183,9 @@ size_t TestFixture::runTests(const char cmd[])
const std::list<TestFixture *> &tests = TestRegistry::theInstance().tests(); const std::list<TestFixture *> &tests = TestRegistry::theInstance().tests();
for (std::list<TestFixture *>::const_iterator it = tests.begin(); it != tests.end(); ++it) for(std::list<TestFixture *>::const_iterator it = tests.begin(); it != tests.end(); ++it)
{ {
if (classname.empty() || (*it)->classname == classname) if(classname.empty() || (*it)->classname == classname)
{ {
(*it)->run(testname); (*it)->run(testname);
} }

View File

@ -51,13 +51,13 @@ private:
ASSERT_EQUALS(token->str(), "1"); ASSERT_EQUALS(token->str(), "1");
ASSERT_EQUALS(token->next()->str(), "2"); ASSERT_EQUALS(token->next()->str(), "2");
ASSERT_EQUALS(token->tokAt(2)->str(), "3"); ASSERT_EQUALS(token->tokAt(2)->str(), "3");
if (last->next()) if(last->next())
ASSERT_EQUALS("Null was expected", ""); ASSERT_EQUALS("Null was expected", "");
ASSERT_EQUALS(last->str(), "3"); ASSERT_EQUALS(last->str(), "3");
ASSERT_EQUALS(last->previous()->str(), "2"); ASSERT_EQUALS(last->previous()->str(), "2");
ASSERT_EQUALS(last->tokAt(-2)->str(), "1"); ASSERT_EQUALS(last->tokAt(-2)->str(), "1");
if (token->previous()) if(token->previous())
ASSERT_EQUALS("Null was expected", ""); ASSERT_EQUALS("Null was expected", "");
Tokenizer::deleteTokens(token); Tokenizer::deleteTokens(token);

View File

@ -210,9 +210,9 @@ private:
bool cmptok(const char *expected[], const Token *actual) bool cmptok(const char *expected[], const Token *actual)
{ {
unsigned int i = 0; 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 false;
} }
return (expected[i] == NULL && actual == NULL); return (expected[i] == NULL && actual == NULL);
@ -225,29 +225,29 @@ private:
Tokenizer tokenizer; Tokenizer tokenizer;
std::istringstream istr(code); std::istringstream istr(code);
tokenizer.tokenize(istr, "test.cpp"); tokenizer.tokenize(istr, "test.cpp");
if (simplify) if(simplify)
tokenizer.simplifyTokenList(); tokenizer.simplifyTokenList();
std::ostringstream ostr; 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 "; ostr << "unsigned ";
else if (tok->isSigned()) else if(tok->isSigned())
ostr << "signed "; ostr << "signed ";
} }
if (tok->isLong()) if(tok->isLong())
ostr << "long "; ostr << "long ";
ostr << tok->str(); ostr << tok->str();
// Append newlines // 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"; ostr << "\n";
} }
else else
@ -352,7 +352,7 @@ private:
tokenizer.simplifyCasts(); tokenizer.simplifyCasts();
std::ostringstream ostr; 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(); ostr << " " << tok->str();
ASSERT_EQUALS(" int * f ( int * ) ;", ostr.str()); ASSERT_EQUALS(" int * f ( int * ) ;", ostr.str());
} }
@ -370,7 +370,7 @@ private:
tokenizer.simplifyCasts(); tokenizer.simplifyCasts();
std::ostringstream ostr; 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(); ostr << " " << tok->str();
ASSERT_EQUALS(" t = ( & p ) ;", ostr.str()); ASSERT_EQUALS(" t = ( & p ) ;", ostr.str());
} }
@ -449,7 +449,7 @@ private:
tokenizer.fillFunctionList(); tokenizer.fillFunctionList();
ASSERT_EQUALS(3, static_cast<unsigned int>(tokenizer._functionList.size())); ASSERT_EQUALS(3, static_cast<unsigned int>(tokenizer._functionList.size()));
if (tokenizer._functionList.size() == 3) if(tokenizer._functionList.size() == 3)
{ {
ASSERT_EQUALS("a", tokenizer._functionList[0]->str()); ASSERT_EQUALS("a", tokenizer._functionList[0]->str());
ASSERT_EQUALS("b", tokenizer._functionList[1]->str()); ASSERT_EQUALS("b", tokenizer._functionList[1]->str());
@ -712,9 +712,9 @@ private:
tokenizer.simplifyKnownVariables(); tokenizer.simplifyKnownVariables();
std::ostringstream ostr; 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 << " ";
ostr << tok->str(); ostr << tok->str();
} }
@ -1171,7 +1171,7 @@ private:
std::istringstream istr(code); std::istringstream istr(code);
tokenizer.tokenize(istr, "test.cpp"); tokenizer.tokenize(istr, "test.cpp");
if (simplify) if(simplify)
tokenizer.simplifyTokenList(); tokenizer.simplifyTokenList();
// result.. // result..
@ -1919,7 +1919,7 @@ private:
std::istringstream istr(code); std::istringstream istr(code);
tokenizer.tokenize(istr, "a"); 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; std::ostringstream ostr;
ostr << char('a' + tok->fileIndex()) << tok->linenr(); ostr << char('a' + tok->fileIndex()) << tok->linenr();
@ -1951,7 +1951,7 @@ private:
std::istringstream istr(code); std::istringstream istr(code);
tokenizer.tokenize(istr, "a"); 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; std::ostringstream ostr;
ostr << char('a' + tok->fileIndex()) << tok->linenr(); ostr << char('a' + tok->fileIndex()) << tok->linenr();
@ -1990,7 +1990,7 @@ private:
// Stringify the tokens.. // Stringify the tokens..
std::ostringstream ostr; 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() << " "; ostr << tok->str() << " ";
ASSERT_EQUALS("TEST ( var , val ) var ## _ ## val = val ", ostr.str()); ASSERT_EQUALS("TEST ( var , val ) var ## _ ## val = val ", ostr.str());
@ -2007,7 +2007,7 @@ private:
// Stringify the tokens.. // Stringify the tokens..
std::ostringstream ostr; 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() << " "; ostr << tok->str() << " ";
ASSERT_EQUALS("DBG ( fmt , args . . . ) printf ( fmt , ## args ) ", ostr.str()); ASSERT_EQUALS("DBG ( fmt , args . . . ) printf ( fmt , ## args ) ", ostr.str());
@ -2060,7 +2060,7 @@ private:
tokenizer.simplifyTokenList(); tokenizer.simplifyTokenList();
std::ostringstream ostr; 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(); ostr << " " << tok->str();
ASSERT_EQUALS(" void foo ( ) { free ( p ) ; }", ostr.str()); ASSERT_EQUALS(" void foo ( ) { free ( p ) ; }", ostr.str());
} }
@ -2081,7 +2081,7 @@ private:
tokenizer.simplifyTokenList(); tokenizer.simplifyTokenList();
std::ostringstream ostr; 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(); ostr << " " << tok->str();
ASSERT_EQUALS(" void foo ( ) { if ( ! s ) { return ; } }", ostr.str()); ASSERT_EQUALS(" void foo ( ) { if ( ! s ) { return ; } }", ostr.str());
} }
@ -2102,7 +2102,7 @@ private:
tokenizer.simplifyTokenList(); tokenizer.simplifyTokenList();
std::ostringstream ostr; 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(); ostr << " " << tok->str();
ASSERT_EQUALS(" void foo ( ) { { } }", ostr.str()); ASSERT_EQUALS(" void foo ( ) { { } }", ostr.str());
} }
@ -2121,7 +2121,7 @@ private:
tokenizer.simplifyTokenList(); tokenizer.simplifyTokenList();
std::ostringstream ostr; 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(); ostr << " " << tok->str();
ASSERT_EQUALS(" void foo ( ) { { } }", ostr.str()); ASSERT_EQUALS(" void foo ( ) { { } }", ostr.str());
} }
@ -2140,7 +2140,7 @@ private:
tokenizer.simplifyTokenList(); tokenizer.simplifyTokenList();
std::ostringstream ostr; 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(); ostr << " " << tok->str();
ASSERT_EQUALS(" void foo ( ) { if ( g ( 10 ) ) { } }", ostr.str()); ASSERT_EQUALS(" void foo ( ) { if ( g ( 10 ) ) { } }", ostr.str());
} }
@ -2162,7 +2162,7 @@ private:
tokenizer.simplifyTokenList(); tokenizer.simplifyTokenList();
std::ostringstream ostr; 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(); ostr << " " << tok->str();
ASSERT_EQUALS(" void foo ( ) { free ( p ) ; }", ostr.str()); ASSERT_EQUALS(" void foo ( ) { free ( p ) ; }", ostr.str());
} }
@ -2184,7 +2184,7 @@ private:
tokenizer.simplifyTokenList(); tokenizer.simplifyTokenList();
std::ostringstream ostr; 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(); ostr << " " << tok->str();
ASSERT_EQUALS(" void foo ( ) { delete p ; }", ostr.str()); ASSERT_EQUALS(" void foo ( ) { delete p ; }", ostr.str());
} }
@ -2204,7 +2204,7 @@ private:
tokenizer.simplifyTokenList(); tokenizer.simplifyTokenList();
std::ostringstream ostr; 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(); ostr << " " << tok->str();
ASSERT_EQUALS(" void foo ( ) { delete [ ] p ; }", ostr.str()); ASSERT_EQUALS(" void foo ( ) { delete [ ] p ; }", ostr.str());
} }
@ -2223,7 +2223,7 @@ private:
tokenizer.simplifyTokenList(); tokenizer.simplifyTokenList();
std::ostringstream ostr; 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(); ostr << " " << tok->str();
ASSERT_EQUALS(" ( ! abc . a )", ostr.str()); ASSERT_EQUALS(" ( ! abc . a )", ostr.str());
} }
@ -2245,7 +2245,7 @@ private:
tokenizer.tokenize(istr, "test.cpp"); tokenizer.tokenize(istr, "test.cpp");
std::ostringstream ostr; 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(); 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()); 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(); tokenizer.simplifyTokenList();
std::ostringstream ostr; 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(); ostr << " " << tok->str();
ASSERT_EQUALS(" void f ( ) { const char * a ; a = { \"hello more world\" } ; }", ostr.str()); ASSERT_EQUALS(" void f ( ) { const char * a ; a = { \"hello more world\" } ; }", ostr.str());
} }
@ -2297,7 +2297,7 @@ private:
tokenizer.simplifyTokenList(); tokenizer.simplifyTokenList();
std::ostringstream ostr; 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(); ostr << " " << tok->str();
ASSERT_EQUALS(" void f ( ) { const int a = 45 ; { ; ; } } void g ( ) { ; ; }", ostr.str()); ASSERT_EQUALS(" void f ( ) { const int a = 45 ; { ; ; } } void g ( ) { ; ; }", ostr.str());
} }
@ -2321,7 +2321,7 @@ private:
tokenizer.simplifyTokenList(); tokenizer.simplifyTokenList();
std::ostringstream ostr; 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(); ostr << " " << tok->str();
std::ostringstream oss; std::ostringstream oss;
@ -2758,7 +2758,7 @@ private:
tokenizer.tokenize(istr, "test.cpp"); tokenizer.tokenize(istr, "test.cpp");
tokenizer.updateClassList(); tokenizer.updateClassList();
ASSERT_EQUALS(2, tokenizer._classInfoList["A"]._memberFunctions.size()); 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]._name);
ASSERT_EQUALS(std::string("f"), tokenizer._classInfoList["A"]._memberFunctions[0]._declaration->str()); ASSERT_EQUALS(std::string("f"), tokenizer._classInfoList["A"]._memberFunctions[0]._declaration->str());
@ -2930,13 +2930,13 @@ private:
tokenizer.tokenize(istr, "test.cpp"); tokenizer.tokenize(istr, "test.cpp");
tokenizer.simplifyFunctionPointers(); tokenizer.simplifyFunctionPointers();
std::ostringstream ostr; 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"; ostr << " unsigned";
else if (tok->isSigned()) else if(tok->isSigned())
ostr << " signed"; ostr << " signed";
if (tok->isLong()) if(tok->isLong())
ostr << " long"; ostr << " long";
ostr << (tok->isName() ? " " : "") << tok->str(); ostr << (tok->isName() ? " " : "") << tok->str();
} }
@ -2982,9 +2982,9 @@ private:
tokenizer.tokenize(istr, "test.cpp"); tokenizer.tokenize(istr, "test.cpp");
std::ostringstream ostr; 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 << " ";
ostr << tok->str(); ostr << tok->str();
} }

View File

@ -347,7 +347,7 @@ private:
void localvarOp() void localvarOp()
{ {
const char op[] = "+-*/%&|^"; const char op[] = "+-*/%&|^";
for (const char *p = op; *p; ++p) for(const char *p = op; *p; ++p)
{ {
std::string code("int main()\n" std::string code("int main()\n"
"{\n" "{\n"

View File

@ -39,34 +39,34 @@ std::string objfile(std::string cppfile)
void getDeps(const std::string &filename, std::vector<std::string> &depfiles) void getDeps(const std::string &filename, std::vector<std::string> &depfiles)
{ {
// Is the dependency already included? // 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; return;
std::ifstream f(filename.c_str()); 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); getDeps("lib" + filename.substr(filename.find("/")), depfiles);
return; return;
} }
if (filename.find(".c") == std::string::npos) if(filename.find(".c") == std::string::npos)
depfiles.push_back(filename); depfiles.push_back(filename);
std::string path(filename); std::string path(filename);
if (path.find("/") != std::string::npos) if(path.find("/") != std::string::npos)
path.erase(1 + path.rfind("/")); path.erase(1 + path.rfind("/"));
std::string line; std::string line;
while (std::getline(f, line)) while(std::getline(f, line))
{ {
std::string::size_type pos1 = line.find("#include \""); std::string::size_type pos1 = line.find("#include \"");
if (pos1 == std::string::npos) if(pos1 == std::string::npos)
continue; continue;
pos1 += 10; pos1 += 10;
std::string::size_type pos2 = line.find("\"", pos1); std::string::size_type pos2 = line.find("\"", pos1);
std::string hfile(path + line.substr(pos1, pos2 - 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("/../")); hfile.erase(0, 4 + hfile.find("/../"));
getDeps(hfile, depfiles); getDeps(hfile, depfiles);
} }
@ -74,12 +74,12 @@ void getDeps(const std::string &filename, std::vector<std::string> &depfiles)
static void compilefiles(std::ostream &fout, const std::vector<std::string> &files) static void compilefiles(std::ostream &fout, const std::vector<std::string> &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]; fout << objfile(files[i]) << ": " << files[i];
std::vector<std::string> depfiles; std::vector<std::string> depfiles;
getDeps(files[i], 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 << " " << depfiles[dep];
fout << "\n\t$(CXX) $(CXXFLAGS) -Ilib -c -o " << objfile(files[i]) << " " << files[i] << "\n\n"; fout << "\n\t$(CXX) $(CXXFLAGS) -Ilib -c -o " << objfile(files[i]) << " " << files[i] << "\n\n";
} }
@ -89,9 +89,9 @@ static void getCppFiles(std::vector<std::string> &files, const std::string &path
{ {
getFileLister()->recursiveAddFiles(files, path, true); getFileLister()->recursiveAddFiles(files, path, true);
// only get *.cpp files.. // only get *.cpp files..
for (std::vector<std::string>::iterator it = files.begin(); it != files.end();) for(std::vector<std::string>::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); it = files.erase(it);
else else
++it; ++it;
@ -116,25 +116,25 @@ int main(int argc, char **argv)
// QMAKE - lib/lib.pri // QMAKE - lib/lib.pri
{ {
std::ofstream fout1("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 << "# no manual edits - this file is autogenerated by dmake\n\n";
fout1 << "HEADERS += $$PWD/check.h \\\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)); 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 continue; // shouldn't happen
fname.erase(fname.find(".cpp")); fname.erase(fname.find(".cpp"));
fout1 << std::string(11, ' ') << "$$PWD/" << fname << ".h"; fout1 << std::string(11, ' ') << "$$PWD/" << fname << ".h";
if (i < libfiles.size() - 1) if(i < libfiles.size() - 1)
fout1 << " \\\n"; fout1 << " \\\n";
} }
fout1 << "\n\nSOURCES += "; 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); fout1 << "$$PWD/" << libfiles[i].substr(4);
if (i < libfiles.size() - 1) if(i < libfiles.size() - 1)
fout1 << " \\\n" << std::string(11, ' '); fout1 << " \\\n" << std::string(11, ' ');
} }
fout1 << "\n"; fout1 << "\n";
@ -159,15 +159,15 @@ int main(int argc, char **argv)
fout << "\n###### Object Files\n\n"; fout << "\n###### Object Files\n\n";
fout << "LIBOBJ = " << objfile(libfiles[0]); 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 << " \\" << std::endl << std::string(14, ' ') << objfile(libfiles[i]);
fout << "\n\n"; fout << "\n\n";
fout << "CLIOBJ = " << objfile(clifiles[0]); 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 << " \\" << std::endl << std::string(14, ' ') << objfile(clifiles[i]);
fout << "\n\n"; fout << "\n\n";
fout << "TESTOBJ = " << objfile(testfiles[0]); 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 << " \\" << std::endl << std::string(14, ' ') << objfile(testfiles[i]);
fout << "\n\n"; fout << "\n\n";

View File

@ -15,7 +15,7 @@ static std::string str(unsigned int value)
int main(const int argc, const char * const * const argv) int main(const int argc, const char * const * const argv)
{ {
if (argc != 2) if(argc != 2)
{ {
std::cerr << "syntax: extracttests testfile" << std::endl; std::cerr << "syntax: extracttests testfile" << std::endl;
return 0; return 0;
@ -26,38 +26,38 @@ int main(const int argc, const char * const * const argv)
std::ifstream f(argv[1]); std::ifstream f(argv[1]);
std::string line; std::string line;
while (std::getline(f, line)) while(std::getline(f, line))
{ {
{ {
std::string::size_type pos = line.find_first_not_of(" "); 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); 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); testname = line.substr(5, line.size() - 7);
subcount = 0; subcount = 0;
continue; continue;
} }
if (line == "}") if(line == "}")
{ {
testname = ""; testname = "";
subcount = 0; subcount = 0;
continue; 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()); std::ofstream fout((testname + str(++subcount) + ext).c_str());
fout << "#include <string.h>" << std::endl; fout << "#include <string.h>" << std::endl;
fout << "#include <stdio.h>" << std::endl; fout << "#include <stdio.h>" << std::endl;
fout << "#include <stdlib.h>" << std::endl; fout << "#include <stdlib.h>" << std::endl;
if (testname == "nullpointer1") if(testname == "nullpointer1")
{ {
if (subcount < 6) if(subcount < 6)
{ {
fout << "class Token\n" fout << "class Token\n"
<< "{\n" << "{\n"
@ -80,7 +80,7 @@ int main(const int argc, const char * const * const argv)
} }
} }
if (testname == "nullpointer2") if(testname == "nullpointer2")
{ {
fout << "class Fred\n" fout << "class Fred\n"
<< "{\n" << "{\n"
@ -90,7 +90,7 @@ int main(const int argc, const char * const * const argv)
<< "};\n"; << "};\n";
} }
if (testname == "nullpointer3") if(testname == "nullpointer3")
{ {
fout << "struct DEF { };\n" fout << "struct DEF { };\n"
<< "struct ABC : public DEF\n" << "struct ABC : public DEF\n"
@ -101,7 +101,7 @@ int main(const int argc, const char * const * const argv)
<< "void bar(int); void f(struct ABC **);\n"; << "void bar(int); void f(struct ABC **);\n";
} }
if (testname == "nullpointer4") if(testname == "nullpointer4")
{ {
fout << "void bar(int);\n" fout << "void bar(int);\n"
<< "int** f(int **p = 0);\n" << "int** f(int **p = 0);\n"
@ -112,7 +112,7 @@ int main(const int argc, const char * const * const argv)
<< "};\n"; << "};\n";
} }
if (testname == "nullpointer5") if(testname == "nullpointer5")
{ {
fout << "struct A {\n" fout << "struct A {\n"
<< " char c() const;\n" << " char c() const;\n"
@ -120,7 +120,7 @@ int main(const int argc, const char * const * const argv)
<< "};\n"; << "};\n";
} }
if (testname == "nullpointer6") if(testname == "nullpointer6")
{ {
fout << "struct Foo {\n" fout << "struct Foo {\n"
<< " void abcd() const;\n" << " void abcd() const;\n"
@ -130,7 +130,7 @@ int main(const int argc, const char * const * const argv)
<< "extern int a;\n"; << "extern int a;\n";
} }
if (testname == "nullpointer7") if(testname == "nullpointer7")
{ {
fout << "struct wxLongLong {\n" fout << "struct wxLongLong {\n"
<< " wxLongLong(int) { }\n" << " wxLongLong(int) { }\n"
@ -141,21 +141,21 @@ int main(const int argc, const char * const * const argv)
do do
{ {
std::string::size_type pos = line.find("\""); std::string::size_type pos = line.find("\"");
if (pos == std::string::npos) if(pos == std::string::npos)
break; break;
line.erase(0, pos + 1); line.erase(0, pos + 1);
pos = line.rfind("\""); pos = line.rfind("\"");
if (pos == std::string::npos) if(pos == std::string::npos)
break; break;
const bool lastline(line.find(");", pos) != std::string::npos); const bool lastline(line.find(");", pos) != std::string::npos);
line.erase(pos); line.erase(pos);
pos = 0; pos = 0;
while ((pos = line.find("\\", pos)) != std::string::npos) while((pos = line.find("\\", pos)) != std::string::npos)
{ {
line.erase(pos, 1); line.erase(pos, 1);
if (line[pos] == 'n') if(line[pos] == 'n')
line.erase(pos, 1); line.erase(pos, 1);
else else
++pos; ++pos;
@ -163,10 +163,10 @@ int main(const int argc, const char * const * const argv)
fout << line << std::endl; fout << line << std::endl;
if (lastline) if(lastline)
break; break;
} }
while (std::getline(f, line)); while(std::getline(f, line));
fout << std::endl; fout << std::endl;
continue; continue;
} }