ID
int64 1
1.09k
| Language
stringclasses 1
value | Repository Name
stringclasses 8
values | File Name
stringlengths 3
35
| File Path in Repository
stringlengths 9
82
| File Path for Unit Test
stringclasses 5
values | Code
stringlengths 17
1.91M
| Unit Test - (Ground Truth)
stringclasses 5
values |
---|---|---|---|---|---|---|---|
701 | cpp | cppcheck | filelist.cpp | gui/filelist.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2023 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "filelist.h"
#include "pathmatch.h"
#include <algorithm>
#include <iterator>
#include <string>
#include <vector>
#include <QDir>
#include <Qt>
QStringList FileList::getDefaultFilters()
{
QStringList extensions;
extensions << "*.cpp" << "*.cxx" << "*.cc" << "*.c" << "*.c++" << "*.txx" << "*.tpp" << "*.ipp" << "*.ixx";
return extensions;
}
bool FileList::filterMatches(const QFileInfo &inf)
{
if (inf.isFile()) {
const QStringList filters = FileList::getDefaultFilters();
QString ext("*.");
ext += inf.suffix();
if (filters.contains(ext, Qt::CaseInsensitive))
return true;
}
return false;
}
void FileList::addFile(const QString &filepath)
{
QFileInfo inf(filepath);
if (filterMatches(inf))
mFileList << inf;
}
void FileList::addDirectory(const QString &directory, bool recursive)
{
QDir dir(directory);
dir.setSorting(QDir::Name);
const QStringList filters = FileList::getDefaultFilters();
const QStringList origNameFilters = dir.nameFilters();
dir.setNameFilters(filters);
if (!recursive) {
dir.setFilter(QDir::Files | QDir::NoDotAndDotDot);
QFileInfoList items = dir.entryInfoList();
mFileList += items;
} else {
dir.setFilter(QDir::Files | QDir::NoDotAndDotDot);
QFileInfoList items = dir.entryInfoList();
mFileList += items;
dir.setNameFilters(origNameFilters);
dir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot);
for (const QFileInfo& item : dir.entryInfoList()) {
const QString path = item.canonicalFilePath();
addDirectory(path, recursive);
}
}
}
void FileList::addPathList(const QStringList &paths)
{
for (const QString& path : paths) {
QFileInfo inf(path);
if (inf.isFile())
addFile(path);
else
addDirectory(path, true);
}
}
QStringList FileList::getFileList() const
{
if (mExcludedPaths.empty()) {
QStringList names;
for (const QFileInfo& item : mFileList) {
QString name = QDir::fromNativeSeparators(item.filePath());
names << name;
}
return names;
}
return applyExcludeList();
}
void FileList::addExcludeList(const QStringList &paths)
{
mExcludedPaths = paths;
}
static std::vector<std::string> toStdStringList(const QStringList &stringList)
{
std::vector<std::string> ret;
std::transform(stringList.cbegin(), stringList.cend(), std::back_inserter(ret), [](const QString& s) {
return s.toStdString();
});
return ret;
}
QStringList FileList::applyExcludeList() const
{
#ifdef _WIN32
const PathMatch pathMatch(toStdStringList(mExcludedPaths), true);
#else
const PathMatch pathMatch(toStdStringList(mExcludedPaths), false);
#endif
QStringList paths;
for (const QFileInfo& item : mFileList) {
if (pathMatch.match(QDir::fromNativeSeparators(item.filePath()).toStdString()))
continue;
QString canonical = QDir::fromNativeSeparators(item.canonicalFilePath());
if (!pathMatch.match(canonical.toStdString()))
paths << canonical;
}
return paths;
}
| null |
702 | cpp | cppcheck | threadhandler.h | gui/threadhandler.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef THREADHANDLER_H
#define THREADHANDLER_H
#include "suppressions.h"
#include "threadresult.h"
#include <set>
#include <string>
#include <QDateTime>
#include <QElapsedTimer>
#include <QList>
#include <QObject>
#include <QString>
#include <QStringList>
class ResultsView;
class CheckThread;
class QSettings;
class Settings;
class ImportProject;
class ErrorItem;
/// @addtogroup GUI
/// @{
/**
* @brief This class handles creating threadresult and starting threads
*
*/
class ThreadHandler : public QObject {
Q_OBJECT
public:
explicit ThreadHandler(QObject *parent = nullptr);
~ThreadHandler() override;
/**
* @brief Set the number of threads to use
* @param count The number of threads to use
*/
void setThreadCount(int count);
/**
* @brief Initialize the threads (connect all signals to resultsview's slots)
*
* @param view View to show error results
*/
void initialize(const ResultsView *view);
/**
* @brief Load settings
* @param settings QSettings to load settings from
*/
void loadSettings(const QSettings &settings);
/**
* @brief Save settings
* @param settings QSettings to save settings to
*/
void saveSettings(QSettings &settings) const;
void setAddonsAndTools(const QStringList &addonsAndTools) {
mAddonsAndTools = addonsAndTools;
}
void setSuppressions(const QList<SuppressionList::Suppression> &s) {
mSuppressions = s;
}
void setClangIncludePaths(const QStringList &s) {
mClangIncludePaths = s;
}
/**
* @brief Clear all files from cppcheck
*
*/
void clearFiles();
/**
* @brief Set files to check
*
* @param files files to check
*/
void setFiles(const QStringList &files);
/**
* @brief Set project to check
*
* @param prj project to check
*/
void setProject(const ImportProject &prj);
/**
* @brief Start the threads to check the files
*
* @param settings Settings for checking
*/
void check(const Settings &settings);
/**
* @brief Set files to check
*
* @param all true if all files, false if modified files
*/
void setCheckFiles(bool all);
/**
* @brief Set selected files to check
*
* @param files list of files to be checked
*/
void setCheckFiles(const QStringList& files);
/**
* @brief Is checking running?
*
* @return true if check is running, false otherwise.
*/
bool isChecking() const;
/**
* @brief Have we checked files already?
*
* @return true check has been previously run and recheck can be done
*/
bool hasPreviousFiles() const;
/**
* @brief Return count of files we checked last time.
*
* @return count of files that were checked last time.
*/
int getPreviousFilesCount() const;
/**
* @brief Return the time elapsed while scanning the previous time.
*
* @return the time elapsed in milliseconds.
*/
int getPreviousScanDuration() const;
/**
* @brief Get files that should be rechecked because they have been
* changed.
*/
QStringList getReCheckFiles(bool all) const;
/**
* @brief Get start time of last check
*
* @return start time of last check
*/
QDateTime getCheckStartTime() const;
/**
* @brief Set start time of check
*
* @param checkStartTime saved start time of the last check
*/
void setCheckStartTime(QDateTime checkStartTime);
signals:
/**
* @brief Signal that all threads are done
*
*/
void done();
// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) - caused by generated MOC code
void log(const QString &msg);
// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) - caused by generated MOC code
void debugError(const ErrorItem &item);
public slots:
/**
* @brief Slot to stop all threads
*
*/
void stop();
protected slots:
/**
* @brief Slot that a single thread is done
*
*/
void threadDone();
protected:
/**
* @brief List of files checked last time (used when rechecking)
*
*/
QStringList mLastFiles;
/** @brief date and time when current checking started */
QDateTime mCheckStartTime;
/**
* @brief when was the files checked the last time (used when rechecking)
*/
QDateTime mLastCheckTime;
/**
* @brief Timer used for measuring scan duration
*
*/
QElapsedTimer mTimer;
/**
* @brief The previous scan duration in milliseconds.
*
*/
int mScanDuration{};
/**
* @brief Function to delete all threads
*
*/
void removeThreads();
/**
* @brief Thread results are stored here
*
*/
ThreadResult mResults;
/**
* @brief List of threads currently in use
*
*/
QList<CheckThread *> mThreads;
/**
* @brief The amount of threads currently running
*
*/
int mRunningThreadCount{};
bool mAnalyseWholeProgram{};
std::string mCtuInfo;
QStringList mAddonsAndTools;
QList<SuppressionList::Suppression> mSuppressions;
QStringList mClangIncludePaths;
private:
/**
* @brief Check if a file needs to be rechecked. Recursively checks
* included headers. Used by GetReCheckFiles()
*/
bool needsReCheck(const QString &filename, std::set<QString> &modified, std::set<QString> &unmodified) const;
};
/// @}
#endif // THREADHANDLER_H
| null |
703 | cpp | cppcheck | fileviewdialog.cpp | gui/fileviewdialog.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2023 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "fileviewdialog.h"
#include <QByteArray>
#include <QDialogButtonBox>
#include <QFile>
#include <QIODevice>
#include <QMessageBox>
#include <QTextEdit>
#include "ui_fileview.h"
FileViewDialog::FileViewDialog(const QString &file,
const QString &title,
QWidget *parent)
: QDialog(parent)
, mUI(new Ui::Fileview)
{
mUI->setupUi(this);
setWindowTitle(title);
connect(mUI->mButtons, SIGNAL(accepted()), this, SLOT(accept()));
loadTextFile(file, mUI->mText);
}
FileViewDialog::~FileViewDialog()
{
delete mUI;
}
void FileViewDialog::loadTextFile(const QString &filename, QTextEdit *edit)
{
QFile file(filename);
if (!file.exists()) {
QString msg(tr("Could not find the file: %1"));
msg = msg.arg(filename);
QMessageBox msgbox(QMessageBox::Critical,
tr("Cppcheck"),
msg,
QMessageBox::Ok,
this);
msgbox.exec();
return;
}
file.open(QIODevice::ReadOnly | QIODevice::Text);
if (!file.isReadable()) {
QString msg(tr("Could not read the file: %1"));
msg = msg.arg(filename);
QMessageBox msgbox(QMessageBox::Critical,
tr("Cppcheck"),
msg,
QMessageBox::Ok,
this);
msgbox.exec();
return;
}
QByteArray filedata = file.readAll();
file.close();
edit->setPlainText(filedata);
}
| null |
704 | cpp | cppcheck | csvreport.cpp | gui/csvreport.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "csvreport.h"
#include "erroritem.h"
#include "report.h"
#include <QDir>
#include <QFile>
#include <QList>
#include <QtGlobal>
CsvReport::CsvReport(const QString &filename) :
Report(filename)
{}
bool CsvReport::create()
{
if (Report::create()) {
mTxtWriter.setDevice(Report::getFile());
return true;
}
return false;
}
void CsvReport::writeHeader()
{
// Added 5 columns to the header.
#if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0))
mTxtWriter << "File, Line, Severity, Id, Summary" << Qt::endl;
#else
mTxtWriter << "File, Line, Severity, Id, Summary" << endl;
#endif
}
void CsvReport::writeFooter()
{
// No footer for CSV report
}
void CsvReport::writeError(const ErrorItem &error)
{
/*
Error as CSV line
gui/test.cpp,23,error,Mismatching allocation and deallocation: k
*/
const QString file = QDir::toNativeSeparators(error.errorPath.back().file);
QString line = QString("%1,%2,").arg(file).arg(error.errorPath.back().line);
line += QString("%1,%2,%3").arg(GuiSeverity::toString(error.severity)).arg(error.errorId).arg(error.summary);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0))
mTxtWriter << line << Qt::endl;
#else
mTxtWriter << line << endl;
#endif
}
| null |
705 | cpp | cppcheck | newsuppressiondialog.cpp | gui/newsuppressiondialog.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "newsuppressiondialog.h"
#include "cppcheck.h"
#include "errorlogger.h"
#include "suppressions.h"
#include "ui_newsuppressiondialog.h"
#include <cstdint>
#include <string>
#include <QComboBox>
#include <QLineEdit>
#include <QString>
#include <QStringList>
class QWidget;
NewSuppressionDialog::NewSuppressionDialog(QWidget *parent) :
QDialog(parent),
mUI(new Ui::NewSuppressionDialog)
{
mUI->setupUi(this);
class QErrorLogger : public ErrorLogger {
public:
void reportOut(const std::string & /*outmsg*/, Color /*c*/) override {}
void reportErr(const ErrorMessage &msg) override {
errorIds << QString::fromStdString(msg.id);
}
QStringList errorIds;
};
QErrorLogger errorLogger;
CppCheck::getErrorMessages(errorLogger);
errorLogger.errorIds.sort();
mUI->mComboErrorId->addItems(errorLogger.errorIds);
mUI->mComboErrorId->setCurrentIndex(-1);
mUI->mComboErrorId->setCurrentText("");
}
NewSuppressionDialog::~NewSuppressionDialog()
{
delete mUI;
}
SuppressionList::Suppression NewSuppressionDialog::getSuppression() const
{
SuppressionList::Suppression ret;
ret.errorId = mUI->mComboErrorId->currentText().toStdString();
if (ret.errorId.empty())
ret.errorId = "*";
ret.fileName = mUI->mTextFileName->text().toStdString();
if (!mUI->mTextLineNumber->text().isEmpty())
ret.lineNumber = mUI->mTextLineNumber->text().toInt();
ret.symbolName = mUI->mTextSymbolName->text().toStdString();
return ret;
}
void NewSuppressionDialog::setSuppression(const SuppressionList::Suppression &suppression)
{
setWindowTitle(tr("Edit suppression"));
mUI->mComboErrorId->setCurrentText(QString::fromStdString(suppression.errorId));
mUI->mTextFileName->setText(QString::fromStdString(suppression.fileName));
mUI->mTextLineNumber->setText(suppression.lineNumber > 0 ? QString::number(suppression.lineNumber) : QString());
mUI->mTextSymbolName->setText(QString::fromStdString(suppression.symbolName));
}
| null |
706 | cpp | cppcheck | librarydialog.h | gui/librarydialog.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef LIBRARYDIALOG_H
#define LIBRARYDIALOG_H
#include "cppchecklibrarydata.h"
#include <QDialog>
#include <QObject>
#include <QString>
class QListWidgetItem;
class QWidget;
namespace Ui {
class LibraryDialog;
}
class LibraryDialog : public QDialog {
Q_OBJECT
public:
explicit LibraryDialog(QWidget *parent = nullptr);
LibraryDialog(const LibraryDialog &) = delete;
~LibraryDialog() override;
LibraryDialog &operator=(const LibraryDialog &) = delete;
private slots:
void openCfg();
void saveCfg();
void saveCfgAs();
void addFunction();
void changeFunction();
void editArg();
void editFunctionName(QListWidgetItem* /*item*/);
void filterFunctions(const QString& /*filter*/);
void selectFunction();
void sortFunctions(bool /*sort*/);
private:
Ui::LibraryDialog *mUi;
CppcheckLibraryData mData;
QString mFileName;
bool mIgnoreChanges{};
static QString getArgText(const CppcheckLibraryData::Function::Arg &arg);
CppcheckLibraryData::Function *currentFunction();
void updateArguments(const CppcheckLibraryData::Function &function);
};
#endif // LIBRARYDIALOG_H
| null |
707 | cpp | cppcheck | applicationlist.h | gui/applicationlist.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef APPLICATIONLIST_H
#define APPLICATIONLIST_H
#include "application.h"
#include <QList>
#include <QObject>
#include <QString>
/// @addtogroup GUI
/// @{
/**
* @brief List of applications user has specified to open errors with.
*/
class ApplicationList : public QObject {
Q_OBJECT
public:
explicit ApplicationList(QObject *parent = nullptr);
~ApplicationList() override;
/**
* @brief Load all applications
*
* @return true if loading succeeded, false if there is problem with
* application list. Most probably because of older version settings need
* to be upgraded.
*/
bool loadSettings();
/**
* @brief Save all applications
*/
void saveSettings() const;
/**
* @brief Get the amount of applications in the list
* @return The count of applications
*/
int getApplicationCount() const;
/**
* @brief Get specific application's name
*
* @param index Index of the application whose name to get
* @return Name of the application
*/
const Application& getApplication(int index) const;
Application& getApplication(int index);
/**
* @brief Return the default application.
* @return Index of the default application.
*/
int getDefaultApplication() const {
return mDefaultApplicationIndex;
}
/**
* @brief Add a new application
*
* @param app Application to add.
*/
void addApplication(const Application &app);
/**
* @brief Remove an application from the list
*
* @param index Index of the application to remove.
*/
void removeApplication(int index);
/**
* @brief Set application as default application.
* @param index Index of the application to make the default one
*/
void setDefault(int index);
/**
* @brief Remove all applications from this list and copy all applications from
* list given as a parameter.
* @param list Copying source
*/
void copy(const ApplicationList *list);
protected:
/**
* @brief Clear the list
*
*/
void clear();
#ifdef _WIN32
/**
* @brief Find editor used by default in Windows.
* Check if Notepad++ is installed and use it. If not, use Notepad.
*/
bool findDefaultWindowsEditor();
#endif
private:
bool checkAndAddApplication(const QString& appPath, const QString& name, const QString& parameters);
/**
* @brief List of applications
*
*/
QList<Application> mApplications;
/**
* @brief Index of the default application.
*
*/
int mDefaultApplicationIndex = -1;
};
/// @}
#endif // APPLICATIONLIST_H
| null |
708 | cpp | cppcheck | report.cpp | gui/report.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2023 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "report.h"
#include <utility>
#include <QIODevice>
Report::Report(QString filename) :
mFilename(std::move(filename))
{}
Report::~Report()
{
close();
}
bool Report::create()
{
bool succeed = false;
if (!mFile.isOpen()) {
mFile.setFileName(mFilename);
succeed = mFile.open(QIODevice::WriteOnly | QIODevice::Text);
}
return succeed;
}
bool Report::open()
{
bool succeed = false;
if (!mFile.isOpen()) {
mFile.setFileName(mFilename);
succeed = mFile.open(QIODevice::ReadOnly | QIODevice::Text);
}
return succeed;
}
void Report::close()
{
if (mFile.isOpen())
mFile.close();
}
QFile* Report::getFile()
{
return &mFile;
}
| null |
709 | cpp | cppcheck | settingsdialog.cpp | gui/settingsdialog.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "settingsdialog.h"
#include "application.h"
#include "applicationdialog.h"
#include "applicationlist.h"
#include "codeeditorstyle.h"
#include "codeeditstyledialog.h"
#include "common.h"
#include "translationhandler.h"
#include "ui_settings.h"
#include <QCheckBox>
#include <QDialogButtonBox>
#include <QDir>
#include <QFileDialog>
#include <QFileInfo>
#include <QGroupBox>
#include <QLabel>
#include <QLineEdit>
#include <QList>
#include <QListWidget>
#include <QListWidgetItem>
#include <QPushButton>
#include <QRadioButton>
#include <QSettings>
#include <QSize>
#include <QThread>
#include <QVariant>
#include <QWidget>
SettingsDialog::SettingsDialog(ApplicationList *list,
TranslationHandler *translator,
bool premium,
QWidget *parent) :
QDialog(parent),
mApplications(list),
mTempApplications(new ApplicationList(this)),
mTranslator(translator),
mUI(new Ui::Settings),
mPremium(premium)
{
mUI->setupUi(this);
mUI->mPythonPathWarning->setStyleSheet("color: red");
QSettings settings;
mTempApplications->copy(list);
mUI->mJobs->setText(settings.value(SETTINGS_CHECK_THREADS, 1).toString());
mUI->mForce->setCheckState(boolToCheckState(settings.value(SETTINGS_CHECK_FORCE, false).toBool()));
mUI->mShowFullPath->setCheckState(boolToCheckState(settings.value(SETTINGS_SHOW_FULL_PATH, false).toBool()));
mUI->mShowNoErrorsMessage->setCheckState(boolToCheckState(settings.value(SETTINGS_SHOW_NO_ERRORS, false).toBool()));
mUI->mShowDebugWarnings->setCheckState(boolToCheckState(settings.value(SETTINGS_SHOW_DEBUG_WARNINGS, false).toBool()));
mUI->mSaveAllErrors->setCheckState(boolToCheckState(settings.value(SETTINGS_SAVE_ALL_ERRORS, false).toBool()));
mUI->mSaveFullPath->setCheckState(boolToCheckState(settings.value(SETTINGS_SAVE_FULL_PATH, false).toBool()));
mUI->mInlineSuppressions->setCheckState(boolToCheckState(settings.value(SETTINGS_INLINE_SUPPRESSIONS, false).toBool()));
mUI->mEnableInconclusive->setCheckState(boolToCheckState(settings.value(SETTINGS_INCONCLUSIVE_ERRORS, false).toBool()));
mUI->mShowStatistics->setCheckState(boolToCheckState(settings.value(SETTINGS_SHOW_STATISTICS, false).toBool()));
mUI->mShowErrorId->setCheckState(boolToCheckState(settings.value(SETTINGS_SHOW_ERROR_ID, true).toBool()));
mUI->mCheckForUpdates->setCheckState(boolToCheckState(settings.value(SETTINGS_CHECK_FOR_UPDATES, false).toBool()));
mUI->mEditPythonPath->setText(settings.value(SETTINGS_PYTHON_PATH, QString()).toString());
validateEditPythonPath();
if (premium)
mUI->mGroupBoxMisra->setVisible(false);
mUI->mEditMisraFile->setText(settings.value(SETTINGS_MISRA_FILE, QString()).toString());
#ifdef Q_OS_WIN
//mUI->mTabClang->setVisible(true);
mUI->mEditClangPath->setText(settings.value(SETTINGS_CLANG_PATH, QString()).toString());
mUI->mEditVsIncludePaths->setText(settings.value(SETTINGS_VS_INCLUDE_PATHS, QString()).toString());
connect(mUI->mBtnBrowseClangPath, &QPushButton::released, this, &SettingsDialog::browseClangPath);
#else
mUI->mTabClang->setVisible(false);
#endif
mCurrentStyle = new CodeEditorStyle(CodeEditorStyle::loadSettings(&settings));
manageStyleControls();
connect(mUI->mEditPythonPath, SIGNAL(textEdited(QString)),
this, SLOT(validateEditPythonPath()));
connect(mUI->mButtons, &QDialogButtonBox::accepted, this, &SettingsDialog::ok);
connect(mUI->mButtons, &QDialogButtonBox::rejected, this, &SettingsDialog::reject);
connect(mUI->mBtnAddApplication, SIGNAL(clicked()),
this, SLOT(addApplication()));
connect(mUI->mBtnRemoveApplication, SIGNAL(clicked()),
this, SLOT(removeApplication()));
connect(mUI->mBtnEditApplication, SIGNAL(clicked()),
this, SLOT(editApplication()));
connect(mUI->mBtnDefaultApplication, SIGNAL(clicked()),
this, SLOT(defaultApplication()));
connect(mUI->mListWidget, SIGNAL(itemDoubleClicked(QListWidgetItem*)),
this, SLOT(editApplication()));
connect(mUI->mBtnBrowsePythonPath, &QPushButton::clicked, this, &SettingsDialog::browsePythonPath);
connect(mUI->mBtnBrowseMisraFile, &QPushButton::clicked, this, &SettingsDialog::browseMisraFile);
connect(mUI->mBtnEditTheme, SIGNAL(clicked()), this, SLOT(editCodeEditorStyle()));
connect(mUI->mThemeSystem, SIGNAL(released()), this, SLOT(setCodeEditorStyleDefault()));
connect(mUI->mThemeDark, SIGNAL(released()), this, SLOT(setCodeEditorStyleDefault()));
connect(mUI->mThemeLight, SIGNAL(released()), this, SLOT(setCodeEditorStyleDefault()));
connect(mUI->mThemeCustom, SIGNAL(toggled(bool)), mUI->mBtnEditTheme, SLOT(setEnabled(bool)));
mUI->mListWidget->setSortingEnabled(false);
populateApplicationList();
const int count = QThread::idealThreadCount();
if (count != -1)
mUI->mLblIdealThreads->setText(QString::number(count));
else
mUI->mLblIdealThreads->setText(tr("N/A"));
loadSettings();
initTranslationsList();
}
SettingsDialog::~SettingsDialog()
{
saveSettings();
delete mCurrentStyle;
delete mUI;
}
void SettingsDialog::initTranslationsList()
{
const QString current = mTranslator->getCurrentLanguage();
for (const TranslationInfo& translation : mTranslator->getTranslations()) {
auto *item = new QListWidgetItem;
item->setText(translation.mName);
item->setData(mLangCodeRole, QVariant(translation.mCode));
mUI->mListLanguages->addItem(item);
if (translation.mCode == current || translation.mCode == current.mid(0, 2))
mUI->mListLanguages->setCurrentItem(item);
}
}
Qt::CheckState SettingsDialog::boolToCheckState(bool yes)
{
if (yes) {
return Qt::Checked;
}
return Qt::Unchecked;
}
bool SettingsDialog::checkStateToBool(Qt::CheckState state)
{
return state == Qt::Checked;
}
void SettingsDialog::loadSettings()
{
QSettings settings;
resize(settings.value(SETTINGS_CHECK_DIALOG_WIDTH, 800).toInt(),
settings.value(SETTINGS_CHECK_DIALOG_HEIGHT, 600).toInt());
}
void SettingsDialog::saveSettings() const
{
QSettings settings;
settings.setValue(SETTINGS_CHECK_DIALOG_WIDTH, size().width());
settings.setValue(SETTINGS_CHECK_DIALOG_HEIGHT, size().height());
}
void SettingsDialog::saveSettingValues() const
{
int jobs = mUI->mJobs->text().toInt();
if (jobs <= 0) {
jobs = 1;
}
QSettings settings;
settings.setValue(SETTINGS_CHECK_THREADS, jobs);
saveCheckboxValue(&settings, mUI->mForce, SETTINGS_CHECK_FORCE);
saveCheckboxValue(&settings, mUI->mSaveAllErrors, SETTINGS_SAVE_ALL_ERRORS);
saveCheckboxValue(&settings, mUI->mSaveFullPath, SETTINGS_SAVE_FULL_PATH);
saveCheckboxValue(&settings, mUI->mShowFullPath, SETTINGS_SHOW_FULL_PATH);
saveCheckboxValue(&settings, mUI->mShowNoErrorsMessage, SETTINGS_SHOW_NO_ERRORS);
saveCheckboxValue(&settings, mUI->mShowDebugWarnings, SETTINGS_SHOW_DEBUG_WARNINGS);
saveCheckboxValue(&settings, mUI->mInlineSuppressions, SETTINGS_INLINE_SUPPRESSIONS);
saveCheckboxValue(&settings, mUI->mEnableInconclusive, SETTINGS_INCONCLUSIVE_ERRORS);
saveCheckboxValue(&settings, mUI->mShowStatistics, SETTINGS_SHOW_STATISTICS);
saveCheckboxValue(&settings, mUI->mShowErrorId, SETTINGS_SHOW_ERROR_ID);
saveCheckboxValue(&settings, mUI->mCheckForUpdates, SETTINGS_CHECK_FOR_UPDATES);
settings.setValue(SETTINGS_PYTHON_PATH, mUI->mEditPythonPath->text());
if (!mPremium)
settings.setValue(SETTINGS_MISRA_FILE, mUI->mEditMisraFile->text());
#ifdef Q_OS_WIN
settings.setValue(SETTINGS_CLANG_PATH, mUI->mEditClangPath->text());
settings.setValue(SETTINGS_VS_INCLUDE_PATHS, mUI->mEditVsIncludePaths->text());
#endif
const QListWidgetItem *currentLang = mUI->mListLanguages->currentItem();
if (currentLang) {
const QString langcode = currentLang->data(mLangCodeRole).toString();
settings.setValue(SETTINGS_LANGUAGE, langcode);
}
CodeEditorStyle::saveSettings(&settings, *mCurrentStyle);
}
void SettingsDialog::saveCheckboxValue(QSettings *settings, const QCheckBox *box,
const QString &name)
{
settings->setValue(name, checkStateToBool(box->checkState()));
}
void SettingsDialog::validateEditPythonPath()
{
const auto pythonPath = mUI->mEditPythonPath->text();
if (pythonPath.isEmpty()) {
mUI->mEditPythonPath->setStyleSheet("");
mUI->mPythonPathWarning->hide();
return;
}
QFileInfo pythonPathInfo(pythonPath);
if (!pythonPathInfo.exists() ||
!pythonPathInfo.isFile() ||
!pythonPathInfo.isExecutable()) {
mUI->mEditPythonPath->setStyleSheet("QLineEdit {border: 1px solid red}");
mUI->mPythonPathWarning->setText(tr("The executable file \"%1\" is not available").arg(pythonPath));
mUI->mPythonPathWarning->show();
} else {
mUI->mEditPythonPath->setStyleSheet("");
mUI->mPythonPathWarning->hide();
}
}
void SettingsDialog::addApplication()
{
Application app;
ApplicationDialog dialog(tr("Add a new application"), app, this);
if (dialog.exec() == QDialog::Accepted) {
mTempApplications->addApplication(app);
mUI->mListWidget->addItem(app.getName());
}
}
void SettingsDialog::removeApplication()
{
for (QListWidgetItem *item : mUI->mListWidget->selectedItems()) {
const int removeIndex = mUI->mListWidget->row(item);
const int currentDefault = mTempApplications->getDefaultApplication();
mTempApplications->removeApplication(removeIndex);
if (removeIndex == currentDefault)
// If default app is removed set default to unknown
mTempApplications->setDefault(-1);
else if (removeIndex < currentDefault)
// Move default app one up if earlier app was removed
mTempApplications->setDefault(currentDefault - 1);
}
mUI->mListWidget->clear();
populateApplicationList();
}
void SettingsDialog::editApplication()
{
for (QListWidgetItem *item : mUI->mListWidget->selectedItems()) {
const int row = mUI->mListWidget->row(item);
Application& app = mTempApplications->getApplication(row);
ApplicationDialog dialog(tr("Modify an application"), app, this);
if (dialog.exec() == QDialog::Accepted) {
QString name = app.getName();
if (mTempApplications->getDefaultApplication() == row)
name += tr(" [Default]");
item->setText(name);
}
}
}
void SettingsDialog::defaultApplication()
{
QList<QListWidgetItem *> selected = mUI->mListWidget->selectedItems();
if (!selected.isEmpty()) {
const int index = mUI->mListWidget->row(selected[0]);
mTempApplications->setDefault(index);
mUI->mListWidget->clear();
populateApplicationList();
}
}
void SettingsDialog::populateApplicationList()
{
const int defapp = mTempApplications->getDefaultApplication();
for (int i = 0; i < mTempApplications->getApplicationCount(); i++) {
const Application& app = mTempApplications->getApplication(i);
QString name = app.getName();
if (i == defapp) {
name += " ";
name += tr("[Default]");
}
mUI->mListWidget->addItem(name);
}
// Select default application, or if there is no default app then the
// first item.
if (defapp == -1)
mUI->mListWidget->setCurrentRow(0);
else {
if (mTempApplications->getApplicationCount() > defapp)
mUI->mListWidget->setCurrentRow(defapp);
else
mUI->mListWidget->setCurrentRow(0);
}
}
void SettingsDialog::ok()
{
mApplications->copy(mTempApplications);
accept();
}
bool SettingsDialog::showFullPath() const
{
return checkStateToBool(mUI->mShowFullPath->checkState());
}
bool SettingsDialog::saveFullPath() const
{
return checkStateToBool(mUI->mSaveFullPath->checkState());
}
bool SettingsDialog::saveAllErrors() const
{
return checkStateToBool(mUI->mSaveAllErrors->checkState());
}
bool SettingsDialog::showNoErrorsMessage() const
{
return checkStateToBool(mUI->mShowNoErrorsMessage->checkState());
}
bool SettingsDialog::showErrorId() const
{
return checkStateToBool(mUI->mShowErrorId->checkState());
}
bool SettingsDialog::showInconclusive() const
{
return checkStateToBool(mUI->mEnableInconclusive->checkState());
}
void SettingsDialog::browsePythonPath()
{
QString fileName = QFileDialog::getOpenFileName(this, tr("Select python binary"), QDir::rootPath());
if (fileName.contains("python", Qt::CaseInsensitive))
mUI->mEditPythonPath->setText(fileName);
}
void SettingsDialog::browseMisraFile()
{
const QString fileName = QFileDialog::getOpenFileName(this, tr("Select MISRA File"), QDir::homePath(), "Misra File (*.pdf *.txt)");
if (!fileName.isEmpty())
mUI->mEditMisraFile->setText(fileName);
}
// Slot to set default light style
void SettingsDialog::setCodeEditorStyleDefault()
{
if (mUI->mThemeSystem->isChecked())
*mCurrentStyle = CodeEditorStyle::getSystemTheme();
if (mUI->mThemeLight->isChecked())
*mCurrentStyle = defaultStyleLight;
if (mUI->mThemeDark->isChecked())
*mCurrentStyle = defaultStyleDark;
manageStyleControls();
}
// Slot to edit custom style
void SettingsDialog::editCodeEditorStyle()
{
StyleEditDialog dlg(*mCurrentStyle, this);
const int nResult = dlg.exec();
if (nResult == QDialog::Accepted) {
*mCurrentStyle = dlg.getStyle();
manageStyleControls();
}
}
void SettingsDialog::browseClangPath()
{
QString selectedDir = QFileDialog::getExistingDirectory(this,
tr("Select clang path"),
QDir::rootPath());
if (!selectedDir.isEmpty()) {
mUI->mEditClangPath->setText(selectedDir);
}
}
void SettingsDialog::manageStyleControls()
{
const bool isSystemTheme = mCurrentStyle->isSystemTheme();
const bool isDefaultLight = !isSystemTheme && *mCurrentStyle == defaultStyleLight;
const bool isDefaultDark = !isSystemTheme && *mCurrentStyle == defaultStyleDark;
mUI->mThemeSystem->setChecked(isSystemTheme);
mUI->mThemeLight->setChecked(isDefaultLight && !isDefaultDark);
mUI->mThemeDark->setChecked(!isDefaultLight && isDefaultDark);
mUI->mThemeCustom->setChecked(!isSystemTheme && !isDefaultLight && !isDefaultDark);
mUI->mBtnEditTheme->setEnabled(!isSystemTheme && !isDefaultLight && !isDefaultDark);
}
| null |
710 | cpp | cppcheck | application.h | gui/application.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef APPLICATION_H
#define APPLICATION_H
#include <QString>
/**
* @brief A class containing information of the application to execute.
*
* Each application has a name and a path. Name is displayed to the user
* and has no other meaning. It isn't used to start the application.
* Path contains the full path to the application containing the executable name.
* Parameters contains the command line arguments for the executable.
*
* User can also specify certain predefined strings to parameters. These strings
* will be replaced with appropriate values concerning the error. Strings are:
* (file) - Filename containing the error
* (line) - Line number containing the error
* (message) - Error message
* (severity) - Error severity
*
* Example opening a file with Kate and make Kate scroll to the correct line.
* Executable: kate
* Parameters: -l(line) (file)
*/
class Application {
public:
Application() = default;
Application(QString name, QString path, QString params);
/**
* @brief Get application name.
* @return Application name.
*/
const QString& getName() const {
return mName;
}
/**
* @brief Get application path.
* @return Application path.
*/
const QString& getPath() const {
return mPath;
}
/**
* @brief Get application command line parameters.
* @return Application command line parameters.
*/
const QString& getParameters() const {
return mParameters;
}
/**
* @brief Set application name.
* @param name Application name.
*/
void setName(const QString &name) {
mName = name;
}
/**
* @brief Set application path.
* @param path Application path.
*/
void setPath(const QString &path) {
mPath = path;
}
/**
* @brief Set application command line parameters.
* @param parameters Application command line parameters.
*/
void setParameters(const QString ¶meters) {
mParameters = parameters;
}
private:
/**
* @brief Application's name
*/
QString mName;
/**
* @brief Application's path
*/
QString mPath;
/**
* @brief Application's parameters
*/
QString mParameters;
};
#endif // APPLICATION_H
| null |
711 | cpp | cppcheck | csvreport.h | gui/csvreport.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef CSV_REPORT_H
#define CSV_REPORT_H
#include "report.h"
#include <QString>
#include <QTextStream>
/// @addtogroup GUI
/// @{
/**
* @brief CSV text file report.
* This report exports results as CSV (comma separated values). CSV files are
* easy to import to many other programs.
* @todo This class should be inherited from TxtReport?
*/
class CsvReport : public Report {
public:
explicit CsvReport(const QString &filename);
/**
* @brief Create the report (file).
* @return true if succeeded, false if file could not be created.
*/
bool create() override;
/**
* @brief Write report header.
*/
void writeHeader() override;
/**
* @brief Write report footer.
*/
void writeFooter() override;
/**
* @brief Write error to report.
* @param error Error data.
*/
void writeError(const ErrorItem &error) override;
private:
/**
* @brief Text stream writer for writing the report in text format.
*/
QTextStream mTxtWriter;
};
/// @}
#endif // CSV_REPORT_H
| null |
712 | cpp | cppcheck | threadresult.cpp | gui/threadresult.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "threadresult.h"
#include "common.h"
#include "erroritem.h"
#include "errorlogger.h"
#include "errortypes.h"
#include "importproject.h"
#include <numeric>
#include <QFile>
void ThreadResult::reportOut(const std::string &outmsg, Color /*c*/)
{
emit log(QString::fromStdString(outmsg));
}
void ThreadResult::fileChecked(const QString &file)
{
std::lock_guard<std::mutex> locker(mutex);
mProgress += QFile(file).size();
mFilesChecked++;
if (mMaxProgress > 0) {
const int value = static_cast<int>(PROGRESS_MAX * mProgress / mMaxProgress);
const QString description = tr("%1 of %2 files checked").arg(mFilesChecked).arg(mTotalFiles);
emit progress(value, description);
}
}
void ThreadResult::reportErr(const ErrorMessage &msg)
{
std::lock_guard<std::mutex> locker(mutex);
const ErrorItem item(msg);
if (msg.severity != Severity::debug)
emit error(item);
else
emit debugError(item);
}
QString ThreadResult::getNextFile()
{
std::lock_guard<std::mutex> locker(mutex);
if (mFiles.isEmpty()) {
return QString();
}
return mFiles.takeFirst();
}
void ThreadResult::getNextFileSettings(const FileSettings*& fs)
{
std::lock_guard<std::mutex> locker(mutex);
fs = nullptr;
if (mItNextFileSettings == mFileSettings.cend()) {
return;
}
fs = &(*mItNextFileSettings);
++mItNextFileSettings;
}
void ThreadResult::setFiles(const QStringList &files)
{
std::lock_guard<std::mutex> locker(mutex);
mFiles = files;
mProgress = 0;
mFilesChecked = 0;
mTotalFiles = files.size();
// Determine the total size of all of the files to check, so that we can
// show an accurate progress estimate
quint64 sizeOfFiles = std::accumulate(files.begin(), files.end(), 0, [](quint64 total, const QString& file) {
return total + QFile(file).size();
});
mMaxProgress = sizeOfFiles;
}
void ThreadResult::setProject(const ImportProject &prj)
{
std::lock_guard<std::mutex> locker(mutex);
mFiles.clear();
mFileSettings = prj.fileSettings;
mItNextFileSettings = mFileSettings.cbegin();
mProgress = 0;
mFilesChecked = 0;
mTotalFiles = prj.fileSettings.size();
// Determine the total size of all of the files to check, so that we can
// show an accurate progress estimate
mMaxProgress = std::accumulate(prj.fileSettings.begin(), prj.fileSettings.end(), quint64{ 0 }, [](quint64 v, const FileSettings& fs) {
return v + QFile(QString::fromStdString(fs.filename())).size();
});
}
void ThreadResult::clearFiles()
{
std::lock_guard<std::mutex> locker(mutex);
mFiles.clear();
mFileSettings.clear();
mItNextFileSettings = mFileSettings.cend();
mFilesChecked = 0;
mTotalFiles = 0;
}
int ThreadResult::getFileCount() const
{
std::lock_guard<std::mutex> locker(mutex);
return mFiles.size() + mFileSettings.size();
}
| null |
713 | cpp | cppcheck | checkthread.h | gui/checkthread.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef CHECKTHREAD_H
#define CHECKTHREAD_H
#include "settings.h"
#include "suppressions.h"
#include <atomic>
#include <cstdint>
#include <string>
#include <vector>
#include <QList>
#include <QObject>
#include <QString>
#include <QStringList>
#include <QThread>
class ThreadResult;
struct FileSettings;
/// @addtogroup GUI
/// @{
/**
* @brief Thread to run cppcheck
*
*/
class CheckThread : public QThread {
Q_OBJECT
public:
explicit CheckThread(ThreadResult &result);
/**
* @brief Set settings for cppcheck
*
* @param settings settings for cppcheck
*/
void setSettings(const Settings &settings);
/**
* @brief Run whole program analysis
* @param files All files
* @param ctuInfo Ctu info for addons
*/
void analyseWholeProgram(const QStringList &files, const std::string& ctuInfo);
void setAddonsAndTools(const QStringList &addonsAndTools) {
mAddonsAndTools = addonsAndTools;
}
void setClangIncludePaths(const QStringList &s) {
mClangIncludePaths = s;
}
void setSuppressions(const QList<SuppressionList::Suppression> &s) {
mSuppressions = s;
}
/**
* @brief method that is run in a thread
*
*/
void run() override;
void stop();
/**
* Determine command to run clang
* \return Command to run clang, empty if it is not found
*/
static QString clangCmd();
/**
* Determine command to run clang-tidy
* \return Command to run clang-tidy, empty if it is not found
*/
static QString clangTidyCmd();
static int executeCommand(std::string exe, std::vector<std::string> args, std::string redirect, std::string &output);
signals:
/**
* @brief cpp checking is done
*
*/
void done();
// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) - caused by generated MOC code
void fileChecked(const QString &file);
protected:
/**
* @brief States for the check thread.
* Whole purpose of these states is to allow stopping of the checking. When
* stopping we say for the thread (Stopping) that stop when current check
* has been completed. Thread must be stopped cleanly, just terminating thread
* likely causes unpredictable side-effects.
*/
enum State : std::uint8_t {
Running, /**< The thread is checking. */
Stopping, /**< The thread will stop after current work. */
Stopped, /**< The thread has been stopped. */
Ready, /**< The thread is ready. */
};
/**
* @brief Thread's current execution state. Can be changed from outside
*/
std::atomic<State> mState{Ready};
ThreadResult &mResult;
Settings mSettings;
private:
void runAddonsAndTools(const Settings& settings, const FileSettings *fileSettings, const QString &fileName);
void parseClangErrors(const QString &tool, const QString &file0, QString err);
bool isSuppressed(const SuppressionList::ErrorMessage &errorMessage) const;
QStringList mFiles;
bool mAnalyseWholeProgram{};
std::string mCtuInfo;
QStringList mAddonsAndTools;
QStringList mClangIncludePaths;
QList<SuppressionList::Suppression> mSuppressions;
};
/// @}
#endif // CHECKTHREAD_H
| null |
714 | cpp | cppcheck | printablereport.h | gui/printablereport.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PRINTABLE_REPORT_H
#define PRINTABLE_REPORT_H
#include "report.h"
#include <QString>
/// @addtogroup GUI
/// @{
/**
* @brief Printable (in-memory) report.
* This report formats results and exposes them for printing.
*/
class PrintableReport : public Report {
public:
PrintableReport();
/**
* @brief Create the report (file).
* @return true if succeeded, false if file could not be created.
*/
bool create() override;
/**
* @brief Write report header.
*/
void writeHeader() override;
/**
* @brief Write report footer.
*/
void writeFooter() override;
/**
* @brief Write error to report.
* @param error Error data.
*/
void writeError(const ErrorItem &error) override;
/**
* @brief Returns the formatted report.
*/
const QString& getFormattedReportText() const;
private:
/**
* @brief Stores the formatted report contents.
*/
QString mFormattedReport;
};
/// @}
#endif // PRINTABLE_REPORT_H
| null |
715 | cpp | cppcheck | mainwindow.cpp | gui/mainwindow.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mainwindow.h"
#include "addoninfo.h"
#include "applicationlist.h"
#include "aboutdialog.h"
#include "analyzerinfo.h"
#include "checkstatistics.h"
#include "checkthread.h"
#include "common.h"
#include "cppcheck.h"
#include "errortypes.h"
#include "filelist.h"
#include "filesettings.h"
#include "compliancereportdialog.h"
#include "fileviewdialog.h"
#include "helpdialog.h"
#include "importproject.h"
#include "librarydialog.h"
#include "platform.h"
#include "projectfile.h"
#include "projectfiledialog.h"
#include "report.h"
#include "resultsview.h"
#include "scratchpad.h"
#include "settings.h"
#include "showtypes.h"
#include "statsdialog.h"
#include "settingsdialog.h"
#include "standards.h"
#include "suppressions.h"
#include "threadhandler.h"
#include "threadresult.h"
#include "translationhandler.h"
#include "ui_mainwindow.h"
#include <algorithm>
#include <iterator>
#include <list>
#include <set>
#include <string>
#include <unordered_set>
#include <utility>
#include <vector>
#include <QApplication>
#include <QAction>
#include <QActionGroup>
#include <QByteArray>
#include <QChar>
#include <QCloseEvent>
#include <QCoreApplication>
#include <QDateTime>
#include <QDebug>
#include <QDialog>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QHBoxLayout>
#include <QInputDialog>
#include <QKeySequence>
#include <QLabel>
#include <QLineEdit>
#include <QList>
#include <QMap>
#include <QMenu>
#include <QMessageBox>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkReply>
#include <QtNetwork/QNetworkRequest>
#include <QPushButton>
#include <QRegularExpression>
#include <QSettings>
#include <QSize>
#include <QTimer>
#include <QTemporaryFile>
#include <QToolBar>
#include <QUrl>
#include <QVariant>
#include <Qt>
#include "json.h"
static const QString compile_commands_json("compile_commands.json");
static QString fromNativePath(const QString& p) {
#ifdef Q_OS_WIN
QString ret(p);
ret.replace('\\', '/');
return ret;
#else
return p;
#endif
}
MainWindow::MainWindow(TranslationHandler* th, QSettings* settings) :
mSettings(settings),
mApplications(new ApplicationList(this)),
mTranslation(th),
mUI(new Ui::MainWindow),
mPlatformActions(new QActionGroup(this)),
mCStandardActions(new QActionGroup(this)),
mCppStandardActions(new QActionGroup(this)),
mSelectLanguageActions(new QActionGroup(this)),
mSelectReportActions(new QActionGroup(this))
{
{
Settings tempSettings;
tempSettings.exename = QCoreApplication::applicationFilePath().toStdString();
Settings::loadCppcheckCfg(tempSettings, tempSettings.supprs); // TODO: how to handle error?
mCppcheckCfgProductName = QString::fromStdString(tempSettings.cppcheckCfgProductName);
mCppcheckCfgAbout = QString::fromStdString(tempSettings.cppcheckCfgAbout);
}
mUI->setupUi(this);
mThread = new ThreadHandler(this);
mUI->mResults->initialize(mSettings, mApplications, mThread);
// Filter timer to delay filtering results slightly while typing
mFilterTimer = new QTimer(this);
mFilterTimer->setInterval(500);
mFilterTimer->setSingleShot(true);
connect(mFilterTimer, &QTimer::timeout, this, &MainWindow::filterResults);
// "Filter" toolbar
mLineEditFilter = new QLineEdit(mUI->mToolBarFilter);
mLineEditFilter->setPlaceholderText(tr("Quick Filter:"));
mLineEditFilter->setClearButtonEnabled(true);
mUI->mToolBarFilter->addWidget(mLineEditFilter);
connect(mLineEditFilter, SIGNAL(textChanged(QString)), mFilterTimer, SLOT(start()));
connect(mLineEditFilter, &QLineEdit::returnPressed, this, &MainWindow::filterResults);
connect(mUI->mActionPrint, SIGNAL(triggered()), mUI->mResults, SLOT(print()));
connect(mUI->mActionPrintPreview, SIGNAL(triggered()), mUI->mResults, SLOT(printPreview()));
connect(mUI->mActionQuit, &QAction::triggered, this, &MainWindow::close);
connect(mUI->mActionAnalyzeFiles, &QAction::triggered, this, &MainWindow::analyzeFiles);
connect(mUI->mActionAnalyzeDirectory, &QAction::triggered, this, &MainWindow::analyzeDirectory);
connect(mUI->mActionSettings, &QAction::triggered, this, &MainWindow::programSettings);
connect(mUI->mActionClearResults, &QAction::triggered, this, &MainWindow::clearResults);
connect(mUI->mActionOpenXML, &QAction::triggered, this, &MainWindow::openResults);
connect(mUI->mActionShowStyle, &QAction::toggled, this, &MainWindow::showStyle);
connect(mUI->mActionShowErrors, &QAction::toggled, this, &MainWindow::showErrors);
connect(mUI->mActionShowWarnings, &QAction::toggled, this, &MainWindow::showWarnings);
connect(mUI->mActionShowPortability, &QAction::toggled, this, &MainWindow::showPortability);
connect(mUI->mActionShowPerformance, &QAction::toggled, this, &MainWindow::showPerformance);
connect(mUI->mActionShowInformation, &QAction::toggled, this, &MainWindow::showInformation);
connect(mUI->mActionShowCppcheck, &QAction::toggled, mUI->mResults, &ResultsView::showCppcheckResults);
connect(mUI->mActionShowClang, &QAction::toggled, mUI->mResults, &ResultsView::showClangResults);
connect(mUI->mActionCheckAll, &QAction::triggered, this, &MainWindow::checkAll);
connect(mUI->mActionUncheckAll, &QAction::triggered, this, &MainWindow::uncheckAll);
connect(mUI->mActionCollapseAll, &QAction::triggered, mUI->mResults, &ResultsView::collapseAllResults);
connect(mUI->mActionExpandAll, &QAction::triggered, mUI->mResults, &ResultsView::expandAllResults);
connect(mUI->mActionShowHidden, &QAction::triggered, mUI->mResults, &ResultsView::showHiddenResults);
connect(mUI->mActionViewStats, &QAction::triggered, this, &MainWindow::showStatistics);
connect(mUI->mActionLibraryEditor, &QAction::triggered, this, &MainWindow::showLibraryEditor);
connect(mUI->mActionReanalyzeModified, &QAction::triggered, this, &MainWindow::reAnalyzeModified);
connect(mUI->mActionReanalyzeAll, &QAction::triggered, this, &MainWindow::reAnalyzeAll);
connect(mUI->mActionCheckLibrary, &QAction::triggered, this, &MainWindow::checkLibrary);
connect(mUI->mActionCheckConfiguration, &QAction::triggered, this, &MainWindow::checkConfiguration);
connect(mUI->mActionStop, &QAction::triggered, this, &MainWindow::stopAnalysis);
connect(mUI->mActionSave, &QAction::triggered, this, &MainWindow::save);
connect(mUI->mActionComplianceReport, &QAction::triggered, this, &MainWindow::complianceReport);
// About menu
connect(mUI->mActionAbout, &QAction::triggered, this, &MainWindow::about);
connect(mUI->mActionLicense, &QAction::triggered, this, &MainWindow::showLicense);
// View > Toolbar menu
connect(mUI->mActionToolBarMain, SIGNAL(toggled(bool)), this, SLOT(toggleMainToolBar()));
connect(mUI->mActionToolBarView, SIGNAL(toggled(bool)), this, SLOT(toggleViewToolBar()));
connect(mUI->mActionToolBarFilter, SIGNAL(toggled(bool)), this, SLOT(toggleFilterToolBar()));
connect(mUI->mActionAuthors, &QAction::triggered, this, &MainWindow::showAuthors);
connect(mThread, &ThreadHandler::done, this, &MainWindow::analysisDone);
connect(mThread, &ThreadHandler::log, mUI->mResults, &ResultsView::log);
connect(mThread, &ThreadHandler::debugError, mUI->mResults, &ResultsView::debugError);
connect(mUI->mResults, &ResultsView::gotResults, this, &MainWindow::resultsAdded);
connect(mUI->mResults, &ResultsView::resultsHidden, mUI->mActionShowHidden, &QAction::setEnabled);
connect(mUI->mResults, &ResultsView::checkSelected, this, &MainWindow::performSelectedFilesCheck);
connect(mUI->mResults, &ResultsView::suppressIds, this, &MainWindow::suppressIds);
connect(mUI->mMenuView, &QMenu::aboutToShow, this, &MainWindow::aboutToShowViewMenu);
// Change report type
connect(mUI->mActionReportNormal, &QAction::triggered, this, &MainWindow::changeReportType);
connect(mUI->mActionReportAutosar, &QAction::triggered, this, &MainWindow::changeReportType);
connect(mUI->mActionReportCertC, &QAction::triggered, this, &MainWindow::changeReportType);
connect(mUI->mActionReportCertCpp, &QAction::triggered, this, &MainWindow::changeReportType);
connect(mUI->mActionReportMisraC, &QAction::triggered, this, &MainWindow::changeReportType);
connect(mUI->mActionReportMisraCpp2008, &QAction::triggered, this, &MainWindow::changeReportType);
connect(mUI->mActionReportMisraCpp2023, &QAction::triggered, this, &MainWindow::changeReportType);
// File menu
connect(mUI->mActionNewProjectFile, &QAction::triggered, this, &MainWindow::newProjectFile);
connect(mUI->mActionOpenProjectFile, &QAction::triggered, this, &MainWindow::openProjectFile);
connect(mUI->mActionShowScratchpad, &QAction::triggered, this, &MainWindow::showScratchpad);
connect(mUI->mActionCloseProjectFile, &QAction::triggered, this, &MainWindow::closeProjectFile);
connect(mUI->mActionEditProjectFile, &QAction::triggered, this, &MainWindow::editProjectFile);
connect(mUI->mActionHelpContents, &QAction::triggered, this, &MainWindow::openHelpContents);
loadSettings();
mThread->initialize(mUI->mResults);
if (mProjectFile)
formatAndSetTitle(tr("Project:") + ' ' + mProjectFile->getFilename());
else
formatAndSetTitle();
mUI->mActionComplianceReport->setVisible(isCppcheckPremium());
enableCheckButtons(true);
mUI->mActionPrint->setShortcut(QKeySequence::Print);
enableResultsButtons();
enableProjectOpenActions(true);
enableProjectActions(false);
// Must setup MRU menu before CLI param handling as it can load a
// project file and update MRU menu.
for (int i = 0; i < MaxRecentProjects; ++i) {
mRecentProjectActs[i] = new QAction(this);
mRecentProjectActs[i]->setVisible(false);
connect(mRecentProjectActs[i], SIGNAL(triggered()),
this, SLOT(openRecentProject()));
}
mRecentProjectActs[MaxRecentProjects] = nullptr; // The separator
mUI->mActionProjectMRU->setVisible(false);
updateMRUMenuItems();
QStringList args = QCoreApplication::arguments();
//Remove the application itself
args.removeFirst();
if (!args.isEmpty()) {
handleCLIParams(args);
}
mUI->mActionCloseProjectFile->setEnabled(mProjectFile != nullptr);
mUI->mActionEditProjectFile->setEnabled(mProjectFile != nullptr);
for (int i = 0; i < mPlatforms.getCount(); i++) {
PlatformData platform = mPlatforms.mPlatforms[i];
auto *action = new QAction(this);
platform.mActMainWindow = action;
mPlatforms.mPlatforms[i] = platform;
action->setText(platform.mTitle);
action->setData(platform.mType);
action->setCheckable(true);
action->setActionGroup(mPlatformActions);
mUI->mMenuAnalyze->insertAction(mUI->mActionPlatforms, action);
connect(action, SIGNAL(triggered()), this, SLOT(selectPlatform()));
}
mUI->mActionReportNormal->setActionGroup(mSelectReportActions);
mUI->mActionReportAutosar->setActionGroup(mSelectReportActions);
mUI->mActionReportCertC->setActionGroup(mSelectReportActions);
mUI->mActionReportCertCpp->setActionGroup(mSelectReportActions);
mUI->mActionReportMisraC->setActionGroup(mSelectReportActions);
mUI->mActionReportMisraCpp2008->setActionGroup(mSelectReportActions);
mUI->mActionReportMisraCpp2023->setActionGroup(mSelectReportActions);
mUI->mActionC89->setActionGroup(mCStandardActions);
mUI->mActionC99->setActionGroup(mCStandardActions);
mUI->mActionC11->setActionGroup(mCStandardActions);
//mUI->mActionC17->setActionGroup(mCStandardActions);
//mUI->mActionC23->setActionGroup(mCStandardActions);
mUI->mActionCpp03->setActionGroup(mCppStandardActions);
mUI->mActionCpp11->setActionGroup(mCppStandardActions);
mUI->mActionCpp14->setActionGroup(mCppStandardActions);
mUI->mActionCpp17->setActionGroup(mCppStandardActions);
mUI->mActionCpp20->setActionGroup(mCppStandardActions);
//mUI->mActionCpp23->setActionGroup(mCppStandardActions);
//mUI->mActionCpp26->setActionGroup(mCppStandardActions);
mUI->mActionEnforceC->setActionGroup(mSelectLanguageActions);
mUI->mActionEnforceCpp->setActionGroup(mSelectLanguageActions);
mUI->mActionAutoDetectLanguage->setActionGroup(mSelectLanguageActions);
// TODO: we no longer default to a Windows platform in CLI - so we should probably also get rid of this in the GUI
// For Windows platforms default to Win32 checked platform.
// For other platforms default to unspecified/default which means the
// platform Cppcheck GUI was compiled on.
#if defined(_WIN32)
constexpr Platform::Type defaultPlatform = Platform::Type::Win32W;
#else
constexpr Platform::Type defaultPlatform = Platform::Type::Unspecified;
#endif
PlatformData &platform = mPlatforms.get((Platform::Type)mSettings->value(SETTINGS_CHECKED_PLATFORM, defaultPlatform).toInt());
platform.mActMainWindow->setChecked(true);
mNetworkAccessManager = new QNetworkAccessManager(this);
connect(mNetworkAccessManager, &QNetworkAccessManager::finished,
this, &MainWindow::replyFinished);
mUI->mLabelInformation->setVisible(false);
mUI->mButtonHideInformation->setVisible(false);
connect(mUI->mButtonHideInformation, &QPushButton::clicked,
this, &MainWindow::hideInformation);
if (mSettings->value(SETTINGS_CHECK_FOR_UPDATES, false).toBool()) {
// Is there a new version?
if (isCppcheckPremium()) {
const QUrl url("https://files.cppchecksolutions.com/version.txt");
mNetworkAccessManager->get(QNetworkRequest(url));
} else {
const QUrl url("https://cppcheck.sourceforge.io/version.txt");
mNetworkAccessManager->get(QNetworkRequest(url));
}
} else {
delete mUI->mLayoutInformation;
}
changeReportType();
}
MainWindow::~MainWindow()
{
delete mProjectFile;
delete mScratchPad;
delete mUI;
}
void MainWindow::handleCLIParams(const QStringList ¶ms)
{
int index;
if (params.contains("-p")) {
index = params.indexOf("-p");
if ((index + 1) < params.length())
loadProjectFile(params[index + 1]);
} else if (params.contains("-l")) {
QString logFile;
index = params.indexOf("-l");
if ((index + 1) < params.length())
logFile = params[index + 1];
if (params.contains("-d")) {
QString checkedDir;
index = params.indexOf("-d");
if ((index + 1) < params.length())
checkedDir = params[index + 1];
loadResults(logFile, checkedDir);
} else {
loadResults(logFile);
}
} else if ((index = params.indexOf(QRegularExpression(".*\\.cppcheck$", QRegularExpression::CaseInsensitiveOption))) >= 0 && index < params.length() && QFile(params[index]).exists()) {
loadProjectFile(params[index]);
} else if ((index = params.indexOf(QRegularExpression(".*\\.xml$", QRegularExpression::CaseInsensitiveOption))) >= 0 && index < params.length() && QFile(params[index]).exists()) {
loadResults(params[index],QDir::currentPath());
} else
doAnalyzeFiles(params);
}
void MainWindow::loadSettings()
{
// Window/dialog sizes
if (mSettings->value(SETTINGS_WINDOW_MAXIMIZED, false).toBool()) {
showMaximized();
} else {
resize(mSettings->value(SETTINGS_WINDOW_WIDTH, 800).toInt(),
mSettings->value(SETTINGS_WINDOW_HEIGHT, 600).toInt());
}
const ReportType reportType = (ReportType)mSettings->value(SETTINGS_REPORT_TYPE, (int)ReportType::normal).toInt();
mUI->mActionReportNormal->setChecked(reportType <= ReportType::normal);
mUI->mActionReportAutosar->setChecked(reportType == ReportType::autosar);
mUI->mActionReportCertC->setChecked(reportType == ReportType::certC);
mUI->mActionReportCertCpp->setChecked(reportType == ReportType::certCpp);
mUI->mActionReportMisraC->setChecked(reportType == ReportType::misraC);
mUI->mActionReportMisraCpp2008->setChecked(reportType == ReportType::misraCpp2008);
mUI->mActionReportMisraCpp2023->setChecked(reportType == ReportType::misraCpp2023);
const ShowTypes &types = mUI->mResults->getShowTypes();
mUI->mActionShowStyle->setChecked(types.isShown(ShowTypes::ShowStyle));
mUI->mActionShowErrors->setChecked(types.isShown(ShowTypes::ShowErrors));
mUI->mActionShowWarnings->setChecked(types.isShown(ShowTypes::ShowWarnings));
mUI->mActionShowPortability->setChecked(types.isShown(ShowTypes::ShowPortability));
mUI->mActionShowPerformance->setChecked(types.isShown(ShowTypes::ShowPerformance));
mUI->mActionShowInformation->setChecked(types.isShown(ShowTypes::ShowInformation));
mUI->mActionShowCppcheck->setChecked(true);
mUI->mActionShowClang->setChecked(true);
Standards standards;
standards.setC(mSettings->value(SETTINGS_STD_C, QString()).toString().toStdString());
mUI->mActionC89->setChecked(standards.c == Standards::C89);
mUI->mActionC99->setChecked(standards.c == Standards::C99);
mUI->mActionC11->setChecked(standards.c == Standards::C11);
//mUI->mActionC17->setChecked(standards.c == Standards::C17);
//mUI->mActionC23->setChecked(standards.c == Standards::C23);
standards.setCPP(mSettings->value(SETTINGS_STD_CPP, QString()).toString().toStdString());
mUI->mActionCpp03->setChecked(standards.cpp == Standards::CPP03);
mUI->mActionCpp11->setChecked(standards.cpp == Standards::CPP11);
mUI->mActionCpp14->setChecked(standards.cpp == Standards::CPP14);
mUI->mActionCpp17->setChecked(standards.cpp == Standards::CPP17);
mUI->mActionCpp20->setChecked(standards.cpp == Standards::CPP20);
//mUI->mActionCpp23->setChecked(standards.cpp == Standards::CPP23);
//mUI->mActionCpp26->setChecked(standards.cpp == Standards::CPP26);
// Main window settings
const bool showMainToolbar = mSettings->value(SETTINGS_TOOLBARS_MAIN_SHOW, true).toBool();
mUI->mActionToolBarMain->setChecked(showMainToolbar);
mUI->mToolBarMain->setVisible(showMainToolbar);
const bool showViewToolbar = mSettings->value(SETTINGS_TOOLBARS_VIEW_SHOW, true).toBool();
mUI->mActionToolBarView->setChecked(showViewToolbar);
mUI->mToolBarView->setVisible(showViewToolbar);
const bool showFilterToolbar = mSettings->value(SETTINGS_TOOLBARS_FILTER_SHOW, true).toBool();
mUI->mActionToolBarFilter->setChecked(showFilterToolbar);
mUI->mToolBarFilter->setVisible(showFilterToolbar);
const Standards::Language enforcedLanguage = (Standards::Language)mSettings->value(SETTINGS_ENFORCED_LANGUAGE, 0).toInt();
if (enforcedLanguage == Standards::Language::CPP)
mUI->mActionEnforceCpp->setChecked(true);
else if (enforcedLanguage == Standards::Language::C)
mUI->mActionEnforceC->setChecked(true);
else
mUI->mActionAutoDetectLanguage->setChecked(true);
const bool succeeded = mApplications->loadSettings();
if (!succeeded) {
const QString msg = tr("There was a problem with loading the editor application settings.\n\n"
"This is probably because the settings were changed between the Cppcheck versions. "
"Please check (and fix) the editor application settings, otherwise the editor "
"program might not start correctly.");
QMessageBox msgBox(QMessageBox::Warning,
tr("Cppcheck"),
msg,
QMessageBox::Ok,
this);
msgBox.exec();
}
const QString projectFile = mSettings->value(SETTINGS_OPEN_PROJECT, QString()).toString();
if (!projectFile.isEmpty() && QCoreApplication::arguments().size()==1) {
QFileInfo inf(projectFile);
if (inf.exists() && inf.isReadable()) {
setPath(SETTINGS_LAST_PROJECT_PATH, projectFile);
mProjectFile = new ProjectFile(this);
mProjectFile->setActiveProject();
mProjectFile->read(projectFile);
loadLastResults();
QDir::setCurrent(inf.absolutePath());
}
}
}
void MainWindow::saveSettings() const
{
// Window/dialog sizes
mSettings->setValue(SETTINGS_WINDOW_WIDTH, size().width());
mSettings->setValue(SETTINGS_WINDOW_HEIGHT, size().height());
mSettings->setValue(SETTINGS_WINDOW_MAXIMIZED, isMaximized());
const ReportType reportType = mUI->mActionReportAutosar->isChecked() ? ReportType::autosar :
mUI->mActionReportCertC->isChecked() ? ReportType::certC :
mUI->mActionReportCertCpp->isChecked() ? ReportType::certCpp :
mUI->mActionReportMisraC->isChecked() ? ReportType::misraC :
mUI->mActionReportMisraCpp2008->isChecked() ? ReportType::misraCpp2008 :
mUI->mActionReportMisraCpp2023->isChecked() ? ReportType::misraCpp2023 :
ReportType::normal;
mSettings->setValue(SETTINGS_REPORT_TYPE, (int)reportType);
// Show * states
mSettings->setValue(SETTINGS_SHOW_STYLE, mUI->mActionShowStyle->isChecked());
mSettings->setValue(SETTINGS_SHOW_ERRORS, mUI->mActionShowErrors->isChecked());
mSettings->setValue(SETTINGS_SHOW_WARNINGS, mUI->mActionShowWarnings->isChecked());
mSettings->setValue(SETTINGS_SHOW_PORTABILITY, mUI->mActionShowPortability->isChecked());
mSettings->setValue(SETTINGS_SHOW_PERFORMANCE, mUI->mActionShowPerformance->isChecked());
mSettings->setValue(SETTINGS_SHOW_INFORMATION, mUI->mActionShowInformation->isChecked());
if (mUI->mActionC89->isChecked())
mSettings->setValue(SETTINGS_STD_C, "C89");
if (mUI->mActionC99->isChecked())
mSettings->setValue(SETTINGS_STD_C, "C99");
if (mUI->mActionC11->isChecked())
mSettings->setValue(SETTINGS_STD_C, "C11");
//if (mUI->mActionC17->isChecked())
// mSettings->setValue(SETTINGS_STD_C, "C17");
//if (mUI->mActionC23->isChecked())
// mSettings->setValue(SETTINGS_STD_C, "C23");
if (mUI->mActionCpp03->isChecked())
mSettings->setValue(SETTINGS_STD_CPP, "C++03");
if (mUI->mActionCpp11->isChecked())
mSettings->setValue(SETTINGS_STD_CPP, "C++11");
if (mUI->mActionCpp14->isChecked())
mSettings->setValue(SETTINGS_STD_CPP, "C++14");
if (mUI->mActionCpp17->isChecked())
mSettings->setValue(SETTINGS_STD_CPP, "C++17");
if (mUI->mActionCpp20->isChecked())
mSettings->setValue(SETTINGS_STD_CPP, "C++20");
//if (mUI.mActionCpp23->isChecked())
// mSettings->setValue(SETTINGS_STD_CPP, "C++23");
//if (mUI.mActionCpp26->isChecked())
// mSettings->setValue(SETTINGS_STD_CPP, "C++26");
// Main window settings
mSettings->setValue(SETTINGS_TOOLBARS_MAIN_SHOW, mUI->mToolBarMain->isVisible());
mSettings->setValue(SETTINGS_TOOLBARS_VIEW_SHOW, mUI->mToolBarView->isVisible());
mSettings->setValue(SETTINGS_TOOLBARS_FILTER_SHOW, mUI->mToolBarFilter->isVisible());
if (mUI->mActionEnforceCpp->isChecked())
mSettings->setValue(SETTINGS_ENFORCED_LANGUAGE, Standards::Language::CPP);
else if (mUI->mActionEnforceC->isChecked())
mSettings->setValue(SETTINGS_ENFORCED_LANGUAGE, Standards::Language::C);
else
mSettings->setValue(SETTINGS_ENFORCED_LANGUAGE, Standards::Language::None);
mApplications->saveSettings();
mSettings->setValue(SETTINGS_LANGUAGE, mTranslation->getCurrentLanguage());
mSettings->setValue(SETTINGS_OPEN_PROJECT, mProjectFile ? mProjectFile->getFilename() : QString());
mUI->mResults->saveSettings(mSettings);
}
void MainWindow::doAnalyzeProject(ImportProject p, const bool checkLibrary, const bool checkConfiguration)
{
QPair<bool,Settings> checkSettingsPair = getCppcheckSettings();
if (!checkSettingsPair.first)
return;
Settings& checkSettings = checkSettingsPair.second;
clearResults();
mIsLogfileLoaded = false;
if (mProjectFile) {
std::vector<std::string> v;
const QStringList excluded = mProjectFile->getExcludedPaths();
std::transform(excluded.cbegin(), excluded.cend(), std::back_inserter(v), [](const QString& e) {
return e.toStdString();
});
p.ignorePaths(v);
if (!mProjectFile->getAnalyzeAllVsConfigs()) {
const Platform::Type platform = (Platform::Type) mSettings->value(SETTINGS_CHECKED_PLATFORM, 0).toInt();
std::vector<std::string> configurations;
const QStringList configs = mProjectFile->getVsConfigurations();
std::transform(configs.cbegin(), configs.cend(), std::back_inserter(configurations), [](const QString& e) {
return e.toStdString();
});
p.selectVsConfigurations(platform, configurations);
}
} else {
enableProjectActions(false);
}
mUI->mResults->clear(true);
mThread->clearFiles();
mUI->mResults->checkingStarted(p.fileSettings.size());
QDir inf(mCurrentDirectory);
const QString checkPath = inf.canonicalPath();
setPath(SETTINGS_LAST_CHECK_PATH, checkPath);
checkLockDownUI(); // lock UI while checking
mUI->mResults->setCheckDirectory(checkPath);
checkSettings.force = false;
checkSettings.checkLibrary = checkLibrary;
checkSettings.checkConfiguration = checkConfiguration;
if (mProjectFile)
qDebug() << "Checking project file" << mProjectFile->getFilename();
if (!checkSettings.buildDir.empty()) {
checkSettings.loadSummaries();
std::list<std::string> sourcefiles;
AnalyzerInformation::writeFilesTxt(checkSettings.buildDir, sourcefiles, checkSettings.userDefines, p.fileSettings);
}
//mThread->SetanalyzeProject(true);
if (mProjectFile) {
mThread->setAddonsAndTools(mProjectFile->getAddonsAndTools());
QString clangHeaders = mSettings->value(SETTINGS_VS_INCLUDE_PATHS).toString();
mThread->setClangIncludePaths(clangHeaders.split(";"));
mThread->setSuppressions(mProjectFile->getSuppressions());
}
mThread->setProject(p);
mThread->check(checkSettings);
mUI->mResults->setCheckSettings(checkSettings);
}
void MainWindow::doAnalyzeFiles(const QStringList &files, const bool checkLibrary, const bool checkConfiguration)
{
if (files.isEmpty())
return;
QPair<bool, Settings> checkSettingsPair = getCppcheckSettings();
if (!checkSettingsPair.first)
return;
Settings& checkSettings = checkSettingsPair.second;
clearResults();
mIsLogfileLoaded = false;
FileList pathList;
pathList.addPathList(files);
if (mProjectFile) {
pathList.addExcludeList(mProjectFile->getExcludedPaths());
} else {
enableProjectActions(false);
}
QStringList fileNames = pathList.getFileList();
mUI->mResults->clear(true);
mThread->clearFiles();
if (fileNames.isEmpty()) {
QMessageBox msg(QMessageBox::Warning,
tr("Cppcheck"),
tr("No suitable files found to analyze!"),
QMessageBox::Ok,
this);
msg.exec();
return;
}
mUI->mResults->checkingStarted(fileNames.count());
mThread->setFiles(fileNames);
if (mProjectFile && !checkConfiguration)
mThread->setAddonsAndTools(mProjectFile->getAddonsAndTools());
mThread->setSuppressions(mProjectFile ? mProjectFile->getCheckingSuppressions() : QList<SuppressionList::Suppression>());
QDir inf(mCurrentDirectory);
const QString checkPath = inf.canonicalPath();
setPath(SETTINGS_LAST_CHECK_PATH, checkPath);
checkLockDownUI(); // lock UI while checking
mUI->mResults->setCheckDirectory(checkPath);
checkSettings.checkLibrary = checkLibrary;
checkSettings.checkConfiguration = checkConfiguration;
if (mProjectFile)
qDebug() << "Checking project file" << mProjectFile->getFilename();
if (!checkSettings.buildDir.empty()) {
checkSettings.loadSummaries();
std::list<std::string> sourcefiles;
std::transform(fileNames.cbegin(), fileNames.cend(), std::back_inserter(sourcefiles), [](const QString& s) {
return s.toStdString();
});
AnalyzerInformation::writeFilesTxt(checkSettings.buildDir, sourcefiles, checkSettings.userDefines, {});
}
mThread->setCheckFiles(true);
mThread->check(checkSettings);
mUI->mResults->setCheckSettings(checkSettings);
}
void MainWindow::analyzeCode(const QString& code, const QString& filename)
{
const QPair<bool, Settings>& checkSettingsPair = getCppcheckSettings();
if (!checkSettingsPair.first)
return;
const Settings& checkSettings = checkSettingsPair.second;
// Initialize dummy ThreadResult as ErrorLogger
ThreadResult result;
result.setFiles(QStringList(filename));
connect(&result, SIGNAL(progress(int,QString)),
mUI->mResults, SLOT(progress(int,QString)));
connect(&result, SIGNAL(error(ErrorItem)),
mUI->mResults, SLOT(error(ErrorItem)));
connect(&result, SIGNAL(log(QString)),
mUI->mResults, SLOT(log(QString)));
connect(&result, SIGNAL(debugError(ErrorItem)),
mUI->mResults, SLOT(debugError(ErrorItem)));
// Create CppCheck instance
CppCheck cppcheck(result, true, nullptr);
cppcheck.settings() = checkSettings;
// Check
checkLockDownUI();
clearResults();
mUI->mResults->checkingStarted(1);
cppcheck.check(FileWithDetails(filename.toStdString()), code.toStdString());
analysisDone();
// Expand results
if (mUI->mResults->hasVisibleResults())
mUI->mResults->expandAllResults();
}
QStringList MainWindow::selectFilesToAnalyze(QFileDialog::FileMode mode)
{
if (mProjectFile) {
QMessageBox msgBox(this);
msgBox.setWindowTitle(tr("Cppcheck"));
const QString msg(tr("You must close the project file before selecting new files or directories!"));
msgBox.setText(msg);
msgBox.setIcon(QMessageBox::Critical);
msgBox.exec();
return QStringList();
}
QStringList selected;
// NOTE: we use QFileDialog::getOpenFileNames() and
// QFileDialog::getExistingDirectory() because they show native Windows
// selection dialog which is a lot more usable than Qt:s own dialog.
if (mode == QFileDialog::ExistingFiles) {
QMap<QString,QString> filters;
filters[tr("C/C++ Source")] = FileList::getDefaultFilters().join(" ");
filters[tr("Compile database")] = compile_commands_json;
filters[tr("Visual Studio")] = "*.sln *.vcxproj";
filters[tr("Borland C++ Builder 6")] = "*.bpr";
QString lastFilter = mSettings->value(SETTINGS_LAST_ANALYZE_FILES_FILTER).toString();
selected = QFileDialog::getOpenFileNames(this,
tr("Select files to analyze"),
getPath(SETTINGS_LAST_CHECK_PATH),
toFilterString(filters),
&lastFilter);
mSettings->setValue(SETTINGS_LAST_ANALYZE_FILES_FILTER, lastFilter);
if (selected.isEmpty())
mCurrentDirectory.clear();
else {
QFileInfo inf(selected[0]);
mCurrentDirectory = inf.absolutePath();
}
formatAndSetTitle();
} else if (mode == QFileDialog::Directory) {
QString dir = QFileDialog::getExistingDirectory(this,
tr("Select directory to analyze"),
getPath(SETTINGS_LAST_CHECK_PATH));
if (!dir.isEmpty()) {
qDebug() << "Setting current directory to: " << dir;
mCurrentDirectory = dir;
selected.append(dir);
dir = QDir::toNativeSeparators(dir);
formatAndSetTitle(dir);
}
}
if (!mCurrentDirectory.isEmpty())
setPath(SETTINGS_LAST_CHECK_PATH, mCurrentDirectory);
return selected;
}
void MainWindow::analyzeFiles()
{
Settings::terminate(false);
QStringList selected = selectFilesToAnalyze(QFileDialog::ExistingFiles);
const QString file0 = (!selected.empty() ? selected[0].toLower() : QString());
if (file0.endsWith(".sln")
|| file0.endsWith(".vcxproj")
|| file0.endsWith(compile_commands_json)
|| file0.endsWith(".bpr")) {
ImportProject p;
p.import(selected[0].toStdString());
if (file0.endsWith(".sln")) {
QStringList configs;
for (std::list<FileSettings>::const_iterator it = p.fileSettings.cbegin(); it != p.fileSettings.cend(); ++it) {
const QString cfg(QString::fromStdString(it->cfg));
if (!configs.contains(cfg))
configs.push_back(cfg);
}
configs.sort();
bool ok = false;
const QString cfg = QInputDialog::getItem(this, tr("Select configuration"), tr("Select the configuration that will be analyzed"), configs, 0, false, &ok);
if (!ok)
return;
p.ignoreOtherConfigs(cfg.toStdString());
}
doAnalyzeProject(p);
return;
}
doAnalyzeFiles(selected);
}
void MainWindow::analyzeDirectory()
{
QStringList dir = selectFilesToAnalyze(QFileDialog::Directory);
if (dir.isEmpty())
return;
QDir checkDir(dir[0]);
QStringList filters;
filters << "*.cppcheck";
checkDir.setFilter(QDir::Files | QDir::Readable);
checkDir.setNameFilters(filters);
QStringList projFiles = checkDir.entryList();
if (!projFiles.empty()) {
if (projFiles.size() == 1) {
// If one project file found, suggest loading it
QMessageBox msgBox(this);
msgBox.setWindowTitle(tr("Cppcheck"));
const QString msg(tr("Found project file: %1\n\nDo you want to "
"load this project file instead?").arg(projFiles[0]));
msgBox.setText(msg);
msgBox.setIcon(QMessageBox::Warning);
msgBox.addButton(QMessageBox::Yes);
msgBox.addButton(QMessageBox::No);
msgBox.setDefaultButton(QMessageBox::Yes);
const int dlgResult = msgBox.exec();
if (dlgResult == QMessageBox::Yes) {
QString path = checkDir.canonicalPath();
if (!path.endsWith("/"))
path += "/";
path += projFiles[0];
loadProjectFile(path);
} else {
doAnalyzeFiles(dir);
}
} else {
// If multiple project files found inform that there are project
// files also available.
QMessageBox msgBox(this);
msgBox.setWindowTitle(tr("Cppcheck"));
const QString msg(tr("Found project files from the directory.\n\n"
"Do you want to proceed analysis without "
"using any of these project files?"));
msgBox.setText(msg);
msgBox.setIcon(QMessageBox::Warning);
msgBox.addButton(QMessageBox::Yes);
msgBox.addButton(QMessageBox::No);
msgBox.setDefaultButton(QMessageBox::Yes);
const int dlgResult = msgBox.exec();
if (dlgResult == QMessageBox::Yes) {
doAnalyzeFiles(dir);
}
}
} else {
doAnalyzeFiles(dir);
}
}
void MainWindow::addIncludeDirs(const QStringList &includeDirs, Settings &result)
{
for (const QString& dir : includeDirs) {
QString incdir;
if (!QDir::isAbsolutePath(dir))
incdir = mCurrentDirectory + "/";
incdir += dir;
incdir = QDir::cleanPath(incdir);
// include paths must end with '/'
if (!incdir.endsWith("/"))
incdir += "/";
result.includePaths.push_back(incdir.toStdString());
}
}
Library::Error MainWindow::loadLibrary(Library &library, const QString &filename)
{
Library::Error ret;
// Try to load the library from the project folder..
if (mProjectFile) {
QString path = QFileInfo(mProjectFile->getFilename()).canonicalPath();
QString libpath = path+"/"+filename;
qDebug().noquote() << "looking for library '" + libpath + "'";
ret = library.load(nullptr, libpath.toLatin1());
if (ret.errorcode != Library::ErrorCode::FILE_NOT_FOUND)
return ret;
}
// Try to load the library from the application folder..
const QString appPath = QFileInfo(QCoreApplication::applicationFilePath()).canonicalPath();
QString libpath = appPath+"/"+filename;
qDebug().noquote() << "looking for library '" + libpath + "'";
ret = library.load(nullptr, libpath.toLatin1());
if (ret.errorcode != Library::ErrorCode::FILE_NOT_FOUND)
return ret;
libpath = appPath+"/cfg/"+filename;
qDebug().noquote() << "looking for library '" + libpath + "'";
ret = library.load(nullptr, libpath.toLatin1());
if (ret.errorcode != Library::ErrorCode::FILE_NOT_FOUND)
return ret;
#ifdef FILESDIR
// Try to load the library from FILESDIR/cfg..
const QString filesdir = FILESDIR;
if (!filesdir.isEmpty()) {
libpath = filesdir+"/cfg/"+filename;
qDebug().noquote() << "looking for library '" + libpath + "'";
ret = library.load(nullptr, libpath.toLatin1());
if (ret.errorcode != Library::ErrorCode::FILE_NOT_FOUND)
return ret;
libpath = filesdir+"/"+filename;
qDebug().noquote() << "looking for library '" + libpath + "'";
ret = library.load(nullptr, libpath.toLatin1());
if (ret.errorcode != Library::ErrorCode::FILE_NOT_FOUND)
return ret;
}
#endif
// Try to load the library from the cfg subfolder..
const QString datadir = getDataDir();
if (!datadir.isEmpty()) {
libpath = datadir+"/"+filename;
qDebug().noquote() << "looking for library '" + libpath + "'";
ret = library.load(nullptr, libpath.toLatin1());
if (ret.errorcode != Library::ErrorCode::FILE_NOT_FOUND)
return ret;
libpath = datadir+"/cfg/"+filename;
qDebug().noquote() << "looking for library '" + libpath + "'";
ret = library.load(nullptr, libpath.toLatin1());
if (ret.errorcode != Library::ErrorCode::FILE_NOT_FOUND)
return ret;
}
qDebug().noquote() << "library not found: '" + filename + "'";
return ret;
}
bool MainWindow::tryLoadLibrary(Library &library, const QString& filename)
{
const Library::Error error = loadLibrary(library, filename);
if (error.errorcode != Library::ErrorCode::OK) {
if (error.errorcode == Library::ErrorCode::UNKNOWN_ELEMENT) {
QMessageBox::information(this, tr("Information"), tr("The library '%1' contains unknown elements:\n%2").arg(filename).arg(error.reason.c_str()));
return true;
}
QString errmsg;
switch (error.errorcode) {
case Library::ErrorCode::OK:
break;
case Library::ErrorCode::FILE_NOT_FOUND:
errmsg = tr("File not found");
break;
case Library::ErrorCode::BAD_XML:
errmsg = tr("Bad XML");
break;
case Library::ErrorCode::MISSING_ATTRIBUTE:
errmsg = tr("Missing attribute");
break;
case Library::ErrorCode::BAD_ATTRIBUTE_VALUE:
errmsg = tr("Bad attribute value");
break;
case Library::ErrorCode::UNSUPPORTED_FORMAT:
errmsg = tr("Unsupported format");
break;
case Library::ErrorCode::DUPLICATE_PLATFORM_TYPE:
errmsg = tr("Duplicate platform type");
break;
case Library::ErrorCode::PLATFORM_TYPE_REDEFINED:
errmsg = tr("Platform type redefined");
break;
case Library::ErrorCode::DUPLICATE_DEFINE:
errmsg = tr("Duplicate define");
break;
case Library::ErrorCode::UNKNOWN_ELEMENT:
errmsg = tr("Unknown element");
break;
default:
errmsg = tr("Unknown issue");
break;
}
if (!error.reason.empty())
errmsg += " '" + QString::fromStdString(error.reason) + "'";
QMessageBox::information(this, tr("Information"), tr("Failed to load the selected library '%1'.\n%2").arg(filename).arg(errmsg));
return false;
}
return true;
}
QString MainWindow::loadAddon(Settings &settings, const QString &filesDir, const QString &pythonCmd, const QString& addon)
{
const QString addonFilePath = fromNativePath(ProjectFile::getAddonFilePath(filesDir, addon));
if (addonFilePath.isEmpty())
return tr("File not found: '%1'").arg(addon);
picojson::object obj;
obj["script"] = picojson::value(addonFilePath.toStdString());
if (!pythonCmd.isEmpty())
obj["python"] = picojson::value(pythonCmd.toStdString());
if (!isCppcheckPremium() && addon == "misra") {
const QString misraFile = fromNativePath(mSettings->value(SETTINGS_MISRA_FILE).toString());
if (!misraFile.isEmpty()) {
QString arg;
picojson::array arr;
if (misraFile.endsWith(".pdf", Qt::CaseInsensitive))
arg = "--misra-pdf=" + misraFile;
else
arg = "--rule-texts=" + misraFile;
arr.emplace_back(arg.toStdString());
obj["args"] = picojson::value(arr);
}
}
const std::string& json_str = picojson::value(obj).serialize();
AddonInfo addonInfo;
const std::string errmsg = addonInfo.getAddonInfo(json_str, settings.exename);
if (!errmsg.empty())
return tr("Failed to load/setup addon %1: %2").arg(addon, QString::fromStdString(errmsg));
settings.addonInfos.emplace_back(std::move(addonInfo));
settings.addons.emplace(json_str);
return "";
}
QPair<bool,Settings> MainWindow::getCppcheckSettings()
{
saveSettings(); // Save settings
Settings::terminate(true);
Settings result;
result.exename = QCoreApplication::applicationFilePath().toStdString();
// default to --check-level=normal for GUI for now
result.setCheckLevel(Settings::CheckLevel::normal);
const bool std = tryLoadLibrary(result.library, "std.cfg");
if (!std) {
QMessageBox::critical(this, tr("Error"), tr("Failed to load %1. Your Cppcheck installation is broken. You can use --data-dir=<directory> at the command line to specify where this file is located. Please note that --data-dir is supposed to be used by installation scripts and therefore the GUI does not start when it is used, all that happens is that the setting is configured.\n\nAnalysis is aborted.").arg("std.cfg"));
return {false, {}};
}
const QString filesDir(getDataDir());
const QString pythonCmd = fromNativePath(mSettings->value(SETTINGS_PYTHON_PATH).toString());
{
const QString cfgErr = QString::fromStdString(Settings::loadCppcheckCfg(result, result.supprs));
if (!cfgErr.isEmpty()) {
QMessageBox::critical(this, tr("Error"), tr("Failed to load %1 - %2\n\nAnalysis is aborted.").arg("cppcheck.cfg").arg(cfgErr));
return {false, {}};
}
const auto cfgAddons = result.addons;
result.addons.clear();
for (const std::string& addon : cfgAddons) {
// TODO: support addons which are a script and not a file
const QString addonError = loadAddon(result, filesDir, pythonCmd, QString::fromStdString(addon));
if (!addonError.isEmpty()) {
QMessageBox::critical(this, tr("Error"), tr("%1\n\nAnalysis is aborted.").arg(addonError));
return {false, {}};
}
}
}
// If project file loaded, read settings from it
if (mProjectFile) {
QStringList dirs = mProjectFile->getIncludeDirs();
addIncludeDirs(dirs, result);
result.inlineSuppressions = mProjectFile->getInlineSuppression();
const QStringList defines = mProjectFile->getDefines();
for (const QString& define : defines) {
if (!result.userDefines.empty())
result.userDefines += ";";
result.userDefines += define.toStdString();
}
result.clang = mProjectFile->clangParser;
const QStringList undefines = mProjectFile->getUndefines();
for (const QString& undefine : undefines)
result.userUndefs.insert(undefine.toStdString());
const QStringList libraries = mProjectFile->getLibraries();
for (const QString& library : libraries) {
result.libraries.emplace_back(library.toStdString());
const QString filename = library + ".cfg";
tryLoadLibrary(result.library, filename);
}
for (const SuppressionList::Suppression &suppression : mProjectFile->getCheckingSuppressions()) {
result.supprs.nomsg.addSuppression(suppression);
}
// Only check the given -D configuration
if (!defines.isEmpty())
result.maxConfigs = 1;
// If importing a project, only check the given configuration
if (!mProjectFile->getImportProject().isEmpty())
result.checkAllConfigurations = false;
const QString &buildDir = fromNativePath(mProjectFile->getBuildDir());
if (!buildDir.isEmpty()) {
if (QDir(buildDir).isAbsolute()) {
result.buildDir = buildDir.toStdString();
} else {
QString prjpath = QFileInfo(mProjectFile->getFilename()).absolutePath();
result.buildDir = (prjpath + '/' + buildDir).toStdString();
}
}
const QString platform = mProjectFile->getPlatform();
if (platform.endsWith(".xml")) {
const QString applicationFilePath = QCoreApplication::applicationFilePath();
result.platform.loadFromFile(applicationFilePath.toStdString().c_str(), platform.toStdString());
} else {
for (int i = Platform::Type::Native; i <= Platform::Type::Unix64; i++) {
const auto p = (Platform::Type)i;
if (platform == Platform::toString(p)) {
result.platform.set(p);
break;
}
}
}
result.maxCtuDepth = mProjectFile->getMaxCtuDepth();
result.maxTemplateRecursion = mProjectFile->getMaxTemplateRecursion();
switch (mProjectFile->getCheckLevel()) {
case ProjectFile::CheckLevel::reduced:
result.setCheckLevel(Settings::CheckLevel::reduced);
break;
case ProjectFile::CheckLevel::normal:
result.setCheckLevel(Settings::CheckLevel::normal);
break;
case ProjectFile::CheckLevel::exhaustive:
result.setCheckLevel(Settings::CheckLevel::exhaustive);
break;
};
result.checkHeaders = mProjectFile->getCheckHeaders();
result.checkUnusedTemplates = mProjectFile->getCheckUnusedTemplates();
result.safeChecks.classes = mProjectFile->safeChecks.classes;
result.safeChecks.externalFunctions = mProjectFile->safeChecks.externalFunctions;
result.safeChecks.internalFunctions = mProjectFile->safeChecks.internalFunctions;
result.safeChecks.externalVariables = mProjectFile->safeChecks.externalVariables;
for (const QString& s : mProjectFile->getCheckUnknownFunctionReturn())
result.checkUnknownFunctionReturn.insert(s.toStdString());
for (const QString& addon : mProjectFile->getAddons()) {
const QString addonError = loadAddon(result, filesDir, pythonCmd, addon);
if (!addonError.isEmpty()) {
QMessageBox::critical(this, tr("Error"), tr("%1\n\nAnalysis is aborted.").arg(addonError));
return {false, {}};
}
}
if (isCppcheckPremium()) {
QString premiumArgs;
if (mProjectFile->getBughunting())
premiumArgs += " --bughunting";
if (mProjectFile->getCertIntPrecision() > 0)
premiumArgs += " --cert-c-int-precision=" + QString::number(mProjectFile->getCertIntPrecision());
for (const QString& c: mProjectFile->getCodingStandards())
premiumArgs += " --" + c;
if (!premiumArgs.contains("misra") && mProjectFile->getAddons().contains("misra"))
premiumArgs += " --misra-c-2012";
result.premiumArgs = premiumArgs.mid(1).toStdString();
result.setMisraRuleTexts(CheckThread::executeCommand);
}
}
else
result.inlineSuppressions = mSettings->value(SETTINGS_INLINE_SUPPRESSIONS, false).toBool();
// Include directories (and files) are searched in listed order.
// Global include directories must be added AFTER the per project include
// directories so per project include directories can override global ones.
const QString globalIncludes = mSettings->value(SETTINGS_GLOBAL_INCLUDE_PATHS).toString();
if (!globalIncludes.isEmpty()) {
QStringList includes = globalIncludes.split(";");
addIncludeDirs(includes, result);
}
result.severity.enable(Severity::warning);
result.severity.enable(Severity::style);
result.severity.enable(Severity::performance);
result.severity.enable(Severity::portability);
result.severity.enable(Severity::information);
result.checks.enable(Checks::missingInclude);
if (!result.buildDir.empty())
result.checks.enable(Checks::unusedFunction);
result.debugwarnings = mSettings->value(SETTINGS_SHOW_DEBUG_WARNINGS, false).toBool();
result.quiet = false;
result.verbose = true;
result.force = mSettings->value(SETTINGS_CHECK_FORCE, 1).toBool();
result.xml = false;
result.jobs = mSettings->value(SETTINGS_CHECK_THREADS, 1).toInt();
result.certainty.setEnabled(Certainty::inconclusive, mSettings->value(SETTINGS_INCONCLUSIVE_ERRORS, false).toBool());
if (!mProjectFile || result.platform.type == Platform::Type::Unspecified)
result.platform.set((Platform::Type) mSettings->value(SETTINGS_CHECKED_PLATFORM, 0).toInt());
result.standards.setCPP(mSettings->value(SETTINGS_STD_CPP, QString()).toString().toStdString());
result.standards.setC(mSettings->value(SETTINGS_STD_C, QString()).toString().toStdString());
result.enforcedLang = (Standards::Language)mSettings->value(SETTINGS_ENFORCED_LANGUAGE, 0).toInt();
result.jobs = std::max(result.jobs, 1u);
Settings::terminate(false);
return {true, std::move(result)};
}
void MainWindow::analysisDone()
{
if (mExiting) {
close();
return;
}
mUI->mResults->checkingFinished();
enableCheckButtons(true);
mUI->mActionSettings->setEnabled(true);
mUI->mActionOpenXML->setEnabled(true);
if (mProjectFile) {
enableProjectActions(true);
} else if (mIsLogfileLoaded) {
mUI->mActionReanalyzeModified->setEnabled(false);
mUI->mActionReanalyzeAll->setEnabled(false);
}
enableProjectOpenActions(true);
mPlatformActions->setEnabled(true);
mCStandardActions->setEnabled(true);
mCppStandardActions->setEnabled(true);
mSelectLanguageActions->setEnabled(true);
mUI->mActionPosix->setEnabled(true);
if (mScratchPad)
mScratchPad->setEnabled(true);
mUI->mActionViewStats->setEnabled(true);
if (mProjectFile && !mProjectFile->getBuildDir().isEmpty()) {
const QString prjpath = QFileInfo(mProjectFile->getFilename()).absolutePath();
const QString buildDir = prjpath + '/' + mProjectFile->getBuildDir();
if (QDir(buildDir).exists()) {
mUI->mResults->saveStatistics(buildDir + "/statistics.txt");
mUI->mResults->updateFromOldReport(buildDir + "/lastResults.xml");
mUI->mResults->save(buildDir + "/lastResults.xml", Report::XMLV2, mCppcheckCfgProductName);
}
}
enableResultsButtons();
for (QAction* recentProjectAct : mRecentProjectActs) {
if (recentProjectAct != nullptr)
recentProjectAct->setEnabled(true);
}
// Notify user - if the window is not active - that check is ready
QApplication::alert(this, 3000);
if (mSettings->value(SETTINGS_SHOW_STATISTICS, false).toBool())
showStatistics();
}
void MainWindow::checkLockDownUI()
{
enableCheckButtons(false);
mUI->mActionSettings->setEnabled(false);
mUI->mActionOpenXML->setEnabled(false);
enableProjectActions(false);
enableProjectOpenActions(false);
mPlatformActions->setEnabled(false);
mCStandardActions->setEnabled(false);
mCppStandardActions->setEnabled(false);
mSelectLanguageActions->setEnabled(false);
mUI->mActionPosix->setEnabled(false);
if (mScratchPad)
mScratchPad->setEnabled(false);
for (QAction* recentProjectAct : mRecentProjectActs) {
if (recentProjectAct != nullptr)
recentProjectAct->setEnabled(false);
}
}
void MainWindow::programSettings()
{
SettingsDialog dialog(mApplications, mTranslation, isCppcheckPremium(), this);
if (dialog.exec() == QDialog::Accepted) {
dialog.saveSettingValues();
mSettings->sync();
mUI->mResults->updateSettings(dialog.showFullPath(),
dialog.saveFullPath(),
dialog.saveAllErrors(),
dialog.showNoErrorsMessage(),
dialog.showErrorId(),
dialog.showInconclusive());
mUI->mResults->updateStyleSetting(mSettings);
const QString newLang = mSettings->value(SETTINGS_LANGUAGE, "en").toString();
setLanguage(newLang);
}
}
void MainWindow::reAnalyzeModified()
{
reAnalyze(false);
}
void MainWindow::reAnalyzeAll()
{
if (mProjectFile)
analyzeProject(mProjectFile, QStringList());
else
reAnalyze(true);
}
void MainWindow::checkLibrary()
{
if (mProjectFile)
analyzeProject(mProjectFile, QStringList(), true);
}
void MainWindow::checkConfiguration()
{
if (mProjectFile)
analyzeProject(mProjectFile, QStringList(), false, true);
}
void MainWindow::reAnalyzeSelected(const QStringList& files)
{
if (files.empty())
return;
if (mThread->isChecking())
return;
if (mProjectFile) {
// Clear details, statistics and progress
mUI->mResults->clear(false);
for (int i = 0; i < files.size(); ++i)
mUI->mResults->clearRecheckFile(files[i]);
analyzeProject(mProjectFile, files);
return;
}
const QPair<bool, Settings> checkSettingsPair = getCppcheckSettings();
if (!checkSettingsPair.first)
return;
const Settings& checkSettings = checkSettingsPair.second;
// Clear details, statistics and progress
mUI->mResults->clear(false);
for (int i = 0; i < files.size(); ++i)
mUI->mResults->clearRecheckFile(files[i]);
mCurrentDirectory = mUI->mResults->getCheckDirectory();
FileList pathList;
pathList.addPathList(files);
if (mProjectFile)
pathList.addExcludeList(mProjectFile->getExcludedPaths());
QStringList fileNames = pathList.getFileList();
checkLockDownUI(); // lock UI while checking
mUI->mResults->checkingStarted(fileNames.size());
mThread->setCheckFiles(fileNames);
// Saving last check start time, otherwise unchecked modified files will not be
// considered in "Modified Files Check" performed after "Selected Files Check"
// TODO: Should we store per file CheckStartTime?
QDateTime saveCheckStartTime = mThread->getCheckStartTime();
mThread->check(checkSettings);
mUI->mResults->setCheckSettings(checkSettings);
mThread->setCheckStartTime(std::move(saveCheckStartTime));
}
void MainWindow::reAnalyze(bool all)
{
const QStringList files = mThread->getReCheckFiles(all);
if (files.empty())
return;
const QPair<bool, Settings>& checkSettingsPair = getCppcheckSettings();
if (!checkSettingsPair.first)
return;
const Settings& checkSettings = checkSettingsPair.second;
// Clear details, statistics and progress
mUI->mResults->clear(all);
// Clear results for changed files
for (int i = 0; i < files.size(); ++i)
mUI->mResults->clear(files[i]);
checkLockDownUI(); // lock UI while checking
mUI->mResults->checkingStarted(files.size());
if (mProjectFile)
qDebug() << "Rechecking project file" << mProjectFile->getFilename();
mThread->setCheckFiles(all);
mThread->check(checkSettings);
mUI->mResults->setCheckSettings(checkSettings);
}
void MainWindow::clearResults()
{
if (mProjectFile && !mProjectFile->getBuildDir().isEmpty()) {
QDir dir(QFileInfo(mProjectFile->getFilename()).absolutePath() + '/' + mProjectFile->getBuildDir());
for (const QString& f: dir.entryList(QDir::Files)) {
if (!f.endsWith("files.txt")) {
static const QRegularExpression rx("^.*.s[0-9]+$");
if (!rx.match(f).hasMatch())
dir.remove(f);
}
}
}
mUI->mResults->clear(true);
Q_ASSERT(false == mUI->mResults->hasResults());
enableResultsButtons();
}
void MainWindow::openResults()
{
if (mUI->mResults->hasResults()) {
QMessageBox msgBox(this);
msgBox.setWindowTitle(tr("Cppcheck"));
const QString msg(tr("Current results will be cleared.\n\n"
"Opening a new XML file will clear current results.\n"
"Do you want to proceed?"));
msgBox.setText(msg);
msgBox.setIcon(QMessageBox::Warning);
msgBox.addButton(QMessageBox::Yes);
msgBox.addButton(QMessageBox::No);
msgBox.setDefaultButton(QMessageBox::Yes);
const int dlgResult = msgBox.exec();
if (dlgResult == QMessageBox::No) {
return;
}
}
QString selectedFilter;
const QString filter(tr("XML files (*.xml)"));
QString selectedFile = QFileDialog::getOpenFileName(this,
tr("Open the report file"),
getPath(SETTINGS_LAST_RESULT_PATH),
filter,
&selectedFilter);
if (!selectedFile.isEmpty()) {
loadResults(selectedFile);
}
}
void MainWindow::loadResults(const QString &selectedFile)
{
if (selectedFile.isEmpty())
return;
if (mProjectFile)
closeProjectFile();
mIsLogfileLoaded = true;
mUI->mResults->clear(true);
mUI->mActionReanalyzeModified->setEnabled(false);
mUI->mActionReanalyzeAll->setEnabled(false);
mUI->mResults->readErrorsXml(selectedFile);
setPath(SETTINGS_LAST_RESULT_PATH, selectedFile);
formatAndSetTitle(selectedFile);
}
void MainWindow::loadResults(const QString &selectedFile, const QString &sourceDirectory)
{
loadResults(selectedFile);
mUI->mResults->setCheckDirectory(sourceDirectory);
}
void MainWindow::enableCheckButtons(bool enable)
{
mUI->mActionStop->setEnabled(!enable);
mUI->mActionAnalyzeFiles->setEnabled(enable);
if (mProjectFile) {
mUI->mActionReanalyzeModified->setEnabled(enable);
mUI->mActionReanalyzeAll->setEnabled(enable);
} else if (!enable || mThread->hasPreviousFiles()) {
mUI->mActionReanalyzeModified->setEnabled(enable);
mUI->mActionReanalyzeAll->setEnabled(enable);
}
mUI->mActionAnalyzeDirectory->setEnabled(enable);
if (isCppcheckPremium()) {
mUI->mActionComplianceReport->setEnabled(enable && mProjectFile && (mProjectFile->getAddons().contains("misra") || !mProjectFile->getCodingStandards().empty()));
}
}
void MainWindow::enableResultsButtons()
{
const bool enabled = mUI->mResults->hasResults();
mUI->mActionClearResults->setEnabled(enabled);
mUI->mActionSave->setEnabled(enabled);
mUI->mActionPrint->setEnabled(enabled);
mUI->mActionPrintPreview->setEnabled(enabled);
}
void MainWindow::showStyle(bool checked)
{
mUI->mResults->showResults(ShowTypes::ShowStyle, checked);
}
void MainWindow::showErrors(bool checked)
{
mUI->mResults->showResults(ShowTypes::ShowErrors, checked);
}
void MainWindow::showWarnings(bool checked)
{
mUI->mResults->showResults(ShowTypes::ShowWarnings, checked);
}
void MainWindow::showPortability(bool checked)
{
mUI->mResults->showResults(ShowTypes::ShowPortability, checked);
}
void MainWindow::showPerformance(bool checked)
{
mUI->mResults->showResults(ShowTypes::ShowPerformance, checked);
}
void MainWindow::showInformation(bool checked)
{
mUI->mResults->showResults(ShowTypes::ShowInformation, checked);
}
void MainWindow::checkAll()
{
toggleAllChecked(true);
}
void MainWindow::uncheckAll()
{
toggleAllChecked(false);
}
void MainWindow::closeEvent(QCloseEvent *event)
{
// Check that we aren't checking files
if (!mThread->isChecking()) {
saveSettings();
event->accept();
} else {
const QString text(tr("Analyzer is running.\n\n" \
"Do you want to stop the analysis and exit Cppcheck?"));
QMessageBox msg(QMessageBox::Warning,
tr("Cppcheck"),
text,
QMessageBox::Yes | QMessageBox::No,
this);
msg.setDefaultButton(QMessageBox::No);
const int rv = msg.exec();
if (rv == QMessageBox::Yes) {
// This isn't really very clean way to close threads but since the app is
// exiting it doesn't matter.
mThread->stop();
saveSettings();
mExiting = true;
}
event->ignore();
}
}
void MainWindow::toggleAllChecked(bool checked)
{
mUI->mActionShowStyle->setChecked(checked);
showStyle(checked);
mUI->mActionShowErrors->setChecked(checked);
showErrors(checked);
mUI->mActionShowWarnings->setChecked(checked);
showWarnings(checked);
mUI->mActionShowPortability->setChecked(checked);
showPortability(checked);
mUI->mActionShowPerformance->setChecked(checked);
showPerformance(checked);
mUI->mActionShowInformation->setChecked(checked);
showInformation(checked);
}
void MainWindow::about()
{
if (!mCppcheckCfgAbout.isEmpty()) {
QMessageBox msg(QMessageBox::Information,
tr("About"),
mCppcheckCfgAbout,
QMessageBox::Ok,
this);
msg.exec();
}
else {
auto *dlg = new AboutDialog(CppCheck::version(), CppCheck::extraVersion(), this);
dlg->exec();
}
}
void MainWindow::showLicense()
{
auto *dlg = new FileViewDialog(":COPYING", tr("License"), this);
dlg->resize(570, 400);
dlg->exec();
}
void MainWindow::showAuthors()
{
auto *dlg = new FileViewDialog(":AUTHORS", tr("Authors"), this);
dlg->resize(350, 400);
dlg->exec();
}
void MainWindow::performSelectedFilesCheck(const QStringList &selectedFilesList)
{
reAnalyzeSelected(selectedFilesList);
}
void MainWindow::save()
{
QString selectedFilter;
const QString filter(tr("XML files (*.xml);;Text files (*.txt);;CSV files (*.csv)"));
QString selectedFile = QFileDialog::getSaveFileName(this,
tr("Save the report file"),
getPath(SETTINGS_LAST_RESULT_PATH),
filter,
&selectedFilter);
if (!selectedFile.isEmpty()) {
Report::Type type = Report::TXT;
if (selectedFilter == tr("XML files (*.xml)")) {
type = Report::XMLV2;
if (!selectedFile.endsWith(".xml", Qt::CaseInsensitive))
selectedFile += ".xml";
} else if (selectedFilter == tr("Text files (*.txt)")) {
type = Report::TXT;
if (!selectedFile.endsWith(".txt", Qt::CaseInsensitive))
selectedFile += ".txt";
} else if (selectedFilter == tr("CSV files (*.csv)")) {
type = Report::CSV;
if (!selectedFile.endsWith(".csv", Qt::CaseInsensitive))
selectedFile += ".csv";
} else {
if (selectedFile.endsWith(".xml", Qt::CaseInsensitive))
type = Report::XMLV2;
else if (selectedFile.endsWith(".txt", Qt::CaseInsensitive))
type = Report::TXT;
else if (selectedFile.endsWith(".csv", Qt::CaseInsensitive))
type = Report::CSV;
}
mUI->mResults->save(selectedFile, type, mCppcheckCfgProductName);
setPath(SETTINGS_LAST_RESULT_PATH, selectedFile);
}
}
void MainWindow::complianceReport()
{
if (!mUI->mResults->isSuccess()) {
QMessageBox m(QMessageBox::Critical,
"Cppcheck",
tr("Cannot generate a compliance report right now, an analysis must finish successfully. Try to reanalyze the code and ensure there are no critical errors."),
QMessageBox::Ok,
this);
m.exec();
return;
}
QTemporaryFile tempResults;
tempResults.open();
tempResults.close();
mUI->mResults->save(tempResults.fileName(), Report::XMLV2, mCppcheckCfgProductName);
ComplianceReportDialog dlg(mProjectFile, tempResults.fileName(), mUI->mResults->getStatistics()->getCheckersReport());
dlg.exec();
}
void MainWindow::resultsAdded()
{}
void MainWindow::toggleMainToolBar()
{
mUI->mToolBarMain->setVisible(mUI->mActionToolBarMain->isChecked());
}
void MainWindow::toggleViewToolBar()
{
mUI->mToolBarView->setVisible(mUI->mActionToolBarView->isChecked());
}
void MainWindow::toggleFilterToolBar()
{
mUI->mToolBarFilter->setVisible(mUI->mActionToolBarFilter->isChecked());
mLineEditFilter->clear(); // Clearing the filter also disables filtering
}
void MainWindow::formatAndSetTitle(const QString &text)
{
QString nameWithVersion = QString("Cppcheck %1").arg(CppCheck::version());
QString extraVersion = CppCheck::extraVersion();
if (!extraVersion.isEmpty()) {
nameWithVersion += " (" + extraVersion + ")";
}
if (!mCppcheckCfgProductName.isEmpty())
nameWithVersion = mCppcheckCfgProductName;
QString title;
if (text.isEmpty())
title = nameWithVersion;
else
title = QString("%1 - %2").arg(nameWithVersion, text);
setWindowTitle(title);
}
void MainWindow::setLanguage(const QString &code)
{
const QString currentLang = mTranslation->getCurrentLanguage();
if (currentLang == code)
return;
if (mTranslation->setLanguage(code)) {
//Translate everything that is visible here
mUI->retranslateUi(this);
mUI->mResults->translate();
mLineEditFilter->setPlaceholderText(QCoreApplication::translate("MainWindow", "Quick Filter:"));
if (mProjectFile)
formatAndSetTitle(tr("Project:") + ' ' + mProjectFile->getFilename());
if (mScratchPad)
mScratchPad->translate();
}
}
void MainWindow::aboutToShowViewMenu()
{
mUI->mActionToolBarMain->setChecked(mUI->mToolBarMain->isVisible());
mUI->mActionToolBarView->setChecked(mUI->mToolBarView->isVisible());
mUI->mActionToolBarFilter->setChecked(mUI->mToolBarFilter->isVisible());
}
void MainWindow::stopAnalysis()
{
mThread->stop();
mUI->mResults->stopAnalysis();
mUI->mResults->disableProgressbar();
const QString &lastResults = getLastResults();
if (!lastResults.isEmpty()) {
mUI->mResults->updateFromOldReport(lastResults);
}
}
void MainWindow::openHelpContents()
{
openOnlineHelp();
}
void MainWindow::openOnlineHelp()
{
auto *helpDialog = new HelpDialog;
helpDialog->showMaximized();
}
void MainWindow::openProjectFile()
{
const QString filter = tr("Project files (*.cppcheck);;All files(*.*)");
const QString filepath = QFileDialog::getOpenFileName(this,
tr("Select Project File"),
getPath(SETTINGS_LAST_PROJECT_PATH),
filter);
if (!filepath.isEmpty()) {
const QFileInfo fi(filepath);
if (fi.exists() && fi.isFile() && fi.isReadable()) {
setPath(SETTINGS_LAST_PROJECT_PATH, filepath);
loadProjectFile(filepath);
}
}
}
void MainWindow::showScratchpad()
{
if (!mScratchPad)
mScratchPad = new ScratchPad(*this);
mScratchPad->show();
if (!mScratchPad->isActiveWindow())
mScratchPad->activateWindow();
}
void MainWindow::loadProjectFile(const QString &filePath)
{
QFileInfo inf(filePath);
const QString filename = inf.fileName();
formatAndSetTitle(tr("Project:") + ' ' + filename);
addProjectMRU(filePath);
mIsLogfileLoaded = false;
mUI->mActionCloseProjectFile->setEnabled(true);
mUI->mActionEditProjectFile->setEnabled(true);
delete mProjectFile;
mProjectFile = new ProjectFile(filePath, this);
mProjectFile->setActiveProject();
if (!loadLastResults())
analyzeProject(mProjectFile, QStringList());
}
QString MainWindow::getLastResults() const
{
if (!mProjectFile || mProjectFile->getBuildDir().isEmpty())
return QString();
return QFileInfo(mProjectFile->getFilename()).absolutePath() + '/' + mProjectFile->getBuildDir() + "/lastResults.xml";
}
bool MainWindow::loadLastResults()
{
const QString &lastResults = getLastResults();
if (lastResults.isEmpty())
return false;
if (!QFileInfo::exists(lastResults))
return false;
mUI->mResults->clear(true);
mUI->mResults->readErrorsXml(lastResults);
mUI->mResults->setCheckDirectory(mSettings->value(SETTINGS_LAST_CHECK_PATH,QString()).toString());
mUI->mActionViewStats->setEnabled(true);
enableResultsButtons();
return true;
}
void MainWindow::analyzeProject(const ProjectFile *projectFile, const QStringList& recheckFiles, const bool checkLibrary, const bool checkConfiguration)
{
Settings::terminate(false);
QFileInfo inf(projectFile->getFilename());
const QString& rootpath = projectFile->getRootPath();
if (isCppcheckPremium() && !projectFile->getLicenseFile().isEmpty()) {
if (rootpath.isEmpty() || rootpath == ".")
QDir::setCurrent(inf.absolutePath());
else if (QDir(rootpath).isAbsolute())
QDir::setCurrent(rootpath);
else
QDir::setCurrent(inf.absolutePath() + "/" + rootpath);
QString licenseFile = projectFile->getLicenseFile();
if (!QFileInfo(licenseFile).isAbsolute() && !rootpath.isEmpty())
licenseFile = inf.absolutePath() + "/" + licenseFile;
#ifdef Q_OS_WIN
const QString premiumaddon = QCoreApplication::applicationDirPath() + "/premiumaddon.exe";
#else
const QString premiumaddon = QCoreApplication::applicationDirPath() + "/premiumaddon";
#endif
const std::vector<std::string> args{"--check-loc-license", licenseFile.toStdString()};
std::string output;
CheckThread::executeCommand(premiumaddon.toStdString(), args, "", output);
std::ofstream fout(inf.absolutePath().toStdString() + "/cppcheck-premium-loc");
fout << output;
}
QDir::setCurrent(inf.absolutePath());
mThread->setAddonsAndTools(projectFile->getAddonsAndTools());
// If the root path is not given or is not "current dir", use project
// file's location directory as root path
if (rootpath.isEmpty() || rootpath == ".")
mCurrentDirectory = inf.canonicalPath();
else if (rootpath.startsWith("./"))
mCurrentDirectory = inf.canonicalPath() + rootpath.mid(1);
else
mCurrentDirectory = rootpath;
if (!projectFile->getBuildDir().isEmpty()) {
QString buildDir = projectFile->getBuildDir();
if (!QDir::isAbsolutePath(buildDir))
buildDir = inf.canonicalPath() + '/' + buildDir;
if (!QDir(buildDir).exists()) {
QMessageBox msg(QMessageBox::Question,
tr("Cppcheck"),
tr("Build dir '%1' does not exist, create it?").arg(buildDir),
QMessageBox::Yes | QMessageBox::No,
this);
if (msg.exec() == QMessageBox::Yes) {
QDir().mkpath(buildDir);
} else if (!projectFile->getAddons().isEmpty()) {
QMessageBox m(QMessageBox::Critical,
tr("Cppcheck"),
tr("To check the project using addons, you need a build directory."),
QMessageBox::Ok,
this);
m.exec();
return;
}
}
}
if (!projectFile->getImportProject().isEmpty()) {
ImportProject p;
QString prjfile;
if (QFileInfo(projectFile->getImportProject()).isAbsolute()) {
prjfile = projectFile->getImportProject();
} else {
prjfile = inf.canonicalPath() + '/' + projectFile->getImportProject();
}
try {
const ImportProject::Type result = p.import(prjfile.toStdString());
QString errorMessage;
switch (result) {
case ImportProject::Type::COMPILE_DB:
case ImportProject::Type::VS_SLN:
case ImportProject::Type::VS_VCXPROJ:
case ImportProject::Type::BORLAND:
case ImportProject::Type::CPPCHECK_GUI:
// Loading was successful
break;
case ImportProject::Type::MISSING:
errorMessage = tr("Failed to open file");
break;
case ImportProject::Type::UNKNOWN:
errorMessage = tr("Unknown project file format");
break;
case ImportProject::Type::FAILURE:
errorMessage = tr("Failed to import project file");
break;
case ImportProject::Type::NONE:
// can never happen
break;
}
if (!errorMessage.isEmpty()) {
QMessageBox msg(QMessageBox::Critical,
tr("Cppcheck"),
tr("Failed to import '%1': %2\n\nAnalysis is stopped.").arg(prjfile).arg(errorMessage),
QMessageBox::Ok,
this);
msg.exec();
return;
}
} catch (InternalError &e) {
QMessageBox msg(QMessageBox::Critical,
tr("Cppcheck"),
tr("Failed to import '%1' (%2), analysis is stopped").arg(prjfile).arg(QString::fromStdString(e.errorMessage)),
QMessageBox::Ok,
this);
msg.exec();
return;
}
doAnalyzeProject(p, checkLibrary, checkConfiguration);
return;
}
QStringList paths = recheckFiles.isEmpty() ? projectFile->getCheckPaths() : recheckFiles;
// If paths not given then check the root path (which may be the project
// file's location, see above). This is to keep the compatibility with
// old "silent" project file loading when we checked the director where the
// project file was located.
if (paths.isEmpty()) {
paths << mCurrentDirectory;
}
doAnalyzeFiles(paths, checkLibrary, checkConfiguration);
}
void MainWindow::newProjectFile()
{
const QString filter = tr("Project files (*.cppcheck)");
QString filepath = QFileDialog::getSaveFileName(this,
tr("Select Project Filename"),
getPath(SETTINGS_LAST_PROJECT_PATH),
filter);
if (filepath.isEmpty())
return;
if (!filepath.endsWith(".cppcheck", Qt::CaseInsensitive))
filepath += ".cppcheck";
setPath(SETTINGS_LAST_PROJECT_PATH, filepath);
QFileInfo inf(filepath);
const QString filename = inf.fileName();
formatAndSetTitle(tr("Project:") + QString(" ") + filename);
delete mProjectFile;
mProjectFile = new ProjectFile(this);
mProjectFile->setActiveProject();
mProjectFile->setFilename(filepath);
mProjectFile->setProjectName(filename.left(filename.indexOf(".")));
mProjectFile->setBuildDir(filename.left(filename.indexOf(".")) + "-cppcheck-build-dir");
ProjectFileDialog dlg(mProjectFile, isCppcheckPremium(), this);
if (dlg.exec() == QDialog::Accepted) {
addProjectMRU(filepath);
analyzeProject(mProjectFile, QStringList());
} else {
closeProjectFile();
}
}
void MainWindow::closeProjectFile()
{
delete mProjectFile;
mProjectFile = nullptr;
mUI->mResults->clear(true);
enableProjectActions(false);
enableProjectOpenActions(true);
formatAndSetTitle();
}
void MainWindow::editProjectFile()
{
if (!mProjectFile) {
QMessageBox msg(QMessageBox::Critical,
tr("Cppcheck"),
tr("No project file loaded"),
QMessageBox::Ok,
this);
msg.exec();
return;
}
ProjectFileDialog dlg(mProjectFile, isCppcheckPremium(), this);
if (dlg.exec() == QDialog::Accepted) {
mProjectFile->write();
analyzeProject(mProjectFile, QStringList());
}
}
void MainWindow::showStatistics()
{
StatsDialog statsDialog(this);
// Show a dialog with the previous scan statistics and project information
statsDialog.setProject(mProjectFile);
statsDialog.setPathSelected(mCurrentDirectory);
statsDialog.setNumberOfFilesScanned(mThread->getPreviousFilesCount());
statsDialog.setScanDuration(mThread->getPreviousScanDuration() / 1000.0);
statsDialog.setStatistics(mUI->mResults->getStatistics());
statsDialog.exec();
}
void MainWindow::showLibraryEditor()
{
LibraryDialog libraryDialog(this);
libraryDialog.exec();
}
void MainWindow::filterResults()
{
mUI->mResults->filterResults(mLineEditFilter->text());
}
void MainWindow::enableProjectActions(bool enable)
{
mUI->mActionCloseProjectFile->setEnabled(enable);
mUI->mActionEditProjectFile->setEnabled(enable);
mUI->mActionCheckLibrary->setEnabled(enable);
mUI->mActionCheckConfiguration->setEnabled(enable);
}
void MainWindow::enableProjectOpenActions(bool enable)
{
mUI->mActionNewProjectFile->setEnabled(enable);
mUI->mActionOpenProjectFile->setEnabled(enable);
}
void MainWindow::openRecentProject()
{
auto *action = qobject_cast<QAction *>(sender());
if (!action)
return;
const QString project = action->data().toString();
QFileInfo inf(project);
if (inf.exists()) {
if (inf.suffix() == "xml")
loadResults(project);
else {
loadProjectFile(project);
loadLastResults();
}
} else {
const QString text(tr("The project file\n\n%1\n\n could not be found!\n\n"
"Do you want to remove the file from the recently "
"used projects -list?").arg(project));
QMessageBox msg(QMessageBox::Warning,
tr("Cppcheck"),
text,
QMessageBox::Yes | QMessageBox::No,
this);
msg.setDefaultButton(QMessageBox::No);
const int rv = msg.exec();
if (rv == QMessageBox::Yes) {
removeProjectMRU(project);
}
}
}
void MainWindow::updateMRUMenuItems()
{
for (QAction* recentProjectAct : mRecentProjectActs) {
if (recentProjectAct != nullptr)
mUI->mMenuFile->removeAction(recentProjectAct);
}
QStringList projects = mSettings->value(SETTINGS_MRU_PROJECTS).toStringList();
// Do a sanity check - remove duplicates and non-existing projects
int removed = projects.removeDuplicates();
for (int i = projects.size() - 1; i >= 0; i--) {
if (!QFileInfo::exists(projects[i])) {
projects.removeAt(i);
removed++;
}
}
if (removed)
mSettings->setValue(SETTINGS_MRU_PROJECTS, projects);
const int numRecentProjects = qMin(projects.size(), (int)MaxRecentProjects);
for (int i = 0; i < numRecentProjects; i++) {
const QString filename = QFileInfo(projects[i]).fileName();
const QString text = QString("&%1 %2").arg(i + 1).arg(filename);
mRecentProjectActs[i]->setText(text);
mRecentProjectActs[i]->setData(projects[i]);
mRecentProjectActs[i]->setVisible(true);
mUI->mMenuFile->insertAction(mUI->mActionProjectMRU, mRecentProjectActs[i]);
}
if (numRecentProjects > 1)
mRecentProjectActs[numRecentProjects] = mUI->mMenuFile->insertSeparator(mUI->mActionProjectMRU);
}
void MainWindow::addProjectMRU(const QString &project)
{
QStringList files = mSettings->value(SETTINGS_MRU_PROJECTS).toStringList();
files.removeAll(project);
files.prepend(project);
while (files.size() > MaxRecentProjects)
files.removeLast();
mSettings->setValue(SETTINGS_MRU_PROJECTS, files);
updateMRUMenuItems();
}
void MainWindow::removeProjectMRU(const QString &project)
{
QStringList files = mSettings->value(SETTINGS_MRU_PROJECTS).toStringList();
files.removeAll(project);
mSettings->setValue(SETTINGS_MRU_PROJECTS, files);
updateMRUMenuItems();
}
void MainWindow::selectPlatform()
{
auto *action = qobject_cast<QAction *>(sender());
if (action) {
const Platform::Type platform = (Platform::Type) action->data().toInt();
mSettings->setValue(SETTINGS_CHECKED_PLATFORM, platform);
}
}
void MainWindow::suppressIds(QStringList ids)
{
if (!mProjectFile)
return;
ids.removeDuplicates();
QList<SuppressionList::Suppression> suppressions = mProjectFile->getSuppressions();
for (const QString& id : ids) {
// Remove all matching suppressions
std::string id2 = id.toStdString();
for (int i = 0; i < suppressions.size();) {
if (suppressions[i].errorId == id2)
suppressions.removeAt(i);
else
++i;
}
SuppressionList::Suppression newSuppression;
newSuppression.errorId = id2;
suppressions << newSuppression;
}
mProjectFile->setSuppressions(suppressions);
mProjectFile->write();
}
static int getVersion(const QString& nameWithVersion) {
int ret = 0;
int v = 0;
int dot = 0;
for (const auto c: nameWithVersion) {
if (c == '\n' || c == '\r')
break;
if (c == ' ') {
if (ret > 0 && dot == 1 && nameWithVersion.endsWith(" dev"))
return (ret * 1000000) + (v * 1000) + 500;
dot = ret = v = 0;
}
else if (c == '.') {
++dot;
ret = ret * 1000 + v;
v = 0;
} else if (c >= '0' && c <= '9')
v = v * 10 + (c.toLatin1() - '0');
}
ret = ret * 1000 + v;
while (dot < 2) {
++dot;
ret *= 1000;
}
return ret;
}
void MainWindow::replyFinished(QNetworkReply *reply) {
reply->deleteLater();
if (reply->error()) {
mUI->mLayoutInformation->deleteLater();
qDebug() << "Response: ERROR";
return;
}
const QString str = reply->readAll();
qDebug() << "Response: " << str;
if (reply->url().fileName() == "version.txt") {
QString nameWithVersion = QString("Cppcheck %1").arg(CppCheck::version());
if (!mCppcheckCfgProductName.isEmpty())
nameWithVersion = mCppcheckCfgProductName;
const int appVersion = getVersion(nameWithVersion);
const int latestVersion = getVersion(str.trimmed());
if (appVersion < latestVersion) {
if (mSettings->value(SETTINGS_CHECK_VERSION, 0).toInt() != latestVersion) {
QString install;
if (isCppcheckPremium()) {
#ifdef Q_OS_WIN
const QString url("https://cppchecksolutions.com/cppcheck-premium-installation");
#else
const QString url("https://cppchecksolutions.com/cppcheck-premium-linux-installation");
#endif
install = "<a href=\"" + url + "\">" + tr("Install") + "</a>";
}
mUI->mButtonHideInformation->setVisible(true);
mUI->mLabelInformation->setVisible(true);
mUI->mLabelInformation->setText(tr("New version available: %1. %2").arg(str.trimmed()).arg(install));
}
}
}
if (!mUI->mLabelInformation->isVisible()) {
mUI->mLayoutInformation->deleteLater();
}
}
void MainWindow::hideInformation() {
int version = getVersion(mUI->mLabelInformation->text());
mSettings->setValue(SETTINGS_CHECK_VERSION, version);
mUI->mLabelInformation->setVisible(false);
mUI->mButtonHideInformation->setVisible(false);
mUI->mLayoutInformation->deleteLater();
}
bool MainWindow::isCppcheckPremium() const {
return mCppcheckCfgProductName.startsWith("Cppcheck Premium ");
}
void MainWindow::changeReportType() {
const ReportType reportType = mUI->mActionReportAutosar->isChecked() ? ReportType::autosar :
mUI->mActionReportCertC->isChecked() ? ReportType::certC :
mUI->mActionReportCertCpp->isChecked() ? ReportType::certCpp :
mUI->mActionReportMisraC->isChecked() ? ReportType::misraC :
mUI->mActionReportMisraCpp2008->isChecked() ? ReportType::misraCpp2008 :
mUI->mActionReportMisraCpp2023->isChecked() ? ReportType::misraCpp2023 :
ReportType::normal;
mUI->mResults->setReportType(reportType);
auto setTextAndHint = [](QAction* a, const QString& s) {
a->setVisible(!s.isEmpty());
a->setText(s);
a->setToolTip(s);
};
const QString showMandatory = tr("Show Mandatory");
const QString showRequired = tr("Show Required");
const QString showAdvisory = tr("Show Advisory");
const QString showDocument = tr("Show Document");
if (mUI->mActionReportAutosar->isChecked()) {
setTextAndHint(mUI->mActionShowErrors, "");
setTextAndHint(mUI->mActionShowWarnings, showRequired);
setTextAndHint(mUI->mActionShowStyle, showAdvisory);
setTextAndHint(mUI->mActionShowPortability, "");
setTextAndHint(mUI->mActionShowPerformance, "");
setTextAndHint(mUI->mActionShowInformation, "");
} else if (mUI->mActionReportMisraC->isChecked() || mUI->mActionReportMisraCpp2008->isChecked() || mUI->mActionReportMisraCpp2023->isChecked()) {
setTextAndHint(mUI->mActionShowErrors, mUI->mActionReportMisraCpp2008->isChecked() ? "" : showMandatory);
setTextAndHint(mUI->mActionShowWarnings, showRequired);
setTextAndHint(mUI->mActionShowStyle, showAdvisory);
setTextAndHint(mUI->mActionShowPortability, "");
setTextAndHint(mUI->mActionShowPerformance, "");
setTextAndHint(mUI->mActionShowInformation, mUI->mActionReportMisraCpp2008->isChecked() ? showDocument : QString());
} else if (mUI->mActionReportCertC->isChecked() || mUI->mActionReportCertCpp->isChecked()) {
setTextAndHint(mUI->mActionShowErrors, tr("Show L1"));
setTextAndHint(mUI->mActionShowWarnings, tr("Show L2"));
setTextAndHint(mUI->mActionShowStyle, tr("Show L3"));
setTextAndHint(mUI->mActionShowPortability, "");
setTextAndHint(mUI->mActionShowPerformance, "");
setTextAndHint(mUI->mActionShowInformation, "");
} else {
setTextAndHint(mUI->mActionShowErrors, tr("Show errors"));
setTextAndHint(mUI->mActionShowWarnings, tr("Show warnings"));
setTextAndHint(mUI->mActionShowStyle, tr("Show style"));
setTextAndHint(mUI->mActionShowPortability, tr("Show portability"));
setTextAndHint(mUI->mActionShowPerformance, tr("Show performance"));
setTextAndHint(mUI->mActionShowInformation, tr("Show information"));
}
}
| null |
716 | cpp | cppcheck | application.cpp | gui/application.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2023 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "application.h"
#include <utility>
Application::Application(QString name, QString path,
QString params)
: mName(std::move(name))
, mPath(std::move(path))
, mParameters(std::move(params))
{}
| null |
717 | cpp | cppcheck | applicationdialog.h | gui/applicationdialog.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef APPLICATIONDIALOG_H
#define APPLICATIONDIALOG_H
#include <QDialog>
#include <QObject>
#include <QString>
class QWidget;
class Application;
namespace Ui {
class ApplicationDialog;
}
/// @addtogroup GUI
/// @{
/**
* @brief Dialog to edit a startable application.
* User can open errors with user specified applications. This is a dialog
* to modify/add an application to open errors with.
*
*/
class ApplicationDialog : public QDialog {
Q_OBJECT
public:
/**
* @brief Constructor.
* @param title Title for the dialog.
* @param app Application definition.
* @param parent Parent widget.
*/
ApplicationDialog(const QString &title,
Application &app,
QWidget *parent = nullptr);
~ApplicationDialog() override;
protected slots:
void ok();
/**
* @brief Slot to browse for an application
*
*/
void browse();
protected:
/**
* @brief UI from the Qt designer
*
*/
Ui::ApplicationDialog* mUI;
private:
/**
* @brief Underlying Application
*/
Application& mApplication;
};
/// @}
#endif // APPLICATIONDIALOG_H
| null |
718 | cpp | cppcheck | statsdialog.h | gui/statsdialog.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef STATSDIALOG_H
#define STATSDIALOG_H
#include <QDialog>
#include <QObject>
#include <QString>
class ProjectFile;
class CheckStatistics;
class QWidget;
namespace Ui {
class StatsDialog;
}
/// @addtogroup GUI
/// @{
/**
* @brief A dialog that shows project and scan statistics.
*
*/
class StatsDialog : public QDialog {
Q_OBJECT
public:
explicit StatsDialog(QWidget *parent = nullptr);
~StatsDialog() override;
/**
* @brief Sets the project to extract statistics from
*/
void setProject(const ProjectFile *projectFile);
/**
* @brief Sets the string to display beside "Path Selected:"
*/
void setPathSelected(const QString& path);
/**
* @brief Sets the number to display beside "Number of Files Scanned:"
*/
void setNumberOfFilesScanned(int num);
/**
* @brief Sets the number of seconds to display beside "Scan Duration:"
*/
void setScanDuration(double seconds);
/**
* @brief Sets the numbers of different error/warnings found."
*/
void setStatistics(const CheckStatistics *stats);
private slots:
void copyToClipboard();
void pdfExport();
private:
Ui::StatsDialog *mUI;
const CheckStatistics* mStatistics{};
};
/// @}
#endif // STATSDIALOG_H
| null |
719 | cpp | cppcheck | codeeditor.h | gui/codeeditor.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef CODEEDITOR_H
#define CODEEDITOR_H
#include <cstdint>
#include <QObject>
#include <QPlainTextEdit>
#include <QRegularExpression>
#include <QSize>
#include <QString>
#include <QStringList>
#include <QSyntaxHighlighter>
#include <QTextCharFormat>
#include <QVector>
#include <QWidget>
class CodeEditorStyle;
class QPaintEvent;
class QRect;
class QTextDocument;
class Highlighter : public QSyntaxHighlighter {
Q_OBJECT
public:
explicit Highlighter(QTextDocument *parent,
CodeEditorStyle *widgetStyle);
void setSymbols(const QStringList &symbols);
void setStyle(const CodeEditorStyle &newStyle);
protected:
void highlightBlock(const QString &text) override;
private:
enum RuleRole : std::uint8_t {
Keyword = 1,
Class = 2,
Comment = 3,
Quote = 4,
Symbol = 5
};
struct HighlightingRule {
QRegularExpression pattern;
QTextCharFormat format;
RuleRole ruleRole;
};
void applyFormat(HighlightingRule &rule);
QVector<HighlightingRule> mHighlightingRules;
QVector<HighlightingRule> mHighlightingRulesWithSymbols;
QRegularExpression mCommentStartExpression;
QRegularExpression mCommentEndExpression;
QTextCharFormat mKeywordFormat;
QTextCharFormat mClassFormat;
QTextCharFormat mSingleLineCommentFormat;
QTextCharFormat mMultiLineCommentFormat;
QTextCharFormat mQuotationFormat;
QTextCharFormat mSymbolFormat;
CodeEditorStyle *mWidgetStyle;
};
class CodeEditor : public QPlainTextEdit {
Q_OBJECT
public:
explicit CodeEditor(QWidget *parent);
CodeEditor(const CodeEditor &) = delete;
CodeEditor &operator=(const CodeEditor &) = delete;
~CodeEditor() override;
void lineNumberAreaPaintEvent(const QPaintEvent *event);
int lineNumberAreaWidth();
void setStyle(const CodeEditorStyle& newStyle);
/**
* Set source code to show, goto error line and highlight that line.
* \param code The source code.
* \param errorLine line number
* \param symbols the related symbols, these are marked
*/
void setError(const QString &code, int errorLine, const QStringList &symbols);
/**
* Goto another error in existing source file
* \param errorLine line number
* \param symbols the related symbols, these are marked
*/
void setError(int errorLine, const QStringList &symbols);
void setFileName(const QString &fileName) {
mFileName = fileName;
}
const QString& getFileName() const {
return mFileName;
}
void clear() {
mFileName.clear();
setPlainText(QString());
}
protected:
void resizeEvent(QResizeEvent *event) override;
private slots:
void updateLineNumberAreaWidth(int newBlockCount);
void highlightErrorLine();
void updateLineNumberArea(const QRect & /*rect*/, int /*dy*/);
private:
QString generateStyleString();
private:
QWidget *mLineNumberArea;
Highlighter *mHighlighter;
CodeEditorStyle *mWidgetStyle;
int mErrorPosition;
QString mFileName;
};
class LineNumberArea : public QWidget {
public:
explicit LineNumberArea(CodeEditor *editor) : QWidget(editor) {
mCodeEditor = editor;
}
QSize sizeHint() const override {
return QSize(mCodeEditor->lineNumberAreaWidth(), 0);
}
protected:
void paintEvent(QPaintEvent *event) override {
mCodeEditor->lineNumberAreaPaintEvent(event);
}
private:
CodeEditor *mCodeEditor;
};
#endif // CODEEDITOR_H
| null |
720 | cpp | cppcheck | resultsview.cpp | gui/resultsview.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "resultsview.h"
#include "checkstatistics.h"
#include "checkersreport.h"
#include "codeeditor.h"
#include "codeeditorstyle.h"
#include "common.h"
#include "csvreport.h"
#include "erroritem.h"
#include "errorlogger.h"
#include "errortypes.h"
#include "path.h"
#include "printablereport.h"
#include "resultstree.h"
#include "settings.h"
#include "txtreport.h"
#include "xmlreport.h"
#include "xmlreportv2.h"
#include "ui_resultsview.h"
#include <set>
#include <string>
#include <QAbstractItemModel>
#include <QApplication>
#include <QByteArray>
#include <QClipboard>
#include <QDate>
#include <QDateTime>
#include <QDialog>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QIODevice>
#include <QLabel>
#include <QList>
#include <QListWidget>
#include <QListWidgetItem>
#include <QMenu>
#include <QMessageBox>
#include <QPoint>
#include <QPrintDialog>
#include <QPrintPreviewDialog>
#include <QPrinter>
#include <QProgressBar>
#include <QSettings>
#include <QSplitter>
#include <QStandardItem>
#include <QStandardItemModel>
#include <QTextDocument>
#include <QTextEdit>
#include <QTextStream>
#include <QVariant>
#include <QVariantMap>
#include <Qt>
ResultsView::ResultsView(QWidget * parent) :
QWidget(parent),
mUI(new Ui::ResultsView),
mStatistics(new CheckStatistics(this))
{
mUI->setupUi(this);
connect(mUI->mTree, &ResultsTree::resultsHidden, this, &ResultsView::resultsHidden);
connect(mUI->mTree, &ResultsTree::checkSelected, this, &ResultsView::checkSelected);
connect(mUI->mTree, &ResultsTree::treeSelectionChanged, this, &ResultsView::updateDetails);
connect(mUI->mTree, &ResultsTree::suppressIds, this, &ResultsView::suppressIds);
connect(this, &ResultsView::showResults, mUI->mTree, &ResultsTree::showResults);
connect(this, &ResultsView::showCppcheckResults, mUI->mTree, &ResultsTree::showCppcheckResults);
connect(this, &ResultsView::showClangResults, mUI->mTree, &ResultsTree::showClangResults);
connect(this, &ResultsView::collapseAllResults, mUI->mTree, &ResultsTree::collapseAll);
connect(this, &ResultsView::expandAllResults, mUI->mTree, &ResultsTree::expandAll);
connect(this, &ResultsView::showHiddenResults, mUI->mTree, &ResultsTree::showHiddenResults);
mUI->mListLog->setContextMenuPolicy(Qt::CustomContextMenu);
}
void ResultsView::initialize(QSettings *settings, ApplicationList *list, ThreadHandler *checkThreadHandler)
{
mUI->mProgress->setMinimum(0);
mUI->mProgress->setVisible(false);
mUI->mLabelCriticalErrors->setVisible(false);
CodeEditorStyle theStyle(CodeEditorStyle::loadSettings(settings));
mUI->mCode->setStyle(theStyle);
QByteArray state = settings->value(SETTINGS_MAINWND_SPLITTER_STATE).toByteArray();
mUI->mVerticalSplitter->restoreState(state);
mShowNoErrorsMessage = settings->value(SETTINGS_SHOW_NO_ERRORS, true).toBool();
mUI->mTree->initialize(settings, list, checkThreadHandler);
}
ResultsView::~ResultsView()
{
delete mUI;
delete mCheckSettings;
}
void ResultsView::clear(bool results)
{
if (results) {
mUI->mTree->clear();
}
mUI->mDetails->setText(QString());
mStatistics->clear();
delete mCheckSettings;
mCheckSettings = nullptr;
//Clear the progressbar
mUI->mProgress->setMaximum(PROGRESS_MAX);
mUI->mProgress->setValue(0);
mUI->mProgress->setFormat("%p%");
mUI->mLabelCriticalErrors->setVisible(false);
mSuccess = false;
}
void ResultsView::clear(const QString &filename)
{
mUI->mTree->clear(filename);
}
void ResultsView::clearRecheckFile(const QString &filename)
{
mUI->mTree->clearRecheckFile(filename);
}
const ShowTypes & ResultsView::getShowTypes() const
{
return mUI->mTree->mShowSeverities;
}
void ResultsView::setReportType(ReportType reportType) {
mUI->mTree->setReportType(reportType);
}
void ResultsView::progress(int value, const QString& description)
{
mUI->mProgress->setValue(value);
mUI->mProgress->setFormat(QString("%p% (%1)").arg(description));
}
void ResultsView::error(const ErrorItem &item)
{
if (item.severity == Severity::internal && (item.errorId == "logChecker" || item.errorId.endsWith("-logChecker"))) {
mStatistics->addChecker(item.message);
return;
}
handleCriticalError(item);
if (item.severity == Severity::internal)
return;
if (mUI->mTree->addErrorItem(item)) {
emit gotResults();
mStatistics->addItem(item.tool(), ShowTypes::SeverityToShowType(item.severity));
}
}
void ResultsView::filterResults(const QString& filter)
{
mUI->mTree->filterResults(filter);
}
void ResultsView::saveStatistics(const QString &filename) const
{
QFile f(filename);
if (!f.open(QIODevice::Text | QIODevice::Append))
return;
QTextStream ts(&f);
ts << '[' << QDate::currentDate().toString("dd.MM.yyyy") << "]\n";
ts << QDateTime::currentMSecsSinceEpoch() << '\n';
for (const QString& tool : mStatistics->getTools()) {
ts << tool << "-error:" << mStatistics->getCount(tool, ShowTypes::ShowErrors) << '\n';
ts << tool << "-warning:" << mStatistics->getCount(tool, ShowTypes::ShowWarnings) << '\n';
ts << tool << "-style:" << mStatistics->getCount(tool, ShowTypes::ShowStyle) << '\n';
ts << tool << "-performance:" << mStatistics->getCount(tool, ShowTypes::ShowPerformance) << '\n';
ts << tool << "-portability:" << mStatistics->getCount(tool, ShowTypes::ShowPortability) << '\n';
}
}
void ResultsView::updateFromOldReport(const QString &filename) const
{
mUI->mTree->updateFromOldReport(filename);
}
void ResultsView::save(const QString &filename, Report::Type type, const QString& productName) const
{
Report *report = nullptr;
switch (type) {
case Report::CSV:
report = new CsvReport(filename);
break;
case Report::TXT:
report = new TxtReport(filename);
break;
case Report::XMLV2:
report = new XmlReportV2(filename, productName);
break;
}
if (report) {
if (report->create())
mUI->mTree->saveResults(report);
else {
QMessageBox msgBox;
msgBox.setText(tr("Failed to save the report."));
msgBox.setIcon(QMessageBox::Critical);
msgBox.exec();
}
delete report;
report = nullptr;
} else {
QMessageBox msgBox;
msgBox.setText(tr("Failed to save the report."));
msgBox.setIcon(QMessageBox::Critical);
msgBox.exec();
}
}
void ResultsView::print()
{
QPrinter printer;
QPrintDialog dialog(&printer, this);
dialog.setWindowTitle(tr("Print Report"));
if (dialog.exec() != QDialog::Accepted)
return;
print(&printer);
}
void ResultsView::printPreview()
{
QPrinter printer;
QPrintPreviewDialog dialog(&printer, this);
connect(&dialog, SIGNAL(paintRequested(QPrinter*)), SLOT(print(QPrinter*)));
dialog.exec();
}
void ResultsView::print(QPrinter* printer) const
{
if (!hasResults()) {
QMessageBox msgBox;
msgBox.setText(tr("No errors found, nothing to print."));
msgBox.setIcon(QMessageBox::Critical);
msgBox.exec();
return;
}
PrintableReport report;
mUI->mTree->saveResults(&report);
QTextDocument doc(report.getFormattedReportText());
doc.print(printer);
}
void ResultsView::updateSettings(bool showFullPath,
bool saveFullPath,
bool saveAllErrors,
bool showNoErrorsMessage,
bool showErrorId,
bool showInconclusive)
{
mUI->mTree->updateSettings(showFullPath, saveFullPath, saveAllErrors, showErrorId, showInconclusive);
mShowNoErrorsMessage = showNoErrorsMessage;
}
void ResultsView::updateStyleSetting(QSettings *settings)
{
CodeEditorStyle theStyle(CodeEditorStyle::loadSettings(settings));
mUI->mCode->setStyle(theStyle);
}
void ResultsView::setCheckDirectory(const QString &dir)
{
mUI->mTree->setCheckDirectory(dir);
}
QString ResultsView::getCheckDirectory() const
{
return mUI->mTree->getCheckDirectory();
}
void ResultsView::setCheckSettings(const Settings &settings)
{
delete mCheckSettings;
mCheckSettings = new Settings;
*mCheckSettings = settings;
}
void ResultsView::checkingStarted(int count)
{
mSuccess = true;
mUI->mProgress->setVisible(true);
mUI->mProgress->setMaximum(PROGRESS_MAX);
mUI->mProgress->setValue(0);
mUI->mProgress->setFormat(tr("%p% (%1 of %2 files checked)").arg(0).arg(count));
}
void ResultsView::checkingFinished()
{
mUI->mProgress->setVisible(false);
mUI->mProgress->setFormat("%p%");
{
Settings checkSettings;
const std::set<std::string> activeCheckers = mStatistics->getActiveCheckers();
CheckersReport checkersReport(mCheckSettings ? *mCheckSettings : checkSettings, activeCheckers);
mStatistics->setCheckersReport(QString::fromStdString(checkersReport.getReport(mCriticalErrors.toStdString())));
}
// TODO: Items can be mysteriously hidden when checking is finished, this function
// call should be redundant but it "unhides" the wrongly hidden items.
mUI->mTree->refreshTree();
//Should we inform user of non visible/not found errors?
if (mShowNoErrorsMessage) {
//Tell user that we found no errors
if (!hasResults()) {
QMessageBox msg(QMessageBox::Information,
tr("Cppcheck"),
tr("No errors found."),
QMessageBox::Ok,
this);
msg.exec();
} //If we have errors but they aren't visible, tell user about it
else if (!mUI->mTree->hasVisibleResults()) {
QString text = tr("Errors were found, but they are configured to be hidden.\n" \
"To toggle what kind of errors are shown, open view menu.");
QMessageBox msg(QMessageBox::Information,
tr("Cppcheck"),
text,
QMessageBox::Ok,
this);
msg.exec();
}
}
}
bool ResultsView::hasVisibleResults() const
{
return mUI->mTree->hasVisibleResults();
}
bool ResultsView::hasResults() const
{
return mUI->mTree->hasResults();
}
void ResultsView::saveSettings(QSettings *settings)
{
mUI->mTree->saveSettings();
QByteArray state = mUI->mVerticalSplitter->saveState();
settings->setValue(SETTINGS_MAINWND_SPLITTER_STATE, state);
mUI->mVerticalSplitter->restoreState(state);
}
void ResultsView::translate()
{
mUI->retranslateUi(this);
mUI->mTree->translate();
}
void ResultsView::disableProgressbar()
{
mUI->mProgress->setEnabled(false);
}
void ResultsView::readErrorsXml(const QString &filename)
{
mSuccess = false; // Don't know if results come from an aborted analysis
const int version = XmlReport::determineVersion(filename);
if (version == 0) {
QMessageBox msgBox;
msgBox.setText(tr("Failed to read the report."));
msgBox.setIcon(QMessageBox::Critical);
msgBox.exec();
return;
}
if (version == 1) {
QMessageBox msgBox;
msgBox.setText(tr("XML format version 1 is no longer supported."));
msgBox.setIcon(QMessageBox::Critical);
msgBox.exec();
return;
}
XmlReportV2 report(filename, QString());
QList<ErrorItem> errors;
if (report.open()) {
errors = report.read();
} else {
QMessageBox msgBox;
msgBox.setText(tr("Failed to read the report."));
msgBox.setIcon(QMessageBox::Critical);
msgBox.exec();
}
for (const ErrorItem& item : errors) {
handleCriticalError(item);
mUI->mTree->addErrorItem(item);
}
QString dir;
if (!errors.isEmpty() && !errors[0].errorPath.isEmpty()) {
QString relativePath = QFileInfo(filename).canonicalPath();
if (QFileInfo::exists(relativePath + '/' + errors[0].errorPath[0].file))
dir = relativePath;
}
mUI->mTree->setCheckDirectory(dir);
}
void ResultsView::updateDetails(const QModelIndex &index)
{
const auto *model = qobject_cast<const QStandardItemModel*>(mUI->mTree->model());
QStandardItem *item = model->itemFromIndex(index);
if (!item) {
mUI->mCode->clear();
mUI->mDetails->setText(QString());
return;
}
// Make sure we are working with the first column
if (item->parent() && item->column() != 0)
item = item->parent()->child(item->row(), 0);
QVariantMap itemdata = item->data().toMap();
// If there is no severity data then it is a parent item without summary and message
if (!itemdata.contains("severity")) {
mUI->mCode->clear();
mUI->mDetails->setText(QString());
return;
}
const QString message = itemdata["message"].toString();
QString formattedMsg = message;
const QString file0 = itemdata["file0"].toString();
if (!file0.isEmpty() && Path::isHeader(itemdata["file"].toString().toStdString()))
formattedMsg += QString("\n\n%1: %2").arg(tr("First included by")).arg(QDir::toNativeSeparators(file0));
if (itemdata["cwe"].toInt() > 0)
formattedMsg.prepend("CWE: " + QString::number(itemdata["cwe"].toInt()) + "\n");
if (mUI->mTree->showIdColumn())
formattedMsg.prepend(tr("Id") + ": " + itemdata["id"].toString() + "\n");
if (itemdata["incomplete"].toBool())
formattedMsg += "\n" + tr("Bug hunting analysis is incomplete");
mUI->mDetails->setText(formattedMsg);
const int lineNumber = itemdata["line"].toInt();
QString filepath = itemdata["file"].toString();
if (!QFileInfo::exists(filepath) && QFileInfo::exists(mUI->mTree->getCheckDirectory() + '/' + filepath))
filepath = mUI->mTree->getCheckDirectory() + '/' + filepath;
QStringList symbols;
if (itemdata.contains("symbolNames"))
symbols = itemdata["symbolNames"].toString().split("\n");
if (filepath == mUI->mCode->getFileName()) {
mUI->mCode->setError(lineNumber, symbols);
return;
}
QFile file(filepath);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
mUI->mCode->clear();
return;
}
QTextStream in(&file);
mUI->mCode->setError(in.readAll(), lineNumber, symbols);
mUI->mCode->setFileName(filepath);
}
void ResultsView::log(const QString &str)
{
mUI->mListLog->addItem(str);
}
void ResultsView::debugError(const ErrorItem &item)
{
mUI->mListLog->addItem(item.toString());
}
void ResultsView::logClear()
{
mUI->mListLog->clear();
}
void ResultsView::logCopyEntry()
{
const QListWidgetItem * item = mUI->mListLog->currentItem();
if (nullptr != item) {
QClipboard *clipboard = QApplication::clipboard();
clipboard->setText(item->text());
}
}
void ResultsView::logCopyComplete()
{
QString logText;
for (int i=0; i < mUI->mListLog->count(); ++i) {
const QListWidgetItem * item = mUI->mListLog->item(i);
if (nullptr != item) {
logText += item->text();
}
}
QClipboard *clipboard = QApplication::clipboard();
clipboard->setText(logText);
}
void ResultsView::on_mListLog_customContextMenuRequested(const QPoint &pos)
{
if (mUI->mListLog->count() <= 0)
return;
const QPoint globalPos = mUI->mListLog->mapToGlobal(pos);
QMenu contextMenu;
contextMenu.addAction(tr("Clear Log"), this, SLOT(logClear()));
contextMenu.addAction(tr("Copy this Log entry"), this, SLOT(logCopyEntry()));
contextMenu.addAction(tr("Copy complete Log"), this, SLOT(logCopyComplete()));
contextMenu.exec(globalPos);
}
void ResultsView::stopAnalysis()
{
mSuccess = false;
mUI->mLabelCriticalErrors->setText(tr("Analysis was stopped"));
mUI->mLabelCriticalErrors->setVisible(true);
}
void ResultsView::handleCriticalError(const ErrorItem &item)
{
if (ErrorLogger::isCriticalErrorId(item.errorId.toStdString())) {
if (!mCriticalErrors.contains(item.errorId)) {
if (!mCriticalErrors.isEmpty())
mCriticalErrors += ",";
mCriticalErrors += item.errorId;
if (item.severity == Severity::internal)
mCriticalErrors += " (suppressed)";
}
QString msg = tr("There was a critical error with id '%1'").arg(item.errorId);
if (!item.file0.isEmpty())
msg += ", " + tr("when checking %1").arg(item.file0);
else
msg += ", " + tr("when checking a file");
msg += ". " + tr("Analysis was aborted.");
mUI->mLabelCriticalErrors->setText(msg);
mUI->mLabelCriticalErrors->setVisible(true);
mSuccess = false;
}
}
bool ResultsView::isSuccess() const {
return mSuccess;
}
| null |
721 | cpp | cppcheck | projectfile.cpp | gui/projectfile.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "projectfile.h"
#include "common.h"
#include "config.h"
#include "importproject.h"
#include "settings.h"
#include "utils.h"
#include <utility>
#include <QFile>
#include <QDir>
#include <QIODevice>
#include <QLatin1String>
#include <QRegularExpression>
#include <QXmlStreamAttributes>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
#include <QStringRef>
#endif
ProjectFile *ProjectFile::mActiveProject;
ProjectFile::ProjectFile(QObject *parent) :
QObject(parent)
{
clear();
}
ProjectFile::ProjectFile(QString filename, QObject *parent) :
QObject(parent),
mFilename(std::move(filename))
{
clear();
read();
}
void ProjectFile::clear()
{
const Settings settings;
clangParser = false;
mCheckLevel = CheckLevel::normal;
mRootPath.clear();
mBuildDir.clear();
mImportProject.clear();
mIncludeDirs.clear();
mDefines.clear();
mUndefines.clear();
mPaths.clear();
mExcludedPaths.clear();
mLibraries.clear();
mPlatform.clear();
mProjectName.clear();
mSuppressions.clear();
mAddons.clear();
mClangAnalyzer = mClangTidy = false;
mAnalyzeAllVsConfigs = false;
mCheckHeaders = true;
mCheckUnusedTemplates = true;
mInlineSuppression = true;
mMaxCtuDepth = settings.maxCtuDepth;
mMaxTemplateRecursion = settings.maxTemplateRecursion;
mCheckUnknownFunctionReturn.clear();
safeChecks.clear();
mVsConfigurations.clear();
mTags.clear();
mWarningTags.clear();
// Premium
mBughunting = false;
mCertIntPrecision = 0;
mCodingStandards.clear();
mPremiumLicenseFile.clear();
}
bool ProjectFile::read(const QString &filename)
{
if (!filename.isEmpty())
mFilename = filename;
QFile file(mFilename);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return false;
clear();
QXmlStreamReader xmlReader(&file);
bool insideProject = false;
bool projectTagFound = false;
while (!xmlReader.atEnd()) {
switch (xmlReader.readNext()) {
case QXmlStreamReader::StartElement:
if (xmlReader.name() == QString(CppcheckXml::ProjectElementName)) {
insideProject = true;
projectTagFound = true;
break;
}
if (!insideProject)
break;
// Read root path from inside project element
if (xmlReader.name() == QString(CppcheckXml::RootPathName))
readRootPath(xmlReader);
// Read root path from inside project element
if (xmlReader.name() == QString(CppcheckXml::BuildDirElementName))
readBuildDir(xmlReader);
// Find paths to check from inside project element
if (xmlReader.name() == QString(CppcheckXml::PathsElementName))
readCheckPaths(xmlReader);
if (xmlReader.name() == QString(CppcheckXml::ImportProjectElementName))
readImportProject(xmlReader);
if (xmlReader.name() == QString(CppcheckXml::AnalyzeAllVsConfigsElementName))
mAnalyzeAllVsConfigs = readBool(xmlReader);
if (xmlReader.name() == QString(CppcheckXml::Parser))
clangParser = true;
if (xmlReader.name() == QString(CppcheckXml::CheckHeadersElementName))
mCheckHeaders = readBool(xmlReader);
if (xmlReader.name() == QString(CppcheckXml::CheckUnusedTemplatesElementName))
mCheckUnusedTemplates = readBool(xmlReader);
if (xmlReader.name() == QString(CppcheckXml::InlineSuppression))
mInlineSuppression = readBool(xmlReader);
if (xmlReader.name() == QString(CppcheckXml::CheckLevelExhaustiveElementName))
mCheckLevel = CheckLevel::exhaustive;
if (xmlReader.name() == QString(CppcheckXml::CheckLevelNormalElementName))
mCheckLevel = CheckLevel::normal;
if (xmlReader.name() == QString(CppcheckXml::CheckLevelReducedElementName))
mCheckLevel = CheckLevel::reduced;
// Find include directory from inside project element
if (xmlReader.name() == QString(CppcheckXml::IncludeDirElementName))
readIncludeDirs(xmlReader);
// Find preprocessor define from inside project element
if (xmlReader.name() == QString(CppcheckXml::DefinesElementName))
readDefines(xmlReader);
// Find preprocessor define from inside project element
if (xmlReader.name() == QString(CppcheckXml::UndefinesElementName))
readStringList(mUndefines, xmlReader, CppcheckXml::UndefineName);
// Find exclude list from inside project element
if (xmlReader.name() == QString(CppcheckXml::ExcludeElementName))
readExcludes(xmlReader);
// Find ignore list from inside project element
// These are read for compatibility
if (xmlReader.name() == QString(CppcheckXml::IgnoreElementName))
readExcludes(xmlReader);
// Find libraries list from inside project element
if (xmlReader.name() == QString(CppcheckXml::LibrariesElementName))
readStringList(mLibraries, xmlReader, CppcheckXml::LibraryElementName);
if (xmlReader.name() == QString(CppcheckXml::PlatformElementName))
readPlatform(xmlReader);
// Find suppressions list from inside project element
if (xmlReader.name() == QString(CppcheckXml::SuppressionsElementName))
readSuppressions(xmlReader);
// Unknown function return values
if (xmlReader.name() == QString(CppcheckXml::CheckUnknownFunctionReturn))
readStringList(mCheckUnknownFunctionReturn, xmlReader, CppcheckXml::Name);
// check all function parameter values
if (xmlReader.name() == QString(Settings::SafeChecks::XmlRootName))
safeChecks.loadFromXml(xmlReader);
// Addons
if (xmlReader.name() == QString(CppcheckXml::AddonsElementName))
readStringList(mAddons, xmlReader, CppcheckXml::AddonElementName);
// Tools
if (xmlReader.name() == QString(CppcheckXml::ToolsElementName)) {
QStringList tools;
readStringList(tools, xmlReader, CppcheckXml::ToolElementName);
mClangAnalyzer = tools.contains(CLANG_ANALYZER);
mClangTidy = tools.contains(CLANG_TIDY);
}
if (xmlReader.name() == QString(CppcheckXml::TagsElementName))
readStringList(mTags, xmlReader, CppcheckXml::TagElementName);
if (xmlReader.name() == QString(CppcheckXml::TagWarningsElementName))
readTagWarnings(xmlReader, xmlReader.attributes().value(QString(), CppcheckXml::TagAttributeName).toString());
if (xmlReader.name() == QString(CppcheckXml::MaxCtuDepthElementName))
mMaxCtuDepth = readInt(xmlReader, mMaxCtuDepth);
if (xmlReader.name() == QString(CppcheckXml::MaxTemplateRecursionElementName))
mMaxTemplateRecursion = readInt(xmlReader, mMaxTemplateRecursion);
// VSConfiguration
if (xmlReader.name() == QString(CppcheckXml::VSConfigurationElementName))
readVsConfigurations(xmlReader);
// Cppcheck Premium
if (xmlReader.name() == QString(CppcheckXml::BughuntingElementName))
mBughunting = true;
if (xmlReader.name() == QString(CppcheckXml::CodingStandardsElementName))
readStringList(mCodingStandards, xmlReader, CppcheckXml::CodingStandardElementName);
if (xmlReader.name() == QString(CppcheckXml::CertIntPrecisionElementName))
mCertIntPrecision = readInt(xmlReader, 0);
if (xmlReader.name() == QString(CppcheckXml::LicenseFileElementName))
mPremiumLicenseFile = readString(xmlReader);
if (xmlReader.name() == QString(CppcheckXml::ProjectNameElementName))
mProjectName = readString(xmlReader);
break;
case QXmlStreamReader::EndElement:
if (xmlReader.name() == QString(CppcheckXml::ProjectElementName))
insideProject = false;
break;
// Not handled
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
case QXmlStreamReader::EndDocument:
case QXmlStreamReader::Characters:
case QXmlStreamReader::Comment:
case QXmlStreamReader::DTD:
case QXmlStreamReader::EntityReference:
case QXmlStreamReader::ProcessingInstruction:
break;
}
}
file.close();
return projectTagFound;
}
void ProjectFile::readRootPath(const QXmlStreamReader &reader)
{
QXmlStreamAttributes attribs = reader.attributes();
QString name = attribs.value(QString(), CppcheckXml::RootPathNameAttrib).toString();
if (!name.isEmpty())
mRootPath = name;
}
void ProjectFile::readBuildDir(QXmlStreamReader &reader)
{
mBuildDir.clear();
do {
const QXmlStreamReader::TokenType type = reader.readNext();
switch (type) {
case QXmlStreamReader::Characters:
mBuildDir = reader.text().toString();
FALLTHROUGH;
case QXmlStreamReader::EndElement:
return;
// Not handled
case QXmlStreamReader::StartElement:
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
case QXmlStreamReader::EndDocument:
case QXmlStreamReader::Comment:
case QXmlStreamReader::DTD:
case QXmlStreamReader::EntityReference:
case QXmlStreamReader::ProcessingInstruction:
break;
}
} while (true);
}
void ProjectFile::readImportProject(QXmlStreamReader &reader)
{
mImportProject.clear();
do {
const QXmlStreamReader::TokenType type = reader.readNext();
switch (type) {
case QXmlStreamReader::Characters:
mImportProject = reader.text().toString();
FALLTHROUGH;
case QXmlStreamReader::EndElement:
return;
// Not handled
case QXmlStreamReader::StartElement:
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
case QXmlStreamReader::EndDocument:
case QXmlStreamReader::Comment:
case QXmlStreamReader::DTD:
case QXmlStreamReader::EntityReference:
case QXmlStreamReader::ProcessingInstruction:
break;
}
} while (true);
}
bool ProjectFile::readBool(QXmlStreamReader &reader)
{
bool ret = false;
do {
const QXmlStreamReader::TokenType type = reader.readNext();
switch (type) {
case QXmlStreamReader::Characters:
ret = (reader.text().toString() == "true");
FALLTHROUGH;
case QXmlStreamReader::EndElement:
return ret;
// Not handled
case QXmlStreamReader::StartElement:
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
case QXmlStreamReader::EndDocument:
case QXmlStreamReader::Comment:
case QXmlStreamReader::DTD:
case QXmlStreamReader::EntityReference:
case QXmlStreamReader::ProcessingInstruction:
break;
}
} while (true);
}
int ProjectFile::readInt(QXmlStreamReader &reader, int defaultValue)
{
int ret = defaultValue;
do {
const QXmlStreamReader::TokenType type = reader.readNext();
switch (type) {
case QXmlStreamReader::Characters:
ret = reader.text().toString().toInt();
FALLTHROUGH;
case QXmlStreamReader::EndElement:
return ret;
// Not handled
case QXmlStreamReader::StartElement:
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
case QXmlStreamReader::EndDocument:
case QXmlStreamReader::Comment:
case QXmlStreamReader::DTD:
case QXmlStreamReader::EntityReference:
case QXmlStreamReader::ProcessingInstruction:
break;
}
} while (true);
}
QString ProjectFile::readString(QXmlStreamReader &reader)
{
QString ret;
do {
const QXmlStreamReader::TokenType type = reader.readNext();
switch (type) {
case QXmlStreamReader::Characters:
ret = reader.text().toString();
FALLTHROUGH;
case QXmlStreamReader::EndElement:
return ret;
// Not handled
case QXmlStreamReader::StartElement:
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
case QXmlStreamReader::EndDocument:
case QXmlStreamReader::Comment:
case QXmlStreamReader::DTD:
case QXmlStreamReader::EntityReference:
case QXmlStreamReader::ProcessingInstruction:
break;
}
} while (true);
}
void ProjectFile::readIncludeDirs(QXmlStreamReader &reader)
{
bool allRead = false;
do {
QXmlStreamReader::TokenType type = reader.readNext();
switch (type) {
case QXmlStreamReader::StartElement:
// Read dir-elements
if (reader.name().toString() == CppcheckXml::DirElementName) {
QXmlStreamAttributes attribs = reader.attributes();
QString name = attribs.value(QString(), CppcheckXml::DirNameAttrib).toString();
if (!name.isEmpty())
mIncludeDirs << name;
}
break;
case QXmlStreamReader::EndElement:
if (reader.name().toString() == CppcheckXml::IncludeDirElementName)
allRead = true;
break;
// Not handled
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
case QXmlStreamReader::EndDocument:
case QXmlStreamReader::Characters:
case QXmlStreamReader::Comment:
case QXmlStreamReader::DTD:
case QXmlStreamReader::EntityReference:
case QXmlStreamReader::ProcessingInstruction:
break;
}
} while (!allRead);
}
void ProjectFile::readDefines(QXmlStreamReader &reader)
{
bool allRead = false;
do {
QXmlStreamReader::TokenType type = reader.readNext();
switch (type) {
case QXmlStreamReader::StartElement:
// Read define-elements
if (reader.name().toString() == CppcheckXml::DefineName) {
QXmlStreamAttributes attribs = reader.attributes();
QString name = attribs.value(QString(), CppcheckXml::DefineNameAttrib).toString();
if (!name.isEmpty())
mDefines << name;
}
break;
case QXmlStreamReader::EndElement:
if (reader.name().toString() == CppcheckXml::DefinesElementName)
allRead = true;
break;
// Not handled
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
case QXmlStreamReader::EndDocument:
case QXmlStreamReader::Characters:
case QXmlStreamReader::Comment:
case QXmlStreamReader::DTD:
case QXmlStreamReader::EntityReference:
case QXmlStreamReader::ProcessingInstruction:
break;
}
} while (!allRead);
}
void ProjectFile::readCheckPaths(QXmlStreamReader &reader)
{
bool allRead = false;
do {
QXmlStreamReader::TokenType type = reader.readNext();
switch (type) {
case QXmlStreamReader::StartElement:
// Read dir-elements
if (reader.name().toString() == CppcheckXml::PathName) {
QXmlStreamAttributes attribs = reader.attributes();
QString name = attribs.value(QString(), CppcheckXml::PathNameAttrib).toString();
if (!name.isEmpty())
mPaths << name;
}
break;
case QXmlStreamReader::EndElement:
if (reader.name().toString() == CppcheckXml::PathsElementName)
allRead = true;
break;
// Not handled
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
case QXmlStreamReader::EndDocument:
case QXmlStreamReader::Characters:
case QXmlStreamReader::Comment:
case QXmlStreamReader::DTD:
case QXmlStreamReader::EntityReference:
case QXmlStreamReader::ProcessingInstruction:
break;
}
} while (!allRead);
}
void ProjectFile::readExcludes(QXmlStreamReader &reader)
{
bool allRead = false;
do {
QXmlStreamReader::TokenType type = reader.readNext();
switch (type) {
case QXmlStreamReader::StartElement:
// Read exclude-elements
if (reader.name().toString() == CppcheckXml::ExcludePathName) {
QXmlStreamAttributes attribs = reader.attributes();
QString name = attribs.value(QString(), CppcheckXml::ExcludePathNameAttrib).toString();
if (!name.isEmpty())
mExcludedPaths << name;
}
// Read ignore-elements - deprecated but support reading them
else if (reader.name().toString() == CppcheckXml::IgnorePathName) {
QXmlStreamAttributes attribs = reader.attributes();
QString name = attribs.value(QString(), CppcheckXml::IgnorePathNameAttrib).toString();
if (!name.isEmpty())
mExcludedPaths << name;
}
break;
case QXmlStreamReader::EndElement:
if (reader.name().toString() == CppcheckXml::IgnoreElementName)
allRead = true;
if (reader.name().toString() == CppcheckXml::ExcludeElementName)
allRead = true;
break;
// Not handled
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
case QXmlStreamReader::EndDocument:
case QXmlStreamReader::Characters:
case QXmlStreamReader::Comment:
case QXmlStreamReader::DTD:
case QXmlStreamReader::EntityReference:
case QXmlStreamReader::ProcessingInstruction:
break;
}
} while (!allRead);
}
void ProjectFile::readVsConfigurations(QXmlStreamReader &reader)
{
do {
QXmlStreamReader::TokenType type = reader.readNext();
switch (type) {
case QXmlStreamReader::StartElement:
// Read library-elements
if (reader.name().toString() == CppcheckXml::VSConfigurationName) {
QString config;
type = reader.readNext();
if (type == QXmlStreamReader::Characters) {
config = reader.text().toString();
}
mVsConfigurations << config;
}
break;
case QXmlStreamReader::EndElement:
if (reader.name().toString() != CppcheckXml::VSConfigurationName)
return;
break;
// Not handled
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
case QXmlStreamReader::EndDocument:
case QXmlStreamReader::Characters:
case QXmlStreamReader::Comment:
case QXmlStreamReader::DTD:
case QXmlStreamReader::EntityReference:
case QXmlStreamReader::ProcessingInstruction:
break;
}
} while (true);
}
void ProjectFile::readPlatform(QXmlStreamReader &reader)
{
do {
const QXmlStreamReader::TokenType type = reader.readNext();
switch (type) {
case QXmlStreamReader::Characters:
mPlatform = reader.text().toString();
FALLTHROUGH;
case QXmlStreamReader::EndElement:
return;
// Not handled
case QXmlStreamReader::StartElement:
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
case QXmlStreamReader::EndDocument:
case QXmlStreamReader::Comment:
case QXmlStreamReader::DTD:
case QXmlStreamReader::EntityReference:
case QXmlStreamReader::ProcessingInstruction:
break;
}
} while (true);
}
void ProjectFile::readSuppressions(QXmlStreamReader &reader)
{
do {
QXmlStreamReader::TokenType type = reader.readNext();
switch (type) {
case QXmlStreamReader::StartElement:
// Read library-elements
if (reader.name().toString() == CppcheckXml::SuppressionElementName) {
SuppressionList::Suppression suppression;
if (reader.attributes().hasAttribute(QString(),"fileName"))
suppression.fileName = reader.attributes().value(QString(),"fileName").toString().toStdString();
if (reader.attributes().hasAttribute(QString(),"lineNumber"))
suppression.lineNumber = reader.attributes().value(QString(),"lineNumber").toInt();
if (reader.attributes().hasAttribute(QString(),"symbolName"))
suppression.symbolName = reader.attributes().value(QString(),"symbolName").toString().toStdString();
if (reader.attributes().hasAttribute(QString(),"hash"))
suppression.hash = reader.attributes().value(QString(),"hash").toULongLong();
type = reader.readNext();
if (type == QXmlStreamReader::Characters) {
suppression.errorId = reader.text().toString().toStdString();
}
mSuppressions << suppression;
}
break;
case QXmlStreamReader::EndElement:
if (reader.name().toString() != CppcheckXml::SuppressionElementName)
return;
break;
// Not handled
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
case QXmlStreamReader::EndDocument:
case QXmlStreamReader::Characters:
case QXmlStreamReader::Comment:
case QXmlStreamReader::DTD:
case QXmlStreamReader::EntityReference:
case QXmlStreamReader::ProcessingInstruction:
break;
}
} while (true);
}
void ProjectFile::readTagWarnings(QXmlStreamReader &reader, const QString &tag)
{
do {
QXmlStreamReader::TokenType type = reader.readNext();
switch (type) {
case QXmlStreamReader::StartElement:
// Read library-elements
if (reader.name().toString() == CppcheckXml::WarningElementName) {
const std::size_t hash = reader.attributes().value(QString(), CppcheckXml::HashAttributeName).toULongLong();
mWarningTags[hash] = tag;
}
break;
case QXmlStreamReader::EndElement:
if (reader.name().toString() != CppcheckXml::WarningElementName)
return;
break;
// Not handled
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
case QXmlStreamReader::EndDocument:
case QXmlStreamReader::Characters:
case QXmlStreamReader::Comment:
case QXmlStreamReader::DTD:
case QXmlStreamReader::EntityReference:
case QXmlStreamReader::ProcessingInstruction:
break;
}
} while (true);
}
void ProjectFile::readStringList(QStringList &stringlist, QXmlStreamReader &reader, const char elementname[])
{
bool allRead = false;
do {
QXmlStreamReader::TokenType type = reader.readNext();
switch (type) {
case QXmlStreamReader::StartElement:
// Read library-elements
if (reader.name().toString() == elementname) {
type = reader.readNext();
if (type == QXmlStreamReader::Characters) {
QString text = reader.text().toString();
stringlist << text;
}
}
break;
case QXmlStreamReader::EndElement:
if (reader.name().toString() != elementname)
allRead = true;
break;
// Not handled
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
case QXmlStreamReader::EndDocument:
case QXmlStreamReader::Characters:
case QXmlStreamReader::Comment:
case QXmlStreamReader::DTD:
case QXmlStreamReader::EntityReference:
case QXmlStreamReader::ProcessingInstruction:
break;
}
} while (!allRead);
}
void ProjectFile::setIncludes(const QStringList &includes)
{
mIncludeDirs = includes;
}
void ProjectFile::setDefines(const QStringList &defines)
{
mDefines = defines;
}
void ProjectFile::setUndefines(const QStringList &undefines)
{
mUndefines = undefines;
}
void ProjectFile::setCheckPaths(const QStringList &paths)
{
mPaths = paths;
}
void ProjectFile::setExcludedPaths(const QStringList &paths)
{
mExcludedPaths = paths;
}
void ProjectFile::setLibraries(const QStringList &libraries)
{
mLibraries = libraries;
}
void ProjectFile::setPlatform(const QString &platform)
{
mPlatform = platform;
}
QList<SuppressionList::Suppression> ProjectFile::getCheckingSuppressions() const
{
const QRegularExpression re1("^[a-zA-Z0-9_\\-]+/.*");
const QRegularExpression re2("^[^/]+$");
QList<SuppressionList::Suppression> result;
for (SuppressionList::Suppression suppression : mSuppressions) {
if (re1.match(suppression.fileName.c_str()).hasMatch() || re2.match(suppression.fileName.c_str()).hasMatch()) {
if (suppression.fileName[0] != '*')
suppression.fileName = QFileInfo(mFilename).absolutePath().toStdString() + "/" + suppression.fileName;
}
result << suppression;
}
return result;
}
void ProjectFile::setSuppressions(const QList<SuppressionList::Suppression> &suppressions)
{
mSuppressions = suppressions;
}
void ProjectFile::addSuppression(const SuppressionList::Suppression &suppression)
{
mSuppressions.append(suppression);
}
void ProjectFile::setAddons(const QStringList &addons)
{
mAddons = addons;
}
void ProjectFile::setVSConfigurations(const QStringList &vsConfigs)
{
mVsConfigurations = vsConfigs;
}
void ProjectFile::setCheckLevel(ProjectFile::CheckLevel checkLevel)
{
mCheckLevel = checkLevel;
}
void ProjectFile::setWarningTags(std::size_t hash, const QString& tags)
{
if (tags.isEmpty())
mWarningTags.erase(hash);
else if (hash > 0)
mWarningTags[hash] = tags;
}
QString ProjectFile::getWarningTags(std::size_t hash) const
{
auto it = mWarningTags.find(hash);
return (it != mWarningTags.end()) ? it->second : QString();
}
bool ProjectFile::write(const QString &filename)
{
if (!filename.isEmpty())
mFilename = filename;
QFile file(mFilename);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
return false;
QXmlStreamWriter xmlWriter(&file);
xmlWriter.setAutoFormatting(true);
xmlWriter.writeStartDocument("1.0");
xmlWriter.writeStartElement(CppcheckXml::ProjectElementName);
xmlWriter.writeAttribute(CppcheckXml::ProjectVersionAttrib, CppcheckXml::ProjectFileVersion);
if (!mRootPath.isEmpty()) {
xmlWriter.writeStartElement(CppcheckXml::RootPathName);
xmlWriter.writeAttribute(CppcheckXml::RootPathNameAttrib, mRootPath);
xmlWriter.writeEndElement();
}
if (!mBuildDir.isEmpty()) {
xmlWriter.writeStartElement(CppcheckXml::BuildDirElementName);
xmlWriter.writeCharacters(mBuildDir);
xmlWriter.writeEndElement();
}
if (!mPlatform.isEmpty()) {
xmlWriter.writeStartElement(CppcheckXml::PlatformElementName);
xmlWriter.writeCharacters(mPlatform);
xmlWriter.writeEndElement();
}
if (!mImportProject.isEmpty()) {
xmlWriter.writeStartElement(CppcheckXml::ImportProjectElementName);
xmlWriter.writeCharacters(mImportProject);
xmlWriter.writeEndElement();
}
xmlWriter.writeStartElement(CppcheckXml::AnalyzeAllVsConfigsElementName);
xmlWriter.writeCharacters(bool_to_string(mAnalyzeAllVsConfigs));
xmlWriter.writeEndElement();
if (clangParser) {
xmlWriter.writeStartElement(CppcheckXml::Parser);
xmlWriter.writeCharacters("clang");
xmlWriter.writeEndElement();
}
xmlWriter.writeStartElement(CppcheckXml::CheckHeadersElementName);
xmlWriter.writeCharacters(bool_to_string(mCheckHeaders));
xmlWriter.writeEndElement();
xmlWriter.writeStartElement(CppcheckXml::CheckUnusedTemplatesElementName);
xmlWriter.writeCharacters(bool_to_string(mCheckUnusedTemplates));
xmlWriter.writeEndElement();
xmlWriter.writeStartElement(CppcheckXml::InlineSuppression);
xmlWriter.writeCharacters(bool_to_string(mInlineSuppression));
xmlWriter.writeEndElement();
xmlWriter.writeStartElement(CppcheckXml::MaxCtuDepthElementName);
xmlWriter.writeCharacters(QString::number(mMaxCtuDepth));
xmlWriter.writeEndElement();
xmlWriter.writeStartElement(CppcheckXml::MaxTemplateRecursionElementName);
xmlWriter.writeCharacters(QString::number(mMaxTemplateRecursion));
xmlWriter.writeEndElement();
if (!mIncludeDirs.isEmpty()) {
xmlWriter.writeStartElement(CppcheckXml::IncludeDirElementName);
for (const QString& incdir : mIncludeDirs) {
xmlWriter.writeStartElement(CppcheckXml::DirElementName);
xmlWriter.writeAttribute(CppcheckXml::DirNameAttrib, incdir);
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
}
if (!mDefines.isEmpty()) {
xmlWriter.writeStartElement(CppcheckXml::DefinesElementName);
for (const QString& define : mDefines) {
xmlWriter.writeStartElement(CppcheckXml::DefineName);
xmlWriter.writeAttribute(CppcheckXml::DefineNameAttrib, define);
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
}
if (!mVsConfigurations.isEmpty()) {
writeStringList(xmlWriter,
mVsConfigurations,
CppcheckXml::VSConfigurationElementName,
CppcheckXml::VSConfigurationName);
}
writeStringList(xmlWriter,
mUndefines,
CppcheckXml::UndefinesElementName,
CppcheckXml::UndefineName);
if (!mPaths.isEmpty()) {
xmlWriter.writeStartElement(CppcheckXml::PathsElementName);
for (const QString& path : mPaths) {
xmlWriter.writeStartElement(CppcheckXml::PathName);
xmlWriter.writeAttribute(CppcheckXml::PathNameAttrib, path);
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
}
if (!mExcludedPaths.isEmpty()) {
xmlWriter.writeStartElement(CppcheckXml::ExcludeElementName);
for (const QString& path : mExcludedPaths) {
xmlWriter.writeStartElement(CppcheckXml::ExcludePathName);
xmlWriter.writeAttribute(CppcheckXml::ExcludePathNameAttrib, path);
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
}
writeStringList(xmlWriter,
mLibraries,
CppcheckXml::LibrariesElementName,
CppcheckXml::LibraryElementName);
if (!mSuppressions.isEmpty()) {
xmlWriter.writeStartElement(CppcheckXml::SuppressionsElementName);
for (const SuppressionList::Suppression &suppression : mSuppressions) {
xmlWriter.writeStartElement(CppcheckXml::SuppressionElementName);
if (!suppression.fileName.empty())
xmlWriter.writeAttribute("fileName", QString::fromStdString(suppression.fileName));
if (suppression.lineNumber > 0)
xmlWriter.writeAttribute("lineNumber", QString::number(suppression.lineNumber));
if (!suppression.symbolName.empty())
xmlWriter.writeAttribute("symbolName", QString::fromStdString(suppression.symbolName));
if (suppression.hash > 0)
xmlWriter.writeAttribute(CppcheckXml::HashAttributeName, QString::number(suppression.hash));
if (!suppression.errorId.empty())
xmlWriter.writeCharacters(QString::fromStdString(suppression.errorId));
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
}
writeStringList(xmlWriter,
mCheckUnknownFunctionReturn,
CppcheckXml::CheckUnknownFunctionReturn,
CppcheckXml::Name);
safeChecks.saveToXml(xmlWriter);
writeStringList(xmlWriter,
mAddons,
CppcheckXml::AddonsElementName,
CppcheckXml::AddonElementName);
QStringList tools;
if (mClangAnalyzer)
tools << CLANG_ANALYZER;
if (mClangTidy)
tools << CLANG_TIDY;
writeStringList(xmlWriter,
tools,
CppcheckXml::ToolsElementName,
CppcheckXml::ToolElementName);
writeStringList(xmlWriter, mTags, CppcheckXml::TagsElementName, CppcheckXml::TagElementName);
if (!mWarningTags.empty()) {
QStringList tags;
for (const auto& wt: mWarningTags) {
if (!tags.contains(wt.second))
tags.append(wt.second);
}
for (const QString &tag: tags) {
xmlWriter.writeStartElement(CppcheckXml::TagWarningsElementName);
xmlWriter.writeAttribute(CppcheckXml::TagAttributeName, tag);
for (const auto& wt: mWarningTags) {
if (wt.second == tag) {
xmlWriter.writeStartElement(CppcheckXml::WarningElementName);
xmlWriter.writeAttribute(CppcheckXml::HashAttributeName, QString::number(wt.first));
xmlWriter.writeEndElement();
}
}
xmlWriter.writeEndElement();
}
}
switch (mCheckLevel) {
case CheckLevel::reduced:
xmlWriter.writeStartElement(CppcheckXml::CheckLevelReducedElementName);
xmlWriter.writeEndElement();
break;
case CheckLevel::normal:
xmlWriter.writeStartElement(CppcheckXml::CheckLevelNormalElementName);
xmlWriter.writeEndElement();
break;
case CheckLevel::exhaustive:
xmlWriter.writeStartElement(CppcheckXml::CheckLevelExhaustiveElementName);
xmlWriter.writeEndElement();
break;
};
// Cppcheck Premium
if (mBughunting) {
xmlWriter.writeStartElement(CppcheckXml::BughuntingElementName);
xmlWriter.writeEndElement();
}
writeStringList(xmlWriter,
mCodingStandards,
CppcheckXml::CodingStandardsElementName,
CppcheckXml::CodingStandardElementName);
if (mCertIntPrecision > 0) {
xmlWriter.writeStartElement(CppcheckXml::CertIntPrecisionElementName);
xmlWriter.writeCharacters(QString::number(mCertIntPrecision));
xmlWriter.writeEndElement();
}
if (!mProjectName.isEmpty()) {
xmlWriter.writeStartElement(CppcheckXml::ProjectNameElementName);
xmlWriter.writeCharacters(mProjectName);
xmlWriter.writeEndElement();
}
if (!mPremiumLicenseFile.isEmpty()) {
xmlWriter.writeStartElement(CppcheckXml::LicenseFileElementName);
xmlWriter.writeCharacters(mPremiumLicenseFile);
xmlWriter.writeEndElement();
}
xmlWriter.writeEndDocument();
file.close();
return true;
}
void ProjectFile::writeStringList(QXmlStreamWriter &xmlWriter, const QStringList &stringlist, const char startelementname[], const char stringelementname[])
{
if (stringlist.isEmpty())
return;
xmlWriter.writeStartElement(startelementname);
for (const QString& str : stringlist) {
xmlWriter.writeStartElement(stringelementname);
xmlWriter.writeCharacters(str);
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
}
QStringList ProjectFile::fromNativeSeparators(const QStringList &paths)
{
QStringList ret;
for (const QString &path : paths)
ret << QDir::fromNativeSeparators(path);
return ret;
}
QStringList ProjectFile::getAddonsAndTools() const
{
QStringList ret(mAddons);
if (mClangAnalyzer)
ret << CLANG_ANALYZER;
if (mClangTidy)
ret << CLANG_TIDY;
return ret;
}
void ProjectFile::SafeChecks::loadFromXml(QXmlStreamReader &xmlReader)
{
classes = externalFunctions = internalFunctions = externalVariables = false;
int level = 0;
do {
const QXmlStreamReader::TokenType type = xmlReader.readNext();
switch (type) {
case QXmlStreamReader::StartElement:
++level;
if (xmlReader.name() == QString(Settings::SafeChecks::XmlClasses))
classes = true;
else if (xmlReader.name() == QString(Settings::SafeChecks::XmlExternalFunctions))
externalFunctions = true;
else if (xmlReader.name() == QString(Settings::SafeChecks::XmlInternalFunctions))
internalFunctions = true;
else if (xmlReader.name() == QString(Settings::SafeChecks::XmlExternalVariables))
externalVariables = true;
break;
case QXmlStreamReader::EndElement:
if (level <= 0)
return;
level--;
break;
// Not handled
case QXmlStreamReader::Characters:
case QXmlStreamReader::NoToken:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::StartDocument:
case QXmlStreamReader::EndDocument:
case QXmlStreamReader::Comment:
case QXmlStreamReader::DTD:
case QXmlStreamReader::EntityReference:
case QXmlStreamReader::ProcessingInstruction:
break;
}
} while (true);
}
void ProjectFile::SafeChecks::saveToXml(QXmlStreamWriter &xmlWriter) const
{
if (!classes && !externalFunctions && !internalFunctions && !externalVariables)
return;
xmlWriter.writeStartElement(QString(Settings::SafeChecks::XmlRootName));
if (classes) {
xmlWriter.writeStartElement(QString(Settings::SafeChecks::XmlClasses));
xmlWriter.writeEndElement();
}
if (externalFunctions) {
xmlWriter.writeStartElement(QString(Settings::SafeChecks::XmlExternalFunctions));
xmlWriter.writeEndElement();
}
if (internalFunctions) {
xmlWriter.writeStartElement(QString(Settings::SafeChecks::XmlInternalFunctions));
xmlWriter.writeEndElement();
}
if (externalVariables) {
xmlWriter.writeStartElement(QString(Settings::SafeChecks::XmlExternalVariables));
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
}
QString ProjectFile::getAddonFilePath(QString filesDir, const QString &addon)
{
if (QFile(addon).exists())
return addon;
if (!filesDir.endsWith("/"))
filesDir += "/";
QStringList searchPaths;
searchPaths << filesDir << (filesDir + "addons/") << (filesDir + "../addons/")
#ifdef FILESDIR
<< (QLatin1String(FILESDIR) + "/addons/")
#endif
;
for (const QString& path : searchPaths) {
QString f = path + addon + ".py";
if (QFile(f).exists())
return f;
}
return QString();
}
| null |
722 | cpp | cppcheck | cppchecklibrarydata.h | gui/cppchecklibrarydata.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef CPPCHECKLIBRARYDATA_H
#define CPPCHECKLIBRARYDATA_H
#include "config.h"
#include <cstdint>
#include <QList>
#include <QMap>
#include <QPair>
#include <QString>
#include <QStringList>
class QIODevice;
class CppcheckLibraryData {
public:
CppcheckLibraryData() = default;
struct Container {
QString id;
QString inherits;
QString startPattern;
QString endPattern;
QString opLessAllowed;
QString itEndPattern;
bool access_arrayLike{};
int size_templateParameter = -1;
struct {
QString templateParameter;
QString string;
} type;
struct RangeItemRecordType {
QString name;
QString templateParameter;
};
struct Function {
QString name;
QString yields;
QString action;
};
QList<Function> accessFunctions;
QList<Function> otherFunctions;
QList<Function> sizeFunctions;
QList<RangeItemRecordType> rangeItemRecordTypeList;
};
struct Define {
QString name;
QString value;
};
struct Function {
QString comments;
QString name;
enum TrueFalseUnknown : std::uint8_t { False, True, Unknown } noreturn = Unknown;
bool gccPure{};
bool gccConst{};
bool leakignore{};
bool useretval{};
struct ReturnValue {
QString type;
QString value;
int container = -1;
bool empty() const {
return type.isNull() && value.isNull() && container < 0;
}
} returnValue;
struct {
QString scan;
QString secure;
} formatstr;
struct Arg {
QString name;
unsigned int nr{};
static const unsigned int ANY;
static const unsigned int VARIADIC;
QString defaultValue;
bool notbool{};
bool notnull{};
bool notuninit{};
bool formatstr{};
bool strz{};
QString valid;
struct MinSize {
QString type;
QString arg;
QString arg2;
};
QList<MinSize> minsizes;
struct Iterator {
int container = -1;
QString type;
} iterator;
};
QList<Arg> args;
struct {
QString severity;
QString cstd;
QString reason;
QString alternatives;
QString msg;
bool isEmpty() const {
return cstd.isEmpty() &&
severity.isEmpty() &&
reason.isEmpty() &&
alternatives.isEmpty() &&
msg.isEmpty();
}
} warn;
QMap<QString, QString> notOverlappingDataArgs;
QMap<QString, QString> containerAttributes;
};
struct MemoryResource {
QString type; // "memory" or "resource"
struct Alloc {
bool isRealloc{};
bool init{};
int arg = -1; // -1: Has no optional "realloc-arg" attribute
int reallocArg = -1; // -1: Has no optional "arg" attribute
QString bufferSize;
QString name;
};
struct Dealloc {
int arg = -1; // -1: Has no optional "arg" attribute
QString name;
};
QList<Alloc> alloc;
QList<Dealloc> dealloc;
QStringList use;
};
struct PodType {
QString name;
QString stdtype;
QString size;
QString sign;
};
struct PlatformType {
QString name;
QString value;
QStringList types; // Keeps element names w/o attribute (e.g. unsigned)
QStringList platforms; // Keeps "type" attribute of each "platform" element
};
using TypeChecks = QList<QPair<QString, QString>>;
struct Reflection {
struct Call {
int arg = -1; // -1: Mandatory "arg" attribute not available
QString name;
};
QList<Call> calls;
};
struct Markup {
struct CodeBlocks {
QStringList blocks;
int offset = -1;
QString start;
QString end;
};
struct Exporter {
QString prefix;
QStringList prefixList;
QStringList suffixList;
};
QString ext;
bool afterCode{};
bool reportErrors{};
QStringList keywords;
QStringList importer;
QList<CodeBlocks> codeBlocks;
QList<Exporter> exporter;
};
struct SmartPointer {
QString name;
bool unique{};
};
struct Entrypoint {
QString name;
};
void clear() {
containers.clear();
defines.clear();
undefines.clear();
functions.clear();
memoryresource.clear();
podtypes.clear();
smartPointers.clear();
typeChecks.clear();
platformTypes.clear();
reflections.clear();
markups.clear();
entrypoints.clear();
}
void swap(CppcheckLibraryData &other) NOEXCEPT {
containers.swap(other.containers);
defines.swap(other.defines);
undefines.swap(other.undefines);
functions.swap(other.functions);
memoryresource.swap(other.memoryresource);
podtypes.swap(other.podtypes);
smartPointers.swap(other.smartPointers);
typeChecks.swap(other.typeChecks);
platformTypes.swap(other.platformTypes);
reflections.swap(other.reflections);
markups.swap(other.markups);
entrypoints.swap(other.entrypoints);
}
QString open(QIODevice &file);
QString toString() const;
QList<Container> containers;
QList<Define> defines;
QList<Function> functions;
QList<MemoryResource> memoryresource;
QList<PodType> podtypes;
QList<TypeChecks> typeChecks;
QList<PlatformType> platformTypes;
QStringList undefines;
QList<SmartPointer> smartPointers;
QList<Reflection> reflections;
QList<Markup> markups;
QList<Entrypoint> entrypoints;
};
#endif // CPPCHECKLIBRARYDATA_H
| null |
723 | cpp | cppcheck | xmlreportv2.h | gui/xmlreportv2.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef XML_REPORTV2_H
#define XML_REPORTV2_H
#include "erroritem.h"
#include "xmlreport.h"
#include <QList>
#include <QString>
class QXmlStreamReader;
class QXmlStreamWriter;
/// @addtogroup GUI
/// @{
/**
* @brief XML file report version 2.
* This report outputs XML-formatted report. The XML format must match command
* line version's XML output.
*/
class XmlReportV2 : public XmlReport {
public:
explicit XmlReportV2(const QString &filename, QString productName);
~XmlReportV2() override;
/**
* @brief Create the report (file).
* @return true if succeeded, false if file could not be created.
*/
bool create() override;
/**
* @brief Open existing report file.
*/
bool open() override;
/**
* @brief Write report header.
*/
void writeHeader() override;
/**
* @brief Write report footer.
*/
void writeFooter() override;
/**
* @brief Write error to report.
* @param error Error data.
*/
void writeError(const ErrorItem &error) override;
/**
* @brief Read contents of the report file.
*/
QList<ErrorItem> read() override;
protected:
/**
* @brief Read and parse error item from XML stream.
* @param reader XML stream reader to use.
*/
ErrorItem readError(const QXmlStreamReader *reader);
private:
/** Product name read from cppcheck.cfg */
const QString mProductName;
/**
* @brief XML stream reader for reading the report in XML format.
*/
QXmlStreamReader *mXmlReader;
/**
* @brief XML stream writer for writing the report in XML format.
*/
QXmlStreamWriter *mXmlWriter;
};
/// @}
#endif // XML_REPORTV2_H
| null |
724 | cpp | cppcheck | resultsview.h | gui/resultsview.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef RESULTSVIEW_H
#define RESULTSVIEW_H
#include "report.h"
#include "showtypes.h"
#include <cstdint>
#include <QObject>
#include <QString>
#include <QStringList>
#include <QWidget>
class ErrorItem;
class Settings;
class ApplicationList;
class ThreadHandler;
class QModelIndex;
class QPrinter;
class QSettings;
class CheckStatistics;
class QPoint;
enum class ReportType : std::uint8_t;
namespace Ui {
class ResultsView;
}
/// @addtogroup GUI
/// @{
/**
* @brief Widget to show cppcheck progressbar and result
*
*/
class ResultsView : public QWidget {
Q_OBJECT
public:
explicit ResultsView(QWidget * parent = nullptr);
void initialize(QSettings *settings, ApplicationList *list, ThreadHandler *checkThreadHandler);
ResultsView(const ResultsView &) = delete;
~ResultsView() override;
ResultsView &operator=(const ResultsView &) = delete;
/**
* @brief Clear results and statistics and reset progressinfo.
* @param results Remove all the results from view?
*/
void clear(bool results);
/**
* @brief Remove a file from the results.
*/
void clear(const QString &filename);
/**
* @brief Remove a recheck file from the results.
*/
void clearRecheckFile(const QString &filename);
/**
* @brief Write statistics in file
*
* @param filename Filename to save statistics to
*/
void saveStatistics(const QString &filename) const;
/**
* @brief Save results to a file
*
* @param filename Filename to save results to
* @param type Type of the report.
* @param productName Custom product name
*/
void save(const QString &filename, Report::Type type, const QString& productName) const;
/**
* @brief Update results from old report (tag, sinceDate)
*/
void updateFromOldReport(const QString &filename) const;
/**
* @brief Update tree settings
*
* @param showFullPath Show full path of files in the tree
* @param saveFullPath Save full path of files in reports
* @param saveAllErrors Save all visible errors
* @param showNoErrorsMessage Show "no errors"?
* @param showErrorId Show error id?
* @param showInconclusive Show inconclusive?
*/
void updateSettings(bool showFullPath,
bool saveFullPath,
bool saveAllErrors,
bool showNoErrorsMessage,
bool showErrorId,
bool showInconclusive);
/**
* @brief Update Code Editor Style
*
* Function will read updated Code Editor styling from
* stored program settings.
*
* @param settings Pointer to QSettings Object
*/
void updateStyleSetting(QSettings *settings);
/**
* @brief Set the directory we are checking
*
* This is used to split error file path to relative if necessary
* @param dir Directory we are checking
*/
void setCheckDirectory(const QString &dir);
/**
* @brief Get the directory we are checking
*
* @return Directory containing source files
*/
QString getCheckDirectory() const;
/**
* Set settings used in checking
*/
void setCheckSettings(const Settings& settings);
/**
* @brief Inform the view that checking has started
*
* @param count Count of files to be checked.
*/
void checkingStarted(int count);
/**
* @brief Inform the view that checking finished.
*
*/
void checkingFinished();
/**
* @brief Do we have visible results to show?
*
* @return true if there is at least one warning/error to show.
*/
bool hasVisibleResults() const;
/**
* @brief Do we have results from check?
*
* @return true if there is at least one warning/error, hidden or visible.
*/
bool hasResults() const;
/**
* @brief Save View's settings
*
* @param settings program settings.
*/
void saveSettings(QSettings *settings);
/**
* @brief Translate this view
*
*/
void translate();
/**
* @brief This function should be called when analysis is stopped
*/
void stopAnalysis();
/**
* @brief Are there successful results?
* @return true if analysis finished without critical errors etc
*/
bool isSuccess() const;
void disableProgressbar();
/**
* @brief Read errors from report XML file.
* @param filename Report file to read.
*
*/
void readErrorsXml(const QString &filename);
/**
* @brief Return checking statistics.
* @return Pointer to checking statistics.
*/
const CheckStatistics *getStatistics() const {
return mStatistics;
}
/**
* @brief Return Showtypes.
* @return Pointer to Showtypes.
*/
const ShowTypes & getShowTypes() const;
void setReportType(ReportType reportType);
signals:
/**
* @brief Signal to be emitted when we have results
*
*/
void gotResults();
/**
* @brief Signal that results have been hidden or shown
*
* @param hidden true if there are some hidden results, or false if there are not
*/
// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) - caused by generated MOC code
void resultsHidden(bool hidden);
/**
* @brief Signal to perform recheck of selected files
*
* @param selectedFilesList list of selected files
*/
// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) - caused by generated MOC code
void checkSelected(QStringList selectedFilesList);
/** Suppress Ids */
// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) - caused by generated MOC code
void suppressIds(QStringList ids);
/**
* @brief Show/hide certain type of errors
* Refreshes the tree.
*
* @param type Type of error to show/hide
* @param show Should specified errors be shown (true) or hidden (false)
*/
// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) - caused by generated MOC code
void showResults(ShowTypes::ShowType type, bool show);
/**
* @brief Show/hide cppcheck errors.
* Refreshes the tree.
*
* @param show Should specified errors be shown (true) or hidden (false)
*/
// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) - caused by generated MOC code
void showCppcheckResults(bool show);
/**
* @brief Show/hide clang-tidy/clang-analyzer errors.
* Refreshes the tree.
*
* @param show Should specified errors be shown (true) or hidden (false)
*/
// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) - caused by generated MOC code
void showClangResults(bool show);
/**
* @brief Collapse all results in the result list.
*/
void collapseAllResults();
/**
* @brief Expand all results in the result list.
*/
void expandAllResults();
/**
* @brief Show hidden results in the result list.
*/
void showHiddenResults();
public slots:
/**
* @brief Slot for updating the checking progress
*
* @param value Current progress value
* @param description Description to accompany the progress
*/
void progress(int value, const QString& description);
/**
* @brief Slot for new error to be displayed
*
* @param item Error data
*/
void error(const ErrorItem &item);
/**
* @brief Filters the results in the result list.
*/
void filterResults(const QString& filter);
/**
* @brief Update detailed message when selected item is changed.
*
* @param index Position of new selected item.
*/
void updateDetails(const QModelIndex &index);
/**
* @brief Slot opening a print dialog to print the current report
*/
void print();
/**
* @brief Slot printing the current report to the printer.
* @param printer The printer used for printing the report.
*/
void print(QPrinter* printer) const;
/**
* @brief Slot opening a print preview dialog
*/
void printPreview();
/**
* \brief Log message
*/
void log(const QString &str);
/**
* \brief debug message
*/
void debugError(const ErrorItem &item);
/**
* \brief Clear log messages
*/
void logClear();
/**
* \brief Copy selected log message entry
*/
void logCopyEntry();
/**
* \brief Copy all log messages
*/
void logCopyComplete();
private:
/**
* If provided ErrorItem is a critical error then display warning message
* in the resultsview
*/
void handleCriticalError(const ErrorItem& item);
/**
* @brief Should we show a "No errors found dialog" every time no errors were found?
*/
bool mShowNoErrorsMessage = true;
Ui::ResultsView *mUI;
CheckStatistics *mStatistics;
Settings* mCheckSettings = nullptr;
/**
* Set to true when checking finish successfully. Set to false whenever analysis starts.
*/
bool mSuccess = false;
/** Critical error ids */
QString mCriticalErrors;
private slots:
/**
* @brief Custom context menu for Analysis Log
* @param pos Mouse click position
*/
void on_mListLog_customContextMenuRequested(const QPoint &pos);
};
/// @}
#endif // RESULTSVIEW_H
| null |
725 | cpp | cppcheck | scratchpad.h | gui/scratchpad.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef SCRATCHPAD_H
#define SCRATCHPAD_H
#include <QDialog>
#include <QObject>
class MainWindow;
namespace Ui {
class ScratchPad;
}
/// @addtogroup GUI
/// @{
/**
* @brief A window with a text field that .
*/
class ScratchPad : public QDialog {
Q_OBJECT
public:
explicit ScratchPad(MainWindow& mainWindow);
~ScratchPad() override;
/**
* @brief Translate dialog
*/
void translate();
private slots:
/**
* @brief Called when check button is clicked.
*/
void checkButtonClicked();
private:
Ui::ScratchPad *mUI;
MainWindow& mMainWindow;
};
/// @}
#endif // SCRATCHPAD_H
| null |
726 | cpp | cppcheck | filelist.h | gui/filelist.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef FILELIST_H
#define FILELIST_H
#include <QFileInfo>
#include <QFileInfoList>
#include <QString>
#include <QStringList>
/**
* @brief A class for listing files and directories to check.
* This class creates a list of files to check. If directory name is given then
* all files in the directory matching the filter will be added. The directory
* can be also added recursively when all files in subdirectories are added too.
* The filenames are matched against the filter and only those files whose
* filename extension is included in the filter list are added.
*
* This class also handles filtering of paths against ignore filters given. If
* there is ignore filters then only paths not matching those filters are
* returned.
*/
class FileList {
public:
/**
* @brief Add filename to the list.
* @param filepath Full path to the file.
*/
void addFile(const QString &filepath);
/**
* @brief Add files in the directory to the list.
* @param directory Full pathname to directory to add.
* @param recursive If true also files in subdirectories are added.
*/
void addDirectory(const QString &directory, bool recursive = false);
/**
* @brief Add list of filenames and directories to the list.
* @param paths List of paths to add.
*/
void addPathList(const QStringList &paths);
/**
* @brief Return list of filenames (to check).
* @return list of filenames to check.
*/
QStringList getFileList() const;
/**
* @brief Add list of paths to exclusion list.
* @param paths Paths to exclude.
*/
void addExcludeList(const QStringList &paths);
/**
* @brief Return list of default filename extensions included.
* @return list of default filename extensions included.
*/
static QStringList getDefaultFilters();
protected:
/**
* @brief Test if filename matches the filename extensions filtering.
* @return true if filename matches filtering.
*/
static bool filterMatches(const QFileInfo &inf);
/**
* @brief Get filtered list of paths.
* This method takes the list of paths and applies the exclude lists to
* it. And then returns the list of paths that did not match the
* exclude filters.
* @return Filtered list of paths.
*/
QStringList applyExcludeList() const;
private:
QFileInfoList mFileList;
QStringList mExcludedPaths;
};
#endif // FILELIST_H
| null |
727 | cpp | cppcheck | resultstree.h | gui/resultstree.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef RESULTSTREE_H
#define RESULTSTREE_H
#include "common.h"
#include "showtypes.h"
#include <cstdint>
#include <QObject>
#include <QStandardItemModel>
#include <QString>
#include <QStringList>
#include <QTreeView>
class ApplicationList;
class Report;
class ErrorItem;
class ErrorLine;
class QModelIndex;
class QWidget;
class QItemSelectionModel;
class ThreadHandler;
class QSettings;
enum class Severity : std::uint8_t;
/// @addtogroup GUI
/// @{
/**
* @brief Cppcheck's results are shown in this tree
*
*/
class ResultsTree : public QTreeView {
Q_OBJECT
public:
explicit ResultsTree(QWidget * parent = nullptr);
void initialize(QSettings *settings, ApplicationList *list, ThreadHandler *checkThreadHandler);
/**
* @brief Add a new item to the tree
*
* @param item Error item data
*/
bool addErrorItem(const ErrorItem &item);
/**
* @brief Clear all errors from the tree
*
*/
void clear();
/**
* @brief Clear errors for a specific file from the tree
*/
void clear(const QString &filename);
/**
* @brief Clear errors of a file selected for recheck
*/
void clearRecheckFile(const QString &filename);
/**
* @brief Function to filter the displayed list of errors.
* Refreshes the tree.
*
* @param filter String that must be found in the summary, description, file or id
*/
void filterResults(const QString& filter);
/**
* @brief Function to show results that were previous hidden with HideResult()
*/
void showHiddenResults();
/**
* @brief Refresh tree by checking which of the items should be shown
* and which should be hidden
*/
void refreshTree();
/**
* @brief Save results to a text stream
*
*/
void saveResults(Report *report) const;
/**
* @brief Update items from old report (tag, sinceDate)
*/
void updateFromOldReport(const QString &filename);
/**
* @brief Update tree settings
*
* @param showFullPath Show full path of files in the tree
* @param saveFullPath Save full path of files in reports
* @param saveAllErrors Save all visible errors
* @param showErrorId Show error id
* @param showInconclusive Show inconclusive column
*/
void updateSettings(bool showFullPath, bool saveFullPath, bool saveAllErrors, bool showErrorId, bool showInconclusive);
/**
* @brief Set the directory we are checking
*
* This is used to split error file path to relative if necessary
* @param dir Directory we are checking
*/
void setCheckDirectory(const QString &dir);
/**
* @brief Get the directory we are checking
*
* @return Directory containing source files
*/
const QString& getCheckDirectory() const;
/**
* @brief Check if there are any visible results in view.
* @return true if there is at least one visible warning/error.
*/
bool hasVisibleResults() const;
/**
* @brief Do we have results from check?
* @return true if there is at least one warning/error, hidden or visible.
*/
bool hasResults() const;
/**
* @brief Save all settings
* Column widths
*/
void saveSettings() const;
/**
* @brief Change all visible texts language
*
*/
void translate();
/**
* @brief Show optional column "Id"
*/
void showIdColumn(bool show);
/**
* @brief Show optional column "Inconclusve"
*/
void showInconclusiveColumn(bool show);
/**
* @brief Returns true if column "Id" is shown
*/
bool showIdColumn() const {
return mShowErrorId;
}
/**
* @brief GUI severities.
*/
ShowTypes mShowSeverities;
void keyPressEvent(QKeyEvent *event) override;
void setReportType(ReportType reportType);
signals:
/**
* @brief Signal that results have been hidden or shown
*
* @param hidden true if there are some hidden results, or false if there are not
*/
// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) - caused by generated MOC code
void resultsHidden(bool hidden);
/**
* @brief Signal to perform selected files recheck
*
* @param selectedItems list of selected files
*/
// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) - caused by generated MOC code
void checkSelected(QStringList selectedItems);
/**
* @brief Signal for selection change in result tree.
*
* @param current Model index to specify new selected item.
*/
// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) - caused by generated MOC code
void treeSelectionChanged(const QModelIndex ¤t);
/** Suppress Ids */
// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) - caused by generated MOC code
void suppressIds(QStringList ids);
public slots:
/**
* @brief Function to show/hide certain type of errors
* Refreshes the tree.
*
* @param type Type of error to show/hide
* @param show Should specified errors be shown (true) or hidden (false)
*/
void showResults(ShowTypes::ShowType type, bool show);
/**
* @brief Show/hide cppcheck errors.
* Refreshes the tree.
*
* @param show Should specified errors be shown (true) or hidden (false)
*/
void showCppcheckResults(bool show);
/**
* @brief Show/hide clang-tidy/clang-analyzer errors.
* Refreshes the tree.
*
* @param show Should specified errors be shown (true) or hidden (false)
*/
void showClangResults(bool show);
protected slots:
/**
* @brief Slot to quickstart an error with default application
*
* @param index Model index to specify which error item to open
*/
void quickStartApplication(const QModelIndex &index);
/**
* @brief Slot for context menu item to open an error with specified application
*
* @param application Index of the application to open the error
*/
void context(int application);
/**
* @brief Slot for context menu item to copy selection to clipboard
*/
void copy();
/**
* @brief Slot for context menu item to hide the current error message
*
*/
void hideResult();
/**
* @brief Slot for rechecking selected files
*
*/
void recheckSelectedFiles();
/**
* @brief Slot for context menu item to hide all messages with the current message Id
*
*/
void hideAllIdResult();
/** Slot for context menu item to suppress all messages with the current message id */
void suppressSelectedIds();
/** Slot for context menu item to suppress message with hash */
void suppressHash();
/**
* @brief Slot for context menu item to open the folder containing the current file.
*/
void openContainingFolder();
/**
* @brief Slot for selection change in the results tree.
*
* @param current Model index to specify new selected item.
* @param previous Model index to specify previous selected item.
*/
void currentChanged(const QModelIndex ¤t, const QModelIndex &previous) override;
protected:
/**
* @brief Hides/shows full file path on all error file items according to mShowFullPath
*
*/
void refreshFilePaths();
/**
* @brief Hides/shows full file path on all error file items according to mShowFullPath
* @param item Parent item whose children's paths to change
*/
void refreshFilePaths(QStandardItem *item);
/**
* @brief Removes checking directory from given path if mShowFullPath is false
*
* @param path Path to remove checking directory
* @param saving are we saving? Check mSaveFullPath instead
* @return Path that has checking directory removed
*/
QString stripPath(const QString &path, bool saving) const;
/**
* @brief Save all errors under specified item
* @param report Report that errors are saved to
* @param fileItem Item whose errors to save
*/
void saveErrors(Report *report, const QStandardItem *fileItem) const;
/**
* @brief Convert a severity string to a icon filename
*
* @param severity Severity
*/
static QString severityToIcon(Severity severity);
/**
* @brief Helper function to open an error within target with application*
*
* @param target Error tree item to open
* @param application Index of the application to open with. Giving -1
* (default value) will open the default application.
*/
void startApplication(const QStandardItem *target, int application = -1);
/**
* @brief Helper function returning the filename/full path of the error tree item \a target.
*
* @param target The error tree item containing the filename/full path
* @param fullPath Whether or not to retrieve the full path or only the filename.
*/
static QString getFilePath(const QStandardItem *target, bool fullPath);
/**
* @brief Context menu event (user right clicked on the tree)
*
* @param e Event
*/
void contextMenuEvent(QContextMenuEvent * e) override;
/**
* @brief Add a new error item beneath a file or a backtrace item beneath an error
*
* @param parent Parent for the item. Either a file item or an error item
* @param item Error line data
* @param hide Should this be hidden (true) or shown (false)
* @param icon Should a default backtrace item icon be added
* @param childOfMessage Is this a child element of a message?
* @return newly created QStandardItem *
*/
QStandardItem *addBacktraceFiles(QStandardItem *parent,
const ErrorLine &item,
bool hide,
const QString &icon,
bool childOfMessage);
/**
* @brief Convert Severity to translated string for GUI.
* @param severity Severity to convert
* @return Severity as translated string
*/
static QString severityToTranslatedString(Severity severity);
/**
* @brief Load all settings
* Column widths
*/
void loadSettings();
/**
* @brief Ask directory where file is located.
* @param file File name.
* @return Directory user chose.
*/
QString askFileDir(const QString &file);
/**
* @brief Create new normal item.
*
* Normal item has left alignment and text set also as tooltip.
* @param name name for the item
* @return new QStandardItem
*/
static QStandardItem *createNormalItem(const QString &name);
/**
* @brief Create new normal item.
*
* Normal item has left alignment and text set also as tooltip.
* @param checked checked
* @return new QStandardItem
*/
static QStandardItem *createCheckboxItem(bool checked);
/**
* @brief Create new line number item.
*
* Line number item has right align and text set as tooltip.
* @param linenumber name for the item
* @return new QStandardItem
*/
static QStandardItem *createLineNumberItem(const QString &linenumber);
/**
* @brief Finds a file item
*
* @param name name of the file item to find
* @return pointer to file item or null if none found
*/
QStandardItem *findFileItem(const QString &name) const;
/**
* @brief Ensures there's a item in the model for the specified file
*
* @param fullpath Full path to the file item.
* @param file0 Source file
* @param hide is the error (we want this file item for) hidden?
* @return QStandardItem to be used as a parent for all errors for specified file
*/
QStandardItem *ensureFileItem(const QString &fullpath, const QString &file0, bool hide);
/**
* @brief Item model for tree
*
*/
QStandardItemModel mModel;
/**
* @brief Program settings
*
*/
QSettings* mSettings{};
/**
* @brief A string used to filter the results for display.
*
*/
QString mFilter;
/**
* @brief List of applications to open errors with
*
*/
ApplicationList* mApplications{};
/**
* @brief Right clicked item (used by context menu slots)
*
*/
QStandardItem* mContextItem{};
/**
* @brief Should full path of files be shown (true) or relative (false)
*
*/
bool mShowFullPath{};
/**
* @brief Should full path of files be saved
*
*/
bool mSaveFullPath{};
/**
* @brief Save all errors (true) or only visible (false)
*
*/
bool mSaveAllErrors = true;
/**
* @brief true if optional column "Id" is shown
*
*/
bool mShowErrorId{};
/**
* @brief Path we are currently checking
*
*/
QString mCheckPath;
/**
* @brief Are there any visible errors
*
*/
bool mVisibleErrors{};
private:
/** tag selected items */
void tagSelectedItems(const QString &tag);
/** @brief Convert GUI error item into data error item */
void readErrorItem(const QStandardItem *error, ErrorItem *item) const;
bool isCertReport() const {
return mReportType == ReportType::certC || mReportType == ReportType::certCpp;
}
bool isAutosarMisraReport() const {
return mReportType == ReportType::autosar ||
mReportType == ReportType::misraC ||
mReportType == ReportType::misraCpp2008 ||
mReportType == ReportType::misraCpp2023;
}
QStringList mHiddenMessageId;
QItemSelectionModel* mSelectionModel{};
ThreadHandler *mThread{};
bool mShowCppcheck = true;
bool mShowClang = true;
ReportType mReportType = ReportType::normal;
QMap<QString,QString> mGuideline;
};
/// @}
#endif // RESULTSTREE_H
| null |
728 | cpp | cppcheck | translationhandler.cpp | gui/translationhandler.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "translationhandler.h"
#include "config.h"
#include "common.h"
#include <QApplication>
#include <QCoreApplication>
#include <QFile>
#include <QFileInfo>
#include <QLocale>
#include <QMessageBox>
#include <QTranslator>
#include <QtGlobal>
// Provide own translations for standard buttons. This (garbage) code is needed to enforce them to appear in .ts files even after "lupdate gui.pro"
UNUSED static void unused()
{
Q_UNUSED(QT_TRANSLATE_NOOP("QPlatformTheme", "OK"))
Q_UNUSED(QT_TRANSLATE_NOOP("QPlatformTheme", "Cancel"))
Q_UNUSED(QT_TRANSLATE_NOOP("QPlatformTheme", "Close"))
Q_UNUSED(QT_TRANSLATE_NOOP("QPlatformTheme", "Save"))
}
TranslationHandler::TranslationHandler(QObject *parent) :
QObject(parent),
mCurrentLanguage("en")
{
// Add our available languages
// Keep this list sorted
addTranslation("Chinese (Simplified)", "cppcheck_zh_CN");
addTranslation("Chinese (Traditional)", "cppcheck_zh_TW");
addTranslation("Dutch", "cppcheck_nl");
addTranslation("English", "cppcheck_en");
addTranslation("Finnish", "cppcheck_fi");
addTranslation("French", "cppcheck_fr");
addTranslation("German", "cppcheck_de");
addTranslation("Italian", "cppcheck_it");
addTranslation("Japanese", "cppcheck_ja");
addTranslation("Georgian", "cppcheck_ka");
addTranslation("Korean", "cppcheck_ko");
addTranslation("Russian", "cppcheck_ru");
addTranslation("Serbian", "cppcheck_sr");
addTranslation("Spanish", "cppcheck_es");
addTranslation("Swedish", "cppcheck_sv");
}
bool TranslationHandler::setLanguage(const QString &code)
{
bool failure = false;
QString error;
//If English is the language. Code can be e.g. en_US
if (code.indexOf("en") == 0) {
//Just remove all extra translators
if (mTranslator) {
qApp->removeTranslator(mTranslator);
delete mTranslator;
mTranslator = nullptr;
}
mCurrentLanguage = code;
return true;
}
//Make sure the translator is otherwise valid
const int index = getLanguageIndexByCode(code);
if (index == -1) {
error = QObject::tr("Unknown language specified!");
failure = true;
} else {
// Make sure there is a translator
if (!mTranslator)
mTranslator = new QTranslator(this);
//Load the new language
const QString appPath = QFileInfo(QCoreApplication::applicationFilePath()).canonicalPath();
QString datadir = getDataDir();
QString translationFile;
if (QFile::exists(datadir + "/lang/" + mTranslations[index].mFilename + ".qm"))
translationFile = datadir + "/lang/" + mTranslations[index].mFilename + ".qm";
else if (QFile::exists(datadir + "/" + mTranslations[index].mFilename + ".qm"))
translationFile = datadir + "/" + mTranslations[index].mFilename + ".qm";
else
translationFile = appPath + "/" + mTranslations[index].mFilename + ".qm";
if (!mTranslator->load(translationFile)) {
failure = true;
//If it failed, lets check if the default file exists
if (!QFile::exists(translationFile)) {
error = QObject::tr("Language file %1 not found!");
error = error.arg(translationFile);
}
else {
//If file exists, there's something wrong with it
error = QObject::tr("Failed to load translation for language %1 from file %2");
error = error.arg(mTranslations[index].mName);
error = error.arg(translationFile);
}
}
}
if (failure) {
const QString msg(tr("Failed to change the user interface language:"
"\n\n%1\n\n"
"The user interface language has been reset to English. Open "
"the Preferences-dialog to select any of the available "
"languages.").arg(error));
QMessageBox msgBox(QMessageBox::Warning,
tr("Cppcheck"),
msg,
QMessageBox::Ok);
msgBox.exec();
return false;
}
qApp->installTranslator(mTranslator);
mCurrentLanguage = code;
return true;
}
const QString& TranslationHandler::getCurrentLanguage() const
{
return mCurrentLanguage;
}
QString TranslationHandler::suggestLanguage() const
{
//Get language from system locale's name ie sv_SE or zh_CN
QString language = QLocale::system().name();
//qDebug()<<"Your language is"<<language;
//And see if we can find it from our list of language files
const int index = getLanguageIndexByCode(language);
//If nothing found, return English
if (index < 0) {
return "en";
}
return language;
}
void TranslationHandler::addTranslation(const char *name, const char *filename)
{
TranslationInfo info;
info.mName = name;
info.mFilename = filename;
const int codeLength = QString(filename).length() - QString(filename).indexOf('_') - 1;
info.mCode = QString(filename).right(codeLength);
mTranslations.append(info);
}
int TranslationHandler::getLanguageIndexByCode(const QString &code) const
{
int index = -1;
for (int i = 0; i < mTranslations.size(); i++) {
if (mTranslations[i].mCode == code || mTranslations[i].mCode == code.left(2)) {
index = i;
break;
}
}
return index;
}
| null |
729 | cpp | cppcheck | txtreport.cpp | gui/txtreport.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2023 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "txtreport.h"
#include "erroritem.h"
#include <QDir>
#include <QFile>
#include <QList>
#include <QtGlobal>
TxtReport::TxtReport(const QString &filename) :
Report(filename)
{}
bool TxtReport::create()
{
if (Report::create()) {
mTxtWriter.setDevice(Report::getFile());
return true;
}
return false;
}
void TxtReport::writeHeader()
{
// No header for txt report
}
void TxtReport::writeFooter()
{
// No footer for txt report
}
void TxtReport::writeError(const ErrorItem &error)
{
/*
Error example from the core program in text
[gui/test.cpp:23] -> [gui/test.cpp:14]: (error) Mismatching allocation and deallocation: k
*/
QString line;
for (int i = 0; i < error.errorPath.size(); i++) {
const QString file = QDir::toNativeSeparators(error.errorPath[i].file);
line += QString("[%1:%2]").arg(file).arg(error.errorPath[i].line);
if (i < error.errorPath.size() - 1) {
line += " -> ";
}
if (i == error.errorPath.size() - 1) {
line += ": ";
}
}
QString temp = "(%1";
if (error.inconclusive) {
temp += ", ";
temp += tr("inconclusive");
}
temp += ") ";
line += temp.arg(GuiSeverity::toString(error.severity));
line += error.summary;
#if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0))
mTxtWriter << line << Qt::endl;
#else
mTxtWriter << line << endl;
#endif
}
| null |
730 | cpp | cppcheck | scratchpad.cpp | gui/scratchpad.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "scratchpad.h"
#include "codeeditor.h"
#include "mainwindow.h"
#include "ui_scratchpad.h"
#include <QLineEdit>
#include <QPushButton>
#include <QString>
ScratchPad::ScratchPad(MainWindow& mainWindow)
: QDialog(&mainWindow)
, mUI(new Ui::ScratchPad)
, mMainWindow(mainWindow)
{
mUI->setupUi(this);
connect(mUI->mCheckButton, &QPushButton::clicked, this, &ScratchPad::checkButtonClicked);
}
ScratchPad::~ScratchPad()
{
delete mUI;
}
void ScratchPad::translate()
{
mUI->retranslateUi(this);
}
void ScratchPad::checkButtonClicked()
{
QString filename = mUI->lineEdit->text();
if (filename.isEmpty())
filename = "test.cpp";
mMainWindow.analyzeCode(mUI->plainTextEdit->toPlainText(), filename);
}
| null |
731 | cpp | cppcheck | cppchecklibrarydata.cpp | gui/cppchecklibrarydata.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "cppchecklibrarydata.h"
#include "utils.h"
#include <stdexcept>
#include <string>
#include <QObject>
#include <QVariant>
#include <QXmlStreamAttributes>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
#include <QtGlobal>
#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
#include <QStringRef>
#endif
const unsigned int CppcheckLibraryData::Function::Arg::ANY = ~0U;
const unsigned int CppcheckLibraryData::Function::Arg::VARIADIC = ~1U;
static std::string unhandledElement(const QXmlStreamReader &xmlReader)
{
throw std::runtime_error(QObject::tr("line %1: Unhandled element %2").arg(xmlReader.lineNumber()).arg(xmlReader.name().toString()).toStdString());
}
static std::string mandatoryAttibuteMissing(const QXmlStreamReader &xmlReader, const QString& attributeName)
{
throw std::runtime_error(QObject::tr("line %1: Mandatory attribute '%2' missing in '%3'")
.arg(xmlReader.lineNumber())
.arg(attributeName)
.arg(xmlReader.name().toString()).toStdString());
}
static CppcheckLibraryData::Container loadContainer(QXmlStreamReader &xmlReader)
{
CppcheckLibraryData::Container container;
container.id = xmlReader.attributes().value("id").toString();
container.inherits = xmlReader.attributes().value("inherits").toString();
container.startPattern = xmlReader.attributes().value("startPattern").toString();
container.endPattern = xmlReader.attributes().value("endPattern").toString();
container.opLessAllowed = xmlReader.attributes().value("opLessAllowed").toString();
container.itEndPattern = xmlReader.attributes().value("itEndPattern").toString();
QXmlStreamReader::TokenType type;
while ((type = xmlReader.readNext()) != QXmlStreamReader::EndElement ||
xmlReader.name().toString() != "container") {
if (type != QXmlStreamReader::StartElement)
continue;
const QString elementName = xmlReader.name().toString();
if (elementName == "type") {
container.type.templateParameter = xmlReader.attributes().value("templateParameter").toString();
container.type.string = xmlReader.attributes().value("string").toString();
} else if (elementName == "size" || elementName == "access" || elementName == "other" || elementName == "rangeItemRecordType") {
const QString indexOperator = xmlReader.attributes().value("indexOperator").toString();
if (elementName == "access" && indexOperator == "array-like")
container.access_arrayLike = true;
const QString templateParameter = xmlReader.attributes().value("templateParameter").toString();
if (elementName == "size" && !templateParameter.isEmpty())
container.size_templateParameter = templateParameter.toInt();
for (;;) {
type = xmlReader.readNext();
if (xmlReader.name().toString() == elementName)
break;
if (type != QXmlStreamReader::StartElement)
continue;
CppcheckLibraryData::Container::Function function;
function.name = xmlReader.attributes().value("name").toString();
function.action = xmlReader.attributes().value("action").toString();
function.yields = xmlReader.attributes().value("yields").toString();
if (elementName == "size")
container.sizeFunctions.append(function);
else if (elementName == "access")
container.accessFunctions.append(function);
else if (elementName == "rangeItemRecordType") {
CppcheckLibraryData::Container::RangeItemRecordType rangeItemRecordType;
rangeItemRecordType.name = xmlReader.attributes().value("name").toString();
rangeItemRecordType.templateParameter = xmlReader.attributes().value("templateParameter").toString();
container.rangeItemRecordTypeList.append(rangeItemRecordType);
} else
container.otherFunctions.append(function);
}
} else {
unhandledElement(xmlReader);
}
}
return container;
}
static CppcheckLibraryData::Define loadDefine(const QXmlStreamReader &xmlReader)
{
CppcheckLibraryData::Define define;
define.name = xmlReader.attributes().value("name").toString();
define.value = xmlReader.attributes().value("value").toString();
return define;
}
static QString loadUndefine(const QXmlStreamReader &xmlReader)
{
return xmlReader.attributes().value("name").toString();
}
static CppcheckLibraryData::SmartPointer loadSmartPointer(QXmlStreamReader &xmlReader)
{
CppcheckLibraryData::SmartPointer smartPointer;
smartPointer.name = xmlReader.attributes().value("class-name").toString();
QXmlStreamReader::TokenType type;
while ((type = xmlReader.readNext()) != QXmlStreamReader::EndElement ||
xmlReader.name().toString() != "smart-pointer") {
if (type != QXmlStreamReader::StartElement)
continue;
const QString elementName = xmlReader.name().toString();
if (elementName == "unique") {
smartPointer.unique = true;
} else {
unhandledElement(xmlReader);
}
}
return smartPointer;
}
static CppcheckLibraryData::TypeChecks loadTypeChecks(QXmlStreamReader &xmlReader)
{
CppcheckLibraryData::TypeChecks typeChecks;
QXmlStreamReader::TokenType type;
while ((type = xmlReader.readNext()) != QXmlStreamReader::EndElement ||
xmlReader.name().toString() != "type-checks") {
if (type != QXmlStreamReader::StartElement)
continue;
const QString elementName = xmlReader.name().toString();
if (elementName == "suppress" || elementName == "check") {
QPair<QString, QString> entry(elementName, xmlReader.readElementText());
typeChecks.append(entry);
}
}
return typeChecks;
}
static CppcheckLibraryData::Function::Arg loadFunctionArg(QXmlStreamReader &xmlReader)
{
CppcheckLibraryData::Function::Arg arg;
QString argnr = xmlReader.attributes().value("nr").toString();
if (argnr == "any")
arg.nr = CppcheckLibraryData::Function::Arg::ANY;
else if (argnr == "variadic")
arg.nr = CppcheckLibraryData::Function::Arg::VARIADIC;
else
arg.nr = argnr.toUInt();
arg.defaultValue = xmlReader.attributes().value("default").toString();
QXmlStreamReader::TokenType type;
while ((type = xmlReader.readNext()) != QXmlStreamReader::EndElement ||
xmlReader.name().toString() != "arg") {
if (type != QXmlStreamReader::StartElement)
continue;
const QString elementName = xmlReader.name().toString();
if (elementName == "not-bool")
arg.notbool = true;
else if (elementName == "not-null")
arg.notnull = true;
else if (elementName == "not-uninit")
arg.notuninit = true;
else if (elementName == "strz")
arg.strz = true;
else if (elementName == "formatstr")
arg.formatstr = true;
else if (elementName == "valid")
arg.valid = xmlReader.readElementText();
else if (elementName == "minsize") {
CppcheckLibraryData::Function::Arg::MinSize minsize;
minsize.type = xmlReader.attributes().value("type").toString();
minsize.arg = xmlReader.attributes().value("arg").toString();
minsize.arg2 = xmlReader.attributes().value("arg2").toString();
arg.minsizes.append(minsize);
} else if (elementName == "iterator") {
arg.iterator.container = xmlReader.attributes().value("container").toInt();
arg.iterator.type = xmlReader.attributes().value("type").toString();
} else {
unhandledElement(xmlReader);
}
}
return arg;
}
static CppcheckLibraryData::Function loadFunction(QXmlStreamReader &xmlReader, const QString &comments)
{
CppcheckLibraryData::Function function;
function.comments = comments;
function.name = xmlReader.attributes().value("name").toString();
QXmlStreamReader::TokenType type;
while ((type = xmlReader.readNext()) != QXmlStreamReader::EndElement ||
xmlReader.name().toString() != "function") {
if (type != QXmlStreamReader::StartElement)
continue;
const QString elementName = xmlReader.name().toString();
if (elementName == "noreturn")
function.noreturn = (xmlReader.readElementText() == "true") ? CppcheckLibraryData::Function::True : CppcheckLibraryData::Function::False;
else if (elementName == "pure")
function.gccPure = true;
else if (elementName == "const")
function.gccConst = true;
else if (elementName == "leak-ignore")
function.leakignore = true;
else if (elementName == "use-retval")
function.useretval = true;
else if (elementName == "returnValue") {
const QString container = xmlReader.attributes().value("container").toString();
function.returnValue.container = container.isNull() ? -1 : container.toInt();
function.returnValue.type = xmlReader.attributes().value("type").toString();
function.returnValue.value = xmlReader.readElementText();
} else if (elementName == "formatstr") {
function.formatstr.scan = xmlReader.attributes().value("scan").toString();
function.formatstr.secure = xmlReader.attributes().value("secure").toString();
} else if (elementName == "arg")
function.args.append(loadFunctionArg(xmlReader));
else if (elementName == "warn") {
function.warn.severity = xmlReader.attributes().value("severity").toString();
function.warn.cstd = xmlReader.attributes().value("cstd").toString();
function.warn.reason = xmlReader.attributes().value("reason").toString();
function.warn.alternatives = xmlReader.attributes().value("alternatives").toString();
function.warn.msg = xmlReader.readElementText();
} else if (elementName == "not-overlapping-data") {
const QStringList attributeList {"ptr1-arg", "ptr2-arg", "size-arg", "strlen-arg"};
for (const QString &attr : attributeList) {
if (xmlReader.attributes().hasAttribute(attr)) {
function.notOverlappingDataArgs[attr] = xmlReader.attributes().value(attr).toString();
}
}
} else if (elementName == "container") {
const QStringList attributeList {"action", "yields"};
for (const QString &attr : attributeList) {
if (xmlReader.attributes().hasAttribute(attr)) {
function.containerAttributes[attr] = xmlReader.attributes().value(attr).toString();
}
}
} else {
unhandledElement(xmlReader);
}
}
return function;
}
static CppcheckLibraryData::MemoryResource loadMemoryResource(QXmlStreamReader &xmlReader)
{
CppcheckLibraryData::MemoryResource memoryresource;
memoryresource.type = xmlReader.name().toString();
QXmlStreamReader::TokenType type;
while ((type = xmlReader.readNext()) != QXmlStreamReader::EndElement ||
xmlReader.name().toString() != memoryresource.type) {
if (type != QXmlStreamReader::StartElement)
continue;
const QString elementName = xmlReader.name().toString();
if (elementName == "alloc" || elementName == "realloc") {
CppcheckLibraryData::MemoryResource::Alloc alloc;
alloc.isRealloc = (elementName == "realloc");
alloc.init = (xmlReader.attributes().value("init").toString() == "true");
if (xmlReader.attributes().hasAttribute("arg")) {
alloc.arg = xmlReader.attributes().value("arg").toInt();
}
if (alloc.isRealloc && xmlReader.attributes().hasAttribute("realloc-arg")) {
alloc.reallocArg = xmlReader.attributes().value("realloc-arg").toInt();
}
if (memoryresource.type == "memory") {
alloc.bufferSize = xmlReader.attributes().value("buffer-size").toString();
}
alloc.name = xmlReader.readElementText();
memoryresource.alloc.append(alloc);
} else if (elementName == "dealloc") {
CppcheckLibraryData::MemoryResource::Dealloc dealloc;
if (xmlReader.attributes().hasAttribute("arg")) {
dealloc.arg = xmlReader.attributes().value("arg").toInt();
}
dealloc.name = xmlReader.readElementText();
memoryresource.dealloc.append(dealloc);
} else if (elementName == "use")
memoryresource.use.append(xmlReader.readElementText());
else
unhandledElement(xmlReader);
}
return memoryresource;
}
static CppcheckLibraryData::PodType loadPodType(const QXmlStreamReader &xmlReader)
{
CppcheckLibraryData::PodType podtype;
podtype.name = xmlReader.attributes().value("name").toString();
if (podtype.name.isEmpty()) {
mandatoryAttibuteMissing(xmlReader, "name");
}
podtype.stdtype = xmlReader.attributes().value("stdtype").toString();
podtype.size = xmlReader.attributes().value("size").toString();
podtype.sign = xmlReader.attributes().value("sign").toString();
return podtype;
}
static CppcheckLibraryData::PlatformType loadPlatformType(QXmlStreamReader &xmlReader)
{
CppcheckLibraryData::PlatformType platformType;
platformType.name = xmlReader.attributes().value("name").toString();
platformType.value = xmlReader.attributes().value("value").toString();
QXmlStreamReader::TokenType type;
while ((type = xmlReader.readNext()) != QXmlStreamReader::EndElement ||
xmlReader.name().toString() != "platformtype") {
if (type != QXmlStreamReader::StartElement)
continue;
const QString elementName = xmlReader.name().toString();
if (QStringList({"unsigned", "long", "pointer", "const_ptr", "ptr_ptr"}).contains(elementName)) {
platformType.types.append(elementName);
} else if (elementName == "platform") {
platformType.platforms.append(xmlReader.attributes().value("type").toString());
} else {
unhandledElement(xmlReader);
}
}
return platformType;
}
static CppcheckLibraryData::Reflection loadReflection(QXmlStreamReader &xmlReader)
{
CppcheckLibraryData::Reflection reflection;
QXmlStreamReader::TokenType type;
while ((type = xmlReader.readNext()) != QXmlStreamReader::EndElement ||
xmlReader.name().toString() != "reflection") {
if (type != QXmlStreamReader::StartElement)
continue;
const QString elementName = xmlReader.name().toString();
if (elementName == "call") {
CppcheckLibraryData::Reflection::Call call;
if (xmlReader.attributes().hasAttribute("arg")) {
call.arg = xmlReader.attributes().value("arg").toInt();
} else {
mandatoryAttibuteMissing(xmlReader, "arg");
}
call.name = xmlReader.readElementText();
reflection.calls.append(call);
} else {
unhandledElement(xmlReader);
}
}
return reflection;
}
static CppcheckLibraryData::Markup loadMarkup(QXmlStreamReader &xmlReader)
{
CppcheckLibraryData::Markup markup;
QXmlStreamReader::TokenType type;
if (xmlReader.attributes().hasAttribute("ext")) {
markup.ext = xmlReader.attributes().value("ext").toString();
} else {
mandatoryAttibuteMissing(xmlReader, "ext");
}
if (xmlReader.attributes().hasAttribute("aftercode")) {
markup.afterCode = (xmlReader.attributes().value("aftercode") == QString("true"));
} else {
mandatoryAttibuteMissing(xmlReader, "aftercode");
}
if (xmlReader.attributes().hasAttribute("reporterrors")) {
markup.reportErrors = (xmlReader.attributes().value("reporterrors") == QString("true"));
} else {
mandatoryAttibuteMissing(xmlReader, "reporterrors");
}
while ((type = xmlReader.readNext()) != QXmlStreamReader::EndElement ||
xmlReader.name().toString() != "markup") {
if (type != QXmlStreamReader::StartElement)
continue;
const QString elementName = xmlReader.name().toString();
if (elementName == "keywords") {
while ((type = xmlReader.readNext()) != QXmlStreamReader::EndElement ||
xmlReader.name().toString() != "keywords") {
if (type != QXmlStreamReader::StartElement)
continue;
if (xmlReader.name().toString() == "keyword") {
markup.keywords.append(xmlReader.attributes().value("name").toString());
} else {
unhandledElement(xmlReader);
}
}
} else if (elementName == "codeblocks") {
CppcheckLibraryData::Markup::CodeBlocks codeBlock;
while ((type = xmlReader.readNext()) != QXmlStreamReader::EndElement ||
xmlReader.name().toString() != "codeblocks") {
if (type != QXmlStreamReader::StartElement)
continue;
if (xmlReader.name().toString() == "block") {
codeBlock.blocks.append(xmlReader.attributes().value("name").toString());
} else if (xmlReader.name().toString() == "structure") {
codeBlock.offset = xmlReader.attributes().value("offset").toInt();
codeBlock.start = xmlReader.attributes().value("start").toString();
codeBlock.end = xmlReader.attributes().value("end").toString();
} else {
unhandledElement(xmlReader);
}
}
markup.codeBlocks.append(codeBlock);
} else if (elementName == "exported") {
CppcheckLibraryData::Markup::Exporter exporter;
while ((type = xmlReader.readNext()) != QXmlStreamReader::EndElement ||
xmlReader.name().toString() != "exported") {
if (type != QXmlStreamReader::StartElement)
continue;
if (xmlReader.name().toString() == "exporter") {
exporter.prefix = xmlReader.attributes().value("prefix").toString();
} else if (xmlReader.name().toString() == "prefix") {
exporter.prefixList.append(xmlReader.readElementText());
} else if (xmlReader.name().toString() == "suffix") {
exporter.suffixList.append(xmlReader.readElementText());
} else {
unhandledElement(xmlReader);
}
}
markup.exporter.append(exporter);
} else if (elementName == "imported") {
while ((type = xmlReader.readNext()) != QXmlStreamReader::EndElement ||
xmlReader.name().toString() != "imported") {
if (type != QXmlStreamReader::StartElement)
continue;
if (xmlReader.name().toString() == "importer") {
markup.importer.append(xmlReader.readElementText());
} else {
unhandledElement(xmlReader);
}
}
} else {
unhandledElement(xmlReader);
}
}
return markup;
}
static CppcheckLibraryData::Entrypoint loadEntrypoint(const QXmlStreamReader &xmlReader)
{
CppcheckLibraryData::Entrypoint entrypoint;
entrypoint.name = xmlReader.attributes().value("name").toString();
return entrypoint;
}
QString CppcheckLibraryData::open(QIODevice &file)
{
clear();
QString comments;
QXmlStreamReader xmlReader(&file);
while (!xmlReader.atEnd()) {
const QXmlStreamReader::TokenType t = xmlReader.readNext();
switch (t) {
case QXmlStreamReader::Comment:
if (!comments.isEmpty())
comments += "\n";
comments += xmlReader.text().toString();
break;
case QXmlStreamReader::StartElement:
try {
const QString elementName(xmlReader.name().toString());
if (elementName == "def")
;
else if (elementName == "container")
containers.append(loadContainer(xmlReader));
else if (elementName == "define")
defines.append(loadDefine(xmlReader));
else if (elementName == "undefine")
undefines.append(loadUndefine(xmlReader));
else if (elementName == "function")
functions.append(loadFunction(xmlReader, comments));
else if (elementName == "memory" || elementName == "resource")
memoryresource.append(loadMemoryResource(xmlReader));
else if (elementName == "podtype")
podtypes.append(loadPodType(xmlReader));
else if (elementName == "smart-pointer")
smartPointers.append(loadSmartPointer(xmlReader));
else if (elementName == "type-checks")
typeChecks.append(loadTypeChecks(xmlReader));
else if (elementName == "platformtype")
platformTypes.append(loadPlatformType(xmlReader));
else if (elementName == "reflection")
reflections.append(loadReflection(xmlReader));
else if (elementName == "markup")
markups.append(loadMarkup(xmlReader));
else if (elementName == "entrypoint")
entrypoints.append(loadEntrypoint(xmlReader));
else
unhandledElement(xmlReader);
} catch (std::runtime_error &e) {
return e.what();
}
comments.clear();
break;
default:
break;
}
}
if (xmlReader.hasError())
return xmlReader.errorString();
return QString();
}
static void writeContainerFunctions(QXmlStreamWriter &xmlWriter, const QString &name, int extra, const QList<CppcheckLibraryData::Container::Function> &functions)
{
if (functions.isEmpty() && extra < 0)
return;
xmlWriter.writeStartElement(name);
if (extra >= 0) {
if (name == "access")
xmlWriter.writeAttribute("indexOperator", "array-like");
else if (name == "size")
xmlWriter.writeAttribute("templateParameter", QString::number(extra));
}
for (const CppcheckLibraryData::Container::Function &function : functions) {
xmlWriter.writeStartElement("function");
xmlWriter.writeAttribute("name", function.name);
if (!function.action.isEmpty())
xmlWriter.writeAttribute("action", function.action);
if (!function.yields.isEmpty())
xmlWriter.writeAttribute("yields", function.yields);
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
}
static void writeContainerRangeItemRecords(QXmlStreamWriter &xmlWriter, const QList<CppcheckLibraryData::Container::RangeItemRecordType> &rangeItemRecords)
{
if (rangeItemRecords.isEmpty())
return;
xmlWriter.writeStartElement("rangeItemRecordType");
for (const CppcheckLibraryData::Container::RangeItemRecordType &item : rangeItemRecords) {
xmlWriter.writeStartElement("member");
xmlWriter.writeAttribute("name", item.name);
xmlWriter.writeAttribute("templateParameter", item.templateParameter);
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
}
static void writeContainer(QXmlStreamWriter &xmlWriter, const CppcheckLibraryData::Container &container)
{
xmlWriter.writeStartElement("container");
xmlWriter.writeAttribute("id", container.id);
if (!container.startPattern.isEmpty())
xmlWriter.writeAttribute("startPattern", container.startPattern);
if (!container.endPattern.isNull())
xmlWriter.writeAttribute("endPattern", container.endPattern);
if (!container.inherits.isEmpty())
xmlWriter.writeAttribute("inherits", container.inherits);
if (!container.opLessAllowed.isEmpty())
xmlWriter.writeAttribute("opLessAllowed", container.opLessAllowed);
if (!container.itEndPattern.isEmpty())
xmlWriter.writeAttribute("itEndPattern", container.itEndPattern);
if (!container.type.templateParameter.isEmpty() || !container.type.string.isEmpty()) {
xmlWriter.writeStartElement("type");
if (!container.type.templateParameter.isEmpty())
xmlWriter.writeAttribute("templateParameter", container.type.templateParameter);
if (!container.type.string.isEmpty())
xmlWriter.writeAttribute("string", container.type.string);
xmlWriter.writeEndElement();
}
writeContainerFunctions(xmlWriter, "size", container.size_templateParameter, container.sizeFunctions);
writeContainerFunctions(xmlWriter, "access", container.access_arrayLike?1:-1, container.accessFunctions);
writeContainerFunctions(xmlWriter, "other", -1, container.otherFunctions);
writeContainerRangeItemRecords(xmlWriter, container.rangeItemRecordTypeList);
xmlWriter.writeEndElement();
}
static void writeFunction(QXmlStreamWriter &xmlWriter, const CppcheckLibraryData::Function &function)
{
QString comments = function.comments;
while (comments.startsWith("\n"))
comments = comments.mid(1);
while (comments.endsWith("\n"))
comments.chop(1);
for (const QString &comment : comments.split('\n')) {
if (comment.length() >= 1)
xmlWriter.writeComment(comment);
}
xmlWriter.writeStartElement("function");
xmlWriter.writeAttribute("name", function.name);
if (function.useretval)
xmlWriter.writeEmptyElement("use-retval");
if (function.gccConst)
xmlWriter.writeEmptyElement("const");
if (function.gccPure)
xmlWriter.writeEmptyElement("pure");
if (!function.returnValue.empty()) {
xmlWriter.writeStartElement("returnValue");
if (!function.returnValue.type.isNull())
xmlWriter.writeAttribute("type", function.returnValue.type);
if (function.returnValue.container >= 0)
xmlWriter.writeAttribute("container", QString::number(function.returnValue.container));
if (!function.returnValue.value.isNull())
xmlWriter.writeCharacters(function.returnValue.value);
xmlWriter.writeEndElement();
}
if (function.noreturn != CppcheckLibraryData::Function::Unknown)
xmlWriter.writeTextElement("noreturn", bool_to_string(function.noreturn == CppcheckLibraryData::Function::True));
if (function.leakignore)
xmlWriter.writeEmptyElement("leak-ignore");
// Argument info..
for (const CppcheckLibraryData::Function::Arg &arg : function.args) {
if (arg.formatstr) {
xmlWriter.writeStartElement("formatstr");
if (!function.formatstr.scan.isNull())
xmlWriter.writeAttribute("scan", function.formatstr.scan);
if (!function.formatstr.secure.isNull())
xmlWriter.writeAttribute("secure", function.formatstr.secure);
xmlWriter.writeEndElement();
}
xmlWriter.writeStartElement("arg");
if (arg.nr == CppcheckLibraryData::Function::Arg::ANY)
xmlWriter.writeAttribute("nr", "any");
else if (arg.nr == CppcheckLibraryData::Function::Arg::VARIADIC)
xmlWriter.writeAttribute("nr", "variadic");
else
xmlWriter.writeAttribute("nr", QString::number(arg.nr));
if (!arg.defaultValue.isNull())
xmlWriter.writeAttribute("default", arg.defaultValue);
if (arg.formatstr)
xmlWriter.writeEmptyElement("formatstr");
if (arg.notnull)
xmlWriter.writeEmptyElement("not-null");
if (arg.notuninit)
xmlWriter.writeEmptyElement("not-uninit");
if (arg.notbool)
xmlWriter.writeEmptyElement("not-bool");
if (arg.strz)
xmlWriter.writeEmptyElement("strz");
if (!arg.valid.isEmpty())
xmlWriter.writeTextElement("valid",arg.valid);
for (const CppcheckLibraryData::Function::Arg::MinSize &minsize : arg.minsizes) {
xmlWriter.writeStartElement("minsize");
xmlWriter.writeAttribute("type", minsize.type);
xmlWriter.writeAttribute("arg", minsize.arg);
if (!minsize.arg2.isEmpty())
xmlWriter.writeAttribute("arg2", minsize.arg2);
xmlWriter.writeEndElement();
}
if (arg.iterator.container >= 0 || !arg.iterator.type.isNull()) {
xmlWriter.writeStartElement("iterator");
if (arg.iterator.container >= 0)
xmlWriter.writeAttribute("container", QString::number(arg.iterator.container));
if (!arg.iterator.type.isNull())
xmlWriter.writeAttribute("type", arg.iterator.type);
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
}
if (!function.warn.isEmpty()) {
xmlWriter.writeStartElement("warn");
if (!function.warn.severity.isEmpty())
xmlWriter.writeAttribute("severity", function.warn.severity);
if (!function.warn.cstd.isEmpty())
xmlWriter.writeAttribute("cstd", function.warn.cstd);
if (!function.warn.alternatives.isEmpty())
xmlWriter.writeAttribute("alternatives", function.warn.alternatives);
if (!function.warn.reason.isEmpty())
xmlWriter.writeAttribute("reason", function.warn.reason);
if (!function.warn.msg.isEmpty())
xmlWriter.writeCharacters(function.warn.msg);
xmlWriter.writeEndElement();
}
if (!function.notOverlappingDataArgs.isEmpty()) {
xmlWriter.writeStartElement("not-overlapping-data");
for (const QString& value : function.notOverlappingDataArgs) {
xmlWriter.writeAttribute(function.notOverlappingDataArgs.key(value), value);
}
xmlWriter.writeEndElement();
}
if (!function.containerAttributes.isEmpty()) {
xmlWriter.writeStartElement("container");
for (const QString& value : function.containerAttributes) {
xmlWriter.writeAttribute(function.containerAttributes.key(value), value);
}
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
}
static void writeMemoryResource(QXmlStreamWriter &xmlWriter, const CppcheckLibraryData::MemoryResource &mr)
{
xmlWriter.writeStartElement(mr.type);
for (const CppcheckLibraryData::MemoryResource::Alloc &alloc : mr.alloc) {
if (alloc.isRealloc) {
xmlWriter.writeStartElement("realloc");
} else {
xmlWriter.writeStartElement("alloc");
}
xmlWriter.writeAttribute("init", bool_to_string(alloc.init));
if (alloc.arg != -1) {
xmlWriter.writeAttribute("arg", QString("%1").arg(alloc.arg));
}
if (alloc.isRealloc && alloc.reallocArg != -1) {
xmlWriter.writeAttribute("realloc-arg", QString("%1").arg(alloc.reallocArg));
}
if (mr.type == "memory" && !alloc.bufferSize.isEmpty()) {
xmlWriter.writeAttribute("buffer-size", alloc.bufferSize);
}
xmlWriter.writeCharacters(alloc.name);
xmlWriter.writeEndElement();
}
for (const CppcheckLibraryData::MemoryResource::Dealloc &dealloc : mr.dealloc) {
xmlWriter.writeStartElement("dealloc");
if (dealloc.arg != -1) {
xmlWriter.writeAttribute("arg", QString("%1").arg(dealloc.arg));
}
xmlWriter.writeCharacters(dealloc.name);
xmlWriter.writeEndElement();
}
for (const QString &use : mr.use) {
xmlWriter.writeTextElement("use", use);
}
xmlWriter.writeEndElement();
}
static void writeTypeChecks(QXmlStreamWriter &xmlWriter, const CppcheckLibraryData::TypeChecks &typeChecks)
{
xmlWriter.writeStartElement("type-checks");
if (!typeChecks.isEmpty()) {
xmlWriter.writeStartElement("unusedvar");
}
for (const QPair<QString, QString> &check : typeChecks) {
xmlWriter.writeStartElement(check.first);
xmlWriter.writeCharacters(check.second);
xmlWriter.writeEndElement();
}
if (!typeChecks.isEmpty()) {
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
}
static void writePlatformType(QXmlStreamWriter &xmlWriter, const CppcheckLibraryData::PlatformType &pt)
{
xmlWriter.writeStartElement("platformtype");
xmlWriter.writeAttribute("name", pt.name);
xmlWriter.writeAttribute("value", pt.value);
for (const QString &type : pt.types) {
xmlWriter.writeStartElement(type);
xmlWriter.writeEndElement();
}
for (const QString &platform : pt.platforms) {
xmlWriter.writeStartElement("platform");
if (!platform.isEmpty()) {
xmlWriter.writeAttribute("type", platform);
}
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
}
static void writeReflection(QXmlStreamWriter &xmlWriter, const CppcheckLibraryData::Reflection &refl)
{
xmlWriter.writeStartElement("reflection");
for (const CppcheckLibraryData::Reflection::Call &call : refl.calls) {
xmlWriter.writeStartElement("call");
xmlWriter.writeAttribute("arg", QString("%1").arg(call.arg));
xmlWriter.writeCharacters(call.name);
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
}
static void writeMarkup(QXmlStreamWriter &xmlWriter, const CppcheckLibraryData::Markup &mup)
{
xmlWriter.writeStartElement("markup");
xmlWriter.writeAttribute("ext", mup.ext);
xmlWriter.writeAttribute("aftercode", QVariant(mup.afterCode).toString());
xmlWriter.writeAttribute("reporterrors", QVariant(mup.reportErrors).toString());
if (!mup.keywords.isEmpty()) {
xmlWriter.writeStartElement("keywords");
for (const QString &keyword : mup.keywords) {
xmlWriter.writeStartElement("keyword");
xmlWriter.writeAttribute("name", keyword);
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
}
if (!mup.importer.isEmpty()) {
xmlWriter.writeStartElement("imported");
for (const QString &import : mup.importer) {
xmlWriter.writeStartElement("importer");
xmlWriter.writeCharacters(import);
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
}
if (!mup.exporter.isEmpty()) {
xmlWriter.writeStartElement("exported");
for (const CppcheckLibraryData::Markup::Exporter &exporter : mup.exporter) {
xmlWriter.writeStartElement("exporter");
xmlWriter.writeAttribute("prefix", exporter.prefix);
for (const QString &prefix : exporter.prefixList) {
xmlWriter.writeStartElement("prefix");
xmlWriter.writeCharacters(prefix);
xmlWriter.writeEndElement();
}
for (const QString &suffix : exporter.suffixList) {
xmlWriter.writeStartElement("suffix");
xmlWriter.writeCharacters(suffix);
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
}
if (!mup.codeBlocks.isEmpty()) {
for (const CppcheckLibraryData::Markup::CodeBlocks &codeblock : mup.codeBlocks) {
xmlWriter.writeStartElement("codeblocks");
for (const QString &block : codeblock.blocks) {
xmlWriter.writeStartElement("block");
xmlWriter.writeAttribute("name", block);
xmlWriter.writeEndElement();
}
xmlWriter.writeStartElement("structure");
xmlWriter.writeAttribute("offset", QString("%1").arg(codeblock.offset));
xmlWriter.writeAttribute("start", codeblock.start);
xmlWriter.writeAttribute("end", codeblock.end);
xmlWriter.writeEndElement();
xmlWriter.writeEndElement();
}
}
xmlWriter.writeEndElement();
}
QString CppcheckLibraryData::toString() const
{
QString outputString;
QXmlStreamWriter xmlWriter(&outputString);
xmlWriter.setAutoFormatting(true);
xmlWriter.setAutoFormattingIndent(2);
xmlWriter.writeStartDocument("1.0");
xmlWriter.writeStartElement("def");
xmlWriter.writeAttribute("format","2");
for (const Define &define : defines) {
xmlWriter.writeStartElement("define");
xmlWriter.writeAttribute("name", define.name);
xmlWriter.writeAttribute("value", define.value);
xmlWriter.writeEndElement();
}
for (const QString &undef : undefines) {
xmlWriter.writeStartElement("undefine");
xmlWriter.writeAttribute("name", undef);
xmlWriter.writeEndElement();
}
for (const Function &function : functions) {
writeFunction(xmlWriter, function);
}
for (const MemoryResource &mr : memoryresource) {
writeMemoryResource(xmlWriter, mr);
}
for (const Container &container : containers) {
writeContainer(xmlWriter, container);
}
for (const PodType &podtype : podtypes) {
xmlWriter.writeStartElement("podtype");
xmlWriter.writeAttribute("name", podtype.name);
if (!podtype.stdtype.isEmpty())
xmlWriter.writeAttribute("stdtype", podtype.stdtype);
if (!podtype.sign.isEmpty())
xmlWriter.writeAttribute("sign", podtype.sign);
if (!podtype.size.isEmpty())
xmlWriter.writeAttribute("size", podtype.size);
xmlWriter.writeEndElement();
}
for (const TypeChecks &check : typeChecks) {
writeTypeChecks(xmlWriter, check);
}
for (const SmartPointer &smartPtr : smartPointers) {
xmlWriter.writeStartElement("smart-pointer");
xmlWriter.writeAttribute("class-name", smartPtr.name);
if (smartPtr.unique) {
xmlWriter.writeEmptyElement("unique");
}
xmlWriter.writeEndElement();
}
for (const PlatformType &pt : platformTypes) {
writePlatformType(xmlWriter, pt);
}
for (const Reflection &refl : reflections) {
writeReflection(xmlWriter, refl);
}
for (const Markup &mup : markups) {
writeMarkup(xmlWriter, mup);
}
for (const Entrypoint &ent : entrypoints) {
xmlWriter.writeStartElement("entrypoint");
xmlWriter.writeAttribute("name", ent.name);
xmlWriter.writeEndElement();
}
xmlWriter.writeEndElement();
return outputString;
}
| null |
732 | cpp | cppcheck | erroritem.cpp | gui/erroritem.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "erroritem.h"
#include "common.h"
#include <list>
QErrorPathItem::QErrorPathItem(const ErrorMessage::FileLocation &loc)
: file(QString::fromStdString(loc.getfile(false)))
, line(loc.line)
, column(loc.column)
, info(QString::fromStdString(loc.getinfo()))
{}
bool operator==(const QErrorPathItem &i1, const QErrorPathItem &i2)
{
return i1.file == i2.file && i1.column == i2.column && i1.line == i2.line && i1.info == i2.info;
}
ErrorItem::ErrorItem()
: severity(Severity::none)
, inconclusive(false)
, cwe(-1)
, hash(0)
{}
ErrorItem::ErrorItem(const ErrorMessage &errmsg)
: file0(QString::fromStdString(errmsg.file0))
, errorId(QString::fromStdString(errmsg.id))
, severity(errmsg.severity)
, inconclusive(errmsg.certainty == Certainty::inconclusive)
, summary(QString::fromStdString(errmsg.shortMessage()))
, message(QString::fromStdString(errmsg.verboseMessage()))
, cwe(errmsg.cwe.id)
, hash(errmsg.hash)
, symbolNames(QString::fromStdString(errmsg.symbolNames()))
, remark(QString::fromStdString(errmsg.remark))
{
for (const auto& loc: errmsg.callStack)
errorPath << QErrorPathItem(loc);
}
QString ErrorItem::tool() const
{
if (errorId == CLANG_ANALYZER)
return CLANG_ANALYZER;
if (errorId.startsWith(CLANG_TIDY))
return CLANG_TIDY;
if (errorId.startsWith("clang-"))
return "clang";
return "cppcheck";
}
QString ErrorItem::toString() const
{
QString str = errorPath.back().file + " - " + errorId + " - ";
if (inconclusive)
str += "inconclusive ";
str += GuiSeverity::toString(severity) +"\n";
str += summary + "\n";
str += message + "\n";
for (const QErrorPathItem& i : errorPath) {
str += " " + i.file + ": " + QString::number(i.line) + "\n";
}
return str;
}
bool ErrorItem::sameCID(const ErrorItem &errorItem1, const ErrorItem &errorItem2)
{
if (errorItem1.hash || errorItem2.hash)
return errorItem1.hash == errorItem2.hash;
// fallback
return errorItem1.errorId == errorItem2.errorId &&
errorItem1.errorPath == errorItem2.errorPath &&
errorItem1.file0 == errorItem2.file0 &&
errorItem1.message == errorItem2.message &&
errorItem1.inconclusive == errorItem2.inconclusive &&
errorItem1.severity == errorItem2.severity;
}
| null |
733 | cpp | cppcheck | codeeditstylecontrols.h | gui/codeeditstylecontrols.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// widget subclass methodology derived from here:
// https://stackoverflow.com/questions/18257281/qt-color-picker-widget/43871405#43871405
#ifndef CODEEDITORSTYLECONTROLS_H
#define CODEEDITORSTYLECONTROLS_H
#include <QColor>
#include <QComboBox>
#include <QFont>
#include <QObject>
#include <QPushButton>
class QWidget;
class SelectColorButton : public QPushButton {
Q_OBJECT
public:
explicit SelectColorButton(QWidget* parent);
void setColor(const QColor& color);
const QColor& getColor() const;
signals:
// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) - caused by generated MOC code
void colorChanged(const QColor& newColor);
public slots:
void updateColor();
void changeColor();
private:
QColor mColor;
};
class SelectFontWeightCombo : public QComboBox {
Q_OBJECT
public:
explicit SelectFontWeightCombo(QWidget* parent);
void setWeight(QFont::Weight weight);
const QFont::Weight& getWeight() const;
signals:
// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) - caused by generated MOC code
void weightChanged(QFont::Weight newWeight);
public slots:
void updateWeight();
void changeWeight(int index);
private:
QFont::Weight mWeight = QFont::Normal;
};
#endif //CODEEDITORSTYLECONTROLS_H
| null |
734 | cpp | cppcheck | threadresult.h | gui/threadresult.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef THREADRESULT_H
#define THREADRESULT_H
#include "color.h"
#include "errorlogger.h"
#include "filesettings.h"
#include <list>
#include <mutex>
#include <string>
#include <QObject>
#include <QString>
#include <QStringList>
#include <QtGlobal>
class ErrorItem;
class ImportProject;
/// @addtogroup GUI
/// @{
/**
* @brief Threads use this class to obtain new files to process and to publish results
*
*/
class ThreadResult : public QObject, public ErrorLogger {
Q_OBJECT
public:
ThreadResult() = default;
/**
* @brief Get next unprocessed file
* @return File path
*/
QString getNextFile();
void getNextFileSettings(const FileSettings*& fs);
/**
* @brief Set list of files to check
* @param files List of files to check
*/
void setFiles(const QStringList &files);
void setProject(const ImportProject &prj);
/**
* @brief Clear files to check
*
*/
void clearFiles();
/**
* @brief Get the number of files to check
*
*/
int getFileCount() const;
/**
* ErrorLogger methods
*/
void reportOut(const std::string &outmsg, Color c = Color::Reset) override;
void reportErr(const ErrorMessage &msg) override;
public slots:
/**
* @brief Slot threads use to signal this class that a specific file is checked
* @param file File that is checked
*/
void fileChecked(const QString &file);
signals:
/**
* @brief Progress signal
* @param value Current progress
* @param description Description of the current stage
*/
// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) - caused by generated MOC code
void progress(int value, const QString& description);
/**
* @brief Signal of a new error
*
* @param item Error data
*/
// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) - caused by generated MOC code
void error(const ErrorItem &item);
/**
* @brief Signal of a new log message
*
* @param logline Log line
*/
// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) - caused by generated MOC code
void log(const QString &logline);
/**
* @brief Signal of a debug error
*
* @param item Error data
*/
// NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) - caused by generated MOC code
void debugError(const ErrorItem &item);
protected:
/**
* @brief Mutex
*
*/
mutable std::mutex mutex;
/**
* @brief List of files to check
*
*/
QStringList mFiles;
std::list<FileSettings> mFileSettings;
std::list<FileSettings>::const_iterator mItNextFileSettings;
/**
* @brief Max progress
*
*/
quint64 mMaxProgress{};
/**
* @brief Current progress
*
*/
quint64 mProgress{};
/**
* @brief Current number of files checked
*
*/
unsigned long mFilesChecked{};
/**
* @brief Total number of files
*
*/
unsigned long mTotalFiles{};
};
/// @}
#endif // THREADRESULT_H
| null |
735 | cpp | cppcheck | showtypes.h | gui/showtypes.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef SHOWTYPES_H
#define SHOWTYPES_H
#include <cstdint>
#include <QVariant>
enum class Severity : std::uint8_t;
/// @addtogroup GUI
/// @{
/**
* @brief A class for different show types we have.
* This class contains enum type for the different show types we have. Each
* show type presents one severity selectable in the GUI. In addition there
* are several supporting functions.
*
* Notice that the "visibility" settings are automatically loaded when the
* class is constructed and saved when the class is destroyed.
*/
class ShowTypes {
public:
/**
* @brief Show types we have (i.e. severities in the GUI).
*/
enum ShowType : std::uint8_t {
ShowStyle = 0,
ShowWarnings,
ShowPerformance,
ShowPortability,
ShowInformation,
ShowErrors, // Keep this as last real item
ShowNone
};
/**
* @brief Constructor.
* @note Loads visibility settings.
*/
ShowTypes();
/**
* @brief Destructor.
* @note Saves visibility settings.
*/
~ShowTypes();
/**
* @brief Load visibility settings from the platform's settings storage.
*/
void load();
/**
* @brief Save visibility settings to the platform's settings storage.
*/
void save() const;
/**
* @brief Is the showtype visible in the GUI?
* @param category Showtype to check.
* @return true if the showtype is visible.
*/
bool isShown(ShowTypes::ShowType category) const;
/**
* @brief Is the severity visible in the GUI?
* @param severity severity to check.
* @return true if the severity is visible.
*/
bool isShown(Severity severity) const;
/**
* @brief Show/hide the showtype.
* @param category Showtype whose visibility to set.
* @param showing true if the severity is set visible.
*/
void show(ShowTypes::ShowType category, bool showing);
/**
* @brief Convert severity string to ShowTypes value
* @param severity Error severity
* @return Severity converted to ShowTypes value
*/
static ShowTypes::ShowType SeverityToShowType(Severity severity);
/**
* @brief Convert ShowType to severity string
* @param type ShowType to convert
* @return ShowType converted to severity
*/
static Severity ShowTypeToSeverity(ShowTypes::ShowType type);
/**
* @brief Convert QVariant (that contains an int) to Showtypes value
*
* @param data QVariant (that contains an int) to be converted
* @return data converted to ShowTypes
*/
static ShowTypes::ShowType VariantToShowType(const QVariant &data);
bool mVisible[ShowNone];
};
/// @}
#endif // SHOWTYPES_H
| null |
736 | cpp | cppcheck | projectfiledialog.cpp | gui/projectfiledialog.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "projectfiledialog.h"
#include "checkthread.h"
#include "common.h"
#include "importproject.h"
#include "library.h"
#include "newsuppressiondialog.h"
#include "platform.h"
#include "platforms.h"
#include "projectfile.h"
#include "settings.h"
#include "ui_projectfile.h"
#include <list>
#include <string>
#include <utility>
#include <QByteArray>
#include <QCheckBox>
#include <QComboBox>
#include <QCoreApplication>
#include <QDialogButtonBox>
#include <QDir>
#include <QFileDialog>
#include <QFileInfo>
#include <QFlags>
#include <QLabel>
#include <QLineEdit>
#include <QListWidget>
#include <QListWidgetItem>
#include <QMap>
#include <QObject>
#include <QPushButton>
#include <QRadioButton>
#include <QRegularExpression>
#include <QRegularExpressionValidator>
#include <QSettings>
#include <QSize>
#include <QSpinBox>
#include <QVariant>
static constexpr char ADDON_MISRA[] = "misra";
static constexpr char CODING_STANDARD_MISRA_C_2023[] = "misra-c-2023";
static constexpr char CODING_STANDARD_MISRA_CPP_2008[] = "misra-cpp-2008";
static constexpr char CODING_STANDARD_MISRA_CPP_2023[] = "misra-cpp-2023";
static constexpr char CODING_STANDARD_CERT_C[] = "cert-c-2016";
static constexpr char CODING_STANDARD_CERT_CPP[] = "cert-cpp-2016";
static constexpr char CODING_STANDARD_AUTOSAR[] = "autosar";
/** Return paths from QListWidget */
static QStringList getPaths(const QListWidget *list)
{
const int count = list->count();
QStringList paths;
for (int i = 0; i < count; i++) {
QListWidgetItem *item = list->item(i);
paths << QDir::fromNativeSeparators(item->text());
}
return paths;
}
/** Platforms shown in the platform combobox */
static constexpr Platform::Type builtinPlatforms[] = {
Platform::Type::Native,
Platform::Type::Win32A,
Platform::Type::Win32W,
Platform::Type::Win64,
Platform::Type::Unix32,
Platform::Type::Unix64
};
static constexpr int numberOfBuiltinPlatforms = sizeof(builtinPlatforms) / sizeof(builtinPlatforms[0]);
QStringList ProjectFileDialog::getProjectConfigs(const QString &fileName)
{
if (!fileName.endsWith(".sln") && !fileName.endsWith(".vcxproj"))
return QStringList();
QStringList ret;
ImportProject importer;
Settings projSettings;
importer.import(fileName.toStdString(), &projSettings);
for (const std::string &cfg : importer.getVSConfigs())
ret << QString::fromStdString(cfg);
return ret;
}
ProjectFileDialog::ProjectFileDialog(ProjectFile *projectFile, bool premium, QWidget *parent)
: QDialog(parent)
, mUI(new Ui::ProjectFile)
, mProjectFile(projectFile)
, mPremium(premium)
{
mUI->setupUi(this);
mUI->mToolClangAnalyzer->hide();
const QFileInfo inf(projectFile->getFilename());
QString filename = inf.fileName();
QString title = tr("Project file: %1").arg(filename);
setWindowTitle(title);
loadSettings();
mUI->premiumLicense->setVisible(false);
// Checkboxes for the libraries..
const QString applicationFilePath = QCoreApplication::applicationFilePath();
const QString appPath = QFileInfo(applicationFilePath).canonicalPath();
const QString datadir = getDataDir();
QStringList searchPaths;
searchPaths << appPath << appPath + "/cfg" << inf.canonicalPath();
#ifdef FILESDIR
if (FILESDIR[0])
searchPaths << FILESDIR << FILESDIR "/cfg";
#endif
if (!datadir.isEmpty())
searchPaths << datadir << datadir + "/cfg";
QStringList libs;
// Search the std.cfg first since other libraries could depend on it
QString stdLibraryFilename;
for (const QString &sp : searchPaths) {
QDir dir(sp);
dir.setSorting(QDir::Name);
dir.setNameFilters(QStringList("*.cfg"));
dir.setFilter(QDir::Files | QDir::NoDotAndDotDot);
for (const QFileInfo& item : dir.entryInfoList()) {
QString library = item.fileName();
if (library.compare("std.cfg", Qt::CaseInsensitive) != 0)
continue;
Library lib;
const QString fullfilename = sp + "/" + library;
const Library::Error err = lib.load(nullptr, fullfilename.toLatin1());
if (err.errorcode != Library::ErrorCode::OK)
continue;
// Working std.cfg found
stdLibraryFilename = fullfilename;
break;
}
if (!stdLibraryFilename.isEmpty())
break;
}
// Search other libraries
for (const QString &sp : searchPaths) {
QDir dir(sp);
dir.setSorting(QDir::Name);
dir.setNameFilters(QStringList("*.cfg"));
dir.setFilter(QDir::Files | QDir::NoDotAndDotDot);
for (const QFileInfo& item : dir.entryInfoList()) {
QString library = item.fileName();
{
Library lib;
const QString fullfilename = sp + "/" + library;
Library::Error err = lib.load(nullptr, fullfilename.toLatin1());
if (err.errorcode != Library::ErrorCode::OK) {
// Some libraries depend on std.cfg so load it first and test again
lib.load(nullptr, stdLibraryFilename.toLatin1());
err = lib.load(nullptr, fullfilename.toLatin1());
}
if (err.errorcode != Library::ErrorCode::OK)
continue;
}
library.chop(4);
if (library.compare("std", Qt::CaseInsensitive) == 0)
continue;
if (libs.indexOf(library) == -1)
libs << library;
}
}
libs.sort();
mUI->mLibraries->clear();
for (const QString &lib : libs) {
auto* item = new QListWidgetItem(lib, mUI->mLibraries);
item->setFlags(item->flags() | Qt::ItemIsUserCheckable); // set checkable flag
item->setCheckState(Qt::Unchecked); // AND initialize check state
}
// Platforms..
Platforms platforms;
for (const Platform::Type builtinPlatform : builtinPlatforms)
mUI->mComboBoxPlatform->addItem(platforms.get(builtinPlatform).mTitle);
QStringList platformFiles;
for (QString sp : searchPaths) {
if (sp.endsWith("/cfg"))
sp = sp.mid(0,sp.length()-3) + "platforms";
QDir dir(sp);
dir.setSorting(QDir::Name);
dir.setNameFilters(QStringList("*.xml"));
dir.setFilter(QDir::Files | QDir::NoDotAndDotDot);
for (const QFileInfo& item : dir.entryInfoList()) {
const QString platformFile = item.fileName();
Platform plat2;
if (!plat2.loadFromFile(applicationFilePath.toStdString().c_str(), platformFile.toStdString()))
continue;
if (platformFiles.indexOf(platformFile) == -1)
platformFiles << platformFile;
}
}
platformFiles.sort();
mUI->mComboBoxPlatform->addItems(platformFiles);
// integer. allow empty.
mUI->mEditCertIntPrecision->setValidator(new QRegularExpressionValidator(QRegularExpression("[0-9]*"),this));
mUI->mEditTags->setValidator(new QRegularExpressionValidator(QRegularExpression("[a-zA-Z0-9 ;]*"),this));
const QRegularExpression undefRegExp("\\s*([a-zA-Z_][a-zA-Z0-9_]*[; ]*)*");
mUI->mEditUndefines->setValidator(new QRegularExpressionValidator(undefRegExp, this));
connect(mUI->mButtons, &QDialogButtonBox::accepted, this, &ProjectFileDialog::ok);
connect(mUI->mBtnBrowseBuildDir, &QPushButton::clicked, this, &ProjectFileDialog::browseBuildDir);
connect(mUI->mBtnClearImportProject, &QPushButton::clicked, this, &ProjectFileDialog::clearImportProject);
connect(mUI->mBtnBrowseImportProject, &QPushButton::clicked, this, &ProjectFileDialog::browseImportProject);
connect(mUI->mBtnAddCheckPath, SIGNAL(clicked()), this, SLOT(addCheckPath()));
connect(mUI->mBtnEditCheckPath, &QPushButton::clicked, this, &ProjectFileDialog::editCheckPath);
connect(mUI->mBtnRemoveCheckPath, &QPushButton::clicked, this, &ProjectFileDialog::removeCheckPath);
connect(mUI->mBtnAddInclude, SIGNAL(clicked()), this, SLOT(addIncludeDir()));
connect(mUI->mBtnEditInclude, &QPushButton::clicked, this, &ProjectFileDialog::editIncludeDir);
connect(mUI->mBtnRemoveInclude, &QPushButton::clicked, this, &ProjectFileDialog::removeIncludeDir);
connect(mUI->mBtnAddIgnorePath, SIGNAL(clicked()), this, SLOT(addExcludePath()));
connect(mUI->mBtnAddIgnoreFile, SIGNAL(clicked()), this, SLOT(addExcludeFile()));
connect(mUI->mBtnEditIgnorePath, &QPushButton::clicked, this, &ProjectFileDialog::editExcludePath);
connect(mUI->mBtnRemoveIgnorePath, &QPushButton::clicked, this, &ProjectFileDialog::removeExcludePath);
connect(mUI->mBtnIncludeUp, &QPushButton::clicked, this, &ProjectFileDialog::moveIncludePathUp);
connect(mUI->mBtnIncludeDown, &QPushButton::clicked, this, &ProjectFileDialog::moveIncludePathDown);
connect(mUI->mBtnAddSuppression, &QPushButton::clicked, this, &ProjectFileDialog::addSuppression);
connect(mUI->mBtnRemoveSuppression, &QPushButton::clicked, this, &ProjectFileDialog::removeSuppression);
connect(mUI->mListSuppressions, &QListWidget::doubleClicked, this, &ProjectFileDialog::editSuppression);
connect(mUI->mBtnBrowseMisraFile, &QPushButton::clicked, this, &ProjectFileDialog::browseMisraFile);
connect(mUI->mChkAllVsConfigs, &QCheckBox::clicked, this, &ProjectFileDialog::checkAllVSConfigs);
loadFromProjectFile(projectFile);
}
ProjectFileDialog::~ProjectFileDialog()
{
saveSettings();
delete mUI;
}
void ProjectFileDialog::loadSettings()
{
QSettings settings;
resize(settings.value(SETTINGS_PROJECT_DIALOG_WIDTH, 470).toInt(),
settings.value(SETTINGS_PROJECT_DIALOG_HEIGHT, 330).toInt());
}
void ProjectFileDialog::saveSettings() const
{
QSettings settings;
settings.setValue(SETTINGS_PROJECT_DIALOG_WIDTH, size().width());
settings.setValue(SETTINGS_PROJECT_DIALOG_HEIGHT, size().height());
}
static void updateAddonCheckBox(QCheckBox *cb, const ProjectFile *projectFile, const QString &dataDir, const QString &addon)
{
if (projectFile)
cb->setChecked(projectFile->getAddons().contains(addon));
if (ProjectFile::getAddonFilePath(dataDir, addon).isEmpty()) {
cb->setEnabled(false);
cb->setText(cb->text() + QObject::tr(" (Not found)"));
}
}
void ProjectFileDialog::checkAllVSConfigs()
{
if (mUI->mChkAllVsConfigs->isChecked()) {
for (int row = 0; row < mUI->mListVsConfigs->count(); ++row) {
QListWidgetItem *item = mUI->mListVsConfigs->item(row);
item->setCheckState(Qt::Checked);
}
}
mUI->mListVsConfigs->setEnabled(!mUI->mChkAllVsConfigs->isChecked());
}
void ProjectFileDialog::loadFromProjectFile(const ProjectFile *projectFile)
{
setRootPath(projectFile->getRootPath());
setBuildDir(projectFile->getBuildDir());
setIncludepaths(projectFile->getIncludeDirs());
setDefines(projectFile->getDefines());
setUndefines(projectFile->getUndefines());
setCheckPaths(projectFile->getCheckPaths());
setImportProject(projectFile->getImportProject());
mUI->mChkAllVsConfigs->setChecked(projectFile->getAnalyzeAllVsConfigs());
setProjectConfigurations(getProjectConfigs(mUI->mEditImportProject->text()));
for (int row = 0; row < mUI->mListVsConfigs->count(); ++row) {
QListWidgetItem *item = mUI->mListVsConfigs->item(row);
if (projectFile->getAnalyzeAllVsConfigs() || projectFile->getVsConfigurations().contains(item->text()))
item->setCheckState(Qt::Checked);
else
item->setCheckState(Qt::Unchecked);
}
switch (projectFile->getCheckLevel()) {
case ProjectFile::CheckLevel::reduced:
mUI->mCheckLevelReduced->setChecked(true);
break;
case ProjectFile::CheckLevel::normal:
mUI->mCheckLevelNormal->setChecked(true);
break;
case ProjectFile::CheckLevel::exhaustive:
mUI->mCheckLevelExhaustive->setChecked(true);
break;
};
mUI->mCheckHeaders->setChecked(projectFile->getCheckHeaders());
mUI->mCheckUnusedTemplates->setChecked(projectFile->getCheckUnusedTemplates());
mUI->mInlineSuppressions->setChecked(projectFile->getInlineSuppression());
mUI->mMaxCtuDepth->setValue(projectFile->getMaxCtuDepth());
mUI->mMaxTemplateRecursion->setValue(projectFile->getMaxTemplateRecursion());
if (projectFile->clangParser)
mUI->mBtnClangParser->setChecked(true);
else
mUI->mBtnCppcheckParser->setChecked(true);
mUI->mBtnSafeClasses->setChecked(projectFile->safeChecks.classes);
setExcludedPaths(projectFile->getExcludedPaths());
setLibraries(projectFile->getLibraries());
const QString& platform = projectFile->getPlatform();
if (platform.endsWith(".xml")) {
int i;
for (i = numberOfBuiltinPlatforms; i < mUI->mComboBoxPlatform->count(); ++i) {
if (mUI->mComboBoxPlatform->itemText(i) == platform)
break;
}
if (i < mUI->mComboBoxPlatform->count())
mUI->mComboBoxPlatform->setCurrentIndex(i);
else {
mUI->mComboBoxPlatform->addItem(platform);
mUI->mComboBoxPlatform->setCurrentIndex(i);
}
} else {
int i;
for (i = 0; i < numberOfBuiltinPlatforms; ++i) {
const Platform::Type p = builtinPlatforms[i];
if (platform == Platform::toString(p))
break;
}
if (i < numberOfBuiltinPlatforms)
mUI->mComboBoxPlatform->setCurrentIndex(i);
else
mUI->mComboBoxPlatform->setCurrentIndex(-1);
}
mUI->mComboBoxPlatform->setCurrentText(projectFile->getPlatform());
setSuppressions(projectFile->getSuppressions());
// TODO
// Human knowledge..
/*
mUI->mListUnknownFunctionReturn->clear();
mUI->mListUnknownFunctionReturn->addItem("rand()");
for (int row = 0; row < mUI->mListUnknownFunctionReturn->count(); ++row) {
QListWidgetItem *item = mUI->mListUnknownFunctionReturn->item(row);
item->setFlags(item->flags() | Qt::ItemIsUserCheckable); // set checkable flag
const bool unknownValues = projectFile->getCheckUnknownFunctionReturn().contains(item->text());
item->setCheckState(unknownValues ? Qt::Checked : Qt::Unchecked); // AND initialize check state
}
mUI->mCheckSafeClasses->setChecked(projectFile->getSafeChecks().classes);
mUI->mCheckSafeExternalFunctions->setChecked(projectFile->getSafeChecks().externalFunctions);
mUI->mCheckSafeInternalFunctions->setChecked(projectFile->getSafeChecks().internalFunctions);
mUI->mCheckSafeExternalVariables->setChecked(projectFile->getSafeChecks().externalVariables);
*/
// Addons..
QSettings settings;
const QString dataDir = getDataDir();
updateAddonCheckBox(mUI->mAddonThreadSafety, projectFile, dataDir, "threadsafety");
updateAddonCheckBox(mUI->mAddonY2038, projectFile, dataDir, "y2038");
// Misra checkbox..
if (mPremium)
mUI->mMisraC->setText("Misra C");
else
mUI->mMisraC->setText("Misra C 2012 " + tr("Note: Open source Cppcheck does not fully implement Misra C 2012"));
updateAddonCheckBox(mUI->mMisraC, projectFile, dataDir, ADDON_MISRA);
mUI->mMisraVersion->setEnabled(mUI->mMisraC->isChecked());
connect(mUI->mMisraC, &QCheckBox::toggled, mUI->mMisraVersion, &QComboBox::setEnabled);
const QString &misraFile = settings.value(SETTINGS_MISRA_FILE, QString()).toString();
mUI->mEditMisraFile->setText(misraFile);
mUI->mMisraVersion->setVisible(mPremium);
mUI->mMisraVersion->setCurrentIndex(projectFile->getCodingStandards().contains(CODING_STANDARD_MISRA_C_2023));
if (mPremium) {
mUI->mLabelMisraFile->setVisible(false);
mUI->mEditMisraFile->setVisible(false);
mUI->mBtnBrowseMisraFile->setVisible(false);
} else if (!mUI->mMisraC->isEnabled()) {
mUI->mEditMisraFile->setEnabled(false);
mUI->mBtnBrowseMisraFile->setEnabled(false);
}
mUI->mMisraCpp->setEnabled(mPremium);
mUI->mMisraCppVersion->setVisible(mPremium);
if (projectFile->getCodingStandards().contains(CODING_STANDARD_MISRA_CPP_2008)) {
mUI->mMisraCpp->setChecked(true);
mUI->mMisraCppVersion->setCurrentIndex(0);
}
else if (projectFile->getCodingStandards().contains(CODING_STANDARD_MISRA_CPP_2023)) {
mUI->mMisraCpp->setChecked(true);
mUI->mMisraCppVersion->setCurrentIndex(1);
} else {
mUI->mMisraCpp->setChecked(false);
mUI->mMisraCppVersion->setCurrentIndex(1);
}
mUI->mMisraCppVersion->setEnabled(mUI->mMisraCpp->isChecked());
connect(mUI->mMisraCpp, &QCheckBox::toggled, mUI->mMisraCppVersion, &QComboBox::setEnabled);
mUI->mCertC2016->setChecked(mPremium && projectFile->getCodingStandards().contains(CODING_STANDARD_CERT_C));
mUI->mCertCpp2016->setChecked(mPremium && projectFile->getCodingStandards().contains(CODING_STANDARD_CERT_CPP));
mUI->mAutosar->setChecked(mPremium && projectFile->getCodingStandards().contains(CODING_STANDARD_AUTOSAR));
if (projectFile->getCertIntPrecision() <= 0)
mUI->mEditCertIntPrecision->setText(QString());
else
mUI->mEditCertIntPrecision->setText(QString::number(projectFile->getCertIntPrecision()));
mUI->mCertC2016->setEnabled(mPremium);
mUI->mCertCpp2016->setEnabled(mPremium);
mUI->mAutosar->setEnabled(mPremium);
mUI->mLabelCertIntPrecision->setVisible(mPremium);
mUI->mEditCertIntPrecision->setVisible(mPremium);
mUI->mBughunting->setChecked(mPremium && projectFile->getBughunting());
mUI->mBughunting->setEnabled(mPremium);
mUI->mToolClangAnalyzer->setChecked(projectFile->getClangAnalyzer());
mUI->mToolClangTidy->setChecked(projectFile->getClangTidy());
if (CheckThread::clangTidyCmd().isEmpty()) {
mUI->mToolClangTidy->setText(tr("Clang-tidy (not found)"));
mUI->mToolClangTidy->setEnabled(false);
}
mUI->mEditTags->setText(projectFile->getTags().join(';'));
mUI->mEditLicenseFile->setText(projectFile->getLicenseFile());
updatePathsAndDefines();
}
void ProjectFileDialog::saveToProjectFile(ProjectFile *projectFile) const
{
projectFile->setRootPath(getRootPath());
projectFile->setBuildDir(getBuildDir());
projectFile->setImportProject(getImportProject());
projectFile->setAnalyzeAllVsConfigs(mUI->mChkAllVsConfigs->isChecked());
projectFile->setVSConfigurations(getProjectConfigurations());
projectFile->setCheckHeaders(mUI->mCheckHeaders->isChecked());
projectFile->setCheckUnusedTemplates(mUI->mCheckUnusedTemplates->isChecked());
projectFile->setInlineSuppression(mUI->mInlineSuppressions->isChecked());
projectFile->setMaxCtuDepth(mUI->mMaxCtuDepth->value());
projectFile->setMaxTemplateRecursion(mUI->mMaxTemplateRecursion->value());
projectFile->setIncludes(getIncludePaths());
projectFile->setDefines(getDefines());
projectFile->setUndefines(getUndefines());
projectFile->setCheckPaths(getCheckPaths());
projectFile->setExcludedPaths(getExcludedPaths());
projectFile->setLibraries(getLibraries());
if (mUI->mCheckLevelReduced->isChecked())
projectFile->setCheckLevel(ProjectFile::CheckLevel::reduced);
else if (mUI->mCheckLevelNormal->isChecked())
projectFile->setCheckLevel(ProjectFile::CheckLevel::normal);
else // if (mUI->mCheckLevelExhaustive->isChecked())
projectFile->setCheckLevel(ProjectFile::CheckLevel::exhaustive);
projectFile->clangParser = mUI->mBtnClangParser->isChecked();
projectFile->safeChecks.classes = mUI->mBtnSafeClasses->isChecked();
if (mUI->mComboBoxPlatform->currentText().endsWith(".xml"))
projectFile->setPlatform(mUI->mComboBoxPlatform->currentText());
else {
const int i = mUI->mComboBoxPlatform->currentIndex();
if (i>=0 && i < numberOfBuiltinPlatforms)
projectFile->setPlatform(Platform::toString(builtinPlatforms[i]));
else
projectFile->setPlatform(QString());
}
projectFile->setSuppressions(getSuppressions());
// Human knowledge
/*
QStringList unknownReturnValues;
for (int row = 0; row < mUI->mListUnknownFunctionReturn->count(); ++row) {
QListWidgetItem *item = mUI->mListUnknownFunctionReturn->item(row);
if (item->checkState() == Qt::Checked)
unknownReturnValues << item->text();
}
projectFile->setCheckUnknownFunctionReturn(unknownReturnValues);
ProjectFile::SafeChecks safeChecks;
safeChecks.classes = mUI->mCheckSafeClasses->isChecked();
safeChecks.externalFunctions = mUI->mCheckSafeExternalFunctions->isChecked();
safeChecks.internalFunctions = mUI->mCheckSafeInternalFunctions->isChecked();
safeChecks.externalVariables = mUI->mCheckSafeExternalVariables->isChecked();
projectFile->setSafeChecks(safeChecks);
*/
// Addons
QStringList addons;
if (mUI->mAddonThreadSafety->isChecked())
addons << "threadsafety";
if (mUI->mAddonY2038->isChecked())
addons << "y2038";
if (mUI->mMisraC->isChecked())
addons << ADDON_MISRA;
projectFile->setAddons(addons);
QStringList codingStandards;
if (mUI->mCertC2016->isChecked())
codingStandards << CODING_STANDARD_CERT_C;
if (mUI->mCertCpp2016->isChecked())
codingStandards << CODING_STANDARD_CERT_CPP;
if (mPremium && mUI->mMisraVersion->currentIndex() == 1)
codingStandards << CODING_STANDARD_MISRA_C_2023;
if (mUI->mMisraCpp->isChecked() && mUI->mMisraCppVersion->currentIndex() == 0)
codingStandards << CODING_STANDARD_MISRA_CPP_2008;
if (mUI->mMisraCpp->isChecked() && mUI->mMisraCppVersion->currentIndex() == 1)
codingStandards << CODING_STANDARD_MISRA_CPP_2023;
if (mUI->mAutosar->isChecked())
codingStandards << CODING_STANDARD_AUTOSAR;
projectFile->setCodingStandards(std::move(codingStandards));
projectFile->setCertIntPrecision(mUI->mEditCertIntPrecision->text().toInt());
projectFile->setBughunting(mUI->mBughunting->isChecked());
projectFile->setClangAnalyzer(mUI->mToolClangAnalyzer->isChecked());
projectFile->setClangTidy(mUI->mToolClangTidy->isChecked());
projectFile->setLicenseFile(mUI->mEditLicenseFile->text());
#if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0))
projectFile->setTags(mUI->mEditTags->text().split(";", Qt::SkipEmptyParts));
#else
projectFile->setTags(mUI->mEditTags->text().split(";", QString::SkipEmptyParts));
#endif
}
void ProjectFileDialog::ok()
{
saveToProjectFile(mProjectFile);
mProjectFile->write();
accept();
}
QString ProjectFileDialog::getExistingDirectory(const QString &caption, bool trailingSlash)
{
const QFileInfo inf(mProjectFile->getFilename());
const QString projectPath = inf.absolutePath();
QString selectedDir = QFileDialog::getExistingDirectory(this,
caption,
projectPath);
if (selectedDir.isEmpty())
return QString();
// Check if the path is relative to project file's path and if so
// make it a relative path instead of absolute path.
const QDir dir(projectPath);
const QString relpath(dir.relativeFilePath(selectedDir));
if (!relpath.startsWith("../.."))
selectedDir = relpath;
// Trailing slash..
if (trailingSlash && !selectedDir.endsWith('/'))
selectedDir += '/';
return selectedDir;
}
void ProjectFileDialog::browseBuildDir()
{
const QString dir(getExistingDirectory(tr("Select Cppcheck build dir"), false));
if (!dir.isEmpty())
mUI->mEditBuildDir->setText(dir);
}
void ProjectFileDialog::updatePathsAndDefines()
{
const QString &fileName = mUI->mEditImportProject->text();
const bool importProject = !fileName.isEmpty();
const bool hasConfigs = fileName.endsWith(".sln") || fileName.endsWith(".vcxproj");
mUI->mBtnClearImportProject->setEnabled(importProject);
mUI->mListCheckPaths->setEnabled(!importProject);
mUI->mListIncludeDirs->setEnabled(!importProject);
mUI->mBtnAddCheckPath->setEnabled(!importProject);
mUI->mBtnEditCheckPath->setEnabled(!importProject);
mUI->mBtnRemoveCheckPath->setEnabled(!importProject);
mUI->mEditUndefines->setEnabled(!importProject);
mUI->mBtnAddInclude->setEnabled(!importProject);
mUI->mBtnEditInclude->setEnabled(!importProject);
mUI->mBtnRemoveInclude->setEnabled(!importProject);
mUI->mBtnIncludeUp->setEnabled(!importProject);
mUI->mBtnIncludeDown->setEnabled(!importProject);
mUI->mChkAllVsConfigs->setEnabled(hasConfigs);
mUI->mListVsConfigs->setEnabled(hasConfigs && !mUI->mChkAllVsConfigs->isChecked());
if (!hasConfigs)
mUI->mListVsConfigs->clear();
}
void ProjectFileDialog::clearImportProject()
{
mUI->mEditImportProject->clear();
updatePathsAndDefines();
}
void ProjectFileDialog::browseImportProject()
{
const QFileInfo inf(mProjectFile->getFilename());
const QDir &dir = inf.absoluteDir();
QMap<QString,QString> filters;
filters[tr("Visual Studio")] = "*.sln *.vcxproj";
filters[tr("Compile database")] = "compile_commands.json";
filters[tr("Borland C++ Builder 6")] = "*.bpr";
QString fileName = QFileDialog::getOpenFileName(this, tr("Import Project"),
dir.canonicalPath(),
toFilterString(filters));
if (!fileName.isEmpty()) {
mUI->mEditImportProject->setText(dir.relativeFilePath(fileName));
updatePathsAndDefines();
setProjectConfigurations(getProjectConfigs(fileName));
for (int row = 0; row < mUI->mListVsConfigs->count(); ++row) {
QListWidgetItem *item = mUI->mListVsConfigs->item(row);
item->setCheckState(Qt::Checked);
}
}
}
QStringList ProjectFileDialog::getProjectConfigurations() const
{
QStringList configs;
for (int row = 0; row < mUI->mListVsConfigs->count(); ++row) {
QListWidgetItem *item = mUI->mListVsConfigs->item(row);
if (item->checkState() == Qt::Checked)
configs << item->text();
}
return configs;
}
void ProjectFileDialog::setProjectConfigurations(const QStringList &configs)
{
mUI->mListVsConfigs->clear();
mUI->mListVsConfigs->setEnabled(!configs.isEmpty() && !mUI->mChkAllVsConfigs->isChecked());
for (const QString &cfg : configs) {
auto* item = new QListWidgetItem(cfg, mUI->mListVsConfigs);
item->setFlags(item->flags() | Qt::ItemIsUserCheckable); // set checkable flag
item->setCheckState(Qt::Unchecked);
}
}
QString ProjectFileDialog::getImportProject() const
{
return mUI->mEditImportProject->text();
}
void ProjectFileDialog::addIncludeDir(const QString &dir)
{
if (dir.isEmpty())
return;
const QString newdir = QDir::toNativeSeparators(dir);
auto *item = new QListWidgetItem(newdir);
item->setFlags(item->flags() | Qt::ItemIsEditable);
mUI->mListIncludeDirs->addItem(item);
}
void ProjectFileDialog::addCheckPath(const QString &path)
{
if (path.isEmpty())
return;
const QString newpath = QDir::toNativeSeparators(path);
auto *item = new QListWidgetItem(newpath);
item->setFlags(item->flags() | Qt::ItemIsEditable);
mUI->mListCheckPaths->addItem(item);
}
void ProjectFileDialog::addExcludePath(const QString &path)
{
if (path.isEmpty())
return;
const QString newpath = QDir::toNativeSeparators(path);
auto *item = new QListWidgetItem(newpath);
item->setFlags(item->flags() | Qt::ItemIsEditable);
mUI->mListExcludedPaths->addItem(item);
}
QString ProjectFileDialog::getRootPath() const
{
QString root = mUI->mEditProjectRoot->text();
root = root.trimmed();
root = QDir::fromNativeSeparators(root);
return root;
}
QString ProjectFileDialog::getBuildDir() const
{
return mUI->mEditBuildDir->text();
}
QStringList ProjectFileDialog::getIncludePaths() const
{
return getPaths(mUI->mListIncludeDirs);
}
QStringList ProjectFileDialog::getDefines() const
{
#if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0))
return mUI->mEditDefines->text().trimmed().split(QRegularExpression("\\s*;\\s*"), Qt::SkipEmptyParts);
#else
return mUI->mEditDefines->text().trimmed().split(QRegularExpression("\\s*;\\s*"), QString::SkipEmptyParts);
#endif
}
QStringList ProjectFileDialog::getUndefines() const
{
const QString undefine = mUI->mEditUndefines->text().trimmed();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0))
QStringList undefines = undefine.split(QRegularExpression("\\s*;\\s*"), Qt::SkipEmptyParts);
#else
QStringList undefines = undefine.split(QRegularExpression("\\s*;\\s*"), QString::SkipEmptyParts);
#endif
undefines.removeDuplicates();
return undefines;
}
QStringList ProjectFileDialog::getCheckPaths() const
{
return getPaths(mUI->mListCheckPaths);
}
QStringList ProjectFileDialog::getExcludedPaths() const
{
return getPaths(mUI->mListExcludedPaths);
}
QStringList ProjectFileDialog::getLibraries() const
{
QStringList libraries;
for (int row = 0; row < mUI->mLibraries->count(); ++row) {
QListWidgetItem *item = mUI->mLibraries->item(row);
if (item->checkState() == Qt::Checked)
libraries << item->text();
}
return libraries;
}
void ProjectFileDialog::setRootPath(const QString &root)
{
mUI->mEditProjectRoot->setText(QDir::toNativeSeparators(root));
}
void ProjectFileDialog::setBuildDir(const QString &buildDir)
{
mUI->mEditBuildDir->setText(buildDir);
}
void ProjectFileDialog::setImportProject(const QString &importProject)
{
mUI->mEditImportProject->setText(importProject);
}
void ProjectFileDialog::setIncludepaths(const QStringList &includes)
{
for (const QString& dir : includes) {
addIncludeDir(dir);
}
}
void ProjectFileDialog::setDefines(const QStringList &defines)
{
mUI->mEditDefines->setText(defines.join(";"));
}
void ProjectFileDialog::setUndefines(const QStringList &undefines)
{
mUI->mEditUndefines->setText(undefines.join(";"));
}
void ProjectFileDialog::setCheckPaths(const QStringList &paths)
{
for (const QString& path : paths) {
addCheckPath(path);
}
}
void ProjectFileDialog::setExcludedPaths(const QStringList &paths)
{
for (const QString& path : paths) {
addExcludePath(path);
}
}
void ProjectFileDialog::setLibraries(const QStringList &libraries)
{
for (int row = 0; row < mUI->mLibraries->count(); ++row) {
QListWidgetItem *item = mUI->mLibraries->item(row);
item->setCheckState(libraries.contains(item->text()) ? Qt::Checked : Qt::Unchecked);
}
}
void ProjectFileDialog::addSingleSuppression(const SuppressionList::Suppression &suppression)
{
mSuppressions += suppression;
mUI->mListSuppressions->addItem(QString::fromStdString(suppression.getText()));
}
void ProjectFileDialog::setSuppressions(const QList<SuppressionList::Suppression> &suppressions)
{
mUI->mListSuppressions->clear();
QList<SuppressionList::Suppression> new_suppressions = suppressions;
mSuppressions.clear();
for (const SuppressionList::Suppression &suppression : new_suppressions) {
addSingleSuppression(suppression);
}
mUI->mListSuppressions->sortItems();
}
void ProjectFileDialog::addCheckPath()
{
QString dir = getExistingDirectory(tr("Select a directory to check"), false);
if (!dir.isEmpty())
addCheckPath(dir);
}
void ProjectFileDialog::editCheckPath()
{
QListWidgetItem *item = mUI->mListCheckPaths->currentItem();
mUI->mListCheckPaths->editItem(item);
}
void ProjectFileDialog::removeCheckPath()
{
const int row = mUI->mListCheckPaths->currentRow();
QListWidgetItem *item = mUI->mListCheckPaths->takeItem(row);
delete item;
}
void ProjectFileDialog::addIncludeDir()
{
const QString dir = getExistingDirectory(tr("Select include directory"), true);
if (!dir.isEmpty())
addIncludeDir(dir);
}
void ProjectFileDialog::removeIncludeDir()
{
const int row = mUI->mListIncludeDirs->currentRow();
QListWidgetItem *item = mUI->mListIncludeDirs->takeItem(row);
delete item;
}
void ProjectFileDialog::editIncludeDir()
{
QListWidgetItem *item = mUI->mListIncludeDirs->currentItem();
mUI->mListIncludeDirs->editItem(item);
}
void ProjectFileDialog::addExcludePath()
{
addExcludePath(getExistingDirectory(tr("Select directory to ignore"), true));
}
void ProjectFileDialog::addExcludeFile()
{
const QFileInfo inf(mProjectFile->getFilename());
const QDir &dir = inf.absoluteDir();
QMap<QString,QString> filters;
filters[tr("Source files")] = "*.c *.cpp";
filters[tr("All files")] = "*.*";
addExcludePath(QFileDialog::getOpenFileName(this, tr("Exclude file"), dir.canonicalPath(), toFilterString(filters)));
}
void ProjectFileDialog::editExcludePath()
{
QListWidgetItem *item = mUI->mListExcludedPaths->currentItem();
mUI->mListExcludedPaths->editItem(item);
}
void ProjectFileDialog::removeExcludePath()
{
const int row = mUI->mListExcludedPaths->currentRow();
QListWidgetItem *item = mUI->mListExcludedPaths->takeItem(row);
delete item;
}
void ProjectFileDialog::moveIncludePathUp()
{
int row = mUI->mListIncludeDirs->currentRow();
QListWidgetItem *item = mUI->mListIncludeDirs->takeItem(row);
row = row > 0 ? row - 1 : 0;
mUI->mListIncludeDirs->insertItem(row, item);
mUI->mListIncludeDirs->setCurrentItem(item);
}
void ProjectFileDialog::moveIncludePathDown()
{
int row = mUI->mListIncludeDirs->currentRow();
QListWidgetItem *item = mUI->mListIncludeDirs->takeItem(row);
const int count = mUI->mListIncludeDirs->count();
row = row < count ? row + 1 : count;
mUI->mListIncludeDirs->insertItem(row, item);
mUI->mListIncludeDirs->setCurrentItem(item);
}
void ProjectFileDialog::addSuppression()
{
NewSuppressionDialog dlg;
if (dlg.exec() == QDialog::Accepted) {
addSingleSuppression(dlg.getSuppression());
}
}
void ProjectFileDialog::removeSuppression()
{
const int row = mUI->mListSuppressions->currentRow();
QListWidgetItem *item = mUI->mListSuppressions->takeItem(row);
if (!item)
return;
const int suppressionIndex = getSuppressionIndex(item->text());
if (suppressionIndex >= 0)
mSuppressions.removeAt(suppressionIndex);
delete item;
}
void ProjectFileDialog::editSuppression(const QModelIndex & /*index*/)
{
const int row = mUI->mListSuppressions->currentRow();
QListWidgetItem *item = mUI->mListSuppressions->item(row);
const int suppressionIndex = getSuppressionIndex(item->text());
if (suppressionIndex >= 0) { // TODO what if suppression is not found?
NewSuppressionDialog dlg;
dlg.setSuppression(mSuppressions[suppressionIndex]);
if (dlg.exec() == QDialog::Accepted) {
mSuppressions[suppressionIndex] = dlg.getSuppression();
setSuppressions(mSuppressions);
}
}
}
int ProjectFileDialog::getSuppressionIndex(const QString &shortText) const
{
const std::string s = shortText.toStdString();
for (int i = 0; i < mSuppressions.size(); ++i) {
if (mSuppressions[i].getText() == s)
return i;
}
return -1;
}
void ProjectFileDialog::browseMisraFile()
{
const QString fileName = QFileDialog::getOpenFileName(this,
tr("Select MISRA rule texts file"),
QDir::homePath(),
tr("MISRA rule texts file (%1)").arg("*.txt"));
if (!fileName.isEmpty()) {
QSettings settings;
mUI->mEditMisraFile->setText(fileName);
settings.setValue(SETTINGS_MISRA_FILE, fileName);
mUI->mMisraC->setText("MISRA C 2012");
mUI->mMisraC->setEnabled(true);
updateAddonCheckBox(mUI->mMisraC, nullptr, getDataDir(), ADDON_MISRA);
}
}
| null |
737 | cpp | cppcheck | libraryeditargdialog.cpp | gui/libraryeditargdialog.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "libraryeditargdialog.h"
#include "ui_libraryeditargdialog.h"
#include <QCheckBox>
#include <QComboBox>
#include <QLineEdit>
#include <QSpinBox>
#include <QString>
#include <QStringList>
class QWidget;
LibraryEditArgDialog::LibraryEditArgDialog(QWidget *parent, const CppcheckLibraryData::Function::Arg &arg) :
QDialog(parent),
mUi(new Ui::LibraryEditArgDialog),
mMinSizes(arg.minsizes)
{
mUi->setupUi(this);
mUi->notbool->setChecked(arg.notbool);
mUi->notnull->setChecked(arg.notnull);
mUi->notuninit->setChecked(arg.notuninit);
mUi->strz->setChecked(arg.strz);
mUi->formatstr->setChecked(arg.formatstr);
mUi->valid->setText(arg.valid);
mUi->minsize1type->setEnabled(true);
mUi->minsize1arg->setEnabled(arg.minsizes.count() >= 1);
mUi->minsize1arg2->setEnabled(arg.minsizes.count() >= 1 && arg.minsizes[0].type == "mul");
mUi->minsize2type->setEnabled(arg.minsizes.count() >= 1);
mUi->minsize2arg->setEnabled(arg.minsizes.count() >= 2);
mUi->minsize2arg2->setEnabled(arg.minsizes.count() >= 2 && arg.minsizes[1].type == "mul");
QStringList items;
items << "None" << "argvalue" << "mul" << "sizeof" << "strlen";
mUi->minsize1type->clear();
mUi->minsize1type->addItems(items);
if (arg.minsizes.count() >= 1) {
mUi->minsize1type->setCurrentIndex(items.indexOf(mMinSizes[0].type));
mUi->minsize1arg->setValue(mMinSizes[0].arg.toInt());
if (arg.minsizes[0].type == "mul")
mUi->minsize1arg2->setValue(mMinSizes[0].arg2.toInt());
else
mUi->minsize1arg2->setValue(0);
} else {
mUi->minsize1type->setCurrentIndex(0);
mUi->minsize1arg->setValue(0);
mUi->minsize1arg2->setValue(0);
}
mUi->minsize2type->clear();
mUi->minsize2type->addItems(items);
if (arg.minsizes.count() >= 2) {
mUi->minsize2type->setCurrentIndex(items.indexOf(mMinSizes[1].type));
mUi->minsize2arg->setValue(mMinSizes[1].arg.toInt());
if (arg.minsizes[1].type == "mul")
mUi->minsize2arg2->setValue(mMinSizes[1].arg2.toInt());
else
mUi->minsize2arg2->setValue(0);
} else {
mUi->minsize2type->setCurrentIndex(0);
mUi->minsize2arg->setValue(0);
mUi->minsize2arg2->setValue(0);
}
}
LibraryEditArgDialog::~LibraryEditArgDialog()
{
delete mUi;
}
CppcheckLibraryData::Function::Arg LibraryEditArgDialog::getArg() const
{
CppcheckLibraryData::Function::Arg ret;
ret.notbool = mUi->notbool->isChecked();
ret.notnull = mUi->notnull->isChecked();
ret.notuninit = mUi->notuninit->isChecked();
ret.strz = mUi->strz->isChecked();
ret.formatstr = mUi->formatstr->isChecked();
if (mUi->minsize1type->currentIndex() != 0) {
CppcheckLibraryData::Function::Arg::MinSize minsize1;
minsize1.type = mUi->minsize1type->currentText();
minsize1.arg = QString::number(mUi->minsize1arg->value());
if (minsize1.type == "mul")
minsize1.arg2 = QString::number(mUi->minsize1arg2->value());
ret.minsizes.append(minsize1);
if (mUi->minsize2type->currentIndex() != 0) {
CppcheckLibraryData::Function::Arg::MinSize minsize2;
minsize2.type = mUi->minsize2type->currentText();
minsize2.arg = QString::number(mUi->minsize2arg->value());
if (minsize2.type == "mul")
minsize2.arg2 = QString::number(mUi->minsize2arg2->value());
ret.minsizes.append(minsize2);
}
}
ret.valid = mUi->valid->text();
return ret;
}
void LibraryEditArgDialog::minsizeChanged()
{
mUi->minsize1arg->setEnabled(mUi->minsize1type->currentIndex() != 0);
mUi->minsize1arg2->setEnabled(mUi->minsize1type->currentText() == "mul");
mUi->minsize2type->setEnabled(mUi->minsize1type->currentIndex() != 0);
mUi->minsize2arg->setEnabled(mUi->minsize2type->currentIndex() != 0);
mUi->minsize2arg2->setEnabled(mUi->minsize2type->currentText() == "mul");
}
| null |
738 | cpp | cppcheck | precompiled.h | gui/precompiled.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
// IWYU pragma: begin_keep
#include "checkthread.h"
#include "codeeditor.h"
#include "codeeditorstyle.h"
#include "config.h"
#include "cppcheck.h"
#include "cppchecklibrarydata.h"
#include "report.h"
#include "showtypes.h"
#include <QFile>
#include <QVariant>
// IWYU pragma: end_keep
| null |
739 | cpp | cppcheck | showtypes.cpp | gui/showtypes.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2023 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "showtypes.h"
#include "common.h"
#include "errortypes.h"
#include <QSettings>
ShowTypes::ShowTypes()
{
load();
}
ShowTypes::~ShowTypes()
{
save();
}
ShowTypes::ShowType ShowTypes::SeverityToShowType(Severity severity)
{
switch (severity) {
case Severity::none:
case Severity::internal:
return ShowTypes::ShowNone;
case Severity::error:
return ShowTypes::ShowErrors;
case Severity::style:
return ShowTypes::ShowStyle;
case Severity::warning:
return ShowTypes::ShowWarnings;
case Severity::performance:
return ShowTypes::ShowPerformance;
case Severity::portability:
return ShowTypes::ShowPortability;
case Severity::information:
return ShowTypes::ShowInformation;
default:
return ShowTypes::ShowNone;
}
}
Severity ShowTypes::ShowTypeToSeverity(ShowTypes::ShowType type)
{
switch (type) {
case ShowTypes::ShowStyle:
return Severity::style;
case ShowTypes::ShowErrors:
return Severity::error;
case ShowTypes::ShowWarnings:
return Severity::warning;
case ShowTypes::ShowPerformance:
return Severity::performance;
case ShowTypes::ShowPortability:
return Severity::portability;
case ShowTypes::ShowInformation:
return Severity::information;
case ShowTypes::ShowNone:
default:
return Severity::none;
}
}
ShowTypes::ShowType ShowTypes::VariantToShowType(const QVariant &data)
{
const int value = data.toInt();
if (value < ShowTypes::ShowStyle || value > ShowTypes::ShowErrors) {
return ShowTypes::ShowNone;
}
return (ShowTypes::ShowType)value;
}
void ShowTypes::load()
{
QSettings settings;
mVisible[ShowStyle] = settings.value(SETTINGS_SHOW_STYLE, true).toBool();
mVisible[ShowErrors] = settings.value(SETTINGS_SHOW_ERRORS, true).toBool();
mVisible[ShowWarnings] = settings.value(SETTINGS_SHOW_WARNINGS, true).toBool();
mVisible[ShowPortability] = settings.value(SETTINGS_SHOW_PORTABILITY, true).toBool();
mVisible[ShowPerformance] = settings.value(SETTINGS_SHOW_PERFORMANCE, true).toBool();
mVisible[ShowInformation] = settings.value(SETTINGS_SHOW_INFORMATION, true).toBool();
}
void ShowTypes::save() const
{
QSettings settings;
settings.setValue(SETTINGS_SHOW_STYLE, mVisible[ShowStyle]);
settings.setValue(SETTINGS_SHOW_ERRORS, mVisible[ShowErrors]);
settings.setValue(SETTINGS_SHOW_WARNINGS, mVisible[ShowWarnings]);
settings.setValue(SETTINGS_SHOW_PORTABILITY, mVisible[ShowPortability]);
settings.setValue(SETTINGS_SHOW_PERFORMANCE, mVisible[ShowPerformance]);
settings.setValue(SETTINGS_SHOW_INFORMATION, mVisible[ShowInformation]);
}
bool ShowTypes::isShown(ShowTypes::ShowType category) const
{
return mVisible[category];
}
bool ShowTypes::isShown(Severity severity) const
{
return isShown(ShowTypes::SeverityToShowType(severity));
}
void ShowTypes::show(ShowTypes::ShowType category, bool showing)
{
mVisible[category] = showing;
}
| null |
740 | cpp | cppcheck | projectfiledialog.h | gui/projectfiledialog.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PROJECTFILE_DIALOG_H
#define PROJECTFILE_DIALOG_H
#include "suppressions.h"
#include <QDialog>
#include <QList>
#include <QObject>
#include <QString>
#include <QStringList>
class QModelIndex;
class QWidget;
namespace Ui {
class ProjectFile;
}
/// @addtogroup GUI
/// @{
class ProjectFile;
/**
* @brief A dialog for editing project file data.
*/
class ProjectFileDialog : public QDialog {
Q_OBJECT
public:
explicit ProjectFileDialog(ProjectFile *projectFile, bool premium, QWidget *parent = nullptr);
~ProjectFileDialog() override;
private:
void loadFromProjectFile(const ProjectFile *projectFile);
void saveToProjectFile(ProjectFile *projectFile) const;
/** Enable and disable widgets in the 'Paths and Defines' tab */
void updatePathsAndDefines();
/**
* @brief Return project root path from the dialog control.
* @return Project root path.
*/
QString getRootPath() const;
QStringList getProjectConfigurations() const;
void setProjectConfigurations(const QStringList &configs);
QString getImportProject() const;
/** Get Cppcheck build dir */
QString getBuildDir() const;
/**
* @brief Return include paths from the dialog control.
* @return List of include paths.
*/
QStringList getIncludePaths() const;
/**
* @brief Return define names from the dialog control.
* @return List of define names.
*/
QStringList getDefines() const;
/**
* @brief Return undefine names from the dialog control.
* @return List of undefine names.
*/
QStringList getUndefines() const;
/**
* @brief Return check paths from the dialog control.
* @return List of check paths.
*/
QStringList getCheckPaths() const;
/**
* @brief Return excluded paths from the dialog control.
* @return List of excluded paths.
*/
QStringList getExcludedPaths() const;
/**
* @brief Return selected libraries from the dialog control.
* @return List of libraries.
*/
QStringList getLibraries() const;
/**
* @brief Return suppressions from the dialog control.
* @return List of suppressions.
*/
const QList<SuppressionList::Suppression>& getSuppressions() const {
return mSuppressions;
}
/**
* @brief Set project root path to dialog control.
* @param root Project root path to set to dialog control.
*/
void setRootPath(const QString &root);
/** Set build dir */
void setBuildDir(const QString &buildDir);
void setImportProject(const QString &importProject);
/**
* @brief Set include paths to dialog control.
* @param includes List of include paths to set to dialog control.
*/
void setIncludepaths(const QStringList &includes);
/**
* @brief Set define names to dialog control.
* @param defines List of define names to set to dialog control.
*/
void setDefines(const QStringList &defines);
/**
* @brief Set undefine names to dialog control.
* @param undefines List of undefine names to set to dialog control.
*/
void setUndefines(const QStringList &undefines);
/**
* @brief Set check paths to dialog control.
* @param paths List of path names to set to dialog control.
*/
void setCheckPaths(const QStringList &paths);
/**
* @brief Set excluded paths to dialog control.
* @param paths List of path names to set to dialog control.
*/
void setExcludedPaths(const QStringList &paths);
/**
* @brief Set libraries to dialog control.
* @param libraries List of libraries to set to dialog control.
*/
void setLibraries(const QStringList &libraries);
/**
* @brief Add a single suppression to dialog control.
* @param suppression A suppressions to add to dialog control.
*/
void addSingleSuppression(const SuppressionList::Suppression &suppression);
/**
* @brief Set suppressions to dialog control.
* @param suppressions List of suppressions to set to dialog control.
*/
void setSuppressions(const QList<SuppressionList::Suppression> &suppressions);
private slots:
/** ok button pressed, save changes and accept */
void ok();
/**
* @brief Browse for build dir.
*/
void browseBuildDir();
/**
* @brief Clear 'import project'.
*/
void clearImportProject();
/**
* @brief Browse for solution / project / compile database.
*/
void browseImportProject();
/**
* @brief Add new path to check.
*/
void addCheckPath();
/**
* @brief Edit path in the list.
*/
void editCheckPath();
/**
* @brief Remove path from the list.
*/
void removeCheckPath();
/**
* @brief Browse for include directory.
* Allow user to add new include directory to the list.
*/
void addIncludeDir();
/**
* @brief Remove include directory from the list.
*/
void removeIncludeDir();
/**
* @brief Edit include directory in the list.
*/
void editIncludeDir();
/**
* @brief Add new path to exclude list.
*/
void addExcludePath();
/**
* @brief Add new file to exclude list.
*/
void addExcludeFile();
/**
* @brief Edit excluded path in the list.
*/
void editExcludePath();
/**
* @brief Remove excluded path from the list.
*/
void removeExcludePath();
/**
* @brief Move include path up in the list.
*/
void moveIncludePathUp();
/**
* @brief Move include path down in the list.
*/
void moveIncludePathDown();
/**
* @brief Add suppression to the list
*/
void addSuppression();
/**
* @brief Remove selected suppression from the list
*/
void removeSuppression();
/**
* @brief Edit suppression (double clicking on suppression)
*/
void editSuppression(const QModelIndex &index);
/**
* @brief Browse for misra file
*/
void browseMisraFile();
/**
* @brief Check for all VS configurations
*/
void checkAllVSConfigs();
protected:
/**
* @brief Save dialog settings.
*/
void loadSettings();
/**
* @brief Load dialog settings.
*/
void saveSettings() const;
/**
* @brief Add new indlude directory.
* @param dir Directory to add.
*/
void addIncludeDir(const QString &dir);
/**
* @brief Add new path to check.
* @param path Path to add.
*/
void addCheckPath(const QString &path);
/**
* @brief Add new path to ignore list.
* @param path Path to add.
*/
void addExcludePath(const QString &path);
/**
* @brief Get mSuppressions index that match the
* given short text
* @param shortText text as generated by Suppression::getText
* @return index of matching suppression, -1 if not found
*/
int getSuppressionIndex(const QString &shortText) const;
private:
static QStringList getProjectConfigs(const QString &fileName);
Ui::ProjectFile * const mUI;
/**
* @brief Projectfile path.
*/
ProjectFile * const mProjectFile;
/** Is this Cppcheck Premium? */
const bool mPremium;
QString getExistingDirectory(const QString &caption, bool trailingSlash);
QList<SuppressionList::Suppression> mSuppressions;
};
/// @}
#endif // PROJECTFILE_DIALOG_H
| null |
741 | cpp | cppcheck | codeeditorstyle.h | gui/codeeditorstyle.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef CODEEDITORSTYLE_H
#define CODEEDITORSTYLE_H
#include <QColor>
#include <QFont>
#include <QString>
#include <Qt>
const QString SETTINGS_STYLE_GROUP("EditorStyle");
const QString SETTINGS_STYLE_TYPE("StyleType");
const QString SETTINGS_STYLE_TYPE_LIGHT("DefaultLight");
const QString SETTINGS_STYLE_TYPE_DARK("DefaultDark");
const QString SETTINGS_STYLE_TYPE_CUSTOM("Custom");
const QString SETTINGS_STYLE_WIDGETFG("StyleWidgetFG");
const QString SETTINGS_STYLE_WIDGETBG("StyleWidgetBG");
const QString SETTINGS_STYLE_HILIFG("StyleHighlightFG");
const QString SETTINGS_STYLE_LINENUMFG("StyleLineNumFG");
const QString SETTINGS_STYLE_LINENUMBG("StyleLineNumBG");
const QString SETTINGS_STYLE_KEYWORDFG("StyleKeywordFG");
const QString SETTINGS_STYLE_KEYWORDWT("StyleKeywordWeight");
const QString SETTINGS_STYLE_CLASSFG("StyleClassFG");
const QString SETTINGS_STYLE_CLASSWT("StyleClassWeight");
const QString SETTINGS_STYLE_QUOTEFG("StyleQuoteFG");
const QString SETTINGS_STYLE_QUOTEWT("StyleQuoteWeight");
const QString SETTINGS_STYLE_COMMENTFG("StyleCommentFG");
const QString SETTINGS_STYLE_COMMENTWT("StyleCommentWeight");
const QString SETTINGS_STYLE_SYMBOLFG("StyleSymbolFG");
const QString SETTINGS_STYLE_SYMBOLBG("StyleSymbolBG");
const QString SETTINGS_STYLE_SYMBOLWT("StyleSymbolWeight");
class QSettings;
class CodeEditorStyle {
public:
explicit CodeEditorStyle(
// cppcheck-suppress naming-varname - TODO: fix this
QColor CtrlFGColor, QColor CtrlBGColor,
// cppcheck-suppress naming-varname - TODO: fix this
QColor HiLiBGColor,
// cppcheck-suppress naming-varname - TODO: fix this
QColor LnNumFGColor, QColor LnNumBGColor,
// cppcheck-suppress naming-varname - TODO: fix this
QColor KeyWdFGColor, QFont::Weight KeyWdWeight,
// cppcheck-suppress naming-varname - TODO: fix this
QColor ClsFGColor, QFont::Weight ClsWeight,
// cppcheck-suppress naming-varname - TODO: fix this
QColor QteFGColor, QFont::Weight QteWeight,
// cppcheck-suppress naming-varname - TODO: fix this
QColor CmtFGColor, QFont::Weight CmtWeight,
// cppcheck-suppress naming-varname - TODO: fix this
QColor SymbFGColor, QColor SymbBGColor,
// cppcheck-suppress naming-varname - TODO: fix this
QFont::Weight SymbWeight);
bool operator==(const CodeEditorStyle& rhs) const;
bool operator!=(const CodeEditorStyle& rhs) const;
bool isSystemTheme() const {
return mSystemTheme;
}
static CodeEditorStyle getSystemTheme();
static CodeEditorStyle loadSettings(QSettings *settings);
static void saveSettings(QSettings *settings, const CodeEditorStyle& theStyle);
public:
bool mSystemTheme{};
QColor widgetFGColor;
QColor widgetBGColor;
QColor highlightBGColor;
QColor lineNumFGColor;
QColor lineNumBGColor;
QColor keywordColor;
QFont::Weight keywordWeight;
QColor classColor;
QFont::Weight classWeight;
QColor quoteColor;
QFont::Weight quoteWeight;
QColor commentColor;
QFont::Weight commentWeight;
QColor symbolFGColor;
QColor symbolBGColor;
QFont::Weight symbolWeight;
};
static const CodeEditorStyle defaultStyleLight(
/* editor FG/BG */ Qt::black, QColor(240, 240, 240),
/* highlight BG */ QColor(255, 220, 220),
/* line number FG/BG */ Qt::black, QColor(240, 240, 240),
/* keyword FG/Weight */ Qt::darkBlue, QFont::Bold,
/* class FG/Weight */ Qt::darkMagenta, QFont::Bold,
/* quote FG/Weight */ Qt::darkGreen, QFont::Normal,
/* comment FG/Weight */ Qt::gray, QFont::Normal,
/* Symbol FG/BG/Weight */ Qt::red, QColor(220, 220, 255), QFont::Normal
);
// Styling derived from Eclipse Color Theme - 'RecognEyes'
// http://www.eclipsecolorthemes.org/?view=theme&id=30
static const CodeEditorStyle defaultStyleDark(
/* editor FG/BG */ QColor(218, 218, 218), QColor(16, 16, 32),
/* highlight BG */ QColor(64, 64, 64),
/* line number FG/BG */ QColor(43, 145, 175), QColor(16, 16, 32),
/* keyword FG/Weight */ QColor(0, 204, 204), QFont::Bold,
/* class FG/Weight */ QColor(218, 0, 218), QFont::Bold,
/* quote FG/Weight */ QColor(0, 204, 0), QFont::Normal,
/* comment FG/Weight */ QColor(180, 180, 180), QFont::Normal,
/* Symbol FG/BG/Weight */ QColor(218, 32, 32), QColor(32, 32, 108), QFont::Normal
);
#endif /* CODEEDITORSTYLE_H */
| null |
742 | cpp | cppcheck | main.cpp | gui/main.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "cppcheck.h"
#include "common.h"
#include "mainwindow.h"
#include "erroritem.h" // IWYU pragma: keep
#include "translationhandler.h"
#ifdef _WIN32
#include "aboutdialog.h"
#include <QMessageBox>
#else
#include <iostream>
#endif
#include <algorithm>
#include <string>
#include <QApplication>
#include <QCoreApplication>
#include <QIcon>
#include <QSettings>
#include <QString>
#include <QStringList>
#include <QVariant>
static void ShowUsage();
static void ShowVersion();
static bool CheckArgs(const QStringList &args);
int main(int argc, char *argv[])
{
#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)) && (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
#endif
QApplication app(argc, argv);
QCoreApplication::setOrganizationName("Cppcheck");
QCoreApplication::setApplicationName("Cppcheck-GUI");
auto* settings = new QSettings("Cppcheck", "Cppcheck-GUI", &app);
// Set data dir..
const QStringList args = QApplication::arguments();
auto it = std::find_if(args.cbegin(), args.cend(), [](const QString& arg) {
return arg.startsWith("--data-dir=");
});
if (it != args.end()) {
settings->setValue("DATADIR", it->mid(11));
return 0;
}
auto* th = new TranslationHandler(&app);
th->setLanguage(settings->value(SETTINGS_LANGUAGE, th->suggestLanguage()).toString());
if (!CheckArgs(QApplication::arguments()))
return 0;
QApplication::setWindowIcon(QIcon(":cppcheck-gui.png"));
// Register this metatype that is used to transfer error info
qRegisterMetaType<ErrorItem>("ErrorItem");
MainWindow window(th, settings);
window.show();
return QApplication::exec();
}
// Check only arguments needing action before GUI is shown.
// Rest of the arguments are handled in MainWindow::HandleCLIParams()
static bool CheckArgs(const QStringList &args)
{
if (args.contains("-h") || args.contains("--help")) {
ShowUsage();
return false;
}
if (args.contains("-v") || args.contains("--version")) {
ShowVersion();
return false;
}
return true;
}
static void ShowUsage()
{
QString helpMessage = MainWindow::tr(
"Cppcheck GUI.\n\n"
"Syntax:\n"
" cppcheck-gui [OPTIONS] [files or paths]\n\n"
"Options:\n"
" -h, --help Print this help\n"
" -p <file> Open given project file and start checking it\n"
" -l <file> Open given results xml file\n"
" -d <directory> Specify the directory that was checked to generate the results xml specified with -l\n"
" -v, --version Show program version\n"
" --data-dir=<directory> This option is for installation scripts so they can configure the directory where\n"
" datafiles are located (translations, cfg). The GUI is not started when this option\n"
" is used.");
#if defined(_WIN32)
QMessageBox msgBox(QMessageBox::Information,
MainWindow::tr("Cppcheck GUI - Command line parameters"),
helpMessage,
QMessageBox::Ok
);
(void)msgBox.exec();
#else
std::cout << helpMessage.toStdString() << std::endl;
#endif
}
static void ShowVersion()
{
#if defined(_WIN32)
AboutDialog *dlg = new AboutDialog(CppCheck::version(), CppCheck::extraVersion(), 0);
dlg->exec();
delete dlg;
#else
std::string versionMessage("Cppcheck ");
versionMessage += CppCheck::version();
const char * extraVersion = CppCheck::extraVersion();
if (*extraVersion != 0)
versionMessage += std::string(" (") + extraVersion + ")";
std::cout << versionMessage << std::endl;
#endif
}
| null |
743 | cpp | cppcheck | common.h | gui/common.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef COMMON_H
#define COMMON_H
#include <cstdint>
#include <QMap>
#include <QString>
/// @addtogroup GUI
/// @{
#define CLANG_ANALYZER "clang-analyzer"
#define CLANG_TIDY "clang-tidy"
/**
* QSetting value names
*/
// Window/dialog sizes
#define SETTINGS_WINDOW_MAXIMIZED "Window maximized"
#define SETTINGS_WINDOW_WIDTH "Window width"
#define SETTINGS_WINDOW_HEIGHT "Window height"
#define SETTINGS_MAINWND_SPLITTER_STATE "Mainwindow/Vertical splitter state"
#define SETTINGS_CHECK_DIALOG_WIDTH "Check dialog width"
#define SETTINGS_CHECK_DIALOG_HEIGHT "Check dialog height"
#define SETTINGS_PROJECT_DIALOG_WIDTH "Project dialog width"
#define SETTINGS_PROJECT_DIALOG_HEIGHT "Project dialog height"
// Main window settings
#define SETTINGS_RESULT_COLUMN_WIDTH "Result column %1 width"
#define SETTINGS_TOOLBARS_MAIN_SHOW "Toolbars/ShowStandard"
#define SETTINGS_TOOLBARS_VIEW_SHOW "Toolbars/ShowView"
#define SETTINGS_TOOLBARS_FILTER_SHOW "Toolbars/ShowFilter"
// Report type
#define SETTINGS_REPORT_TYPE "Report type"
enum class ReportType : std::uint8_t { normal=0, autosar=1, certC=2, certCpp=3, misraC=4, misraCpp2008=5, misraCpp2023=6 };
// Show * states
#define SETTINGS_SHOW_STYLE "Show style"
#define SETTINGS_SHOW_ERRORS "Show errors"
#define SETTINGS_SHOW_WARNINGS "Show warnings"
#define SETTINGS_SHOW_PERFORMANCE "Show performance"
#define SETTINGS_SHOW_INFORMATION "Show information"
#define SETTINGS_SHOW_PORTABILITY "Show portability"
// Standards support
#define SETTINGS_STD_CPP "Standard CPP"
#define SETTINGS_STD_C "Standard C"
// Language enforcement
#define SETTINGS_ENFORCED_LANGUAGE "Enforced language"
// Other settings
#define SETTINGS_CHECK_FORCE "Check force"
#define SETTINGS_CHECK_THREADS "Check threads"
#define SETTINGS_SHOW_FULL_PATH "Show full path"
#define SETTINGS_SHOW_NO_ERRORS "Show no errors message"
#define SETTINGS_SHOW_DEBUG_WARNINGS "Show debug warnings"
#define SETTINGS_SAVE_ALL_ERRORS "Save all errors"
#define SETTINGS_SAVE_FULL_PATH "Save full path"
#define SETTINGS_APPLICATION_NAMES "Application names"
#define SETTINGS_APPLICATION_PATHS "Application paths"
#define SETTINGS_APPLICATION_PARAMS "Application parameters"
#define SETTINGS_APPLICATION_DEFAULT "Default Application"
#define SETTINGS_LANGUAGE "Application language"
#define SETTINGS_GLOBAL_INCLUDE_PATHS "Global include paths"
#define SETTINGS_PYTHON_PATH "Python path"
#define SETTINGS_MISRA_FILE "MISRA C 2012 file"
#define SETTINGS_CLANG_PATH "Clang path"
#define SETTINGS_VS_INCLUDE_PATHS "VS include paths"
#define SETTINGS_INLINE_SUPPRESSIONS "Inline suppressions"
#define SETTINGS_INCONCLUSIVE_ERRORS "Inconclusive errors"
#define SETTINGS_MRU_PROJECTS "MRU Projects"
#define SETTINGS_SHOW_ERROR_ID "Show error Id"
#define SETTINGS_SHOW_STATISTICS "Show statistics"
#define SETTINGS_OPEN_PROJECT "Open Project"
#define SETTINGS_CHECK_VERSION "Check Version"
#define SETTINGS_CHECK_FOR_UPDATES "Check for updates"
// The maximum value for the progress bar
#define PROGRESS_MAX 1024.0
#define SETTINGS_CHECKED_PLATFORM "Checked platform"
#define SETTINGS_LAST_CHECK_PATH "Last check path"
#define SETTINGS_LAST_PROJECT_PATH "Last project path"
#define SETTINGS_LAST_RESULT_PATH "Last result path"
#define SETTINGS_LAST_SOURCE_PATH "Last source path"
#define SETTINGS_LAST_APP_PATH "Last application path"
#define SETTINGS_LAST_ANALYZE_FILES_FILTER "Last analyze files filter"
/**
* @brief Obtains the path of specified type
* Returns the path of specified type if not empty. Otherwise returns last check
* path if valid or user's home directory.
* @param type Type of path to obtain
* @return Best path for provided type
*/
QString getPath(const QString &type);
/**
* @brief Stores last used path of specified type
* Stores provided path as last used path for specified type.
* @param type Type of the path to store
* @param value Path to store
*/
void setPath(const QString &type, const QString &value);
/**
* @brief Creates a string suitable for passing as the filter argument to
* methods like QFileDialog::getOpenFileName.
* @param filters A map of filter descriptions to the associated file name
* patterns.
* @param addAllSupported If set to true (the default), the function will
* include a filter entry containing all the file name patterns found in
* \p filters. This entry will be the first in the resulting filter string.
* @param addAll If set to true (the default), the function will
* include a filter entry displaying all files. This entry will be placed
* after the entry for \p addAllSupported files.
*
* Example usage:
*
* @code
* QMap<QString,QString> filters;
* filters[tr("Supported images")] = "*.bmp *.jpg *.png";
* filters[tr("Plain text")] = "*.txt";
*
* const QString filterString = toFilterString(filters);
*
* // filterString contains "All supported files (*.txt *.bmp *.jpg *.png);;All files (*.*);;Plain text (*.txt);;Supported images (*.bmp *.jpg *.png)"
* @endcode
*/
QString toFilterString(const QMap<QString,QString>& filters, bool addAllSupported=true, bool addAll=true);
/**
* Get configured data dir. If not configured then it will try to determine that from exe path.
*/
QString getDataDir();
/// @}
#endif
| null |
744 | cpp | cppcheck | platforms.h | gui/platforms.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PLATFORMS_H
#define PLATFORMS_H
#include "platform.h"
#include <QList>
#include <QObject>
#include <QString>
class QAction;
/// @addtogroup GUI
/// @{
/**
* @brief Checked platform GUI-data.
*/
struct PlatformData {
QString mTitle; /**< Text visible in the GUI. */
Platform::Type mType; /**< Type in the core. */
QAction *mActMainWindow; /**< Pointer to main window action item. */
};
/**
* @brief List of checked platforms.
*/
class Platforms : public QObject {
Q_OBJECT
public:
explicit Platforms(QObject *parent = nullptr);
void add(const QString &title, Platform::Type platform);
int getCount() const;
void init();
PlatformData& get(Platform::Type platform);
QList<PlatformData> mPlatforms;
};
/// @}
#endif // PLATFORMS_H
| null |
745 | cpp | cppcheck | applicationdialog.cpp | gui/applicationdialog.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2023 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "applicationdialog.h"
#include "application.h"
#include "common.h"
#include "ui_applicationdialog.h"
#include <QDialogButtonBox>
#include <QDir>
#include <QFileDialog>
#include <QLineEdit>
#include <QMessageBox>
#include <QPushButton>
ApplicationDialog::ApplicationDialog(const QString &title,
Application &app,
QWidget *parent) :
QDialog(parent),
mUI(new Ui::ApplicationDialog),
mApplication(app)
{
mUI->setupUi(this);
connect(mUI->mButtonBrowse, &QPushButton::clicked, this, &ApplicationDialog::browse);
connect(mUI->mButtons, &QDialogButtonBox::accepted, this, &ApplicationDialog::ok);
connect(mUI->mButtons, &QDialogButtonBox::rejected, this, &ApplicationDialog::reject);
mUI->mPath->setText(app.getPath());
mUI->mName->setText(app.getName());
mUI->mParameters->setText(app.getParameters());
setWindowTitle(title);
adjustSize();
}
ApplicationDialog::~ApplicationDialog()
{
delete mUI;
}
void ApplicationDialog::browse()
{
QString filter;
#ifdef Q_OS_WIN
// In Windows (almost) all executables have .exe extension
// so it does not make sense to show everything.
filter += tr("Executable files (*.exe);;All files(*.*)");
#endif // Q_OS_WIN
QString selectedFile = QFileDialog::getOpenFileName(this,
tr("Select viewer application"),
getPath(SETTINGS_LAST_APP_PATH),
filter);
if (!selectedFile.isEmpty()) {
setPath(SETTINGS_LAST_APP_PATH, selectedFile);
QString path(QDir::toNativeSeparators(selectedFile));
mUI->mPath->setText(path);
}
}
void ApplicationDialog::ok()
{
if (mUI->mName->text().isEmpty() || mUI->mPath->text().isEmpty()) {
QMessageBox msg(QMessageBox::Warning,
tr("Cppcheck"),
tr("You must specify a name, a path and optionally parameters for the application!"),
QMessageBox::Ok,
this);
msg.exec();
reject();
} else {
// Convert possible native (Windows) path to internal presentation format
mApplication.setName(mUI->mName->text());
mApplication.setPath(QDir::fromNativeSeparators(mUI->mPath->text()));
mApplication.setParameters(mUI->mParameters->text());
accept();
}
}
| null |
746 | cpp | cppcheck | precompiled_qmake.h | gui/precompiled_qmake.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "precompiled.h"
#include <QDialog>
#include <QObject>
#include <QWidget>
| null |
747 | cpp | cppcheck | newsuppressiondialog.h | gui/newsuppressiondialog.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef NEWSUPPRESSIONDIALOG_H
#define NEWSUPPRESSIONDIALOG_H
#include "suppressions.h"
#include <QDialog>
#include <QObject>
class QWidget;
namespace Ui {
class NewSuppressionDialog;
}
class NewSuppressionDialog : public QDialog {
Q_OBJECT
public:
explicit NewSuppressionDialog(QWidget *parent = nullptr);
NewSuppressionDialog(const NewSuppressionDialog &) = delete;
~NewSuppressionDialog() override;
NewSuppressionDialog &operator=(const NewSuppressionDialog &) = delete;
/**
* @brief Translate the user input in the GUI into a suppression
* @return Cppcheck suppression
*/
SuppressionList::Suppression getSuppression() const;
/**
* @brief Update the GUI so it corresponds with the given
* Cppcheck suppression
* @param suppression Cppcheck suppression
*/
void setSuppression(const SuppressionList::Suppression &suppression);
private:
Ui::NewSuppressionDialog *mUI;
};
#endif // NEWSUPPRESSIONDIALOG_H
| null |
748 | cpp | cppcheck | libraryaddfunctiondialog.cpp | gui/libraryaddfunctiondialog.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2023 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "libraryaddfunctiondialog.h"
#include "ui_libraryaddfunctiondialog.h"
#include <QLineEdit>
#include <QRegularExpression>
#include <QRegularExpressionValidator>
#include <QSpinBox>
class QWidget;
LibraryAddFunctionDialog::LibraryAddFunctionDialog(QWidget *parent) :
QDialog(parent),
mUi(new Ui::LibraryAddFunctionDialog)
{
mUi->setupUi(this);
static const QRegularExpression rx(NAMES);
QValidator *validator = new QRegularExpressionValidator(rx, this);
mUi->functionName->setValidator(validator);
}
LibraryAddFunctionDialog::~LibraryAddFunctionDialog()
{
delete mUi;
}
QString LibraryAddFunctionDialog::functionName() const
{
return mUi->functionName->text();
}
int LibraryAddFunctionDialog::numberOfArguments() const
{
return mUi->numberOfArguments->value();
}
| null |
749 | cpp | cppcheck | checkstatistics.h | gui/checkstatistics.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef CHECKSTATISTICS_H
#define CHECKSTATISTICS_H
#include "showtypes.h"
#include <QMap>
#include <QObject>
#include <QString>
#include <QStringList>
#include <set>
#include <string>
#include <utility>
/// @addtogroup GUI
/// @{
/**
* A class for check statistics.
*/
class CheckStatistics : public QObject {
public:
explicit CheckStatistics(QObject *parent = nullptr);
/**
* @brief Add new checked item to statistics.
*
* @param tool Tool.
* @param type Type of the item to add.
*/
void addItem(const QString &tool, ShowTypes::ShowType type);
/**
* @brief Add checker to statistics
*/
void addChecker(const QString& checker);
/**
* @brief Clear the statistics.
*
*/
void clear();
/**
* @brief Return statistics for given type.
*
* @param tool Tool.
* @param type Type for which the statistics are returned.
* @return Number of items of given type.
*/
unsigned getCount(const QString &tool, ShowTypes::ShowType type) const;
const std::set<std::string>& getActiveCheckers() const {
return mActiveCheckers;
}
int getNumberOfActiveCheckers() const {
return mActiveCheckers.size();
}
/** Get tools with results */
QStringList getTools() const;
void setCheckersReport(QString report) {
mCheckersReport = std::move(report);
}
const QString& getCheckersReport() const {
return mCheckersReport;
}
private:
QMap<QString, unsigned> mStyle;
QMap<QString, unsigned> mWarning;
QMap<QString, unsigned> mPerformance;
QMap<QString, unsigned> mPortability;
QMap<QString, unsigned> mInformation;
QMap<QString, unsigned> mError;
std::set<std::string> mActiveCheckers;
QString mCheckersReport;
};
/// @}
#endif // CHECKSTATISTICS_H
| null |
750 | cpp | cppcheck | fileviewdialog.h | gui/fileviewdialog.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef FILEVIEW_DIALOG_H
#define FILEVIEW_DIALOG_H
#include <QDialog>
#include <QObject>
#include <QString>
class QWidget;
class QTextEdit;
namespace Ui {
class Fileview;
}
/// @addtogroup GUI
/// @{
/**
* @brief File view -dialog.
* This dialog shows text files. It is used for showing the license file and
* the authors list.
*
*/
class FileViewDialog : public QDialog {
Q_OBJECT
public:
FileViewDialog(const QString &file,
const QString &title,
QWidget *parent = nullptr);
~FileViewDialog() override;
protected:
/**
* @brief Load text file contents to edit control.
*
* @param filename File to load.
* @param edit Control where to load the file contents.
*/
void loadTextFile(const QString &filename, QTextEdit *edit);
Ui::Fileview* mUI;
};
/// @}
#endif // FILEVIEW_DIALOG_H
| null |
751 | cpp | cppcheck | testfilelist.cpp | gui/test/filelist/testfilelist.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2021 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "testfilelist.h"
#include "filelist.h"
#include <QDir>
#include <QString>
#include <QStringList>
#include <QtTest>
void TestFileList::addFile() const
{
// Accepted extensions: *.cpp, *.cxx, *.cc, *.c, *.c++, *.txx, *.tpp, *.ipp, *.ixx"
FileList list;
list.addFile(QString(SRCDIR) + "/../data/files/foo1.cpp");
list.addFile(QString(SRCDIR) + "/../data/files/foo2.cxx");
list.addFile(QString(SRCDIR) + "/../data/files/foo3.cc");
list.addFile(QString(SRCDIR) + "/../data/files/foo4.c");
list.addFile(QString(SRCDIR) + "/../data/files/foo5.c++");
list.addFile(QString(SRCDIR) + "/../data/files/foo6.txx");
list.addFile(QString(SRCDIR) + "/../data/files/foo7.tpp");
list.addFile(QString(SRCDIR) + "/../data/files/foo8.ipp");
list.addFile(QString(SRCDIR) + "/../data/files/foo9.ixx");
QStringList files = list.getFileList();
QCOMPARE(files.size(), 9);
}
void TestFileList::addPathList() const
{
// Accepted extensions: *.cpp, *.cxx, *.cc, *.c, *.c++, *.txx, *.tpp, *.ipp, *.ixx"
QStringList paths;
paths << QString(SRCDIR) + "/../data/files/foo1.cpp";
paths << QString(SRCDIR) + "/../data/files/foo2.cxx";
paths << QString(SRCDIR) + "/../data/files/foo3.cc";
paths << QString(SRCDIR) + "/../data/files/foo4.c";
paths << QString(SRCDIR) + "/../data/files/foo5.c++";
paths << QString(SRCDIR) + "/../data/files/foo6.txx";
paths << QString(SRCDIR) + "/../data/files/foo7.tpp";
paths << QString(SRCDIR) + "/../data/files/foo8.ipp";
paths << QString(SRCDIR) + "/../data/files/foo9.ixx";
FileList list;
list.addPathList(paths);
QStringList files = list.getFileList();
QCOMPARE(files.size(), 9);
}
void TestFileList::addFile_notexist() const
{
FileList list;
list.addFile(QString(SRCDIR) + "/../data/files/bar1.cpp");
QStringList files = list.getFileList();
QCOMPARE(files.size(), 0);
}
void TestFileList::addFile_unknown() const
{
FileList list;
list.addFile(QString(SRCDIR) + "/../data/files/bar1");
list.addFile(QString(SRCDIR) + "/../data/files/bar1.foo");
QStringList files = list.getFileList();
QCOMPARE(files.size(), 0);
}
void TestFileList::addDirectory() const
{
FileList list;
list.addDirectory(QString(SRCDIR) + "/../data/files");
QStringList files = list.getFileList();
QCOMPARE(files.size(), 9);
}
void TestFileList::addDirectory_recursive() const
{
FileList list;
list.addDirectory(QString(SRCDIR) + "/../data/files", true);
QStringList files = list.getFileList();
QCOMPARE(files.size(), 12);
QDir dir(QString(SRCDIR) + "/../data/files");
QString base = dir.canonicalPath();
QVERIFY(files.contains(base + "/dir1/foo1.cpp"));
QVERIFY(files.contains(base + "/dir1/dir11/foo11.cpp"));
QVERIFY(files.contains(base + "/dir2/foo1.cpp"));
}
void TestFileList::filterFiles() const
{
FileList list;
QStringList filters;
filters << "foo1.cpp" << "foo3.cc";
list.addExcludeList(filters);
list.addFile(QString(SRCDIR) + "/../data/files/foo1.cpp");
list.addFile(QString(SRCDIR) + "/../data/files/foo2.cxx");
list.addFile(QString(SRCDIR) + "/../data/files/foo3.cc");
list.addFile(QString(SRCDIR) + "/../data/files/foo4.c");
list.addFile(QString(SRCDIR) + "/../data/files/foo5.c++");
list.addFile(QString(SRCDIR) + "/../data/files/foo6.txx");
list.addFile(QString(SRCDIR) + "/../data/files/foo7.tpp");
list.addFile(QString(SRCDIR) + "/../data/files/foo8.ipp");
list.addFile(QString(SRCDIR) + "/../data/files/foo9.ixx");
QStringList files = list.getFileList();
QCOMPARE(files.size(), 7);
QDir dir(QString(SRCDIR) + "/../data/files");
QString base = dir.canonicalPath();
QVERIFY(!files.contains(base + "/foo1.cpp"));
QVERIFY(!files.contains(base + "/foo3.cpp"));
}
void TestFileList::filterFiles2() const
{
FileList list;
QStringList filters;
filters << "foo1.cpp" << "foo3.cc";
list.addExcludeList(filters);
list.addDirectory(QString(SRCDIR) + "/../data/files");
QStringList files = list.getFileList();
QCOMPARE(files.size(), 7);
QDir dir(QString(SRCDIR) + "/../data/files");
QString base = dir.canonicalPath();
QVERIFY(!files.contains(base + "/foo1.cpp"));
QVERIFY(!files.contains(base + "/foo3.cpp"));
}
void TestFileList::filterFiles3() const
{
FileList list;
QStringList filters;
filters << "foo1.cpp" << "foo3.cc";
list.addExcludeList(filters);
list.addDirectory(QString(SRCDIR) + "/../data/files", true);
QStringList files = list.getFileList();
QCOMPARE(files.size(), 8);
QDir dir(QString(SRCDIR) + "/../data/files");
QString base = dir.canonicalPath();
QVERIFY(!files.contains(base + "/foo1.cpp"));
QVERIFY(!files.contains(base + "/foo3.cpp"));
QVERIFY(!files.contains(base + "/dir1/foo1.cpp"));
QVERIFY(!files.contains(base + "/dir2/foo1.cpp"));
}
void TestFileList::filterFiles4() const
{
FileList list;
QStringList filters;
filters << "dir1/";
list.addExcludeList(filters);
list.addDirectory(QString(SRCDIR) + "/../data/files", true);
QStringList files = list.getFileList();
QCOMPARE(files.size(), 10);
QDir dir(QString(SRCDIR) + "/../data/files");
QString base = dir.canonicalPath();
QVERIFY(!files.contains(base + "/dir1/foo1.cpp"));
QVERIFY(!files.contains(base + "/dir1/dir11/foo11.cpp"));
}
void TestFileList::filterFiles5() const
{
FileList list;
QStringList filters;
filters << QDir(QString(SRCDIR) + "/../data/files/dir1/").absolutePath() + "/";
list.addExcludeList(filters);
list.addDirectory(QString(SRCDIR) + "/../data/files", true);
QStringList files = list.getFileList();
QCOMPARE(files.size(), 10);
QDir dir(QString(SRCDIR) + "/../data/files");
QString base = dir.canonicalPath();
QVERIFY(!files.contains(base + "/dir1/foo1.cpp"));
QVERIFY(!files.contains(base + "/dir1/dir11/foo11.cpp"));
}
QTEST_MAIN(TestFileList)
| null |
752 | cpp | cppcheck | testfilelist.h | gui/test/filelist/testfilelist.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2021 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <QObject>
class TestFileList : public QObject {
Q_OBJECT
private slots:
void addFile() const;
void addPathList() const;
void addFile_notexist() const;
void addFile_unknown() const;
void addDirectory() const;
void addDirectory_recursive() const;
void filterFiles() const;
void filterFiles2() const;
void filterFiles3() const;
void filterFiles4() const;
void filterFiles5() const;
};
| null |
753 | cpp | cppcheck | testprojectfile.cpp | gui/test/projectfile/testprojectfile.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2021 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "testprojectfile.h"
#include "importproject.h"
#include "library.h"
#include "platform.h"
#include "projectfile.h"
#include "settings.h"
#include "suppressions.h"
#include <string>
#include <QFile>
#include <QIODevice>
#include <QList>
#include <QStringList>
#include <QTemporaryDir>
#include <QtTest>
// Mock...
const char Settings::SafeChecks::XmlRootName[] = "safe-checks";
const char Settings::SafeChecks::XmlClasses[] = "class-public";
const char Settings::SafeChecks::XmlExternalFunctions[] = "external-functions";
const char Settings::SafeChecks::XmlInternalFunctions[] = "internal-functions";
const char Settings::SafeChecks::XmlExternalVariables[] = "external-variables";
Settings::Settings() : maxCtuDepth(10) {}
Platform::Platform() = default;
Library::Library() = default;
Library::~Library() = default;
struct Library::LibraryData {};
bool ImportProject::sourceFileExists(const std::string & /*file*/) {
return true;
}
void TestProjectFile::loadInexisting() const
{
const QString filepath(QString(SRCDIR) + "/../data/projectfiles/foo.cppcheck");
ProjectFile pfile(filepath);
QCOMPARE(pfile.read(), false);
}
void TestProjectFile::loadSimple() const
{
const QString filepath(QString(SRCDIR) + "/../data/projectfiles/simple.cppcheck");
ProjectFile pfile(filepath);
QVERIFY(pfile.read());
QCOMPARE(pfile.getRootPath(), QString("../.."));
QStringList includes = pfile.getIncludeDirs();
QCOMPARE(includes.size(), 2);
QCOMPARE(includes[0], QString("lib/"));
QCOMPARE(includes[1], QString("cli/"));
QStringList paths = pfile.getCheckPaths();
QCOMPARE(paths.size(), 2);
QCOMPARE(paths[0], QString("gui/"));
QCOMPARE(paths[1], QString("test/"));
QStringList excludes = pfile.getExcludedPaths();
QCOMPARE(excludes.size(), 1);
QCOMPARE(excludes[0], QString("gui/temp/"));
QStringList defines = pfile.getDefines();
QCOMPARE(defines.size(), 1);
QCOMPARE(defines[0], QString("FOO"));
}
// Test that project file with old 'ignore' element works
void TestProjectFile::loadSimpleWithIgnore() const
{
const QString filepath(QString(SRCDIR) + "/../data/projectfiles/simple_ignore.cppcheck");
ProjectFile pfile(filepath);
QVERIFY(pfile.read());
QCOMPARE(pfile.getRootPath(), QString("../.."));
QStringList includes = pfile.getIncludeDirs();
QCOMPARE(includes.size(), 2);
QCOMPARE(includes[0], QString("lib/"));
QCOMPARE(includes[1], QString("cli/"));
QStringList paths = pfile.getCheckPaths();
QCOMPARE(paths.size(), 2);
QCOMPARE(paths[0], QString("gui/"));
QCOMPARE(paths[1], QString("test/"));
QStringList excludes = pfile.getExcludedPaths();
QCOMPARE(excludes.size(), 1);
QCOMPARE(excludes[0], QString("gui/temp/"));
QStringList defines = pfile.getDefines();
QCOMPARE(defines.size(), 1);
QCOMPARE(defines[0], QString("FOO"));
}
void TestProjectFile::loadSimpleNoroot() const
{
const QString filepath(QString(SRCDIR) + "/../data/projectfiles/simple_noroot.cppcheck");
ProjectFile pfile(filepath);
QVERIFY(pfile.read());
QCOMPARE(pfile.getRootPath(), QString());
QStringList includes = pfile.getIncludeDirs();
QCOMPARE(includes.size(), 2);
QCOMPARE(includes[0], QString("lib/"));
QCOMPARE(includes[1], QString("cli/"));
QStringList paths = pfile.getCheckPaths();
QCOMPARE(paths.size(), 2);
QCOMPARE(paths[0], QString("gui/"));
QCOMPARE(paths[1], QString("test/"));
QStringList excludes = pfile.getExcludedPaths();
QCOMPARE(excludes.size(), 1);
QCOMPARE(excludes[0], QString("gui/temp/"));
QStringList defines = pfile.getDefines();
QCOMPARE(defines.size(), 1);
QCOMPARE(defines[0], QString("FOO"));
}
void TestProjectFile::getAddonFilePath() const
{
QTemporaryDir tempdir;
QVERIFY(tempdir.isValid());
const QString filepath(tempdir.path() + "/addon.py");
QFile file(filepath);
QVERIFY(file.open(QIODevice::WriteOnly | QIODevice::Text));
file.close();
// Relative path to addon
QCOMPARE(ProjectFile::getAddonFilePath(tempdir.path(), "addon"), filepath);
QCOMPARE(ProjectFile::getAddonFilePath(tempdir.path(), "not exist"), QString());
// Absolute path to addon
QCOMPARE(ProjectFile::getAddonFilePath("/not/exist", filepath), filepath);
QCOMPARE(ProjectFile::getAddonFilePath(tempdir.path(), filepath), filepath);
}
void TestProjectFile::getInlineSuppressionDefaultValue() const
{
ProjectFile projectFile;
projectFile.setFilename("/some/path/123.cppcheck");
QCOMPARE(projectFile.getInlineSuppression(), true);
}
void TestProjectFile::getInlineSuppression() const
{
ProjectFile projectFile;
projectFile.setFilename("/some/path/123.cppcheck");
projectFile.setInlineSuppression(false);
QCOMPARE(projectFile.getInlineSuppression(), false);
}
void TestProjectFile::getCheckingSuppressionsRelative() const
{
const SuppressionList::Suppression suppression("*", "externals/*");
const QList<SuppressionList::Suppression> suppressions{suppression};
ProjectFile projectFile;
projectFile.setFilename("/some/path/123.cppcheck");
projectFile.setSuppressions(suppressions);
QCOMPARE(projectFile.getCheckingSuppressions()[0].fileName, "/some/path/externals/*");
}
void TestProjectFile::getCheckingSuppressionsAbsolute() const
{
const SuppressionList::Suppression suppression("*", "/some/path/1.h");
const QList<SuppressionList::Suppression> suppressions{suppression};
ProjectFile projectFile;
projectFile.setFilename("/other/123.cppcheck");
projectFile.setSuppressions(suppressions);
QCOMPARE(projectFile.getCheckingSuppressions()[0].fileName, "/some/path/1.h");
}
void TestProjectFile::getCheckingSuppressionsStar() const
{
const SuppressionList::Suppression suppression("*", "*.cpp");
const QList<SuppressionList::Suppression> suppressions{suppression};
ProjectFile projectFile;
projectFile.setFilename("/some/path/123.cppcheck");
projectFile.setSuppressions(suppressions);
QCOMPARE(projectFile.getCheckingSuppressions()[0].fileName, "*.cpp");
}
QTEST_MAIN(TestProjectFile)
| null |
754 | cpp | cppcheck | testprojectfile.h | gui/test/projectfile/testprojectfile.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2021 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <QObject>
class TestProjectFile : public QObject {
Q_OBJECT
private slots:
void loadInexisting() const;
void loadSimple() const;
void loadSimpleWithIgnore() const;
void loadSimpleNoroot() const;
void getAddonFilePath() const;
void getInlineSuppressionDefaultValue() const;
void getInlineSuppression() const;
void getCheckingSuppressionsRelative() const;
void getCheckingSuppressionsAbsolute() const;
void getCheckingSuppressionsStar() const;
};
| null |
755 | cpp | cppcheck | testcppchecklibrarydata.cpp | gui/test/cppchecklibrarydata/testcppchecklibrarydata.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2021 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "testcppchecklibrarydata.h"
#include <QDir>
#include <QDebug>
#include <QFile>
#include <QIODevice>
#include <QList>
#include <QPair>
#include <QStringList>
#include <QTextStream>
#include <QtTest>
const QString TestCppcheckLibraryData::TempCfgFile = "./tmp.cfg";
void TestCppcheckLibraryData::init()
{
result.clear();
libraryData.clear();
fileLibraryData.clear();
}
void TestCppcheckLibraryData::xmlReaderError()
{
loadCfgFile(":/files/xml_reader_error.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), false);
qDebug() << result;
}
void TestCppcheckLibraryData::unhandledElement()
{
loadCfgFile(":/files/unhandled_element.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), false);
qDebug() << result;
loadCfgFile(":/files/platform_type_unhandled_element.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), false);
qDebug() << result;
loadCfgFile(":/files/memory_resource_unhandled_element.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), false);
qDebug() << result;
loadCfgFile(":/files/container_unhandled_element.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), false);
qDebug() << result;
loadCfgFile(":/files/reflection_unhandled_element.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), false);
qDebug() << result;
loadCfgFile(":/files/markup_unhandled_element.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), false);
qDebug() << result;
}
void TestCppcheckLibraryData::mandatoryAttributeMissing()
{
loadCfgFile(":/files/mandatory_attribute_missing.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), false);
qDebug() << result;
loadCfgFile(":/files/reflection_mandatory_attribute_missing.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), false);
qDebug() << result;
loadCfgFile(":/files/markup_mandatory_attribute_missing.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), false);
qDebug() << result;
}
void TestCppcheckLibraryData::podtypeValid()
{
// Load library data from file
loadCfgFile(":/files/podtype_valid.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), true);
// Swap library data read from file to other object
libraryData.swap(fileLibraryData);
// Do size and content checks against swapped data.
QCOMPARE(libraryData.podtypes.size(), 2);
QCOMPARE(libraryData.podtypes[0].name, QString("bool"));
QCOMPARE(libraryData.podtypes[0].stdtype.isEmpty(), true);
QCOMPARE(libraryData.podtypes[0].sign.isEmpty(), true);
QCOMPARE(libraryData.podtypes[0].size.isEmpty(), true);
QCOMPARE(libraryData.podtypes[1].name, QString("ulong"));
QCOMPARE(libraryData.podtypes[1].stdtype, QString("uint32_t"));
QCOMPARE(libraryData.podtypes[1].sign, QString("u"));
QCOMPARE(libraryData.podtypes[1].size, QString("4"));
// Save library data to file
saveCfgFile(TempCfgFile, libraryData);
fileLibraryData.clear();
QCOMPARE(fileLibraryData.podtypes.size(), 0);
// Reload library data from file
loadCfgFile(TempCfgFile, fileLibraryData, result, true);
QCOMPARE(result.isNull(), true);
// Verify no data got lost or modified
QCOMPARE(libraryData.podtypes.size(), fileLibraryData.podtypes.size());
QCOMPARE(libraryData.podtypes.size(), 2);
for (int i=0; i < libraryData.podtypes.size(); i++) {
QCOMPARE(libraryData.podtypes[i].name, fileLibraryData.podtypes[i].name);
QCOMPARE(libraryData.podtypes[i].stdtype, fileLibraryData.podtypes[i].stdtype);
QCOMPARE(libraryData.podtypes[i].sign, fileLibraryData.podtypes[i].sign);
QCOMPARE(libraryData.podtypes[i].size, fileLibraryData.podtypes[i].size);
}
}
void TestCppcheckLibraryData::typechecksValid()
{
// Load library data from file
loadCfgFile(":/files/typechecks_valid.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), true);
// Swap library data read from file to other object
libraryData.swap(fileLibraryData);
// Do size and content checks against swapped data.
QCOMPARE(libraryData.typeChecks.size(), 3);
CppcheckLibraryData::TypeChecks check = libraryData.typeChecks[0];
QCOMPARE(check.size(), 2);
QCOMPARE(check[0].first, QString("suppress"));
QCOMPARE(check[0].second, QString("std::insert_iterator"));
QCOMPARE(check[1].first, QString("check"));
QCOMPARE(check[1].second, QString("std::pair"));
check = libraryData.typeChecks[1];
QCOMPARE(check.isEmpty(), true);
check = libraryData.typeChecks[2];
QCOMPARE(check.size(), 1);
QCOMPARE(check[0].first, QString("check"));
QCOMPARE(check[0].second, QString("std::tuple"));
// Save library data to file
saveCfgFile(TempCfgFile, libraryData);
fileLibraryData.clear();
QCOMPARE(fileLibraryData.typeChecks.size(), 0);
// Reload library data from file
loadCfgFile(TempCfgFile, fileLibraryData, result, true);
QCOMPARE(result.isNull(), true);
// Verify no data got lost or modified
QCOMPARE(libraryData.typeChecks.size(), fileLibraryData.typeChecks.size());
QCOMPARE(libraryData.typeChecks.size(), 3);
for (int idx=0; idx < libraryData.typeChecks.size(); idx++) {
CppcheckLibraryData::TypeChecks lhs = libraryData.typeChecks[idx];
CppcheckLibraryData::TypeChecks rhs = fileLibraryData.typeChecks[idx];
QCOMPARE(lhs.size(), rhs.size());
QCOMPARE(lhs, rhs);
}
}
void TestCppcheckLibraryData::smartPointerValid()
{
// Load library data from file
loadCfgFile(":/files/smartptr_valid.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), true);
// Swap library data read from file to other object
libraryData.swap(fileLibraryData);
// Do size and content checks against swapped data.
QCOMPARE(libraryData.smartPointers.size(), 3);
QCOMPARE(libraryData.smartPointers[0].name, QString("wxObjectDataPtr"));
QCOMPARE(libraryData.smartPointers[0].unique, false);
QCOMPARE(libraryData.smartPointers[1].name, QString("wxScopedArray"));
QCOMPARE(libraryData.smartPointers[1].unique, true);
QCOMPARE(libraryData.smartPointers[2].name, QString("wxScopedPtr"));
QCOMPARE(libraryData.smartPointers[2].unique, false);
// Save library data to file
saveCfgFile(TempCfgFile, libraryData);
fileLibraryData.clear();
QCOMPARE(fileLibraryData.smartPointers.size(), 0);
// Reload library data from file
loadCfgFile(TempCfgFile, fileLibraryData, result, true);
QCOMPARE(result.isNull(), true);
// Verify no data got lost or modified
QCOMPARE(libraryData.smartPointers.size(), fileLibraryData.smartPointers.size());
QCOMPARE(libraryData.smartPointers.size(), 3);
for (int idx=0; idx < libraryData.smartPointers.size(); idx++) {
QCOMPARE(libraryData.smartPointers[idx].name, fileLibraryData.smartPointers[idx].name);
QCOMPARE(libraryData.smartPointers[idx].unique, fileLibraryData.smartPointers[idx].unique);
}
}
void TestCppcheckLibraryData::platformTypeValid()
{
// Load library data from file
loadCfgFile(":/files/platform_type_valid.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), true);
// Swap library data read from file to other object
libraryData.swap(fileLibraryData);
// Do size and content checks against swapped data.
QCOMPARE(libraryData.platformTypes.size(), 3);
QCOMPARE(libraryData.platformTypes[0].name, QString("platform"));
QCOMPARE(libraryData.platformTypes[0].value, QString("with attribute and empty"));
QCOMPARE(libraryData.platformTypes[0].types.size(), 0);
QCOMPARE(libraryData.platformTypes[0].platforms.size(), 2);
QCOMPARE(libraryData.platformTypes[0].platforms[0], QString("win64"));
QCOMPARE(libraryData.platformTypes[0].platforms[1].isEmpty(), true);
QCOMPARE(libraryData.platformTypes[1].name, QString("types"));
QCOMPARE(libraryData.platformTypes[1].value, QString("all"));
QCOMPARE(libraryData.platformTypes[1].types.size(), 5);
QCOMPARE(libraryData.platformTypes[1].types,
QStringList({"unsigned", "long", "pointer", "const_ptr", "ptr_ptr"}));
QCOMPARE(libraryData.platformTypes[1].platforms.isEmpty(), true);
QCOMPARE(libraryData.platformTypes[2].name, QString("types and platform"));
QCOMPARE(libraryData.platformTypes[2].value.isEmpty(), true);
QCOMPARE(libraryData.platformTypes[2].types.size(), 2);
QCOMPARE(libraryData.platformTypes[2].types, QStringList({"pointer", "ptr_ptr"}));
QCOMPARE(libraryData.platformTypes[2].platforms.size(), 1);
QCOMPARE(libraryData.platformTypes[2].platforms[0], QString("win32"));
// Save library data to file
saveCfgFile(TempCfgFile, libraryData);
fileLibraryData.clear();
QCOMPARE(fileLibraryData.platformTypes.size(), 0);
// Reload library data from file
loadCfgFile(TempCfgFile, fileLibraryData, result, true);
QCOMPARE(result.isNull(), true);
// Verify no data got lost or modified
QCOMPARE(libraryData.platformTypes.size(), fileLibraryData.platformTypes.size());
QCOMPARE(libraryData.platformTypes.size(), 3);
for (int idx=0; idx < libraryData.platformTypes.size(); idx++) {
CppcheckLibraryData::PlatformType lhs = libraryData.platformTypes[idx];
CppcheckLibraryData::PlatformType rhs = fileLibraryData.platformTypes[idx];
QCOMPARE(lhs.name, rhs.name);
QCOMPARE(lhs.value, rhs.value);
QCOMPARE(lhs.types.size(), rhs.types.size());
QCOMPARE(lhs.types, rhs.types);
QCOMPARE(lhs.platforms.size(), rhs.platforms.size());
QCOMPARE(lhs.platforms, rhs.platforms);
}
}
void TestCppcheckLibraryData::memoryResourceValid()
{
// Load library data from file
loadCfgFile(":/files/memory_resource_valid.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), true);
// Swap library data read from file to other object
libraryData.swap(fileLibraryData);
// Do size and content checks against swapped data.
QCOMPARE(libraryData.memoryresource.size(), 2);
QCOMPARE(libraryData.memoryresource[0].type, QString("memory"));
QCOMPARE(libraryData.memoryresource[0].alloc.size(), 4);
QCOMPARE(libraryData.memoryresource[0].dealloc.size(), 1);
QCOMPARE(libraryData.memoryresource[0].use.size(), 0);
QCOMPARE(libraryData.memoryresource[0].alloc[0].name, QString("malloc"));
QCOMPARE(libraryData.memoryresource[0].alloc[0].bufferSize, QString("malloc"));
QCOMPARE(libraryData.memoryresource[0].alloc[0].isRealloc, false);
QCOMPARE(libraryData.memoryresource[0].alloc[0].init, false);
QCOMPARE(libraryData.memoryresource[0].alloc[0].arg, -1);
QCOMPARE(libraryData.memoryresource[0].alloc[0].reallocArg, -1);
QCOMPARE(libraryData.memoryresource[0].alloc[1].name, QString("calloc"));
QCOMPARE(libraryData.memoryresource[0].alloc[1].bufferSize, QString("calloc"));
QCOMPARE(libraryData.memoryresource[0].alloc[1].isRealloc, false);
QCOMPARE(libraryData.memoryresource[0].alloc[1].init, true);
QCOMPARE(libraryData.memoryresource[0].alloc[1].arg, -1);
QCOMPARE(libraryData.memoryresource[0].alloc[1].reallocArg, -1);
QCOMPARE(libraryData.memoryresource[0].alloc[2].name, QString("realloc"));
QCOMPARE(libraryData.memoryresource[0].alloc[2].bufferSize, QString("malloc:2"));
QCOMPARE(libraryData.memoryresource[0].alloc[2].isRealloc, true);
QCOMPARE(libraryData.memoryresource[0].alloc[2].init, false);
QCOMPARE(libraryData.memoryresource[0].alloc[2].arg, -1);
QCOMPARE(libraryData.memoryresource[0].alloc[2].reallocArg, -1);
QCOMPARE(libraryData.memoryresource[0].alloc[3].name, QString("UuidToString"));
QCOMPARE(libraryData.memoryresource[0].alloc[3].bufferSize.isEmpty(), true);
QCOMPARE(libraryData.memoryresource[0].alloc[3].isRealloc, false);
QCOMPARE(libraryData.memoryresource[0].alloc[3].init, false);
QCOMPARE(libraryData.memoryresource[0].alloc[3].arg, 2);
QCOMPARE(libraryData.memoryresource[0].alloc[3].reallocArg, -1);
QCOMPARE(libraryData.memoryresource[0].dealloc[0].name, QString("HeapFree"));
QCOMPARE(libraryData.memoryresource[0].dealloc[0].arg, 3);
QCOMPARE(libraryData.memoryresource[1].type, QString("resource"));
QCOMPARE(libraryData.memoryresource[1].alloc.size(), 1);
QCOMPARE(libraryData.memoryresource[1].dealloc.size(), 1);
QCOMPARE(libraryData.memoryresource[1].use.size(), 0);
QCOMPARE(libraryData.memoryresource[1].alloc[0].name, QString("_wfopen_s"));
QCOMPARE(libraryData.memoryresource[1].alloc[0].bufferSize.isEmpty(), true);
QCOMPARE(libraryData.memoryresource[1].alloc[0].isRealloc, false);
QCOMPARE(libraryData.memoryresource[1].alloc[0].init, true);
QCOMPARE(libraryData.memoryresource[1].alloc[0].arg, 1);
QCOMPARE(libraryData.memoryresource[1].alloc[0].reallocArg, -1);
QCOMPARE(libraryData.memoryresource[1].dealloc[0].name, QString("fclose"));
QCOMPARE(libraryData.memoryresource[1].dealloc[0].arg, -1);
// Save library data to file
saveCfgFile(TempCfgFile, libraryData);
fileLibraryData.clear();
QCOMPARE(fileLibraryData.memoryresource.size(), 0);
// Reload library data from file
loadCfgFile(TempCfgFile, fileLibraryData, result, true);
QCOMPARE(result.isNull(), true);
// Verify no data got lost or modified
QCOMPARE(libraryData.memoryresource.size(), fileLibraryData.memoryresource.size());
QCOMPARE(libraryData.memoryresource.size(), 2);
for (int idx=0; idx < libraryData.memoryresource.size(); idx++) {
CppcheckLibraryData::MemoryResource lhs = libraryData.memoryresource[idx];
CppcheckLibraryData::MemoryResource rhs = fileLibraryData.memoryresource[idx];
QCOMPARE(lhs.type, rhs.type);
QCOMPARE(lhs.alloc.size(), rhs.alloc.size());
QCOMPARE(lhs.dealloc.size(), rhs.dealloc.size());
QCOMPARE(lhs.use, rhs.use);
for (int num=0; num < lhs.alloc.size(); num++) {
QCOMPARE(lhs.alloc[num].name, rhs.alloc[num].name);
QCOMPARE(lhs.alloc[num].bufferSize, rhs.alloc[num].bufferSize);
QCOMPARE(lhs.alloc[num].isRealloc, rhs.alloc[num].isRealloc);
QCOMPARE(lhs.alloc[num].init, rhs.alloc[num].init);
QCOMPARE(lhs.alloc[num].arg, rhs.alloc[num].arg);
QCOMPARE(lhs.alloc[num].reallocArg, rhs.alloc[num].reallocArg);
}
for (int num=0; num < lhs.dealloc.size(); num++) {
QCOMPARE(lhs.dealloc[num].name, rhs.dealloc[num].name);
QCOMPARE(lhs.dealloc[num].arg, rhs.dealloc[num].arg);
}
}
}
void TestCppcheckLibraryData::defineValid()
{
// Load library data from file
loadCfgFile(":/files/define_valid.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), true);
// Swap library data read from file to other object
libraryData.swap(fileLibraryData);
// Do size and content checks against swapped data.
QCOMPARE(libraryData.defines.size(), 2);
QCOMPARE(libraryData.defines[0].name, QString("INT8_MIN"));
QCOMPARE(libraryData.defines[0].value, QString("-128"));
QCOMPARE(libraryData.defines[1].name.isEmpty(), true);
QCOMPARE(libraryData.defines[1].value.isEmpty(), true);
// Save library data to file
saveCfgFile(TempCfgFile, libraryData);
fileLibraryData.clear();
QCOMPARE(fileLibraryData.defines.size(), 0);
// Reload library data from file
loadCfgFile(TempCfgFile, fileLibraryData, result, true);
QCOMPARE(result.isNull(), true);
// Verify no data got lost or modified
QCOMPARE(libraryData.defines.size(), fileLibraryData.defines.size());
QCOMPARE(libraryData.defines.size(), 2);
for (int idx=0; idx < libraryData.defines.size(); idx++) {
QCOMPARE(libraryData.defines[idx].name, fileLibraryData.defines[idx].name);
QCOMPARE(libraryData.defines[idx].value, fileLibraryData.defines[idx].value);
}
}
void TestCppcheckLibraryData::undefineValid()
{
// Load library data from file
loadCfgFile(":/files/undefine_valid.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), true);
// Swap library data read from file to other object
libraryData.swap(fileLibraryData);
// Do size and content checks against swapped data.
QCOMPARE(libraryData.undefines.size(), 2);
QCOMPARE(libraryData.undefines[0], QString("INT8_MIN"));
QCOMPARE(libraryData.undefines[1].isEmpty(), true);
// Save library data to file
saveCfgFile(TempCfgFile, libraryData);
fileLibraryData.clear();
QCOMPARE(fileLibraryData.undefines.size(), 0);
// Reload library data from file
loadCfgFile(TempCfgFile, fileLibraryData, result, true);
QCOMPARE(result.isNull(), true);
// Verify no data got lost or modified
QCOMPARE(libraryData.undefines.size(), fileLibraryData.undefines.size());
QCOMPARE(libraryData.undefines.size(), 2);
QCOMPARE(libraryData.undefines, fileLibraryData.undefines);
}
void TestCppcheckLibraryData::reflectionValid()
{
// Load library data from file
loadCfgFile(":/files/reflection_valid.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), true);
// Swap library data read from file to other object
libraryData.swap(fileLibraryData);
// Do size and content checks against swapped data.
QCOMPARE(libraryData.reflections.size(), 2);
QCOMPARE(libraryData.reflections[0].calls.size(), 2);
QCOMPARE(libraryData.reflections[0].calls[0].arg, 2);
QCOMPARE(libraryData.reflections[0].calls[0].name, QString("invokeMethod"));
QCOMPARE(libraryData.reflections[0].calls[1].arg, 1);
QCOMPARE(libraryData.reflections[0].calls[1].name, QString("callFunction"));
QCOMPARE(libraryData.reflections[1].calls.isEmpty(), true);
// Save library data to file
saveCfgFile(TempCfgFile, libraryData);
fileLibraryData.clear();
QCOMPARE(fileLibraryData.reflections.size(), 0);
// Reload library data from file
loadCfgFile(TempCfgFile, fileLibraryData, result, true);
QCOMPARE(result.isNull(), true);
// Verify no data got lost or modified
QCOMPARE(libraryData.reflections.size(), fileLibraryData.reflections.size());
QCOMPARE(libraryData.reflections.size(), 2);
for (int idx=0; idx < libraryData.reflections.size(); idx++) {
CppcheckLibraryData::Reflection lhs = libraryData.reflections[idx];
CppcheckLibraryData::Reflection rhs = fileLibraryData.reflections[idx];
QCOMPARE(lhs.calls.size(), rhs.calls.size());
for (int num=0; num < lhs.calls.size(); num++) {
QCOMPARE(lhs.calls[num].arg, rhs.calls[num].arg);
QCOMPARE(lhs.calls[num].name, rhs.calls[num].name);
}
}
}
void TestCppcheckLibraryData::markupValid()
{
// Load library data from file
loadCfgFile(":/files/markup_valid.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), true);
// Swap library data read from file to other object
libraryData.swap(fileLibraryData);
// Do size and content checks against swapped data.
QCOMPARE(libraryData.markups.size(), 1);
QCOMPARE(libraryData.markups[0].ext, QString(".qml"));
QCOMPARE(libraryData.markups[0].reportErrors, false);
QCOMPARE(libraryData.markups[0].afterCode, true);
QCOMPARE(libraryData.markups[0].keywords.size(), 4);
QCOMPARE(libraryData.markups[0].keywords, QStringList({"if", "while", "typeof", "for"}));
QCOMPARE(libraryData.markups[0].importer.size(), 1);
QCOMPARE(libraryData.markups[0].importer, QStringList("connect"));
QCOMPARE(libraryData.markups[0].exporter.size(), 1);
QCOMPARE(libraryData.markups[0].exporter[0].prefix, QString("Q_PROPERTY"));
QCOMPARE(libraryData.markups[0].exporter[0].suffixList.size(), 1);
QCOMPARE(libraryData.markups[0].exporter[0].suffixList, QStringList("READ"));
QCOMPARE(libraryData.markups[0].exporter[0].prefixList.size(), 3);
QCOMPARE(libraryData.markups[0].exporter[0].prefixList, QStringList({"READ", "WRITE", "NOTIFY"}));
QCOMPARE(libraryData.markups[0].codeBlocks.size(), 2);
QCOMPARE(libraryData.markups[0].codeBlocks[0].blocks.size(), 5);
QCOMPARE(libraryData.markups[0].codeBlocks[0].blocks, QStringList({"onClicked", "onFinished", "onTriggered", "onPressed", "onTouch"}));
QCOMPARE(libraryData.markups[0].codeBlocks[0].offset, 3);
QCOMPARE(libraryData.markups[0].codeBlocks[0].start, QString("{"));
QCOMPARE(libraryData.markups[0].codeBlocks[0].end, QString("}"));
QCOMPARE(libraryData.markups[0].codeBlocks[1].blocks.size(), 1);
QCOMPARE(libraryData.markups[0].codeBlocks[1].blocks, QStringList("function"));
QCOMPARE(libraryData.markups[0].codeBlocks[1].offset, 2);
QCOMPARE(libraryData.markups[0].codeBlocks[1].start, QString("{"));
QCOMPARE(libraryData.markups[0].codeBlocks[1].end, QString("}"));
// Save library data to file
saveCfgFile(TempCfgFile, libraryData);
fileLibraryData.clear();
QCOMPARE(fileLibraryData.markups.size(), 0);
// Reload library data from file
loadCfgFile(TempCfgFile, fileLibraryData, result, true);
QCOMPARE(result.isNull(), true);
// Verify no data got lost or modified
QCOMPARE(libraryData.markups.size(), fileLibraryData.markups.size());
for (int idx=0; idx < libraryData.markups.size(); idx++) {
CppcheckLibraryData::Markup lhs = libraryData.markups[idx];
CppcheckLibraryData::Markup rhs = fileLibraryData.markups[idx];
QCOMPARE(lhs.ext, rhs.ext);
QCOMPARE(lhs.reportErrors, rhs.reportErrors);
QCOMPARE(lhs.afterCode, rhs.afterCode);
QCOMPARE(lhs.keywords, rhs.keywords);
QCOMPARE(lhs.importer, rhs.importer);
for (int num=0; num < lhs.exporter.size(); num++) {
QCOMPARE(lhs.exporter[num].prefix, rhs.exporter[num].prefix);
QCOMPARE(lhs.exporter[num].suffixList, rhs.exporter[num].suffixList);
QCOMPARE(lhs.exporter[num].prefixList, rhs.exporter[num].prefixList);
}
for (int num=0; num < lhs.codeBlocks.size(); num++) {
QCOMPARE(lhs.codeBlocks[num].blocks, rhs.codeBlocks[num].blocks);
QCOMPARE(lhs.codeBlocks[num].offset, rhs.codeBlocks[num].offset);
QCOMPARE(lhs.codeBlocks[num].start, rhs.codeBlocks[num].start);
QCOMPARE(lhs.codeBlocks[num].end, rhs.codeBlocks[num].end);
}
}
}
void TestCppcheckLibraryData::containerValid()
{
// Load library data from file
loadCfgFile(":/files/container_valid.cfg", fileLibraryData, result);
QCOMPARE(result.isNull(), true);
// Swap library data read from file to other object
libraryData.swap(fileLibraryData);
// Do size and content checks against swapped data.
QCOMPARE(libraryData.containers.size(), 1);
QCOMPARE(libraryData.containers[0].rangeItemRecordTypeList.size(), 2);
QCOMPARE(libraryData.containers[0].rangeItemRecordTypeList[0].name, QString("first"));
QCOMPARE(libraryData.containers[0].rangeItemRecordTypeList[0].templateParameter, QString("0"));
QCOMPARE(libraryData.containers[0].rangeItemRecordTypeList[1].name, QString("second"));
QCOMPARE(libraryData.containers[0].rangeItemRecordTypeList[1].templateParameter, QString("1"));
// Save library data to file
saveCfgFile(TempCfgFile, libraryData);
fileLibraryData.clear();
QCOMPARE(fileLibraryData.containers.size(), 0);
// Reload library data from file
loadCfgFile(TempCfgFile, fileLibraryData, result, true);
QCOMPARE(result.isNull(), true);
// Verify no data got lost or modified
QCOMPARE(libraryData.containers.size(), fileLibraryData.containers.size());
for (int idx=0; idx < libraryData.containers.size(); idx++) {
CppcheckLibraryData::Container lhs = libraryData.containers[idx];
CppcheckLibraryData::Container rhs = fileLibraryData.containers[idx];
for (int num=0; num < lhs.rangeItemRecordTypeList.size(); num++) {
QCOMPARE(lhs.rangeItemRecordTypeList[num].name, rhs.rangeItemRecordTypeList[num].name);
QCOMPARE(lhs.rangeItemRecordTypeList[num].templateParameter, rhs.rangeItemRecordTypeList[num].templateParameter);
}
}
}
void TestCppcheckLibraryData::loadCfgFile(const QString &filename, CppcheckLibraryData &data, QString &res, bool removeFile)
{
QFile file(filename);
QVERIFY(file.open(QIODevice::ReadOnly | QIODevice::Text));
res = data.open(file);
file.close();
if (removeFile) {
file.remove();
}
}
void TestCppcheckLibraryData::saveCfgFile(const QString &filename, CppcheckLibraryData &data)
{
QFile file(filename);
QVERIFY(file.open(QIODevice::WriteOnly | QIODevice::Text));
QTextStream textStream(&file);
textStream << data.toString() << '\n';
file.close();
}
void TestCppcheckLibraryData::validateAllCfg()
{
const QDir dir(QString(SRCDIR) + "/../../../cfg/");
const QStringList files = dir.entryList(QStringList() << "*.cfg",QDir::Files);
QVERIFY(!files.empty());
bool error = false;
for (const QString& f : files) {
loadCfgFile(dir.absolutePath() + "/" + f, fileLibraryData, result);
if (!result.isNull()) {
error = true;
qDebug() << f << " - " << result;
}
}
QCOMPARE(error, false);
}
QTEST_MAIN(TestCppcheckLibraryData)
| null |
756 | cpp | cppcheck | testcppchecklibrarydata.h | gui/test/cppchecklibrarydata/testcppchecklibrarydata.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2021 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "cppchecklibrarydata.h"
#include <QObject>
#include <QString>
class TestCppcheckLibraryData : public QObject {
Q_OBJECT
private slots:
void init();
void xmlReaderError();
void unhandledElement();
void mandatoryAttributeMissing();
void podtypeValid();
void typechecksValid();
void smartPointerValid();
void platformTypeValid();
void memoryResourceValid();
void defineValid();
void undefineValid();
void reflectionValid();
void markupValid();
void containerValid();
void validateAllCfg();
private:
static void loadCfgFile(const QString &filename, CppcheckLibraryData &data, QString &res, bool removeFile = false);
static void saveCfgFile(const QString &filename, CppcheckLibraryData &data);
CppcheckLibraryData libraryData;
CppcheckLibraryData fileLibraryData;
QString result;
static const QString TempCfgFile;
};
| null |
757 | cpp | cppcheck | testtranslationhandler.cpp | gui/test/translationhandler/testtranslationhandler.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2021 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "testtranslationhandler.h"
#include "translationhandler.h"
#include <QList>
#include <QStringList>
#include <QtTest>
static QStringList getTranslationNames(const TranslationHandler& handler)
{
QStringList names;
for (const TranslationInfo& translation : handler.getTranslations()) {
names.append(translation.mName);
}
return names;
}
void TestTranslationHandler::construct() const
{
TranslationHandler handler;
QCOMPARE(getTranslationNames(handler).size(), 13); // 12 translations + english
QCOMPARE(handler.getCurrentLanguage(), QString("en"));
}
QTEST_MAIN(TestTranslationHandler)
| null |
758 | cpp | cppcheck | testtranslationhandler.h | gui/test/translationhandler/testtranslationhandler.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2021 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <QObject>
class TestTranslationHandler : public QObject {
Q_OBJECT
private slots:
void construct() const;
};
| null |
759 | cpp | cppcheck | foo3.cc | gui/test/data/files/foo3.cc | null | Dummy test file.
| null |
760 | cpp | cppcheck | foo1.cpp | gui/test/data/files/foo1.cpp | null | Dummy test file .
| null |
761 | cpp | cppcheck | foo1.cpp | gui/test/data/files/dir1/foo1.cpp | null | Dummy test file .
| null |
762 | cpp | cppcheck | foo11.cpp | gui/test/data/files/dir1/dir11/foo11.cpp | null | Dummy test file .
| null |
763 | cpp | cppcheck | foo1.cpp | gui/test/data/files/dir2/foo1.cpp | null | Dummy test file .
| null |
764 | cpp | cppcheck | testresultstree.h | gui/test/resultstree/testresultstree.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2021 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <QObject>
class TestResultsTree : public QObject {
Q_OBJECT
private slots:
void test1() const;
void testReportType() const;
void testGetGuidelineError() const;
};
| null |
765 | cpp | cppcheck | testresultstree.cpp | gui/test/resultstree/testresultstree.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2021 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "testresultstree.h"
#include "resultstree.h"
// headers that declare mocked functions/variables
#include "applicationlist.h"
#include "common.h"
#include "threadhandler.h"
#include "projectfile.h"
#include "application.h"
#include "cppcheck.h"
#include "erroritem.h"
#include "errorlogger.h"
#include "errortypes.h"
#include "path.h"
#include "report.h"
#include "settings.h"
#include "showtypes.h"
#include "suppressions.h"
#include "xmlreport.h"
#include <cstddef>
#include <set>
#include <string>
#include <utility>
#include <QModelIndex>
#include <QString>
#include <QtTest>
class TestReport : public Report {
public:
explicit TestReport(QString format) : Report(QString()), format(std::move(format)) {}
void writeHeader() override {
output.clear();
}
void writeFooter() override {}
void writeError(const ErrorItem &error) override {
QString line = format;
line.replace("{id}", error.errorId);
line.replace("{classification}", error.classification);
line.replace("{guideline}", error.guideline);
output += (output.isEmpty() ? "" : "\n") + line;
}
QString format;
QString output;
};
// Mock GUI...
ProjectFile::ProjectFile(QObject *parent) : QObject(parent) {}
ProjectFile *ProjectFile::mActiveProject;
void ProjectFile::addSuppression(const SuppressionList::Suppression & /*unused*/) {}
QString ProjectFile::getWarningTags(std::size_t /*unused*/) const {
return QString();
}
void ProjectFile::setWarningTags(std::size_t /*unused*/, const QString& /*unused*/) {}
bool ProjectFile::write(const QString & /*unused*/) {
return true;
}
std::string severityToString(Severity severity) {
return std::to_string((int)severity);
}
ApplicationList::ApplicationList(QObject *parent) : QObject(parent) {}
ApplicationList::~ApplicationList() = default;
int ApplicationList::getApplicationCount() const {
return 0;
}
ThreadHandler::ThreadHandler(QObject *parent) : QObject(parent) {}
ThreadHandler::~ThreadHandler() = default;
bool ThreadHandler::isChecking() const {
return false;
}
void ThreadHandler::stop() {
throw 1;
}
void ThreadHandler::threadDone() {
throw 1;
}
Application& ApplicationList::getApplication(const int /*unused*/) {
throw 1;
}
const Application& ApplicationList::getApplication(const int index) const {
return mApplications.at(index);
}
QString getPath(const QString &type) {
return "/" + type;
}
void setPath(const QString & /*unused*/, const QString & /*unused*/) {}
QString XmlReport::quoteMessage(const QString &message) {
return message;
}
QString XmlReport::unquoteMessage(const QString &message) {
return message;
}
XmlReport::XmlReport(const QString& filename) : Report(filename) {}
void ThreadResult::fileChecked(const QString & /*unused*/) {
throw 1;
}
void ThreadResult::reportOut(const std::string & /*unused*/, Color /*unused*/) {
throw 1;
}
void ThreadResult::reportErr(const ErrorMessage & /*unused*/) {
throw 1;
}
// Mock LIB...
bool Path::isHeader(std::string const& /*unused*/) {
return false;
}
const std::set<std::string> ErrorLogger::mCriticalErrorIds;
std::string ErrorMessage::FileLocation::getfile(bool /*unused*/) const {
return std::string();
}
const char* CppCheck::version() {
return "1.0";
}
std::pair<std::string, std::string> Settings::getNameAndVersion(const std::string& /*unused*/) {
throw 1;
}
Severity severityFromString(const std::string& severity) {
return (Severity)std::stoi(severity);
}
// Test...
void TestResultsTree::test1() const
{
// #12772 : GUI: information messages are shown even though information tool button is deselected
ResultsTree tree(nullptr);
tree.showResults(ShowTypes::ShowType::ShowInformation, false);
ErrorItem errorItem;
errorItem.errorPath << QErrorPathItem();
errorItem.severity = Severity::information;
tree.addErrorItem(errorItem);
QCOMPARE(tree.isRowHidden(0,QModelIndex()), true); // Added item is hidden
tree.showResults(ShowTypes::ShowType::ShowInformation, true);
QCOMPARE(tree.isRowHidden(0,QModelIndex()), false); // Show item
}
void TestResultsTree::testReportType() const
{
TestReport report("{id},{classification},{guideline}");
int msgCount = 0;
auto createErrorItem = [&msgCount](const Severity severity, const QString& errorId) -> ErrorItem {
++msgCount;
ErrorItem errorItem;
errorItem.errorPath << QErrorPathItem(ErrorMessage::FileLocation("file1.c", msgCount, 1));
errorItem.severity = severity;
errorItem.errorId = errorId;
errorItem.summary = "test summary " + QString::number(msgCount);
return errorItem;
};
// normal report with 2 errors
ResultsTree tree(nullptr);
tree.updateSettings(false, false, false, false, false);
tree.addErrorItem(createErrorItem(Severity::style, "id1"));
tree.addErrorItem(createErrorItem(Severity::style, "unusedVariable")); // Misra C 2.8
tree.saveResults(&report);
QCOMPARE(report.output, "id1,,\nunusedVariable,,");
// switch to Misra C report and check that "id1" is not shown
tree.setReportType(ReportType::misraC);
tree.saveResults(&report);
QCOMPARE(report.output, "unusedVariable,Advisory,2.8");
// add "missingReturn" and check that it is added properly
tree.addErrorItem(createErrorItem(Severity::warning, "missingReturn")); // Misra C 17.4
tree.saveResults(&report);
QCOMPARE(report.output,
"unusedVariable,Advisory,2.8\n"
"missingReturn,Mandatory,17.4");
}
void TestResultsTree::testGetGuidelineError() const
{
TestReport report("{id},{classification},{guideline}");
int msgCount = 0;
auto createErrorItem = [&msgCount](const Severity severity, const QString& errorId) -> ErrorItem {
++msgCount;
ErrorItem errorItem;
errorItem.errorPath << QErrorPathItem(ErrorMessage::FileLocation("file1.c", msgCount, 1));
errorItem.severity = severity;
errorItem.errorId = errorId;
errorItem.summary = "test summary " + QString::number(msgCount);
return errorItem;
};
// normal report with 2 errors
ResultsTree tree(nullptr);
tree.setReportType(ReportType::misraC);
tree.addErrorItem(createErrorItem(Severity::error, "id1")); // error severity => guideline 1.3
tree.saveResults(&report);
QCOMPARE(report.output, "id1,Required,1.3");
}
QTEST_MAIN(TestResultsTree)
| null |
766 | cpp | cppcheck | testxmlreportv2.cpp | gui/test/xmlreportv2/testxmlreportv2.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2021 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "testxmlreportv2.h"
#include "erroritem.h"
#include "xmlreportv2.h"
#include <QList>
#include <QtTest>
void TestXmlReportV2::readXml() const
{
const QString filepath(QString(SRCDIR) + "/../data/xmlfiles/xmlreport_v2.xml");
XmlReportV2 report(filepath, QString());
QVERIFY(report.open());
QList<ErrorItem> errors = report.read();
QCOMPARE(errors.size(), 6);
const ErrorItem &item = errors[0];
QCOMPARE(item.errorPath.size(), 1);
QCOMPARE(item.errorPath[0].file, QString("test.cxx"));
QCOMPARE(item.errorPath[0].line, 11);
QCOMPARE(item.errorId, QString("unreadVariable"));
QCOMPARE(GuiSeverity::toString(item.severity), QString("style"));
QCOMPARE(item.summary, QString("Variable 'a' is assigned a value that is never used"));
QCOMPARE(item.message, QString("Variable 'a' is assigned a value that is never used"));
const ErrorItem &item2 = errors[3];
QCOMPARE(item2.errorPath.size(), 2);
QCOMPARE(item2.errorPath[0].file, QString("test.cxx"));
QCOMPARE(item2.errorPath[0].line, 16);
QCOMPARE(item2.errorPath[1].file, QString("test.cxx"));
QCOMPARE(item2.errorPath[1].line, 32);
QCOMPARE(item2.errorId, QString("mismatchAllocDealloc"));
QCOMPARE(GuiSeverity::toString(item2.severity), QString("error"));
QCOMPARE(item2.summary, QString("Mismatching allocation and deallocation: k"));
QCOMPARE(item2.message, QString("Mismatching allocation and deallocation: k"));
}
QTEST_MAIN(TestXmlReportV2)
| null |
767 | cpp | cppcheck | testxmlreportv2.h | gui/test/xmlreportv2/testxmlreportv2.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2021 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <QObject>
class TestXmlReportV2 : public QObject {
Q_OBJECT
private slots:
void readXml() const;
};
| null |
768 | cpp | cppcheck | mainwindow.h | tools/triage/mainwindow.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2021 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QFileSystemModel>
#include <QMainWindow>
#include <QObject>
#include <QRegularExpression>
#include <QString>
#include <QStringList>
class QListWidgetItem;
class QTextStream;
class QPoint;
class QWidget;
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow {
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
MainWindow(const MainWindow &) = delete;
MainWindow &operator=(const MainWindow &) = delete;
~MainWindow() override;
public slots:
void loadFile();
void loadFromClipboard();
void filter(const QString& filter);
void showResult(QListWidgetItem *item);
void refreshResults();
void fileTreeFilter(const QString &str);
void findInFilesClicked();
void directorytreeDoubleClick();
void searchResultsDoubleClick();
void resultsContextMenu(const QPoint& pos);
private:
Ui::MainWindow *ui;
void load(QTextStream &textStream);
bool runProcess(const QString &programName, const QStringList & arguments);
bool wget(const QString &url);
bool unpackArchive(const QString &archiveName);
void showSrcFile(const QString &fileName, const QString &url, int lineNumber);
QStringList mAllErrors;
QFileSystemModel mFSmodel;
const QRegularExpression mVersionRe;
const QStringList hFiles;
const QStringList srcFiles;
};
#endif // MAINWINDOW_H
| null |
769 | cpp | cppcheck | mainwindow.cpp | tools/triage/mainwindow.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2021 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mainwindow.h"
#include "codeeditor.h"
#include "ui_mainwindow.h"
#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <random>
#include <QAction>
#include <QApplication>
#include <QByteArray>
#include <QCheckBox>
#include <QClipboard>
#include <QComboBox>
#include <QCoreApplication>
#include <QDir>
#include <QDirIterator>
#include <QFile>
#include <QFileDialog>
#include <QFileInfo>
#include <QFlags>
#include <QHeaderView>
#include <QIODevice>
#include <QLineEdit>
#include <QList>
#include <QListWidget>
#include <QListWidgetItem>
#include <QMenu>
#include <QMimeDatabase>
#include <QMimeType>
#include <QProcess>
#include <QProgressDialog>
#include <QRegularExpression>
#include <QStatusBar>
#include <QStringLiteral>
#include <QTabWidget>
#include <QTextStream>
#include <QTreeView>
#include <QtCore>
class QWidget;
static const QString WORK_FOLDER(QDir::homePath() + "/triage");
static const QString DACA2_PACKAGES(QDir::homePath() + "/daca2-packages");
static constexpr int MAX_ERRORS = 100;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
mVersionRe("^(master|main|your|head|[12].[0-9][0-9]?) (.*)$"),
hFiles{"*.hpp", "*.h", "*.hxx", "*.hh", "*.tpp", "*.txx", "*.ipp", "*.ixx"},
srcFiles{"*.cpp", "*.cxx", "*.cc", "*.c++", "*.C", "*.c", "*.cl"}
{
ui->setupUi(this);
std::srand(static_cast<unsigned int>(std::time(nullptr)));
QDir workFolder(WORK_FOLDER);
if (!workFolder.exists()) {
workFolder.mkdir(WORK_FOLDER);
}
ui->results->setContextMenuPolicy(Qt::CustomContextMenu);
connect(ui->results, &QListWidget::customContextMenuRequested,
this, &MainWindow::resultsContextMenu);
mFSmodel.setRootPath(WORK_FOLDER);
mFSmodel.setReadOnly(true);
mFSmodel.setFilter(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);
ui->directoryTree->setModel(&mFSmodel);
QHeaderView * header = ui->directoryTree->header();
for (int i = 1; i < header->length(); ++i) // hide all except [0]
header->hideSection(i);
ui->directoryTree->setRootIndex(mFSmodel.index(WORK_FOLDER));
ui->hFilesFilter->setToolTip(hFiles.join(','));
ui->srcFilesFilter->setToolTip(srcFiles.join(','));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::loadFile()
{
ui->statusBar->clearMessage();
const QString fileName = QFileDialog::getOpenFileName(this, tr("daca results file"), WORK_FOLDER, tr("Text files (*.txt *.log);;All (*.*)"));
if (fileName.isEmpty())
return;
QFile file(fileName);
file.open(QIODevice::ReadOnly | QIODevice::Text);
QTextStream textStream(&file);
load(textStream);
}
void MainWindow::loadFromClipboard()
{
ui->statusBar->clearMessage();
QString clipboardContent = QApplication::clipboard()->text();
QTextStream textStream(&clipboardContent);
load(textStream);
}
void MainWindow::load(QTextStream &textStream)
{
bool local = false;
QString url;
QString errorMessage;
QStringList versions;
mAllErrors.clear();
while (true) {
QString line = textStream.readLine();
if (line.isNull())
break;
if (line.startsWith("ftp://") || (line.startsWith(DACA2_PACKAGES) && line.endsWith(".tar.xz"))) {
local = line.startsWith(DACA2_PACKAGES) && line.endsWith(".tar.xz");
url = line;
if (!errorMessage.isEmpty())
mAllErrors << errorMessage;
errorMessage.clear();
} else if (!url.isEmpty()) {
static const QRegularExpression severityRe("^.*: (error|warning|style|note):.*$");
if (!severityRe.match(line).hasMatch())
continue;
if (!local) {
const QRegularExpressionMatch matchRes = mVersionRe.match(line);
if (matchRes.hasMatch()) {
const QString version = matchRes.captured(1);
if (versions.indexOf(version) < 0)
versions << version;
}
}
if (line.indexOf(": note:") > 0)
errorMessage += '\n' + line;
else if (errorMessage.isEmpty()) {
errorMessage = url + '\n' + line;
} else {
mAllErrors << errorMessage;
errorMessage = url + '\n' + line;
}
}
}
if (!errorMessage.isEmpty())
mAllErrors << errorMessage;
ui->version->clear();
if (versions.size() > 1)
ui->version->addItem("");
ui->version->addItems(versions);
filter("");
}
void MainWindow::refreshResults()
{
filter(ui->version->currentText());
}
void MainWindow::filter(const QString& filter)
{
QStringList allErrors;
for (const QString &errorItem : mAllErrors) {
if (filter.isEmpty()) {
allErrors << errorItem;
continue;
}
const QStringList lines = errorItem.split("\n");
if (lines.size() < 2)
continue;
if (lines[1].startsWith(filter))
allErrors << errorItem;
}
ui->results->clear();
if (ui->random100->isChecked() && allErrors.size() > MAX_ERRORS) {
// remove items in /test/
for (int i = allErrors.size() - 1; i >= 0 && allErrors.size() > MAX_ERRORS; --i) {
if (allErrors[i].indexOf("test") > 0)
allErrors.removeAt(i);
}
std::shuffle(allErrors.begin(), allErrors.end(), std::mt19937(std::random_device()()));
ui->results->addItems(allErrors.mid(0, MAX_ERRORS));
ui->results->sortItems();
} else {
ui->results->addItems(allErrors);
}
}
bool MainWindow::runProcess(const QString &programName, const QStringList &arguments)
{
QProgressDialog dialog("Running external process: " + programName, "Kill", 0 /*min*/, 1 /*max*/, this);
dialog.setWindowModality(Qt::WindowModal);
dialog.setMinimumDuration(0 /*msec*/);
dialog.setValue(0);
QProcess process;
process.setWorkingDirectory(WORK_FOLDER);
process.start(programName, arguments); // async action
bool success = false;
bool state = (QProcess::Running == process.state() || QProcess::Starting == process.state());
while (!success && state) {
success = process.waitForFinished(50 /*msec*/);
// Not the best way to keep UI unfreeze, keep work async in other thread much more a Qt style
QCoreApplication::processEvents();
if (dialog.wasCanceled()) {
process.kill();
success = false;
break;
}
state = (QProcess::Running == process.state() || QProcess::Starting == process.state());
}
dialog.setValue(1);
if (!success) {
QString errorstr(programName);
errorstr.append(": ");
errorstr.append(process.errorString());
ui->statusBar->showMessage(errorstr);
} else {
const int exitCode = process.exitCode();
if (exitCode != 0) {
success = false;
const QByteArray stderrOutput = process.readAllStandardError();
QString errorstr(programName);
errorstr.append(QString(": exited with %1: ").arg(exitCode));
errorstr.append(stderrOutput);
ui->statusBar->showMessage(errorstr);
}
}
return success;
}
bool MainWindow::wget(const QString &url)
{
return runProcess("wget", QStringList{url});
}
bool MainWindow::unpackArchive(const QString &archiveName)
{
// Unpack archive
QStringList args;
#ifdef Q_OS_WIN
/* On Windows --force-local is necessary because tar wants to connect to a remote system
* when a colon is found in the archiveName. So "C:/Users/blah/triage/package" would not work
* without it. */
args << "--force-local";
#endif
if (archiveName.endsWith(".tar.gz"))
args << "-xzvf";
else if (archiveName.endsWith(".tar.bz2"))
args << "-xjvf";
else if (archiveName.endsWith(".tar.xz"))
args << "-xJvf";
else {
// Try to automatically find an (un)compressor for this archive
args << "-xavf";
}
args << archiveName;
return runProcess("tar", args);
}
void MainWindow::showResult(QListWidgetItem *item)
{
ui->statusBar->clearMessage();
const bool local = item->text().startsWith(DACA2_PACKAGES);
if (!item->text().startsWith("ftp://") && !local)
return;
const QStringList lines = item->text().split("\n");
if (lines.size() < 2)
return;
const QString &url = lines[0];
QString msg = lines[1];
if (!local) {
const QRegularExpressionMatch matchRes = mVersionRe.match(msg);
if (matchRes.hasMatch())
msg = matchRes.captured(2);
}
const QString archiveName = url.mid(url.lastIndexOf("/") + 1);
const int pos1 = msg.indexOf(":");
const int pos2 = msg.indexOf(":", pos1+1);
const QString fileName = WORK_FOLDER + '/' + msg.left(msg.indexOf(":"));
const int lineNumber = msg.mid(pos1+1, pos2-pos1-1).toInt();
if (!QFileInfo::exists(fileName)) {
const QString daca2archiveFile {DACA2_PACKAGES + '/' + archiveName.mid(0,archiveName.indexOf(".tar.")) + ".tar.xz"};
if (QFileInfo::exists(daca2archiveFile)) {
if (!unpackArchive(daca2archiveFile))
return;
} else if (!local) {
const QString archiveFullPath {WORK_FOLDER + '/' + archiveName};
if (!QFileInfo::exists(archiveFullPath)) {
// Download archive
if (!wget(url))
return;
}
if (!unpackArchive(archiveFullPath))
return;
}
}
showSrcFile(fileName, url, lineNumber);
}
void MainWindow::showSrcFile(const QString &fileName, const QString &url, const int lineNumber)
{
// Open file
ui->code->setFocus();
QFile f(fileName);
if (!f.open(QIODevice::ReadOnly | QIODevice::Text)) {
const QString errorMsg =
QString("Opening file %1 failed: %2").arg(f.fileName(), f.errorString());
ui->statusBar->showMessage(errorMsg);
} else {
QTextStream textStream(&f);
const QString fileData = textStream.readAll();
ui->code->setError(fileData, lineNumber, QStringList());
f.close();
ui->urlEdit->setText(url);
ui->fileEdit->setText(fileName);
ui->directoryTree->setCurrentIndex(mFSmodel.index(fileName));
}
}
void MainWindow::fileTreeFilter(const QString &str)
{
mFSmodel.setNameFilters(QStringList{"*" + str + "*"});
mFSmodel.setNameFilterDisables(false);
}
void MainWindow::findInFilesClicked()
{
ui->tabWidget->setCurrentIndex(1);
ui->inFilesResult->clear();
const QString text = ui->filterEdit->text();
// cppcheck-suppress shadowFunction - TODO: fix this
QStringList filter;
if (ui->hFilesFilter->isChecked())
filter.append(hFiles);
if (ui->srcFilesFilter->isChecked())
filter.append(srcFiles);
QMimeDatabase mimeDatabase;
QDirIterator it(WORK_FOLDER, filter, QDir::AllEntries | QDir::NoSymLinks | QDir::NoDotAndDotDot, QDirIterator::Subdirectories);
const auto common_path_len = WORK_FOLDER.length() + 1; // let's remove common part of path improve UI
while (it.hasNext()) {
const QString fileName = it.next();
const QMimeType mimeType = mimeDatabase.mimeTypeForFile(fileName);
if (mimeType.isValid() && !mimeType.inherits(QStringLiteral("text/plain"))) {
continue;
}
QFile file(fileName);
if (file.open(QIODevice::ReadOnly)) {
int lineN = 0;
QTextStream in(&file);
while (!in.atEnd()) {
++lineN;
QString line = in.readLine();
if (line.contains(text, Qt::CaseInsensitive)) {
ui->inFilesResult->addItem(fileName.mid(common_path_len) + QString{":"} + QString::number(lineN));
}
}
}
}
}
void MainWindow::directorytreeDoubleClick()
{
showSrcFile(mFSmodel.filePath(ui->directoryTree->currentIndex()), "", 1);
}
void MainWindow::searchResultsDoubleClick()
{
QString filename = ui->inFilesResult->currentItem()->text();
const auto idx = filename.lastIndexOf(':');
const int line = filename.mid(idx + 1).toInt();
showSrcFile(WORK_FOLDER + QString{"/"} + filename.left(idx), "", line);
}
void MainWindow::resultsContextMenu(const QPoint& pos)
{
if (ui->results->selectedItems().isEmpty())
return;
QMenu submenu;
submenu.addAction("Copy");
const QAction* menuItem = submenu.exec(ui->results->mapToGlobal(pos));
if (menuItem && menuItem->text().contains("Copy"))
{
QString text;
for (const auto *res: ui->results->selectedItems())
text += res->text() + "\n";
QApplication::clipboard()->setText(text);
}
}
| null |
770 | cpp | cppcheck | main.cpp | tools/triage/main.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2021 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return QApplication::exec();
}
| null |
771 | cpp | cppcheck | dmake.cpp | tools/dmake/dmake.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2023 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// Generate Makefile for cppcheck
#include <algorithm>
#include <array>
#include <cstdint>
#include <cstdlib>
#include <fstream>
#include <functional>
#include <iostream>
#include <list>
#include <map>
#include <set>
#include <string>
#include <vector>
#include "config.h"
#include "../cli/filelister.h"
#include "../lib/filesettings.h"
#include "../lib/pathmatch.h"
#include "../lib/utils.h"
static std::string builddir(std::string filename)
{
if (startsWith(filename,"lib/"))
filename = "$(libcppdir)" + filename.substr(3);
else if (startsWith(filename, "../lib/")) // oss-fuzz
filename = "$(libcppdir)" + filename.substr(6);
return filename;
}
static std::string objfile(std::string cppfile)
{
cppfile.erase(cppfile.rfind('.'));
if (startsWith(cppfile, "../externals/simplecpp/")) // oss-fuzz
cppfile = cppfile.substr(23);
else if (startsWith(cppfile, "../externals/tinyxml2/")) // oss-fuzz
cppfile = cppfile.substr(22);
return builddir(cppfile + ".o");
}
static std::string objfiles(const std::vector<std::string> &files)
{
std::string allObjfiles;
for (const std::string &file : files) {
if (file != files.front())
allObjfiles += std::string(14, ' ');
allObjfiles += objfile(file);
if (file != files.back())
allObjfiles += " \\\n";
}
return allObjfiles;
}
static void getDeps(std::string filename, std::vector<std::string> &depfiles)
{
static const std::array<std::string, 3> externalfolders{"externals/picojson", "externals/simplecpp", "externals/tinyxml2"};
static const std::array<std::string, 3> externalfolders_rel{"../externals/picojson", "../externals/simplecpp", "../externals/tinyxml2"};
// Is the dependency already included?
if (std::find(depfiles.cbegin(), depfiles.cend(), filename) != depfiles.cend())
return;
const bool relative = startsWith(filename, "../"); // oss-fuzz
if (relative)
filename = filename.substr(3);
std::ifstream f(filename.c_str());
if (!f.is_open()) {
/*
* Recursively search for includes in other directories.
* Files are searched according to the following priority:
* [test, tools] -> cli -> lib -> externals
*/
if (startsWith(filename, "cli/"))
getDeps("lib" + filename.substr(filename.find('/')), depfiles);
else if (startsWith(filename, "test/"))
getDeps("cli" + filename.substr(filename.find('/')), depfiles);
else if (startsWith(filename, "tools"))
getDeps("cli" + filename.substr(filename.find('/')), depfiles);
else if (startsWith(filename, "lib/")) {
const auto& extfolders = relative ? externalfolders_rel : externalfolders;
for (const std::string & external : extfolders)
getDeps(external + filename.substr(filename.find('/')), depfiles);
}
return;
}
if (filename.find(".c") == std::string::npos)
{
if (relative)
depfiles.push_back("../" + filename);
else
depfiles.push_back(filename);
}
std::string path(filename);
if (path.find('/') != std::string::npos)
path.erase(1 + path.rfind('/'));
std::string line;
while (std::getline(f, line)) {
std::string::size_type pos1 = line.find("#include \"");
char rightBracket = '\"';
if (pos1 == std::string::npos) {
pos1 = line.find("#include <");
rightBracket = '>';
if (pos1 == std::string::npos)
continue;
}
pos1 += 10;
const std::string::size_type pos2 = line.find(rightBracket, pos1);
std::string hfile(path);
hfile += line.substr(pos1, pos2 - pos1);
const std::string::size_type traverse_pos = hfile.find("/../");
if (traverse_pos != std::string::npos) // TODO: Ugly fix
hfile.erase(0, 4 + traverse_pos);
// no need to look up extension-less headers
if (!endsWith(hfile, ".h"))
continue;
if (relative)
hfile = "../" + hfile;
getDeps(hfile, depfiles);
}
}
static void compilefiles(std::ostream &fout, const std::vector<std::string> &files, const std::string &args)
{
for (const std::string &file : files) {
const bool external(startsWith(file,"externals/") || startsWith(file,"../externals/"));
fout << objfile(file) << ": " << file;
std::vector<std::string> depfiles;
getDeps(file, depfiles);
std::sort(depfiles.begin(), depfiles.end());
for (const std::string &depfile : depfiles)
fout << " " << depfile;
fout << "\n\t$(CXX) " << args << " $(CPPFLAGS) $(CXXFLAGS)" << (external?" -w":"") << " -c -o $@ " << builddir(file) << "\n\n";
}
}
static std::string getCppFiles(std::vector<std::string> &files, const std::string &path, bool recursive)
{
std::list<FileWithDetails> filelist;
const std::set<std::string> extra;
const std::vector<std::string> masks;
const PathMatch matcher(masks);
std::string err = FileLister::addFiles(filelist, path, extra, recursive, matcher);
if (!err.empty())
return err;
// add *.cpp files to the "files" vector..
for (const auto& file : filelist) {
if (endsWith(file.path(), ".cpp"))
files.push_back(file.path());
}
return "";
}
static void makeConditionalVariable(std::ostream &os, const std::string &variable, const std::string &defaultValue)
{
os << "ifndef " << variable << '\n'
<< " " << variable << '=' << defaultValue << '\n'
<< "endif\n"
<< "\n";
}
static int write_vcxproj(const std::string &proj_name, const std::function<void(std::string&)> &source_f, const std::function<void(std::string&)> &header_f)
{
std::string outstr;
{
// treat as binary to prevent implicit line ending conversions
std::ifstream in(proj_name, std::ios::binary);
if (!in.is_open()) {
std::cerr << "Could not open " << proj_name << std::endl;
return EXIT_FAILURE;
}
std::string line;
bool in_itemgroup = false;
while (std::getline(in, line)) {
if (in_itemgroup) {
if (line.find("</ItemGroup>") == std::string::npos)
continue;
in_itemgroup = false;
}
// strip all remaining line endings
const std::string::size_type pos = line.find_last_not_of("\r\n");
if (pos != std::string::npos)
line.resize(pos+1, '\0');
outstr += line;
outstr += "\r\n";
if (line.find("<ItemGroup Label=\"SourceFiles\">") != std::string::npos) {
in_itemgroup = true;
source_f(outstr);
}
if (line.find("<ItemGroup Label=\"HeaderFiles\">") != std::string::npos) {
in_itemgroup = true;
header_f(outstr);
}
}
}
// strip trailing \r\n
{
const std::string::size_type pos = outstr.find_last_not_of("\r\n");
if (pos != std::string::npos)
outstr.resize(pos+1, '\0');
}
// treat as binary to prevent implicit line ending conversions
std::ofstream out(proj_name, std::ios::binary|std::ios::trunc);
out << outstr;
return EXIT_SUCCESS;
}
enum ClType : std::uint8_t { Compile, Include, Precompile };
static std::string make_vcxproj_cl_entry(const std::string& file, ClType type)
{
std::string outstr;
if (type == Precompile) {
outstr += R"( <ClCompile Include=")";
outstr += file;
outstr += R"(">)";
outstr += "\r\n";
outstr += R"( <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Create</PrecompiledHeader>)";
outstr += "\r\n";
outstr += R"( <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Create</PrecompiledHeader>)";
outstr += "\r\n";
outstr += R"( <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release-PCRE|x64'">Create</PrecompiledHeader>)";
outstr += "\r\n";
outstr += R"( <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug-PCRE|x64'">Create</PrecompiledHeader>)";
outstr += "\r\n";
outstr += " </ClCompile>\r\n";
return outstr;
}
outstr += " <";
outstr += (type == Compile) ? "ClCompile" : "ClInclude";
outstr += R"( Include=")";
outstr += file;
outstr += R"(" />)";
outstr += "\r\n";
return outstr;
}
static std::vector<std::string> prioritizelib(const std::vector<std::string>& libfiles)
{
std::map<std::string, std::size_t> priorities;
std::size_t prio = libfiles.size();
for (const auto &l : libfiles) {
priorities.emplace(l, prio--);
}
priorities["lib/valueflow.cpp"] = 1000;
priorities["lib/tokenize.cpp"] = 900;
priorities["lib/symboldatabase.cpp"] = 800;
std::vector<std::string> libfiles_prio = libfiles;
std::sort(libfiles_prio.begin(), libfiles_prio.end(), [&](const std::string &l1, const std::string &l2) {
const auto p1 = priorities.find(l1);
const auto p2 = priorities.find(l2);
return (p1 != priorities.end() ? p1->second : 0) > (p2 != priorities.end() ? p2->second : 0);
});
return libfiles_prio;
}
static void makeMatchcompiler(std::ostream& fout, const std::string& toolsPrefix, std::string args)
{
if (!args.empty())
args = " " + args;
// avoid undefined variable
fout << "ifndef MATCHCOMPILER\n"
<< " MATCHCOMPILER=\n"
<< "endif\n";
// TODO: bail out when matchcompiler.py fails (i.e. invalid PYTHON_INTERPRETER specified)
// TODO: handle "PYTHON_INTERPRETER="
// use match compiler..
fout << "# use match compiler\n";
fout << "ifeq ($(MATCHCOMPILER),yes)\n"
<< " # Find available Python interpreter\n"
<< " ifeq ($(PYTHON_INTERPRETER),)\n"
<< " PYTHON_INTERPRETER := $(shell which python3)\n"
<< " endif\n"
<< " ifeq ($(PYTHON_INTERPRETER),)\n"
<< " PYTHON_INTERPRETER := $(shell which python)\n"
<< " endif\n"
<< " ifeq ($(PYTHON_INTERPRETER),)\n"
<< " $(error Did not find a Python interpreter)\n"
<< " endif\n"
<< " ifdef VERIFY\n"
<< " matchcompiler_S := $(shell $(PYTHON_INTERPRETER) " << toolsPrefix << "tools/matchcompiler.py" << args << " --verify)\n"
<< " else\n"
<< " matchcompiler_S := $(shell $(PYTHON_INTERPRETER) " << toolsPrefix << "tools/matchcompiler.py" << args << ")\n"
<< " endif\n"
<< " libcppdir:=build\n"
<< "else ifeq ($(MATCHCOMPILER),)\n"
<< " libcppdir:=lib\n"
<< "else\n"
<< " $(error invalid MATCHCOMPILER value '$(MATCHCOMPILER)')\n"
<< "endif\n\n";
}
static void write_ossfuzz_makefile(std::vector<std::string> libfiles_prio, std::vector<std::string> extfiles)
{
for (auto& l : libfiles_prio)
{
l = "../" + l;
}
for (auto& e : extfiles)
{
e = "../" + e;
}
std::ofstream fout("oss-fuzz/Makefile");
fout << "# This file is generated by dmake, do not edit.\n";
fout << '\n';
fout << "# make CXX=clang++ MATCHCOMPILER=yes CXXFLAGS=\"-O1 -fno-omit-frame-pointer -gline-tables-only -DFUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION -fsanitize=address -fsanitize-address-use-after-scope -DHAVE_BOOST\" LIB_FUZZING_ENGINE=\"-fsanitize=fuzzer\" oss-fuzz-client\n";
fout << '\n';
fout << "MATCHCOMPILER=yes\n"; // always need to enable the matchcompiler so the library files are being copied
makeMatchcompiler(fout, "../", "--read-dir ../lib");
fout << "INCS=-I../lib -isystem../externals/simplecpp -isystem../externals/tinyxml2 -isystem../externals/picojson\n";
fout << "CPPFLAGS=-std=c++11 -g -w $(INCS)\n";
fout << '\n';
fout << "LIBOBJ = " << objfiles(libfiles_prio) << "\n";
fout << '\n';
fout << "EXTOBJ = " << objfiles(extfiles) << "\n";
fout << '\n';
fout << "oss-fuzz-client: $(EXTOBJ) $(LIBOBJ) main.o type2.o\n";
fout << "\t${CXX} $(CPPFLAGS) ${CXXFLAGS} -o $@ $^ ${LIB_FUZZING_ENGINE}\n";
fout << '\n';
fout << "no-fuzz: $(EXTOBJ) $(LIBOBJ) main_nofuzz.o type2.o\n";
fout << "\t${CXX} $(CPPFLAGS) ${CXXFLAGS} -o $@ $^\n";
fout << '\n';
fout << "translate: translate.o type2.o\n";
fout << "\t${CXX} -std=c++11 -g ${CXXFLAGS} -o $@ type2.cpp translate.cpp\n";
fout << '\n';
fout << "clean:\n";
fout << "\trm -f *.o build/*.o oss-fuzz-client no-fuzz translate\n";
fout << '\n';
fout << "preprare-samples:\n";
fout << "\trm -rf samples\n";
fout << "\tmkdir -p samples\n";
fout << "\tcp -R ../samples .\n";
fout << "\tfind ./samples -type f -name '*.txt' -exec rm -vf {} \\;\n";
fout << '\n';
fout << "do-fuzz: oss-fuzz-client preprare-samples\n";
fout << "\tmkdir -p corpus\n";
fout << "\t./oss-fuzz-client -only_ascii=1 -timeout=5 -detect_leaks=0 corpus samples ../test/cli/fuzz-crash ../test/cli/fuzz-crash_c ../test/cli/fuzz-timeout\n";
fout << '\n';
fout << "dedup-corpus: oss-fuzz-client preprare-samples\n";
fout << "\tmv corpus corpus_\n";
fout << "\tmkdir -p corpus\n";
fout << "\t./oss-fuzz-client -only_ascii=1 -timeout=5 -detect_leaks=0 corpus corpus_ samples ../test/cli/fuzz-crash ../test/cli/fuzz-crash_c ../test/cli/fuzz-timeout -merge=1\n";
fout << '\n';
fout << "# jobs:\n";
fout << "# ./oss-fuzz-client -only_ascii=1 -timeout=5 -detect_leaks=0 corpus samples ../test/cli/fuzz-crash ../test/cli/fuzz-crash_c ../test/cli/fuzz-timeout -workers=12 -jobs=9\n";
fout << '\n';
fout << "# minimize:\n";
fout << "# ./oss-fuzz-client -only_ascii=1 -timeout=5 -detect_leaks=0 -minimize_crash=1 crash-0123456789abcdef\n";
fout << '\n';
compilefiles(fout, extfiles, "${LIB_FUZZING_ENGINE}");
compilefiles(fout, libfiles_prio, "${LIB_FUZZING_ENGINE}");
fout << '\n';
fout << "type2.o: type2.cpp type2.h\n";
fout << "\t$(CXX) ${LIB_FUZZING_ENGINE} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ type2.cpp\n";
fout << '\n';
fout << "translate.o: translate.cpp type2.h\n";
fout << "\t$(CXX) ${LIB_FUZZING_ENGINE} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ translate.cpp\n";
fout << '\n';
fout << "main.o: main.cpp type2.h\n";
fout << "\t$(CXX) ${LIB_FUZZING_ENGINE} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ main.cpp\n";
fout << '\n';
fout << "main_nofuzz.o: main.cpp type2.h\n";
fout << "\t$(CXX) ${LIB_FUZZING_ENGINE} $(CPPFLAGS) $(CXXFLAGS) -DNO_FUZZ -c -o $@ main.cpp\n";
}
int main(int argc, char **argv)
{
const bool release(argc >= 2 && std::string(argv[1]) == "--release");
// Get files..
std::vector<std::string> libfiles;
std::string err = getCppFiles(libfiles, "lib/", false);
if (!err.empty()) {
std::cerr << err << std::endl;
return EXIT_FAILURE;
}
const std::vector<std::string> libfiles_prio = prioritizelib(libfiles);
std::vector<std::string> extfiles;
err = getCppFiles(extfiles, "externals/", true);
if (!err.empty()) {
std::cerr << err << std::endl;
return EXIT_FAILURE;
}
std::vector<std::string> clifiles;
err = getCppFiles(clifiles, "cli/", false);
if (!err.empty()) {
std::cerr << err << std::endl;
return EXIT_FAILURE;
}
std::vector<std::string> testfiles;
err = getCppFiles(testfiles, "test/", false);
if (!err.empty()) {
std::cerr << err << std::endl;
return EXIT_FAILURE;
}
std::vector<std::string> toolsfiles;
err = getCppFiles(toolsfiles, "tools/dmake/", false);
if (!err.empty()) {
std::cerr << err << std::endl;
return EXIT_FAILURE;
}
if (libfiles.empty() && clifiles.empty() && testfiles.empty()) {
std::cerr << "No files found. Are you in the correct directory?" << std::endl;
return EXIT_FAILURE;
}
// TODO: add files without source via parsing
std::vector<std::string> libfiles_h;
for (const std::string &libfile : libfiles) {
std::string fname(libfile.substr(4));
fname.erase(fname.find(".cpp"));
libfiles_h.emplace_back(fname + ".h");
}
libfiles_h.emplace_back("analyzer.h");
libfiles_h.emplace_back("calculate.h");
libfiles_h.emplace_back("config.h");
libfiles_h.emplace_back("filesettings.h");
libfiles_h.emplace_back("findtoken.h");
libfiles_h.emplace_back("json.h");
libfiles_h.emplace_back("matchcompiler.h");
libfiles_h.emplace_back("precompiled.h");
libfiles_h.emplace_back("smallvector.h");
libfiles_h.emplace_back("sourcelocation.h");
libfiles_h.emplace_back("tokenrange.h");
libfiles_h.emplace_back("valueptr.h");
libfiles_h.emplace_back("version.h");
libfiles_h.emplace_back("vf_analyze.h");
libfiles_h.emplace_back("xml.h");
std::sort(libfiles_h.begin(), libfiles_h.end());
std::vector<std::string> clifiles_h;
for (const std::string &clifile : clifiles) {
std::string fname(clifile.substr(4));
if (fname == "main.cpp")
continue;
fname.erase(fname.find(".cpp"));
clifiles_h.emplace_back(fname + ".h");
}
std::vector<std::string> testfiles_h;
testfiles_h.emplace_back("fixture.h");
testfiles_h.emplace_back("helpers.h");
testfiles_h.emplace_back("options.h");
testfiles_h.emplace_back("precompiled.h");
testfiles_h.emplace_back("redirect.h");
std::sort(testfiles_h.begin(), testfiles_h.end());
// TODO: write filter files
// Visual Studio projects
write_vcxproj("cli/cli.vcxproj", [&](std::string &outstr){
for (const std::string &clifile: clifiles) {
const std::string c = clifile.substr(4);
outstr += make_vcxproj_cl_entry(c, c == "executor.cpp" ? Precompile : Compile);
}
}, [&](std::string &outstr){
for (const std::string &clifile_h: clifiles_h) {
outstr += make_vcxproj_cl_entry(clifile_h, Include);
}
});
write_vcxproj("lib/cppcheck.vcxproj", [&](std::string &outstr){
outstr += make_vcxproj_cl_entry(R"(..\externals\simplecpp\simplecpp.cpp)", Compile);
outstr += make_vcxproj_cl_entry(R"(..\externals\tinyxml2\tinyxml2.cpp)", Compile);
for (const std::string &libfile: libfiles_prio) {
const std::string l = libfile.substr(4);
outstr += make_vcxproj_cl_entry(l, l == "check.cpp" ? Precompile : Compile);
}
}, [&](std::string &outstr){
outstr += make_vcxproj_cl_entry(R"(..\externals\simplecpp\simplecpp.h)", Include);
outstr += make_vcxproj_cl_entry(R"(..\externals\tinyxml2\tinyxml2.h)", Include);
for (const std::string &libfile_h: libfiles_h) {
outstr += make_vcxproj_cl_entry(libfile_h, Include);
}
});
write_vcxproj("test/testrunner.vcxproj", [&](std::string &outstr){
for (const std::string &clifile: clifiles) {
if (clifile == "cli/main.cpp")
continue;
const std::string c = R"(..\cli\)" + clifile.substr(4);
outstr += make_vcxproj_cl_entry(c, Compile);
}
for (const std::string &testfile: testfiles) {
const std::string t = testfile.substr(5);
outstr += make_vcxproj_cl_entry(t, t == "fixture.cpp" ? Precompile : Compile);
}
}, [&](std::string &outstr){
for (const std::string &clifile_h: clifiles_h) {
const std::string c = R"(..\cli\)" + clifile_h;
outstr += make_vcxproj_cl_entry(c, Include);
}
for (const std::string &testfile_h: testfiles_h) {
outstr += make_vcxproj_cl_entry(testfile_h, Include);
}
});
static constexpr char makefile[] = "Makefile";
std::ofstream fout(makefile, std::ios_base::trunc);
if (!fout.is_open()) {
std::cerr << "An error occurred while trying to open "
<< makefile
<< ".\n";
return EXIT_FAILURE;
}
fout << "# This file is generated by dmake, do not edit.\n\n";
fout << "ifndef VERBOSE\n"
<< " VERBOSE=\n"
<< "endif\n";
fout << "# To compile with rules, use 'make HAVE_RULES=yes'\n";
makeConditionalVariable(fout, "HAVE_RULES", "");
makeMatchcompiler(fout, emptyString, emptyString);
// avoid undefined variable
fout << "ifndef CPPFLAGS\n"
<< " CPPFLAGS=\n"
<< "endif\n\n";
// explicit files dir..
fout << "ifdef FILESDIR\n"
<< " override CPPFLAGS+=-DFILESDIR=\\\"$(FILESDIR)\\\"\n"
<< "endif\n\n";
// enable backtrac
fout << "RDYNAMIC=-rdynamic\n";
// The _GLIBCXX_DEBUG doesn't work in cygwin or other Win32 systems.
fout << "# Set the CPPCHK_GLIBCXX_DEBUG flag. This flag is not used in release Makefiles.\n"
<< "# The _GLIBCXX_DEBUG define doesn't work in Cygwin or other Win32 systems.\n"
<< "ifndef COMSPEC\n"
<< " ifeq ($(VERBOSE),1)\n"
<< " $(info COMSPEC not found)\n"
<< " endif\n"
<< " ifdef ComSpec\n"
<< " ifeq ($(VERBOSE),1)\n"
<< " $(info ComSpec found)\n"
<< " endif\n"
<< " #### ComSpec is defined on some WIN32's.\n"
<< " WINNT=1\n"
<< "\n"
<< " ifeq ($(VERBOSE),1)\n"
<< " $(info PATH=$(PATH))\n"
<< " endif\n"
<< "\n"
<< " ifneq (,$(findstring /cygdrive/,$(PATH)))\n"
<< " ifeq ($(VERBOSE),1)\n"
<< " $(info /cygdrive/ found in PATH)\n"
<< " endif\n"
<< " CYGWIN=1\n"
<< " endif # CYGWIN\n"
<< " endif # ComSpec\n"
<< "endif # COMSPEC\n"
<< "\n"
<< "ifdef WINNT\n"
<< " ifeq ($(VERBOSE),1)\n"
<< " $(info WINNT found)\n"
<< " endif\n"
<< " #### Maybe Windows\n"
<< " ifndef CPPCHK_GLIBCXX_DEBUG\n"
<< " CPPCHK_GLIBCXX_DEBUG=\n"
<< " endif # !CPPCHK_GLIBCXX_DEBUG\n"
<< "\n"
<< " ifeq ($(VERBOSE),1)\n"
<< " $(info MSYSTEM=$(MSYSTEM))\n"
<< " endif\n"
<< "\n"
<< " ifneq ($(MSYSTEM),MINGW32 MINGW64)\n"
<< " RDYNAMIC=\n"
<< " endif\n"
<< "\n"
<< " LDFLAGS+=-lshlwapi\n"
<< "else # !WINNT\n"
<< " ifeq ($(VERBOSE),1)\n"
<< " $(info WINNT not found)\n"
<< " endif\n"
<< "\n"
<< " uname_S := $(shell sh -c 'uname -s 2>/dev/null || echo not')\n"
<< "\n"
<< " ifeq ($(VERBOSE),1)\n"
<< " $(info uname_S=$(uname_S))\n"
<< " endif\n"
<< "\n"
<< " ifeq ($(uname_S),Linux)\n"
<< " ifndef CPPCHK_GLIBCXX_DEBUG\n"
<< " CPPCHK_GLIBCXX_DEBUG=-D_GLIBCXX_DEBUG\n"
<< " endif # !CPPCHK_GLIBCXX_DEBUG\n"
<< " endif # Linux\n"
<< "\n"
<< " ifeq ($(uname_S),GNU/kFreeBSD)\n"
<< " ifndef CPPCHK_GLIBCXX_DEBUG\n"
<< " CPPCHK_GLIBCXX_DEBUG=-D_GLIBCXX_DEBUG\n"
<< " endif # !CPPCHK_GLIBCXX_DEBUG\n"
<< " endif # GNU/kFreeBSD\n"
<< "\n"
<< " LDFLAGS+=-pthread\n"
<< "\n"
<< "endif # WINNT\n"
<< "\n";
// tinymxl2 requires __STRICT_ANSI__ to be undefined to compile under CYGWIN.
fout << "ifdef CYGWIN\n"
<< " ifeq ($(VERBOSE),1)\n"
<< " $(info CYGWIN found)\n"
<< " endif\n"
<< "\n"
<< " # Set the flag to address compile time warnings\n"
<< " # with tinyxml2 and Cygwin.\n"
<< " CPPFLAGS+=-U__STRICT_ANSI__\n"
<< " \n"
<< " # Increase stack size for Cygwin builds to avoid segmentation fault in limited recursive tests.\n"
<< " CXXFLAGS+=-Wl,--stack,8388608\n"
<< "endif # CYGWIN\n"
<< "\n";
// skip "-D_GLIBCXX_DEBUG" if clang, since it breaks the build
makeConditionalVariable(fout, "CXX", "g++");
fout << "ifeq (clang++, $(findstring clang++,$(CXX)))\n"
<< " CPPCHK_GLIBCXX_DEBUG=\n"
<< "endif\n";
// Makefile settings..
if (release) {
makeConditionalVariable(fout, "CXXFLAGS", "-std=c++0x -O2 -DNDEBUG -Wall -Wno-sign-compare -Wno-multichar");
} else {
makeConditionalVariable(fout, "CXXFLAGS",
"-pedantic "
"-Wall "
"-Wextra "
"-Wcast-qual "
"-Wfloat-equal "
"-Wmissing-declarations "
"-Wmissing-format-attribute "
"-Wno-long-long "
"-Wpacked "
"-Wredundant-decls "
"-Wundef "
"-Wno-sign-compare "
"-Wno-multichar "
"-Woverloaded-virtual "
"$(CPPCHK_GLIBCXX_DEBUG) "
"-g");
}
fout << "ifeq (g++, $(findstring g++,$(CXX)))\n"
<< " override CXXFLAGS += -std=gnu++0x -pipe\n"
<< "else ifeq (clang++, $(findstring clang++,$(CXX)))\n"
<< " override CXXFLAGS += -std=c++0x\n"
<< "else ifeq ($(CXX), c++)\n"
<< " ifeq ($(shell uname -s), Darwin)\n"
<< " override CXXFLAGS += -std=c++0x\n"
<< " endif\n"
<< "endif\n"
<< "\n";
fout << "ifeq ($(HAVE_RULES),yes)\n"
<< " PCRE_CONFIG = $(shell which pcre-config)\n"
<< " ifeq ($(PCRE_CONFIG),)\n"
<< " $(error Did not find pcre-config)\n"
<< " endif\n"
<< " override CXXFLAGS += -DHAVE_RULES $(shell $(PCRE_CONFIG) --cflags)\n"
<< " ifdef LIBS\n"
<< " LIBS += $(shell $(PCRE_CONFIG) --libs)\n"
<< " else\n"
<< " LIBS=$(shell $(PCRE_CONFIG) --libs)\n"
<< " endif\n"
<< "else ifneq ($(HAVE_RULES),)\n"
<< " $(error invalid HAVE_RULES value '$(HAVE_RULES)')\n"
<< "endif\n\n";
makeConditionalVariable(fout, "PREFIX", "/usr");
makeConditionalVariable(fout, "INCLUDE_FOR_LIB", "-Ilib -isystem externals -isystem externals/picojson -isystem externals/simplecpp -isystem externals/tinyxml2");
makeConditionalVariable(fout, "INCLUDE_FOR_CLI", "-Ilib -isystem externals/picojson -isystem externals/simplecpp -isystem externals/tinyxml2");
makeConditionalVariable(fout, "INCLUDE_FOR_TEST", "-Ilib -Icli -isystem externals/simplecpp -isystem externals/tinyxml2");
fout << "BIN=$(DESTDIR)$(PREFIX)/bin\n\n";
fout << "# For 'make man': sudo apt-get install xsltproc docbook-xsl docbook-xml on Linux\n";
fout << "DB2MAN?=/usr/share/sgml/docbook/stylesheet/xsl/nwalsh/manpages/docbook.xsl\n";
fout << "XP=xsltproc -''-nonet -''-param man.charmap.use.subset \"0\"\n";
fout << "MAN_SOURCE=man/cppcheck.1.xml\n\n";
fout << "\n###### Object Files\n\n";
fout << "LIBOBJ = " << objfiles(libfiles_prio) << "\n\n";
fout << "EXTOBJ = " << objfiles(extfiles) << "\n\n";
fout << "CLIOBJ = " << objfiles(clifiles) << "\n\n";
fout << "TESTOBJ = " << objfiles(testfiles) << "\n\n";
fout << ".PHONY: run-dmake tags\n\n";
fout << "\n###### Targets\n\n";
fout << "cppcheck: $(EXTOBJ) $(LIBOBJ) $(CLIOBJ)\n";
fout << "\t$(CXX) $(CPPFLAGS) $(CXXFLAGS) -o $@ $^ $(LIBS) $(LDFLAGS) $(RDYNAMIC)\n\n";
fout << "all:\tcppcheck testrunner\n\n";
// TODO: generate from clifiles
fout << "testrunner: $(EXTOBJ) $(TESTOBJ) $(LIBOBJ) cli/executor.o cli/processexecutor.o cli/singleexecutor.o cli/threadexecutor.o cli/cmdlineparser.o cli/cppcheckexecutor.o cli/cppcheckexecutorseh.o cli/signalhandler.o cli/stacktrace.o cli/filelister.o\n";
fout << "\t$(CXX) $(CPPFLAGS) $(CXXFLAGS) -o $@ $^ $(LIBS) $(LDFLAGS) $(RDYNAMIC)\n\n";
fout << "test:\tall\n";
fout << "\t./testrunner\n\n";
fout << "check:\tall\n";
fout << "\t./testrunner -q\n\n";
fout << "checkcfg:\tcppcheck validateCFG\n";
fout << "\t./test/cfg/runtests.sh\n\n";
fout << "dmake:\ttools/dmake/dmake.o cli/filelister.o $(libcppdir)/pathmatch.o $(libcppdir)/path.o $(libcppdir)/utils.o externals/simplecpp/simplecpp.o\n";
fout << "\t$(CXX) $(CXXFLAGS) -o $@ $^ $(LDFLAGS)\n\n";
fout << "run-dmake: dmake\n";
fout << "\t./dmake" << (release ? " --release" : "") << "\n\n"; // Make CI in release builds happy
fout << "clean:\n";
fout << "\trm -f build/*.cpp build/*.o lib/*.o cli/*.o test/*.o tools/dmake/*.o externals/*/*.o testrunner dmake cppcheck cppcheck.exe cppcheck.1\n\n";
fout << "man:\tman/cppcheck.1\n\n";
fout << "man/cppcheck.1:\t$(MAN_SOURCE)\n\n";
fout << "\t$(XP) $(DB2MAN) $(MAN_SOURCE)\n\n";
fout << "tags:\n";
fout << "\tctags -R --exclude=doxyoutput --exclude=test/cfg cli externals gui lib test\n\n";
fout << "install: cppcheck\n";
fout << "\tinstall -d ${BIN}\n";
fout << "\tinstall cppcheck ${BIN}\n";
fout << "\tinstall htmlreport/cppcheck-htmlreport ${BIN}\n";
fout << "ifdef FILESDIR\n";
fout << "\tinstall -d ${DESTDIR}${FILESDIR}\n";
fout << "\tinstall -d ${DESTDIR}${FILESDIR}/addons\n";
fout << "\tinstall -m 644 addons/*.json ${DESTDIR}${FILESDIR}/addons\n";
fout << "\tinstall -m 644 addons/*.py ${DESTDIR}${FILESDIR}/addons\n";
fout << "\tinstall -d ${DESTDIR}${FILESDIR}/cfg\n";
fout << "\tinstall -m 644 cfg/*.cfg ${DESTDIR}${FILESDIR}/cfg\n";
fout << "\tinstall -d ${DESTDIR}${FILESDIR}/platforms\n";
fout << "\tinstall -m 644 platforms/*.xml ${DESTDIR}${FILESDIR}/platforms\n";
fout << "else\n";
fout << "\t$(error FILESDIR must be set!)\n";
fout << "endif\n";
fout << "\n";
fout << "uninstall:\n";
fout << "\t@if test -d ${BIN}; then \\\n";
fout << "\t files=\"cppcheck cppcheck-htmlreport\"; \\\n";
fout << "\t echo '(' cd ${BIN} '&&' rm -f $$files ')'; \\\n";
fout << "\t ( cd ${BIN} && rm -f $$files ); \\\n";
fout << "\tfi\n";
fout << "ifdef FILESDIR \n";
fout << "\t@if test -d ${DESTDIR}${FILESDIR}; then \\\n";
fout << "\t echo rm -rf ${DESTDIR}${FILESDIR}; \\\n";
fout << "\t rm -rf ${DESTDIR}${FILESDIR}; \\\n";
fout << "\tfi\n";
fout << "endif\n";
fout << "# Validation of library files:\n";
fout << "ConfigFiles := $(wildcard cfg/*.cfg)\n";
fout << "ConfigFilesCHECKED := $(patsubst %.cfg,%.checked,$(ConfigFiles))\n";
fout << ".PHONY: validateCFG\n";
fout << "%.checked:%.cfg\n";
fout << "\txmllint --noout --relaxng cfg/cppcheck-cfg.rng $<\n";
fout << "validateCFG: ${ConfigFilesCHECKED}\n";
fout << "\txmllint --noout cfg/cppcheck-cfg.rng\n\n";
fout << "# Validation of platforms files:\n";
fout << "PlatformFiles := $(wildcard platforms/*.xml)\n";
fout << "PlatformFilesCHECKED := $(patsubst %.xml,%.checked,$(PlatformFiles))\n";
fout << ".PHONY: validatePlatforms\n";
fout << "%.checked:%.xml\n";
fout << "\txmllint --noout --relaxng platforms/cppcheck-platforms.rng $<\n";
fout << "validatePlatforms: ${PlatformFilesCHECKED}\n";
fout << "\txmllint --noout platforms/cppcheck-platforms.rng\n";
fout << "\n";
fout << "# Validate XML output (to detect regressions)\n";
fout << "/tmp/errorlist.xml: cppcheck\n";
fout << "\t./cppcheck --errorlist >$@\n";
fout << "/tmp/example.xml: cppcheck\n";
fout << "\t./cppcheck --xml --enable=all --inconclusive --max-configs=1 samples 2>/tmp/example.xml\n";
fout << "createXMLExamples:/tmp/errorlist.xml /tmp/example.xml\n";
fout << ".PHONY: validateXML\n";
fout << "validateXML: createXMLExamples\n";
fout << "\txmllint --noout cppcheck-errors.rng\n";
fout << "\txmllint --noout --relaxng cppcheck-errors.rng /tmp/errorlist.xml\n";
fout << "\txmllint --noout --relaxng cppcheck-errors.rng /tmp/example.xml\n";
fout << "\ncheckCWEEntries: /tmp/errorlist.xml\n";
// TODO: handle "PYTHON_INTERPRETER="
fout << "\t$(eval PYTHON_INTERPRETER := $(if $(PYTHON_INTERPRETER),$(PYTHON_INTERPRETER),$(shell which python3)))\n";
fout << "\t$(eval PYTHON_INTERPRETER := $(if $(PYTHON_INTERPRETER),$(PYTHON_INTERPRETER),$(shell which python)))\n";
fout << "\t$(eval PYTHON_INTERPRETER := $(if $(PYTHON_INTERPRETER),$(PYTHON_INTERPRETER),$(error Did not find a Python interpreter)))\n";
fout << "\t$(PYTHON_INTERPRETER) tools/listErrorsWithoutCWE.py -F /tmp/errorlist.xml\n";
fout << ".PHONY: validateRules\n";
fout << "validateRules:\n";
fout << "\txmllint --noout rules/*.xml\n";
fout << "\n###### Build\n\n";
compilefiles(fout, libfiles_prio, "${INCLUDE_FOR_LIB}");
compilefiles(fout, clifiles, "${INCLUDE_FOR_CLI}");
compilefiles(fout, testfiles, "${INCLUDE_FOR_TEST}");
compilefiles(fout, extfiles, emptyString);
compilefiles(fout, toolsfiles, "${INCLUDE_FOR_LIB}");
write_ossfuzz_makefile(libfiles_prio, extfiles);
return 0;
}
| null |
772 | cpp | cppcheck | type2.h | oss-fuzz/type2.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <cstdint>
#include <string>
std::string generateCode2(const uint8_t *data, size_t dataSize);
| null |
773 | cpp | cppcheck | translate.cpp | oss-fuzz/translate.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2022 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <fstream>
#include "type2.h"
int main(int argc, char **argv)
{
const char *filename = argc==2 ? argv[1] : nullptr;
if (!filename) {
std::cout << "Invalid args, no filename\n";
return 1;
}
std::ifstream f(filename);
if (!f.is_open()) {
std::cout << "failed to open file:" << filename << "\n";
return 1;
}
std::string str((std::istreambuf_iterator<char>(f)),
std::istreambuf_iterator<char>());
std::cout << generateCode2(reinterpret_cast<const uint8_t *>(str.data()), str.size()) << std::endl;
return 0;
}
| null |
774 | cpp | cppcheck | main.cpp | oss-fuzz/main.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "cppcheck.h"
#include "errorlogger.h"
#include "errortypes.h"
#include "filesettings.h"
#include "settings.h"
#include <string>
#ifndef NO_FUZZ
#include <cstddef>
#include <cstdint>
#include "type2.h"
#else
#include <cstdlib>
#include <fstream>
#include <sstream>
#endif
class DummyErrorLogger : public ErrorLogger {
public:
void reportOut(const std::string& /*outmsg*/, Color /*c*/) override {}
void reportErr(const ErrorMessage& /*msg*/) override {}
void reportProgress(const std::string& /*filename*/,
const char /*stage*/[],
const std::size_t /*value*/) override {} // FN
};
static DummyErrorLogger s_errorLogger;
static const FileWithDetails s_file("test.cpp");
static void doCheck(const std::string& code)
{
CppCheck cppcheck(s_errorLogger, false, nullptr);
cppcheck.settings().addEnabled("all");
cppcheck.settings().certainty.setEnabled(Certainty::inconclusive, true);
cppcheck.check(s_file, code);
}
#ifndef NO_FUZZ
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t dataSize);
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t dataSize)
{
if (dataSize < 10000) {
const std::string code = generateCode2(data, dataSize);
doCheck(code);
}
return 0;
}
#else
int main(int argc, char * argv[])
{
if (argc < 2 || argc > 3)
return EXIT_FAILURE;
std::ifstream f(argv[1]);
if (!f.is_open())
return EXIT_FAILURE;
std::ostringstream oss;
oss << f.rdbuf();
if (!f.good())
return EXIT_FAILURE;
const int cnt = (argc == 3) ? std::stoi(argv[2]) : 1;
const std::string code = oss.str();
for (int i = 0; i < cnt; ++i)
doCheck(code);
return EXIT_SUCCESS;
}
#endif
| null |
775 | cpp | cppcheck | type2.cpp | oss-fuzz/type2.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "type2.h"
#include <cstring>
static int getValue(const uint8_t *data, size_t dataSize, uint8_t maxValue, bool *done = nullptr)
{
static size_t pos; // current "data" position
static int dataValue; // value extracted from data
static int ones; // ones. This variable tracks if we need to add more stuff in "dataValue".
// Shift more bits from "data" into "dataValue" if needed
while (pos < dataSize && ones < 0xFFFF) {
ones = (ones << 8) | 0xff;
dataValue = (dataValue << 8) | data[pos];
pos++;
}
if (done)
*done = (ones == 0);
if (maxValue == 0)
return 0;
// Shift out info from "dataValue" using % . Using & and >> would work but then we are limited to "power of 2" max value.
const int ret = dataValue % maxValue;
ones /= maxValue;
dataValue /= maxValue;
return ret;
}
static std::string generateExpression2_lvalue(const uint8_t *data, size_t dataSize)
{
return "var" + std::to_string(1 + getValue(data, dataSize, 5));
}
static std::string generateExpression2_Op(const uint8_t *data, size_t dataSize, uint8_t numberOfGlobalConstants)
{
std::string code;
switch (getValue(data, dataSize, 3)) {
case 0:
code += generateExpression2_lvalue(data, dataSize);
break;
case 1:
code += "globalconstant";
code += (1 + getValue(data, dataSize, numberOfGlobalConstants));
break;
case 2:
code += (getValue(data, dataSize, 0x80) * 0x80 + getValue(data, dataSize, 0x80));
break;
}
return code;
}
static std::string generateExpression2_Expr(const uint8_t *data, size_t dataSize, uint8_t numberOfGlobalConstants, int depth=0)
{
++depth;
const int type = (depth > 3) ? 0 : getValue(data, dataSize, 3);
const char binop[] = "=<>+-*/%&|^";
const char *unop[] = {"++","--","()","~"};
switch (type) {
case 0:
return generateExpression2_Op(data, dataSize, numberOfGlobalConstants);
case 1: {
const char op = binop[getValue(data,dataSize,sizeof(binop)-1)];
const std::string lhs = (op == '=') ?
generateExpression2_lvalue(data, dataSize) :
generateExpression2_Expr(data, dataSize, numberOfGlobalConstants, depth);
const std::string rhs = generateExpression2_Expr(data, dataSize, numberOfGlobalConstants, depth);
std::string ret = lhs + op + rhs;
if (depth > 1 && op == '=')
ret = "(" + ret + ")";
return ret;
}
case 2: {
const char *u = unop[getValue(data,dataSize,sizeof(unop)/sizeof(*unop))];
if (strcmp(u, "()") == 0)
return "(" + generateExpression2_Expr(data, dataSize, numberOfGlobalConstants, depth) + ")";
else if (strcmp(u, "++") == 0 || strcmp(u, "--") == 0)
return u + generateExpression2_lvalue(data, dataSize);
return u + generateExpression2_Expr(data, dataSize, numberOfGlobalConstants, depth);
}
default:
break;
}
return "0";
}
static std::string generateExpression2_Cond(const uint8_t *data, size_t dataSize, uint8_t numberOfGlobalConstants)
{
const char *comp[] = {"==", "!=", "<", "<=", ">", ">="};
const int i = getValue(data, dataSize, 6);
const std::string lhs = generateExpression2_Expr(data, dataSize, numberOfGlobalConstants);
const std::string rhs = generateExpression2_Expr(data, dataSize, numberOfGlobalConstants);
return lhs + comp[i] + rhs;
}
static std::string functionStart()
{
static int functionNumber;
return "int f" + std::to_string(++functionNumber) + "()\n"
"{\n";
}
static std::string generateExpression2_conditionalCode(const std::string &indent,
const uint8_t *data,
size_t dataSize,
uint8_t numberOfGlobalConstants)
{
std::string code;
if (indent.empty())
code += functionStart();
else {
code += indent;
code += "{\n";
}
for (int line = 0; line < 4 || indent.empty(); ++line) {
bool done = false;
const int type1 = getValue(data, dataSize, 8, &done);
if (done)
break;
const int mostLikelyType = (line >= 2) ? 4 : 0; // should var assignment or return be more likely?
const int type2 = (indent.size() >= 12) ?
mostLikelyType : // max indentation, no inner conditions
((type1 >= 5) ? mostLikelyType : type1);
if (type2 == 0) {
code += indent;
code += " var";
code += getValue(data, dataSize, 5);
code += "=";
code += generateExpression2_Expr(data, dataSize, numberOfGlobalConstants);
code += ";\n";
} else if (type2 == 1) {
code += indent;
code += " if (";
code += generateExpression2_Cond(data, dataSize, numberOfGlobalConstants);
code += ")\n";
code += generateExpression2_conditionalCode(indent + " ", data, dataSize, numberOfGlobalConstants);
} else if (type2 == 2) {
code += indent;
code += " if (";
code += generateExpression2_Cond(data, dataSize, numberOfGlobalConstants);
code += ")\n";
code += generateExpression2_conditionalCode(indent + " ", data, dataSize, numberOfGlobalConstants);
code += indent;
code += " else\n";
code += generateExpression2_conditionalCode(indent + " ", data, dataSize, numberOfGlobalConstants);
} else if (type2 == 3) {
code += indent;
code += " while (";
code += generateExpression2_Cond(data, dataSize, numberOfGlobalConstants);
code += ")\n";
code += generateExpression2_conditionalCode(indent + " ", data, dataSize, numberOfGlobalConstants);
} else if (type2 == 4) {
code += indent;
code += " return ";
code += generateExpression2_Expr(data, dataSize, numberOfGlobalConstants);
code += ";\n";
if (indent.empty()) {
code += "}\n\n";
code += functionStart();
}
else
break;
}
}
if (!indent.empty()) {
code += indent;
code += "}\n";
}
else {
code += " return 0;\n}\n";
}
return code;
}
std::string generateCode2(const uint8_t *data, size_t dataSize)
{
std::string code;
// create global constants
constexpr uint8_t numberOfGlobalConstants = 0;
/*
const int numberOfGlobalConstants = getValue(data, dataSize, 5);
for (int nr = 1; nr <= numberOfGlobalConstants; nr++) {
const char *types[4] = {"char", "int", "long long", "float"};
code << "const " << types[getValue(data, dataSize, 4)] << " globalconstant" << nr << " = " << generateExpression2_Expr(data, dataSize, nr - 1) << ";\n";
}
*/
code += "int var1 = 1;\n"
"int var2 = 0;\n"
"int var3 = 1;\n"
"int var4 = 0;\n"
"int var5 = -1;\n\n";
code += generateExpression2_conditionalCode("", data, dataSize, numberOfGlobalConstants);
return code;
}
| null |
776 | cpp | cppcheck | bad.cpp | samples/passedByValue_1/bad.cpp | null | class C
{
public:
explicit C(std::string s)
: _s(s)
{
}
void foo();
private:
std::string _s;
}; | null |
777 | cpp | cppcheck | good.cpp | samples/passedByValue_1/good.cpp | null | class C
{
public:
explicit C(std::string s)
: _s(std::move(s))
{
}
void foo();
private:
std::string _s;
}; | null |
778 | cpp | cppcheck | bad.cpp | samples/passedByValue_2/bad.cpp | null | bool foo(std::string s)
{
return s.empty();
}
int main()
{
std::string s;
foo(s);
}
| null |
779 | cpp | cppcheck | good.cpp | samples/passedByValue_2/good.cpp | null | bool foo(const std::string& s)
{
return s.empty();
}
int main()
{
std::string s;
foo(s);
}
| null |
780 | cpp | cppcheck | bad.cpp | samples/invalidContainer/bad.cpp | null | #include <vector>
int main()
{
std::vector<int> items;
items.push_back(1);
items.push_back(2);
items.push_back(3);
std::vector<int>::iterator iter;
for (iter = items.begin(); iter != items.end(); ++iter) {
if (*iter == 2) {
items.erase(iter);
}
}
}
| null |
781 | cpp | cppcheck | good.cpp | samples/invalidContainer/good.cpp | null | #include <vector>
int main()
{
std::vector<int> items;
items.push_back(1);
items.push_back(2);
items.push_back(3);
std::vector<int>::iterator iter;
for (iter = items.begin(); iter != items.end();) {
if (*iter == 2) {
iter = items.erase(iter);
} else {
++iter;
}
}
}
| null |
782 | cpp | cppcheck | bad.cpp | samples/accessMoved/bad.cpp | null | void foo(std::string);
int main()
{
std::string s = "test";
foo(std::move(s));
std::cout << s << std::endl;
}
| null |
783 | cpp | cppcheck | good.cpp | samples/accessMoved/good.cpp | null | void foo(std::string);
int main()
{
std::string s = "test";
foo(s);
std::cout << s << std::endl;
}
| null |
784 | cpp | cppcheck | bad.cpp | samples/unreadVariable/bad.cpp | null | void foo(const std::string&, const std::string&);
int main()
{
std::string s1 = "test1", s2 = "test2";
foo(s1, s1);
}
| null |
785 | cpp | cppcheck | good.cpp | samples/unreadVariable/good.cpp | null | void foo(const std::string&, const std::string&);
int main()
{
std::string s1 = "test1", s2 = "test2";
foo(s1, s2);
}
| null |
786 | cpp | cppcheck | misc-test.cpp | addons/test/misc-test.cpp | null | // To test:
// ~/cppcheck/cppcheck --dump misc-test.cpp && python ../misc.py -verify misc-test.cpp.dump
#include <string>
#include <vector>
// Warn about string concatenation in array initializers..
const char *a[] = {"a" "b"}; // stringConcatInArrayInit
const char *b[] = {"a","b" "c"}; // stringConcatInArrayInit
#define MACRO "MACRO"
const char *c[] = { MACRO "text" }; // stringConcatInArrayInit
// Function is implicitly virtual
class base {
virtual void dostuff(int);
};
class derived : base {
void dostuff(int); // implicitlyVirtual
};
// Pass struct to ellipsis function
struct {int x;int y;} s;
void ellipsis(int x, ...);
void foo(std::vector<std::string> v) {
ellipsis(321, s); // ellipsisStructArg
ellipsis(321, v[0]); // ellipsisStructArg
}
| null |
787 | cpp | cppcheck | naming_test.cpp | addons/test/naming_test.cpp | addons/test/naming_test.cpp | // To test:
// ~/cppcheck/cppcheck --dump naming_test.cpp && python ../naming.py --var='[a-z].*' --function='[a-z].*' naming_test.cpp.dump
// No error for mismatching Constructor/Destructor names should be issued, they can not be changed.
class TestClass1
{
TestClass1() {}
~TestClass1() {}
TestClass1(const TestClass1 &) {}
TestClass1(TestClass1 &&) {}
};
| // To test:
// ~/cppcheck/cppcheck --dump naming_test.cpp && python ../naming.py --var='[a-z].*' --function='[a-z].*' naming_test.cpp.dump
// No error for mismatching Constructor/Destructor names should be issued, they can not be changed.
class TestClass1
{
TestClass1() {}
~TestClass1() {}
TestClass1(const TestClass1 &) {}
TestClass1(TestClass1 &&) {}
};
|
788 | cpp | cppcheck | y2038-inc.h | addons/test/y2038/y2038-inc.h | null | #ifndef __INC2038
#define _INC2038
/*
* This file defines _USE_TIME_BITS64.
* It plays the role of a Y2038-proof glibc.
*/
#define _USE_TIME_BITS64
/*
* Declare just enough for clock_gettime
*/
typedef int clockid_t;
typedef int __time_t;
typedef long int __syscall_slong_t;
struct timespec
{
__time_t tv_sec; /* Seconds. */
__syscall_slong_t tv_nsec; /* Nanoseconds. */
};
extern int clock_gettime(clockid_t clk_id, struct timespec *tp);
#define CLOCK_REALTIME 0
#endif /* INC2038 */
| null |
789 | cpp | cppcheck | local_static.cpp | addons/test/threadsafety/local_static.cpp | null | struct Dummy {
int x;
};
void func() {
// cppcheck-suppress threadsafety-threadsafety
static Dummy dummy;
}
| null |
790 | cpp | cppcheck | local_static_const.cpp | addons/test/threadsafety/local_static_const.cpp | null | struct Dummy {
int x;
};
void func() {
// cppcheck-suppress threadsafety-threadsafety-const
static const Dummy dummy;
}
| null |
791 | cpp | cppcheck | MT-Unsafe.cpp | addons/test/threadsafety/MT-Unsafe.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2023 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* This does not match the standard cppchek test code,
* because I haven't figured that out yet.
* This code does compile and run, and does demonstrate
* the issues that the threadsafety.py addon is supposed to find.
* It does not use threads !
*/
#include <stdio.h>
#include <time.h>
#include <string.h>
void threadsafety_static()
{
// cppcheck-suppress threadsafety-threadsafety
static unsigned int nCount = 0;
nCount++;
printf("%d\n", nCount);
}
void threadsafety_call()
{
time_t now = time(nullptr);
// cppcheck-suppress threadsafety-unsafe-call
printf("%s\n", ctime(&now));
}
// cppcheck --addon=threadsafety
// should *not* find any problems with this function.
void threadsafety_safecall()
{
char haystack[] = "alphabet";
char needle[] = "Alph";
char* found = strcasestr(haystack, needle);
printf("%s %sin %s\n", needle, found ? "" : "not ", haystack);
}
int main() {
threadsafety_static();
threadsafety_call();
threadsafety_safecall();
threadsafety_static();
return 0;
}
| null |
792 | cpp | cppcheck | misra-ctu-test.h | addons/test/misra/misra-ctu-test.h | null |
typedef int MISRA_2_3_A;
typedef int MISRA_2_3_B;
typedef int MISRA_2_3_VIOLATION; // cppcheck-suppress misra-c2012-2.3
// cppcheck-suppress misra-c2012-2.4
struct misra_2_4_violation_t {
int x;
};
static inline void misra_5_9_exception(void) {}
void misra_8_7_external(void);
#define MISRA_2_5_OK_1 1
#define MISRA_2_5_OK_2 2
// cppcheck-suppress misra-c2012-2.5
#define MISRA_2_5_VIOLATION 0
// #12362
extern void misra_8_7_compliant( void );
| null |
793 | cpp | cppcheck | misra-test.h | addons/test/misra/misra-test.h | null | #ifndef MISRA_TEST_H
#define MISRA_TEST_H
struct misra_h_s { int foo; };
bool test(char *a); // OK
int misra_8_2_no_fp(int a);
void misra_8_4_bar(void);
// #12978
typedef struct m8_4_stErrorDef
{
uint8_t ubReturnVal;
} m8_4_stErrorDef;
extern const m8_4_stErrorDef * m8_4_pubTestPointer;
#endif // MISRA_TEST_H
| null |
794 | cpp | cppcheck | misra-test.cpp | addons/test/misra/misra-test.cpp | null | // #8441
class C {
int a;
int b;
C(void) : a(1), b(1) { c; }
};
class misra_21_1_C {
public:
misra_21_1_C operator=(const misra_21_1_C &);
};
class C2 {
public:
C2(void);
private:
void* f;
};
C2::C2(void) : f(NULL) {}
static void test_misra_21_1_crash(void)
{
auto misra_21_1_C a, b; // 12.3
a = b;
}
| null |
795 | cpp | cppcheck | picojson.h | externals/picojson/picojson.h | null | /*
* Copyright 2009-2010 Cybozu Labs, Inc.
* Copyright 2011-2014 Kazuho Oku
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef picojson_h
#define picojson_h
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cstddef>
#include <iostream>
#include <iterator>
#include <limits>
#include <map>
#include <stdexcept>
#include <string>
#include <vector>
#include <utility>
// for isnan/isinf
#if __cplusplus >= 201103L
#include <cmath>
#else
extern "C" {
#ifdef _MSC_VER
#include <float.h>
#elif defined(__INTEL_COMPILER)
#include <mathimf.h>
#else
#include <math.h>
#endif
}
#endif
#ifndef PICOJSON_USE_RVALUE_REFERENCE
#if (defined(__cpp_rvalue_references) && __cpp_rvalue_references >= 200610) || (defined(_MSC_VER) && _MSC_VER >= 1600)
#define PICOJSON_USE_RVALUE_REFERENCE 1
#else
#define PICOJSON_USE_RVALUE_REFERENCE 0
#endif
#endif // PICOJSON_USE_RVALUE_REFERENCE
#ifndef PICOJSON_NOEXCEPT
#if PICOJSON_USE_RVALUE_REFERENCE
#define PICOJSON_NOEXCEPT noexcept
#else
#define PICOJSON_NOEXCEPT throw()
#endif
#endif
// experimental support for int64_t (see README.mkdn for detail)
#ifdef PICOJSON_USE_INT64
#define __STDC_FORMAT_MACROS
#include <cerrno>
#if __cplusplus >= 201103L
#include <cinttypes>
#else
extern "C" {
#include <inttypes.h>
}
#endif
#endif
// to disable the use of localeconv(3), set PICOJSON_USE_LOCALE to 0
#ifndef PICOJSON_USE_LOCALE
#define PICOJSON_USE_LOCALE 1
#endif
#if PICOJSON_USE_LOCALE
extern "C" {
#include <locale.h>
}
#endif
#ifndef PICOJSON_ASSERT
#define PICOJSON_ASSERT(e) \
do { \
if (!(e)) \
throw std::runtime_error(#e); \
} while (0)
#endif
#ifdef _MSC_VER
#define SNPRINTF _snprintf_s
#pragma warning(push)
#pragma warning(disable : 4244) // conversion from int to char
#pragma warning(disable : 4127) // conditional expression is constant
#pragma warning(disable : 4702) // unreachable code
#pragma warning(disable : 4706) // assignment within conditional expression
#else
#define SNPRINTF snprintf
#endif
namespace picojson {
enum {
null_type,
boolean_type,
number_type,
string_type,
array_type,
object_type
#ifdef PICOJSON_USE_INT64
,
int64_type
#endif
};
enum { INDENT_WIDTH = 2, DEFAULT_MAX_DEPTHS = 100 };
struct null {};
class value {
public:
typedef std::vector<value> array;
typedef std::map<std::string, value> object;
union _storage {
bool boolean_;
double number_;
#ifdef PICOJSON_USE_INT64
int64_t int64_;
#endif
std::string *string_;
array *array_;
object *object_;
};
protected:
int type_;
_storage u_;
public:
value();
value(int type, bool);
explicit value(bool b);
#ifdef PICOJSON_USE_INT64
explicit value(int64_t i);
#endif
explicit value(double n);
explicit value(const std::string &s);
explicit value(const array &a);
explicit value(const object &o);
#if PICOJSON_USE_RVALUE_REFERENCE
explicit value(std::string &&s);
explicit value(array &&a);
explicit value(object &&o);
#endif
explicit value(const char *s);
value(const char *s, size_t len);
~value();
value(const value &x);
value &operator=(const value &x);
#if PICOJSON_USE_RVALUE_REFERENCE
value(value &&x) PICOJSON_NOEXCEPT;
value &operator=(value &&x) PICOJSON_NOEXCEPT;
#endif
void swap(value &x) PICOJSON_NOEXCEPT;
template <typename T> bool is() const;
template <typename T> const T &get() const;
template <typename T> T &get();
template <typename T> void set(const T &);
#if PICOJSON_USE_RVALUE_REFERENCE
template <typename T> void set(T &&);
#endif
bool evaluate_as_boolean() const;
const value &get(const size_t idx) const;
const value &get(const std::string &key) const;
value &get(const size_t idx);
value &get(const std::string &key);
bool contains(const size_t idx) const;
bool contains(const std::string &key) const;
std::string to_str() const;
template <typename Iter> void serialize(Iter os, bool prettify = false) const;
std::string serialize(bool prettify = false) const;
private:
template <typename T> value(const T *); // intentionally defined to block implicit conversion of pointer to bool
template <typename Iter> static void _indent(Iter os, int indent);
template <typename Iter> void _serialize(Iter os, int indent) const;
std::string _serialize(int indent) const;
void clear();
};
typedef value::array array;
typedef value::object object;
inline value::value() : type_(null_type), u_() {
}
inline value::value(int type, bool) : type_(type), u_() {
switch (type) {
#define INIT(p, v) \
case p##type: \
u_.p = v; \
break
INIT(boolean_, false);
INIT(number_, 0.0);
#ifdef PICOJSON_USE_INT64
INIT(int64_, 0);
#endif
INIT(string_, new std::string());
INIT(array_, new array());
INIT(object_, new object());
#undef INIT
default:
break;
}
}
inline value::value(bool b) : type_(boolean_type), u_() {
u_.boolean_ = b;
}
#ifdef PICOJSON_USE_INT64
inline value::value(int64_t i) : type_(int64_type), u_() {
u_.int64_ = i;
}
#endif
inline value::value(double n) : type_(number_type), u_() {
if (
#ifdef _MSC_VER
!_finite(n)
#elif __cplusplus >= 201103L
std::isnan(n) || std::isinf(n)
#else
isnan(n) || isinf(n)
#endif
) {
throw std::overflow_error("");
}
u_.number_ = n;
}
inline value::value(const std::string &s) : type_(string_type), u_() {
u_.string_ = new std::string(s);
}
inline value::value(const array &a) : type_(array_type), u_() {
u_.array_ = new array(a);
}
inline value::value(const object &o) : type_(object_type), u_() {
u_.object_ = new object(o);
}
#if PICOJSON_USE_RVALUE_REFERENCE
inline value::value(std::string &&s) : type_(string_type), u_() {
u_.string_ = new std::string(std::move(s));
}
inline value::value(array &&a) : type_(array_type), u_() {
u_.array_ = new array(std::move(a));
}
inline value::value(object &&o) : type_(object_type), u_() {
u_.object_ = new object(std::move(o));
}
#endif
inline value::value(const char *s) : type_(string_type), u_() {
u_.string_ = new std::string(s);
}
inline value::value(const char *s, size_t len) : type_(string_type), u_() {
u_.string_ = new std::string(s, len);
}
inline void value::clear() {
switch (type_) {
#define DEINIT(p) \
case p##type: \
delete u_.p; \
break
DEINIT(string_);
DEINIT(array_);
DEINIT(object_);
#undef DEINIT
default:
break;
}
}
inline value::~value() {
clear();
}
inline value::value(const value &x) : type_(x.type_), u_() {
switch (type_) {
#define INIT(p, v) \
case p##type: \
u_.p = v; \
break
INIT(string_, new std::string(*x.u_.string_));
INIT(array_, new array(*x.u_.array_));
INIT(object_, new object(*x.u_.object_));
#undef INIT
default:
u_ = x.u_;
break;
}
}
inline value &value::operator=(const value &x) {
if (this != &x) {
value t(x);
swap(t);
}
return *this;
}
#if PICOJSON_USE_RVALUE_REFERENCE
inline value::value(value &&x) PICOJSON_NOEXCEPT : type_(null_type), u_() {
swap(x);
}
inline value &value::operator=(value &&x) PICOJSON_NOEXCEPT {
swap(x);
return *this;
}
#endif
inline void value::swap(value &x) PICOJSON_NOEXCEPT {
std::swap(type_, x.type_);
std::swap(u_, x.u_);
}
#define IS(ctype, jtype) \
template <> inline bool value::is<ctype>() const { \
return type_ == jtype##_type; \
}
IS(null, null)
IS(bool, boolean)
#ifdef PICOJSON_USE_INT64
IS(int64_t, int64)
#endif
IS(std::string, string)
IS(array, array)
IS(object, object)
#undef IS
template <> inline bool value::is<double>() const {
return type_ == number_type
#ifdef PICOJSON_USE_INT64
|| type_ == int64_type
#endif
;
}
#define GET(ctype, var) \
template <> inline const ctype &value::get<ctype>() const { \
PICOJSON_ASSERT("type mismatch! call is<type>() before get<type>()" && is<ctype>()); \
return var; \
} \
template <> inline ctype &value::get<ctype>() { \
PICOJSON_ASSERT("type mismatch! call is<type>() before get<type>()" && is<ctype>()); \
return var; \
}
GET(bool, u_.boolean_)
GET(std::string, *u_.string_)
GET(array, *u_.array_)
GET(object, *u_.object_)
#ifdef PICOJSON_USE_INT64
GET(double,
(type_ == int64_type && (const_cast<value *>(this)->type_ = number_type, (const_cast<value *>(this)->u_.number_ = u_.int64_)),
u_.number_))
GET(int64_t, u_.int64_)
#else
GET(double, u_.number_)
#endif
#undef GET
#define SET(ctype, jtype, setter) \
template <> inline void value::set<ctype>(const ctype &_val) { \
clear(); \
type_ = jtype##_type; \
setter \
}
SET(bool, boolean, u_.boolean_ = _val;)
SET(std::string, string, u_.string_ = new std::string(_val);)
SET(array, array, u_.array_ = new array(_val);)
SET(object, object, u_.object_ = new object(_val);)
SET(double, number, u_.number_ = _val;)
#ifdef PICOJSON_USE_INT64
SET(int64_t, int64, u_.int64_ = _val;)
#endif
#undef SET
#if PICOJSON_USE_RVALUE_REFERENCE
#define MOVESET(ctype, jtype, setter) \
template <> inline void value::set<ctype>(ctype && _val) { \
clear(); \
type_ = jtype##_type; \
setter \
}
MOVESET(std::string, string, u_.string_ = new std::string(std::move(_val));)
MOVESET(array, array, u_.array_ = new array(std::move(_val));)
MOVESET(object, object, u_.object_ = new object(std::move(_val));)
#undef MOVESET
#endif
inline bool value::evaluate_as_boolean() const {
switch (type_) {
case null_type:
return false;
case boolean_type:
return u_.boolean_;
case number_type:
return u_.number_ != 0;
#ifdef PICOJSON_USE_INT64
case int64_type:
return u_.int64_ != 0;
#endif
case string_type:
return !u_.string_->empty();
default:
return true;
}
}
inline const value &value::get(const size_t idx) const {
static value s_null;
PICOJSON_ASSERT(is<array>());
return idx < u_.array_->size() ? (*u_.array_)[idx] : s_null;
}
inline value &value::get(const size_t idx) {
static value s_null;
PICOJSON_ASSERT(is<array>());
return idx < u_.array_->size() ? (*u_.array_)[idx] : s_null;
}
inline const value &value::get(const std::string &key) const {
static value s_null;
PICOJSON_ASSERT(is<object>());
object::const_iterator i = u_.object_->find(key);
return i != u_.object_->end() ? i->second : s_null;
}
inline value &value::get(const std::string &key) {
static value s_null;
PICOJSON_ASSERT(is<object>());
object::iterator i = u_.object_->find(key);
return i != u_.object_->end() ? i->second : s_null;
}
inline bool value::contains(const size_t idx) const {
PICOJSON_ASSERT(is<array>());
return idx < u_.array_->size();
}
inline bool value::contains(const std::string &key) const {
PICOJSON_ASSERT(is<object>());
object::const_iterator i = u_.object_->find(key);
return i != u_.object_->end();
}
inline std::string value::to_str() const {
switch (type_) {
case null_type:
return "null";
case boolean_type:
return u_.boolean_ ? "true" : "false";
#ifdef PICOJSON_USE_INT64
case int64_type: {
char buf[sizeof("-9223372036854775808")];
SNPRINTF(buf, sizeof(buf), "%" PRId64, u_.int64_);
return buf;
}
#endif
case number_type: {
char buf[256];
double tmp;
SNPRINTF(buf, sizeof(buf), fabs(u_.number_) < (1ULL << 53) && modf(u_.number_, &tmp) == 0 ? "%.f" : "%.17g", u_.number_);
#if PICOJSON_USE_LOCALE
char *decimal_point = localeconv()->decimal_point;
if (strcmp(decimal_point, ".") != 0) {
size_t decimal_point_len = strlen(decimal_point);
for (char *p = buf; *p != '\0'; ++p) {
if (strncmp(p, decimal_point, decimal_point_len) == 0) {
return std::string(buf, p) + "." + (p + decimal_point_len);
}
}
}
#endif
return buf;
}
case string_type:
return *u_.string_;
case array_type:
return "array";
case object_type:
return "object";
default:
PICOJSON_ASSERT(0);
#ifdef _MSC_VER
__assume(0);
#endif
}
return std::string();
}
template <typename Iter> void copy(const std::string &s, Iter oi) {
std::copy(s.begin(), s.end(), oi);
}
template <typename Iter> struct serialize_str_char {
Iter oi;
void operator()(char c) {
switch (c) {
#define MAP(val, sym) \
case val: \
copy(sym, oi); \
break
MAP('"', "\\\"");
MAP('\\', "\\\\");
MAP('/', "\\/");
MAP('\b', "\\b");
MAP('\f', "\\f");
MAP('\n', "\\n");
MAP('\r', "\\r");
MAP('\t', "\\t");
#undef MAP
default:
if (static_cast<unsigned char>(c) < 0x20 || c == 0x7f) {
char buf[7];
SNPRINTF(buf, sizeof(buf), "\\u%04x", c & 0xff);
copy(buf, buf + 6, oi);
} else {
*oi++ = c;
}
break;
}
}
};
template <typename Iter> void serialize_str(const std::string &s, Iter oi) {
*oi++ = '"';
serialize_str_char<Iter> process_char = {oi};
std::for_each(s.begin(), s.end(), process_char);
*oi++ = '"';
}
template <typename Iter> void value::serialize(Iter oi, bool prettify) const {
return _serialize(oi, prettify ? 0 : -1);
}
inline std::string value::serialize(bool prettify) const {
return _serialize(prettify ? 0 : -1);
}
template <typename Iter> void value::_indent(Iter oi, int indent) {
*oi++ = '\n';
for (int i = 0; i < indent * INDENT_WIDTH; ++i) {
*oi++ = ' ';
}
}
template <typename Iter> void value::_serialize(Iter oi, int indent) const {
switch (type_) {
case string_type:
serialize_str(*u_.string_, oi);
break;
case array_type: {
*oi++ = '[';
if (indent != -1) {
++indent;
}
for (array::const_iterator i = u_.array_->begin(); i != u_.array_->end(); ++i) {
if (i != u_.array_->begin()) {
*oi++ = ',';
}
if (indent != -1) {
_indent(oi, indent);
}
i->_serialize(oi, indent);
}
if (indent != -1) {
--indent;
if (!u_.array_->empty()) {
_indent(oi, indent);
}
}
*oi++ = ']';
break;
}
case object_type: {
*oi++ = '{';
if (indent != -1) {
++indent;
}
for (object::const_iterator i = u_.object_->begin(); i != u_.object_->end(); ++i) {
if (i != u_.object_->begin()) {
*oi++ = ',';
}
if (indent != -1) {
_indent(oi, indent);
}
serialize_str(i->first, oi);
*oi++ = ':';
if (indent != -1) {
*oi++ = ' ';
}
i->second._serialize(oi, indent);
}
if (indent != -1) {
--indent;
if (!u_.object_->empty()) {
_indent(oi, indent);
}
}
*oi++ = '}';
break;
}
default:
copy(to_str(), oi);
break;
}
if (indent == 0) {
*oi++ = '\n';
}
}
inline std::string value::_serialize(int indent) const {
std::string s;
_serialize(std::back_inserter(s), indent);
return s;
}
template <typename Iter> class input {
protected:
Iter cur_, end_;
bool consumed_;
int line_;
public:
input(const Iter &first, const Iter &last) : cur_(first), end_(last), consumed_(false), line_(1) {
}
int getc() {
if (consumed_) {
if (*cur_ == '\n') {
++line_;
}
++cur_;
}
if (cur_ == end_) {
consumed_ = false;
return -1;
}
consumed_ = true;
return *cur_ & 0xff;
}
void ungetc() {
consumed_ = false;
}
Iter cur() const {
if (consumed_) {
input<Iter> *self = const_cast<input<Iter> *>(this);
self->consumed_ = false;
++self->cur_;
}
return cur_;
}
int line() const {
return line_;
}
void skip_ws() {
while (1) {
int ch = getc();
if (!(ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r')) {
ungetc();
break;
}
}
}
bool expect(const int expected) {
skip_ws();
if (getc() != expected) {
ungetc();
return false;
}
return true;
}
bool match(const std::string &pattern) {
for (std::string::const_iterator pi(pattern.begin()); pi != pattern.end(); ++pi) {
if (getc() != *pi) {
ungetc();
return false;
}
}
return true;
}
};
template <typename Iter> inline int _parse_quadhex(input<Iter> &in) {
int uni_ch = 0, hex;
for (int i = 0; i < 4; i++) {
if ((hex = in.getc()) == -1) {
return -1;
}
if ('0' <= hex && hex <= '9') {
hex -= '0';
} else if ('A' <= hex && hex <= 'F') {
hex -= 'A' - 0xa;
} else if ('a' <= hex && hex <= 'f') {
hex -= 'a' - 0xa;
} else {
in.ungetc();
return -1;
}
uni_ch = uni_ch * 16 + hex;
}
return uni_ch;
}
template <typename String, typename Iter> inline bool _parse_codepoint(String &out, input<Iter> &in) {
int uni_ch;
if ((uni_ch = _parse_quadhex(in)) == -1) {
return false;
}
if (0xd800 <= uni_ch && uni_ch <= 0xdfff) {
if (0xdc00 <= uni_ch) {
// a second 16-bit of a surrogate pair appeared
return false;
}
// first 16-bit of surrogate pair, get the next one
if (in.getc() != '\\' || in.getc() != 'u') {
in.ungetc();
return false;
}
int second = _parse_quadhex(in);
if (!(0xdc00 <= second && second <= 0xdfff)) {
return false;
}
uni_ch = ((uni_ch - 0xd800) << 10) | ((second - 0xdc00) & 0x3ff);
uni_ch += 0x10000;
}
if (uni_ch < 0x80) {
out.push_back(static_cast<char>(uni_ch));
} else {
if (uni_ch < 0x800) {
out.push_back(static_cast<char>(0xc0 | (uni_ch >> 6)));
} else {
if (uni_ch < 0x10000) {
out.push_back(static_cast<char>(0xe0 | (uni_ch >> 12)));
} else {
out.push_back(static_cast<char>(0xf0 | (uni_ch >> 18)));
out.push_back(static_cast<char>(0x80 | ((uni_ch >> 12) & 0x3f)));
}
out.push_back(static_cast<char>(0x80 | ((uni_ch >> 6) & 0x3f)));
}
out.push_back(static_cast<char>(0x80 | (uni_ch & 0x3f)));
}
return true;
}
template <typename String, typename Iter> inline bool _parse_string(String &out, input<Iter> &in) {
while (1) {
int ch = in.getc();
if (ch < ' ') {
in.ungetc();
return false;
} else if (ch == '"') {
return true;
} else if (ch == '\\') {
if ((ch = in.getc()) == -1) {
return false;
}
switch (ch) {
#define MAP(sym, val) \
case sym: \
out.push_back(val); \
break
MAP('"', '\"');
MAP('\\', '\\');
MAP('/', '/');
MAP('b', '\b');
MAP('f', '\f');
MAP('n', '\n');
MAP('r', '\r');
MAP('t', '\t');
#undef MAP
case 'u':
if (!_parse_codepoint(out, in)) {
return false;
}
break;
default:
return false;
}
} else {
out.push_back(static_cast<char>(ch));
}
}
return false;
}
template <typename Context, typename Iter> inline bool _parse_array(Context &ctx, input<Iter> &in) {
if (!ctx.parse_array_start()) {
return false;
}
size_t idx = 0;
if (in.expect(']')) {
return ctx.parse_array_stop(idx);
}
do {
if (!ctx.parse_array_item(in, idx)) {
return false;
}
idx++;
} while (in.expect(','));
return in.expect(']') && ctx.parse_array_stop(idx);
}
template <typename Context, typename Iter> inline bool _parse_object(Context &ctx, input<Iter> &in) {
if (!ctx.parse_object_start()) {
return false;
}
if (in.expect('}')) {
return ctx.parse_object_stop();
}
do {
std::string key;
if (!in.expect('"') || !_parse_string(key, in) || !in.expect(':')) {
return false;
}
if (!ctx.parse_object_item(in, key)) {
return false;
}
} while (in.expect(','));
return in.expect('}') && ctx.parse_object_stop();
}
template <typename Iter> inline std::string _parse_number(input<Iter> &in) {
std::string num_str;
while (1) {
int ch = in.getc();
if (('0' <= ch && ch <= '9') || ch == '+' || ch == '-' || ch == 'e' || ch == 'E') {
num_str.push_back(static_cast<char>(ch));
} else if (ch == '.') {
#if PICOJSON_USE_LOCALE
num_str += localeconv()->decimal_point;
#else
num_str.push_back('.');
#endif
} else {
in.ungetc();
break;
}
}
return num_str;
}
template <typename Context, typename Iter> inline bool _parse(Context &ctx, input<Iter> &in) {
in.skip_ws();
int ch = in.getc();
switch (ch) {
#define IS(ch, text, op) \
case ch: \
if (in.match(text) && op) { \
return true; \
} else { \
return false; \
}
IS('n', "ull", ctx.set_null());
IS('f', "alse", ctx.set_bool(false));
IS('t', "rue", ctx.set_bool(true));
#undef IS
case '"':
return ctx.parse_string(in);
case '[':
return _parse_array(ctx, in);
case '{':
return _parse_object(ctx, in);
default:
if (('0' <= ch && ch <= '9') || ch == '-') {
double f;
char *endp;
in.ungetc();
std::string num_str(_parse_number(in));
if (num_str.empty()) {
return false;
}
#ifdef PICOJSON_USE_INT64
{
errno = 0;
intmax_t ival = strtoimax(num_str.c_str(), &endp, 10);
if (errno == 0 && std::numeric_limits<int64_t>::min() <= ival && ival <= std::numeric_limits<int64_t>::max() &&
endp == num_str.c_str() + num_str.size()) {
ctx.set_int64(ival);
return true;
}
}
#endif
f = strtod(num_str.c_str(), &endp);
if (endp == num_str.c_str() + num_str.size()) {
ctx.set_number(f);
return true;
}
return false;
}
break;
}
in.ungetc();
return false;
}
class deny_parse_context {
public:
bool set_null() {
return false;
}
bool set_bool(bool) {
return false;
}
#ifdef PICOJSON_USE_INT64
bool set_int64(int64_t) {
return false;
}
#endif
bool set_number(double) {
return false;
}
template <typename Iter> bool parse_string(input<Iter> &) {
return false;
}
bool parse_array_start() {
return false;
}
template <typename Iter> bool parse_array_item(input<Iter> &, size_t) {
return false;
}
bool parse_array_stop(size_t) {
return false;
}
bool parse_object_start() {
return false;
}
template <typename Iter> bool parse_object_item(input<Iter> &, const std::string &) {
return false;
}
};
class default_parse_context {
protected:
value *out_;
size_t depths_;
public:
default_parse_context(value *out, size_t depths = DEFAULT_MAX_DEPTHS) : out_(out), depths_(depths) {
}
bool set_null() {
*out_ = value();
return true;
}
bool set_bool(bool b) {
*out_ = value(b);
return true;
}
#ifdef PICOJSON_USE_INT64
bool set_int64(int64_t i) {
*out_ = value(i);
return true;
}
#endif
bool set_number(double f) {
*out_ = value(f);
return true;
}
template <typename Iter> bool parse_string(input<Iter> &in) {
*out_ = value(string_type, false);
return _parse_string(out_->get<std::string>(), in);
}
bool parse_array_start() {
if (depths_ == 0)
return false;
--depths_;
*out_ = value(array_type, false);
return true;
}
template <typename Iter> bool parse_array_item(input<Iter> &in, size_t) {
array &a = out_->get<array>();
a.push_back(value());
default_parse_context ctx(&a.back(), depths_);
return _parse(ctx, in);
}
bool parse_array_stop(size_t) {
++depths_;
return true;
}
bool parse_object_start() {
if (depths_ == 0)
return false;
*out_ = value(object_type, false);
return true;
}
template <typename Iter> bool parse_object_item(input<Iter> &in, const std::string &key) {
object &o = out_->get<object>();
default_parse_context ctx(&o[key], depths_);
return _parse(ctx, in);
}
bool parse_object_stop() {
++depths_;
return true;
}
private:
default_parse_context(const default_parse_context &);
default_parse_context &operator=(const default_parse_context &);
};
class null_parse_context {
protected:
size_t depths_;
public:
struct dummy_str {
void push_back(int) {
}
};
public:
null_parse_context(size_t depths = DEFAULT_MAX_DEPTHS) : depths_(depths) {
}
bool set_null() {
return true;
}
bool set_bool(bool) {
return true;
}
#ifdef PICOJSON_USE_INT64
bool set_int64(int64_t) {
return true;
}
#endif
bool set_number(double) {
return true;
}
template <typename Iter> bool parse_string(input<Iter> &in) {
dummy_str s;
return _parse_string(s, in);
}
bool parse_array_start() {
if (depths_ == 0)
return false;
--depths_;
return true;
}
template <typename Iter> bool parse_array_item(input<Iter> &in, size_t) {
return _parse(*this, in);
}
bool parse_array_stop(size_t) {
++depths_;
return true;
}
bool parse_object_start() {
if (depths_ == 0)
return false;
--depths_;
return true;
}
template <typename Iter> bool parse_object_item(input<Iter> &in, const std::string &) {
++depths_;
return _parse(*this, in);
}
bool parse_object_stop() {
return true;
}
private:
null_parse_context(const null_parse_context &);
null_parse_context &operator=(const null_parse_context &);
};
// obsolete, use the version below
template <typename Iter> inline std::string parse(value &out, Iter &pos, const Iter &last) {
std::string err;
pos = parse(out, pos, last, &err);
return err;
}
template <typename Context, typename Iter> inline Iter _parse(Context &ctx, const Iter &first, const Iter &last, std::string *err) {
input<Iter> in(first, last);
if (!_parse(ctx, in) && err != NULL) {
char buf[64];
SNPRINTF(buf, sizeof(buf), "syntax error at line %d near: ", in.line());
*err = buf;
while (1) {
int ch = in.getc();
if (ch == -1 || ch == '\n') {
break;
} else if (ch >= ' ') {
err->push_back(static_cast<char>(ch));
}
}
}
return in.cur();
}
template <typename Iter> inline Iter parse(value &out, const Iter &first, const Iter &last, std::string *err) {
default_parse_context ctx(&out);
return _parse(ctx, first, last, err);
}
inline std::string parse(value &out, const std::string &s) {
std::string err;
parse(out, s.begin(), s.end(), &err);
return err;
}
inline std::string parse(value &out, std::istream &is) {
std::string err;
parse(out, std::istreambuf_iterator<char>(is.rdbuf()), std::istreambuf_iterator<char>(), &err);
return err;
}
template <typename T> struct last_error_t { static std::string s; };
template <typename T> std::string last_error_t<T>::s;
inline void set_last_error(const std::string &s) {
last_error_t<bool>::s = s;
}
inline const std::string &get_last_error() {
return last_error_t<bool>::s;
}
inline bool operator==(const value &x, const value &y) {
if (x.is<null>())
return y.is<null>();
#define PICOJSON_CMP(type) \
if (x.is<type>()) \
return y.is<type>() && x.get<type>() == y.get<type>()
PICOJSON_CMP(bool);
PICOJSON_CMP(double);
PICOJSON_CMP(std::string);
PICOJSON_CMP(array);
PICOJSON_CMP(object);
#undef PICOJSON_CMP
PICOJSON_ASSERT(0);
#ifdef _MSC_VER
__assume(0);
#endif
return false;
}
inline bool operator!=(const value &x, const value &y) {
return !(x == y);
}
}
#if !PICOJSON_USE_RVALUE_REFERENCE
namespace std {
template <> inline void swap(picojson::value &x, picojson::value &y) {
x.swap(y);
}
}
#endif
inline std::istream &operator>>(std::istream &is, picojson::value &x) {
picojson::set_last_error(std::string());
const std::string err(picojson::parse(x, is));
if (!err.empty()) {
picojson::set_last_error(err);
is.setstate(std::ios::failbit);
}
return is;
}
inline std::ostream &operator<<(std::ostream &os, const picojson::value &x) {
x.serialize(std::ostream_iterator<char>(os));
return os;
}
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#endif
| null |
796 | cpp | cppcheck | simplecpp.h | externals/simplecpp/simplecpp.h | null | /* -*- C++ -*-
* simplecpp - A simple and high-fidelity C/C++ preprocessor library
* Copyright (C) 2016-2023 simplecpp team
*/
#ifndef simplecppH
#define simplecppH
#include <cctype>
#include <cstring>
#include <iosfwd>
#include <list>
#include <map>
#include <set>
#include <string>
#include <vector>
#ifdef _WIN32
# ifdef SIMPLECPP_EXPORT
# define SIMPLECPP_LIB __declspec(dllexport)
# elif defined(SIMPLECPP_IMPORT)
# define SIMPLECPP_LIB __declspec(dllimport)
# else
# define SIMPLECPP_LIB
# endif
#else
# define SIMPLECPP_LIB
#endif
#if (__cplusplus < 201103L) && !defined(__APPLE__)
#define nullptr NULL
#endif
#if defined(_MSC_VER)
# pragma warning(push)
// suppress warnings about "conversion from 'type1' to 'type2', possible loss of data"
# pragma warning(disable : 4267)
# pragma warning(disable : 4244)
#endif
namespace simplecpp {
/** C code standard */
enum cstd_t { CUnknown=-1, C89, C99, C11, C17, C23 };
/** C++ code standard */
enum cppstd_t { CPPUnknown=-1, CPP03, CPP11, CPP14, CPP17, CPP20, CPP23, CPP26 };
typedef std::string TokenString;
class Macro;
/**
* Location in source code
*/
class SIMPLECPP_LIB Location {
public:
explicit Location(const std::vector<std::string> &f) : files(f), fileIndex(0), line(1U), col(0U) {}
Location(const Location &loc) : files(loc.files), fileIndex(loc.fileIndex), line(loc.line), col(loc.col) {}
Location &operator=(const Location &other) {
if (this != &other) {
fileIndex = other.fileIndex;
line = other.line;
col = other.col;
}
return *this;
}
/** increment this location by string */
void adjust(const std::string &str);
bool operator<(const Location &rhs) const {
if (fileIndex != rhs.fileIndex)
return fileIndex < rhs.fileIndex;
if (line != rhs.line)
return line < rhs.line;
return col < rhs.col;
}
bool sameline(const Location &other) const {
return fileIndex == other.fileIndex && line == other.line;
}
const std::string& file() const {
return fileIndex < files.size() ? files[fileIndex] : emptyFileName;
}
const std::vector<std::string> &files;
unsigned int fileIndex;
unsigned int line;
unsigned int col;
private:
static const std::string emptyFileName;
};
/**
* token class.
* @todo don't use std::string representation - for both memory and performance reasons
*/
class SIMPLECPP_LIB Token {
public:
Token(const TokenString &s, const Location &loc, bool wsahead = false) :
whitespaceahead(wsahead), location(loc), previous(nullptr), next(nullptr), string(s) {
flags();
}
Token(const Token &tok) :
macro(tok.macro), op(tok.op), comment(tok.comment), name(tok.name), number(tok.number), whitespaceahead(tok.whitespaceahead), location(tok.location), previous(nullptr), next(nullptr), string(tok.string), mExpandedFrom(tok.mExpandedFrom) {
}
void flags() {
name = (std::isalpha(static_cast<unsigned char>(string[0])) || string[0] == '_' || string[0] == '$')
&& (std::memchr(string.c_str(), '\'', string.size()) == nullptr);
comment = string.size() > 1U && string[0] == '/' && (string[1] == '/' || string[1] == '*');
number = isNumberLike(string);
op = (string.size() == 1U && !name && !comment && !number) ? string[0] : '\0';
}
const TokenString& str() const {
return string;
}
void setstr(const std::string &s) {
string = s;
flags();
}
bool isOneOf(const char ops[]) const;
bool startsWithOneOf(const char c[]) const;
bool endsWithOneOf(const char c[]) const;
static bool isNumberLike(const std::string& str) {
return std::isdigit(static_cast<unsigned char>(str[0])) ||
(str.size() > 1U && (str[0] == '-' || str[0] == '+') && std::isdigit(static_cast<unsigned char>(str[1])));
}
TokenString macro;
char op;
bool comment;
bool name;
bool number;
bool whitespaceahead;
Location location;
Token *previous;
Token *next;
const Token *previousSkipComments() const {
const Token *tok = this->previous;
while (tok && tok->comment)
tok = tok->previous;
return tok;
}
const Token *nextSkipComments() const {
const Token *tok = this->next;
while (tok && tok->comment)
tok = tok->next;
return tok;
}
void setExpandedFrom(const Token *tok, const Macro* m) {
mExpandedFrom = tok->mExpandedFrom;
mExpandedFrom.insert(m);
if (tok->whitespaceahead)
whitespaceahead = true;
}
bool isExpandedFrom(const Macro* m) const {
return mExpandedFrom.find(m) != mExpandedFrom.end();
}
void printAll() const;
void printOut() const;
private:
TokenString string;
std::set<const Macro*> mExpandedFrom;
// Not implemented - prevent assignment
Token &operator=(const Token &tok);
};
/** Output from preprocessor */
struct SIMPLECPP_LIB Output {
explicit Output(const std::vector<std::string> &files) : type(ERROR), location(files) {}
enum Type {
ERROR, /* #error */
WARNING, /* #warning */
MISSING_HEADER,
INCLUDE_NESTED_TOO_DEEPLY,
SYNTAX_ERROR,
PORTABILITY_BACKSLASH,
UNHANDLED_CHAR_ERROR,
EXPLICIT_INCLUDE_NOT_FOUND,
FILE_NOT_FOUND,
DUI_ERROR
} type;
explicit Output(const std::vector<std::string>& files, Type type, const std::string& msg) : type(type), location(files), msg(msg) {}
Location location;
std::string msg;
};
typedef std::list<Output> OutputList;
/** List of tokens. */
class SIMPLECPP_LIB TokenList {
public:
class Stream;
explicit TokenList(std::vector<std::string> &filenames);
/** generates a token list from the given std::istream parameter */
TokenList(std::istream &istr, std::vector<std::string> &filenames, const std::string &filename=std::string(), OutputList *outputList = nullptr);
/** generates a token list from the given buffer */
TokenList(const unsigned char* data, std::size_t size, std::vector<std::string> &filenames, const std::string &filename=std::string(), OutputList *outputList = nullptr);
/** generates a token list from the given buffer */
TokenList(const char* data, std::size_t size, std::vector<std::string> &filenames, const std::string &filename=std::string(), OutputList *outputList = nullptr);
/** generates a token list from the given filename parameter */
TokenList(const std::string &filename, std::vector<std::string> &filenames, OutputList *outputList = nullptr);
TokenList(const TokenList &other);
#if __cplusplus >= 201103L
TokenList(TokenList &&other);
#endif
~TokenList();
TokenList &operator=(const TokenList &other);
#if __cplusplus >= 201103L
TokenList &operator=(TokenList &&other);
#endif
void clear();
bool empty() const {
return !frontToken;
}
void push_back(Token *tok);
void dump() const;
std::string stringify() const;
void readfile(Stream &stream, const std::string &filename=std::string(), OutputList *outputList = nullptr);
void constFold();
void removeComments();
Token *front() {
return frontToken;
}
const Token *cfront() const {
return frontToken;
}
Token *back() {
return backToken;
}
const Token *cback() const {
return backToken;
}
void deleteToken(Token *tok) {
if (!tok)
return;
Token * const prev = tok->previous;
Token * const next = tok->next;
if (prev)
prev->next = next;
if (next)
next->previous = prev;
if (frontToken == tok)
frontToken = next;
if (backToken == tok)
backToken = prev;
delete tok;
}
void takeTokens(TokenList &other) {
if (!other.frontToken)
return;
if (!frontToken) {
frontToken = other.frontToken;
} else {
backToken->next = other.frontToken;
other.frontToken->previous = backToken;
}
backToken = other.backToken;
other.frontToken = other.backToken = nullptr;
}
/** sizeof(T) */
std::map<std::string, std::size_t> sizeOfType;
const std::vector<std::string>& getFiles() const {
return files;
}
private:
void combineOperators();
void constFoldUnaryNotPosNeg(Token *tok);
void constFoldMulDivRem(Token *tok);
void constFoldAddSub(Token *tok);
void constFoldShift(Token *tok);
void constFoldComparison(Token *tok);
void constFoldBitwise(Token *tok);
void constFoldLogicalOp(Token *tok);
void constFoldQuestionOp(Token **tok1);
std::string readUntil(Stream &stream, const Location &location, char start, char end, OutputList *outputList);
void lineDirective(unsigned int fileIndex, unsigned int line, Location *location);
std::string lastLine(int maxsize=1000) const;
const Token* lastLineTok(int maxsize=1000) const;
bool isLastLinePreprocessor(int maxsize=1000) const;
unsigned int fileIndex(const std::string &filename);
Token *frontToken;
Token *backToken;
std::vector<std::string> &files;
};
/** Tracking how macros are used */
struct SIMPLECPP_LIB MacroUsage {
explicit MacroUsage(const std::vector<std::string> &f, bool macroValueKnown_) : macroLocation(f), useLocation(f), macroValueKnown(macroValueKnown_) {}
std::string macroName;
Location macroLocation;
Location useLocation;
bool macroValueKnown;
};
/** Tracking #if/#elif expressions */
struct SIMPLECPP_LIB IfCond {
explicit IfCond(const Location& location, const std::string &E, long long result) : location(location), E(E), result(result) {}
Location location; // location of #if/#elif
std::string E; // preprocessed condition
long long result; // condition result
};
/**
* Command line preprocessor settings.
* On the command line these are configured by -D, -U, -I, --include, -std
*/
struct SIMPLECPP_LIB DUI {
DUI() : clearIncludeCache(false), removeComments(false) {}
std::list<std::string> defines;
std::set<std::string> undefined;
std::list<std::string> includePaths;
std::list<std::string> includes;
std::string std;
bool clearIncludeCache;
bool removeComments; /** remove comment tokens from included files */
};
SIMPLECPP_LIB long long characterLiteralToLL(const std::string& str);
SIMPLECPP_LIB std::map<std::string, TokenList*> load(const TokenList &rawtokens, std::vector<std::string> &filenames, const DUI &dui, OutputList *outputList = nullptr);
/**
* Preprocess
* @todo simplify interface
* @param output TokenList that receives the preprocessing output
* @param rawtokens Raw tokenlist for top sourcefile
* @param files internal data of simplecpp
* @param filedata output from simplecpp::load()
* @param dui defines, undefs, and include paths
* @param outputList output: list that will receive output messages
* @param macroUsage output: macro usage
* @param ifCond output: #if/#elif expressions
*/
SIMPLECPP_LIB void preprocess(TokenList &output, const TokenList &rawtokens, std::vector<std::string> &files, std::map<std::string, TokenList*> &filedata, const DUI &dui, OutputList *outputList = nullptr, std::list<MacroUsage> *macroUsage = nullptr, std::list<IfCond> *ifCond = nullptr);
/**
* Deallocate data
*/
SIMPLECPP_LIB void cleanup(std::map<std::string, TokenList*> &filedata);
/** Simplify path */
SIMPLECPP_LIB std::string simplifyPath(std::string path);
/** Convert Cygwin path to Windows path */
SIMPLECPP_LIB std::string convertCygwinToWindowsPath(const std::string &cygwinPath);
/** Returns the C version a given standard */
SIMPLECPP_LIB cstd_t getCStd(const std::string &std);
/** Returns the C++ version a given standard */
SIMPLECPP_LIB cppstd_t getCppStd(const std::string &std);
/** Returns the __STDC_VERSION__ value for a given standard */
SIMPLECPP_LIB std::string getCStdString(const std::string &std);
SIMPLECPP_LIB std::string getCStdString(cstd_t std);
/** Returns the __cplusplus value for a given standard */
SIMPLECPP_LIB std::string getCppStdString(const std::string &std);
SIMPLECPP_LIB std::string getCppStdString(cppstd_t std);
}
#if defined(_MSC_VER)
# pragma warning(pop)
#endif
#if (__cplusplus < 201103L) && !defined(__APPLE__)
#undef nullptr
#endif
#endif
| null |
797 | cpp | cppcheck | simplecpp.cpp | externals/simplecpp/simplecpp.cpp | null | /*
* simplecpp - A simple and high-fidelity C/C++ preprocessor library
* Copyright (C) 2016-2023 simplecpp team
*/
#if defined(_WIN32) || defined(__CYGWIN__) || defined(__MINGW32__)
#define SIMPLECPP_WINDOWS
#define NOMINMAX
#endif
#include "simplecpp.h"
#include <algorithm>
#include <cassert>
#include <cctype>
#include <climits>
#include <cstddef> // IWYU pragma: keep
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <exception>
#include <fstream>
#include <iostream>
#include <istream>
#include <limits>
#include <list>
#include <map>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <string>
#if __cplusplus >= 201103L
#ifdef SIMPLECPP_WINDOWS
#include <mutex>
#endif
#include <unordered_map>
#endif
#include <utility>
#include <vector>
#ifdef SIMPLECPP_WINDOWS
#include <windows.h>
#undef ERROR
#endif
#if __cplusplus >= 201103L
#define OVERRIDE override
#define EXPLICIT explicit
#else
#define OVERRIDE
#define EXPLICIT
#endif
#if (__cplusplus < 201103L) && !defined(__APPLE__)
#define nullptr NULL
#endif
static bool isHex(const std::string &s)
{
return s.size()>2 && (s.compare(0,2,"0x")==0 || s.compare(0,2,"0X")==0);
}
static bool isOct(const std::string &s)
{
return s.size()>1 && (s[0]=='0') && (s[1] >= '0') && (s[1] < '8');
}
// TODO: added an undercore since this conflicts with a function of the same name in utils.h from Cppcheck source when building Cppcheck with MSBuild
static bool isStringLiteral_(const std::string &s)
{
return s.size() > 1 && (s[0]=='\"') && (*s.rbegin()=='\"');
}
// TODO: added an undercore since this conflicts with a function of the same name in utils.h from Cppcheck source when building Cppcheck with MSBuild
static bool isCharLiteral_(const std::string &s)
{
// char literal patterns can include 'a', '\t', '\000', '\xff', 'abcd', and maybe ''
// This only checks for the surrounding '' but doesn't parse the content.
return s.size() > 1 && (s[0]=='\'') && (*s.rbegin()=='\'');
}
static const simplecpp::TokenString DEFINE("define");
static const simplecpp::TokenString UNDEF("undef");
static const simplecpp::TokenString INCLUDE("include");
static const simplecpp::TokenString ERROR("error");
static const simplecpp::TokenString WARNING("warning");
static const simplecpp::TokenString IF("if");
static const simplecpp::TokenString IFDEF("ifdef");
static const simplecpp::TokenString IFNDEF("ifndef");
static const simplecpp::TokenString DEFINED("defined");
static const simplecpp::TokenString ELSE("else");
static const simplecpp::TokenString ELIF("elif");
static const simplecpp::TokenString ENDIF("endif");
static const simplecpp::TokenString PRAGMA("pragma");
static const simplecpp::TokenString ONCE("once");
static const simplecpp::TokenString HAS_INCLUDE("__has_include");
template<class T> static std::string toString(T t)
{
// NOLINTNEXTLINE(misc-const-correctness) - false positive
std::ostringstream ostr;
ostr << t;
return ostr.str();
}
#ifdef SIMPLECPP_DEBUG_MACRO_EXPANSION
static std::string locstring(const simplecpp::Location &loc)
{
std::ostringstream ostr;
ostr << '[' << loc.file() << ':' << loc.line << ':' << loc.col << ']';
return ostr.str();
}
#endif
static long long stringToLL(const std::string &s)
{
long long ret;
const bool hex = isHex(s);
const bool oct = isOct(s);
std::istringstream istr(hex ? s.substr(2) : oct ? s.substr(1) : s);
if (hex)
istr >> std::hex;
else if (oct)
istr >> std::oct;
istr >> ret;
return ret;
}
static unsigned long long stringToULL(const std::string &s)
{
unsigned long long ret;
const bool hex = isHex(s);
const bool oct = isOct(s);
std::istringstream istr(hex ? s.substr(2) : oct ? s.substr(1) : s);
if (hex)
istr >> std::hex;
else if (oct)
istr >> std::oct;
istr >> ret;
return ret;
}
static bool endsWith(const std::string &s, const std::string &e)
{
return (s.size() >= e.size()) && std::equal(e.rbegin(), e.rend(), s.rbegin());
}
static bool sameline(const simplecpp::Token *tok1, const simplecpp::Token *tok2)
{
return tok1 && tok2 && tok1->location.sameline(tok2->location);
}
static bool isAlternativeBinaryOp(const simplecpp::Token *tok, const std::string &alt)
{
return (tok->name &&
tok->str() == alt &&
tok->previous &&
tok->next &&
(tok->previous->number || tok->previous->name || tok->previous->op == ')') &&
(tok->next->number || tok->next->name || tok->next->op == '('));
}
static bool isAlternativeUnaryOp(const simplecpp::Token *tok, const std::string &alt)
{
return ((tok->name && tok->str() == alt) &&
(!tok->previous || tok->previous->op == '(') &&
(tok->next && (tok->next->name || tok->next->number)));
}
static std::string replaceAll(std::string s, const std::string& from, const std::string& to)
{
for (size_t pos = s.find(from); pos != std::string::npos; pos = s.find(from, pos + to.size()))
s.replace(pos, from.size(), to);
return s;
}
const std::string simplecpp::Location::emptyFileName;
void simplecpp::Location::adjust(const std::string &str)
{
if (strpbrk(str.c_str(), "\r\n") == nullptr) {
col += str.size();
return;
}
for (std::size_t i = 0U; i < str.size(); ++i) {
col++;
if (str[i] == '\n' || str[i] == '\r') {
col = 1;
line++;
if (str[i] == '\r' && (i+1)<str.size() && str[i+1]=='\n')
++i;
}
}
}
bool simplecpp::Token::isOneOf(const char ops[]) const
{
return (op != '\0') && (std::strchr(ops, op) != nullptr);
}
bool simplecpp::Token::startsWithOneOf(const char c[]) const
{
return std::strchr(c, string[0]) != nullptr;
}
bool simplecpp::Token::endsWithOneOf(const char c[]) const
{
return std::strchr(c, string[string.size() - 1U]) != nullptr;
}
void simplecpp::Token::printAll() const
{
const Token *tok = this;
while (tok->previous)
tok = tok->previous;
for (; tok; tok = tok->next) {
if (tok->previous) {
std::cout << (sameline(tok, tok->previous) ? ' ' : '\n');
}
std::cout << tok->str();
}
std::cout << std::endl;
}
void simplecpp::Token::printOut() const
{
for (const Token *tok = this; tok; tok = tok->next) {
if (tok != this) {
std::cout << (sameline(tok, tok->previous) ? ' ' : '\n');
}
std::cout << tok->str();
}
std::cout << std::endl;
}
// cppcheck-suppress noConstructor - we call init() in the inherited to initialize the private members
class simplecpp::TokenList::Stream {
public:
virtual ~Stream() {}
virtual int get() = 0;
virtual int peek() = 0;
virtual void unget() = 0;
virtual bool good() = 0;
unsigned char readChar() {
unsigned char ch = static_cast<unsigned char>(get());
// For UTF-16 encoded files the BOM is 0xfeff/0xfffe. If the
// character is non-ASCII character then replace it with 0xff
if (isUtf16) {
const unsigned char ch2 = static_cast<unsigned char>(get());
const int ch16 = makeUtf16Char(ch, ch2);
ch = static_cast<unsigned char>(((ch16 >= 0x80) ? 0xff : ch16));
}
// Handling of newlines..
if (ch == '\r') {
ch = '\n';
int ch2 = get();
if (isUtf16) {
const int c2 = get();
ch2 = makeUtf16Char(ch2, c2);
}
if (ch2 != '\n')
ungetChar();
}
return ch;
}
unsigned char peekChar() {
unsigned char ch = static_cast<unsigned char>(peek());
// For UTF-16 encoded files the BOM is 0xfeff/0xfffe. If the
// character is non-ASCII character then replace it with 0xff
if (isUtf16) {
(void)get();
const unsigned char ch2 = static_cast<unsigned char>(peek());
unget();
const int ch16 = makeUtf16Char(ch, ch2);
ch = static_cast<unsigned char>(((ch16 >= 0x80) ? 0xff : ch16));
}
// Handling of newlines..
if (ch == '\r')
ch = '\n';
return ch;
}
void ungetChar() {
unget();
if (isUtf16)
unget();
}
protected:
void init() {
// initialize since we use peek() in getAndSkipBOM()
isUtf16 = false;
bom = getAndSkipBOM();
isUtf16 = (bom == 0xfeff || bom == 0xfffe);
}
private:
inline int makeUtf16Char(const unsigned char ch, const unsigned char ch2) const {
return (bom == 0xfeff) ? (ch<<8 | ch2) : (ch2<<8 | ch);
}
unsigned short getAndSkipBOM() {
const int ch1 = peek();
// The UTF-16 BOM is 0xfffe or 0xfeff.
if (ch1 >= 0xfe) {
(void)get();
const unsigned short byte = (static_cast<unsigned char>(ch1) << 8);
if (peek() >= 0xfe)
return byte | static_cast<unsigned char>(get());
unget();
return 0;
}
// Skip UTF-8 BOM 0xefbbbf
if (ch1 == 0xef) {
(void)get();
if (peek() == 0xbb) {
(void)get();
if (peek() == 0xbf) {
(void)get();
return 0;
}
unget();
}
unget();
}
return 0;
}
unsigned short bom;
protected:
bool isUtf16;
};
class StdIStream : public simplecpp::TokenList::Stream {
public:
// cppcheck-suppress uninitDerivedMemberVar - we call Stream::init() to initialize the private members
EXPLICIT StdIStream(std::istream &istr)
: istr(istr) {
assert(istr.good());
init();
}
virtual int get() OVERRIDE {
return istr.get();
}
virtual int peek() OVERRIDE {
return istr.peek();
}
virtual void unget() OVERRIDE {
istr.unget();
}
virtual bool good() OVERRIDE {
return istr.good();
}
private:
std::istream &istr;
};
class StdCharBufStream : public simplecpp::TokenList::Stream {
public:
// cppcheck-suppress uninitDerivedMemberVar - we call Stream::init() to initialize the private members
StdCharBufStream(const unsigned char* str, std::size_t size)
: str(str)
, size(size)
, pos(0)
, lastStatus(0) {
init();
}
virtual int get() OVERRIDE {
if (pos >= size)
return lastStatus = EOF;
return str[pos++];
}
virtual int peek() OVERRIDE {
if (pos >= size)
return lastStatus = EOF;
return str[pos];
}
virtual void unget() OVERRIDE {
--pos;
}
virtual bool good() OVERRIDE {
return lastStatus != EOF;
}
private:
const unsigned char *str;
const std::size_t size;
std::size_t pos;
int lastStatus;
};
class FileStream : public simplecpp::TokenList::Stream {
public:
// cppcheck-suppress uninitDerivedMemberVar - we call Stream::init() to initialize the private members
EXPLICIT FileStream(const std::string &filename, std::vector<std::string> &files)
: file(fopen(filename.c_str(), "rb"))
, lastCh(0)
, lastStatus(0) {
if (!file) {
files.push_back(filename);
throw simplecpp::Output(files, simplecpp::Output::FILE_NOT_FOUND, "File is missing: " + filename);
}
init();
}
~FileStream() OVERRIDE {
fclose(file);
file = nullptr;
}
virtual int get() OVERRIDE {
lastStatus = lastCh = fgetc(file);
return lastCh;
}
virtual int peek() OVERRIDE{
// keep lastCh intact
const int ch = fgetc(file);
unget_internal(ch);
return ch;
}
virtual void unget() OVERRIDE {
unget_internal(lastCh);
}
virtual bool good() OVERRIDE {
return lastStatus != EOF;
}
private:
void unget_internal(int ch) {
if (isUtf16) {
// TODO: use ungetc() as well
// UTF-16 has subsequent unget() calls
fseek(file, -1, SEEK_CUR);
} else
ungetc(ch, file);
}
FileStream(const FileStream&);
FileStream &operator=(const FileStream&);
FILE *file;
int lastCh;
int lastStatus;
};
simplecpp::TokenList::TokenList(std::vector<std::string> &filenames) : frontToken(nullptr), backToken(nullptr), files(filenames) {}
simplecpp::TokenList::TokenList(std::istream &istr, std::vector<std::string> &filenames, const std::string &filename, OutputList *outputList)
: frontToken(nullptr), backToken(nullptr), files(filenames)
{
StdIStream stream(istr);
readfile(stream,filename,outputList);
}
simplecpp::TokenList::TokenList(const unsigned char* data, std::size_t size, std::vector<std::string> &filenames, const std::string &filename, OutputList *outputList)
: frontToken(nullptr), backToken(nullptr), files(filenames)
{
StdCharBufStream stream(data, size);
readfile(stream,filename,outputList);
}
simplecpp::TokenList::TokenList(const char* data, std::size_t size, std::vector<std::string> &filenames, const std::string &filename, OutputList *outputList)
: frontToken(nullptr), backToken(nullptr), files(filenames)
{
StdCharBufStream stream(reinterpret_cast<const unsigned char*>(data), size);
readfile(stream,filename,outputList);
}
simplecpp::TokenList::TokenList(const std::string &filename, std::vector<std::string> &filenames, OutputList *outputList)
: frontToken(nullptr), backToken(nullptr), files(filenames)
{
try {
FileStream stream(filename, filenames);
readfile(stream,filename,outputList);
} catch (const simplecpp::Output & e) { // TODO handle extra type of errors
outputList->push_back(e);
}
}
simplecpp::TokenList::TokenList(const TokenList &other) : frontToken(nullptr), backToken(nullptr), files(other.files)
{
*this = other;
}
#if __cplusplus >= 201103L
simplecpp::TokenList::TokenList(TokenList &&other) : frontToken(nullptr), backToken(nullptr), files(other.files)
{
*this = std::move(other);
}
#endif
simplecpp::TokenList::~TokenList()
{
clear();
}
simplecpp::TokenList &simplecpp::TokenList::operator=(const TokenList &other)
{
if (this != &other) {
clear();
files = other.files;
for (const Token *tok = other.cfront(); tok; tok = tok->next)
push_back(new Token(*tok));
sizeOfType = other.sizeOfType;
}
return *this;
}
#if __cplusplus >= 201103L
simplecpp::TokenList &simplecpp::TokenList::operator=(TokenList &&other)
{
if (this != &other) {
clear();
frontToken = other.frontToken;
other.frontToken = nullptr;
backToken = other.backToken;
other.backToken = nullptr;
files = other.files;
sizeOfType = std::move(other.sizeOfType);
}
return *this;
}
#endif
void simplecpp::TokenList::clear()
{
backToken = nullptr;
while (frontToken) {
Token * const next = frontToken->next;
delete frontToken;
frontToken = next;
}
sizeOfType.clear();
}
void simplecpp::TokenList::push_back(Token *tok)
{
if (!frontToken)
frontToken = tok;
else
backToken->next = tok;
tok->previous = backToken;
backToken = tok;
}
void simplecpp::TokenList::dump() const
{
std::cout << stringify() << std::endl;
}
std::string simplecpp::TokenList::stringify() const
{
std::ostringstream ret;
Location loc(files);
for (const Token *tok = cfront(); tok; tok = tok->next) {
if (tok->location.line < loc.line || tok->location.fileIndex != loc.fileIndex) {
ret << "\n#line " << tok->location.line << " \"" << tok->location.file() << "\"\n";
loc = tok->location;
}
while (tok->location.line > loc.line) {
ret << '\n';
loc.line++;
}
if (sameline(tok->previous, tok))
ret << ' ';
ret << tok->str();
loc.adjust(tok->str());
}
return ret.str();
}
static bool isNameChar(unsigned char ch)
{
return std::isalnum(ch) || ch == '_' || ch == '$';
}
static std::string escapeString(const std::string &str)
{
std::ostringstream ostr;
ostr << '\"';
for (std::size_t i = 1U; i < str.size() - 1; ++i) {
const char c = str[i];
if (c == '\\' || c == '\"' || c == '\'')
ostr << '\\';
ostr << c;
}
ostr << '\"';
return ostr.str();
}
static void portabilityBackslash(simplecpp::OutputList *outputList, const std::vector<std::string> &files, const simplecpp::Location &location)
{
if (!outputList)
return;
simplecpp::Output err(files);
err.type = simplecpp::Output::PORTABILITY_BACKSLASH;
err.location = location;
err.msg = "Combination 'backslash space newline' is not portable.";
outputList->push_back(err);
}
static bool isStringLiteralPrefix(const std::string &str)
{
return str == "u" || str == "U" || str == "L" || str == "u8" ||
str == "R" || str == "uR" || str == "UR" || str == "LR" || str == "u8R";
}
void simplecpp::TokenList::lineDirective(unsigned int fileIndex, unsigned int line, Location *location)
{
if (fileIndex != location->fileIndex || line >= location->line) {
location->fileIndex = fileIndex;
location->line = line;
return;
}
if (line + 2 >= location->line) {
location->line = line;
while (cback()->op != '#')
deleteToken(back());
deleteToken(back());
return;
}
}
static const std::string COMMENT_END("*/");
void simplecpp::TokenList::readfile(Stream &stream, const std::string &filename, OutputList *outputList)
{
std::stack<simplecpp::Location> loc;
unsigned int multiline = 0U;
const Token *oldLastToken = nullptr;
Location location(files);
location.fileIndex = fileIndex(filename);
location.line = 1U;
location.col = 1U;
while (stream.good()) {
unsigned char ch = stream.readChar();
if (!stream.good())
break;
if (ch >= 0x80) {
if (outputList) {
simplecpp::Output err(files);
err.type = simplecpp::Output::UNHANDLED_CHAR_ERROR;
err.location = location;
std::ostringstream s;
s << static_cast<int>(ch);
err.msg = "The code contains unhandled character(s) (character code=" + s.str() + "). Neither unicode nor extended ascii is supported.";
outputList->push_back(err);
}
clear();
return;
}
if (ch == '\n') {
if (cback() && cback()->op == '\\') {
if (location.col > cback()->location.col + 1U)
portabilityBackslash(outputList, files, cback()->location);
++multiline;
deleteToken(back());
} else {
location.line += multiline + 1;
multiline = 0U;
}
if (!multiline)
location.col = 1;
if (oldLastToken != cback()) {
oldLastToken = cback();
if (!isLastLinePreprocessor())
continue;
const std::string lastline(lastLine());
if (lastline == "# file %str%") {
const Token *strtok = cback();
while (strtok->comment)
strtok = strtok->previous;
loc.push(location);
location.fileIndex = fileIndex(strtok->str().substr(1U, strtok->str().size() - 2U));
location.line = 1U;
} else if (lastline == "# line %num%") {
const Token *numtok = cback();
while (numtok->comment)
numtok = numtok->previous;
lineDirective(location.fileIndex, std::atol(numtok->str().c_str()), &location);
} else if (lastline == "# %num% %str%" || lastline == "# line %num% %str%") {
const Token *strtok = cback();
while (strtok->comment)
strtok = strtok->previous;
const Token *numtok = strtok->previous;
while (numtok->comment)
numtok = numtok->previous;
lineDirective(fileIndex(replaceAll(strtok->str().substr(1U, strtok->str().size() - 2U),"\\\\","\\")),
std::atol(numtok->str().c_str()), &location);
}
// #endfile
else if (lastline == "# endfile" && !loc.empty()) {
location = loc.top();
loc.pop();
}
}
continue;
}
if (ch <= ' ') {
location.col++;
continue;
}
TokenString currentToken;
if (cback() && cback()->location.line == location.line && cback()->previous && cback()->previous->op == '#') {
const Token* const llTok = lastLineTok();
if (llTok && llTok->op == '#' && llTok->next && (llTok->next->str() == "error" || llTok->next->str() == "warning")) {
char prev = ' ';
while (stream.good() && (prev == '\\' || (ch != '\r' && ch != '\n'))) {
currentToken += ch;
prev = ch;
ch = stream.readChar();
}
stream.ungetChar();
push_back(new Token(currentToken, location));
location.adjust(currentToken);
continue;
}
}
// number or name
if (isNameChar(ch)) {
const bool num = std::isdigit(ch);
while (stream.good() && isNameChar(ch)) {
currentToken += ch;
ch = stream.readChar();
if (num && ch=='\'' && isNameChar(stream.peekChar()))
ch = stream.readChar();
}
stream.ungetChar();
}
// comment
else if (ch == '/' && stream.peekChar() == '/') {
while (stream.good() && ch != '\r' && ch != '\n') {
currentToken += ch;
ch = stream.readChar();
}
const std::string::size_type pos = currentToken.find_last_not_of(" \t");
if (pos < currentToken.size() - 1U && currentToken[pos] == '\\')
portabilityBackslash(outputList, files, location);
if (currentToken[currentToken.size() - 1U] == '\\') {
++multiline;
currentToken.erase(currentToken.size() - 1U);
} else {
stream.ungetChar();
}
}
// comment
else if (ch == '/' && stream.peekChar() == '*') {
currentToken = "/*";
(void)stream.readChar();
ch = stream.readChar();
while (stream.good()) {
currentToken += ch;
if (currentToken.size() >= 4U && endsWith(currentToken, COMMENT_END))
break;
ch = stream.readChar();
}
// multiline..
std::string::size_type pos = 0;
while ((pos = currentToken.find("\\\n",pos)) != std::string::npos) {
currentToken.erase(pos,2);
++multiline;
}
if (multiline || isLastLinePreprocessor()) {
pos = 0;
while ((pos = currentToken.find('\n',pos)) != std::string::npos) {
currentToken.erase(pos,1);
++multiline;
}
}
}
// string / char literal
else if (ch == '\"' || ch == '\'') {
std::string prefix;
if (cback() && cback()->name && isStringLiteralPrefix(cback()->str()) &&
((cback()->location.col + cback()->str().size()) == location.col) &&
(cback()->location.line == location.line)) {
prefix = cback()->str();
}
// C++11 raw string literal
if (ch == '\"' && !prefix.empty() && *cback()->str().rbegin() == 'R') {
std::string delim;
currentToken = ch;
prefix.resize(prefix.size() - 1);
ch = stream.readChar();
while (stream.good() && ch != '(' && ch != '\n') {
delim += ch;
ch = stream.readChar();
}
if (!stream.good() || ch == '\n') {
if (outputList) {
Output err(files);
err.type = Output::SYNTAX_ERROR;
err.location = location;
err.msg = "Invalid newline in raw string delimiter.";
outputList->push_back(err);
}
return;
}
const std::string endOfRawString(')' + delim + currentToken);
while (stream.good() && !(endsWith(currentToken, endOfRawString) && currentToken.size() > 1))
currentToken += stream.readChar();
if (!endsWith(currentToken, endOfRawString)) {
if (outputList) {
Output err(files);
err.type = Output::SYNTAX_ERROR;
err.location = location;
err.msg = "Raw string missing terminating delimiter.";
outputList->push_back(err);
}
return;
}
currentToken.erase(currentToken.size() - endOfRawString.size(), endOfRawString.size() - 1U);
currentToken = escapeString(currentToken);
currentToken.insert(0, prefix);
back()->setstr(currentToken);
location.adjust(currentToken);
if (currentToken.find_first_of("\r\n") == std::string::npos)
location.col += 2 + 2 * delim.size();
else
location.col += 1 + delim.size();
continue;
}
currentToken = readUntil(stream,location,ch,ch,outputList);
if (currentToken.size() < 2U)
// Error is reported by readUntil()
return;
std::string s = currentToken;
std::string::size_type pos;
int newlines = 0;
while ((pos = s.find_first_of("\r\n")) != std::string::npos) {
s.erase(pos,1);
newlines++;
}
if (prefix.empty())
push_back(new Token(s, location, std::isspace(stream.peekChar()))); // push string without newlines
else
back()->setstr(prefix + s);
if (newlines > 0) {
const Token * const llTok = lastLineTok();
if (llTok && llTok->op == '#' && llTok->next && (llTok->next->str() == "define" || llTok->next->str() == "pragma") && llTok->next->next) {
multiline += newlines;
location.adjust(s);
continue;
}
}
location.adjust(currentToken);
continue;
}
else {
currentToken += ch;
}
if (*currentToken.begin() == '<') {
const Token * const llTok = lastLineTok();
if (llTok && llTok->op == '#' && llTok->next && llTok->next->str() == "include") {
currentToken = readUntil(stream, location, '<', '>', outputList);
if (currentToken.size() < 2U)
return;
}
}
push_back(new Token(currentToken, location, std::isspace(stream.peekChar())));
if (multiline)
location.col += currentToken.size();
else
location.adjust(currentToken);
}
combineOperators();
}
void simplecpp::TokenList::constFold()
{
while (cfront()) {
// goto last '('
Token *tok = back();
while (tok && tok->op != '(')
tok = tok->previous;
// no '(', goto first token
if (!tok)
tok = front();
// Constant fold expression
constFoldUnaryNotPosNeg(tok);
constFoldMulDivRem(tok);
constFoldAddSub(tok);
constFoldShift(tok);
constFoldComparison(tok);
constFoldBitwise(tok);
constFoldLogicalOp(tok);
constFoldQuestionOp(&tok);
// If there is no '(' we are done with the constant folding
if (tok->op != '(')
break;
if (!tok->next || !tok->next->next || tok->next->next->op != ')')
break;
tok = tok->next;
deleteToken(tok->previous);
deleteToken(tok->next);
}
}
static bool isFloatSuffix(const simplecpp::Token *tok)
{
if (!tok || tok->str().size() != 1U)
return false;
const char c = std::tolower(tok->str()[0]);
return c == 'f' || c == 'l';
}
void simplecpp::TokenList::combineOperators()
{
std::stack<bool> executableScope;
executableScope.push(false);
for (Token *tok = front(); tok; tok = tok->next) {
if (tok->op == '{') {
if (executableScope.top()) {
executableScope.push(true);
continue;
}
const Token *prev = tok->previous;
while (prev && prev->isOneOf(";{}()"))
prev = prev->previous;
executableScope.push(prev && prev->op == ')');
continue;
}
if (tok->op == '}') {
if (executableScope.size() > 1)
executableScope.pop();
continue;
}
if (tok->op == '.') {
// ellipsis ...
if (tok->next && tok->next->op == '.' && tok->next->location.col == (tok->location.col + 1) &&
tok->next->next && tok->next->next->op == '.' && tok->next->next->location.col == (tok->location.col + 2)) {
tok->setstr("...");
deleteToken(tok->next);
deleteToken(tok->next);
continue;
}
// float literals..
if (tok->previous && tok->previous->number && sameline(tok->previous, tok) && tok->previous->str().find_first_of("._") == std::string::npos) {
tok->setstr(tok->previous->str() + '.');
deleteToken(tok->previous);
if (sameline(tok, tok->next) && (isFloatSuffix(tok->next) || (tok->next && tok->next->startsWithOneOf("AaBbCcDdEeFfPp")))) {
tok->setstr(tok->str() + tok->next->str());
deleteToken(tok->next);
}
}
if (tok->next && tok->next->number) {
tok->setstr(tok->str() + tok->next->str());
deleteToken(tok->next);
}
}
// match: [0-9.]+E [+-] [0-9]+
const char lastChar = tok->str()[tok->str().size() - 1];
if (tok->number && !isOct(tok->str()) &&
((!isHex(tok->str()) && (lastChar == 'E' || lastChar == 'e')) ||
(isHex(tok->str()) && (lastChar == 'P' || lastChar == 'p'))) &&
tok->next && tok->next->isOneOf("+-") && tok->next->next && tok->next->next->number) {
tok->setstr(tok->str() + tok->next->op + tok->next->next->str());
deleteToken(tok->next);
deleteToken(tok->next);
}
if (tok->op == '\0' || !tok->next || tok->next->op == '\0')
continue;
if (!sameline(tok,tok->next))
continue;
if (tok->location.col + 1U != tok->next->location.col)
continue;
if (tok->next->op == '=' && tok->isOneOf("=!<>+-*/%&|^")) {
if (tok->op == '&' && !executableScope.top()) {
// don't combine &= if it is a anonymous reference parameter with default value:
// void f(x&=2)
int indentlevel = 0;
const Token *start = tok;
while (indentlevel >= 0 && start) {
if (start->op == ')')
++indentlevel;
else if (start->op == '(')
--indentlevel;
else if (start->isOneOf(";{}"))
break;
start = start->previous;
}
if (indentlevel == -1 && start) {
const Token * const ftok = start;
bool isFuncDecl = ftok->name;
while (isFuncDecl) {
if (!start->name && start->str() != "::" && start->op != '*' && start->op != '&')
isFuncDecl = false;
if (!start->previous)
break;
if (start->previous->isOneOf(";{}:"))
break;
start = start->previous;
}
isFuncDecl &= start != ftok && start->name;
if (isFuncDecl) {
// TODO: we could loop through the parameters here and check if they are correct.
continue;
}
}
}
tok->setstr(tok->str() + "=");
deleteToken(tok->next);
} else if ((tok->op == '|' || tok->op == '&') && tok->op == tok->next->op) {
tok->setstr(tok->str() + tok->next->str());
deleteToken(tok->next);
} else if (tok->op == ':' && tok->next->op == ':') {
tok->setstr(tok->str() + tok->next->str());
deleteToken(tok->next);
} else if (tok->op == '-' && tok->next->op == '>') {
tok->setstr(tok->str() + tok->next->str());
deleteToken(tok->next);
} else if ((tok->op == '<' || tok->op == '>') && tok->op == tok->next->op) {
tok->setstr(tok->str() + tok->next->str());
deleteToken(tok->next);
if (tok->next && tok->next->op == '=' && tok->next->next && tok->next->next->op != '=') {
tok->setstr(tok->str() + tok->next->str());
deleteToken(tok->next);
}
} else if ((tok->op == '+' || tok->op == '-') && tok->op == tok->next->op) {
if (tok->location.col + 1U != tok->next->location.col)
continue;
if (tok->previous && tok->previous->number)
continue;
if (tok->next->next && tok->next->next->number)
continue;
tok->setstr(tok->str() + tok->next->str());
deleteToken(tok->next);
}
}
}
static const std::string COMPL("compl");
static const std::string NOT("not");
void simplecpp::TokenList::constFoldUnaryNotPosNeg(simplecpp::Token *tok)
{
for (; tok && tok->op != ')'; tok = tok->next) {
// "not" might be !
if (isAlternativeUnaryOp(tok, NOT))
tok->op = '!';
// "compl" might be ~
else if (isAlternativeUnaryOp(tok, COMPL))
tok->op = '~';
if (tok->op == '!' && tok->next && tok->next->number) {
tok->setstr(tok->next->str() == "0" ? "1" : "0");
deleteToken(tok->next);
} else if (tok->op == '~' && tok->next && tok->next->number) {
tok->setstr(toString(~stringToLL(tok->next->str())));
deleteToken(tok->next);
} else {
if (tok->previous && (tok->previous->number || tok->previous->name))
continue;
if (!tok->next || !tok->next->number)
continue;
switch (tok->op) {
case '+':
tok->setstr(tok->next->str());
deleteToken(tok->next);
break;
case '-':
tok->setstr(tok->op + tok->next->str());
deleteToken(tok->next);
break;
}
}
}
}
void simplecpp::TokenList::constFoldMulDivRem(Token *tok)
{
for (; tok && tok->op != ')'; tok = tok->next) {
if (!tok->previous || !tok->previous->number)
continue;
if (!tok->next || !tok->next->number)
continue;
long long result;
if (tok->op == '*')
result = (stringToLL(tok->previous->str()) * stringToLL(tok->next->str()));
else if (tok->op == '/' || tok->op == '%') {
const long long rhs = stringToLL(tok->next->str());
if (rhs == 0)
throw std::overflow_error("division/modulo by zero");
const long long lhs = stringToLL(tok->previous->str());
if (rhs == -1 && lhs == std::numeric_limits<long long>::min())
throw std::overflow_error("division overflow");
if (tok->op == '/')
result = (lhs / rhs);
else
result = (lhs % rhs);
} else
continue;
tok = tok->previous;
tok->setstr(toString(result));
deleteToken(tok->next);
deleteToken(tok->next);
}
}
void simplecpp::TokenList::constFoldAddSub(Token *tok)
{
for (; tok && tok->op != ')'; tok = tok->next) {
if (!tok->previous || !tok->previous->number)
continue;
if (!tok->next || !tok->next->number)
continue;
long long result;
if (tok->op == '+')
result = stringToLL(tok->previous->str()) + stringToLL(tok->next->str());
else if (tok->op == '-')
result = stringToLL(tok->previous->str()) - stringToLL(tok->next->str());
else
continue;
tok = tok->previous;
tok->setstr(toString(result));
deleteToken(tok->next);
deleteToken(tok->next);
}
}
void simplecpp::TokenList::constFoldShift(Token *tok)
{
for (; tok && tok->op != ')'; tok = tok->next) {
if (!tok->previous || !tok->previous->number)
continue;
if (!tok->next || !tok->next->number)
continue;
long long result;
if (tok->str() == "<<")
result = stringToLL(tok->previous->str()) << stringToLL(tok->next->str());
else if (tok->str() == ">>")
result = stringToLL(tok->previous->str()) >> stringToLL(tok->next->str());
else
continue;
tok = tok->previous;
tok->setstr(toString(result));
deleteToken(tok->next);
deleteToken(tok->next);
}
}
static const std::string NOTEQ("not_eq");
void simplecpp::TokenList::constFoldComparison(Token *tok)
{
for (; tok && tok->op != ')'; tok = tok->next) {
if (isAlternativeBinaryOp(tok,NOTEQ))
tok->setstr("!=");
if (!tok->startsWithOneOf("<>=!"))
continue;
if (!tok->previous || !tok->previous->number)
continue;
if (!tok->next || !tok->next->number)
continue;
int result;
if (tok->str() == "==")
result = (stringToLL(tok->previous->str()) == stringToLL(tok->next->str()));
else if (tok->str() == "!=")
result = (stringToLL(tok->previous->str()) != stringToLL(tok->next->str()));
else if (tok->str() == ">")
result = (stringToLL(tok->previous->str()) > stringToLL(tok->next->str()));
else if (tok->str() == ">=")
result = (stringToLL(tok->previous->str()) >= stringToLL(tok->next->str()));
else if (tok->str() == "<")
result = (stringToLL(tok->previous->str()) < stringToLL(tok->next->str()));
else if (tok->str() == "<=")
result = (stringToLL(tok->previous->str()) <= stringToLL(tok->next->str()));
else
continue;
tok = tok->previous;
tok->setstr(toString(result));
deleteToken(tok->next);
deleteToken(tok->next);
}
}
static const std::string BITAND("bitand");
static const std::string BITOR("bitor");
static const std::string XOR("xor");
void simplecpp::TokenList::constFoldBitwise(Token *tok)
{
Token * const tok1 = tok;
for (const char *op = "&^|"; *op; op++) {
const std::string* alternativeOp;
if (*op == '&')
alternativeOp = &BITAND;
else if (*op == '|')
alternativeOp = &BITOR;
else
alternativeOp = &XOR;
for (tok = tok1; tok && tok->op != ')'; tok = tok->next) {
if (tok->op != *op && !isAlternativeBinaryOp(tok, *alternativeOp))
continue;
if (!tok->previous || !tok->previous->number)
continue;
if (!tok->next || !tok->next->number)
continue;
long long result;
if (*op == '&')
result = (stringToLL(tok->previous->str()) & stringToLL(tok->next->str()));
else if (*op == '^')
result = (stringToLL(tok->previous->str()) ^ stringToLL(tok->next->str()));
else /*if (*op == '|')*/
result = (stringToLL(tok->previous->str()) | stringToLL(tok->next->str()));
tok = tok->previous;
tok->setstr(toString(result));
deleteToken(tok->next);
deleteToken(tok->next);
}
}
}
static const std::string AND("and");
static const std::string OR("or");
void simplecpp::TokenList::constFoldLogicalOp(Token *tok)
{
for (; tok && tok->op != ')'; tok = tok->next) {
if (tok->name) {
if (isAlternativeBinaryOp(tok,AND))
tok->setstr("&&");
else if (isAlternativeBinaryOp(tok,OR))
tok->setstr("||");
}
if (tok->str() != "&&" && tok->str() != "||")
continue;
if (!tok->previous || !tok->previous->number)
continue;
if (!tok->next || !tok->next->number)
continue;
int result;
if (tok->str() == "||")
result = (stringToLL(tok->previous->str()) || stringToLL(tok->next->str()));
else /*if (tok->str() == "&&")*/
result = (stringToLL(tok->previous->str()) && stringToLL(tok->next->str()));
tok = tok->previous;
tok->setstr(toString(result));
deleteToken(tok->next);
deleteToken(tok->next);
}
}
void simplecpp::TokenList::constFoldQuestionOp(Token **tok1)
{
bool gotoTok1 = false;
for (Token *tok = *tok1; tok && tok->op != ')'; tok = gotoTok1 ? *tok1 : tok->next) {
gotoTok1 = false;
if (tok->str() != "?")
continue;
if (!tok->previous || !tok->next || !tok->next->next)
throw std::runtime_error("invalid expression");
if (!tok->previous->number)
continue;
if (tok->next->next->op != ':')
continue;
Token * const condTok = tok->previous;
Token * const trueTok = tok->next;
Token * const falseTok = trueTok->next->next;
if (!falseTok)
throw std::runtime_error("invalid expression");
if (condTok == *tok1)
*tok1 = (condTok->str() != "0" ? trueTok : falseTok);
deleteToken(condTok->next); // ?
deleteToken(trueTok->next); // :
deleteToken(condTok->str() == "0" ? trueTok : falseTok);
deleteToken(condTok);
gotoTok1 = true;
}
}
void simplecpp::TokenList::removeComments()
{
Token *tok = frontToken;
while (tok) {
Token * const tok1 = tok;
tok = tok->next;
if (tok1->comment)
deleteToken(tok1);
}
}
std::string simplecpp::TokenList::readUntil(Stream &stream, const Location &location, const char start, const char end, OutputList *outputList)
{
std::string ret;
ret += start;
bool backslash = false;
char ch = 0;
while (ch != end && ch != '\r' && ch != '\n' && stream.good()) {
ch = stream.readChar();
if (backslash && ch == '\n') {
ch = 0;
backslash = false;
continue;
}
backslash = false;
ret += ch;
if (ch == '\\') {
bool update_ch = false;
char next = 0;
do {
next = stream.readChar();
if (next == '\r' || next == '\n') {
ret.erase(ret.size()-1U);
backslash = (next == '\r');
update_ch = false;
} else if (next == '\\')
update_ch = !update_ch;
ret += next;
} while (next == '\\');
if (update_ch)
ch = next;
}
}
if (!stream.good() || ch != end) {
clear();
if (outputList) {
Output err(files);
err.type = Output::SYNTAX_ERROR;
err.location = location;
err.msg = std::string("No pair for character (") + start + "). Can't process file. File is either invalid or unicode, which is currently not supported.";
outputList->push_back(err);
}
return "";
}
return ret;
}
std::string simplecpp::TokenList::lastLine(int maxsize) const
{
std::string ret;
int count = 0;
for (const Token *tok = cback(); ; tok = tok->previous) {
if (!sameline(tok, cback())) {
break;
}
if (tok->comment)
continue;
if (++count > maxsize)
return "";
if (!ret.empty())
ret += ' ';
// add tokens in reverse for performance reasons
if (tok->str()[0] == '\"')
ret += "%rts%"; // %str%
else if (tok->number)
ret += "%mun%"; // %num%
else {
ret += tok->str();
std::reverse(ret.end() - tok->str().length(), ret.end());
}
}
std::reverse(ret.begin(), ret.end());
return ret;
}
const simplecpp::Token* simplecpp::TokenList::lastLineTok(int maxsize) const
{
const Token* prevTok = nullptr;
int count = 0;
for (const Token *tok = cback(); ; tok = tok->previous) {
if (!sameline(tok, cback()))
break;
if (tok->comment)
continue;
if (++count > maxsize)
return nullptr;
prevTok = tok;
}
return prevTok;
}
bool simplecpp::TokenList::isLastLinePreprocessor(int maxsize) const
{
const Token * const prevTok = lastLineTok(maxsize);
return prevTok && prevTok->op == '#';
}
unsigned int simplecpp::TokenList::fileIndex(const std::string &filename)
{
for (unsigned int i = 0; i < files.size(); ++i) {
if (files[i] == filename)
return i;
}
files.push_back(filename);
return files.size() - 1U;
}
namespace simplecpp {
class Macro;
#if __cplusplus >= 201103L
using MacroMap = std::unordered_map<TokenString,Macro>;
#else
typedef std::map<TokenString,Macro> MacroMap;
#endif
class Macro {
public:
explicit Macro(std::vector<std::string> &f) : nameTokDef(nullptr), valueToken(nullptr), endToken(nullptr), files(f), tokenListDefine(f), variadic(false), valueDefinedInCode_(false) {}
Macro(const Token *tok, std::vector<std::string> &f) : nameTokDef(nullptr), files(f), tokenListDefine(f), valueDefinedInCode_(true) {
if (sameline(tok->previousSkipComments(), tok))
throw std::runtime_error("bad macro syntax");
if (tok->op != '#')
throw std::runtime_error("bad macro syntax");
const Token * const hashtok = tok;
tok = tok->next;
if (!tok || tok->str() != DEFINE)
throw std::runtime_error("bad macro syntax");
tok = tok->next;
if (!tok || !tok->name || !sameline(hashtok,tok))
throw std::runtime_error("bad macro syntax");
if (!parseDefine(tok))
throw std::runtime_error("bad macro syntax");
}
Macro(const std::string &name, const std::string &value, std::vector<std::string> &f) : nameTokDef(nullptr), files(f), tokenListDefine(f), valueDefinedInCode_(false) {
const std::string def(name + ' ' + value);
StdCharBufStream stream(reinterpret_cast<const unsigned char*>(def.data()), def.size());
tokenListDefine.readfile(stream);
if (!parseDefine(tokenListDefine.cfront()))
throw std::runtime_error("bad macro syntax. macroname=" + name + " value=" + value);
}
Macro(const Macro &other) : nameTokDef(nullptr), files(other.files), tokenListDefine(other.files), valueDefinedInCode_(other.valueDefinedInCode_) {
*this = other;
}
Macro &operator=(const Macro &other) {
if (this != &other) {
files = other.files;
valueDefinedInCode_ = other.valueDefinedInCode_;
if (other.tokenListDefine.empty())
parseDefine(other.nameTokDef);
else {
tokenListDefine = other.tokenListDefine;
parseDefine(tokenListDefine.cfront());
}
usageList = other.usageList;
}
return *this;
}
bool valueDefinedInCode() const {
return valueDefinedInCode_;
}
/**
* Expand macro. This will recursively expand inner macros.
* @param output destination tokenlist
* @param rawtok macro token
* @param macros list of macros
* @param inputFiles the input files
* @return token after macro
* @throw Can throw wrongNumberOfParameters or invalidHashHash
*/
const Token * expand(TokenList * const output,
const Token * rawtok,
const MacroMap ¯os,
std::vector<std::string> &inputFiles) const {
std::set<TokenString> expandedmacros;
#ifdef SIMPLECPP_DEBUG_MACRO_EXPANSION
std::cout << "expand " << name() << " " << locstring(rawtok->location) << std::endl;
#endif
TokenList output2(inputFiles);
if (functionLike() && rawtok->next && rawtok->next->op == '(') {
// Copy macro call to a new tokenlist with no linebreaks
const Token * const rawtok1 = rawtok;
TokenList rawtokens2(inputFiles);
rawtokens2.push_back(new Token(rawtok->str(), rawtok1->location, rawtok->whitespaceahead));
rawtok = rawtok->next;
rawtokens2.push_back(new Token(rawtok->str(), rawtok1->location, rawtok->whitespaceahead));
rawtok = rawtok->next;
int par = 1;
while (rawtok && par > 0) {
if (rawtok->op == '(')
++par;
else if (rawtok->op == ')')
--par;
else if (rawtok->op == '#' && !sameline(rawtok->previous, rawtok))
throw Error(rawtok->location, "it is invalid to use a preprocessor directive as macro parameter");
rawtokens2.push_back(new Token(rawtok->str(), rawtok1->location, rawtok->whitespaceahead));
rawtok = rawtok->next;
}
if (expand(&output2, rawtok1->location, rawtokens2.cfront(), macros, expandedmacros))
rawtok = rawtok1->next;
} else {
rawtok = expand(&output2, rawtok->location, rawtok, macros, expandedmacros);
}
while (output2.cback() && rawtok) {
unsigned int par = 0;
Token* macro2tok = output2.back();
while (macro2tok) {
if (macro2tok->op == '(') {
if (par==0)
break;
--par;
} else if (macro2tok->op == ')')
++par;
macro2tok = macro2tok->previous;
}
if (macro2tok) { // macro2tok->op == '('
macro2tok = macro2tok->previous;
expandedmacros.insert(name());
} else if (rawtok->op == '(')
macro2tok = output2.back();
if (!macro2tok || !macro2tok->name)
break;
if (output2.cfront() != output2.cback() && macro2tok->str() == this->name())
break;
const MacroMap::const_iterator macro = macros.find(macro2tok->str());
if (macro == macros.end() || !macro->second.functionLike())
break;
TokenList rawtokens2(inputFiles);
const Location loc(macro2tok->location);
while (macro2tok) {
Token * const next = macro2tok->next;
rawtokens2.push_back(new Token(macro2tok->str(), loc));
output2.deleteToken(macro2tok);
macro2tok = next;
}
par = (rawtokens2.cfront() != rawtokens2.cback()) ? 1U : 0U;
const Token *rawtok2 = rawtok;
for (; rawtok2; rawtok2 = rawtok2->next) {
rawtokens2.push_back(new Token(rawtok2->str(), loc));
if (rawtok2->op == '(')
++par;
else if (rawtok2->op == ')') {
if (par <= 1U)
break;
--par;
}
}
if (!rawtok2 || par != 1U)
break;
if (macro->second.expand(&output2, rawtok->location, rawtokens2.cfront(), macros, expandedmacros) != nullptr)
break;
rawtok = rawtok2->next;
}
output->takeTokens(output2);
return rawtok;
}
/** macro name */
const TokenString &name() const {
return nameTokDef->str();
}
/** location for macro definition */
const Location &defineLocation() const {
return nameTokDef->location;
}
/** how has this macro been used so far */
const std::list<Location> &usage() const {
return usageList;
}
/** is this a function like macro */
bool functionLike() const {
return nameTokDef->next &&
nameTokDef->next->op == '(' &&
sameline(nameTokDef, nameTokDef->next) &&
nameTokDef->next->location.col == nameTokDef->location.col + nameTokDef->str().size();
}
/** base class for errors */
struct Error {
Error(const Location &loc, const std::string &s) : location(loc), what(s) {}
const Location location;
const std::string what;
};
/** Struct that is thrown when macro is expanded with wrong number of parameters */
struct wrongNumberOfParameters : public Error {
wrongNumberOfParameters(const Location &loc, const std::string ¯oName) : Error(loc, "Wrong number of parameters for macro \'" + macroName + "\'.") {}
};
/** Struct that is thrown when there is invalid ## usage */
struct invalidHashHash : public Error {
static inline std::string format(const std::string ¯oName, const std::string &message) {
return "Invalid ## usage when expanding \'" + macroName + "\': " + message;
}
invalidHashHash(const Location &loc, const std::string ¯oName, const std::string &message)
: Error(loc, format(macroName, message)) { }
static inline invalidHashHash unexpectedToken(const Location &loc, const std::string ¯oName, const Token *tokenA) {
return invalidHashHash(loc, macroName, "Unexpected token '"+ tokenA->str()+"'");
}
static inline invalidHashHash cannotCombine(const Location &loc, const std::string ¯oName, const Token *tokenA, const Token *tokenB) {
return invalidHashHash(loc, macroName, "Combining '"+ tokenA->str()+ "' and '"+ tokenB->str() + "' yields an invalid token.");
}
static inline invalidHashHash unexpectedNewline(const Location &loc, const std::string ¯oName) {
return invalidHashHash(loc, macroName, "Unexpected newline");
}
static inline invalidHashHash universalCharacterUB(const Location &loc, const std::string ¯oName, const Token* tokenA, const std::string& strAB) {
return invalidHashHash(loc, macroName, "Combining '\\"+ tokenA->str()+ "' and '"+ strAB.substr(tokenA->str().size()) + "' yields universal character '\\" + strAB + "'. This is undefined behavior according to C standard chapter 5.1.1.2, paragraph 4.");
}
};
private:
/** Create new token where Token::macro is set for replaced tokens */
Token *newMacroToken(const TokenString &str, const Location &loc, bool replaced, const Token *expandedFromToken=nullptr) const {
Token *tok = new Token(str,loc);
if (replaced)
tok->macro = nameTokDef->str();
if (expandedFromToken)
tok->setExpandedFrom(expandedFromToken, this);
return tok;
}
bool parseDefine(const Token *nametoken) {
nameTokDef = nametoken;
variadic = false;
if (!nameTokDef) {
valueToken = endToken = nullptr;
args.clear();
return false;
}
// function like macro..
if (functionLike()) {
args.clear();
const Token *argtok = nameTokDef->next->next;
while (sameline(nametoken, argtok) && argtok->op != ')') {
if (argtok->str() == "..." &&
argtok->next && argtok->next->op == ')') {
variadic = true;
if (!argtok->previous->name)
args.push_back("__VA_ARGS__");
argtok = argtok->next; // goto ')'
break;
}
if (argtok->op != ',')
args.push_back(argtok->str());
argtok = argtok->next;
}
if (!sameline(nametoken, argtok)) {
endToken = argtok ? argtok->previous : argtok;
valueToken = nullptr;
return false;
}
valueToken = argtok ? argtok->next : nullptr;
} else {
args.clear();
valueToken = nameTokDef->next;
}
if (!sameline(valueToken, nameTokDef))
valueToken = nullptr;
endToken = valueToken;
while (sameline(endToken, nameTokDef))
endToken = endToken->next;
return true;
}
unsigned int getArgNum(const TokenString &str) const {
unsigned int par = 0;
while (par < args.size()) {
if (str == args[par])
return par;
par++;
}
return ~0U;
}
std::vector<const Token *> getMacroParameters(const Token *nameTokInst, bool calledInDefine) const {
if (!nameTokInst->next || nameTokInst->next->op != '(' || !functionLike())
return std::vector<const Token *>();
std::vector<const Token *> parametertokens;
parametertokens.push_back(nameTokInst->next);
unsigned int par = 0U;
for (const Token *tok = nameTokInst->next->next; calledInDefine ? sameline(tok, nameTokInst) : (tok != nullptr); tok = tok->next) {
if (tok->op == '(')
++par;
else if (tok->op == ')') {
if (par == 0U) {
parametertokens.push_back(tok);
break;
}
--par;
} else if (par == 0U && tok->op == ',' && (!variadic || parametertokens.size() < args.size()))
parametertokens.push_back(tok);
}
return parametertokens;
}
const Token *appendTokens(TokenList *tokens,
const Location &rawloc,
const Token * const lpar,
const MacroMap ¯os,
const std::set<TokenString> &expandedmacros,
const std::vector<const Token*> ¶metertokens) const {
if (!lpar || lpar->op != '(')
return nullptr;
unsigned int par = 0;
const Token *tok = lpar;
while (sameline(lpar, tok)) {
if (tok->op == '#' && sameline(tok,tok->next) && tok->next->op == '#' && sameline(tok,tok->next->next)) {
// A##B => AB
tok = expandHashHash(tokens, rawloc, tok, macros, expandedmacros, parametertokens, false);
} else if (tok->op == '#' && sameline(tok, tok->next) && tok->next->op != '#') {
tok = expandHash(tokens, rawloc, tok, expandedmacros, parametertokens);
} else {
if (!expandArg(tokens, tok, rawloc, macros, expandedmacros, parametertokens)) {
tokens->push_back(new Token(*tok));
if (tok->macro.empty() && (par > 0 || tok->str() != "("))
tokens->back()->macro = name();
}
if (tok->op == '(')
++par;
else if (tok->op == ')') {
--par;
if (par == 0U)
break;
}
tok = tok->next;
}
}
for (Token *tok2 = tokens->front(); tok2; tok2 = tok2->next)
tok2->location = lpar->location;
return sameline(lpar,tok) ? tok : nullptr;
}
const Token * expand(TokenList * const output, const Location &loc, const Token * const nameTokInst, const MacroMap ¯os, std::set<TokenString> expandedmacros) const {
expandedmacros.insert(nameTokInst->str());
#ifdef SIMPLECPP_DEBUG_MACRO_EXPANSION
std::cout << " expand " << name() << " " << locstring(defineLocation()) << std::endl;
#endif
usageList.push_back(loc);
if (nameTokInst->str() == "__FILE__") {
output->push_back(new Token('\"'+loc.file()+'\"', loc));
return nameTokInst->next;
}
if (nameTokInst->str() == "__LINE__") {
output->push_back(new Token(toString(loc.line), loc));
return nameTokInst->next;
}
if (nameTokInst->str() == "__COUNTER__") {
output->push_back(new Token(toString(usageList.size()-1U), loc));
return nameTokInst->next;
}
const bool calledInDefine = (loc.fileIndex != nameTokInst->location.fileIndex ||
loc.line < nameTokInst->location.line);
std::vector<const Token*> parametertokens1(getMacroParameters(nameTokInst, calledInDefine));
if (functionLike()) {
// No arguments => not macro expansion
if (nameTokInst->next && nameTokInst->next->op != '(') {
output->push_back(new Token(nameTokInst->str(), loc));
return nameTokInst->next;
}
// Parse macro-call
if (variadic) {
if (parametertokens1.size() < args.size()) {
throw wrongNumberOfParameters(nameTokInst->location, name());
}
} else {
if (parametertokens1.size() != args.size() + (args.empty() ? 2U : 1U))
throw wrongNumberOfParameters(nameTokInst->location, name());
}
}
// If macro call uses __COUNTER__ then expand that first
TokenList tokensparams(files);
std::vector<const Token *> parametertokens2;
if (!parametertokens1.empty()) {
bool counter = false;
for (const Token *tok = parametertokens1[0]; tok != parametertokens1.back(); tok = tok->next) {
if (tok->str() == "__COUNTER__") {
counter = true;
break;
}
}
const MacroMap::const_iterator m = macros.find("__COUNTER__");
if (!counter || m == macros.end())
parametertokens2.swap(parametertokens1);
else {
const Macro &counterMacro = m->second;
unsigned int par = 0;
for (const Token *tok = parametertokens1[0]; tok && par < parametertokens1.size(); tok = tok->next) {
if (tok->str() == "__COUNTER__") {
tokensparams.push_back(new Token(toString(counterMacro.usageList.size()), tok->location));
counterMacro.usageList.push_back(tok->location);
} else {
tokensparams.push_back(new Token(*tok));
if (tok == parametertokens1[par]) {
parametertokens2.push_back(tokensparams.cback());
par++;
}
}
}
}
}
Token * const output_end_1 = output->back();
// expand
for (const Token *tok = valueToken; tok != endToken;) {
if (tok->op != '#') {
// A##B => AB
if (sameline(tok, tok->next) && tok->next && tok->next->op == '#' && tok->next->next && tok->next->next->op == '#') {
if (!sameline(tok, tok->next->next->next))
throw invalidHashHash::unexpectedNewline(tok->location, name());
if (variadic && tok->op == ',' && tok->next->next->next->str() == args.back()) {
Token *const comma = newMacroToken(tok->str(), loc, isReplaced(expandedmacros), tok);
output->push_back(comma);
tok = expandToken(output, loc, tok->next->next->next, macros, expandedmacros, parametertokens2);
if (output->back() == comma)
output->deleteToken(comma);
continue;
}
TokenList new_output(files);
if (!expandArg(&new_output, tok, parametertokens2))
output->push_back(newMacroToken(tok->str(), loc, isReplaced(expandedmacros), tok));
else if (new_output.empty()) // placemarker token
output->push_back(newMacroToken("", loc, isReplaced(expandedmacros)));
else
for (const Token *tok2 = new_output.cfront(); tok2; tok2 = tok2->next)
output->push_back(newMacroToken(tok2->str(), loc, isReplaced(expandedmacros), tok2));
tok = tok->next;
} else {
tok = expandToken(output, loc, tok, macros, expandedmacros, parametertokens2);
}
continue;
}
int numberOfHash = 1;
const Token *hashToken = tok->next;
while (sameline(tok,hashToken) && hashToken->op == '#') {
hashToken = hashToken->next;
++numberOfHash;
}
if (numberOfHash == 4 && tok->next->location.col + 1 == tok->next->next->location.col) {
// # ## # => ##
output->push_back(newMacroToken("##", loc, isReplaced(expandedmacros)));
tok = hashToken;
continue;
}
if (numberOfHash >= 2 && tok->location.col + 1 < tok->next->location.col) {
output->push_back(new Token(*tok));
tok = tok->next;
continue;
}
tok = tok->next;
if (tok == endToken) {
output->push_back(new Token(*tok->previous));
break;
}
if (tok->op == '#') {
// A##B => AB
tok = expandHashHash(output, loc, tok->previous, macros, expandedmacros, parametertokens2);
} else {
// #123 => "123"
tok = expandHash(output, loc, tok->previous, expandedmacros, parametertokens2);
}
}
if (!functionLike()) {
for (Token *tok = output_end_1 ? output_end_1->next : output->front(); tok; tok = tok->next) {
tok->macro = nameTokInst->str();
}
}
if (!parametertokens1.empty())
parametertokens1.swap(parametertokens2);
return functionLike() ? parametertokens2.back()->next : nameTokInst->next;
}
const Token *recursiveExpandToken(TokenList *output, TokenList &temp, const Location &loc, const Token *tok, const MacroMap ¯os, const std::set<TokenString> &expandedmacros, const std::vector<const Token*> ¶metertokens) const {
if (!(temp.cback() && temp.cback()->name && tok->next && tok->next->op == '(')) {
output->takeTokens(temp);
return tok->next;
}
if (!sameline(tok, tok->next)) {
output->takeTokens(temp);
return tok->next;
}
const MacroMap::const_iterator it = macros.find(temp.cback()->str());
if (it == macros.end() || expandedmacros.find(temp.cback()->str()) != expandedmacros.end()) {
output->takeTokens(temp);
return tok->next;
}
const Macro &calledMacro = it->second;
if (!calledMacro.functionLike()) {
output->takeTokens(temp);
return tok->next;
}
TokenList temp2(files);
temp2.push_back(new Token(temp.cback()->str(), tok->location));
const Token * const tok2 = appendTokens(&temp2, loc, tok->next, macros, expandedmacros, parametertokens);
if (!tok2)
return tok->next;
output->takeTokens(temp);
output->deleteToken(output->back());
calledMacro.expand(output, loc, temp2.cfront(), macros, expandedmacros);
return tok2->next;
}
const Token *expandToken(TokenList *output, const Location &loc, const Token *tok, const MacroMap ¯os, const std::set<TokenString> &expandedmacros, const std::vector<const Token*> ¶metertokens) const {
// Not name..
if (!tok->name) {
output->push_back(newMacroToken(tok->str(), loc, true, tok));
return tok->next;
}
// Macro parameter..
{
TokenList temp(files);
if (tok->str() == "__VA_OPT__") {
if (sameline(tok, tok->next) && tok->next->str() == "(") {
tok = tok->next;
int paren = 1;
while (sameline(tok, tok->next)) {
if (tok->next->str() == "(")
++paren;
else if (tok->next->str() == ")")
--paren;
if (paren == 0)
return tok->next->next;
tok = tok->next;
if (parametertokens.size() > args.size() && parametertokens.front()->next->str() != ")")
tok = expandToken(output, loc, tok, macros, expandedmacros, parametertokens)->previous;
}
}
throw Error(tok->location, "Missing parenthesis for __VA_OPT__(content)");
}
if (expandArg(&temp, tok, loc, macros, expandedmacros, parametertokens)) {
if (tok->str() == "__VA_ARGS__" && temp.empty() && output->cback() && output->cback()->str() == "," &&
tok->nextSkipComments() && tok->nextSkipComments()->str() == ")")
output->deleteToken(output->back());
return recursiveExpandToken(output, temp, loc, tok, macros, expandedmacros, parametertokens);
}
}
// Macro..
const MacroMap::const_iterator it = macros.find(tok->str());
if (it != macros.end() && expandedmacros.find(tok->str()) == expandedmacros.end()) {
std::set<std::string> expandedmacros2(expandedmacros);
expandedmacros2.insert(tok->str());
const Macro &calledMacro = it->second;
if (!calledMacro.functionLike()) {
TokenList temp(files);
calledMacro.expand(&temp, loc, tok, macros, expandedmacros);
return recursiveExpandToken(output, temp, loc, tok, macros, expandedmacros2, parametertokens);
}
if (!sameline(tok, tok->next)) {
output->push_back(newMacroToken(tok->str(), loc, true, tok));
return tok->next;
}
TokenList tokens(files);
tokens.push_back(new Token(*tok));
const Token * tok2 = nullptr;
if (tok->next->op == '(')
tok2 = appendTokens(&tokens, loc, tok->next, macros, expandedmacros, parametertokens);
else if (expandArg(&tokens, tok->next, loc, macros, expandedmacros, parametertokens)) {
tokens.front()->location = loc;
if (tokens.cfront()->next && tokens.cfront()->next->op == '(')
tok2 = tok->next;
}
if (!tok2) {
output->push_back(newMacroToken(tok->str(), loc, true, tok));
return tok->next;
}
TokenList temp(files);
calledMacro.expand(&temp, loc, tokens.cfront(), macros, expandedmacros);
return recursiveExpandToken(output, temp, loc, tok2, macros, expandedmacros, parametertokens);
}
if (tok->str() == DEFINED) {
const Token * const tok2 = tok->next;
const Token * const tok3 = tok2 ? tok2->next : nullptr;
const Token * const tok4 = tok3 ? tok3->next : nullptr;
const Token *defToken = nullptr;
const Token *lastToken = nullptr;
if (sameline(tok, tok4) && tok2->op == '(' && tok3->name && tok4->op == ')') {
defToken = tok3;
lastToken = tok4;
} else if (sameline(tok,tok2) && tok2->name) {
defToken = lastToken = tok2;
}
if (defToken) {
std::string macroName = defToken->str();
if (defToken->next && defToken->next->op == '#' && defToken->next->next && defToken->next->next->op == '#' && defToken->next->next->next && defToken->next->next->next->name && sameline(defToken,defToken->next->next->next)) {
TokenList temp(files);
if (expandArg(&temp, defToken, parametertokens))
macroName = temp.cback()->str();
if (expandArg(&temp, defToken->next->next->next, parametertokens))
macroName += temp.cback()->str();
else
macroName += defToken->next->next->next->str();
lastToken = defToken->next->next->next;
}
const bool def = (macros.find(macroName) != macros.end());
output->push_back(newMacroToken(def ? "1" : "0", loc, true));
return lastToken->next;
}
}
output->push_back(newMacroToken(tok->str(), loc, true, tok));
return tok->next;
}
bool expandArg(TokenList *output, const Token *tok, const std::vector<const Token*> ¶metertokens) const {
if (!tok->name)
return false;
const unsigned int argnr = getArgNum(tok->str());
if (argnr >= args.size())
return false;
// empty variadic parameter
if (variadic && argnr + 1U >= parametertokens.size())
return true;
for (const Token *partok = parametertokens[argnr]->next; partok != parametertokens[argnr + 1U]; partok = partok->next)
output->push_back(new Token(*partok));
return true;
}
bool expandArg(TokenList *output, const Token *tok, const Location &loc, const MacroMap ¯os, const std::set<TokenString> &expandedmacros, const std::vector<const Token*> ¶metertokens) const {
if (!tok->name)
return false;
const unsigned int argnr = getArgNum(tok->str());
if (argnr >= args.size())
return false;
if (variadic && argnr + 1U >= parametertokens.size()) // empty variadic parameter
return true;
for (const Token *partok = parametertokens[argnr]->next; partok != parametertokens[argnr + 1U];) {
const MacroMap::const_iterator it = macros.find(partok->str());
if (it != macros.end() && !partok->isExpandedFrom(&it->second) && (partok->str() == name() || expandedmacros.find(partok->str()) == expandedmacros.end())) {
const std::set<TokenString> expandedmacros2; // temporary amnesia to allow reexpansion of currently expanding macros during argument evaluation
partok = it->second.expand(output, loc, partok, macros, expandedmacros2);
} else {
output->push_back(newMacroToken(partok->str(), loc, isReplaced(expandedmacros), partok));
output->back()->macro = partok->macro;
partok = partok->next;
}
}
if (tok->whitespaceahead && output->back())
output->back()->whitespaceahead = true;
return true;
}
/**
* Expand #X => "X"
* @param output destination tokenlist
* @param loc location for expanded token
* @param tok The # token
* @param expandedmacros set with expanded macros, with this macro
* @param parametertokens parameters given when expanding this macro
* @return token after the X
*/
const Token *expandHash(TokenList *output, const Location &loc, const Token *tok, const std::set<TokenString> &expandedmacros, const std::vector<const Token*> ¶metertokens) const {
TokenList tokenListHash(files);
const MacroMap macros2; // temporarily bypass macro expansion
tok = expandToken(&tokenListHash, loc, tok->next, macros2, expandedmacros, parametertokens);
std::ostringstream ostr;
ostr << '\"';
for (const Token *hashtok = tokenListHash.cfront(), *next; hashtok; hashtok = next) {
next = hashtok->next;
ostr << hashtok->str();
if (next && hashtok->whitespaceahead)
ostr << ' ';
}
ostr << '\"';
output->push_back(newMacroToken(escapeString(ostr.str()), loc, isReplaced(expandedmacros)));
return tok;
}
/**
* Expand A##B => AB
* The A should already be expanded. Call this when you reach the first # token
* @param output destination tokenlist
* @param loc location for expanded token
* @param tok first # token
* @param macros all macros
* @param expandedmacros set with expanded macros, with this macro
* @param parametertokens parameters given when expanding this macro
* @param expandResult expand ## result i.e. "AB"?
* @return token after B
*/
const Token *expandHashHash(TokenList *output, const Location &loc, const Token *tok, const MacroMap ¯os, const std::set<TokenString> &expandedmacros, const std::vector<const Token*> ¶metertokens, bool expandResult=true) const {
Token *A = output->back();
if (!A)
throw invalidHashHash(tok->location, name(), "Missing first argument");
if (!sameline(tok, tok->next) || !sameline(tok, tok->next->next))
throw invalidHashHash::unexpectedNewline(tok->location, name());
const bool canBeConcatenatedWithEqual = A->isOneOf("+-*/%&|^") || A->str() == "<<" || A->str() == ">>";
const bool canBeConcatenatedStringOrChar = isStringLiteral_(A->str()) || isCharLiteral_(A->str());
const bool unexpectedA = (!A->name && !A->number && !A->str().empty() && !canBeConcatenatedWithEqual && !canBeConcatenatedStringOrChar);
Token * const B = tok->next->next;
if (!B->name && !B->number && B->op && !B->isOneOf("#="))
throw invalidHashHash::unexpectedToken(tok->location, name(), B);
if ((canBeConcatenatedWithEqual && B->op != '=') ||
(!canBeConcatenatedWithEqual && B->op == '='))
throw invalidHashHash::cannotCombine(tok->location, name(), A, B);
// Superficial check; more in-depth would in theory be possible _after_ expandArg
if (canBeConcatenatedStringOrChar && (B->number || !B->name))
throw invalidHashHash::cannotCombine(tok->location, name(), A, B);
TokenList tokensB(files);
const Token *nextTok = B->next;
if (canBeConcatenatedStringOrChar) {
if (unexpectedA)
throw invalidHashHash::unexpectedToken(tok->location, name(), A);
// It seems clearer to handle this case separately even though the code is similar-ish, but we don't want to merge here.
// TODO The question is whether the ## or varargs may still apply, and how to provoke?
if (expandArg(&tokensB, B, parametertokens)) {
for (Token *b = tokensB.front(); b; b = b->next)
b->location = loc;
} else {
tokensB.push_back(new Token(*B));
tokensB.back()->location = loc;
}
output->takeTokens(tokensB);
} else {
std::string strAB;
const bool varargs = variadic && !args.empty() && B->str() == args[args.size()-1U];
if (expandArg(&tokensB, B, parametertokens)) {
if (tokensB.empty())
strAB = A->str();
else if (varargs && A->op == ',')
strAB = ",";
else if (varargs && unexpectedA)
throw invalidHashHash::unexpectedToken(tok->location, name(), A);
else {
strAB = A->str() + tokensB.cfront()->str();
tokensB.deleteToken(tokensB.front());
}
} else {
if (unexpectedA)
throw invalidHashHash::unexpectedToken(tok->location, name(), A);
strAB = A->str() + B->str();
}
// producing universal character is undefined behavior
if (A->previous && A->previous->str() == "\\") {
if (strAB[0] == 'u' && strAB.size() == 5)
throw invalidHashHash::universalCharacterUB(tok->location, name(), A, strAB);
if (strAB[0] == 'U' && strAB.size() == 9)
throw invalidHashHash::universalCharacterUB(tok->location, name(), A, strAB);
}
if (varargs && tokensB.empty() && tok->previous->str() == ",")
output->deleteToken(A);
else if (strAB != "," && macros.find(strAB) == macros.end()) {
A->setstr(strAB);
for (Token *b = tokensB.front(); b; b = b->next)
b->location = loc;
output->takeTokens(tokensB);
} else if (sameline(B, nextTok) && sameline(B, nextTok->next) && nextTok->op == '#' && nextTok->next->op == '#') {
TokenList output2(files);
output2.push_back(new Token(strAB, tok->location));
nextTok = expandHashHash(&output2, loc, nextTok, macros, expandedmacros, parametertokens);
output->deleteToken(A);
output->takeTokens(output2);
} else {
output->deleteToken(A);
TokenList tokens(files);
tokens.push_back(new Token(strAB, tok->location));
// for function like macros, push the (...)
if (tokensB.empty() && sameline(B,B->next) && B->next->op=='(') {
const MacroMap::const_iterator it = macros.find(strAB);
if (it != macros.end() && expandedmacros.find(strAB) == expandedmacros.end() && it->second.functionLike()) {
const Token * const tok2 = appendTokens(&tokens, loc, B->next, macros, expandedmacros, parametertokens);
if (tok2)
nextTok = tok2->next;
}
}
if (expandResult)
expandToken(output, loc, tokens.cfront(), macros, expandedmacros, parametertokens);
else
output->takeTokens(tokens);
for (Token *b = tokensB.front(); b; b = b->next)
b->location = loc;
output->takeTokens(tokensB);
}
}
return nextTok;
}
static bool isReplaced(const std::set<std::string> &expandedmacros) {
// return true if size > 1
std::set<std::string>::const_iterator it = expandedmacros.begin();
if (it == expandedmacros.end())
return false;
++it;
return (it != expandedmacros.end());
}
/** name token in definition */
const Token *nameTokDef;
/** arguments for macro */
std::vector<TokenString> args;
/** first token in replacement string */
const Token *valueToken;
/** token after replacement string */
const Token *endToken;
/** files */
std::vector<std::string> &files;
/** this is used for -D where the definition is not seen anywhere in code */
TokenList tokenListDefine;
/** usage of this macro */
mutable std::list<Location> usageList;
/** is macro variadic? */
bool variadic;
/** was the value of this macro actually defined in the code? */
bool valueDefinedInCode_;
};
}
namespace simplecpp {
#ifdef __CYGWIN__
bool startsWith(const std::string &str, const std::string &s)
{
return (str.size() >= s.size() && str.compare(0, s.size(), s) == 0);
}
std::string convertCygwinToWindowsPath(const std::string &cygwinPath)
{
std::string windowsPath;
std::string::size_type pos = 0;
if (cygwinPath.size() >= 11 && startsWith(cygwinPath, "/cygdrive/")) {
const unsigned char driveLetter = cygwinPath[10];
if (std::isalpha(driveLetter)) {
if (cygwinPath.size() == 11) {
windowsPath = toupper(driveLetter);
windowsPath += ":\\"; // volume root directory
pos = 11;
} else if (cygwinPath[11] == '/') {
windowsPath = toupper(driveLetter);
windowsPath += ":";
pos = 11;
}
}
}
for (; pos < cygwinPath.size(); ++pos) {
unsigned char c = cygwinPath[pos];
if (c == '/')
c = '\\';
windowsPath += c;
}
return windowsPath;
}
#endif
}
#ifdef SIMPLECPP_WINDOWS
#if __cplusplus >= 201103L
using MyMutex = std::mutex;
template<class T>
using MyLock = std::lock_guard<T>;
#else
class MyMutex {
public:
MyMutex() {
InitializeCriticalSection(&m_criticalSection);
}
~MyMutex() {
DeleteCriticalSection(&m_criticalSection);
}
CRITICAL_SECTION* lock() {
return &m_criticalSection;
}
private:
CRITICAL_SECTION m_criticalSection;
};
template<typename T>
class MyLock {
public:
explicit MyLock(T& m)
: m_mutex(m) {
EnterCriticalSection(m_mutex.lock());
}
~MyLock() {
LeaveCriticalSection(m_mutex.lock());
}
private:
MyLock& operator=(const MyLock&);
MyLock(const MyLock&);
T& m_mutex;
};
#endif
class RealFileNameMap {
public:
RealFileNameMap() {}
bool getCacheEntry(const std::string& path, std::string& returnPath) {
MyLock<MyMutex> lock(m_mutex);
const std::map<std::string, std::string>::iterator it = m_fileMap.find(path);
if (it != m_fileMap.end()) {
returnPath = it->second;
return true;
}
return false;
}
void addToCache(const std::string& path, const std::string& actualPath) {
MyLock<MyMutex> lock(m_mutex);
m_fileMap[path] = actualPath;
}
private:
std::map<std::string, std::string> m_fileMap;
MyMutex m_mutex;
};
static RealFileNameMap realFileNameMap;
static bool realFileName(const std::string &f, std::string &result)
{
// are there alpha characters in last subpath?
bool alpha = false;
for (std::string::size_type pos = 1; pos <= f.size(); ++pos) {
const unsigned char c = f[f.size() - pos];
if (c == '/' || c == '\\')
break;
if (std::isalpha(c)) {
alpha = true;
break;
}
}
// do not convert this path if there are no alpha characters (either pointless or cause wrong results for . and ..)
if (!alpha)
return false;
// Lookup filename or foldername on file system
if (!realFileNameMap.getCacheEntry(f, result)) {
WIN32_FIND_DATAA FindFileData;
#ifdef __CYGWIN__
const std::string fConverted = simplecpp::convertCygwinToWindowsPath(f);
const HANDLE hFind = FindFirstFileExA(fConverted.c_str(), FindExInfoBasic, &FindFileData, FindExSearchNameMatch, NULL, 0);
#else
HANDLE hFind = FindFirstFileExA(f.c_str(), FindExInfoBasic, &FindFileData, FindExSearchNameMatch, NULL, 0);
#endif
if (INVALID_HANDLE_VALUE == hFind)
return false;
result = FindFileData.cFileName;
realFileNameMap.addToCache(f, result);
FindClose(hFind);
}
return true;
}
static RealFileNameMap realFilePathMap;
/** Change case in given path to match filesystem */
static std::string realFilename(const std::string &f)
{
std::string ret;
ret.reserve(f.size()); // this will be the final size
if (realFilePathMap.getCacheEntry(f, ret))
return ret;
// Current subpath
std::string subpath;
for (std::string::size_type pos = 0; pos < f.size(); ++pos) {
const unsigned char c = f[pos];
// Separator.. add subpath and separator
if (c == '/' || c == '\\') {
// if subpath is empty just add separator
if (subpath.empty()) {
ret += c;
continue;
}
const bool isDriveSpecification =
(pos == 2 && subpath.size() == 2 && std::isalpha(subpath[0]) && subpath[1] == ':');
// Append real filename (proper case)
std::string f2;
if (!isDriveSpecification && realFileName(f.substr(0, pos), f2))
ret += f2;
else
ret += subpath;
subpath.clear();
// Append separator
ret += c;
} else {
subpath += c;
}
}
if (!subpath.empty()) {
std::string f2;
if (realFileName(f,f2))
ret += f2;
else
ret += subpath;
}
realFilePathMap.addToCache(f, ret);
return ret;
}
static bool isAbsolutePath(const std::string &path)
{
if (path.length() >= 3 && path[0] > 0 && std::isalpha(path[0]) && path[1] == ':' && (path[2] == '\\' || path[2] == '/'))
return true;
return path.length() > 1U && (path[0] == '/' || path[0] == '\\');
}
#else
#define realFilename(f) f
static bool isAbsolutePath(const std::string &path)
{
return path.length() > 1U && path[0] == '/';
}
#endif
namespace simplecpp {
/**
* perform path simplifications for . and ..
*/
std::string simplifyPath(std::string path)
{
if (path.empty())
return path;
std::string::size_type pos;
// replace backslash separators
std::replace(path.begin(), path.end(), '\\', '/');
const bool unc(path.compare(0,2,"//") == 0);
// replace "//" with "/"
pos = 0;
while ((pos = path.find("//",pos)) != std::string::npos) {
path.erase(pos,1);
}
// remove "./"
pos = 0;
while ((pos = path.find("./",pos)) != std::string::npos) {
if (pos == 0 || path[pos - 1U] == '/')
path.erase(pos,2);
else
pos += 2;
}
// remove trailing dot if path ends with "/."
if (endsWith(path,"/."))
path.erase(path.size()-1);
// simplify ".."
pos = 1; // don't simplify ".." if path starts with that
while ((pos = path.find("/..", pos)) != std::string::npos) {
// not end of path, then string must be "/../"
if (pos + 3 < path.size() && path[pos + 3] != '/') {
++pos;
continue;
}
// get previous subpath
std::string::size_type pos1 = path.rfind('/', pos - 1U);
if (pos1 == std::string::npos) {
pos1 = 0;
} else {
pos1 += 1U;
}
const std::string previousSubPath = path.substr(pos1, pos - pos1);
if (previousSubPath == "..") {
// don't simplify
++pos;
} else {
// remove previous subpath and ".."
path.erase(pos1, pos - pos1 + 4);
if (path.empty())
path = ".";
// update pos
pos = (pos1 == 0) ? 1 : (pos1 - 1);
}
}
// Remove trailing '/'?
//if (path.size() > 1 && endsWith(path, "/"))
// path.erase(path.size()-1);
if (unc)
path = '/' + path;
// cppcheck-suppress duplicateExpressionTernary - platform-dependent implementation
return strpbrk(path.c_str(), "*?") == nullptr ? realFilename(path) : path;
}
}
/** Evaluate sizeof(type) */
static void simplifySizeof(simplecpp::TokenList &expr, const std::map<std::string, std::size_t> &sizeOfType)
{
for (simplecpp::Token *tok = expr.front(); tok; tok = tok->next) {
if (tok->str() != "sizeof")
continue;
simplecpp::Token *tok1 = tok->next;
if (!tok1) {
throw std::runtime_error("missing sizeof argument");
}
simplecpp::Token *tok2 = tok1->next;
if (!tok2) {
throw std::runtime_error("missing sizeof argument");
}
if (tok1->op == '(') {
tok1 = tok1->next;
while (tok2->op != ')') {
tok2 = tok2->next;
if (!tok2) {
throw std::runtime_error("invalid sizeof expression");
}
}
}
std::string type;
for (simplecpp::Token *typeToken = tok1; typeToken != tok2; typeToken = typeToken->next) {
if ((typeToken->str() == "unsigned" || typeToken->str() == "signed") && typeToken->next->name)
continue;
if (typeToken->str() == "*" && type.find('*') != std::string::npos)
continue;
if (!type.empty())
type += ' ';
type += typeToken->str();
}
const std::map<std::string, std::size_t>::const_iterator it = sizeOfType.find(type);
if (it != sizeOfType.end())
tok->setstr(toString(it->second));
else
continue;
tok2 = tok2->next;
while (tok->next != tok2)
expr.deleteToken(tok->next);
}
}
/** Evaluate __has_include(file) */
static bool isCpp17OrLater(const simplecpp::DUI &dui)
{
const std::string std_ver = simplecpp::getCppStdString(dui.std);
return !std_ver.empty() && (std_ver >= "201703L");
}
static std::string openHeader(std::ifstream &f, const simplecpp::DUI &dui, const std::string &sourcefile, const std::string &header, bool systemheader);
static void simplifyHasInclude(simplecpp::TokenList &expr, const simplecpp::DUI &dui)
{
if (!isCpp17OrLater(dui))
return;
for (simplecpp::Token *tok = expr.front(); tok; tok = tok->next) {
if (tok->str() != HAS_INCLUDE)
continue;
simplecpp::Token *tok1 = tok->next;
if (!tok1) {
throw std::runtime_error("missing __has_include argument");
}
simplecpp::Token *tok2 = tok1->next;
if (!tok2) {
throw std::runtime_error("missing __has_include argument");
}
if (tok1->op == '(') {
tok1 = tok1->next;
while (tok2->op != ')') {
tok2 = tok2->next;
if (!tok2) {
throw std::runtime_error("invalid __has_include expression");
}
}
}
const std::string &sourcefile = tok->location.file();
const bool systemheader = (tok1 && tok1->op == '<');
std::string header;
if (systemheader) {
simplecpp::Token *tok3 = tok1->next;
if (!tok3) {
throw std::runtime_error("missing __has_include closing angular bracket");
}
while (tok3->op != '>') {
tok3 = tok3->next;
if (!tok3) {
throw std::runtime_error("invalid __has_include expression");
}
}
for (simplecpp::Token *headerToken = tok1->next; headerToken != tok3; headerToken = headerToken->next)
header += headerToken->str();
// cppcheck-suppress selfAssignment - platform-dependent implementation
header = realFilename(header);
} else {
header = realFilename(tok1->str().substr(1U, tok1->str().size() - 2U));
}
std::ifstream f;
const std::string header2 = openHeader(f,dui,sourcefile,header,systemheader);
tok->setstr(header2.empty() ? "0" : "1");
tok2 = tok2->next;
while (tok->next != tok2)
expr.deleteToken(tok->next);
}
}
static const char * const altopData[] = {"and","or","bitand","bitor","compl","not","not_eq","xor"};
static const std::set<std::string> altop(&altopData[0], &altopData[8]);
static void simplifyName(simplecpp::TokenList &expr)
{
for (simplecpp::Token *tok = expr.front(); tok; tok = tok->next) {
if (tok->name) {
if (altop.find(tok->str()) != altop.end()) {
bool alt;
if (tok->str() == "not" || tok->str() == "compl") {
alt = isAlternativeUnaryOp(tok,tok->str());
} else {
alt = isAlternativeBinaryOp(tok,tok->str());
}
if (alt)
continue;
}
tok->setstr("0");
}
}
}
/*
* Reads at least minlen and at most maxlen digits (inc. prefix) in base base
* from s starting at position pos and converts them to a
* unsigned long long value, updating pos to point to the first
* unused element of s.
* Returns ULLONG_MAX if the result is not representable and
* throws if the above requirements were not possible to satisfy.
*/
static unsigned long long stringToULLbounded(
const std::string& s,
std::size_t& pos,
int base = 0,
std::ptrdiff_t minlen = 1,
std::size_t maxlen = std::string::npos
)
{
const std::string sub = s.substr(pos, maxlen);
const char * const start = sub.c_str();
char* end;
const unsigned long long value = std::strtoull(start, &end, base);
pos += end - start;
if (end - start < minlen)
throw std::runtime_error("expected digit");
return value;
}
/* Converts character literal (including prefix, but not ud-suffix)
* to long long value.
*
* Assumes ASCII-compatible single-byte encoded str for narrow literals
* and UTF-8 otherwise.
*
* For target assumes
* - execution character set encoding matching str
* - UTF-32 execution wide-character set encoding
* - requirements for __STDC_UTF_16__, __STDC_UTF_32__ and __STDC_ISO_10646__ satisfied
* - char16_t is 16bit wide
* - char32_t is 32bit wide
* - wchar_t is 32bit wide and unsigned
* - matching char signedness to host
* - matching sizeof(int) to host
*
* For host assumes
* - ASCII-compatible execution character set
*
* For host and target assumes
* - CHAR_BIT == 8
* - two's complement
*
* Implements multi-character narrow literals according to GCC's behavior,
* except multi code unit universal character names are not supported.
* Multi-character wide literals are not supported.
* Limited support of universal character names for non-UTF-8 execution character set encodings.
*/
long long simplecpp::characterLiteralToLL(const std::string& str)
{
// default is wide/utf32
bool narrow = false;
bool utf8 = false;
bool utf16 = false;
std::size_t pos;
if (!str.empty() && str[0] == '\'') {
narrow = true;
pos = 1;
} else if (str.size() >= 2 && str[0] == 'u' && str[1] == '\'') {
utf16 = true;
pos = 2;
} else if (str.size() >= 3 && str[0] == 'u' && str[1] == '8' && str[2] == '\'') {
utf8 = true;
pos = 3;
} else if (str.size() >= 2 && (str[0] == 'L' || str[0] == 'U') && str[1] == '\'') {
pos = 2;
} else
throw std::runtime_error("expected a character literal");
unsigned long long multivalue = 0;
std::size_t nbytes = 0;
while (pos + 1 < str.size()) {
if (str[pos] == '\'' || str[pos] == '\n')
throw std::runtime_error("raw single quotes and newlines not allowed in character literals");
if (nbytes >= 1 && !narrow)
throw std::runtime_error("multiple characters only supported in narrow character literals");
unsigned long long value;
if (str[pos] == '\\') {
pos++;
const char escape = str[pos++];
if (pos >= str.size())
throw std::runtime_error("unexpected end of character literal");
switch (escape) {
// obscure GCC extensions
case '%':
case '(':
case '[':
case '{':
// standard escape sequences
case '\'':
case '"':
case '?':
case '\\':
value = static_cast<unsigned char>(escape);
break;
case 'a':
value = static_cast<unsigned char>('\a');
break;
case 'b':
value = static_cast<unsigned char>('\b');
break;
case 'f':
value = static_cast<unsigned char>('\f');
break;
case 'n':
value = static_cast<unsigned char>('\n');
break;
case 'r':
value = static_cast<unsigned char>('\r');
break;
case 't':
value = static_cast<unsigned char>('\t');
break;
case 'v':
value = static_cast<unsigned char>('\v');
break;
// GCC extension for ESC character
case 'e':
case 'E':
value = static_cast<unsigned char>('\x1b');
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
// octal escape sequences consist of 1 to 3 digits
value = stringToULLbounded(str, --pos, 8, 1, 3);
break;
case 'x':
// hexadecimal escape sequences consist of at least 1 digit
value = stringToULLbounded(str, pos, 16);
break;
case 'u':
case 'U': {
// universal character names have exactly 4 or 8 digits
const std::size_t ndigits = (escape == 'u' ? 4 : 8);
value = stringToULLbounded(str, pos, 16, ndigits, ndigits);
// UTF-8 encodes code points above 0x7f in multiple code units
// code points above 0x10ffff are not allowed
if (((narrow || utf8) && value > 0x7f) || (utf16 && value > 0xffff) || value > 0x10ffff)
throw std::runtime_error("code point too large");
if (value >= 0xd800 && value <= 0xdfff)
throw std::runtime_error("surrogate code points not allowed in universal character names");
break;
}
default:
throw std::runtime_error("invalid escape sequence");
}
} else {
value = static_cast<unsigned char>(str[pos++]);
if (!narrow && value >= 0x80) {
// Assuming this is a UTF-8 encoded code point.
// This decoder may not completely validate the input.
// Noncharacters are neither rejected nor replaced.
int additional_bytes;
if (value >= 0xf5) // higher values would result in code points above 0x10ffff
throw std::runtime_error("assumed UTF-8 encoded source, but sequence is invalid");
if (value >= 0xf0)
additional_bytes = 3;
else if (value >= 0xe0)
additional_bytes = 2;
else if (value >= 0xc2) // 0xc0 and 0xc1 are always overlong 2-bytes encodings
additional_bytes = 1;
else
throw std::runtime_error("assumed UTF-8 encoded source, but sequence is invalid");
value &= (1 << (6 - additional_bytes)) - 1;
while (additional_bytes--) {
if (pos + 1 >= str.size())
throw std::runtime_error("assumed UTF-8 encoded source, but character literal ends unexpectedly");
const unsigned char c = str[pos++];
if (((c >> 6) != 2) // ensure c has form 0xb10xxxxxx
|| (!value && additional_bytes == 1 && c < 0xa0) // overlong 3-bytes encoding
|| (!value && additional_bytes == 2 && c < 0x90)) // overlong 4-bytes encoding
throw std::runtime_error("assumed UTF-8 encoded source, but sequence is invalid");
value = (value << 6) | (c & ((1 << 7) - 1));
}
if (value >= 0xd800 && value <= 0xdfff)
throw std::runtime_error("assumed UTF-8 encoded source, but sequence is invalid");
if ((utf8 && value > 0x7f) || (utf16 && value > 0xffff) || value > 0x10ffff)
throw std::runtime_error("code point too large");
}
}
if (((narrow || utf8) && value > std::numeric_limits<unsigned char>::max()) || (utf16 && value >> 16) || value >> 32)
throw std::runtime_error("numeric escape sequence too large");
multivalue <<= CHAR_BIT;
multivalue |= value;
nbytes++;
}
if (pos + 1 != str.size() || str[pos] != '\'')
throw std::runtime_error("missing closing quote in character literal");
if (!nbytes)
throw std::runtime_error("empty character literal");
// ordinary narrow character literal's value is determined by (possibly signed) char
if (narrow && nbytes == 1)
return static_cast<char>(multivalue);
// while multi-character literal's value is determined by (signed) int
if (narrow)
return static_cast<int>(multivalue);
// All other cases are unsigned. Since long long is at least 64bit wide,
// while the literals at most 32bit wide, the conversion preserves all values.
return multivalue;
}
static void simplifyNumbers(simplecpp::TokenList &expr)
{
for (simplecpp::Token *tok = expr.front(); tok; tok = tok->next) {
if (tok->str().size() == 1U)
continue;
if (tok->str().compare(0,2,"0x") == 0)
tok->setstr(toString(stringToULL(tok->str())));
else if (!tok->number && tok->str().find('\'') != std::string::npos)
tok->setstr(toString(simplecpp::characterLiteralToLL(tok->str())));
}
}
static void simplifyComments(simplecpp::TokenList &expr)
{
for (simplecpp::Token *tok = expr.front(); tok;) {
simplecpp::Token * const d = tok;
tok = tok->next;
if (d->comment)
expr.deleteToken(d);
}
}
static long long evaluate(simplecpp::TokenList &expr, const simplecpp::DUI &dui, const std::map<std::string, std::size_t> &sizeOfType)
{
simplifyComments(expr);
simplifySizeof(expr, sizeOfType);
simplifyHasInclude(expr, dui);
simplifyName(expr);
simplifyNumbers(expr);
expr.constFold();
// TODO: handle invalid expressions
return expr.cfront() && expr.cfront() == expr.cback() && expr.cfront()->number ? stringToLL(expr.cfront()->str()) : 0LL;
}
static const simplecpp::Token *gotoNextLine(const simplecpp::Token *tok)
{
const unsigned int line = tok->location.line;
const unsigned int file = tok->location.fileIndex;
while (tok && tok->location.line == line && tok->location.fileIndex == file)
tok = tok->next;
return tok;
}
#ifdef SIMPLECPP_WINDOWS
class NonExistingFilesCache {
public:
NonExistingFilesCache() {}
bool contains(const std::string& path) {
MyLock<MyMutex> lock(m_mutex);
return (m_pathSet.find(path) != m_pathSet.end());
}
void add(const std::string& path) {
MyLock<MyMutex> lock(m_mutex);
m_pathSet.insert(path);
}
void clear() {
MyLock<MyMutex> lock(m_mutex);
m_pathSet.clear();
}
private:
std::set<std::string> m_pathSet;
MyMutex m_mutex;
};
static NonExistingFilesCache nonExistingFilesCache;
#endif
static std::string openHeader(std::ifstream &f, const std::string &path)
{
std::string simplePath = simplecpp::simplifyPath(path);
#ifdef SIMPLECPP_WINDOWS
if (nonExistingFilesCache.contains(simplePath))
return ""; // file is known not to exist, skip expensive file open call
#endif
f.open(simplePath.c_str());
if (f.is_open())
return simplePath;
#ifdef SIMPLECPP_WINDOWS
nonExistingFilesCache.add(simplePath);
#endif
return "";
}
static std::string getRelativeFileName(const std::string &sourcefile, const std::string &header)
{
if (sourcefile.find_first_of("\\/") != std::string::npos)
return simplecpp::simplifyPath(sourcefile.substr(0, sourcefile.find_last_of("\\/") + 1U) + header);
return simplecpp::simplifyPath(header);
}
static std::string openHeaderRelative(std::ifstream &f, const std::string &sourcefile, const std::string &header)
{
return openHeader(f, getRelativeFileName(sourcefile, header));
}
static std::string getIncludePathFileName(const std::string &includePath, const std::string &header)
{
std::string path = includePath;
if (!path.empty() && path[path.size()-1U]!='/' && path[path.size()-1U]!='\\')
path += '/';
return path + header;
}
static std::string openHeaderIncludePath(std::ifstream &f, const simplecpp::DUI &dui, const std::string &header)
{
for (std::list<std::string>::const_iterator it = dui.includePaths.begin(); it != dui.includePaths.end(); ++it) {
std::string simplePath = openHeader(f, getIncludePathFileName(*it, header));
if (!simplePath.empty())
return simplePath;
}
return "";
}
static std::string openHeader(std::ifstream &f, const simplecpp::DUI &dui, const std::string &sourcefile, const std::string &header, bool systemheader)
{
if (isAbsolutePath(header))
return openHeader(f, header);
std::string ret;
if (systemheader) {
ret = openHeaderIncludePath(f, dui, header);
return ret;
}
ret = openHeaderRelative(f, sourcefile, header);
if (ret.empty())
return openHeaderIncludePath(f, dui, header);
return ret;
}
static std::string getFileName(const std::map<std::string, simplecpp::TokenList *> &filedata, const std::string &sourcefile, const std::string &header, const simplecpp::DUI &dui, bool systemheader)
{
if (filedata.empty()) {
return "";
}
if (isAbsolutePath(header)) {
return (filedata.find(header) != filedata.end()) ? simplecpp::simplifyPath(header) : "";
}
if (!systemheader) {
const std::string relativeFilename = getRelativeFileName(sourcefile, header);
if (filedata.find(relativeFilename) != filedata.end())
return relativeFilename;
}
for (std::list<std::string>::const_iterator it = dui.includePaths.begin(); it != dui.includePaths.end(); ++it) {
std::string s = simplecpp::simplifyPath(getIncludePathFileName(*it, header));
if (filedata.find(s) != filedata.end())
return s;
}
if (systemheader && filedata.find(header) != filedata.end())
return header;
return "";
}
static bool hasFile(const std::map<std::string, simplecpp::TokenList *> &filedata, const std::string &sourcefile, const std::string &header, const simplecpp::DUI &dui, bool systemheader)
{
return !getFileName(filedata, sourcefile, header, dui, systemheader).empty();
}
std::map<std::string, simplecpp::TokenList*> simplecpp::load(const simplecpp::TokenList &rawtokens, std::vector<std::string> &filenames, const simplecpp::DUI &dui, simplecpp::OutputList *outputList)
{
#ifdef SIMPLECPP_WINDOWS
if (dui.clearIncludeCache)
nonExistingFilesCache.clear();
#endif
std::map<std::string, simplecpp::TokenList*> ret;
std::list<const Token *> filelist;
// -include files
for (std::list<std::string>::const_iterator it = dui.includes.begin(); it != dui.includes.end(); ++it) {
const std::string &filename = realFilename(*it);
if (ret.find(filename) != ret.end())
continue;
std::ifstream fin(filename.c_str());
if (!fin.is_open()) {
if (outputList) {
simplecpp::Output err(filenames);
err.type = simplecpp::Output::EXPLICIT_INCLUDE_NOT_FOUND;
err.location = Location(filenames);
err.msg = "Can not open include file '" + filename + "' that is explicitly included.";
outputList->push_back(err);
}
continue;
}
fin.close();
TokenList *tokenlist = new TokenList(filename, filenames, outputList);
if (!tokenlist->front()) {
delete tokenlist;
continue;
}
if (dui.removeComments)
tokenlist->removeComments();
ret[filename] = tokenlist;
filelist.push_back(tokenlist->front());
}
for (const Token *rawtok = rawtokens.cfront(); rawtok || !filelist.empty(); rawtok = rawtok ? rawtok->next : nullptr) {
if (rawtok == nullptr) {
rawtok = filelist.back();
filelist.pop_back();
}
if (rawtok->op != '#' || sameline(rawtok->previousSkipComments(), rawtok))
continue;
rawtok = rawtok->nextSkipComments();
if (!rawtok || rawtok->str() != INCLUDE)
continue;
const std::string &sourcefile = rawtok->location.file();
const Token * const htok = rawtok->nextSkipComments();
if (!sameline(rawtok, htok))
continue;
const bool systemheader = (htok->str()[0] == '<');
const std::string header(realFilename(htok->str().substr(1U, htok->str().size() - 2U)));
if (hasFile(ret, sourcefile, header, dui, systemheader))
continue;
std::ifstream f;
const std::string header2 = openHeader(f,dui,sourcefile,header,systemheader);
if (!f.is_open())
continue;
f.close();
TokenList *tokens = new TokenList(header2, filenames, outputList);
if (dui.removeComments)
tokens->removeComments();
ret[header2] = tokens;
if (tokens->front())
filelist.push_back(tokens->front());
}
return ret;
}
static bool preprocessToken(simplecpp::TokenList &output, const simplecpp::Token **tok1, simplecpp::MacroMap ¯os, std::vector<std::string> &files, simplecpp::OutputList *outputList)
{
const simplecpp::Token * const tok = *tok1;
const simplecpp::MacroMap::const_iterator it = macros.find(tok->str());
if (it != macros.end()) {
simplecpp::TokenList value(files);
try {
*tok1 = it->second.expand(&value, tok, macros, files);
} catch (simplecpp::Macro::Error &err) {
if (outputList) {
simplecpp::Output out(files);
out.type = simplecpp::Output::SYNTAX_ERROR;
out.location = err.location;
out.msg = "failed to expand \'" + tok->str() + "\', " + err.what;
outputList->push_back(out);
}
return false;
}
output.takeTokens(value);
} else {
if (!tok->comment)
output.push_back(new simplecpp::Token(*tok));
*tok1 = tok->next;
}
return true;
}
static void getLocaltime(struct tm <ime)
{
time_t t;
time(&t);
#ifndef _WIN32
// NOLINTNEXTLINE(misc-include-cleaner) - false positive
localtime_r(&t, <ime);
#else
localtime_s(<ime, &t);
#endif
}
static std::string getDateDefine(const struct tm *timep)
{
char buf[] = "??? ?? ????";
strftime(buf, sizeof(buf), "%b %d %Y", timep);
return std::string("\"").append(buf).append("\"");
}
static std::string getTimeDefine(const struct tm *timep)
{
char buf[] = "??:??:??";
strftime(buf, sizeof(buf), "%T", timep);
return std::string("\"").append(buf).append("\"");
}
void simplecpp::preprocess(simplecpp::TokenList &output, const simplecpp::TokenList &rawtokens, std::vector<std::string> &files, std::map<std::string, simplecpp::TokenList *> &filedata, const simplecpp::DUI &dui, simplecpp::OutputList *outputList, std::list<simplecpp::MacroUsage> *macroUsage, std::list<simplecpp::IfCond> *ifCond)
{
#ifdef SIMPLECPP_WINDOWS
if (dui.clearIncludeCache)
nonExistingFilesCache.clear();
#endif
std::map<std::string, std::size_t> sizeOfType(rawtokens.sizeOfType);
sizeOfType.insert(std::make_pair("char", sizeof(char)));
sizeOfType.insert(std::make_pair("short", sizeof(short)));
sizeOfType.insert(std::make_pair("short int", sizeOfType["short"]));
sizeOfType.insert(std::make_pair("int", sizeof(int)));
sizeOfType.insert(std::make_pair("long", sizeof(long)));
sizeOfType.insert(std::make_pair("long int", sizeOfType["long"]));
sizeOfType.insert(std::make_pair("long long", sizeof(long long)));
sizeOfType.insert(std::make_pair("float", sizeof(float)));
sizeOfType.insert(std::make_pair("double", sizeof(double)));
sizeOfType.insert(std::make_pair("long double", sizeof(long double)));
sizeOfType.insert(std::make_pair("char *", sizeof(char *)));
sizeOfType.insert(std::make_pair("short *", sizeof(short *)));
sizeOfType.insert(std::make_pair("short int *", sizeOfType["short *"]));
sizeOfType.insert(std::make_pair("int *", sizeof(int *)));
sizeOfType.insert(std::make_pair("long *", sizeof(long *)));
sizeOfType.insert(std::make_pair("long int *", sizeOfType["long *"]));
sizeOfType.insert(std::make_pair("long long *", sizeof(long long *)));
sizeOfType.insert(std::make_pair("float *", sizeof(float *)));
sizeOfType.insert(std::make_pair("double *", sizeof(double *)));
sizeOfType.insert(std::make_pair("long double *", sizeof(long double *)));
// use a dummy vector for the macros because as this is not part of the file and would add an empty entry - e.g. /usr/include/poll.h
std::vector<std::string> dummy;
const bool hasInclude = isCpp17OrLater(dui);
MacroMap macros;
for (std::list<std::string>::const_iterator it = dui.defines.begin(); it != dui.defines.end(); ++it) {
const std::string ¯ostr = *it;
const std::string::size_type eq = macrostr.find('=');
const std::string::size_type par = macrostr.find('(');
const std::string macroname = macrostr.substr(0, std::min(eq,par));
if (dui.undefined.find(macroname) != dui.undefined.end())
continue;
const std::string lhs(macrostr.substr(0,eq));
const std::string rhs(eq==std::string::npos ? std::string("1") : macrostr.substr(eq+1));
const Macro macro(lhs, rhs, dummy);
macros.insert(std::pair<TokenString,Macro>(macro.name(), macro));
}
macros.insert(std::make_pair("__FILE__", Macro("__FILE__", "__FILE__", dummy)));
macros.insert(std::make_pair("__LINE__", Macro("__LINE__", "__LINE__", dummy)));
macros.insert(std::make_pair("__COUNTER__", Macro("__COUNTER__", "__COUNTER__", dummy)));
struct tm ltime = {};
getLocaltime(ltime);
macros.insert(std::make_pair("__DATE__", Macro("__DATE__", getDateDefine(<ime), dummy)));
macros.insert(std::make_pair("__TIME__", Macro("__TIME__", getTimeDefine(<ime), dummy)));
if (!dui.std.empty()) {
const cstd_t c_std = simplecpp::getCStd(dui.std);
if (c_std != CUnknown) {
const std::string std_def = simplecpp::getCStdString(c_std);
if (!std_def.empty())
macros.insert(std::make_pair("__STDC_VERSION__", Macro("__STDC_VERSION__", std_def, dummy)));
} else {
const cppstd_t cpp_std = simplecpp::getCppStd(dui.std);
if (cpp_std == CPPUnknown) {
if (outputList) {
simplecpp::Output err(files);
err.type = Output::DUI_ERROR;
err.msg = "unknown standard specified: '" + dui.std + "'";
outputList->push_back(err);
}
output.clear();
return;
}
const std::string std_def = simplecpp::getCppStdString(cpp_std);
if (!std_def.empty())
macros.insert(std::make_pair("__cplusplus", Macro("__cplusplus", std_def, dummy)));
}
}
// True => code in current #if block should be kept
// ElseIsTrue => code in current #if block should be dropped. the code in the #else should be kept.
// AlwaysFalse => drop all code in #if and #else
enum IfState { True, ElseIsTrue, AlwaysFalse };
std::stack<int> ifstates;
ifstates.push(True);
std::stack<const Token *> includetokenstack;
std::set<std::string> pragmaOnce;
includetokenstack.push(rawtokens.cfront());
for (std::list<std::string>::const_iterator it = dui.includes.begin(); it != dui.includes.end(); ++it) {
const std::map<std::string, TokenList*>::const_iterator f = filedata.find(*it);
if (f != filedata.end())
includetokenstack.push(f->second->cfront());
}
std::map<std::string, std::list<Location> > maybeUsedMacros;
for (const Token *rawtok = nullptr; rawtok || !includetokenstack.empty();) {
if (rawtok == nullptr) {
rawtok = includetokenstack.top();
includetokenstack.pop();
continue;
}
if (rawtok->op == '#' && !sameline(rawtok->previousSkipComments(), rawtok)) {
if (!sameline(rawtok, rawtok->next)) {
rawtok = rawtok->next;
continue;
}
rawtok = rawtok->next;
if (!rawtok->name) {
rawtok = gotoNextLine(rawtok);
continue;
}
if (ifstates.size() <= 1U && (rawtok->str() == ELIF || rawtok->str() == ELSE || rawtok->str() == ENDIF)) {
if (outputList) {
simplecpp::Output err(files);
err.type = Output::SYNTAX_ERROR;
err.location = rawtok->location;
err.msg = "#" + rawtok->str() + " without #if";
outputList->push_back(err);
}
output.clear();
return;
}
if (ifstates.top() == True && (rawtok->str() == ERROR || rawtok->str() == WARNING)) {
if (outputList) {
simplecpp::Output err(rawtok->location.files);
err.type = rawtok->str() == ERROR ? Output::ERROR : Output::WARNING;
err.location = rawtok->location;
for (const Token *tok = rawtok->next; tok && sameline(rawtok,tok); tok = tok->next) {
if (!err.msg.empty() && isNameChar(tok->str()[0]))
err.msg += ' ';
err.msg += tok->str();
}
err.msg = '#' + rawtok->str() + ' ' + err.msg;
outputList->push_back(err);
}
if (rawtok->str() == ERROR) {
output.clear();
return;
}
}
if (rawtok->str() == DEFINE) {
if (ifstates.top() != True)
continue;
try {
const Macro ¯o = Macro(rawtok->previous, files);
if (dui.undefined.find(macro.name()) == dui.undefined.end()) {
const MacroMap::iterator it = macros.find(macro.name());
if (it == macros.end())
macros.insert(std::pair<TokenString, Macro>(macro.name(), macro));
else
it->second = macro;
}
} catch (const std::runtime_error &) {
if (outputList) {
simplecpp::Output err(files);
err.type = Output::SYNTAX_ERROR;
err.location = rawtok->location;
err.msg = "Failed to parse #define";
outputList->push_back(err);
}
output.clear();
return;
}
} else if (ifstates.top() == True && rawtok->str() == INCLUDE) {
TokenList inc1(files);
for (const Token *inctok = rawtok->next; sameline(rawtok,inctok); inctok = inctok->next) {
if (!inctok->comment)
inc1.push_back(new Token(*inctok));
}
TokenList inc2(files);
if (!inc1.empty() && inc1.cfront()->name) {
const Token *inctok = inc1.cfront();
if (!preprocessToken(inc2, &inctok, macros, files, outputList)) {
output.clear();
return;
}
} else {
inc2.takeTokens(inc1);
}
if (!inc1.empty() && !inc2.empty() && inc2.cfront()->op == '<' && inc2.cback()->op == '>') {
TokenString hdr;
// TODO: Sometimes spaces must be added in the string
// Somehow preprocessToken etc must be told that the location should be source location not destination location
for (const Token *tok = inc2.cfront(); tok; tok = tok->next) {
hdr += tok->str();
}
inc2.clear();
inc2.push_back(new Token(hdr, inc1.cfront()->location));
inc2.front()->op = '<';
}
if (inc2.empty() || inc2.cfront()->str().size() <= 2U) {
if (outputList) {
simplecpp::Output err(files);
err.type = Output::SYNTAX_ERROR;
err.location = rawtok->location;
err.msg = "No header in #include";
outputList->push_back(err);
}
output.clear();
return;
}
const Token * const inctok = inc2.cfront();
const bool systemheader = (inctok->str()[0] == '<');
const std::string header(realFilename(inctok->str().substr(1U, inctok->str().size() - 2U)));
std::string header2 = getFileName(filedata, rawtok->location.file(), header, dui, systemheader);
if (header2.empty()) {
// try to load file..
std::ifstream f;
header2 = openHeader(f, dui, rawtok->location.file(), header, systemheader);
if (f.is_open()) {
f.close();
TokenList * const tokens = new TokenList(header2, files, outputList);
if (dui.removeComments)
tokens->removeComments();
filedata[header2] = tokens;
}
}
if (header2.empty()) {
if (outputList) {
simplecpp::Output out(files);
out.type = Output::MISSING_HEADER;
out.location = rawtok->location;
out.msg = "Header not found: " + inctok->str();
outputList->push_back(out);
}
} else if (includetokenstack.size() >= 400) {
if (outputList) {
simplecpp::Output out(files);
out.type = Output::INCLUDE_NESTED_TOO_DEEPLY;
out.location = rawtok->location;
out.msg = "#include nested too deeply";
outputList->push_back(out);
}
} else if (pragmaOnce.find(header2) == pragmaOnce.end()) {
includetokenstack.push(gotoNextLine(rawtok));
const TokenList * const includetokens = filedata.find(header2)->second;
rawtok = includetokens ? includetokens->cfront() : nullptr;
continue;
}
} else if (rawtok->str() == IF || rawtok->str() == IFDEF || rawtok->str() == IFNDEF || rawtok->str() == ELIF) {
if (!sameline(rawtok,rawtok->next)) {
if (outputList) {
simplecpp::Output out(files);
out.type = Output::SYNTAX_ERROR;
out.location = rawtok->location;
out.msg = "Syntax error in #" + rawtok->str();
outputList->push_back(out);
}
output.clear();
return;
}
bool conditionIsTrue;
if (ifstates.top() == AlwaysFalse || (ifstates.top() == ElseIsTrue && rawtok->str() != ELIF))
conditionIsTrue = false;
else if (rawtok->str() == IFDEF) {
conditionIsTrue = (macros.find(rawtok->next->str()) != macros.end() || (hasInclude && rawtok->next->str() == HAS_INCLUDE));
maybeUsedMacros[rawtok->next->str()].push_back(rawtok->next->location);
} else if (rawtok->str() == IFNDEF) {
conditionIsTrue = (macros.find(rawtok->next->str()) == macros.end() && !(hasInclude && rawtok->next->str() == HAS_INCLUDE));
maybeUsedMacros[rawtok->next->str()].push_back(rawtok->next->location);
} else { /*if (rawtok->str() == IF || rawtok->str() == ELIF)*/
TokenList expr(files);
for (const Token *tok = rawtok->next; tok && tok->location.sameline(rawtok->location); tok = tok->next) {
if (!tok->name) {
expr.push_back(new Token(*tok));
continue;
}
if (tok->str() == DEFINED) {
tok = tok->next;
const bool par = (tok && tok->op == '(');
if (par)
tok = tok->next;
maybeUsedMacros[rawtok->next->str()].push_back(rawtok->next->location);
if (tok) {
if (macros.find(tok->str()) != macros.end())
expr.push_back(new Token("1", tok->location));
else if (hasInclude && tok->str() == HAS_INCLUDE)
expr.push_back(new Token("1", tok->location));
else
expr.push_back(new Token("0", tok->location));
}
if (par)
tok = tok ? tok->next : nullptr;
if (!tok || !sameline(rawtok,tok) || (par && tok->op != ')')) {
if (outputList) {
Output out(rawtok->location.files);
out.type = Output::SYNTAX_ERROR;
out.location = rawtok->location;
out.msg = "failed to evaluate " + std::string(rawtok->str() == IF ? "#if" : "#elif") + " condition";
outputList->push_back(out);
}
output.clear();
return;
}
continue;
}
if (hasInclude && tok->str() == HAS_INCLUDE) {
tok = tok->next;
const bool par = (tok && tok->op == '(');
if (par)
tok = tok->next;
bool closingAngularBracket = false;
if (tok) {
const std::string &sourcefile = rawtok->location.file();
const bool systemheader = (tok && tok->op == '<');
std::string header;
if (systemheader) {
while ((tok = tok->next) && tok->op != '>')
header += tok->str();
// cppcheck-suppress selfAssignment - platform-dependent implementation
header = realFilename(header);
if (tok && tok->op == '>')
closingAngularBracket = true;
} else {
header = realFilename(tok->str().substr(1U, tok->str().size() - 2U));
closingAngularBracket = true;
}
std::ifstream f;
const std::string header2 = openHeader(f,dui,sourcefile,header,systemheader);
expr.push_back(new Token(header2.empty() ? "0" : "1", tok->location));
}
if (par)
tok = tok ? tok->next : nullptr;
if (!tok || !sameline(rawtok,tok) || (par && tok->op != ')') || (!closingAngularBracket)) {
if (outputList) {
Output out(rawtok->location.files);
out.type = Output::SYNTAX_ERROR;
out.location = rawtok->location;
out.msg = "failed to evaluate " + std::string(rawtok->str() == IF ? "#if" : "#elif") + " condition";
outputList->push_back(out);
}
output.clear();
return;
}
continue;
}
maybeUsedMacros[rawtok->next->str()].push_back(rawtok->next->location);
const Token *tmp = tok;
if (!preprocessToken(expr, &tmp, macros, files, outputList)) {
output.clear();
return;
}
if (!tmp)
break;
tok = tmp->previous;
}
try {
if (ifCond) {
std::string E;
for (const simplecpp::Token *tok = expr.cfront(); tok; tok = tok->next)
E += (E.empty() ? "" : " ") + tok->str();
const long long result = evaluate(expr, dui, sizeOfType);
conditionIsTrue = (result != 0);
ifCond->push_back(IfCond(rawtok->location, E, result));
} else {
const long long result = evaluate(expr, dui, sizeOfType);
conditionIsTrue = (result != 0);
}
} catch (const std::exception &e) {
if (outputList) {
Output out(rawtok->location.files);
out.type = Output::SYNTAX_ERROR;
out.location = rawtok->location;
out.msg = "failed to evaluate " + std::string(rawtok->str() == IF ? "#if" : "#elif") + " condition";
if (e.what() && *e.what())
out.msg += std::string(", ") + e.what();
outputList->push_back(out);
}
output.clear();
return;
}
}
if (rawtok->str() != ELIF) {
// push a new ifstate..
if (ifstates.top() != True)
ifstates.push(AlwaysFalse);
else
ifstates.push(conditionIsTrue ? True : ElseIsTrue);
} else if (ifstates.top() == True) {
ifstates.top() = AlwaysFalse;
} else if (ifstates.top() == ElseIsTrue && conditionIsTrue) {
ifstates.top() = True;
}
} else if (rawtok->str() == ELSE) {
ifstates.top() = (ifstates.top() == ElseIsTrue) ? True : AlwaysFalse;
} else if (rawtok->str() == ENDIF) {
ifstates.pop();
} else if (rawtok->str() == UNDEF) {
if (ifstates.top() == True) {
const Token *tok = rawtok->next;
while (sameline(rawtok,tok) && tok->comment)
tok = tok->next;
if (sameline(rawtok, tok))
macros.erase(tok->str());
}
} else if (ifstates.top() == True && rawtok->str() == PRAGMA && rawtok->next && rawtok->next->str() == ONCE && sameline(rawtok,rawtok->next)) {
pragmaOnce.insert(rawtok->location.file());
}
rawtok = gotoNextLine(rawtok);
continue;
}
if (ifstates.top() != True) {
// drop code
rawtok = gotoNextLine(rawtok);
continue;
}
bool hash=false, hashhash=false;
if (rawtok->op == '#' && sameline(rawtok,rawtok->next)) {
if (rawtok->next->op != '#') {
hash = true;
rawtok = rawtok->next; // skip '#'
} else if (sameline(rawtok,rawtok->next->next)) {
hashhash = true;
rawtok = rawtok->next->next; // skip '#' '#'
}
}
const Location loc(rawtok->location);
TokenList tokens(files);
if (!preprocessToken(tokens, &rawtok, macros, files, outputList)) {
output.clear();
return;
}
if (hash || hashhash) {
std::string s;
for (const Token *hashtok = tokens.cfront(); hashtok; hashtok = hashtok->next)
s += hashtok->str();
if (hash)
output.push_back(new Token('\"' + s + '\"', loc));
else if (output.back())
output.back()->setstr(output.cback()->str() + s);
else
output.push_back(new Token(s, loc));
} else {
output.takeTokens(tokens);
}
}
if (macroUsage) {
for (simplecpp::MacroMap::const_iterator macroIt = macros.begin(); macroIt != macros.end(); ++macroIt) {
const Macro ¯o = macroIt->second;
std::list<Location> usage = macro.usage();
const std::list<Location>& temp = maybeUsedMacros[macro.name()];
usage.insert(usage.end(), temp.begin(), temp.end());
for (std::list<Location>::const_iterator usageIt = usage.begin(); usageIt != usage.end(); ++usageIt) {
MacroUsage mu(usageIt->files, macro.valueDefinedInCode());
mu.macroName = macro.name();
mu.macroLocation = macro.defineLocation();
mu.useLocation = *usageIt;
macroUsage->push_back(mu);
}
}
}
}
void simplecpp::cleanup(std::map<std::string, TokenList*> &filedata)
{
for (std::map<std::string, TokenList*>::iterator it = filedata.begin(); it != filedata.end(); ++it)
delete it->second;
filedata.clear();
}
simplecpp::cstd_t simplecpp::getCStd(const std::string &std)
{
if (std == "c90" || std == "c89" || std == "iso9899:1990" || std == "iso9899:199409" || std == "gnu90" || std == "gnu89")
return C89;
if (std == "c99" || std == "c9x" || std == "iso9899:1999" || std == "iso9899:199x" || std == "gnu99"|| std == "gnu9x")
return C99;
if (std == "c11" || std == "c1x" || std == "iso9899:2011" || std == "gnu11" || std == "gnu1x")
return C11;
if (std == "c17" || std == "c18" || std == "iso9899:2017" || std == "iso9899:2018" || std == "gnu17"|| std == "gnu18")
return C17;
if (std == "c23" || std == "gnu23" || std == "c2x" || std == "gnu2x")
return C23;
return CUnknown;
}
std::string simplecpp::getCStdString(cstd_t std)
{
switch (std) {
case C89:
// __STDC_VERSION__ is not set for C90 although the macro was added in the 1994 amendments
return "";
case C99:
return "199901L";
case C11:
return "201112L";
case C17:
return "201710L";
case C23:
// supported by GCC 9+ and Clang 9+
// Clang 9, 10, 11, 12, 13 return "201710L"
// Clang 14, 15, 16, 17 return "202000L"
// Clang 9, 10, 11, 12, 13, 14, 15, 16, 17 do not support "c23" and "gnu23"
return "202311L";
case CUnknown:
return "";
}
return "";
}
std::string simplecpp::getCStdString(const std::string &std)
{
return getCStdString(getCStd(std));
}
simplecpp::cppstd_t simplecpp::getCppStd(const std::string &std)
{
if (std == "c++98" || std == "c++03" || std == "gnu++98" || std == "gnu++03")
return CPP03;
if (std == "c++11" || std == "gnu++11" || std == "c++0x" || std == "gnu++0x")
return CPP11;
if (std == "c++14" || std == "c++1y" || std == "gnu++14" || std == "gnu++1y")
return CPP14;
if (std == "c++17" || std == "c++1z" || std == "gnu++17" || std == "gnu++1z")
return CPP17;
if (std == "c++20" || std == "c++2a" || std == "gnu++20" || std == "gnu++2a")
return CPP20;
if (std == "c++23" || std == "c++2b" || std == "gnu++23" || std == "gnu++2b")
return CPP23;
if (std == "c++26" || std == "c++2c" || std == "gnu++26" || std == "gnu++2c")
return CPP26;
return CPPUnknown;
}
std::string simplecpp::getCppStdString(cppstd_t std)
{
switch (std) {
case CPP03:
return "199711L";
case CPP11:
return "201103L";
case CPP14:
return "201402L";
case CPP17:
return "201703L";
case CPP20:
// GCC 10 returns "201703L" - correct in 11+
return "202002L";
case CPP23:
// supported by GCC 11+ and Clang 12+
// GCC 11, 12, 13 return "202100L"
// Clang 12, 13, 14, 15, 16 do not support "c++23" and "gnu++23" and return "202101L"
// Clang 17, 18 return "202302L"
return "202302L";
case CPP26:
// supported by Clang 17+
return "202400L";
case CPPUnknown:
return "";
}
return "";
}
std::string simplecpp::getCppStdString(const std::string &std)
{
return getCppStdString(getCppStd(std));
}
#if (__cplusplus < 201103L) && !defined(__APPLE__)
#undef nullptr
#endif
| null |
798 | cpp | cppcheck | tinyxml2.h | externals/tinyxml2/tinyxml2.h | null | /*
Original code by Lee Thomason (www.grinninglizard.com)
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#ifndef TINYXML2_INCLUDED
#define TINYXML2_INCLUDED
#if defined(ANDROID_NDK) || defined(__BORLANDC__) || defined(__QNXNTO__)
# include <ctype.h>
# include <limits.h>
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# if defined(__PS3__)
# include <stddef.h>
# endif
#else
# include <cctype>
# include <climits>
# include <cstdio>
# include <cstdlib>
# include <cstring>
#endif
#include <stdint.h>
/*
gcc:
g++ -Wall -DTINYXML2_DEBUG tinyxml2.cpp xmltest.cpp -o gccxmltest.exe
Formatting, Artistic Style:
AStyle.exe --style=1tbs --indent-switches --break-closing-brackets --indent-preprocessor tinyxml2.cpp tinyxml2.h
*/
#if defined( _DEBUG ) || defined (__DEBUG__)
# ifndef TINYXML2_DEBUG
# define TINYXML2_DEBUG
# endif
#endif
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable: 4251)
#endif
#ifdef _MSC_VER
# ifdef TINYXML2_EXPORT
# define TINYXML2_LIB __declspec(dllexport)
# elif defined(TINYXML2_IMPORT)
# define TINYXML2_LIB __declspec(dllimport)
# else
# define TINYXML2_LIB
# endif
#elif __GNUC__ >= 4
# define TINYXML2_LIB __attribute__((visibility("default")))
#else
# define TINYXML2_LIB
#endif
#if !defined(TIXMLASSERT)
#if defined(TINYXML2_DEBUG)
# if defined(_MSC_VER)
# // "(void)0," is for suppressing C4127 warning in "assert(false)", "assert(true)" and the like
# define TIXMLASSERT( x ) do { if ( !((void)0,(x))) { __debugbreak(); } } while(false)
# elif defined (ANDROID_NDK)
# include <android/log.h>
# define TIXMLASSERT( x ) do { if ( !(x)) { __android_log_assert( "assert", "grinliz", "ASSERT in '%s' at %d.", __FILE__, __LINE__ ); } } while(false)
# else
# include <assert.h>
# define TIXMLASSERT assert
# endif
#else
# define TIXMLASSERT( x ) do {} while(false)
#endif
#endif
/* Versioning, past 1.0.14:
http://semver.org/
*/
static const int TIXML2_MAJOR_VERSION = 10;
static const int TIXML2_MINOR_VERSION = 0;
static const int TIXML2_PATCH_VERSION = 0;
#define TINYXML2_MAJOR_VERSION 10
#define TINYXML2_MINOR_VERSION 0
#define TINYXML2_PATCH_VERSION 0
// A fixed element depth limit is problematic. There needs to be a
// limit to avoid a stack overflow. However, that limit varies per
// system, and the capacity of the stack. On the other hand, it's a trivial
// attack that can result from ill, malicious, or even correctly formed XML,
// so there needs to be a limit in place.
static const int TINYXML2_MAX_ELEMENT_DEPTH = 500;
namespace tinyxml2
{
class XMLDocument;
class XMLElement;
class XMLAttribute;
class XMLComment;
class XMLText;
class XMLDeclaration;
class XMLUnknown;
class XMLPrinter;
/*
A class that wraps strings. Normally stores the start and end
pointers into the XML file itself, and will apply normalization
and entity translation if actually read. Can also store (and memory
manage) a traditional char[]
Isn't clear why TINYXML2_LIB is needed; but seems to fix #719
*/
class TINYXML2_LIB StrPair
{
public:
enum Mode {
NEEDS_ENTITY_PROCESSING = 0x01,
NEEDS_NEWLINE_NORMALIZATION = 0x02,
NEEDS_WHITESPACE_COLLAPSING = 0x04,
TEXT_ELEMENT = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION,
TEXT_ELEMENT_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION,
ATTRIBUTE_NAME = 0,
ATTRIBUTE_VALUE = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION,
ATTRIBUTE_VALUE_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION,
COMMENT = NEEDS_NEWLINE_NORMALIZATION
};
StrPair() : _flags( 0 ), _start( 0 ), _end( 0 ) {}
~StrPair();
void Set( char* start, char* end, int flags ) {
TIXMLASSERT( start );
TIXMLASSERT( end );
Reset();
_start = start;
_end = end;
_flags = flags | NEEDS_FLUSH;
}
const char* GetStr();
bool Empty() const {
return _start == _end;
}
void SetInternedStr( const char* str ) {
Reset();
_start = const_cast<char*>(str);
}
void SetStr( const char* str, int flags=0 );
char* ParseText( char* in, const char* endTag, int strFlags, int* curLineNumPtr );
char* ParseName( char* in );
void TransferTo( StrPair* other );
void Reset();
private:
void CollapseWhitespace();
enum {
NEEDS_FLUSH = 0x100,
NEEDS_DELETE = 0x200
};
int _flags;
char* _start;
char* _end;
StrPair( const StrPair& other ); // not supported
void operator=( const StrPair& other ); // not supported, use TransferTo()
};
/*
A dynamic array of Plain Old Data. Doesn't support constructors, etc.
Has a small initial memory pool, so that low or no usage will not
cause a call to new/delete
*/
template <class T, int INITIAL_SIZE>
class DynArray
{
public:
DynArray() :
_mem( _pool ),
_allocated( INITIAL_SIZE ),
_size( 0 )
{
}
~DynArray() {
if ( _mem != _pool ) {
delete [] _mem;
}
}
void Clear() {
_size = 0;
}
void Push( T t ) {
TIXMLASSERT( _size < INT_MAX );
EnsureCapacity( _size+1 );
_mem[_size] = t;
++_size;
}
T* PushArr( int count ) {
TIXMLASSERT( count >= 0 );
TIXMLASSERT( _size <= INT_MAX - count );
EnsureCapacity( _size+count );
T* ret = &_mem[_size];
_size += count;
return ret;
}
T Pop() {
TIXMLASSERT( _size > 0 );
--_size;
return _mem[_size];
}
void PopArr( int count ) {
TIXMLASSERT( _size >= count );
_size -= count;
}
bool Empty() const {
return _size == 0;
}
T& operator[](int i) {
TIXMLASSERT( i>= 0 && i < _size );
return _mem[i];
}
const T& operator[](int i) const {
TIXMLASSERT( i>= 0 && i < _size );
return _mem[i];
}
const T& PeekTop() const {
TIXMLASSERT( _size > 0 );
return _mem[ _size - 1];
}
int Size() const {
TIXMLASSERT( _size >= 0 );
return _size;
}
int Capacity() const {
TIXMLASSERT( _allocated >= INITIAL_SIZE );
return _allocated;
}
void SwapRemove(int i) {
TIXMLASSERT(i >= 0 && i < _size);
TIXMLASSERT(_size > 0);
_mem[i] = _mem[_size - 1];
--_size;
}
const T* Mem() const {
TIXMLASSERT( _mem );
return _mem;
}
T* Mem() {
TIXMLASSERT( _mem );
return _mem;
}
private:
DynArray( const DynArray& ); // not supported
void operator=( const DynArray& ); // not supported
void EnsureCapacity( int cap ) {
TIXMLASSERT( cap > 0 );
if ( cap > _allocated ) {
TIXMLASSERT( cap <= INT_MAX / 2 );
const int newAllocated = cap * 2;
T* newMem = new T[static_cast<unsigned int>(newAllocated)];
TIXMLASSERT( newAllocated >= _size );
memcpy( newMem, _mem, sizeof(T)*static_cast<size_t>(_size) ); // warning: not using constructors, only works for PODs
if ( _mem != _pool ) {
delete [] _mem;
}
_mem = newMem;
_allocated = newAllocated;
}
}
T* _mem;
T _pool[static_cast<size_t>(INITIAL_SIZE)];
int _allocated; // objects allocated
int _size; // number objects in use
};
/*
Parent virtual class of a pool for fast allocation
and deallocation of objects.
*/
class MemPool
{
public:
MemPool() {}
virtual ~MemPool() {}
virtual int ItemSize() const = 0;
virtual void* Alloc() = 0;
virtual void Free( void* ) = 0;
virtual void SetTracked() = 0;
};
/*
Template child class to create pools of the correct type.
*/
template< int ITEM_SIZE >
class MemPoolT : public MemPool
{
public:
MemPoolT() : _blockPtrs(), _root(0), _currentAllocs(0), _nAllocs(0), _maxAllocs(0), _nUntracked(0) {}
~MemPoolT() {
MemPoolT< ITEM_SIZE >::Clear();
}
void Clear() {
// Delete the blocks.
while( !_blockPtrs.Empty()) {
Block* lastBlock = _blockPtrs.Pop();
delete lastBlock;
}
_root = 0;
_currentAllocs = 0;
_nAllocs = 0;
_maxAllocs = 0;
_nUntracked = 0;
}
virtual int ItemSize() const override{
return ITEM_SIZE;
}
int CurrentAllocs() const {
return _currentAllocs;
}
virtual void* Alloc() override{
if ( !_root ) {
// Need a new block.
Block* block = new Block;
_blockPtrs.Push( block );
Item* blockItems = block->items;
for( int i = 0; i < ITEMS_PER_BLOCK - 1; ++i ) {
blockItems[i].next = &(blockItems[i + 1]);
}
blockItems[ITEMS_PER_BLOCK - 1].next = 0;
_root = blockItems;
}
Item* const result = _root;
TIXMLASSERT( result != 0 );
_root = _root->next;
++_currentAllocs;
if ( _currentAllocs > _maxAllocs ) {
_maxAllocs = _currentAllocs;
}
++_nAllocs;
++_nUntracked;
return result;
}
virtual void Free( void* mem ) override {
if ( !mem ) {
return;
}
--_currentAllocs;
Item* item = static_cast<Item*>( mem );
#ifdef TINYXML2_DEBUG
memset( item, 0xfe, sizeof( *item ) );
#endif
item->next = _root;
_root = item;
}
void Trace( const char* name ) {
printf( "Mempool %s watermark=%d [%dk] current=%d size=%d nAlloc=%d blocks=%d\n",
name, _maxAllocs, _maxAllocs * ITEM_SIZE / 1024, _currentAllocs,
ITEM_SIZE, _nAllocs, _blockPtrs.Size() );
}
void SetTracked() override {
--_nUntracked;
}
int Untracked() const {
return _nUntracked;
}
// This number is perf sensitive. 4k seems like a good tradeoff on my machine.
// The test file is large, 170k.
// Release: VS2010 gcc(no opt)
// 1k: 4000
// 2k: 4000
// 4k: 3900 21000
// 16k: 5200
// 32k: 4300
// 64k: 4000 21000
// Declared public because some compilers do not accept to use ITEMS_PER_BLOCK
// in private part if ITEMS_PER_BLOCK is private
enum { ITEMS_PER_BLOCK = (4 * 1024) / ITEM_SIZE };
private:
MemPoolT( const MemPoolT& ); // not supported
void operator=( const MemPoolT& ); // not supported
union Item {
Item* next;
char itemData[static_cast<size_t>(ITEM_SIZE)];
};
struct Block {
Item items[ITEMS_PER_BLOCK];
};
DynArray< Block*, 10 > _blockPtrs;
Item* _root;
int _currentAllocs;
int _nAllocs;
int _maxAllocs;
int _nUntracked;
};
/**
Implements the interface to the "Visitor pattern" (see the Accept() method.)
If you call the Accept() method, it requires being passed a XMLVisitor
class to handle callbacks. For nodes that contain other nodes (Document, Element)
you will get called with a VisitEnter/VisitExit pair. Nodes that are always leafs
are simply called with Visit().
If you return 'true' from a Visit method, recursive parsing will continue. If you return
false, <b>no children of this node or its siblings</b> will be visited.
All flavors of Visit methods have a default implementation that returns 'true' (continue
visiting). You need to only override methods that are interesting to you.
Generally Accept() is called on the XMLDocument, although all nodes support visiting.
You should never change the document from a callback.
@sa XMLNode::Accept()
*/
class TINYXML2_LIB XMLVisitor
{
public:
virtual ~XMLVisitor() {}
/// Visit a document.
virtual bool VisitEnter( const XMLDocument& /*doc*/ ) {
return true;
}
/// Visit a document.
virtual bool VisitExit( const XMLDocument& /*doc*/ ) {
return true;
}
/// Visit an element.
virtual bool VisitEnter( const XMLElement& /*element*/, const XMLAttribute* /*firstAttribute*/ ) {
return true;
}
/// Visit an element.
virtual bool VisitExit( const XMLElement& /*element*/ ) {
return true;
}
/// Visit a declaration.
virtual bool Visit( const XMLDeclaration& /*declaration*/ ) {
return true;
}
/// Visit a text node.
virtual bool Visit( const XMLText& /*text*/ ) {
return true;
}
/// Visit a comment node.
virtual bool Visit( const XMLComment& /*comment*/ ) {
return true;
}
/// Visit an unknown node.
virtual bool Visit( const XMLUnknown& /*unknown*/ ) {
return true;
}
};
// WARNING: must match XMLDocument::_errorNames[]
enum XMLError {
XML_SUCCESS = 0,
XML_NO_ATTRIBUTE,
XML_WRONG_ATTRIBUTE_TYPE,
XML_ERROR_FILE_NOT_FOUND,
XML_ERROR_FILE_COULD_NOT_BE_OPENED,
XML_ERROR_FILE_READ_ERROR,
XML_ERROR_PARSING_ELEMENT,
XML_ERROR_PARSING_ATTRIBUTE,
XML_ERROR_PARSING_TEXT,
XML_ERROR_PARSING_CDATA,
XML_ERROR_PARSING_COMMENT,
XML_ERROR_PARSING_DECLARATION,
XML_ERROR_PARSING_UNKNOWN,
XML_ERROR_EMPTY_DOCUMENT,
XML_ERROR_MISMATCHED_ELEMENT,
XML_ERROR_PARSING,
XML_CAN_NOT_CONVERT_TEXT,
XML_NO_TEXT_NODE,
XML_ELEMENT_DEPTH_EXCEEDED,
XML_ERROR_COUNT
};
/*
Utility functionality.
*/
class TINYXML2_LIB XMLUtil
{
public:
static const char* SkipWhiteSpace( const char* p, int* curLineNumPtr ) {
TIXMLASSERT( p );
while( IsWhiteSpace(*p) ) {
if (curLineNumPtr && *p == '\n') {
++(*curLineNumPtr);
}
++p;
}
TIXMLASSERT( p );
return p;
}
static char* SkipWhiteSpace( char* const p, int* curLineNumPtr ) {
return const_cast<char*>( SkipWhiteSpace( const_cast<const char*>(p), curLineNumPtr ) );
}
// Anything in the high order range of UTF-8 is assumed to not be whitespace. This isn't
// correct, but simple, and usually works.
static bool IsWhiteSpace( char p ) {
return !IsUTF8Continuation(p) && isspace( static_cast<unsigned char>(p) );
}
inline static bool IsNameStartChar( unsigned char ch ) {
if ( ch >= 128 ) {
// This is a heuristic guess in attempt to not implement Unicode-aware isalpha()
return true;
}
if ( isalpha( ch ) ) {
return true;
}
return ch == ':' || ch == '_';
}
inline static bool IsNameChar( unsigned char ch ) {
return IsNameStartChar( ch )
|| isdigit( ch )
|| ch == '.'
|| ch == '-';
}
inline static bool IsPrefixHex( const char* p) {
p = SkipWhiteSpace(p, 0);
return p && *p == '0' && ( *(p + 1) == 'x' || *(p + 1) == 'X');
}
inline static bool StringEqual( const char* p, const char* q, int nChar=INT_MAX ) {
if ( p == q ) {
return true;
}
TIXMLASSERT( p );
TIXMLASSERT( q );
TIXMLASSERT( nChar >= 0 );
return strncmp( p, q, static_cast<size_t>(nChar) ) == 0;
}
inline static bool IsUTF8Continuation( const char p ) {
return ( p & 0x80 ) != 0;
}
static const char* ReadBOM( const char* p, bool* hasBOM );
// p is the starting location,
// the UTF-8 value of the entity will be placed in value, and length filled in.
static const char* GetCharacterRef( const char* p, char* value, int* length );
static void ConvertUTF32ToUTF8( unsigned long input, char* output, int* length );
// converts primitive types to strings
static void ToStr( int v, char* buffer, int bufferSize );
static void ToStr( unsigned v, char* buffer, int bufferSize );
static void ToStr( bool v, char* buffer, int bufferSize );
static void ToStr( float v, char* buffer, int bufferSize );
static void ToStr( double v, char* buffer, int bufferSize );
static void ToStr(int64_t v, char* buffer, int bufferSize);
static void ToStr(uint64_t v, char* buffer, int bufferSize);
// converts strings to primitive types
static bool ToInt( const char* str, int* value );
static bool ToUnsigned( const char* str, unsigned* value );
static bool ToBool( const char* str, bool* value );
static bool ToFloat( const char* str, float* value );
static bool ToDouble( const char* str, double* value );
static bool ToInt64(const char* str, int64_t* value);
static bool ToUnsigned64(const char* str, uint64_t* value);
// Changes what is serialized for a boolean value.
// Default to "true" and "false". Shouldn't be changed
// unless you have a special testing or compatibility need.
// Be careful: static, global, & not thread safe.
// Be sure to set static const memory as parameters.
static void SetBoolSerialization(const char* writeTrue, const char* writeFalse);
private:
static const char* writeBoolTrue;
static const char* writeBoolFalse;
};
/** XMLNode is a base class for every object that is in the
XML Document Object Model (DOM), except XMLAttributes.
Nodes have siblings, a parent, and children which can
be navigated. A node is always in a XMLDocument.
The type of a XMLNode can be queried, and it can
be cast to its more defined type.
A XMLDocument allocates memory for all its Nodes.
When the XMLDocument gets deleted, all its Nodes
will also be deleted.
@verbatim
A Document can contain: Element (container or leaf)
Comment (leaf)
Unknown (leaf)
Declaration( leaf )
An Element can contain: Element (container or leaf)
Text (leaf)
Attributes (not on tree)
Comment (leaf)
Unknown (leaf)
@endverbatim
*/
class TINYXML2_LIB XMLNode
{
friend class XMLDocument;
friend class XMLElement;
public:
/// Get the XMLDocument that owns this XMLNode.
const XMLDocument* GetDocument() const {
TIXMLASSERT( _document );
return _document;
}
/// Get the XMLDocument that owns this XMLNode.
XMLDocument* GetDocument() {
TIXMLASSERT( _document );
return _document;
}
/// Safely cast to an Element, or null.
virtual XMLElement* ToElement() {
return 0;
}
/// Safely cast to Text, or null.
virtual XMLText* ToText() {
return 0;
}
/// Safely cast to a Comment, or null.
virtual XMLComment* ToComment() {
return 0;
}
/// Safely cast to a Document, or null.
virtual XMLDocument* ToDocument() {
return 0;
}
/// Safely cast to a Declaration, or null.
virtual XMLDeclaration* ToDeclaration() {
return 0;
}
/// Safely cast to an Unknown, or null.
virtual XMLUnknown* ToUnknown() {
return 0;
}
virtual const XMLElement* ToElement() const {
return 0;
}
virtual const XMLText* ToText() const {
return 0;
}
virtual const XMLComment* ToComment() const {
return 0;
}
virtual const XMLDocument* ToDocument() const {
return 0;
}
virtual const XMLDeclaration* ToDeclaration() const {
return 0;
}
virtual const XMLUnknown* ToUnknown() const {
return 0;
}
// ChildElementCount was originally suggested by msteiger on the sourceforge page for TinyXML and modified by KB1SPH for TinyXML-2.
int ChildElementCount(const char *value) const;
int ChildElementCount() const;
/** The meaning of 'value' changes for the specific type.
@verbatim
Document: empty (NULL is returned, not an empty string)
Element: name of the element
Comment: the comment text
Unknown: the tag contents
Text: the text string
@endverbatim
*/
const char* Value() const;
/** Set the Value of an XML node.
@sa Value()
*/
void SetValue( const char* val, bool staticMem=false );
/// Gets the line number the node is in, if the document was parsed from a file.
int GetLineNum() const { return _parseLineNum; }
/// Get the parent of this node on the DOM.
const XMLNode* Parent() const {
return _parent;
}
XMLNode* Parent() {
return _parent;
}
/// Returns true if this node has no children.
bool NoChildren() const {
return !_firstChild;
}
/// Get the first child node, or null if none exists.
const XMLNode* FirstChild() const {
return _firstChild;
}
XMLNode* FirstChild() {
return _firstChild;
}
/** Get the first child element, or optionally the first child
element with the specified name.
*/
const XMLElement* FirstChildElement( const char* name = 0 ) const;
XMLElement* FirstChildElement( const char* name = 0 ) {
return const_cast<XMLElement*>(const_cast<const XMLNode*>(this)->FirstChildElement( name ));
}
/// Get the last child node, or null if none exists.
const XMLNode* LastChild() const {
return _lastChild;
}
XMLNode* LastChild() {
return _lastChild;
}
/** Get the last child element or optionally the last child
element with the specified name.
*/
const XMLElement* LastChildElement( const char* name = 0 ) const;
XMLElement* LastChildElement( const char* name = 0 ) {
return const_cast<XMLElement*>(const_cast<const XMLNode*>(this)->LastChildElement(name) );
}
/// Get the previous (left) sibling node of this node.
const XMLNode* PreviousSibling() const {
return _prev;
}
XMLNode* PreviousSibling() {
return _prev;
}
/// Get the previous (left) sibling element of this node, with an optionally supplied name.
const XMLElement* PreviousSiblingElement( const char* name = 0 ) const ;
XMLElement* PreviousSiblingElement( const char* name = 0 ) {
return const_cast<XMLElement*>(const_cast<const XMLNode*>(this)->PreviousSiblingElement( name ) );
}
/// Get the next (right) sibling node of this node.
const XMLNode* NextSibling() const {
return _next;
}
XMLNode* NextSibling() {
return _next;
}
/// Get the next (right) sibling element of this node, with an optionally supplied name.
const XMLElement* NextSiblingElement( const char* name = 0 ) const;
XMLElement* NextSiblingElement( const char* name = 0 ) {
return const_cast<XMLElement*>(const_cast<const XMLNode*>(this)->NextSiblingElement( name ) );
}
/**
Add a child node as the last (right) child.
If the child node is already part of the document,
it is moved from its old location to the new location.
Returns the addThis argument or 0 if the node does not
belong to the same document.
*/
XMLNode* InsertEndChild( XMLNode* addThis );
XMLNode* LinkEndChild( XMLNode* addThis ) {
return InsertEndChild( addThis );
}
/**
Add a child node as the first (left) child.
If the child node is already part of the document,
it is moved from its old location to the new location.
Returns the addThis argument or 0 if the node does not
belong to the same document.
*/
XMLNode* InsertFirstChild( XMLNode* addThis );
/**
Add a node after the specified child node.
If the child node is already part of the document,
it is moved from its old location to the new location.
Returns the addThis argument or 0 if the afterThis node
is not a child of this node, or if the node does not
belong to the same document.
*/
XMLNode* InsertAfterChild( XMLNode* afterThis, XMLNode* addThis );
/**
Delete all the children of this node.
*/
void DeleteChildren();
/**
Delete a child of this node.
*/
void DeleteChild( XMLNode* node );
/**
Make a copy of this node, but not its children.
You may pass in a Document pointer that will be
the owner of the new Node. If the 'document' is
null, then the node returned will be allocated
from the current Document. (this->GetDocument())
Note: if called on a XMLDocument, this will return null.
*/
virtual XMLNode* ShallowClone( XMLDocument* document ) const = 0;
/**
Make a copy of this node and all its children.
If the 'target' is null, then the nodes will
be allocated in the current document. If 'target'
is specified, the memory will be allocated is the
specified XMLDocument.
NOTE: This is probably not the correct tool to
copy a document, since XMLDocuments can have multiple
top level XMLNodes. You probably want to use
XMLDocument::DeepCopy()
*/
XMLNode* DeepClone( XMLDocument* target ) const;
/**
Test if 2 nodes are the same, but don't test children.
The 2 nodes do not need to be in the same Document.
Note: if called on a XMLDocument, this will return false.
*/
virtual bool ShallowEqual( const XMLNode* compare ) const = 0;
/** Accept a hierarchical visit of the nodes in the TinyXML-2 DOM. Every node in the
XML tree will be conditionally visited and the host will be called back
via the XMLVisitor interface.
This is essentially a SAX interface for TinyXML-2. (Note however it doesn't re-parse
the XML for the callbacks, so the performance of TinyXML-2 is unchanged by using this
interface versus any other.)
The interface has been based on ideas from:
- http://www.saxproject.org/
- http://c2.com/cgi/wiki?HierarchicalVisitorPattern
Which are both good references for "visiting".
An example of using Accept():
@verbatim
XMLPrinter printer;
tinyxmlDoc.Accept( &printer );
const char* xmlcstr = printer.CStr();
@endverbatim
*/
virtual bool Accept( XMLVisitor* visitor ) const = 0;
/**
Set user data into the XMLNode. TinyXML-2 in
no way processes or interprets user data.
It is initially 0.
*/
void SetUserData(void* userData) { _userData = userData; }
/**
Get user data set into the XMLNode. TinyXML-2 in
no way processes or interprets user data.
It is initially 0.
*/
void* GetUserData() const { return _userData; }
protected:
explicit XMLNode( XMLDocument* );
virtual ~XMLNode();
virtual char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr);
XMLDocument* _document;
XMLNode* _parent;
mutable StrPair _value;
int _parseLineNum;
XMLNode* _firstChild;
XMLNode* _lastChild;
XMLNode* _prev;
XMLNode* _next;
void* _userData;
private:
MemPool* _memPool;
void Unlink( XMLNode* child );
static void DeleteNode( XMLNode* node );
void InsertChildPreamble( XMLNode* insertThis ) const;
const XMLElement* ToElementWithName( const char* name ) const;
XMLNode( const XMLNode& ); // not supported
XMLNode& operator=( const XMLNode& ); // not supported
};
/** XML text.
Note that a text node can have child element nodes, for example:
@verbatim
<root>This is <b>bold</b></root>
@endverbatim
A text node can have 2 ways to output the next. "normal" output
and CDATA. It will default to the mode it was parsed from the XML file and
you generally want to leave it alone, but you can change the output mode with
SetCData() and query it with CData().
*/
class TINYXML2_LIB XMLText : public XMLNode
{
friend class XMLDocument;
public:
virtual bool Accept( XMLVisitor* visitor ) const override;
virtual XMLText* ToText() override {
return this;
}
virtual const XMLText* ToText() const override {
return this;
}
/// Declare whether this should be CDATA or standard text.
void SetCData( bool isCData ) {
_isCData = isCData;
}
/// Returns true if this is a CDATA text element.
bool CData() const {
return _isCData;
}
virtual XMLNode* ShallowClone( XMLDocument* document ) const override;
virtual bool ShallowEqual( const XMLNode* compare ) const override;
protected:
explicit XMLText( XMLDocument* doc ) : XMLNode( doc ), _isCData( false ) {}
virtual ~XMLText() {}
char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ) override;
private:
bool _isCData;
XMLText( const XMLText& ); // not supported
XMLText& operator=( const XMLText& ); // not supported
};
/** An XML Comment. */
class TINYXML2_LIB XMLComment : public XMLNode
{
friend class XMLDocument;
public:
virtual XMLComment* ToComment() override {
return this;
}
virtual const XMLComment* ToComment() const override {
return this;
}
virtual bool Accept( XMLVisitor* visitor ) const override;
virtual XMLNode* ShallowClone( XMLDocument* document ) const override;
virtual bool ShallowEqual( const XMLNode* compare ) const override;
protected:
explicit XMLComment( XMLDocument* doc );
virtual ~XMLComment();
char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr) override;
private:
XMLComment( const XMLComment& ); // not supported
XMLComment& operator=( const XMLComment& ); // not supported
};
/** In correct XML the declaration is the first entry in the file.
@verbatim
<?xml version="1.0" standalone="yes"?>
@endverbatim
TinyXML-2 will happily read or write files without a declaration,
however.
The text of the declaration isn't interpreted. It is parsed
and written as a string.
*/
class TINYXML2_LIB XMLDeclaration : public XMLNode
{
friend class XMLDocument;
public:
virtual XMLDeclaration* ToDeclaration() override {
return this;
}
virtual const XMLDeclaration* ToDeclaration() const override {
return this;
}
virtual bool Accept( XMLVisitor* visitor ) const override;
virtual XMLNode* ShallowClone( XMLDocument* document ) const override;
virtual bool ShallowEqual( const XMLNode* compare ) const override;
protected:
explicit XMLDeclaration( XMLDocument* doc );
virtual ~XMLDeclaration();
char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ) override;
private:
XMLDeclaration( const XMLDeclaration& ); // not supported
XMLDeclaration& operator=( const XMLDeclaration& ); // not supported
};
/** Any tag that TinyXML-2 doesn't recognize is saved as an
unknown. It is a tag of text, but should not be modified.
It will be written back to the XML, unchanged, when the file
is saved.
DTD tags get thrown into XMLUnknowns.
*/
class TINYXML2_LIB XMLUnknown : public XMLNode
{
friend class XMLDocument;
public:
virtual XMLUnknown* ToUnknown() override {
return this;
}
virtual const XMLUnknown* ToUnknown() const override {
return this;
}
virtual bool Accept( XMLVisitor* visitor ) const override;
virtual XMLNode* ShallowClone( XMLDocument* document ) const override;
virtual bool ShallowEqual( const XMLNode* compare ) const override;
protected:
explicit XMLUnknown( XMLDocument* doc );
virtual ~XMLUnknown();
char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ) override;
private:
XMLUnknown( const XMLUnknown& ); // not supported
XMLUnknown& operator=( const XMLUnknown& ); // not supported
};
/** An attribute is a name-value pair. Elements have an arbitrary
number of attributes, each with a unique name.
@note The attributes are not XMLNodes. You may only query the
Next() attribute in a list.
*/
class TINYXML2_LIB XMLAttribute
{
friend class XMLElement;
public:
/// The name of the attribute.
const char* Name() const;
/// The value of the attribute.
const char* Value() const;
/// Gets the line number the attribute is in, if the document was parsed from a file.
int GetLineNum() const { return _parseLineNum; }
/// The next attribute in the list.
const XMLAttribute* Next() const {
return _next;
}
/** IntValue interprets the attribute as an integer, and returns the value.
If the value isn't an integer, 0 will be returned. There is no error checking;
use QueryIntValue() if you need error checking.
*/
int IntValue() const {
int i = 0;
QueryIntValue(&i);
return i;
}
int64_t Int64Value() const {
int64_t i = 0;
QueryInt64Value(&i);
return i;
}
uint64_t Unsigned64Value() const {
uint64_t i = 0;
QueryUnsigned64Value(&i);
return i;
}
/// Query as an unsigned integer. See IntValue()
unsigned UnsignedValue() const {
unsigned i=0;
QueryUnsignedValue( &i );
return i;
}
/// Query as a boolean. See IntValue()
bool BoolValue() const {
bool b=false;
QueryBoolValue( &b );
return b;
}
/// Query as a double. See IntValue()
double DoubleValue() const {
double d=0;
QueryDoubleValue( &d );
return d;
}
/// Query as a float. See IntValue()
float FloatValue() const {
float f=0;
QueryFloatValue( &f );
return f;
}
/** QueryIntValue interprets the attribute as an integer, and returns the value
in the provided parameter. The function will return XML_SUCCESS on success,
and XML_WRONG_ATTRIBUTE_TYPE if the conversion is not successful.
*/
XMLError QueryIntValue( int* value ) const;
/// See QueryIntValue
XMLError QueryUnsignedValue( unsigned int* value ) const;
/// See QueryIntValue
XMLError QueryInt64Value(int64_t* value) const;
/// See QueryIntValue
XMLError QueryUnsigned64Value(uint64_t* value) const;
/// See QueryIntValue
XMLError QueryBoolValue( bool* value ) const;
/// See QueryIntValue
XMLError QueryDoubleValue( double* value ) const;
/// See QueryIntValue
XMLError QueryFloatValue( float* value ) const;
/// Set the attribute to a string value.
void SetAttribute( const char* value );
/// Set the attribute to value.
void SetAttribute( int value );
/// Set the attribute to value.
void SetAttribute( unsigned value );
/// Set the attribute to value.
void SetAttribute(int64_t value);
/// Set the attribute to value.
void SetAttribute(uint64_t value);
/// Set the attribute to value.
void SetAttribute( bool value );
/// Set the attribute to value.
void SetAttribute( double value );
/// Set the attribute to value.
void SetAttribute( float value );
private:
enum { BUF_SIZE = 200 };
XMLAttribute() : _name(), _value(),_parseLineNum( 0 ), _next( 0 ), _memPool( 0 ) {}
virtual ~XMLAttribute() {}
XMLAttribute( const XMLAttribute& ); // not supported
void operator=( const XMLAttribute& ); // not supported
void SetName( const char* name );
char* ParseDeep( char* p, bool processEntities, int* curLineNumPtr );
mutable StrPair _name;
mutable StrPair _value;
int _parseLineNum;
XMLAttribute* _next;
MemPool* _memPool;
};
/** The element is a container class. It has a value, the element name,
and can contain other elements, text, comments, and unknowns.
Elements also contain an arbitrary number of attributes.
*/
class TINYXML2_LIB XMLElement : public XMLNode
{
friend class XMLDocument;
public:
/// Get the name of an element (which is the Value() of the node.)
const char* Name() const {
return Value();
}
/// Set the name of the element.
void SetName( const char* str, bool staticMem=false ) {
SetValue( str, staticMem );
}
virtual XMLElement* ToElement() override {
return this;
}
virtual const XMLElement* ToElement() const override {
return this;
}
virtual bool Accept( XMLVisitor* visitor ) const override;
/** Given an attribute name, Attribute() returns the value
for the attribute of that name, or null if none
exists. For example:
@verbatim
const char* value = ele->Attribute( "foo" );
@endverbatim
The 'value' parameter is normally null. However, if specified,
the attribute will only be returned if the 'name' and 'value'
match. This allow you to write code:
@verbatim
if ( ele->Attribute( "foo", "bar" ) ) callFooIsBar();
@endverbatim
rather than:
@verbatim
if ( ele->Attribute( "foo" ) ) {
if ( strcmp( ele->Attribute( "foo" ), "bar" ) == 0 ) callFooIsBar();
}
@endverbatim
*/
const char* Attribute( const char* name, const char* value=0 ) const;
/** Given an attribute name, IntAttribute() returns the value
of the attribute interpreted as an integer. The default
value will be returned if the attribute isn't present,
or if there is an error. (For a method with error
checking, see QueryIntAttribute()).
*/
int IntAttribute(const char* name, int defaultValue = 0) const;
/// See IntAttribute()
unsigned UnsignedAttribute(const char* name, unsigned defaultValue = 0) const;
/// See IntAttribute()
int64_t Int64Attribute(const char* name, int64_t defaultValue = 0) const;
/// See IntAttribute()
uint64_t Unsigned64Attribute(const char* name, uint64_t defaultValue = 0) const;
/// See IntAttribute()
bool BoolAttribute(const char* name, bool defaultValue = false) const;
/// See IntAttribute()
double DoubleAttribute(const char* name, double defaultValue = 0) const;
/// See IntAttribute()
float FloatAttribute(const char* name, float defaultValue = 0) const;
/** Given an attribute name, QueryIntAttribute() returns
XML_SUCCESS, XML_WRONG_ATTRIBUTE_TYPE if the conversion
can't be performed, or XML_NO_ATTRIBUTE if the attribute
doesn't exist. If successful, the result of the conversion
will be written to 'value'. If not successful, nothing will
be written to 'value'. This allows you to provide default
value:
@verbatim
int value = 10;
QueryIntAttribute( "foo", &value ); // if "foo" isn't found, value will still be 10
@endverbatim
*/
XMLError QueryIntAttribute( const char* name, int* value ) const {
const XMLAttribute* a = FindAttribute( name );
if ( !a ) {
return XML_NO_ATTRIBUTE;
}
return a->QueryIntValue( value );
}
/// See QueryIntAttribute()
XMLError QueryUnsignedAttribute( const char* name, unsigned int* value ) const {
const XMLAttribute* a = FindAttribute( name );
if ( !a ) {
return XML_NO_ATTRIBUTE;
}
return a->QueryUnsignedValue( value );
}
/// See QueryIntAttribute()
XMLError QueryInt64Attribute(const char* name, int64_t* value) const {
const XMLAttribute* a = FindAttribute(name);
if (!a) {
return XML_NO_ATTRIBUTE;
}
return a->QueryInt64Value(value);
}
/// See QueryIntAttribute()
XMLError QueryUnsigned64Attribute(const char* name, uint64_t* value) const {
const XMLAttribute* a = FindAttribute(name);
if(!a) {
return XML_NO_ATTRIBUTE;
}
return a->QueryUnsigned64Value(value);
}
/// See QueryIntAttribute()
XMLError QueryBoolAttribute( const char* name, bool* value ) const {
const XMLAttribute* a = FindAttribute( name );
if ( !a ) {
return XML_NO_ATTRIBUTE;
}
return a->QueryBoolValue( value );
}
/// See QueryIntAttribute()
XMLError QueryDoubleAttribute( const char* name, double* value ) const {
const XMLAttribute* a = FindAttribute( name );
if ( !a ) {
return XML_NO_ATTRIBUTE;
}
return a->QueryDoubleValue( value );
}
/// See QueryIntAttribute()
XMLError QueryFloatAttribute( const char* name, float* value ) const {
const XMLAttribute* a = FindAttribute( name );
if ( !a ) {
return XML_NO_ATTRIBUTE;
}
return a->QueryFloatValue( value );
}
/// See QueryIntAttribute()
XMLError QueryStringAttribute(const char* name, const char** value) const {
const XMLAttribute* a = FindAttribute(name);
if (!a) {
return XML_NO_ATTRIBUTE;
}
*value = a->Value();
return XML_SUCCESS;
}
/** Given an attribute name, QueryAttribute() returns
XML_SUCCESS, XML_WRONG_ATTRIBUTE_TYPE if the conversion
can't be performed, or XML_NO_ATTRIBUTE if the attribute
doesn't exist. It is overloaded for the primitive types,
and is a generally more convenient replacement of
QueryIntAttribute() and related functions.
If successful, the result of the conversion
will be written to 'value'. If not successful, nothing will
be written to 'value'. This allows you to provide default
value:
@verbatim
int value = 10;
QueryAttribute( "foo", &value ); // if "foo" isn't found, value will still be 10
@endverbatim
*/
XMLError QueryAttribute( const char* name, int* value ) const {
return QueryIntAttribute( name, value );
}
XMLError QueryAttribute( const char* name, unsigned int* value ) const {
return QueryUnsignedAttribute( name, value );
}
XMLError QueryAttribute(const char* name, int64_t* value) const {
return QueryInt64Attribute(name, value);
}
XMLError QueryAttribute(const char* name, uint64_t* value) const {
return QueryUnsigned64Attribute(name, value);
}
XMLError QueryAttribute( const char* name, bool* value ) const {
return QueryBoolAttribute( name, value );
}
XMLError QueryAttribute( const char* name, double* value ) const {
return QueryDoubleAttribute( name, value );
}
XMLError QueryAttribute( const char* name, float* value ) const {
return QueryFloatAttribute( name, value );
}
XMLError QueryAttribute(const char* name, const char** value) const {
return QueryStringAttribute(name, value);
}
/// Sets the named attribute to value.
void SetAttribute( const char* name, const char* value ) {
XMLAttribute* a = FindOrCreateAttribute( name );
a->SetAttribute( value );
}
/// Sets the named attribute to value.
void SetAttribute( const char* name, int value ) {
XMLAttribute* a = FindOrCreateAttribute( name );
a->SetAttribute( value );
}
/// Sets the named attribute to value.
void SetAttribute( const char* name, unsigned value ) {
XMLAttribute* a = FindOrCreateAttribute( name );
a->SetAttribute( value );
}
/// Sets the named attribute to value.
void SetAttribute(const char* name, int64_t value) {
XMLAttribute* a = FindOrCreateAttribute(name);
a->SetAttribute(value);
}
/// Sets the named attribute to value.
void SetAttribute(const char* name, uint64_t value) {
XMLAttribute* a = FindOrCreateAttribute(name);
a->SetAttribute(value);
}
/// Sets the named attribute to value.
void SetAttribute( const char* name, bool value ) {
XMLAttribute* a = FindOrCreateAttribute( name );
a->SetAttribute( value );
}
/// Sets the named attribute to value.
void SetAttribute( const char* name, double value ) {
XMLAttribute* a = FindOrCreateAttribute( name );
a->SetAttribute( value );
}
/// Sets the named attribute to value.
void SetAttribute( const char* name, float value ) {
XMLAttribute* a = FindOrCreateAttribute( name );
a->SetAttribute( value );
}
/**
Delete an attribute.
*/
void DeleteAttribute( const char* name );
/// Return the first attribute in the list.
const XMLAttribute* FirstAttribute() const {
return _rootAttribute;
}
/// Query a specific attribute in the list.
const XMLAttribute* FindAttribute( const char* name ) const;
/** Convenience function for easy access to the text inside an element. Although easy
and concise, GetText() is limited compared to getting the XMLText child
and accessing it directly.
If the first child of 'this' is a XMLText, the GetText()
returns the character string of the Text node, else null is returned.
This is a convenient method for getting the text of simple contained text:
@verbatim
<foo>This is text</foo>
const char* str = fooElement->GetText();
@endverbatim
'str' will be a pointer to "This is text".
Note that this function can be misleading. If the element foo was created from
this XML:
@verbatim
<foo><b>This is text</b></foo>
@endverbatim
then the value of str would be null. The first child node isn't a text node, it is
another element. From this XML:
@verbatim
<foo>This is <b>text</b></foo>
@endverbatim
GetText() will return "This is ".
*/
const char* GetText() const;
/** Convenience function for easy access to the text inside an element. Although easy
and concise, SetText() is limited compared to creating an XMLText child
and mutating it directly.
If the first child of 'this' is a XMLText, SetText() sets its value to
the given string, otherwise it will create a first child that is an XMLText.
This is a convenient method for setting the text of simple contained text:
@verbatim
<foo>This is text</foo>
fooElement->SetText( "Hullaballoo!" );
<foo>Hullaballoo!</foo>
@endverbatim
Note that this function can be misleading. If the element foo was created from
this XML:
@verbatim
<foo><b>This is text</b></foo>
@endverbatim
then it will not change "This is text", but rather prefix it with a text element:
@verbatim
<foo>Hullaballoo!<b>This is text</b></foo>
@endverbatim
For this XML:
@verbatim
<foo />
@endverbatim
SetText() will generate
@verbatim
<foo>Hullaballoo!</foo>
@endverbatim
*/
void SetText( const char* inText );
/// Convenience method for setting text inside an element. See SetText() for important limitations.
void SetText( int value );
/// Convenience method for setting text inside an element. See SetText() for important limitations.
void SetText( unsigned value );
/// Convenience method for setting text inside an element. See SetText() for important limitations.
void SetText(int64_t value);
/// Convenience method for setting text inside an element. See SetText() for important limitations.
void SetText(uint64_t value);
/// Convenience method for setting text inside an element. See SetText() for important limitations.
void SetText( bool value );
/// Convenience method for setting text inside an element. See SetText() for important limitations.
void SetText( double value );
/// Convenience method for setting text inside an element. See SetText() for important limitations.
void SetText( float value );
/**
Convenience method to query the value of a child text node. This is probably best
shown by example. Given you have a document is this form:
@verbatim
<point>
<x>1</x>
<y>1.4</y>
</point>
@endverbatim
The QueryIntText() and similar functions provide a safe and easier way to get to the
"value" of x and y.
@verbatim
int x = 0;
float y = 0; // types of x and y are contrived for example
const XMLElement* xElement = pointElement->FirstChildElement( "x" );
const XMLElement* yElement = pointElement->FirstChildElement( "y" );
xElement->QueryIntText( &x );
yElement->QueryFloatText( &y );
@endverbatim
@returns XML_SUCCESS (0) on success, XML_CAN_NOT_CONVERT_TEXT if the text cannot be converted
to the requested type, and XML_NO_TEXT_NODE if there is no child text to query.
*/
XMLError QueryIntText( int* ival ) const;
/// See QueryIntText()
XMLError QueryUnsignedText( unsigned* uval ) const;
/// See QueryIntText()
XMLError QueryInt64Text(int64_t* uval) const;
/// See QueryIntText()
XMLError QueryUnsigned64Text(uint64_t* uval) const;
/// See QueryIntText()
XMLError QueryBoolText( bool* bval ) const;
/// See QueryIntText()
XMLError QueryDoubleText( double* dval ) const;
/// See QueryIntText()
XMLError QueryFloatText( float* fval ) const;
int IntText(int defaultValue = 0) const;
/// See QueryIntText()
unsigned UnsignedText(unsigned defaultValue = 0) const;
/// See QueryIntText()
int64_t Int64Text(int64_t defaultValue = 0) const;
/// See QueryIntText()
uint64_t Unsigned64Text(uint64_t defaultValue = 0) const;
/// See QueryIntText()
bool BoolText(bool defaultValue = false) const;
/// See QueryIntText()
double DoubleText(double defaultValue = 0) const;
/// See QueryIntText()
float FloatText(float defaultValue = 0) const;
/**
Convenience method to create a new XMLElement and add it as last (right)
child of this node. Returns the created and inserted element.
*/
XMLElement* InsertNewChildElement(const char* name);
/// See InsertNewChildElement()
XMLComment* InsertNewComment(const char* comment);
/// See InsertNewChildElement()
XMLText* InsertNewText(const char* text);
/// See InsertNewChildElement()
XMLDeclaration* InsertNewDeclaration(const char* text);
/// See InsertNewChildElement()
XMLUnknown* InsertNewUnknown(const char* text);
// internal:
enum ElementClosingType {
OPEN, // <foo>
CLOSED, // <foo/>
CLOSING // </foo>
};
ElementClosingType ClosingType() const {
return _closingType;
}
virtual XMLNode* ShallowClone( XMLDocument* document ) const override;
virtual bool ShallowEqual( const XMLNode* compare ) const override;
protected:
char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ) override;
private:
XMLElement( XMLDocument* doc );
virtual ~XMLElement();
XMLElement( const XMLElement& ); // not supported
void operator=( const XMLElement& ); // not supported
XMLAttribute* FindOrCreateAttribute( const char* name );
char* ParseAttributes( char* p, int* curLineNumPtr );
static void DeleteAttribute( XMLAttribute* attribute );
XMLAttribute* CreateAttribute();
enum { BUF_SIZE = 200 };
ElementClosingType _closingType;
// The attribute list is ordered; there is no 'lastAttribute'
// because the list needs to be scanned for dupes before adding
// a new attribute.
XMLAttribute* _rootAttribute;
};
enum Whitespace {
PRESERVE_WHITESPACE,
COLLAPSE_WHITESPACE,
PEDANTIC_WHITESPACE
};
/** A Document binds together all the functionality.
It can be saved, loaded, and printed to the screen.
All Nodes are connected and allocated to a Document.
If the Document is deleted, all its Nodes are also deleted.
*/
class TINYXML2_LIB XMLDocument : public XMLNode
{
friend class XMLElement;
// Gives access to SetError and Push/PopDepth, but over-access for everything else.
// Wishing C++ had "internal" scope.
friend class XMLNode;
friend class XMLText;
friend class XMLComment;
friend class XMLDeclaration;
friend class XMLUnknown;
public:
/// constructor
XMLDocument( bool processEntities = true, Whitespace whitespaceMode = PRESERVE_WHITESPACE );
~XMLDocument();
virtual XMLDocument* ToDocument() override {
TIXMLASSERT( this == _document );
return this;
}
virtual const XMLDocument* ToDocument() const override {
TIXMLASSERT( this == _document );
return this;
}
/**
Parse an XML file from a character string.
Returns XML_SUCCESS (0) on success, or
an errorID.
You may optionally pass in the 'nBytes', which is
the number of bytes which will be parsed. If not
specified, TinyXML-2 will assume 'xml' points to a
null terminated string.
*/
XMLError Parse( const char* xml, size_t nBytes=static_cast<size_t>(-1) );
/**
Load an XML file from disk.
Returns XML_SUCCESS (0) on success, or
an errorID.
*/
XMLError LoadFile( const char* filename );
/**
Load an XML file from disk. You are responsible
for providing and closing the FILE*.
NOTE: The file should be opened as binary ("rb")
not text in order for TinyXML-2 to correctly
do newline normalization.
Returns XML_SUCCESS (0) on success, or
an errorID.
*/
XMLError LoadFile( FILE* );
/**
Save the XML file to disk.
Returns XML_SUCCESS (0) on success, or
an errorID.
*/
XMLError SaveFile( const char* filename, bool compact = false );
/**
Save the XML file to disk. You are responsible
for providing and closing the FILE*.
Returns XML_SUCCESS (0) on success, or
an errorID.
*/
XMLError SaveFile( FILE* fp, bool compact = false );
bool ProcessEntities() const {
return _processEntities;
}
Whitespace WhitespaceMode() const {
return _whitespaceMode;
}
/**
Returns true if this document has a leading Byte Order Mark of UTF8.
*/
bool HasBOM() const {
return _writeBOM;
}
/** Sets whether to write the BOM when writing the file.
*/
void SetBOM( bool useBOM ) {
_writeBOM = useBOM;
}
/** Return the root element of DOM. Equivalent to FirstChildElement().
To get the first node, use FirstChild().
*/
XMLElement* RootElement() {
return FirstChildElement();
}
const XMLElement* RootElement() const {
return FirstChildElement();
}
/** Print the Document. If the Printer is not provided, it will
print to stdout. If you provide Printer, this can print to a file:
@verbatim
XMLPrinter printer( fp );
doc.Print( &printer );
@endverbatim
Or you can use a printer to print to memory:
@verbatim
XMLPrinter printer;
doc.Print( &printer );
// printer.CStr() has a const char* to the XML
@endverbatim
*/
void Print( XMLPrinter* streamer=0 ) const;
virtual bool Accept( XMLVisitor* visitor ) const override;
/**
Create a new Element associated with
this Document. The memory for the Element
is managed by the Document.
*/
XMLElement* NewElement( const char* name );
/**
Create a new Comment associated with
this Document. The memory for the Comment
is managed by the Document.
*/
XMLComment* NewComment( const char* comment );
/**
Create a new Text associated with
this Document. The memory for the Text
is managed by the Document.
*/
XMLText* NewText( const char* text );
/**
Create a new Declaration associated with
this Document. The memory for the object
is managed by the Document.
If the 'text' param is null, the standard
declaration is used.:
@verbatim
<?xml version="1.0" encoding="UTF-8"?>
@endverbatim
*/
XMLDeclaration* NewDeclaration( const char* text=0 );
/**
Create a new Unknown associated with
this Document. The memory for the object
is managed by the Document.
*/
XMLUnknown* NewUnknown( const char* text );
/**
Delete a node associated with this document.
It will be unlinked from the DOM.
*/
void DeleteNode( XMLNode* node );
/// Clears the error flags.
void ClearError();
/// Return true if there was an error parsing the document.
bool Error() const {
return _errorID != XML_SUCCESS;
}
/// Return the errorID.
XMLError ErrorID() const {
return _errorID;
}
const char* ErrorName() const;
static const char* ErrorIDToName(XMLError errorID);
/** Returns a "long form" error description. A hopefully helpful
diagnostic with location, line number, and/or additional info.
*/
const char* ErrorStr() const;
/// A (trivial) utility function that prints the ErrorStr() to stdout.
void PrintError() const;
/// Return the line where the error occurred, or zero if unknown.
int ErrorLineNum() const
{
return _errorLineNum;
}
/// Clear the document, resetting it to the initial state.
void Clear();
/**
Copies this document to a target document.
The target will be completely cleared before the copy.
If you want to copy a sub-tree, see XMLNode::DeepClone().
NOTE: that the 'target' must be non-null.
*/
void DeepCopy(XMLDocument* target) const;
// internal
char* Identify( char* p, XMLNode** node, bool first );
// internal
void MarkInUse(const XMLNode* const);
virtual XMLNode* ShallowClone( XMLDocument* /*document*/ ) const override{
return 0;
}
virtual bool ShallowEqual( const XMLNode* /*compare*/ ) const override{
return false;
}
private:
XMLDocument( const XMLDocument& ); // not supported
void operator=( const XMLDocument& ); // not supported
bool _writeBOM;
bool _processEntities;
XMLError _errorID;
Whitespace _whitespaceMode;
mutable StrPair _errorStr;
int _errorLineNum;
char* _charBuffer;
int _parseCurLineNum;
int _parsingDepth;
// Memory tracking does add some overhead.
// However, the code assumes that you don't
// have a bunch of unlinked nodes around.
// Therefore it takes less memory to track
// in the document vs. a linked list in the XMLNode,
// and the performance is the same.
DynArray<XMLNode*, 10> _unlinked;
MemPoolT< sizeof(XMLElement) > _elementPool;
MemPoolT< sizeof(XMLAttribute) > _attributePool;
MemPoolT< sizeof(XMLText) > _textPool;
MemPoolT< sizeof(XMLComment) > _commentPool;
static const char* _errorNames[XML_ERROR_COUNT];
void Parse();
void SetError( XMLError error, int lineNum, const char* format, ... );
// Something of an obvious security hole, once it was discovered.
// Either an ill-formed XML or an excessively deep one can overflow
// the stack. Track stack depth, and error out if needed.
class DepthTracker {
public:
explicit DepthTracker(XMLDocument * document) {
this->_document = document;
document->PushDepth();
}
~DepthTracker() {
_document->PopDepth();
}
private:
XMLDocument * _document;
};
void PushDepth();
void PopDepth();
template<class NodeType, int PoolElementSize>
NodeType* CreateUnlinkedNode( MemPoolT<PoolElementSize>& pool );
};
template<class NodeType, int PoolElementSize>
inline NodeType* XMLDocument::CreateUnlinkedNode( MemPoolT<PoolElementSize>& pool )
{
TIXMLASSERT( sizeof( NodeType ) == PoolElementSize );
TIXMLASSERT( sizeof( NodeType ) == pool.ItemSize() );
NodeType* returnNode = new (pool.Alloc()) NodeType( this );
TIXMLASSERT( returnNode );
returnNode->_memPool = &pool;
_unlinked.Push(returnNode);
return returnNode;
}
/**
A XMLHandle is a class that wraps a node pointer with null checks; this is
an incredibly useful thing. Note that XMLHandle is not part of the TinyXML-2
DOM structure. It is a separate utility class.
Take an example:
@verbatim
<Document>
<Element attributeA = "valueA">
<Child attributeB = "value1" />
<Child attributeB = "value2" />
</Element>
</Document>
@endverbatim
Assuming you want the value of "attributeB" in the 2nd "Child" element, it's very
easy to write a *lot* of code that looks like:
@verbatim
XMLElement* root = document.FirstChildElement( "Document" );
if ( root )
{
XMLElement* element = root->FirstChildElement( "Element" );
if ( element )
{
XMLElement* child = element->FirstChildElement( "Child" );
if ( child )
{
XMLElement* child2 = child->NextSiblingElement( "Child" );
if ( child2 )
{
// Finally do something useful.
@endverbatim
And that doesn't even cover "else" cases. XMLHandle addresses the verbosity
of such code. A XMLHandle checks for null pointers so it is perfectly safe
and correct to use:
@verbatim
XMLHandle docHandle( &document );
XMLElement* child2 = docHandle.FirstChildElement( "Document" ).FirstChildElement( "Element" ).FirstChildElement().NextSiblingElement();
if ( child2 )
{
// do something useful
@endverbatim
Which is MUCH more concise and useful.
It is also safe to copy handles - internally they are nothing more than node pointers.
@verbatim
XMLHandle handleCopy = handle;
@endverbatim
See also XMLConstHandle, which is the same as XMLHandle, but operates on const objects.
*/
class TINYXML2_LIB XMLHandle
{
public:
/// Create a handle from any node (at any depth of the tree.) This can be a null pointer.
explicit XMLHandle( XMLNode* node ) : _node( node ) {
}
/// Create a handle from a node.
explicit XMLHandle( XMLNode& node ) : _node( &node ) {
}
/// Copy constructor
XMLHandle( const XMLHandle& ref ) : _node( ref._node ) {
}
/// Assignment
XMLHandle& operator=( const XMLHandle& ref ) {
_node = ref._node;
return *this;
}
/// Get the first child of this handle.
XMLHandle FirstChild() {
return XMLHandle( _node ? _node->FirstChild() : 0 );
}
/// Get the first child element of this handle.
XMLHandle FirstChildElement( const char* name = 0 ) {
return XMLHandle( _node ? _node->FirstChildElement( name ) : 0 );
}
/// Get the last child of this handle.
XMLHandle LastChild() {
return XMLHandle( _node ? _node->LastChild() : 0 );
}
/// Get the last child element of this handle.
XMLHandle LastChildElement( const char* name = 0 ) {
return XMLHandle( _node ? _node->LastChildElement( name ) : 0 );
}
/// Get the previous sibling of this handle.
XMLHandle PreviousSibling() {
return XMLHandle( _node ? _node->PreviousSibling() : 0 );
}
/// Get the previous sibling element of this handle.
XMLHandle PreviousSiblingElement( const char* name = 0 ) {
return XMLHandle( _node ? _node->PreviousSiblingElement( name ) : 0 );
}
/// Get the next sibling of this handle.
XMLHandle NextSibling() {
return XMLHandle( _node ? _node->NextSibling() : 0 );
}
/// Get the next sibling element of this handle.
XMLHandle NextSiblingElement( const char* name = 0 ) {
return XMLHandle( _node ? _node->NextSiblingElement( name ) : 0 );
}
/// Safe cast to XMLNode. This can return null.
XMLNode* ToNode() {
return _node;
}
/// Safe cast to XMLElement. This can return null.
XMLElement* ToElement() {
return ( _node ? _node->ToElement() : 0 );
}
/// Safe cast to XMLText. This can return null.
XMLText* ToText() {
return ( _node ? _node->ToText() : 0 );
}
/// Safe cast to XMLUnknown. This can return null.
XMLUnknown* ToUnknown() {
return ( _node ? _node->ToUnknown() : 0 );
}
/// Safe cast to XMLDeclaration. This can return null.
XMLDeclaration* ToDeclaration() {
return ( _node ? _node->ToDeclaration() : 0 );
}
private:
XMLNode* _node;
};
/**
A variant of the XMLHandle class for working with const XMLNodes and Documents. It is the
same in all regards, except for the 'const' qualifiers. See XMLHandle for API.
*/
class TINYXML2_LIB XMLConstHandle
{
public:
explicit XMLConstHandle( const XMLNode* node ) : _node( node ) {
}
explicit XMLConstHandle( const XMLNode& node ) : _node( &node ) {
}
XMLConstHandle( const XMLConstHandle& ref ) : _node( ref._node ) {
}
XMLConstHandle& operator=( const XMLConstHandle& ref ) {
_node = ref._node;
return *this;
}
const XMLConstHandle FirstChild() const {
return XMLConstHandle( _node ? _node->FirstChild() : 0 );
}
const XMLConstHandle FirstChildElement( const char* name = 0 ) const {
return XMLConstHandle( _node ? _node->FirstChildElement( name ) : 0 );
}
const XMLConstHandle LastChild() const {
return XMLConstHandle( _node ? _node->LastChild() : 0 );
}
const XMLConstHandle LastChildElement( const char* name = 0 ) const {
return XMLConstHandle( _node ? _node->LastChildElement( name ) : 0 );
}
const XMLConstHandle PreviousSibling() const {
return XMLConstHandle( _node ? _node->PreviousSibling() : 0 );
}
const XMLConstHandle PreviousSiblingElement( const char* name = 0 ) const {
return XMLConstHandle( _node ? _node->PreviousSiblingElement( name ) : 0 );
}
const XMLConstHandle NextSibling() const {
return XMLConstHandle( _node ? _node->NextSibling() : 0 );
}
const XMLConstHandle NextSiblingElement( const char* name = 0 ) const {
return XMLConstHandle( _node ? _node->NextSiblingElement( name ) : 0 );
}
const XMLNode* ToNode() const {
return _node;
}
const XMLElement* ToElement() const {
return ( _node ? _node->ToElement() : 0 );
}
const XMLText* ToText() const {
return ( _node ? _node->ToText() : 0 );
}
const XMLUnknown* ToUnknown() const {
return ( _node ? _node->ToUnknown() : 0 );
}
const XMLDeclaration* ToDeclaration() const {
return ( _node ? _node->ToDeclaration() : 0 );
}
private:
const XMLNode* _node;
};
/**
Printing functionality. The XMLPrinter gives you more
options than the XMLDocument::Print() method.
It can:
-# Print to memory.
-# Print to a file you provide.
-# Print XML without a XMLDocument.
Print to Memory
@verbatim
XMLPrinter printer;
doc.Print( &printer );
SomeFunction( printer.CStr() );
@endverbatim
Print to a File
You provide the file pointer.
@verbatim
XMLPrinter printer( fp );
doc.Print( &printer );
@endverbatim
Print without a XMLDocument
When loading, an XML parser is very useful. However, sometimes
when saving, it just gets in the way. The code is often set up
for streaming, and constructing the DOM is just overhead.
The Printer supports the streaming case. The following code
prints out a trivially simple XML file without ever creating
an XML document.
@verbatim
XMLPrinter printer( fp );
printer.OpenElement( "foo" );
printer.PushAttribute( "foo", "bar" );
printer.CloseElement();
@endverbatim
*/
class TINYXML2_LIB XMLPrinter : public XMLVisitor
{
public:
/** Construct the printer. If the FILE* is specified,
this will print to the FILE. Else it will print
to memory, and the result is available in CStr().
If 'compact' is set to true, then output is created
with only required whitespace and newlines.
*/
XMLPrinter( FILE* file=0, bool compact = false, int depth = 0 );
virtual ~XMLPrinter() {}
/** If streaming, write the BOM and declaration. */
void PushHeader( bool writeBOM, bool writeDeclaration );
/** If streaming, start writing an element.
The element must be closed with CloseElement()
*/
void OpenElement( const char* name, bool compactMode=false );
/// If streaming, add an attribute to an open element.
void PushAttribute( const char* name, const char* value );
void PushAttribute( const char* name, int value );
void PushAttribute( const char* name, unsigned value );
void PushAttribute( const char* name, int64_t value );
void PushAttribute( const char* name, uint64_t value );
void PushAttribute( const char* name, bool value );
void PushAttribute( const char* name, double value );
/// If streaming, close the Element.
virtual void CloseElement( bool compactMode=false );
/// Add a text node.
void PushText( const char* text, bool cdata=false );
/// Add a text node from an integer.
void PushText( int value );
/// Add a text node from an unsigned.
void PushText( unsigned value );
/// Add a text node from a signed 64bit integer.
void PushText( int64_t value );
/// Add a text node from an unsigned 64bit integer.
void PushText( uint64_t value );
/// Add a text node from a bool.
void PushText( bool value );
/// Add a text node from a float.
void PushText( float value );
/// Add a text node from a double.
void PushText( double value );
/// Add a comment
void PushComment( const char* comment );
void PushDeclaration( const char* value );
void PushUnknown( const char* value );
virtual bool VisitEnter( const XMLDocument& /*doc*/ ) override;
virtual bool VisitExit( const XMLDocument& /*doc*/ ) override {
return true;
}
virtual bool VisitEnter( const XMLElement& element, const XMLAttribute* attribute ) override;
virtual bool VisitExit( const XMLElement& element ) override;
virtual bool Visit( const XMLText& text ) override;
virtual bool Visit( const XMLComment& comment ) override;
virtual bool Visit( const XMLDeclaration& declaration ) override;
virtual bool Visit( const XMLUnknown& unknown ) override;
/**
If in print to memory mode, return a pointer to
the XML file in memory.
*/
const char* CStr() const {
return _buffer.Mem();
}
/**
If in print to memory mode, return the size
of the XML file in memory. (Note the size returned
includes the terminating null.)
*/
int CStrSize() const {
return _buffer.Size();
}
/**
If in print to memory mode, reset the buffer to the
beginning.
*/
void ClearBuffer( bool resetToFirstElement = true ) {
_buffer.Clear();
_buffer.Push(0);
_firstElement = resetToFirstElement;
}
protected:
virtual bool CompactMode( const XMLElement& ) { return _compactMode; }
/** Prints out the space before an element. You may override to change
the space and tabs used. A PrintSpace() override should call Print().
*/
virtual void PrintSpace( int depth );
virtual void Print( const char* format, ... );
virtual void Write( const char* data, size_t size );
virtual void Putc( char ch );
inline void Write(const char* data) { Write(data, strlen(data)); }
void SealElementIfJustOpened();
bool _elementJustOpened;
DynArray< const char*, 10 > _stack;
private:
/**
Prepares to write a new node. This includes sealing an element that was
just opened, and writing any whitespace necessary if not in compact mode.
*/
void PrepareForNewNode( bool compactMode );
void PrintString( const char*, bool restrictedEntitySet ); // prints out, after detecting entities.
bool _firstElement;
FILE* _fp;
int _depth;
int _textDepth;
bool _processEntities;
bool _compactMode;
enum {
ENTITY_RANGE = 64,
BUF_SIZE = 200
};
bool _entityFlag[ENTITY_RANGE];
bool _restrictedEntityFlag[ENTITY_RANGE];
DynArray< char, 20 > _buffer;
// Prohibit cloning, intentionally not implemented
XMLPrinter( const XMLPrinter& );
XMLPrinter& operator=( const XMLPrinter& );
};
} // tinyxml2
#if defined(_MSC_VER)
# pragma warning(pop)
#endif
#endif // TINYXML2_INCLUDED
| null |
799 | cpp | cppcheck | tinyxml2.cpp | externals/tinyxml2/tinyxml2.cpp | null | /*
Original code by Lee Thomason (www.grinninglizard.com)
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include "tinyxml2.h"
#include <new> // yes, this one new style header, is in the Android SDK.
#if defined(ANDROID_NDK) || defined(__BORLANDC__) || defined(__QNXNTO__)
# include <stddef.h>
# include <stdarg.h>
#else
# include <cstddef>
# include <cstdarg>
#endif
#if defined(_MSC_VER) && (_MSC_VER >= 1400 ) && (!defined WINCE)
// Microsoft Visual Studio, version 2005 and higher. Not WinCE.
/*int _snprintf_s(
char *buffer,
size_t sizeOfBuffer,
size_t count,
const char *format [,
argument] ...
);*/
static inline int TIXML_SNPRINTF( char* buffer, size_t size, const char* format, ... )
{
va_list va;
va_start( va, format );
const int result = vsnprintf_s( buffer, size, _TRUNCATE, format, va );
va_end( va );
return result;
}
static inline int TIXML_VSNPRINTF( char* buffer, size_t size, const char* format, va_list va )
{
const int result = vsnprintf_s( buffer, size, _TRUNCATE, format, va );
return result;
}
#define TIXML_VSCPRINTF _vscprintf
#define TIXML_SSCANF sscanf_s
#elif defined _MSC_VER
// Microsoft Visual Studio 2003 and earlier or WinCE
#define TIXML_SNPRINTF _snprintf
#define TIXML_VSNPRINTF _vsnprintf
#define TIXML_SSCANF sscanf
#if (_MSC_VER < 1400 ) && (!defined WINCE)
// Microsoft Visual Studio 2003 and not WinCE.
#define TIXML_VSCPRINTF _vscprintf // VS2003's C runtime has this, but VC6 C runtime or WinCE SDK doesn't have.
#else
// Microsoft Visual Studio 2003 and earlier or WinCE.
static inline int TIXML_VSCPRINTF( const char* format, va_list va )
{
int len = 512;
for (;;) {
len = len*2;
char* str = new char[len]();
const int required = _vsnprintf(str, len, format, va);
delete[] str;
if ( required != -1 ) {
TIXMLASSERT( required >= 0 );
len = required;
break;
}
}
TIXMLASSERT( len >= 0 );
return len;
}
#endif
#else
// GCC version 3 and higher
//#warning( "Using sn* functions." )
#define TIXML_SNPRINTF snprintf
#define TIXML_VSNPRINTF vsnprintf
static inline int TIXML_VSCPRINTF( const char* format, va_list va )
{
int len = vsnprintf( 0, 0, format, va );
TIXMLASSERT( len >= 0 );
return len;
}
#define TIXML_SSCANF sscanf
#endif
#if defined(_WIN64)
#define TIXML_FSEEK _fseeki64
#define TIXML_FTELL _ftelli64
#elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__) || defined(__CYGWIN__)
#define TIXML_FSEEK fseeko
#define TIXML_FTELL ftello
#elif defined(__ANDROID__)
#if __ANDROID_API__ > 24
#define TIXML_FSEEK fseeko64
#define TIXML_FTELL ftello64
#else
#define TIXML_FSEEK fseeko
#define TIXML_FTELL ftello
#endif
#else
#define TIXML_FSEEK fseek
#define TIXML_FTELL ftell
#endif
static const char LINE_FEED = static_cast<char>(0x0a); // all line endings are normalized to LF
static const char LF = LINE_FEED;
static const char CARRIAGE_RETURN = static_cast<char>(0x0d); // CR gets filtered out
static const char CR = CARRIAGE_RETURN;
static const char SINGLE_QUOTE = '\'';
static const char DOUBLE_QUOTE = '\"';
// Bunch of unicode info at:
// http://www.unicode.org/faq/utf_bom.html
// ef bb bf (Microsoft "lead bytes") - designates UTF-8
static const unsigned char TIXML_UTF_LEAD_0 = 0xefU;
static const unsigned char TIXML_UTF_LEAD_1 = 0xbbU;
static const unsigned char TIXML_UTF_LEAD_2 = 0xbfU;
namespace tinyxml2
{
struct Entity {
const char* pattern;
int length;
char value;
};
static const int NUM_ENTITIES = 5;
static const Entity entities[NUM_ENTITIES] = {
{ "quot", 4, DOUBLE_QUOTE },
{ "amp", 3, '&' },
{ "apos", 4, SINGLE_QUOTE },
{ "lt", 2, '<' },
{ "gt", 2, '>' }
};
StrPair::~StrPair()
{
Reset();
}
void StrPair::TransferTo( StrPair* other )
{
if ( this == other ) {
return;
}
// This in effect implements the assignment operator by "moving"
// ownership (as in auto_ptr).
TIXMLASSERT( other != 0 );
TIXMLASSERT( other->_flags == 0 );
TIXMLASSERT( other->_start == 0 );
TIXMLASSERT( other->_end == 0 );
other->Reset();
other->_flags = _flags;
other->_start = _start;
other->_end = _end;
_flags = 0;
_start = 0;
_end = 0;
}
void StrPair::Reset()
{
if ( _flags & NEEDS_DELETE ) {
delete [] _start;
}
_flags = 0;
_start = 0;
_end = 0;
}
void StrPair::SetStr( const char* str, int flags )
{
TIXMLASSERT( str );
Reset();
size_t len = strlen( str );
TIXMLASSERT( _start == 0 );
_start = new char[ len+1 ];
memcpy( _start, str, len+1 );
_end = _start + len;
_flags = flags | NEEDS_DELETE;
}
char* StrPair::ParseText( char* p, const char* endTag, int strFlags, int* curLineNumPtr )
{
TIXMLASSERT( p );
TIXMLASSERT( endTag && *endTag );
TIXMLASSERT(curLineNumPtr);
char* start = p;
const char endChar = *endTag;
size_t length = strlen( endTag );
// Inner loop of text parsing.
while ( *p ) {
if ( *p == endChar && strncmp( p, endTag, length ) == 0 ) {
Set( start, p, strFlags );
return p + length;
} else if (*p == '\n') {
++(*curLineNumPtr);
}
++p;
TIXMLASSERT( p );
}
return 0;
}
char* StrPair::ParseName( char* p )
{
if ( !p || !(*p) ) {
return 0;
}
if ( !XMLUtil::IsNameStartChar( (unsigned char) *p ) ) {
return 0;
}
char* const start = p;
++p;
while ( *p && XMLUtil::IsNameChar( (unsigned char) *p ) ) {
++p;
}
Set( start, p, 0 );
return p;
}
void StrPair::CollapseWhitespace()
{
// Adjusting _start would cause undefined behavior on delete[]
TIXMLASSERT( ( _flags & NEEDS_DELETE ) == 0 );
// Trim leading space.
_start = XMLUtil::SkipWhiteSpace( _start, 0 );
if ( *_start ) {
const char* p = _start; // the read pointer
char* q = _start; // the write pointer
while( *p ) {
if ( XMLUtil::IsWhiteSpace( *p )) {
p = XMLUtil::SkipWhiteSpace( p, 0 );
if ( *p == 0 ) {
break; // don't write to q; this trims the trailing space.
}
*q = ' ';
++q;
}
*q = *p;
++q;
++p;
}
*q = 0;
}
}
const char* StrPair::GetStr()
{
TIXMLASSERT( _start );
TIXMLASSERT( _end );
if ( _flags & NEEDS_FLUSH ) {
*_end = 0;
_flags ^= NEEDS_FLUSH;
if ( _flags ) {
const char* p = _start; // the read pointer
char* q = _start; // the write pointer
while( p < _end ) {
if ( (_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == CR ) {
// CR-LF pair becomes LF
// CR alone becomes LF
// LF-CR becomes LF
if ( *(p+1) == LF ) {
p += 2;
}
else {
++p;
}
*q = LF;
++q;
}
else if ( (_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == LF ) {
if ( *(p+1) == CR ) {
p += 2;
}
else {
++p;
}
*q = LF;
++q;
}
else if ( (_flags & NEEDS_ENTITY_PROCESSING) && *p == '&' ) {
// Entities handled by tinyXML2:
// - special entities in the entity table [in/out]
// - numeric character reference [in]
// 中 or 中
if ( *(p+1) == '#' ) {
const int buflen = 10;
char buf[buflen] = { 0 };
int len = 0;
const char* adjusted = const_cast<char*>( XMLUtil::GetCharacterRef( p, buf, &len ) );
if ( adjusted == 0 ) {
*q = *p;
++p;
++q;
}
else {
TIXMLASSERT( 0 <= len && len <= buflen );
TIXMLASSERT( q + len <= adjusted );
p = adjusted;
memcpy( q, buf, len );
q += len;
}
}
else {
bool entityFound = false;
for( int i = 0; i < NUM_ENTITIES; ++i ) {
const Entity& entity = entities[i];
if ( strncmp( p + 1, entity.pattern, entity.length ) == 0
&& *( p + entity.length + 1 ) == ';' ) {
// Found an entity - convert.
*q = entity.value;
++q;
p += entity.length + 2;
entityFound = true;
break;
}
}
if ( !entityFound ) {
// fixme: treat as error?
++p;
++q;
}
}
}
else {
*q = *p;
++p;
++q;
}
}
*q = 0;
}
// The loop below has plenty going on, and this
// is a less useful mode. Break it out.
if ( _flags & NEEDS_WHITESPACE_COLLAPSING ) {
CollapseWhitespace();
}
_flags = (_flags & NEEDS_DELETE);
}
TIXMLASSERT( _start );
return _start;
}
// --------- XMLUtil ----------- //
const char* XMLUtil::writeBoolTrue = "true";
const char* XMLUtil::writeBoolFalse = "false";
void XMLUtil::SetBoolSerialization(const char* writeTrue, const char* writeFalse)
{
static const char* defTrue = "true";
static const char* defFalse = "false";
writeBoolTrue = (writeTrue) ? writeTrue : defTrue;
writeBoolFalse = (writeFalse) ? writeFalse : defFalse;
}
const char* XMLUtil::ReadBOM( const char* p, bool* bom )
{
TIXMLASSERT( p );
TIXMLASSERT( bom );
*bom = false;
const unsigned char* pu = reinterpret_cast<const unsigned char*>(p);
// Check for BOM:
if ( *(pu+0) == TIXML_UTF_LEAD_0
&& *(pu+1) == TIXML_UTF_LEAD_1
&& *(pu+2) == TIXML_UTF_LEAD_2 ) {
*bom = true;
p += 3;
}
TIXMLASSERT( p );
return p;
}
void XMLUtil::ConvertUTF32ToUTF8( unsigned long input, char* output, int* length )
{
const unsigned long BYTE_MASK = 0xBF;
const unsigned long BYTE_MARK = 0x80;
const unsigned long FIRST_BYTE_MARK[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC };
if (input < 0x80) {
*length = 1;
}
else if ( input < 0x800 ) {
*length = 2;
}
else if ( input < 0x10000 ) {
*length = 3;
}
else if ( input < 0x200000 ) {
*length = 4;
}
else {
*length = 0; // This code won't convert this correctly anyway.
return;
}
output += *length;
// Scary scary fall throughs are annotated with carefully designed comments
// to suppress compiler warnings such as -Wimplicit-fallthrough in gcc
switch (*length) {
case 4:
--output;
*output = static_cast<char>((input | BYTE_MARK) & BYTE_MASK);
input >>= 6;
//fall through
case 3:
--output;
*output = static_cast<char>((input | BYTE_MARK) & BYTE_MASK);
input >>= 6;
//fall through
case 2:
--output;
*output = static_cast<char>((input | BYTE_MARK) & BYTE_MASK);
input >>= 6;
//fall through
case 1:
--output;
*output = static_cast<char>(input | FIRST_BYTE_MARK[*length]);
break;
default:
TIXMLASSERT( false );
}
}
const char* XMLUtil::GetCharacterRef( const char* p, char* value, int* length )
{
// Presume an entity, and pull it out.
*length = 0;
if ( *(p+1) == '#' && *(p+2) ) {
unsigned long ucs = 0;
TIXMLASSERT( sizeof( ucs ) >= 4 );
ptrdiff_t delta = 0;
unsigned mult = 1;
static const char SEMICOLON = ';';
if ( *(p+2) == 'x' ) {
// Hexadecimal.
const char* q = p+3;
if ( !(*q) ) {
return 0;
}
q = strchr( q, SEMICOLON );
if ( !q ) {
return 0;
}
TIXMLASSERT( *q == SEMICOLON );
delta = q-p;
--q;
while ( *q != 'x' ) {
unsigned int digit = 0;
if ( *q >= '0' && *q <= '9' ) {
digit = *q - '0';
}
else if ( *q >= 'a' && *q <= 'f' ) {
digit = *q - 'a' + 10;
}
else if ( *q >= 'A' && *q <= 'F' ) {
digit = *q - 'A' + 10;
}
else {
return 0;
}
TIXMLASSERT( digit < 16 );
TIXMLASSERT( digit == 0 || mult <= UINT_MAX / digit );
const unsigned int digitScaled = mult * digit;
TIXMLASSERT( ucs <= ULONG_MAX - digitScaled );
ucs += digitScaled;
TIXMLASSERT( mult <= UINT_MAX / 16 );
mult *= 16;
--q;
}
}
else {
// Decimal.
const char* q = p+2;
if ( !(*q) ) {
return 0;
}
q = strchr( q, SEMICOLON );
if ( !q ) {
return 0;
}
TIXMLASSERT( *q == SEMICOLON );
delta = q-p;
--q;
while ( *q != '#' ) {
if ( *q >= '0' && *q <= '9' ) {
const unsigned int digit = *q - '0';
TIXMLASSERT( digit < 10 );
TIXMLASSERT( digit == 0 || mult <= UINT_MAX / digit );
const unsigned int digitScaled = mult * digit;
TIXMLASSERT( ucs <= ULONG_MAX - digitScaled );
ucs += digitScaled;
}
else {
return 0;
}
TIXMLASSERT( mult <= UINT_MAX / 10 );
mult *= 10;
--q;
}
}
// convert the UCS to UTF-8
ConvertUTF32ToUTF8( ucs, value, length );
return p + delta + 1;
}
return p+1;
}
void XMLUtil::ToStr( int v, char* buffer, int bufferSize )
{
TIXML_SNPRINTF( buffer, bufferSize, "%d", v );
}
void XMLUtil::ToStr( unsigned v, char* buffer, int bufferSize )
{
TIXML_SNPRINTF( buffer, bufferSize, "%u", v );
}
void XMLUtil::ToStr( bool v, char* buffer, int bufferSize )
{
TIXML_SNPRINTF( buffer, bufferSize, "%s", v ? writeBoolTrue : writeBoolFalse);
}
/*
ToStr() of a number is a very tricky topic.
https://github.com/leethomason/tinyxml2/issues/106
*/
void XMLUtil::ToStr( float v, char* buffer, int bufferSize )
{
TIXML_SNPRINTF( buffer, bufferSize, "%.8g", v );
}
void XMLUtil::ToStr( double v, char* buffer, int bufferSize )
{
TIXML_SNPRINTF( buffer, bufferSize, "%.17g", v );
}
void XMLUtil::ToStr( int64_t v, char* buffer, int bufferSize )
{
// horrible syntax trick to make the compiler happy about %lld
TIXML_SNPRINTF(buffer, bufferSize, "%lld", static_cast<long long>(v));
}
void XMLUtil::ToStr( uint64_t v, char* buffer, int bufferSize )
{
// horrible syntax trick to make the compiler happy about %llu
TIXML_SNPRINTF(buffer, bufferSize, "%llu", (long long)v);
}
bool XMLUtil::ToInt(const char* str, int* value)
{
if (IsPrefixHex(str)) {
unsigned v;
if (TIXML_SSCANF(str, "%x", &v) == 1) {
*value = static_cast<int>(v);
return true;
}
}
else {
if (TIXML_SSCANF(str, "%d", value) == 1) {
return true;
}
}
return false;
}
bool XMLUtil::ToUnsigned(const char* str, unsigned* value)
{
if (TIXML_SSCANF(str, IsPrefixHex(str) ? "%x" : "%u", value) == 1) {
return true;
}
return false;
}
bool XMLUtil::ToBool( const char* str, bool* value )
{
int ival = 0;
if ( ToInt( str, &ival )) {
*value = (ival==0) ? false : true;
return true;
}
static const char* TRUE_VALS[] = { "true", "True", "TRUE", 0 };
static const char* FALSE_VALS[] = { "false", "False", "FALSE", 0 };
for (int i = 0; TRUE_VALS[i]; ++i) {
if (StringEqual(str, TRUE_VALS[i])) {
*value = true;
return true;
}
}
for (int i = 0; FALSE_VALS[i]; ++i) {
if (StringEqual(str, FALSE_VALS[i])) {
*value = false;
return true;
}
}
return false;
}
bool XMLUtil::ToFloat( const char* str, float* value )
{
if ( TIXML_SSCANF( str, "%f", value ) == 1 ) {
return true;
}
return false;
}
bool XMLUtil::ToDouble( const char* str, double* value )
{
if ( TIXML_SSCANF( str, "%lf", value ) == 1 ) {
return true;
}
return false;
}
bool XMLUtil::ToInt64(const char* str, int64_t* value)
{
if (IsPrefixHex(str)) {
unsigned long long v = 0; // horrible syntax trick to make the compiler happy about %llx
if (TIXML_SSCANF(str, "%llx", &v) == 1) {
*value = static_cast<int64_t>(v);
return true;
}
}
else {
long long v = 0; // horrible syntax trick to make the compiler happy about %lld
if (TIXML_SSCANF(str, "%lld", &v) == 1) {
*value = static_cast<int64_t>(v);
return true;
}
}
return false;
}
bool XMLUtil::ToUnsigned64(const char* str, uint64_t* value) {
unsigned long long v = 0; // horrible syntax trick to make the compiler happy about %llu
if(TIXML_SSCANF(str, IsPrefixHex(str) ? "%llx" : "%llu", &v) == 1) {
*value = (uint64_t)v;
return true;
}
return false;
}
char* XMLDocument::Identify( char* p, XMLNode** node, bool first )
{
TIXMLASSERT( node );
TIXMLASSERT( p );
char* const start = p;
int const startLine = _parseCurLineNum;
p = XMLUtil::SkipWhiteSpace( p, &_parseCurLineNum );
if( !*p ) {
*node = 0;
TIXMLASSERT( p );
return p;
}
// These strings define the matching patterns:
static const char* xmlHeader = { "<?" };
static const char* commentHeader = { "<!--" };
static const char* cdataHeader = { "<![CDATA[" };
static const char* dtdHeader = { "<!" };
static const char* elementHeader = { "<" }; // and a header for everything else; check last.
static const int xmlHeaderLen = 2;
static const int commentHeaderLen = 4;
static const int cdataHeaderLen = 9;
static const int dtdHeaderLen = 2;
static const int elementHeaderLen = 1;
TIXMLASSERT( sizeof( XMLComment ) == sizeof( XMLUnknown ) ); // use same memory pool
TIXMLASSERT( sizeof( XMLComment ) == sizeof( XMLDeclaration ) ); // use same memory pool
XMLNode* returnNode = 0;
if ( XMLUtil::StringEqual( p, xmlHeader, xmlHeaderLen ) ) {
returnNode = CreateUnlinkedNode<XMLDeclaration>( _commentPool );
returnNode->_parseLineNum = _parseCurLineNum;
p += xmlHeaderLen;
}
else if ( XMLUtil::StringEqual( p, commentHeader, commentHeaderLen ) ) {
returnNode = CreateUnlinkedNode<XMLComment>( _commentPool );
returnNode->_parseLineNum = _parseCurLineNum;
p += commentHeaderLen;
}
else if ( XMLUtil::StringEqual( p, cdataHeader, cdataHeaderLen ) ) {
XMLText* text = CreateUnlinkedNode<XMLText>( _textPool );
returnNode = text;
returnNode->_parseLineNum = _parseCurLineNum;
p += cdataHeaderLen;
text->SetCData( true );
}
else if ( XMLUtil::StringEqual( p, dtdHeader, dtdHeaderLen ) ) {
returnNode = CreateUnlinkedNode<XMLUnknown>( _commentPool );
returnNode->_parseLineNum = _parseCurLineNum;
p += dtdHeaderLen;
}
else if ( XMLUtil::StringEqual( p, elementHeader, elementHeaderLen ) ) {
// Preserve whitespace pedantically before closing tag, when it's immediately after opening tag
if (WhitespaceMode() == PEDANTIC_WHITESPACE && first && p != start && *(p + elementHeaderLen) == '/') {
returnNode = CreateUnlinkedNode<XMLText>(_textPool);
returnNode->_parseLineNum = startLine;
p = start; // Back it up, all the text counts.
_parseCurLineNum = startLine;
}
else {
returnNode = CreateUnlinkedNode<XMLElement>(_elementPool);
returnNode->_parseLineNum = _parseCurLineNum;
p += elementHeaderLen;
}
}
else {
returnNode = CreateUnlinkedNode<XMLText>( _textPool );
returnNode->_parseLineNum = _parseCurLineNum; // Report line of first non-whitespace character
p = start; // Back it up, all the text counts.
_parseCurLineNum = startLine;
}
TIXMLASSERT( returnNode );
TIXMLASSERT( p );
*node = returnNode;
return p;
}
bool XMLDocument::Accept( XMLVisitor* visitor ) const
{
TIXMLASSERT( visitor );
if ( visitor->VisitEnter( *this ) ) {
for ( const XMLNode* node=FirstChild(); node; node=node->NextSibling() ) {
if ( !node->Accept( visitor ) ) {
break;
}
}
}
return visitor->VisitExit( *this );
}
// --------- XMLNode ----------- //
XMLNode::XMLNode( XMLDocument* doc ) :
_document( doc ),
_parent( 0 ),
_value(),
_parseLineNum( 0 ),
_firstChild( 0 ), _lastChild( 0 ),
_prev( 0 ), _next( 0 ),
_userData( 0 ),
_memPool( 0 )
{
}
XMLNode::~XMLNode()
{
DeleteChildren();
if ( _parent ) {
_parent->Unlink( this );
}
}
// ChildElementCount was originally suggested by msteiger on the sourceforge page for TinyXML and modified by KB1SPH for TinyXML-2.
int XMLNode::ChildElementCount(const char *value) const {
int count = 0;
const XMLElement *e = FirstChildElement(value);
while (e) {
e = e->NextSiblingElement(value);
count++;
}
return count;
}
int XMLNode::ChildElementCount() const {
int count = 0;
const XMLElement *e = FirstChildElement();
while (e) {
e = e->NextSiblingElement();
count++;
}
return count;
}
const char* XMLNode::Value() const
{
// Edge case: XMLDocuments don't have a Value. Return null.
if ( this->ToDocument() )
return 0;
return _value.GetStr();
}
void XMLNode::SetValue( const char* str, bool staticMem )
{
if ( staticMem ) {
_value.SetInternedStr( str );
}
else {
_value.SetStr( str );
}
}
XMLNode* XMLNode::DeepClone(XMLDocument* target) const
{
XMLNode* clone = this->ShallowClone(target);
if (!clone) return 0;
for (const XMLNode* child = this->FirstChild(); child; child = child->NextSibling()) {
XMLNode* childClone = child->DeepClone(target);
TIXMLASSERT(childClone);
clone->InsertEndChild(childClone);
}
return clone;
}
void XMLNode::DeleteChildren()
{
while( _firstChild ) {
TIXMLASSERT( _lastChild );
DeleteChild( _firstChild );
}
_firstChild = _lastChild = 0;
}
void XMLNode::Unlink( XMLNode* child )
{
TIXMLASSERT( child );
TIXMLASSERT( child->_document == _document );
TIXMLASSERT( child->_parent == this );
if ( child == _firstChild ) {
_firstChild = _firstChild->_next;
}
if ( child == _lastChild ) {
_lastChild = _lastChild->_prev;
}
if ( child->_prev ) {
child->_prev->_next = child->_next;
}
if ( child->_next ) {
child->_next->_prev = child->_prev;
}
child->_next = 0;
child->_prev = 0;
child->_parent = 0;
}
void XMLNode::DeleteChild( XMLNode* node )
{
TIXMLASSERT( node );
TIXMLASSERT( node->_document == _document );
TIXMLASSERT( node->_parent == this );
Unlink( node );
TIXMLASSERT(node->_prev == 0);
TIXMLASSERT(node->_next == 0);
TIXMLASSERT(node->_parent == 0);
DeleteNode( node );
}
XMLNode* XMLNode::InsertEndChild( XMLNode* addThis )
{
TIXMLASSERT( addThis );
if ( addThis->_document != _document ) {
TIXMLASSERT( false );
return 0;
}
InsertChildPreamble( addThis );
if ( _lastChild ) {
TIXMLASSERT( _firstChild );
TIXMLASSERT( _lastChild->_next == 0 );
_lastChild->_next = addThis;
addThis->_prev = _lastChild;
_lastChild = addThis;
addThis->_next = 0;
}
else {
TIXMLASSERT( _firstChild == 0 );
_firstChild = _lastChild = addThis;
addThis->_prev = 0;
addThis->_next = 0;
}
addThis->_parent = this;
return addThis;
}
XMLNode* XMLNode::InsertFirstChild( XMLNode* addThis )
{
TIXMLASSERT( addThis );
if ( addThis->_document != _document ) {
TIXMLASSERT( false );
return 0;
}
InsertChildPreamble( addThis );
if ( _firstChild ) {
TIXMLASSERT( _lastChild );
TIXMLASSERT( _firstChild->_prev == 0 );
_firstChild->_prev = addThis;
addThis->_next = _firstChild;
_firstChild = addThis;
addThis->_prev = 0;
}
else {
TIXMLASSERT( _lastChild == 0 );
_firstChild = _lastChild = addThis;
addThis->_prev = 0;
addThis->_next = 0;
}
addThis->_parent = this;
return addThis;
}
XMLNode* XMLNode::InsertAfterChild( XMLNode* afterThis, XMLNode* addThis )
{
TIXMLASSERT( addThis );
if ( addThis->_document != _document ) {
TIXMLASSERT( false );
return 0;
}
TIXMLASSERT( afterThis );
if ( afterThis->_parent != this ) {
TIXMLASSERT( false );
return 0;
}
if ( afterThis == addThis ) {
// Current state: BeforeThis -> AddThis -> OneAfterAddThis
// Now AddThis must disappear from it's location and then
// reappear between BeforeThis and OneAfterAddThis.
// So just leave it where it is.
return addThis;
}
if ( afterThis->_next == 0 ) {
// The last node or the only node.
return InsertEndChild( addThis );
}
InsertChildPreamble( addThis );
addThis->_prev = afterThis;
addThis->_next = afterThis->_next;
afterThis->_next->_prev = addThis;
afterThis->_next = addThis;
addThis->_parent = this;
return addThis;
}
const XMLElement* XMLNode::FirstChildElement( const char* name ) const
{
for( const XMLNode* node = _firstChild; node; node = node->_next ) {
const XMLElement* element = node->ToElementWithName( name );
if ( element ) {
return element;
}
}
return 0;
}
const XMLElement* XMLNode::LastChildElement( const char* name ) const
{
for( const XMLNode* node = _lastChild; node; node = node->_prev ) {
const XMLElement* element = node->ToElementWithName( name );
if ( element ) {
return element;
}
}
return 0;
}
const XMLElement* XMLNode::NextSiblingElement( const char* name ) const
{
for( const XMLNode* node = _next; node; node = node->_next ) {
const XMLElement* element = node->ToElementWithName( name );
if ( element ) {
return element;
}
}
return 0;
}
const XMLElement* XMLNode::PreviousSiblingElement( const char* name ) const
{
for( const XMLNode* node = _prev; node; node = node->_prev ) {
const XMLElement* element = node->ToElementWithName( name );
if ( element ) {
return element;
}
}
return 0;
}
char* XMLNode::ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr )
{
// This is a recursive method, but thinking about it "at the current level"
// it is a pretty simple flat list:
// <foo/>
// <!-- comment -->
//
// With a special case:
// <foo>
// </foo>
// <!-- comment -->
//
// Where the closing element (/foo) *must* be the next thing after the opening
// element, and the names must match. BUT the tricky bit is that the closing
// element will be read by the child.
//
// 'endTag' is the end tag for this node, it is returned by a call to a child.
// 'parentEnd' is the end tag for the parent, which is filled in and returned.
XMLDocument::DepthTracker tracker(_document);
if (_document->Error())
return 0;
bool first = true;
while( p && *p ) {
XMLNode* node = 0;
p = _document->Identify( p, &node, first );
TIXMLASSERT( p );
if ( node == 0 ) {
break;
}
first = false;
const int initialLineNum = node->_parseLineNum;
StrPair endTag;
p = node->ParseDeep( p, &endTag, curLineNumPtr );
if ( !p ) {
_document->DeleteNode( node );
if ( !_document->Error() ) {
_document->SetError( XML_ERROR_PARSING, initialLineNum, 0);
}
break;
}
const XMLDeclaration* const decl = node->ToDeclaration();
if ( decl ) {
// Declarations are only allowed at document level
//
// Multiple declarations are allowed but all declarations
// must occur before anything else.
//
// Optimized due to a security test case. If the first node is
// a declaration, and the last node is a declaration, then only
// declarations have so far been added.
bool wellLocated = false;
if (ToDocument()) {
if (FirstChild()) {
wellLocated =
FirstChild() &&
FirstChild()->ToDeclaration() &&
LastChild() &&
LastChild()->ToDeclaration();
}
else {
wellLocated = true;
}
}
if ( !wellLocated ) {
_document->SetError( XML_ERROR_PARSING_DECLARATION, initialLineNum, "XMLDeclaration value=%s", decl->Value());
_document->DeleteNode( node );
break;
}
}
XMLElement* ele = node->ToElement();
if ( ele ) {
// We read the end tag. Return it to the parent.
if ( ele->ClosingType() == XMLElement::CLOSING ) {
if ( parentEndTag ) {
ele->_value.TransferTo( parentEndTag );
}
node->_memPool->SetTracked(); // created and then immediately deleted.
DeleteNode( node );
return p;
}
// Handle an end tag returned to this level.
// And handle a bunch of annoying errors.
bool mismatch = false;
if ( endTag.Empty() ) {
if ( ele->ClosingType() == XMLElement::OPEN ) {
mismatch = true;
}
}
else {
if ( ele->ClosingType() != XMLElement::OPEN ) {
mismatch = true;
}
else if ( !XMLUtil::StringEqual( endTag.GetStr(), ele->Name() ) ) {
mismatch = true;
}
}
if ( mismatch ) {
_document->SetError( XML_ERROR_MISMATCHED_ELEMENT, initialLineNum, "XMLElement name=%s", ele->Name());
_document->DeleteNode( node );
break;
}
}
InsertEndChild( node );
}
return 0;
}
/*static*/ void XMLNode::DeleteNode( XMLNode* node )
{
if ( node == 0 ) {
return;
}
TIXMLASSERT(node->_document);
if (!node->ToDocument()) {
node->_document->MarkInUse(node);
}
MemPool* pool = node->_memPool;
node->~XMLNode();
pool->Free( node );
}
void XMLNode::InsertChildPreamble( XMLNode* insertThis ) const
{
TIXMLASSERT( insertThis );
TIXMLASSERT( insertThis->_document == _document );
if (insertThis->_parent) {
insertThis->_parent->Unlink( insertThis );
}
else {
insertThis->_document->MarkInUse(insertThis);
insertThis->_memPool->SetTracked();
}
}
const XMLElement* XMLNode::ToElementWithName( const char* name ) const
{
const XMLElement* element = this->ToElement();
if ( element == 0 ) {
return 0;
}
if ( name == 0 ) {
return element;
}
if ( XMLUtil::StringEqual( element->Name(), name ) ) {
return element;
}
return 0;
}
// --------- XMLText ---------- //
char* XMLText::ParseDeep( char* p, StrPair*, int* curLineNumPtr )
{
if ( this->CData() ) {
p = _value.ParseText( p, "]]>", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr );
if ( !p ) {
_document->SetError( XML_ERROR_PARSING_CDATA, _parseLineNum, 0 );
}
return p;
}
else {
int flags = _document->ProcessEntities() ? StrPair::TEXT_ELEMENT : StrPair::TEXT_ELEMENT_LEAVE_ENTITIES;
if ( _document->WhitespaceMode() == COLLAPSE_WHITESPACE ) {
flags |= StrPair::NEEDS_WHITESPACE_COLLAPSING;
}
p = _value.ParseText( p, "<", flags, curLineNumPtr );
if ( p && *p ) {
return p-1;
}
if ( !p ) {
_document->SetError( XML_ERROR_PARSING_TEXT, _parseLineNum, 0 );
}
}
return 0;
}
XMLNode* XMLText::ShallowClone( XMLDocument* doc ) const
{
if ( !doc ) {
doc = _document;
}
XMLText* text = doc->NewText( Value() ); // fixme: this will always allocate memory. Intern?
text->SetCData( this->CData() );
return text;
}
bool XMLText::ShallowEqual( const XMLNode* compare ) const
{
TIXMLASSERT( compare );
const XMLText* text = compare->ToText();
return ( text && XMLUtil::StringEqual( text->Value(), Value() ) );
}
bool XMLText::Accept( XMLVisitor* visitor ) const
{
TIXMLASSERT( visitor );
return visitor->Visit( *this );
}
// --------- XMLComment ---------- //
XMLComment::XMLComment( XMLDocument* doc ) : XMLNode( doc )
{
}
XMLComment::~XMLComment()
{
}
char* XMLComment::ParseDeep( char* p, StrPair*, int* curLineNumPtr )
{
// Comment parses as text.
p = _value.ParseText( p, "-->", StrPair::COMMENT, curLineNumPtr );
if ( p == 0 ) {
_document->SetError( XML_ERROR_PARSING_COMMENT, _parseLineNum, 0 );
}
return p;
}
XMLNode* XMLComment::ShallowClone( XMLDocument* doc ) const
{
if ( !doc ) {
doc = _document;
}
XMLComment* comment = doc->NewComment( Value() ); // fixme: this will always allocate memory. Intern?
return comment;
}
bool XMLComment::ShallowEqual( const XMLNode* compare ) const
{
TIXMLASSERT( compare );
const XMLComment* comment = compare->ToComment();
return ( comment && XMLUtil::StringEqual( comment->Value(), Value() ));
}
bool XMLComment::Accept( XMLVisitor* visitor ) const
{
TIXMLASSERT( visitor );
return visitor->Visit( *this );
}
// --------- XMLDeclaration ---------- //
XMLDeclaration::XMLDeclaration( XMLDocument* doc ) : XMLNode( doc )
{
}
XMLDeclaration::~XMLDeclaration()
{
//printf( "~XMLDeclaration\n" );
}
char* XMLDeclaration::ParseDeep( char* p, StrPair*, int* curLineNumPtr )
{
// Declaration parses as text.
p = _value.ParseText( p, "?>", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr );
if ( p == 0 ) {
_document->SetError( XML_ERROR_PARSING_DECLARATION, _parseLineNum, 0 );
}
return p;
}
XMLNode* XMLDeclaration::ShallowClone( XMLDocument* doc ) const
{
if ( !doc ) {
doc = _document;
}
XMLDeclaration* dec = doc->NewDeclaration( Value() ); // fixme: this will always allocate memory. Intern?
return dec;
}
bool XMLDeclaration::ShallowEqual( const XMLNode* compare ) const
{
TIXMLASSERT( compare );
const XMLDeclaration* declaration = compare->ToDeclaration();
return ( declaration && XMLUtil::StringEqual( declaration->Value(), Value() ));
}
bool XMLDeclaration::Accept( XMLVisitor* visitor ) const
{
TIXMLASSERT( visitor );
return visitor->Visit( *this );
}
// --------- XMLUnknown ---------- //
XMLUnknown::XMLUnknown( XMLDocument* doc ) : XMLNode( doc )
{
}
XMLUnknown::~XMLUnknown()
{
}
char* XMLUnknown::ParseDeep( char* p, StrPair*, int* curLineNumPtr )
{
// Unknown parses as text.
p = _value.ParseText( p, ">", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr );
if ( !p ) {
_document->SetError( XML_ERROR_PARSING_UNKNOWN, _parseLineNum, 0 );
}
return p;
}
XMLNode* XMLUnknown::ShallowClone( XMLDocument* doc ) const
{
if ( !doc ) {
doc = _document;
}
XMLUnknown* text = doc->NewUnknown( Value() ); // fixme: this will always allocate memory. Intern?
return text;
}
bool XMLUnknown::ShallowEqual( const XMLNode* compare ) const
{
TIXMLASSERT( compare );
const XMLUnknown* unknown = compare->ToUnknown();
return ( unknown && XMLUtil::StringEqual( unknown->Value(), Value() ));
}
bool XMLUnknown::Accept( XMLVisitor* visitor ) const
{
TIXMLASSERT( visitor );
return visitor->Visit( *this );
}
// --------- XMLAttribute ---------- //
const char* XMLAttribute::Name() const
{
return _name.GetStr();
}
const char* XMLAttribute::Value() const
{
return _value.GetStr();
}
char* XMLAttribute::ParseDeep( char* p, bool processEntities, int* curLineNumPtr )
{
// Parse using the name rules: bug fix, was using ParseText before
p = _name.ParseName( p );
if ( !p || !*p ) {
return 0;
}
// Skip white space before =
p = XMLUtil::SkipWhiteSpace( p, curLineNumPtr );
if ( *p != '=' ) {
return 0;
}
++p; // move up to opening quote
p = XMLUtil::SkipWhiteSpace( p, curLineNumPtr );
if ( *p != '\"' && *p != '\'' ) {
return 0;
}
const char endTag[2] = { *p, 0 };
++p; // move past opening quote
p = _value.ParseText( p, endTag, processEntities ? StrPair::ATTRIBUTE_VALUE : StrPair::ATTRIBUTE_VALUE_LEAVE_ENTITIES, curLineNumPtr );
return p;
}
void XMLAttribute::SetName( const char* n )
{
_name.SetStr( n );
}
XMLError XMLAttribute::QueryIntValue( int* value ) const
{
if ( XMLUtil::ToInt( Value(), value )) {
return XML_SUCCESS;
}
return XML_WRONG_ATTRIBUTE_TYPE;
}
XMLError XMLAttribute::QueryUnsignedValue( unsigned int* value ) const
{
if ( XMLUtil::ToUnsigned( Value(), value )) {
return XML_SUCCESS;
}
return XML_WRONG_ATTRIBUTE_TYPE;
}
XMLError XMLAttribute::QueryInt64Value(int64_t* value) const
{
if (XMLUtil::ToInt64(Value(), value)) {
return XML_SUCCESS;
}
return XML_WRONG_ATTRIBUTE_TYPE;
}
XMLError XMLAttribute::QueryUnsigned64Value(uint64_t* value) const
{
if(XMLUtil::ToUnsigned64(Value(), value)) {
return XML_SUCCESS;
}
return XML_WRONG_ATTRIBUTE_TYPE;
}
XMLError XMLAttribute::QueryBoolValue( bool* value ) const
{
if ( XMLUtil::ToBool( Value(), value )) {
return XML_SUCCESS;
}
return XML_WRONG_ATTRIBUTE_TYPE;
}
XMLError XMLAttribute::QueryFloatValue( float* value ) const
{
if ( XMLUtil::ToFloat( Value(), value )) {
return XML_SUCCESS;
}
return XML_WRONG_ATTRIBUTE_TYPE;
}
XMLError XMLAttribute::QueryDoubleValue( double* value ) const
{
if ( XMLUtil::ToDouble( Value(), value )) {
return XML_SUCCESS;
}
return XML_WRONG_ATTRIBUTE_TYPE;
}
void XMLAttribute::SetAttribute( const char* v )
{
_value.SetStr( v );
}
void XMLAttribute::SetAttribute( int v )
{
char buf[BUF_SIZE];
XMLUtil::ToStr( v, buf, BUF_SIZE );
_value.SetStr( buf );
}
void XMLAttribute::SetAttribute( unsigned v )
{
char buf[BUF_SIZE];
XMLUtil::ToStr( v, buf, BUF_SIZE );
_value.SetStr( buf );
}
void XMLAttribute::SetAttribute(int64_t v)
{
char buf[BUF_SIZE];
XMLUtil::ToStr(v, buf, BUF_SIZE);
_value.SetStr(buf);
}
void XMLAttribute::SetAttribute(uint64_t v)
{
char buf[BUF_SIZE];
XMLUtil::ToStr(v, buf, BUF_SIZE);
_value.SetStr(buf);
}
void XMLAttribute::SetAttribute( bool v )
{
char buf[BUF_SIZE];
XMLUtil::ToStr( v, buf, BUF_SIZE );
_value.SetStr( buf );
}
void XMLAttribute::SetAttribute( double v )
{
char buf[BUF_SIZE];
XMLUtil::ToStr( v, buf, BUF_SIZE );
_value.SetStr( buf );
}
void XMLAttribute::SetAttribute( float v )
{
char buf[BUF_SIZE];
XMLUtil::ToStr( v, buf, BUF_SIZE );
_value.SetStr( buf );
}
// --------- XMLElement ---------- //
XMLElement::XMLElement( XMLDocument* doc ) : XMLNode( doc ),
_closingType( OPEN ),
_rootAttribute( 0 )
{
}
XMLElement::~XMLElement()
{
while( _rootAttribute ) {
XMLAttribute* next = _rootAttribute->_next;
DeleteAttribute( _rootAttribute );
_rootAttribute = next;
}
}
const XMLAttribute* XMLElement::FindAttribute( const char* name ) const
{
for( XMLAttribute* a = _rootAttribute; a; a = a->_next ) {
if ( XMLUtil::StringEqual( a->Name(), name ) ) {
return a;
}
}
return 0;
}
const char* XMLElement::Attribute( const char* name, const char* value ) const
{
const XMLAttribute* a = FindAttribute( name );
if ( !a ) {
return 0;
}
if ( !value || XMLUtil::StringEqual( a->Value(), value )) {
return a->Value();
}
return 0;
}
int XMLElement::IntAttribute(const char* name, int defaultValue) const
{
int i = defaultValue;
QueryIntAttribute(name, &i);
return i;
}
unsigned XMLElement::UnsignedAttribute(const char* name, unsigned defaultValue) const
{
unsigned i = defaultValue;
QueryUnsignedAttribute(name, &i);
return i;
}
int64_t XMLElement::Int64Attribute(const char* name, int64_t defaultValue) const
{
int64_t i = defaultValue;
QueryInt64Attribute(name, &i);
return i;
}
uint64_t XMLElement::Unsigned64Attribute(const char* name, uint64_t defaultValue) const
{
uint64_t i = defaultValue;
QueryUnsigned64Attribute(name, &i);
return i;
}
bool XMLElement::BoolAttribute(const char* name, bool defaultValue) const
{
bool b = defaultValue;
QueryBoolAttribute(name, &b);
return b;
}
double XMLElement::DoubleAttribute(const char* name, double defaultValue) const
{
double d = defaultValue;
QueryDoubleAttribute(name, &d);
return d;
}
float XMLElement::FloatAttribute(const char* name, float defaultValue) const
{
float f = defaultValue;
QueryFloatAttribute(name, &f);
return f;
}
const char* XMLElement::GetText() const
{
/* skip comment node */
const XMLNode* node = FirstChild();
while (node) {
if (node->ToComment()) {
node = node->NextSibling();
continue;
}
break;
}
if ( node && node->ToText() ) {
return node->Value();
}
return 0;
}
void XMLElement::SetText( const char* inText )
{
if ( FirstChild() && FirstChild()->ToText() )
FirstChild()->SetValue( inText );
else {
XMLText* theText = GetDocument()->NewText( inText );
InsertFirstChild( theText );
}
}
void XMLElement::SetText( int v )
{
char buf[BUF_SIZE];
XMLUtil::ToStr( v, buf, BUF_SIZE );
SetText( buf );
}
void XMLElement::SetText( unsigned v )
{
char buf[BUF_SIZE];
XMLUtil::ToStr( v, buf, BUF_SIZE );
SetText( buf );
}
void XMLElement::SetText(int64_t v)
{
char buf[BUF_SIZE];
XMLUtil::ToStr(v, buf, BUF_SIZE);
SetText(buf);
}
void XMLElement::SetText(uint64_t v) {
char buf[BUF_SIZE];
XMLUtil::ToStr(v, buf, BUF_SIZE);
SetText(buf);
}
void XMLElement::SetText( bool v )
{
char buf[BUF_SIZE];
XMLUtil::ToStr( v, buf, BUF_SIZE );
SetText( buf );
}
void XMLElement::SetText( float v )
{
char buf[BUF_SIZE];
XMLUtil::ToStr( v, buf, BUF_SIZE );
SetText( buf );
}
void XMLElement::SetText( double v )
{
char buf[BUF_SIZE];
XMLUtil::ToStr( v, buf, BUF_SIZE );
SetText( buf );
}
XMLError XMLElement::QueryIntText( int* ival ) const
{
if ( FirstChild() && FirstChild()->ToText() ) {
const char* t = FirstChild()->Value();
if ( XMLUtil::ToInt( t, ival ) ) {
return XML_SUCCESS;
}
return XML_CAN_NOT_CONVERT_TEXT;
}
return XML_NO_TEXT_NODE;
}
XMLError XMLElement::QueryUnsignedText( unsigned* uval ) const
{
if ( FirstChild() && FirstChild()->ToText() ) {
const char* t = FirstChild()->Value();
if ( XMLUtil::ToUnsigned( t, uval ) ) {
return XML_SUCCESS;
}
return XML_CAN_NOT_CONVERT_TEXT;
}
return XML_NO_TEXT_NODE;
}
XMLError XMLElement::QueryInt64Text(int64_t* ival) const
{
if (FirstChild() && FirstChild()->ToText()) {
const char* t = FirstChild()->Value();
if (XMLUtil::ToInt64(t, ival)) {
return XML_SUCCESS;
}
return XML_CAN_NOT_CONVERT_TEXT;
}
return XML_NO_TEXT_NODE;
}
XMLError XMLElement::QueryUnsigned64Text(uint64_t* uval) const
{
if(FirstChild() && FirstChild()->ToText()) {
const char* t = FirstChild()->Value();
if(XMLUtil::ToUnsigned64(t, uval)) {
return XML_SUCCESS;
}
return XML_CAN_NOT_CONVERT_TEXT;
}
return XML_NO_TEXT_NODE;
}
XMLError XMLElement::QueryBoolText( bool* bval ) const
{
if ( FirstChild() && FirstChild()->ToText() ) {
const char* t = FirstChild()->Value();
if ( XMLUtil::ToBool( t, bval ) ) {
return XML_SUCCESS;
}
return XML_CAN_NOT_CONVERT_TEXT;
}
return XML_NO_TEXT_NODE;
}
XMLError XMLElement::QueryDoubleText( double* dval ) const
{
if ( FirstChild() && FirstChild()->ToText() ) {
const char* t = FirstChild()->Value();
if ( XMLUtil::ToDouble( t, dval ) ) {
return XML_SUCCESS;
}
return XML_CAN_NOT_CONVERT_TEXT;
}
return XML_NO_TEXT_NODE;
}
XMLError XMLElement::QueryFloatText( float* fval ) const
{
if ( FirstChild() && FirstChild()->ToText() ) {
const char* t = FirstChild()->Value();
if ( XMLUtil::ToFloat( t, fval ) ) {
return XML_SUCCESS;
}
return XML_CAN_NOT_CONVERT_TEXT;
}
return XML_NO_TEXT_NODE;
}
int XMLElement::IntText(int defaultValue) const
{
int i = defaultValue;
QueryIntText(&i);
return i;
}
unsigned XMLElement::UnsignedText(unsigned defaultValue) const
{
unsigned i = defaultValue;
QueryUnsignedText(&i);
return i;
}
int64_t XMLElement::Int64Text(int64_t defaultValue) const
{
int64_t i = defaultValue;
QueryInt64Text(&i);
return i;
}
uint64_t XMLElement::Unsigned64Text(uint64_t defaultValue) const
{
uint64_t i = defaultValue;
QueryUnsigned64Text(&i);
return i;
}
bool XMLElement::BoolText(bool defaultValue) const
{
bool b = defaultValue;
QueryBoolText(&b);
return b;
}
double XMLElement::DoubleText(double defaultValue) const
{
double d = defaultValue;
QueryDoubleText(&d);
return d;
}
float XMLElement::FloatText(float defaultValue) const
{
float f = defaultValue;
QueryFloatText(&f);
return f;
}
XMLAttribute* XMLElement::FindOrCreateAttribute( const char* name )
{
XMLAttribute* last = 0;
XMLAttribute* attrib = 0;
for( attrib = _rootAttribute;
attrib;
last = attrib, attrib = attrib->_next ) {
if ( XMLUtil::StringEqual( attrib->Name(), name ) ) {
break;
}
}
if ( !attrib ) {
attrib = CreateAttribute();
TIXMLASSERT( attrib );
if ( last ) {
TIXMLASSERT( last->_next == 0 );
last->_next = attrib;
}
else {
TIXMLASSERT( _rootAttribute == 0 );
_rootAttribute = attrib;
}
attrib->SetName( name );
}
return attrib;
}
void XMLElement::DeleteAttribute( const char* name )
{
XMLAttribute* prev = 0;
for( XMLAttribute* a=_rootAttribute; a; a=a->_next ) {
if ( XMLUtil::StringEqual( name, a->Name() ) ) {
if ( prev ) {
prev->_next = a->_next;
}
else {
_rootAttribute = a->_next;
}
DeleteAttribute( a );
break;
}
prev = a;
}
}
char* XMLElement::ParseAttributes( char* p, int* curLineNumPtr )
{
XMLAttribute* prevAttribute = 0;
// Read the attributes.
while( p ) {
p = XMLUtil::SkipWhiteSpace( p, curLineNumPtr );
if ( !(*p) ) {
_document->SetError( XML_ERROR_PARSING_ELEMENT, _parseLineNum, "XMLElement name=%s", Name() );
return 0;
}
// attribute.
if (XMLUtil::IsNameStartChar( (unsigned char) *p ) ) {
XMLAttribute* attrib = CreateAttribute();
TIXMLASSERT( attrib );
attrib->_parseLineNum = _document->_parseCurLineNum;
const int attrLineNum = attrib->_parseLineNum;
p = attrib->ParseDeep( p, _document->ProcessEntities(), curLineNumPtr );
if ( !p || Attribute( attrib->Name() ) ) {
DeleteAttribute( attrib );
_document->SetError( XML_ERROR_PARSING_ATTRIBUTE, attrLineNum, "XMLElement name=%s", Name() );
return 0;
}
// There is a minor bug here: if the attribute in the source xml
// document is duplicated, it will not be detected and the
// attribute will be doubly added. However, tracking the 'prevAttribute'
// avoids re-scanning the attribute list. Preferring performance for
// now, may reconsider in the future.
if ( prevAttribute ) {
TIXMLASSERT( prevAttribute->_next == 0 );
prevAttribute->_next = attrib;
}
else {
TIXMLASSERT( _rootAttribute == 0 );
_rootAttribute = attrib;
}
prevAttribute = attrib;
}
// end of the tag
else if ( *p == '>' ) {
++p;
break;
}
// end of the tag
else if ( *p == '/' && *(p+1) == '>' ) {
_closingType = CLOSED;
return p+2; // done; sealed element.
}
else {
_document->SetError( XML_ERROR_PARSING_ELEMENT, _parseLineNum, 0 );
return 0;
}
}
return p;
}
void XMLElement::DeleteAttribute( XMLAttribute* attribute )
{
if ( attribute == 0 ) {
return;
}
MemPool* pool = attribute->_memPool;
attribute->~XMLAttribute();
pool->Free( attribute );
}
XMLAttribute* XMLElement::CreateAttribute()
{
TIXMLASSERT( sizeof( XMLAttribute ) == _document->_attributePool.ItemSize() );
XMLAttribute* attrib = new (_document->_attributePool.Alloc() ) XMLAttribute();
TIXMLASSERT( attrib );
attrib->_memPool = &_document->_attributePool;
attrib->_memPool->SetTracked();
return attrib;
}
XMLElement* XMLElement::InsertNewChildElement(const char* name)
{
XMLElement* node = _document->NewElement(name);
return InsertEndChild(node) ? node : 0;
}
XMLComment* XMLElement::InsertNewComment(const char* comment)
{
XMLComment* node = _document->NewComment(comment);
return InsertEndChild(node) ? node : 0;
}
XMLText* XMLElement::InsertNewText(const char* text)
{
XMLText* node = _document->NewText(text);
return InsertEndChild(node) ? node : 0;
}
XMLDeclaration* XMLElement::InsertNewDeclaration(const char* text)
{
XMLDeclaration* node = _document->NewDeclaration(text);
return InsertEndChild(node) ? node : 0;
}
XMLUnknown* XMLElement::InsertNewUnknown(const char* text)
{
XMLUnknown* node = _document->NewUnknown(text);
return InsertEndChild(node) ? node : 0;
}
//
// <ele></ele>
// <ele>foo<b>bar</b></ele>
//
char* XMLElement::ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr )
{
// Read the element name.
p = XMLUtil::SkipWhiteSpace( p, curLineNumPtr );
// The closing element is the </element> form. It is
// parsed just like a regular element then deleted from
// the DOM.
if ( *p == '/' ) {
_closingType = CLOSING;
++p;
}
p = _value.ParseName( p );
if ( _value.Empty() ) {
return 0;
}
p = ParseAttributes( p, curLineNumPtr );
if ( !p || !*p || _closingType != OPEN ) {
return p;
}
p = XMLNode::ParseDeep( p, parentEndTag, curLineNumPtr );
return p;
}
XMLNode* XMLElement::ShallowClone( XMLDocument* doc ) const
{
if ( !doc ) {
doc = _document;
}
XMLElement* element = doc->NewElement( Value() ); // fixme: this will always allocate memory. Intern?
for( const XMLAttribute* a=FirstAttribute(); a; a=a->Next() ) {
element->SetAttribute( a->Name(), a->Value() ); // fixme: this will always allocate memory. Intern?
}
return element;
}
bool XMLElement::ShallowEqual( const XMLNode* compare ) const
{
TIXMLASSERT( compare );
const XMLElement* other = compare->ToElement();
if ( other && XMLUtil::StringEqual( other->Name(), Name() )) {
const XMLAttribute* a=FirstAttribute();
const XMLAttribute* b=other->FirstAttribute();
while ( a && b ) {
if ( !XMLUtil::StringEqual( a->Value(), b->Value() ) ) {
return false;
}
a = a->Next();
b = b->Next();
}
if ( a || b ) {
// different count
return false;
}
return true;
}
return false;
}
bool XMLElement::Accept( XMLVisitor* visitor ) const
{
TIXMLASSERT( visitor );
if ( visitor->VisitEnter( *this, _rootAttribute ) ) {
for ( const XMLNode* node=FirstChild(); node; node=node->NextSibling() ) {
if ( !node->Accept( visitor ) ) {
break;
}
}
}
return visitor->VisitExit( *this );
}
// --------- XMLDocument ----------- //
// Warning: List must match 'enum XMLError'
const char* XMLDocument::_errorNames[XML_ERROR_COUNT] = {
"XML_SUCCESS",
"XML_NO_ATTRIBUTE",
"XML_WRONG_ATTRIBUTE_TYPE",
"XML_ERROR_FILE_NOT_FOUND",
"XML_ERROR_FILE_COULD_NOT_BE_OPENED",
"XML_ERROR_FILE_READ_ERROR",
"XML_ERROR_PARSING_ELEMENT",
"XML_ERROR_PARSING_ATTRIBUTE",
"XML_ERROR_PARSING_TEXT",
"XML_ERROR_PARSING_CDATA",
"XML_ERROR_PARSING_COMMENT",
"XML_ERROR_PARSING_DECLARATION",
"XML_ERROR_PARSING_UNKNOWN",
"XML_ERROR_EMPTY_DOCUMENT",
"XML_ERROR_MISMATCHED_ELEMENT",
"XML_ERROR_PARSING",
"XML_CAN_NOT_CONVERT_TEXT",
"XML_NO_TEXT_NODE",
"XML_ELEMENT_DEPTH_EXCEEDED"
};
XMLDocument::XMLDocument( bool processEntities, Whitespace whitespaceMode ) :
XMLNode( 0 ),
_writeBOM( false ),
_processEntities( processEntities ),
_errorID(XML_SUCCESS),
_whitespaceMode( whitespaceMode ),
_errorStr(),
_errorLineNum( 0 ),
_charBuffer( 0 ),
_parseCurLineNum( 0 ),
_parsingDepth(0),
_unlinked(),
_elementPool(),
_attributePool(),
_textPool(),
_commentPool()
{
// avoid VC++ C4355 warning about 'this' in initializer list (C4355 is off by default in VS2012+)
_document = this;
}
XMLDocument::~XMLDocument()
{
Clear();
}
void XMLDocument::MarkInUse(const XMLNode* const node)
{
TIXMLASSERT(node);
TIXMLASSERT(node->_parent == 0);
for (int i = 0; i < _unlinked.Size(); ++i) {
if (node == _unlinked[i]) {
_unlinked.SwapRemove(i);
break;
}
}
}
void XMLDocument::Clear()
{
DeleteChildren();
while( _unlinked.Size()) {
DeleteNode(_unlinked[0]); // Will remove from _unlinked as part of delete.
}
#ifdef TINYXML2_DEBUG
const bool hadError = Error();
#endif
ClearError();
delete [] _charBuffer;
_charBuffer = 0;
_parsingDepth = 0;
#if 0
_textPool.Trace( "text" );
_elementPool.Trace( "element" );
_commentPool.Trace( "comment" );
_attributePool.Trace( "attribute" );
#endif
#ifdef TINYXML2_DEBUG
if ( !hadError ) {
TIXMLASSERT( _elementPool.CurrentAllocs() == _elementPool.Untracked() );
TIXMLASSERT( _attributePool.CurrentAllocs() == _attributePool.Untracked() );
TIXMLASSERT( _textPool.CurrentAllocs() == _textPool.Untracked() );
TIXMLASSERT( _commentPool.CurrentAllocs() == _commentPool.Untracked() );
}
#endif
}
void XMLDocument::DeepCopy(XMLDocument* target) const
{
TIXMLASSERT(target);
if (target == this) {
return; // technically success - a no-op.
}
target->Clear();
for (const XMLNode* node = this->FirstChild(); node; node = node->NextSibling()) {
target->InsertEndChild(node->DeepClone(target));
}
}
XMLElement* XMLDocument::NewElement( const char* name )
{
XMLElement* ele = CreateUnlinkedNode<XMLElement>( _elementPool );
ele->SetName( name );
return ele;
}
XMLComment* XMLDocument::NewComment( const char* str )
{
XMLComment* comment = CreateUnlinkedNode<XMLComment>( _commentPool );
comment->SetValue( str );
return comment;
}
XMLText* XMLDocument::NewText( const char* str )
{
XMLText* text = CreateUnlinkedNode<XMLText>( _textPool );
text->SetValue( str );
return text;
}
XMLDeclaration* XMLDocument::NewDeclaration( const char* str )
{
XMLDeclaration* dec = CreateUnlinkedNode<XMLDeclaration>( _commentPool );
dec->SetValue( str ? str : "xml version=\"1.0\" encoding=\"UTF-8\"" );
return dec;
}
XMLUnknown* XMLDocument::NewUnknown( const char* str )
{
XMLUnknown* unk = CreateUnlinkedNode<XMLUnknown>( _commentPool );
unk->SetValue( str );
return unk;
}
static FILE* callfopen( const char* filepath, const char* mode )
{
TIXMLASSERT( filepath );
TIXMLASSERT( mode );
#if defined(_MSC_VER) && (_MSC_VER >= 1400 ) && (!defined WINCE)
FILE* fp = 0;
const errno_t err = fopen_s( &fp, filepath, mode );
if ( err ) {
return 0;
}
#else
FILE* fp = fopen( filepath, mode );
#endif
return fp;
}
void XMLDocument::DeleteNode( XMLNode* node ) {
TIXMLASSERT( node );
TIXMLASSERT(node->_document == this );
if (node->_parent) {
node->_parent->DeleteChild( node );
}
else {
// Isn't in the tree.
// Use the parent delete.
// Also, we need to mark it tracked: we 'know'
// it was never used.
node->_memPool->SetTracked();
// Call the static XMLNode version:
XMLNode::DeleteNode(node);
}
}
XMLError XMLDocument::LoadFile( const char* filename )
{
if ( !filename ) {
TIXMLASSERT( false );
SetError( XML_ERROR_FILE_COULD_NOT_BE_OPENED, 0, "filename=<null>" );
return _errorID;
}
Clear();
FILE* fp = callfopen( filename, "rb" );
if ( !fp ) {
SetError( XML_ERROR_FILE_NOT_FOUND, 0, "filename=%s", filename );
return _errorID;
}
LoadFile( fp );
fclose( fp );
return _errorID;
}
XMLError XMLDocument::LoadFile( FILE* fp )
{
Clear();
TIXML_FSEEK( fp, 0, SEEK_SET );
if ( fgetc( fp ) == EOF && ferror( fp ) != 0 ) {
SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 );
return _errorID;
}
TIXML_FSEEK( fp, 0, SEEK_END );
unsigned long long filelength;
{
const long long fileLengthSigned = TIXML_FTELL( fp );
TIXML_FSEEK( fp, 0, SEEK_SET );
if ( fileLengthSigned == -1L ) {
SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 );
return _errorID;
}
TIXMLASSERT( fileLengthSigned >= 0 );
filelength = static_cast<unsigned long long>(fileLengthSigned);
}
const size_t maxSizeT = static_cast<size_t>(-1);
// We'll do the comparison as an unsigned long long, because that's guaranteed to be at
// least 8 bytes, even on a 32-bit platform.
if ( filelength >= static_cast<unsigned long long>(maxSizeT) ) {
// Cannot handle files which won't fit in buffer together with null terminator
SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 );
return _errorID;
}
if ( filelength == 0 ) {
SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 );
return _errorID;
}
const size_t size = static_cast<size_t>(filelength);
TIXMLASSERT( _charBuffer == 0 );
_charBuffer = new char[size+1];
const size_t read = fread( _charBuffer, 1, size, fp );
if ( read != size ) {
SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 );
return _errorID;
}
_charBuffer[size] = 0;
Parse();
return _errorID;
}
XMLError XMLDocument::SaveFile( const char* filename, bool compact )
{
if ( !filename ) {
TIXMLASSERT( false );
SetError( XML_ERROR_FILE_COULD_NOT_BE_OPENED, 0, "filename=<null>" );
return _errorID;
}
FILE* fp = callfopen( filename, "w" );
if ( !fp ) {
SetError( XML_ERROR_FILE_COULD_NOT_BE_OPENED, 0, "filename=%s", filename );
return _errorID;
}
SaveFile(fp, compact);
fclose( fp );
return _errorID;
}
XMLError XMLDocument::SaveFile( FILE* fp, bool compact )
{
// Clear any error from the last save, otherwise it will get reported
// for *this* call.
ClearError();
XMLPrinter stream( fp, compact );
Print( &stream );
return _errorID;
}
XMLError XMLDocument::Parse( const char* xml, size_t nBytes )
{
Clear();
if ( nBytes == 0 || !xml || !*xml ) {
SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 );
return _errorID;
}
if ( nBytes == static_cast<size_t>(-1) ) {
nBytes = strlen( xml );
}
TIXMLASSERT( _charBuffer == 0 );
_charBuffer = new char[ nBytes+1 ];
memcpy( _charBuffer, xml, nBytes );
_charBuffer[nBytes] = 0;
Parse();
if ( Error() ) {
// clean up now essentially dangling memory.
// and the parse fail can put objects in the
// pools that are dead and inaccessible.
DeleteChildren();
_elementPool.Clear();
_attributePool.Clear();
_textPool.Clear();
_commentPool.Clear();
}
return _errorID;
}
void XMLDocument::Print( XMLPrinter* streamer ) const
{
if ( streamer ) {
Accept( streamer );
}
else {
XMLPrinter stdoutStreamer( stdout );
Accept( &stdoutStreamer );
}
}
void XMLDocument::ClearError() {
_errorID = XML_SUCCESS;
_errorLineNum = 0;
_errorStr.Reset();
}
void XMLDocument::SetError( XMLError error, int lineNum, const char* format, ... )
{
TIXMLASSERT( error >= 0 && error < XML_ERROR_COUNT );
_errorID = error;
_errorLineNum = lineNum;
_errorStr.Reset();
const size_t BUFFER_SIZE = 1000;
char* buffer = new char[BUFFER_SIZE];
TIXMLASSERT(sizeof(error) <= sizeof(int));
TIXML_SNPRINTF(buffer, BUFFER_SIZE, "Error=%s ErrorID=%d (0x%x) Line number=%d", ErrorIDToName(error), int(error), int(error), lineNum);
if (format) {
size_t len = strlen(buffer);
TIXML_SNPRINTF(buffer + len, BUFFER_SIZE - len, ": ");
len = strlen(buffer);
va_list va;
va_start(va, format);
TIXML_VSNPRINTF(buffer + len, BUFFER_SIZE - len, format, va);
va_end(va);
}
_errorStr.SetStr(buffer);
delete[] buffer;
}
/*static*/ const char* XMLDocument::ErrorIDToName(XMLError errorID)
{
TIXMLASSERT( errorID >= 0 && errorID < XML_ERROR_COUNT );
const char* errorName = _errorNames[errorID];
TIXMLASSERT( errorName && errorName[0] );
return errorName;
}
const char* XMLDocument::ErrorStr() const
{
return _errorStr.Empty() ? "" : _errorStr.GetStr();
}
void XMLDocument::PrintError() const
{
printf("%s\n", ErrorStr());
}
const char* XMLDocument::ErrorName() const
{
return ErrorIDToName(_errorID);
}
void XMLDocument::Parse()
{
TIXMLASSERT( NoChildren() ); // Clear() must have been called previously
TIXMLASSERT( _charBuffer );
_parseCurLineNum = 1;
_parseLineNum = 1;
char* p = _charBuffer;
p = XMLUtil::SkipWhiteSpace( p, &_parseCurLineNum );
p = const_cast<char*>( XMLUtil::ReadBOM( p, &_writeBOM ) );
if ( !*p ) {
SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 );
return;
}
ParseDeep(p, 0, &_parseCurLineNum );
}
void XMLDocument::PushDepth()
{
_parsingDepth++;
if (_parsingDepth == TINYXML2_MAX_ELEMENT_DEPTH) {
SetError(XML_ELEMENT_DEPTH_EXCEEDED, _parseCurLineNum, "Element nesting is too deep." );
}
}
void XMLDocument::PopDepth()
{
TIXMLASSERT(_parsingDepth > 0);
--_parsingDepth;
}
XMLPrinter::XMLPrinter( FILE* file, bool compact, int depth ) :
_elementJustOpened( false ),
_stack(),
_firstElement( true ),
_fp( file ),
_depth( depth ),
_textDepth( -1 ),
_processEntities( true ),
_compactMode( compact ),
_buffer()
{
for( int i=0; i<ENTITY_RANGE; ++i ) {
_entityFlag[i] = false;
_restrictedEntityFlag[i] = false;
}
for( int i=0; i<NUM_ENTITIES; ++i ) {
const char entityValue = entities[i].value;
const unsigned char flagIndex = static_cast<unsigned char>(entityValue);
TIXMLASSERT( flagIndex < ENTITY_RANGE );
_entityFlag[flagIndex] = true;
}
_restrictedEntityFlag[static_cast<unsigned char>('&')] = true;
_restrictedEntityFlag[static_cast<unsigned char>('<')] = true;
_restrictedEntityFlag[static_cast<unsigned char>('>')] = true; // not required, but consistency is nice
_buffer.Push( 0 );
}
void XMLPrinter::Print( const char* format, ... )
{
va_list va;
va_start( va, format );
if ( _fp ) {
vfprintf( _fp, format, va );
}
else {
const int len = TIXML_VSCPRINTF( format, va );
// Close out and re-start the va-args
va_end( va );
TIXMLASSERT( len >= 0 );
va_start( va, format );
TIXMLASSERT( _buffer.Size() > 0 && _buffer[_buffer.Size() - 1] == 0 );
char* p = _buffer.PushArr( len ) - 1; // back up over the null terminator.
TIXML_VSNPRINTF( p, len+1, format, va );
}
va_end( va );
}
void XMLPrinter::Write( const char* data, size_t size )
{
if ( _fp ) {
fwrite ( data , sizeof(char), size, _fp);
}
else {
char* p = _buffer.PushArr( static_cast<int>(size) ) - 1; // back up over the null terminator.
memcpy( p, data, size );
p[size] = 0;
}
}
void XMLPrinter::Putc( char ch )
{
if ( _fp ) {
fputc ( ch, _fp);
}
else {
char* p = _buffer.PushArr( sizeof(char) ) - 1; // back up over the null terminator.
p[0] = ch;
p[1] = 0;
}
}
void XMLPrinter::PrintSpace( int depth )
{
for( int i=0; i<depth; ++i ) {
Write( " " );
}
}
void XMLPrinter::PrintString( const char* p, bool restricted )
{
// Look for runs of bytes between entities to print.
const char* q = p;
if ( _processEntities ) {
const bool* flag = restricted ? _restrictedEntityFlag : _entityFlag;
while ( *q ) {
TIXMLASSERT( p <= q );
// Remember, char is sometimes signed. (How many times has that bitten me?)
if ( *q > 0 && *q < ENTITY_RANGE ) {
// Check for entities. If one is found, flush
// the stream up until the entity, write the
// entity, and keep looking.
if ( flag[static_cast<unsigned char>(*q)] ) {
while ( p < q ) {
const size_t delta = q - p;
const int toPrint = ( INT_MAX < delta ) ? INT_MAX : static_cast<int>(delta);
Write( p, toPrint );
p += toPrint;
}
bool entityPatternPrinted = false;
for( int i=0; i<NUM_ENTITIES; ++i ) {
if ( entities[i].value == *q ) {
Putc( '&' );
Write( entities[i].pattern, entities[i].length );
Putc( ';' );
entityPatternPrinted = true;
break;
}
}
if ( !entityPatternPrinted ) {
// TIXMLASSERT( entityPatternPrinted ) causes gcc -Wunused-but-set-variable in release
TIXMLASSERT( false );
}
++p;
}
}
++q;
TIXMLASSERT( p <= q );
}
// Flush the remaining string. This will be the entire
// string if an entity wasn't found.
if ( p < q ) {
const size_t delta = q - p;
const int toPrint = ( INT_MAX < delta ) ? INT_MAX : static_cast<int>(delta);
Write( p, toPrint );
}
}
else {
Write( p );
}
}
void XMLPrinter::PushHeader( bool writeBOM, bool writeDec )
{
if ( writeBOM ) {
static const unsigned char bom[] = { TIXML_UTF_LEAD_0, TIXML_UTF_LEAD_1, TIXML_UTF_LEAD_2, 0 };
Write( reinterpret_cast< const char* >( bom ) );
}
if ( writeDec ) {
PushDeclaration( "xml version=\"1.0\"" );
}
}
void XMLPrinter::PrepareForNewNode( bool compactMode )
{
SealElementIfJustOpened();
if ( compactMode ) {
return;
}
if ( _firstElement ) {
PrintSpace (_depth);
} else if ( _textDepth < 0) {
Putc( '\n' );
PrintSpace( _depth );
}
_firstElement = false;
}
void XMLPrinter::OpenElement( const char* name, bool compactMode )
{
PrepareForNewNode( compactMode );
_stack.Push( name );
Write ( "<" );
Write ( name );
_elementJustOpened = true;
++_depth;
}
void XMLPrinter::PushAttribute( const char* name, const char* value )
{
TIXMLASSERT( _elementJustOpened );
Putc ( ' ' );
Write( name );
Write( "=\"" );
PrintString( value, false );
Putc ( '\"' );
}
void XMLPrinter::PushAttribute( const char* name, int v )
{
char buf[BUF_SIZE];
XMLUtil::ToStr( v, buf, BUF_SIZE );
PushAttribute( name, buf );
}
void XMLPrinter::PushAttribute( const char* name, unsigned v )
{
char buf[BUF_SIZE];
XMLUtil::ToStr( v, buf, BUF_SIZE );
PushAttribute( name, buf );
}
void XMLPrinter::PushAttribute(const char* name, int64_t v)
{
char buf[BUF_SIZE];
XMLUtil::ToStr(v, buf, BUF_SIZE);
PushAttribute(name, buf);
}
void XMLPrinter::PushAttribute(const char* name, uint64_t v)
{
char buf[BUF_SIZE];
XMLUtil::ToStr(v, buf, BUF_SIZE);
PushAttribute(name, buf);
}
void XMLPrinter::PushAttribute( const char* name, bool v )
{
char buf[BUF_SIZE];
XMLUtil::ToStr( v, buf, BUF_SIZE );
PushAttribute( name, buf );
}
void XMLPrinter::PushAttribute( const char* name, double v )
{
char buf[BUF_SIZE];
XMLUtil::ToStr( v, buf, BUF_SIZE );
PushAttribute( name, buf );
}
void XMLPrinter::CloseElement( bool compactMode )
{
--_depth;
const char* name = _stack.Pop();
if ( _elementJustOpened ) {
Write( "/>" );
}
else {
if ( _textDepth < 0 && !compactMode) {
Putc( '\n' );
PrintSpace( _depth );
}
Write ( "</" );
Write ( name );
Write ( ">" );
}
if ( _textDepth == _depth ) {
_textDepth = -1;
}
if ( _depth == 0 && !compactMode) {
Putc( '\n' );
}
_elementJustOpened = false;
}
void XMLPrinter::SealElementIfJustOpened()
{
if ( !_elementJustOpened ) {
return;
}
_elementJustOpened = false;
Putc( '>' );
}
void XMLPrinter::PushText( const char* text, bool cdata )
{
_textDepth = _depth-1;
SealElementIfJustOpened();
if ( cdata ) {
Write( "<![CDATA[" );
Write( text );
Write( "]]>" );
}
else {
PrintString( text, true );
}
}
void XMLPrinter::PushText( int64_t value )
{
char buf[BUF_SIZE];
XMLUtil::ToStr( value, buf, BUF_SIZE );
PushText( buf, false );
}
void XMLPrinter::PushText( uint64_t value )
{
char buf[BUF_SIZE];
XMLUtil::ToStr(value, buf, BUF_SIZE);
PushText(buf, false);
}
void XMLPrinter::PushText( int value )
{
char buf[BUF_SIZE];
XMLUtil::ToStr( value, buf, BUF_SIZE );
PushText( buf, false );
}
void XMLPrinter::PushText( unsigned value )
{
char buf[BUF_SIZE];
XMLUtil::ToStr( value, buf, BUF_SIZE );
PushText( buf, false );
}
void XMLPrinter::PushText( bool value )
{
char buf[BUF_SIZE];
XMLUtil::ToStr( value, buf, BUF_SIZE );
PushText( buf, false );
}
void XMLPrinter::PushText( float value )
{
char buf[BUF_SIZE];
XMLUtil::ToStr( value, buf, BUF_SIZE );
PushText( buf, false );
}
void XMLPrinter::PushText( double value )
{
char buf[BUF_SIZE];
XMLUtil::ToStr( value, buf, BUF_SIZE );
PushText( buf, false );
}
void XMLPrinter::PushComment( const char* comment )
{
PrepareForNewNode( _compactMode );
Write( "<!--" );
Write( comment );
Write( "-->" );
}
void XMLPrinter::PushDeclaration( const char* value )
{
PrepareForNewNode( _compactMode );
Write( "<?" );
Write( value );
Write( "?>" );
}
void XMLPrinter::PushUnknown( const char* value )
{
PrepareForNewNode( _compactMode );
Write( "<!" );
Write( value );
Putc( '>' );
}
bool XMLPrinter::VisitEnter( const XMLDocument& doc )
{
_processEntities = doc.ProcessEntities();
if ( doc.HasBOM() ) {
PushHeader( true, false );
}
return true;
}
bool XMLPrinter::VisitEnter( const XMLElement& element, const XMLAttribute* attribute )
{
const XMLElement* parentElem = 0;
if ( element.Parent() ) {
parentElem = element.Parent()->ToElement();
}
const bool compactMode = parentElem ? CompactMode( *parentElem ) : _compactMode;
OpenElement( element.Name(), compactMode );
while ( attribute ) {
PushAttribute( attribute->Name(), attribute->Value() );
attribute = attribute->Next();
}
return true;
}
bool XMLPrinter::VisitExit( const XMLElement& element )
{
CloseElement( CompactMode(element) );
return true;
}
bool XMLPrinter::Visit( const XMLText& text )
{
PushText( text.Value(), text.CData() );
return true;
}
bool XMLPrinter::Visit( const XMLComment& comment )
{
PushComment( comment.Value() );
return true;
}
bool XMLPrinter::Visit( const XMLDeclaration& declaration )
{
PushDeclaration( declaration.Value() );
return true;
}
bool XMLPrinter::Visit( const XMLUnknown& unknown )
{
PushUnknown( unknown.Value() );
return true;
}
} // namespace tinyxml2
| null |
800 | cpp | cppcheck | checkvaarg.cpp | lib/checkvaarg.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "checkvaarg.h"
#include "astutils.h"
#include "errortypes.h"
#include "settings.h"
#include "symboldatabase.h"
#include "token.h"
#include "tokenize.h"
#include <cstddef>
#include <iterator>
#include <list>
#include <vector>
//---------------------------------------------------------------------------
// Register this check class (by creating a static instance of it)
namespace {
CheckVaarg instance;
}
//---------------------------------------------------------------------------
// Ensure that correct parameter is passed to va_start()
//---------------------------------------------------------------------------
// CWE ids used:
static const CWE CWE664(664U); // Improper Control of a Resource Through its Lifetime
static const CWE CWE688(688U); // Function Call With Incorrect Variable or Reference as Argument
static const CWE CWE758(758U); // Reliance on Undefined, Unspecified, or Implementation-Defined Behavior
void CheckVaarg::va_start_argument()
{
const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
const std::size_t functions = symbolDatabase->functionScopes.size();
const bool printWarnings = mSettings->severity.isEnabled(Severity::warning);
logChecker("CheckVaarg::va_start_argument");
for (std::size_t i = 0; i < functions; ++i) {
const Scope* scope = symbolDatabase->functionScopes[i];
const Function* function = scope->function;
if (!function)
continue;
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (!tok->scope()->isExecutable())
tok = tok->scope()->bodyEnd;
else if (Token::simpleMatch(tok, "va_start (")) {
const Token* param2 = tok->tokAt(2)->nextArgument();
if (!param2)
continue;
const Variable* var = param2->variable();
if (var && var->isReference())
referenceAs_va_start_error(param2, var->name());
if (var && var->index() + 2 < function->argCount() && printWarnings) {
auto it = function->argumentList.end();
std::advance(it, -2);
wrongParameterTo_va_start_error(tok, var->name(), it->name()); // cppcheck-suppress derefInvalidIterator // FP due to isVariableChangedByFunctionCall()
}
tok = tok->linkAt(1);
}
}
}
}
void CheckVaarg::wrongParameterTo_va_start_error(const Token *tok, const std::string& paramIsName, const std::string& paramShouldName)
{
reportError(tok, Severity::warning,
"va_start_wrongParameter", "'" + paramIsName + "' given to va_start() is not last named argument of the function. Did you intend to pass '" + paramShouldName + "'?", CWE688, Certainty::normal);
}
void CheckVaarg::referenceAs_va_start_error(const Token *tok, const std::string& paramName)
{
reportError(tok, Severity::error,
"va_start_referencePassed", "Using reference '" + paramName + "' as parameter for va_start() results in undefined behaviour.", CWE758, Certainty::normal);
}
//---------------------------------------------------------------------------
// Detect missing va_end() if va_start() was used
// Detect va_list usage after va_end()
//---------------------------------------------------------------------------
void CheckVaarg::va_list_usage()
{
if (mSettings->clang)
return;
logChecker("CheckVaarg::va_list_usage"); // notclang
const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Variable* var : symbolDatabase->variableList()) {
if (!var || var->isPointer() || var->isReference() || var->isArray() || !var->scope() || var->typeStartToken()->str() != "va_list")
continue;
if (!var->isLocal() && !var->isArgument()) // Check only local variables and arguments
continue;
bool open = var->isArgument(); // va_list passed as argument are opened
bool exitOnEndOfStatement = false;
const Token* tok = var->nameToken()->next();
for (; tok && tok != var->scope()->bodyEnd; tok = tok->next()) {
// Skip lambdas
const Token* tok2 = findLambdaEndToken(tok);
if (tok2)
tok = tok2;
if (Token::Match(tok, "va_start ( %varid%", var->declarationId())) {
if (open)
va_start_subsequentCallsError(tok, var->name());
open = true;
tok = tok->linkAt(1);
} else if (Token::Match(tok, "va_end ( %varid%", var->declarationId())) {
if (!open)
va_list_usedBeforeStartedError(tok, var->name());
open = false;
tok = tok->linkAt(1);
} else if (Token::simpleMatch(tok, "va_copy (")) {
bool nopen = open;
if (tok->linkAt(1)->previous()->varId() == var->declarationId()) { // Source
if (!open)
va_list_usedBeforeStartedError(tok, var->name());
}
if (tok->tokAt(2)->varId() == var->declarationId()) { // Destination
if (open)
va_start_subsequentCallsError(tok, var->name());
nopen = true;
}
open = nopen;
tok = tok->linkAt(1);
} else if (Token::Match(tok, "throw|return"))
exitOnEndOfStatement = true;
else if (tok->str() == "break") {
tok = findNextTokenFromBreak(tok);
if (!tok)
return;
} else if (tok->str() == "goto" || (tok->isCpp() && tok->str() == "try")) {
open = false;
break;
} else if (!open && tok->varId() == var->declarationId())
va_list_usedBeforeStartedError(tok, var->name());
else if (exitOnEndOfStatement && tok->str() == ";")
break;
}
if (open && !var->isArgument())
va_end_missingError(tok, var->name());
}
}
void CheckVaarg::va_end_missingError(const Token *tok, const std::string& varname)
{
reportError(tok, Severity::error,
"va_end_missing", "va_list '" + varname + "' was opened but not closed by va_end().", CWE664, Certainty::normal);
}
void CheckVaarg::va_list_usedBeforeStartedError(const Token *tok, const std::string& varname)
{
reportError(tok, Severity::error,
"va_list_usedBeforeStarted", "va_list '" + varname + "' used before va_start() was called.", CWE664, Certainty::normal);
}
void CheckVaarg::va_start_subsequentCallsError(const Token *tok, const std::string& varname)
{
reportError(tok, Severity::error,
"va_start_subsequentCalls", "va_start() or va_copy() called subsequently on '" + varname + "' without va_end() in between.", CWE664, Certainty::normal);
}
| null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.