applied clang-tidy `misc-const-correctness` fixes for POD types, iterators and references (#4529)

* applied `misc-const-correctness` fixes for POD types and iterators

* applied `misc-const-correctness` fixes for references
This commit is contained in:
Oliver Stöneberg 2022-10-02 07:12:40 +02:00 committed by GitHub
parent 586c29c772
commit cff1cd9cda
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
56 changed files with 313 additions and 313 deletions

View File

@ -218,9 +218,9 @@ static std::string addFiles2(std::map<std::string, std::size_t> &files,
new_path = path + '/' + dir_result->d_name;
#if defined(_DIRENT_HAVE_D_TYPE) || defined(_BSD_SOURCE)
bool path_is_directory = (dir_result->d_type == DT_DIR || (dir_result->d_type == DT_UNKNOWN && FileLister::isDirectory(new_path)));
const bool path_is_directory = (dir_result->d_type == DT_DIR || (dir_result->d_type == DT_UNKNOWN && FileLister::isDirectory(new_path)));
#else
bool path_is_directory = FileLister::isDirectory(new_path);
const bool path_is_directory = FileLister::isDirectory(new_path);
#endif
if (path_is_directory) {
if (recursive && !ignored.match(new_path)) {

View File

@ -230,7 +230,7 @@ unsigned int ProcessExecutor::check()
std::list<ImportProject::FileSettings>::const_iterator iFileSettings = mSettings.project.fileSettings.begin();
for (;;) {
// Start a new child
size_t nchildren = childFile.size();
const size_t nchildren = childFile.size();
if ((iFile != mFiles.end() || iFileSettings != mSettings.project.fileSettings.end()) && nchildren < mSettings.jobs && checkLoadAverage(nchildren)) {
int pipes[2];
if (pipe(pipes) == -1) {
@ -238,7 +238,7 @@ unsigned int ProcessExecutor::check()
std::exit(EXIT_FAILURE);
}
int flags = fcntl(pipes[0], F_GETFL, 0);
const int flags = fcntl(pipes[0], F_GETFL, 0);
if (flags < 0) {
std::cerr << "#### ThreadExecutor::check, fcntl(F_GETFL) failed: "<< std::strerror(errno) << std::endl;
std::exit(EXIT_FAILURE);
@ -249,7 +249,7 @@ unsigned int ProcessExecutor::check()
std::exit(EXIT_FAILURE);
}
pid_t pid = fork();
const pid_t pid = fork();
if (pid < 0) {
// Error
std::cerr << "#### ThreadExecutor::check, Failed to create child process: "<< std::strerror(errno) << std::endl;
@ -298,20 +298,20 @@ unsigned int ProcessExecutor::check()
struct timeval tv; // for every second polling of load average condition
tv.tv_sec = 1;
tv.tv_usec = 0;
int r = select(*std::max_element(rpipes.begin(), rpipes.end()) + 1, &rfds, nullptr, nullptr, &tv);
const int r = select(*std::max_element(rpipes.begin(), rpipes.end()) + 1, &rfds, nullptr, nullptr, &tv);
if (r > 0) {
std::list<int>::iterator rp = rpipes.begin();
while (rp != rpipes.end()) {
if (FD_ISSET(*rp, &rfds)) {
int readRes = handleRead(*rp, result);
const int readRes = handleRead(*rp, result);
if (readRes == -1) {
std::size_t size = 0;
std::map<int, std::string>::iterator p = pipeFile.find(*rp);
const std::map<int, std::string>::iterator p = pipeFile.find(*rp);
if (p != pipeFile.end()) {
std::string name = p->second;
pipeFile.erase(p);
std::map<std::string, std::size_t>::const_iterator fs = mFiles.find(name);
const std::map<std::string, std::size_t>::const_iterator fs = mFiles.find(name);
if (fs != mFiles.end()) {
size = fs->second;
}
@ -333,10 +333,10 @@ unsigned int ProcessExecutor::check()
}
if (!childFile.empty()) {
int stat = 0;
pid_t child = waitpid(0, &stat, WNOHANG);
const pid_t child = waitpid(0, &stat, WNOHANG);
if (child > 0) {
std::string childname;
std::map<pid_t, std::string>::iterator c = childFile.find(child);
const std::map<pid_t, std::string>::iterator c = childFile.find(child);
if (c != childFile.end()) {
childname = c->second;
childFile.erase(c);

View File

@ -217,7 +217,7 @@ void Highlighter::highlightBlock(const QString &text)
while (startIndex >= 0) {
QRegularExpressionMatch match = mCommentEndExpression.match(text, startIndex);
int endIndex = match.capturedStart();
const int endIndex = match.capturedStart();
int commentLength = 0;
if (endIndex == -1) {
setCurrentBlockState(1);
@ -353,9 +353,9 @@ int CodeEditor::lineNumberAreaWidth()
}
#if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
int space = 3 + fontMetrics().horizontalAdvance(QLatin1Char('9')) * digits;
const int space = 3 + fontMetrics().horizontalAdvance(QLatin1Char('9')) * digits;
#else
int space = 3 + fontMetrics().width(QLatin1Char('9')) * digits;
const int space = 3 + fontMetrics().width(QLatin1Char('9')) * digits;
#endif
return space;
}

View File

@ -183,8 +183,8 @@ void CodeEditorStyle::saveSettings(QSettings *settings,
}
settings->beginGroup(SETTINGS_STYLE_GROUP);
bool isDefaultLight = (defaultStyleLight == theStyle);
bool isDefaultDark = (defaultStyleDark == theStyle);
const bool isDefaultLight = (defaultStyleLight == theStyle);
const bool isDefaultDark = (defaultStyleDark == theStyle);
if (isDefaultLight && !isDefaultDark) {
settings->setValue(SETTINGS_STYLE_TYPE,
SETTINGS_STYLE_TYPE_LIGHT);

View File

@ -47,7 +47,7 @@ void SelectColorButton::changeColor()
{
QColorDialog pDlg(mColor);
pDlg.setModal(true);
int nResult = pDlg.exec();
const int nResult = pDlg.exec();
if (nResult == QDialog::Accepted) {
setColor(pDlg.selectedColor());
emit colorChanged(mColor);
@ -95,7 +95,7 @@ SelectFontWeightCombo::SelectFontWeightCombo(QWidget* parent) :
void SelectFontWeightCombo::updateWeight()
{
int nResult = findData(QVariant(static_cast<int>(mWeight)));
const int nResult = findData(QVariant(static_cast<int>(mWeight)));
if (nResult != -1) {
setCurrentIndex(nResult);

View File

@ -179,7 +179,7 @@ void LibraryDialog::addFunction()
CppcheckLibraryData::Function f;
f.name = d->functionName();
int args = d->numberOfArguments();
const int args = d->numberOfArguments();
for (int i = 1; i <= args; i++) {
CppcheckLibraryData::Function::Arg arg;
@ -321,7 +321,7 @@ void LibraryDialog::editArg()
LibraryEditArgDialog d(nullptr, arg);
if (d.exec() == QDialog::Accepted) {
unsigned number = arg.nr;
const unsigned number = arg.nr;
arg = d.getArg();
arg.nr = number;
mUi->arguments->selectedItems().first()->setText(getArgText(arg));

View File

@ -331,7 +331,7 @@ void MainWindow::loadSettings()
mUI->mActionToolBarFilter->setChecked(showFilterToolbar);
mUI->mToolBarFilter->setVisible(showFilterToolbar);
Settings::Language enforcedLanguage = (Settings::Language)mSettings->value(SETTINGS_ENFORCED_LANGUAGE, 0).toInt();
const Settings::Language enforcedLanguage = (Settings::Language)mSettings->value(SETTINGS_ENFORCED_LANGUAGE, 0).toInt();
if (enforcedLanguage == Settings::CPP)
mUI->mActionEnforceCpp->setChecked(true);
else if (enforcedLanguage == Settings::C)
@ -339,7 +339,7 @@ void MainWindow::loadSettings()
else
mUI->mActionAutoDetectLanguage->setChecked(true);
bool succeeded = mApplications->loadSettings();
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. "
@ -436,7 +436,7 @@ void MainWindow::doAnalyzeProject(ImportProject p, const bool checkLibrary, cons
p.ignorePaths(v);
if (!mProjectFile->getAnalyzeAllVsConfigs()) {
Settings::PlatformType platform = (Settings::PlatformType) mSettings->value(SETTINGS_CHECKED_PLATFORM, 0).toInt();
const Settings::PlatformType platform = (Settings::PlatformType) mSettings->value(SETTINGS_CHECKED_PLATFORM, 0).toInt();
p.selectOneVsConfig(platform);
}
} else {
@ -689,7 +689,7 @@ void MainWindow::analyzeDirectory()
msgBox.addButton(QMessageBox::Yes);
msgBox.addButton(QMessageBox::No);
msgBox.setDefaultButton(QMessageBox::Yes);
int dlgResult = msgBox.exec();
const int dlgResult = msgBox.exec();
if (dlgResult == QMessageBox::Yes) {
QString path = checkDir.canonicalPath();
if (!path.endsWith("/"))
@ -712,7 +712,7 @@ void MainWindow::analyzeDirectory()
msgBox.addButton(QMessageBox::Yes);
msgBox.addButton(QMessageBox::No);
msgBox.setDefaultButton(QMessageBox::Yes);
int dlgResult = msgBox.exec();
const int dlgResult = msgBox.exec();
if (dlgResult == QMessageBox::Yes) {
doAnalyzeFiles(dir);
}
@ -1199,7 +1199,7 @@ void MainWindow::openResults()
msgBox.addButton(QMessageBox::Yes);
msgBox.addButton(QMessageBox::No);
msgBox.setDefaultButton(QMessageBox::Yes);
int dlgResult = msgBox.exec();
const int dlgResult = msgBox.exec();
if (dlgResult == QMessageBox::No) {
return;
}
@ -1257,7 +1257,7 @@ void MainWindow::enableCheckButtons(bool enable)
void MainWindow::enableResultsButtons()
{
bool enabled = mUI->mResults->hasResults();
const bool enabled = mUI->mResults->hasResults();
mUI->mActionClearResults->setEnabled(enabled);
mUI->mActionSave->setEnabled(enabled);
mUI->mActionPrint->setEnabled(enabled);
@ -1321,7 +1321,7 @@ void MainWindow::closeEvent(QCloseEvent *event)
this);
msg.setDefaultButton(QMessageBox::No);
int rv = msg.exec();
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.
@ -1781,7 +1781,7 @@ void MainWindow::openRecentProject()
this);
msg.setDefaultButton(QMessageBox::No);
int rv = msg.exec();
const int rv = msg.exec();
if (rv == QMessageBox::Yes) {
removeProjectMRU(project);
}

View File

@ -625,7 +625,7 @@ void ProjectFile::readTagWarnings(QXmlStreamReader &reader, const QString &tag)
case QXmlStreamReader::StartElement:
// Read library-elements
if (reader.name().toString() == CppcheckXml::WarningElementName) {
std::size_t hash = reader.attributes().value(QString(), CppcheckXml::HashAttributeName).toULongLong();
const std::size_t hash = reader.attributes().value(QString(), CppcheckXml::HashAttributeName).toULongLong();
mWarningTags[hash] = tag;
}
break;

View File

@ -173,7 +173,7 @@ ProjectFileDialog::ProjectFileDialog(ProjectFile *projectFile, bool premium, QWi
// Platforms..
Platforms platforms;
for (cppcheck::Platform::PlatformType builtinPlatform : builtinPlatforms)
for (const cppcheck::Platform::PlatformType builtinPlatform : builtinPlatforms)
mUI->mComboBoxPlatform->addItem(platforms.get(builtinPlatform).mTitle);
QStringList platformFiles;
for (QString sp : searchPaths) {
@ -411,7 +411,7 @@ void ProjectFileDialog::saveToProjectFile(ProjectFile *projectFile) const
if (mUI->mComboBoxPlatform->currentText().endsWith(".xml"))
projectFile->setPlatform(mUI->mComboBoxPlatform->currentText());
else {
int i = mUI->mComboBoxPlatform->currentIndex();
const int i = mUI->mComboBoxPlatform->currentIndex();
if (i < numberOfBuiltinPlatforms)
projectFile->setPlatform(cppcheck::Platform::platformString(builtinPlatforms[i]));
else
@ -504,8 +504,8 @@ void ProjectFileDialog::browseBuildDir()
void ProjectFileDialog::updatePathsAndDefines()
{
const QString &fileName = mUI->mEditImportProject->text();
bool importProject = !fileName.isEmpty();
bool hasConfigs = fileName.endsWith(".sln") || fileName.endsWith(".vcxproj");
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);
@ -730,7 +730,7 @@ void ProjectFileDialog::setLibraries(const QStringList &libraries)
void ProjectFileDialog::addSingleSuppression(const Suppressions::Suppression &suppression)
{
QString suppression_name;
static char sep = QDir::separator().toLatin1();
static const char sep = QDir::separator().toLatin1();
bool found_relative = false;
// Replace relative file path in the suppression with the absolute one
@ -872,7 +872,7 @@ void ProjectFileDialog::removeSuppression()
if (!item)
return;
int suppressionIndex = getSuppressionIndex(item->text());
const int suppressionIndex = getSuppressionIndex(item->text());
if (suppressionIndex >= 0)
mSuppressions.removeAt(suppressionIndex);
delete item;
@ -882,7 +882,7 @@ void ProjectFileDialog::editSuppression(const QModelIndex & /*index*/)
{
const int row = mUI->mListSuppressions->currentRow();
QListWidgetItem *item = mUI->mListSuppressions->item(row);
int suppressionIndex = getSuppressionIndex(item->text());
const int suppressionIndex = getSuppressionIndex(item->text());
if (suppressionIndex >= 0) { // TODO what if suppression is not found?
NewSuppressionDialog dlg;
dlg.setSuppression(mSuppressions[suppressionIndex]);

View File

@ -469,7 +469,7 @@ void ResultsTree::showHiddenResults()
{
//Clear the "hide" flag for each item
mHiddenMessageId.clear();
int filecount = mModel.rowCount();
const int filecount = mModel.rowCount();
for (int i = 0; i < filecount; i++) {
QStandardItem *fileItem = mModel.item(i, 0);
if (!fileItem)
@ -479,7 +479,7 @@ void ResultsTree::showHiddenResults()
data[HIDE] = false;
fileItem->setData(QVariant(data));
int errorcount = fileItem->rowCount();
const int errorcount = fileItem->rowCount();
for (int j = 0; j < errorcount; j++) {
QStandardItem *child = fileItem->child(j, 0);
if (child) {
@ -498,7 +498,7 @@ void ResultsTree::refreshTree()
{
mVisibleErrors = false;
//Get the amount of files in the tree
int filecount = mModel.rowCount();
const int filecount = mModel.rowCount();
for (int i = 0; i < filecount; i++) {
//Get file i
@ -508,7 +508,7 @@ void ResultsTree::refreshTree()
}
//Get the amount of errors this file contains
int errorcount = fileItem->rowCount();
const int errorcount = fileItem->rowCount();
//By default it shouldn't be visible
bool show = false;
@ -820,7 +820,7 @@ void ResultsTree::startApplication(QStandardItem *target, int application)
const QString cmdLine = QString("%1 %2").arg(program).arg(params);
// this is reported as deprecated in Qt 5.15.2 but no longer in Qt 6
bool success = SUPPRESS_DEPRECATED_WARNING(QProcess::startDetached(cmdLine));
const bool success = SUPPRESS_DEPRECATED_WARNING(QProcess::startDetached(cmdLine));
if (!success) {
QString text = tr("Could not start %1\n\nPlease check the application path and parameters are correct.").arg(program);
@ -983,7 +983,7 @@ void ResultsTree::hideAllIdResult()
mHiddenMessageId.append(messageId);
// hide all errors with that message Id
int filecount = mModel.rowCount();
const int filecount = mModel.rowCount();
for (int i = 0; i < filecount; i++) {
//Get file i
QStandardItem *file = mModel.item(i, 0);
@ -992,7 +992,7 @@ void ResultsTree::hideAllIdResult()
}
//Get the amount of errors this file contains
int errorcount = file->rowCount();
const int errorcount = file->rowCount();
for (int j = 0; j < errorcount; j++) {
//Get the error itself
@ -1239,7 +1239,7 @@ void ResultsTree::updateFromOldReport(const QString &filename)
QStandardItem *error = fileItem->child(j,0);
ErrorItem errorItem;
readErrorItem(error, &errorItem);
int oldErrorIndex = indexOf(oldErrors, errorItem);
const int oldErrorIndex = indexOf(oldErrors, errorItem);
QVariantMap data = error->data().toMap();
// New error .. set the "sinceDate" property

View File

@ -257,7 +257,7 @@ void SettingsDialog::removeApplication()
void SettingsDialog::editApplication()
{
for (QListWidgetItem *item : mUI->mListWidget->selectedItems()) {
int row = mUI->mListWidget->row(item);
const int row = mUI->mListWidget->row(item);
Application& app = mTempApplications->getApplication(row);
ApplicationDialog dialog(tr("Modify an application"), app, this);
@ -274,7 +274,7 @@ void SettingsDialog::defaultApplication()
{
QList<QListWidgetItem *> selected = mUI->mListWidget->selectedItems();
if (!selected.isEmpty()) {
int index = mUI->mListWidget->row(selected[0]);
const int index = mUI->mListWidget->row(selected[0]);
mTempApplications->setDefault(index);
mUI->mListWidget->clear();
populateApplicationList();
@ -372,7 +372,7 @@ void SettingsDialog::setCodeEditorStyleDefault()
void SettingsDialog::editCodeEditorStyle()
{
StyleEditDialog dlg(*mCurrentStyle, this);
int nResult = dlg.exec();
const int nResult = dlg.exec();
if (nResult == QDialog::Accepted) {
*mCurrentStyle = dlg.getStyle();
manageStyleControls();
@ -392,9 +392,9 @@ void SettingsDialog::browseClangPath()
void SettingsDialog::manageStyleControls()
{
bool isSystemTheme = mCurrentStyle->isSystemTheme();
bool isDefaultLight = !isSystemTheme && *mCurrentStyle == defaultStyleLight;
bool isDefaultDark = !isSystemTheme && *mCurrentStyle == defaultStyleDark;
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);

View File

@ -125,11 +125,11 @@ void StatsDialog::setScanDuration(double seconds)
{
// Factor the duration into units (days/hours/minutes/seconds)
int secs = seconds;
int days = secs / (24 * 60 * 60);
const int days = secs / (24 * 60 * 60);
secs -= days * (24 * 60 * 60);
int hours = secs / (60 * 60);
const int hours = secs / (60 * 60);
secs -= hours * (60 * 60);
int mins = secs / 60;
const int mins = secs / 60;
secs -= mins * 60;
// Concatenate the two most significant units (e.g. "1 day and 3 hours")
@ -412,9 +412,9 @@ QLineSeries *StatsDialog::numberOfReports(const QString &fileName, const QString
static const QRegularExpression rxdate("^\\[(\\d\\d)\\.(\\d\\d)\\.(\\d\\d\\d\\d)\\]$");
const QRegularExpressionMatch matchRes = rxdate.match(line);
if (matchRes.hasMatch()) {
int y = matchRes.captured(3).toInt();
int m = matchRes.captured(2).toInt();
int d = matchRes.captured(1).toInt();
const int y = matchRes.captured(3).toInt();
const int m = matchRes.captured(2).toInt();
const int d = matchRes.captured(1).toInt();
QDateTime dt;
dt.setDate(QDate(y,m,d));
if (t == dt.toMSecsSinceEpoch())
@ -423,7 +423,7 @@ QLineSeries *StatsDialog::numberOfReports(const QString &fileName, const QString
t = dt.toMSecsSinceEpoch();
}
if (line.startsWith(severity + ':')) {
int y = line.mid(1+severity.length()).toInt();
const int y = line.mid(1+severity.length()).toInt();
series->append(t, y);
}
}

View File

@ -272,7 +272,7 @@ bool ThreadHandler::needsReCheck(const QString &filename, std::set<QString> &mod
QString line = in.readLine();
if (line.startsWith("#include \"")) {
line.remove(0,10);
int i = line.indexOf("\"");
const int i = line.indexOf("\"");
if (i > 0) {
line.remove(i,line.length());
line = QFileInfo(filename).absolutePath() + "/" + line;

View File

@ -82,7 +82,7 @@ bool TranslationHandler::setLanguage(const QString &code)
}
//Make sure the translator is otherwise valid
int index = getLanguageIndexByCode(code);
const int index = getLanguageIndexByCode(code);
if (index == -1) {
error = QObject::tr("Unknown language specified!");
failure = true;
@ -154,7 +154,7 @@ QString TranslationHandler::suggestLanguage() const
//qDebug()<<"Your language is"<<language;
//And see if we can find it from our list of language files
int index = getLanguageIndexByCode(language);
const int index = getLanguageIndexByCode(language);
//If nothing found, return English
if (index < 0) {
@ -169,7 +169,7 @@ void TranslationHandler::addTranslation(const char *name, const char *filename)
TranslationInfo info;
info.mName = name;
info.mFilename = filename;
int codeLength = QString(filename).length() - QString(filename).indexOf('_') - 1;
const int codeLength = QString(filename).length() - QString(filename).indexOf('_') - 1;
info.mCode = QString(filename).right(codeLength);
mTranslations.append(info);
}

View File

@ -56,7 +56,7 @@ int XmlReport::determineVersion(const QString &filename)
{
QFile file;
file.setFileName(filename);
bool succeed = file.open(QIODevice::ReadOnly | QIODevice::Text);
const bool succeed = file.open(QIODevice::ReadOnly | QIODevice::Text);
if (!succeed)
return 0;
@ -67,7 +67,7 @@ int XmlReport::determineVersion(const QString &filename)
if (reader.name() == QString(ResultElementName)) {
QXmlStreamAttributes attribs = reader.attributes();
if (attribs.hasAttribute(QString(VersionAttribute))) {
int ver = attribs.value(QString(), VersionAttribute).toString().toInt();
const int ver = attribs.value(QString(), VersionAttribute).toString().toInt();
return ver;
} else
return 1;

View File

@ -75,7 +75,7 @@ static int findArgumentPosRecursive(const Token* tok, const Token* tokToFind, b
return -1;
if (found)
return res;
int argn = res;
const int argn = res;
res = findArgumentPosRecursive(tok->astOperand2(), tokToFind, found, depth);
if (res == -1)
return -1;
@ -89,7 +89,7 @@ static int findArgumentPosRecursive(const Token* tok, const Token* tokToFind, b
static int findArgumentPos(const Token* tok, const Token* tokToFind){
bool found = false;
int argn = findArgumentPosRecursive(tok, tokToFind, found, 0);
const int argn = findArgumentPosRecursive(tok, tokToFind, found, 0);
if (found)
return argn - 1;
return -1;
@ -1228,7 +1228,7 @@ SmallVector<ReferenceToken> followAllReferences(const Token* tok,
return refs_result;
}
if (argvar->isArgument() && (argvar->isReference() || argvar->isRValueReference())) {
int n = getArgumentPos(argvar, f);
const int n = getArgumentPos(argvar, f);
if (n < 0) {
refs_result.push_back({tok, std::move(errors)});
return refs_result;
@ -1883,7 +1883,7 @@ bool isConstFunctionCall(const Token* ftok, const Library& library)
return true;
return false;
} else {
bool memberFunction = Token::Match(ftok->previous(), ". %name% (");
const bool memberFunction = Token::Match(ftok->previous(), ". %name% (");
bool constMember = !memberFunction;
if (Token::Match(ftok->tokAt(-2), "%var% . %name% (")) {
const Variable* var = ftok->tokAt(-2)->variable();
@ -3343,7 +3343,7 @@ struct FwdAnalysis::Result FwdAnalysis::checkRecursive(const Token *expr, const
const Token *conditionStart = tok->next();
const Token *condTok = conditionStart->astOperand2();
if (condTok->hasKnownIntValue()) {
bool cond = condTok->values().front().intvalue;
const bool cond = condTok->values().front().intvalue;
if (cond) {
FwdAnalysis::Result result = checkRecursive(expr, bodyStart, bodyStart->link(), exprVarIds, local, true, depth);
if (result.type != Result::Type::NONE)

View File

@ -61,7 +61,7 @@ void visitAstNodes(T *ast, const TFunc &visitor)
std::stack<T *, SmallVector<T *, 8 + 1>> tokens;
T *tok = ast;
do {
ChildrenToVisit c = visitor(tok);
const ChildrenToVisit c = visitor(tok);
if (c == ChildrenToVisit::done)
break;

View File

@ -538,7 +538,7 @@ void CheckAutoVariables::checkVarLifetimeScope(const Token * start, const Token
// If the scope is not set correctly then skip checking it
if (scope->bodyStart != start)
return;
bool returnRef = Function::returnsReference(scope->function);
const bool returnRef = Function::returnsReference(scope->function);
for (const Token *tok = start; tok && tok != end; tok = tok->next()) {
// Return reference from function
if (returnRef && Token::simpleMatch(tok->astParent(), "return")) {

View File

@ -377,7 +377,7 @@ void CheckBool::checkComparisonOfBoolExpressionWithInt()
maxval = nullptr;
if (minval || maxval) {
bool not0or1 = (minval && minval->intvalue < 0) || (maxval && maxval->intvalue > 1);
const bool not0or1 = (minval && minval->intvalue < 0) || (maxval && maxval->intvalue > 1);
comparisonOfBoolExpressionWithIntError(tok, not0or1);
}
}

View File

@ -557,7 +557,7 @@ ValueFlow::Value CheckBufferOverrun::getBufferSize(const Token *bufTok) const
if (!var)
return ValueFlow::Value(-1);
MathLib::bigint dim = std::accumulate(var->dimensions().begin(), var->dimensions().end(), 1LL, [](MathLib::bigint i1, const Dimension &dim) {
const MathLib::bigint dim = std::accumulate(var->dimensions().begin(), var->dimensions().end(), 1LL, [](MathLib::bigint i1, const Dimension &dim) {
return i1 * dim.num;
});
@ -596,7 +596,7 @@ static bool checkBufferSize(const Token *ftok, const Library::ArgumentChecks::Mi
case Library::ArgumentChecks::MinSize::Type::ARGVALUE: {
if (arg && arg->hasKnownIntValue()) {
MathLib::bigint myMinsize = arg->getKnownIntValue();
unsigned int baseSize = tokenizer->sizeOfType(minsize.baseType);
const unsigned int baseSize = tokenizer->sizeOfType(minsize.baseType);
if (baseSize != 0)
myMinsize *= baseSize;
return myMinsize <= bufferSize;
@ -612,7 +612,7 @@ static bool checkBufferSize(const Token *ftok, const Library::ArgumentChecks::Mi
break;
case Library::ArgumentChecks::MinSize::Type::VALUE: {
MathLib::bigint myMinsize = minsize.value;
unsigned int baseSize = tokenizer->sizeOfType(minsize.baseType);
const unsigned int baseSize = tokenizer->sizeOfType(minsize.baseType);
if (baseSize != 0)
myMinsize *= baseSize;
return myMinsize <= bufferSize;

View File

@ -3076,9 +3076,9 @@ Check::FileInfo *CheckClass::getFileInfo(const Tokenizer *tokenizer, const Setti
continue;
// the full definition must be compared
bool fullDefinition = std::all_of(classScope->functionList.begin(),
classScope->functionList.end(),
[](const Function& f) {
const bool fullDefinition = std::all_of(classScope->functionList.begin(),
classScope->functionList.end(),
[](const Function& f) {
return f.hasBody();
});
if (!fullDefinition)

View File

@ -665,7 +665,7 @@ void CheckCondition::multiCondition2()
std::vector<MULTICONDITIONTYPE> types = {MULTICONDITIONTYPE::INNER};
if (Token::Match(scope.bodyStart, "{ return|throw|continue|break"))
types.push_back(MULTICONDITIONTYPE::AFTER);
for (MULTICONDITIONTYPE type:types) {
for (const MULTICONDITIONTYPE type:types) {
if (type == MULTICONDITIONTYPE::AFTER) {
tok = scope.bodyEnd->next();
} else {
@ -753,7 +753,7 @@ void CheckCondition::multiCondition2()
break;
}
bool changed = false;
for (int varid : vars) {
for (const int varid : vars) {
if (isVariableChanged(tok1, tok2, varid, nonlocal, mSettings, mTokenizer->isCPP())) {
changed = true;
break;

View File

@ -149,7 +149,7 @@ void CheckInternal::checkTokenSimpleMatchPatterns()
// Check for [xyz] usage - but exclude standalone square brackets
unsigned int char_count = 0;
for (char c : pattern) {
for (const char c : pattern) {
if (c == ' ') {
char_count = 0;
} else if (c == ']') {
@ -164,7 +164,7 @@ void CheckInternal::checkTokenSimpleMatchPatterns()
// Check | usage: Count characters before the symbol
char_count = 0;
for (char c : pattern) {
for (const char c : pattern) {
if (c == ' ') {
char_count = 0;
} else if (c == '|') {

View File

@ -170,7 +170,7 @@ void CheckIO::checkFileUsage()
} else if (Token::Match(tok, "%var% =") &&
(tok->strAt(2) != "fopen" && tok->strAt(2) != "freopen" && tok->strAt(2) != "tmpfile" &&
(windows ? (tok->str() != "_wfopen" && tok->str() != "_wfreopen") : true))) {
std::map<int, Filepointer>::iterator i = filepointers.find(tok->varId());
const std::map<int, Filepointer>::iterator i = filepointers.find(tok->varId());
if (i != filepointers.end()) {
i->second.mode = OpenMode::UNKNOWN_OM;
i->second.lastOperation = Filepointer::Operation::UNKNOWN_OP;
@ -496,7 +496,7 @@ static bool findFormat(nonneg int arg, const Token *firstArg,
argTok->variable()->dimension(0) != 0))) {
*formatArgTok = argTok->nextArgument();
if (!argTok->values().empty()) {
std::list<ValueFlow::Value>::const_iterator value = std::find_if(
const std::list<ValueFlow::Value>::const_iterator value = std::find_if(
argTok->values().begin(), argTok->values().end(), std::mem_fn(&ValueFlow::Value::isTokValue));
if (value != argTok->values().end() && value->isTokValue() && value->tokvalue &&
value->tokvalue->tokType() == Token::eString) {
@ -1312,7 +1312,7 @@ void CheckIO::checkFormatString(const Token * const tok,
if (printWarning) {
// Check that all parameter positions reference an actual parameter
for (int i : parameterPositionsUsed) {
for (const int i : parameterPositionsUsed) {
if ((i == 0) || (i > numFormat))
wrongPrintfScanfPosixParameterPositionError(tok, tok->str(), i, numFormat);
}

View File

@ -1062,6 +1062,6 @@ void CheckLeakAutoVar::ret(const Token *tok, VarInfo &varInfo, const bool isEndO
toRemove.push_back(varid);
}
}
for (int varId : toRemove)
for (const int varId : toRemove)
varInfo.erase(varId);
}

View File

@ -398,7 +398,7 @@ CheckMemoryLeak::AllocType CheckMemoryLeak::functionReturnType(const Function* f
// Check if return pointer is allocated..
AllocType allocType = No;
nonneg int varid = var->declarationId();
nonneg int const varid = var->declarationId();
for (const Token* tok = func->functionScope->bodyStart; tok != func->functionScope->bodyEnd; tok = tok->next()) {
if (Token::Match(tok, "%varid% =", varid)) {
allocType = getAllocationType(tok->tokAt(2), varid, callstack);

View File

@ -1484,7 +1484,7 @@ void CheckOther::checkConstVariable()
castToNonConst = true; // safe guess
break;
}
bool isConst = 0 != (tok->valueType()->constness & (1 << tok->valueType()->pointer));
const bool isConst = 0 != (tok->valueType()->constness & (1 << tok->valueType()->pointer));
if (!isConst) {
castToNonConst = true;
break;
@ -1928,7 +1928,7 @@ void CheckOther::checkIncompleteStatement()
if (mTokenizer->isCPP() && tok->str() == "&" && !(tok->astOperand1()->valueType() && tok->astOperand1()->valueType()->isIntegral()))
// Possible archive
continue;
bool inconclusive = tok->isConstOp();
const bool inconclusive = tok->isConstOp();
if (mSettings->certainty.isEnabled(Certainty::inconclusive) || !inconclusive)
constStatementError(tok, tok->isNumber() ? "numeric" : "string", inconclusive);
}

View File

@ -75,7 +75,7 @@ static bool isElementAccessYield(const Library::Container::Yield& yield)
static bool containerAppendsElement(const Library::Container* container, const Token* parent)
{
if (Token::Match(parent, ". %name% (")) {
Library::Container::Action action = container->getAction(parent->strAt(1));
const Library::Container::Action action = container->getAction(parent->strAt(1));
if (contains({Library::Container::Action::INSERT,
Library::Container::Action::CHANGE,
Library::Container::Action::CHANGE_INTERNAL,
@ -90,7 +90,7 @@ static bool containerAppendsElement(const Library::Container* container, const T
static bool containerYieldsElement(const Library::Container* container, const Token* parent)
{
if (Token::Match(parent, ". %name% (")) {
Library::Container::Yield yield = container->getYield(parent->strAt(1));
const Library::Container::Yield yield = container->getYield(parent->strAt(1));
if (isElementAccessYield(yield))
return true;
}
@ -100,7 +100,7 @@ static bool containerYieldsElement(const Library::Container* container, const To
static const Token* getContainerIndex(const Library::Container* container, const Token* parent)
{
if (Token::Match(parent, ". %name% (")) {
Library::Container::Yield yield = container->getYield(parent->strAt(1));
const Library::Container::Yield yield = container->getYield(parent->strAt(1));
if (yield == Library::Container::Yield::AT_INDEX && !Token::simpleMatch(parent->tokAt(2), "( )"))
return parent->tokAt(2)->astOperand2();
}
@ -116,7 +116,7 @@ static const Token* getContainerFromSize(const Library::Container* container, co
if (!tok)
return nullptr;
if (Token::Match(tok->tokAt(-2), ". %name% (")) {
Library::Container::Yield yield = container->getYield(tok->strAt(-1));
const Library::Container::Yield yield = container->getYield(tok->strAt(-1));
if (yield == Library::Container::Yield::SIZE)
return tok->tokAt(-2)->astOperand1();
}
@ -858,7 +858,7 @@ void CheckStl::mismatchingContainerIterator()
const std::vector<const Token *> args = getArguments(ftok);
const Library::Container * c = tok->valueType()->container;
Library::Container::Action action = c->getAction(tok->strAt(2));
const Library::Container::Action action = c->getAction(tok->strAt(2));
const Token* iterTok = nullptr;
if (action == Library::Container::Action::INSERT && args.size() == 2) {
// Skip if iterator pair
@ -901,7 +901,7 @@ static const Token* getInvalidMethod(const Token* tok)
if (!ftok)
return nullptr;
if (const Library::Container * c = tok->valueType()->container) {
Library::Container::Action action = c->getAction(ftok->str());
const Library::Container::Action action = c->getAction(ftok->str());
if (c->unstableErase) {
if (action == Library::Container::Action::ERASE)
return ftok;
@ -987,7 +987,7 @@ struct InvalidContainerAnalyzer {
if (!var)
continue;
if (var->isArgument()) {
int n = getArgumentPos(var, f);
const int n = getArgumentPos(var, f);
const Token* tok2 = nullptr;
if (n >= 0 && n < args.size())
tok2 = args[n];
@ -1125,7 +1125,7 @@ void CheckStl::invalidContainer()
// Skip if the variable is assigned to
const Token* assignExpr = tok;
while (assignExpr->astParent()) {
bool isRHS = astIsRHS(assignExpr);
const bool isRHS = astIsRHS(assignExpr);
assignExpr = assignExpr->astParent();
if (Token::Match(assignExpr, "%assign%")) {
if (!isRHS)
@ -2720,7 +2720,7 @@ void CheckStl::useStlAlgorithm()
bool useLoopVarInAssign;
const Token *assignTok = singleAssignInScope(bodyTok, loopVar->varId(), useLoopVarInAssign);
if (assignTok) {
int assignVarId = assignTok->astOperand1()->varId();
const int assignVarId = assignTok->astOperand1()->varId();
std::string algo;
if (assignVarId == loopVar->varId()) {
if (useLoopVarInAssign)

View File

@ -1582,7 +1582,7 @@ void CheckUninitVar::valueFlowUninit()
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
std::unordered_set<nonneg int> ids;
for (bool subfunction : {false, true}) {
for (const bool subfunction : {false, true}) {
// check every executable scope
for (const Scope* scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
@ -1630,7 +1630,7 @@ void CheckUninitVar::valueFlowUninit()
if (Token::Match(tok->astParent(), ". %var%") && !isleaf)
continue;
}
ExprUsage usage = getExprUsage(tok, v->indirect, mSettings);
const ExprUsage usage = getExprUsage(tok, v->indirect, mSettings);
if (usage == ExprUsage::NotUsed)
continue;
if (!v->subexpressions.empty() && usage == ExprUsage::PassedByReference)

View File

@ -295,7 +295,7 @@ void Variables::readAliases(nonneg int varid, const Token* tok)
VariableUsage *usage = find(varid);
if (usage) {
for (nonneg int aliases : usage->_aliases) {
for (nonneg int const aliases : usage->_aliases) {
VariableUsage *aliased = find(aliases);
if (aliased) {
@ -389,7 +389,7 @@ void Variables::modified(nonneg int varid, const Token* tok)
Variables::VariableUsage *Variables::find(nonneg int varid)
{
if (varid) {
std::map<nonneg int, VariableUsage>::iterator i = mVarUsage.find(varid);
const std::map<nonneg int, VariableUsage>::iterator i = mVarUsage.find(varid);
if (i != mVarUsage.end())
return &i->second;
}
@ -1621,7 +1621,7 @@ bool CheckUnusedVar::isVariableWithoutSideEffects(const Variable& var)
} else {
if (WRONG_DATA(!var.valueType(), var.typeStartToken()))
return false;
ValueType::Type valueType = var.valueType()->type;
const ValueType::Type valueType = var.valueType()->type;
if ((valueType == ValueType::Type::UNKNOWN_TYPE) || (valueType == ValueType::Type::NONSTD))
return false;
}

View File

@ -393,7 +393,7 @@ std::string clangimport::AstNode::getSpelling() const
int typeIndex = 1;
while (typeIndex < mExtTokens.size() && mExtTokens[typeIndex][0] != '\'')
typeIndex++;
int nameIndex = typeIndex + 1;
const int nameIndex = typeIndex + 1;
return (nameIndex < mExtTokens.size()) ? unquote(mExtTokens[nameIndex]) : "";
}
@ -424,17 +424,17 @@ std::string clangimport::AstNode::getType(int index) const
{
std::string type = getFullType(index);
if (type.find(" (") != std::string::npos) {
std::string::size_type pos = type.find(" (");
const std::string::size_type pos = type.find(" (");
type[pos] = '\'';
type.erase(pos+1);
}
if (type.find(" *(") != std::string::npos) {
std::string::size_type pos = type.find(" *(") + 2;
const std::string::size_type pos = type.find(" *(") + 2;
type[pos] = '\'';
type.erase(pos+1);
}
if (type.find(" &(") != std::string::npos) {
std::string::size_type pos = type.find(" &(") + 2;
const std::string::size_type pos = type.find(" &(") + 2;
type[pos] = '\'';
type.erase(pos+1);
}
@ -508,8 +508,8 @@ void clangimport::AstNode::setLocations(TokenList *tokenList, int file, int line
const std::string::size_type colon = ext.find(':');
if (colon != std::string::npos) {
const bool windowsPath = colon == 2 && ext.size() > 4 && ext[3] == '\\';
std::string::size_type sep1 = windowsPath ? ext.find(':', 4) : colon;
std::string::size_type sep2 = ext.find(':', sep1 + 1);
const std::string::size_type sep1 = windowsPath ? ext.find(':', 4) : colon;
const std::string::size_type sep2 = ext.find(':', sep1 + 1);
file = tokenList->appendFileIfNew(ext.substr(1, sep1 - 1));
line = MathLib::toLongNumber(ext.substr(sep1 + 1, sep2 - sep1 - 1));
}
@ -628,7 +628,7 @@ void clangimport::AstNode::setValueType(Token *tok)
if (!decl.front())
break;
ValueType valueType = ValueType::parseDecl(decl.front(), mData->mSettings, true); // TODO: set isCpp
const ValueType valueType = ValueType::parseDecl(decl.front(), mData->mSettings, true); // TODO: set isCpp
if (valueType.type != ValueType::Type::UNKNOWN_TYPE) {
tok->setValueType(new ValueType(valueType));
break;
@ -732,7 +732,7 @@ Token *clangimport::AstNode::createTokens(TokenList *tokenList)
if (nodeType == BreakStmt)
return addtoken(tokenList, "break");
if (nodeType == CharacterLiteral) {
int c = MathLib::toLongNumber(mExtTokens.back());
const int c = MathLib::toLongNumber(mExtTokens.back());
if (c == 0)
return addtoken(tokenList, "\'\\0\'");
if (c == '\r')
@ -1425,7 +1425,7 @@ void clangimport::AstNode::createTokensFunctionDecl(TokenList *tokenList)
void clangimport::AstNode::createTokensForCXXRecord(TokenList *tokenList)
{
bool isStruct = contains(mExtTokens, "struct");
const bool isStruct = contains(mExtTokens, "struct");
Token * const classToken = addtoken(tokenList, isStruct ? "struct" : "class");
std::string className;
if (mExtTokens[mExtTokens.size() - 2] == (isStruct?"struct":"class"))
@ -1544,7 +1544,7 @@ static void setValues(Tokenizer *tokenizer, SymbolDatabase *symbolDatabase)
for (Token *tok = const_cast<Token*>(tokenizer->tokens()); tok; tok = tok->next()) {
if (Token::simpleMatch(tok, "sizeof (")) {
ValueType vt = ValueType::parseDecl(tok->tokAt(2), settings, tokenizer->isCPP());
int sz = vt.typeSize(*settings, true);
const int sz = vt.typeSize(*settings, true);
if (sz <= 0)
continue;
long long mul = 1;

View File

@ -574,7 +574,7 @@ unsigned int CppCheck::check(const ImportProject::FileSettings &fs)
return temp.check(Path::simplifyPath(fs.filename));
}
std::ifstream fin(fs.filename);
unsigned int returnValue = temp.checkFile(Path::simplifyPath(fs.filename), fs.cfg, fin);
const unsigned int returnValue = temp.checkFile(Path::simplifyPath(fs.filename), fs.cfg, fin);
mSettings.nomsg.addSuppressions(temp.mSettings.nomsg.getSuppressions());
return returnValue;
}
@ -673,7 +673,7 @@ unsigned int CppCheck::checkFile(const std::string& filename, const std::string
filename2 = filename.substr(filename.rfind('/') + 1);
else
filename2 = filename;
std::size_t fileNameHash = std::hash<std::string> {}(filename);
const std::size_t fileNameHash = std::hash<std::string> {}(filename);
filename2 = mSettings.plistOutput + filename2.substr(0, filename2.find('.')) + "_" + std::to_string(fileNameHash) + ".plist";
mPlistFile.open(filename2);
mPlistFile << ErrorLogger::plistHeader(version(), files);
@ -863,7 +863,7 @@ unsigned int CppCheck::checkFile(const std::string& filename, const std::string
// Simplify tokens into normal form, skip rest of iteration if failed
Timer timer2("Tokenizer::simplifyTokens1", mSettings.showtime, &s_timerResults);
bool result = tokenizer.simplifyTokens1(mCurrentConfig);
const bool result = tokenizer.simplifyTokens1(mCurrentConfig);
timer2.stop();
if (!result)
continue;

View File

@ -180,7 +180,7 @@ static std::string readAttrString(const tinyxml2::XMLElement *e, const char *att
static long long readAttrInt(const tinyxml2::XMLElement *e, const char *attr, bool *error)
{
int64_t value = 0;
bool err = (e->QueryInt64Attribute(attr, &value) != tinyxml2::XML_SUCCESS);
const bool err = (e->QueryInt64Attribute(attr, &value) != tinyxml2::XML_SUCCESS);
if (error)
*error = err;
return value;
@ -483,7 +483,7 @@ std::list<CTU::FileInfo::UnsafeUsage> CTU::getUnsafeUsage(const Tokenizer *token
for (int argnr = 0; argnr < function->argCount(); ++argnr) {
for (const std::pair<const Token *, MathLib::bigint> &v : getUnsafeFunction(tokenizer, settings, &scope, argnr, check, isUnsafeUsage)) {
const Token *tok = v.first;
MathLib::bigint val = v.second;
const MathLib::bigint val = v.second;
unsafeUsage.emplace_back(CTU::getFunctionId(tokenizer, function), argnr+1, tok->str(), CTU::FileInfo::Location(tokenizer,tok), val);
}
}

View File

@ -667,7 +667,7 @@ std::string ErrorMessage::FileLocation::stringify() const
std::string ErrorLogger::toxml(const std::string &str)
{
std::ostringstream xml;
for (unsigned char c : str) {
for (const unsigned char c : str) {
switch (c) {
case '<':
xml << "&lt;";

View File

@ -102,10 +102,10 @@ struct ForwardTraversal {
return std::make_pair(false, false);
std::vector<MathLib::bigint> result = analyzer->evaluate(tok, ctx);
// TODO: We should convert to bool
bool checkThen = std::any_of(result.begin(), result.end(), [](int x) {
const bool checkThen = std::any_of(result.begin(), result.end(), [](int x) {
return x != 0;
});
bool checkElse = std::any_of(result.begin(), result.end(), [](int x) {
const bool checkElse = std::any_of(result.begin(), result.end(), [](int x) {
return x == 0;
});
return std::make_pair(checkThen, checkElse);
@ -185,7 +185,7 @@ struct ForwardTraversal {
std::swap(firstOp, secondOp);
if (firstOp && traverseRecursive(firstOp, f, traverseUnknown, recursion+1) == Progress::Break)
return Break();
Progress p = tok->isAssignmentOp() ? Progress::Continue : traverseTok(tok, f, traverseUnknown);
const Progress p = tok->isAssignmentOp() ? Progress::Continue : traverseTok(tok, f, traverseUnknown);
if (p == Progress::Break)
return Break();
if (p == Progress::Continue && secondOp && traverseRecursive(secondOp, f, traverseUnknown, recursion+1) == Progress::Break)
@ -325,7 +325,7 @@ struct ForwardTraversal {
for (const Token* tok=start; tok != end; tok = tok->previous()) {
if (Token::simpleMatch(tok, "}")) {
const Token* ftok = nullptr;
bool r = isReturnScope(tok, &settings->library, &ftok);
const bool r = isReturnScope(tok, &settings->library, &ftok);
if (r)
return true;
}
@ -335,7 +335,7 @@ struct ForwardTraversal {
bool isEscapeScope(const Token* endBlock, bool& unknown) const {
const Token* ftok = nullptr;
bool r = isReturnScope(endBlock, &settings->library, &ftok);
const bool r = isReturnScope(endBlock, &settings->library, &ftok);
if (!r && ftok)
unknown = true;
return r;
@ -367,7 +367,7 @@ struct ForwardTraversal {
Analyzer::Action a = analyzeScope(branch.endBlock);
branch.action = a;
std::vector<ForwardTraversal> ft1 = tryForkUpdateScope(branch.endBlock, a.isModified());
bool bail = hasGoto(branch.endBlock);
const bool bail = hasGoto(branch.endBlock);
if (!a.isModified() && !bail) {
if (ft1.empty()) {
// Traverse into the branch to see if there is a conditional escape
@ -696,7 +696,7 @@ struct ForwardTraversal {
std::tie(thenBranch.check, elseBranch.check) = evalCond(condTok);
if (!thenBranch.check && !elseBranch.check && analyzer->stopOnCondition(condTok) && stopUpdates())
return Break(Analyzer::Terminate::Conditional);
bool hasElse = Token::simpleMatch(endBlock, "} else {");
const bool hasElse = Token::simpleMatch(endBlock, "} else {");
bool bail = false;
// Traverse then block
@ -715,7 +715,7 @@ struct ForwardTraversal {
elseBranch.escape = isEscapeScope(endBlock->linkAt(2), elseBranch.escapeUnknown);
if (elseBranch.check) {
elseBranch.active = true;
Progress result = updateRange(endBlock->tokAt(2), endBlock->linkAt(2), depth - 1);
const Progress result = updateRange(endBlock->tokAt(2), endBlock->linkAt(2), depth - 1);
if (result == Progress::Break)
return Break();
} else if (!thenBranch.check) {
@ -855,7 +855,7 @@ struct ForwardTraversal {
static Token* skipTo(Token* tok, const Token* dest, const Token* end = nullptr) {
if (end && dest->index() > end->index())
return nullptr;
int i = dest->index() - tok->index();
const int i = dest->index() - tok->index();
if (i > 0)
return tok->tokAt(dest->index() - tok->index());
return nullptr;

View File

@ -259,7 +259,7 @@ static std::string unescape(const std::string &in)
{
std::string out;
bool escape = false;
for (char c: in) {
for (const char c: in) {
if (escape) {
escape = false;
if (!std::strchr("\\\"\'",c))
@ -875,7 +875,7 @@ bool ImportProject::importBcb6Prj(const std::string &projectFilename)
{
std::string arg;
for (char i : cflag1) {
for (const char i : cflag1) {
if (i == ' ' && !arg.empty()) {
cflags.insert(arg);
arg.clear();

View File

@ -209,7 +209,7 @@ Library::Error Library::load(const tinyxml2::XMLDocument &doc)
if (strcmp(rootnode->Name(),"def") != 0)
return Error(ErrorCode::UNSUPPORTED_FORMAT, rootnode->Name());
int format = rootnode->IntAttribute("format", 1); // Assume format version 1 if nothing else is specified (very old .cfg files had no 'format' attribute)
const int format = rootnode->IntAttribute("format", 1); // Assume format version 1 if nothing else is specified (very old .cfg files had no 'format' attribute)
if (format > 2 || format <= 0)
return Error(ErrorCode::UNSUPPORTED_FORMAT);
@ -1250,7 +1250,7 @@ const Library::WarnInfo* Library::getWarnInfo(const Token* ftok) const
{
if (isNotLibraryFunction(ftok))
return nullptr;
std::map<std::string, WarnInfo>::const_iterator i = functionwarn.find(getFunctionName(ftok));
const std::map<std::string, WarnInfo>::const_iterator i = functionwarn.find(getFunctionName(ftok));
if (i == functionwarn.cend())
return nullptr;
return &i->second;
@ -1687,7 +1687,7 @@ std::shared_ptr<Token> createTokenFromExpression(const std::string& returnValue,
for (Token* tok2 = tokenList->front(); tok2; tok2 = tok2->next()) {
if (tok2->str().compare(0, 3, "arg") != 0)
continue;
nonneg int id = std::atoi(tok2->str().c_str() + 3);
nonneg int const id = std::atoi(tok2->str().c_str() + 3);
tok2->varId(id);
if (lookupVarId)
(*lookupVarId)[id] = tok2;

View File

@ -343,7 +343,7 @@ MathLib::biguint MathLib::toULongNumber(const std::string & str)
unsigned int MathLib::encodeMultiChar(const std::string& str)
{
unsigned int retval = 0;
for (char it : str) {
for (const char it : str) {
retval = (retval << 8) | it;
}
return retval;
@ -1194,8 +1194,8 @@ bool MathLib::isNullValue(const std::string &str)
if (!isInt(str) && !isFloat(str))
return false;
bool isHex = isIntHex(str) || isFloatHex(str);
for (char i : str) {
const bool isHex = isIntHex(str) || isFloatHex(str);
for (const char i : str) {
if (std::isdigit(static_cast<unsigned char>(i)) && i != '0') // May not contain digits other than 0
return false;
if (i == 'p' || i == 'P' || (!isHex && (i == 'E' || i == 'e')))

View File

@ -151,7 +151,7 @@ PathAnalysis::Progress PathAnalysis::forwardRange(const Token* startToken, const
if (Token::simpleMatch(endBlock, "} else {")) {
if (checkElse) {
i.errorPath.back().second = "Assuming condition is false.";
Progress result = forwardRange(endCond->next(), endBlock, i, f);
const Progress result = forwardRange(endCond->next(), endBlock, i, f);
if (result == Progress::Break)
return Progress::Break;
}

View File

@ -60,7 +60,7 @@ namespace cppcheck {
}
bool isIntValue(unsigned long long value) const {
unsigned long long intMax = max_value(int_bit);
const unsigned long long intMax = max_value(int_bit);
return value <= intMax;
}
@ -69,12 +69,12 @@ namespace cppcheck {
}
bool isLongValue(unsigned long long value) const {
unsigned long long longMax = max_value(long_bit);
const unsigned long long longMax = max_value(long_bit);
return value <= longMax;
}
bool isLongLongValue(unsigned long long value) const {
unsigned long long longLongMax = max_value(long_long_bit);
const unsigned long long longLongMax = max_value(long_long_bit);
return value <= longLongMax;
}

View File

@ -892,8 +892,8 @@ bool Preprocessor::validateCfg(const std::string &cfg, const std::list<simplecpp
continue;
if (mu.macroName != macroName)
continue;
bool directiveLocation = std::any_of(mDirectives.cbegin(), mDirectives.cend(),
[=](const Directive &dir) {
const bool directiveLocation = std::any_of(mDirectives.cbegin(), mDirectives.cend(),
[=](const Directive &dir) {
return mu.useLocation.file() == dir.file && mu.useLocation.line == dir.linenr;
});

View File

@ -581,7 +581,7 @@ static ValueFlow::Value evaluate(const std::string& op, const ValueFlow::Value&
// If not the same type then one must be int
if (lhs.valueType != rhs.valueType && !lhs.isIntValue() && !rhs.isIntValue())
return ValueFlow::Value::unknown();
bool compareOp = contains({"==", "!=", "<", ">", ">=", "<="}, op);
const bool compareOp = contains({"==", "!=", "<", ">", ">=", "<="}, op);
// Comparison must be the same type
if (compareOp && lhs.valueType != rhs.valueType)
return ValueFlow::Value::unknown();
@ -637,7 +637,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::sin(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
@ -648,7 +648,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::lgamma(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
@ -659,7 +659,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::cos(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
@ -670,7 +670,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::tan(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
@ -681,7 +681,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::asin(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
@ -692,7 +692,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::acos(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
@ -703,7 +703,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::atan(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
@ -713,7 +713,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
return v.isFloatValue() || v.isIntValue();
}))
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
ValueFlow::Value v;
combineValueProperties(args[0], args[1], &v);
v.floatValue = std::atan2(value, args[1].isFloatValue() ? args[1].floatValue : args[1].intvalue);
@ -725,7 +725,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
return v.isFloatValue() || v.isIntValue();
}))
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
ValueFlow::Value v;
combineValueProperties(args[0], args[1], &v);
v.floatValue = std::remainder(value, args[1].isFloatValue() ? args[1].floatValue : args[1].intvalue);
@ -737,7 +737,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
return v.isFloatValue() || v.isIntValue();
}))
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
ValueFlow::Value v;
combineValueProperties(args[0], args[1], &v);
v.floatValue = std::nextafter(value, args[1].isFloatValue() ? args[1].floatValue : args[1].intvalue);
@ -749,7 +749,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
return v.isFloatValue() || v.isIntValue();
}))
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
ValueFlow::Value v;
combineValueProperties(args[0], args[1], &v);
v.floatValue = std::nexttoward(value, args[1].isFloatValue() ? args[1].floatValue : args[1].intvalue);
@ -761,7 +761,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
return v.isFloatValue() || v.isIntValue();
}))
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
ValueFlow::Value v;
combineValueProperties(args[0], args[1], &v);
v.floatValue = std::hypot(value, args[1].isFloatValue() ? args[1].floatValue : args[1].intvalue);
@ -773,7 +773,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
return v.isFloatValue() || v.isIntValue();
}))
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
ValueFlow::Value v;
combineValueProperties(args[0], args[1], &v);
v.floatValue = std::fdim(value, args[1].isFloatValue() ? args[1].floatValue : args[1].intvalue);
@ -785,7 +785,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
return v.isFloatValue() || v.isIntValue();
}))
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
ValueFlow::Value v;
combineValueProperties(args[0], args[1], &v);
v.floatValue = std::fmax(value, args[1].isFloatValue() ? args[1].floatValue : args[1].intvalue);
@ -797,7 +797,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
return v.isFloatValue() || v.isIntValue();
}))
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
ValueFlow::Value v;
combineValueProperties(args[0], args[1], &v);
v.floatValue = std::fmin(value, args[1].isFloatValue() ? args[1].floatValue : args[1].intvalue);
@ -809,7 +809,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
return v.isFloatValue() || v.isIntValue();
}))
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
ValueFlow::Value v;
combineValueProperties(args[0], args[1], &v);
v.floatValue = std::fmod(value, args[1].isFloatValue() ? args[1].floatValue : args[1].intvalue);
@ -821,7 +821,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
return v.isFloatValue() || v.isIntValue();
}))
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
ValueFlow::Value v;
combineValueProperties(args[0], args[1], &v);
v.floatValue = std::pow(value, args[1].isFloatValue() ? args[1].floatValue : args[1].intvalue);
@ -833,7 +833,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
return v.isFloatValue() || v.isIntValue();
}))
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
ValueFlow::Value v;
combineValueProperties(args[0], args[1], &v);
v.floatValue = std::scalbln(value, args[1].isFloatValue() ? args[1].floatValue : args[1].intvalue);
@ -845,7 +845,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
return v.isFloatValue() || v.isIntValue();
}))
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
ValueFlow::Value v;
combineValueProperties(args[0], args[1], &v);
v.floatValue = std::ldexp(value, args[1].isFloatValue() ? args[1].floatValue : args[1].intvalue);
@ -858,7 +858,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.intvalue = std::ilogb(value);
v.valueType = ValueFlow::Value::ValueType::INT;
return v;
@ -869,7 +869,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::erf(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
@ -880,7 +880,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::erfc(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
@ -891,7 +891,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::floor(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
@ -902,7 +902,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::sqrt(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
@ -913,7 +913,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::cbrt(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
@ -924,7 +924,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::ceil(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
@ -935,7 +935,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::exp(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
@ -946,7 +946,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::exp2(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
@ -957,7 +957,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::expm1(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
@ -968,7 +968,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::fabs(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
@ -979,7 +979,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::log(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
@ -990,7 +990,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::log10(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
@ -1001,7 +1001,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::log1p(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
@ -1012,7 +1012,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::log2(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
@ -1023,7 +1023,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::logb(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
@ -1034,7 +1034,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::nearbyint(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
@ -1045,7 +1045,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::sinh(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
@ -1056,7 +1056,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::cosh(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
@ -1067,7 +1067,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::tanh(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
@ -1078,7 +1078,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::asinh(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
@ -1089,7 +1089,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::acosh(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
@ -1100,7 +1100,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::atanh(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
@ -1111,7 +1111,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::round(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
@ -1122,7 +1122,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::tgamma(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
@ -1133,7 +1133,7 @@ static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibr
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::trunc(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
@ -1171,7 +1171,7 @@ static ValueFlow::Value executeImpl(const Token* expr, ProgramMemory& pm, const
return ValueFlow::Value{ expr->str() == "true" };
} else if (Token::Match(expr->tokAt(-2), ". %name% (") && astIsContainer(expr->tokAt(-2)->astOperand1())) {
const Token* containerTok = expr->tokAt(-2)->astOperand1();
Library::Container::Yield yield = containerTok->valueType()->container->getYield(expr->strAt(-1));
const Library::Container::Yield yield = containerTok->valueType()->container->getYield(expr->strAt(-1));
if (yield == Library::Container::Yield::SIZE) {
ValueFlow::Value v = execute(containerTok, pm);
if (!v.isContainerSizeValue())
@ -1257,7 +1257,7 @@ static ValueFlow::Value executeImpl(const Token* expr, ProgramMemory& pm, const
ValueFlow::Value rhs = execute(expr->astOperand2(), pm);
if (!rhs.isIntValue())
return unknown;
MathLib::bigint index = rhs.intvalue;
const MathLib::bigint index = rhs.intvalue;
if (index >= 0 && index < strValue.size())
return ValueFlow::Value{strValue[index]};
else if (index == strValue.size())

View File

@ -45,10 +45,10 @@ struct ReverseTraversal {
std::pair<bool, bool> evalCond(const Token* tok) {
std::vector<MathLib::bigint> result = analyzer->evaluate(tok);
// TODO: We should convert to bool
bool checkThen = std::any_of(result.begin(), result.end(), [](int x) {
const bool checkThen = std::any_of(result.begin(), result.end(), [](int x) {
return x == 1;
});
bool checkElse = std::any_of(result.begin(), result.end(), [](int x) {
const bool checkElse = std::any_of(result.begin(), result.end(), [](int x) {
return x == 0;
});
return std::make_pair(checkThen, checkElse);

View File

@ -83,7 +83,7 @@ std::string Summaries::create(const Tokenizer *tokenizer, const std::string &cfg
if (!settings->buildDir.empty()) {
std::string filename = AnalyzerInformation::getAnalyzerInfoFile(settings->buildDir, tokenizer->list.getSourceFilePath(), cfg);
std::string::size_type pos = filename.rfind(".a");
const std::string::size_type pos = filename.rfind(".a");
if (pos != std::string::npos) {
filename[pos+1] = 's';
std::ofstream fout(filename);
@ -105,8 +105,8 @@ static std::vector<std::string> getSummaryFiles(const std::string &filename)
return ret;
std::string line;
while (std::getline(fin, line)) {
std::string::size_type dotA = line.find(".a");
std::string::size_type colon = line.find(":");
const std::string::size_type dotA = line.find(".a");
const std::string::size_type colon = line.find(":");
if (colon > line.size() || dotA > colon)
continue;
std::string f = line.substr(0,colon);
@ -128,7 +128,7 @@ static std::vector<std::string> getSummaryData(const std::string &line, const st
std::string::size_type pos1 = start + 3 + data.size();
while (pos1 < end) {
std::string::size_type pos2 = line.find_first_of(",]",pos1);
const std::string::size_type pos2 = line.find_first_of(",]",pos1);
ret.push_back(line.substr(pos1, pos2-pos1-1));
pos1 = pos2 + 1;
}

View File

@ -826,7 +826,7 @@ void SymbolDatabase::createSymbolDatabaseCopyAndMoveConstructors()
void SymbolDatabase::createSymbolDatabaseFunctionScopes()
{
// fill in function scopes
for (Scope & scope : scopeList) {
for (const Scope & scope : scopeList) {
if (scope.type == Scope::eFunction)
functionScopes.push_back(&scope);
}
@ -835,7 +835,7 @@ void SymbolDatabase::createSymbolDatabaseFunctionScopes()
void SymbolDatabase::createSymbolDatabaseClassAndStructScopes()
{
// fill in class and struct scopes
for (Scope& scope : scopeList) {
for (const Scope& scope : scopeList) {
if (scope.isClassOrStruct())
classAndStructScopes.push_back(&scope);
}
@ -1058,7 +1058,7 @@ void SymbolDatabase::createSymbolDatabaseSetScopePointers()
};
// Set scope pointers
for (Scope& scope: scopeList) {
for (const Scope& scope: scopeList) {
if (scope.type == Scope::eGlobal)
setScopePointers(scope, mTokenizer->list.front(), mTokenizer->list.back());
else {
@ -1310,22 +1310,22 @@ void SymbolDatabase::createSymbolDatabaseSetVariablePointers()
void SymbolDatabase::createSymbolDatabaseEnums()
{
// fill in enumerators in enum
for (Scope &scope : scopeList) {
for (const Scope &scope : scopeList) {
if (scope.type != Scope::eEnum)
continue;
// add enumerators to enumerator tokens
for (Enumerator & i : scope.enumeratorList)
for (const Enumerator & i : scope.enumeratorList)
const_cast<Token *>(i.name)->enumerator(&i);
}
std::set<std::string> tokensThatAreNotEnumeratorValues;
for (Scope &scope : scopeList) {
for (const Scope &scope : scopeList) {
if (scope.type != Scope::eEnum)
continue;
for (Enumerator & enumerator : scope.enumeratorList) {
for (const Enumerator & enumerator : scope.enumeratorList) {
// look for initialization tokens that can be converted to enumerators and convert them
if (enumerator.start) {
if (!enumerator.end)
@ -1583,7 +1583,7 @@ void SymbolDatabase::createSymbolDatabaseExprIds()
continue;
if (!isSameExpression(isCPP(), true, tok1, tok2, mSettings->library, false, false))
continue;
nonneg int cid = std::min(tok1->exprId(), tok2->exprId());
nonneg int const cid = std::min(tok1->exprId(), tok2->exprId());
tok1->exprId(cid);
tok2->exprId(cid);
}
@ -5140,7 +5140,7 @@ std::vector<const Scope*> Scope::findAssociatedScopes() const
static void checkVariableCallMatch(const Variable* callarg, const Variable* funcarg, size_t& same, size_t& fallback1, size_t& fallback2)
{
if (callarg) {
ValueType::MatchResult res = ValueType::matchParameter(callarg->valueType(), callarg, funcarg);
const ValueType::MatchResult res = ValueType::matchParameter(callarg->valueType(), callarg, funcarg);
if (res == ValueType::MatchResult::SAME) {
same++;
return;
@ -5156,8 +5156,8 @@ static void checkVariableCallMatch(const Variable* callarg, const Variable* func
if (res == ValueType::MatchResult::NOMATCH)
return;
bool ptrequals = callarg->isArrayOrPointer() == funcarg->isArrayOrPointer();
bool constEquals = !callarg->isArrayOrPointer() || ((callarg->typeStartToken()->strAt(-1) == "const") == (funcarg->typeStartToken()->strAt(-1) == "const"));
const bool ptrequals = callarg->isArrayOrPointer() == funcarg->isArrayOrPointer();
const bool constEquals = !callarg->isArrayOrPointer() || ((callarg->typeStartToken()->strAt(-1) == "const") == (funcarg->typeStartToken()->strAt(-1) == "const"));
if (ptrequals && constEquals &&
callarg->typeStartToken()->str() == funcarg->typeStartToken()->str() &&
callarg->typeStartToken()->isUnsigned() == funcarg->typeStartToken()->isUnsigned() &&
@ -5330,7 +5330,7 @@ const Function* Scope::findFunction(const Token *tok, bool requireConst) const
callArgType.sign = funcArgType.sign = ValueType::Sign::SIGNED;
callArgType.type = funcArgType.type = ValueType::Type::INT;
ValueType::MatchResult res = ValueType::matchParameter(&callArgType, &funcArgType);
const ValueType::MatchResult res = ValueType::matchParameter(&callArgType, &funcArgType);
if (res == ValueType::MatchResult::SAME)
++same;
else if (res == ValueType::MatchResult::FALLBACK1)
@ -5377,7 +5377,7 @@ const Function* Scope::findFunction(const Token *tok, bool requireConst) const
else
unknownDeref = true;
}
ValueType::MatchResult res = ValueType::matchParameter(arguments[j]->valueType(), var, funcarg);
const ValueType::MatchResult res = ValueType::matchParameter(arguments[j]->valueType(), var, funcarg);
if (res == ValueType::MatchResult::SAME)
++same;
else if (res == ValueType::MatchResult::FALLBACK1)
@ -6529,7 +6529,7 @@ static const Token* parsedecl(const Token* type,
TokenList typeTokens(settings);
std::string::size_type pos1 = 0;
do {
std::string::size_type pos2 = type->str().find("::", pos1);
const std::string::size_type pos2 = type->str().find("::", pos1);
if (pos2 == std::string::npos) {
typeTokens.addtoken(type->str().substr(pos1), 0, 0, 0, false);
break;
@ -6597,7 +6597,7 @@ static const Token* parsedecl(const Token* type,
if (valuetype->fromLibraryType(typestr, settings))
type = end;
} else if (ValueType::Type::UNKNOWN_TYPE != ValueType::typeFromString(type->str(), type->isLong())) {
ValueType::Type t0 = valuetype->type;
const ValueType::Type t0 = valuetype->type;
valuetype->type = ValueType::typeFromString(type->str(), type->isLong());
if (t0 == ValueType::Type::LONG) {
if (valuetype->type == ValueType::Type::LONG)
@ -6760,8 +6760,8 @@ void SymbolDatabase::setValueTypeInTokenList(bool reportDebugWarnings, Token *to
} else if (tok->isBoolean()) {
setValueType(tok, ValueType(ValueType::Sign::UNKNOWN_SIGN, ValueType::Type::BOOL, 0U));
} else if (tok->tokType() == Token::eChar || tok->tokType() == Token::eString) {
nonneg int pointer = tok->tokType() == Token::eChar ? 0U : 1U;
nonneg int constness = tok->tokType() == Token::eChar ? 0U : 1U;
nonneg int const pointer = tok->tokType() == Token::eChar ? 0U : 1U;
nonneg int const constness = tok->tokType() == Token::eChar ? 0U : 1U;
ValueType valuetype(ValueType::Sign::UNKNOWN_SIGN, ValueType::Type::CHAR, pointer, constness);
if (mIsCpp && mSettings->standards.cpp >= Standards::CPP20 && tok->isUtf8()) {
@ -7439,7 +7439,7 @@ ValueType::MatchResult ValueType::matchParameter(const ValueType *call, const Va
++vt.pointer;
pvt = &vt;
}
ValueType::MatchResult res = ValueType::matchParameter(call, pvt);
const ValueType::MatchResult res = ValueType::matchParameter(call, pvt);
if (callVar && ((res == ValueType::MatchResult::SAME && call->container) || res == ValueType::MatchResult::UNKNOWN)) {
const std::string type1 = getTypeString(callVar->typeStartToken());
const std::string type2 = getTypeString(funcVar->typeStartToken());

View File

@ -699,9 +699,9 @@ void TemplateSimplifier::addInstantiation(Token *token, const std::string &scope
TokenAndName instantiation(token, scope);
// check if instantiation already exists before adding it
std::list<TokenAndName>::iterator it = std::find(mTemplateInstantiations.begin(),
mTemplateInstantiations.end(),
instantiation);
const std::list<TokenAndName>::iterator it = std::find(mTemplateInstantiations.begin(),
mTemplateInstantiations.end(),
instantiation);
if (it == mTemplateInstantiations.end())
mTemplateInstantiations.emplace_back(std::move(instantiation));
@ -778,7 +778,7 @@ void TemplateSimplifier::getTemplateInstantiations()
// Don't ignore user specialization but don't consider it an instantiation.
// Instantiations in return type, function parameters, and executable code
// are not ignored.
unsigned int pos = getTemplateNamePosition(tok);
const unsigned int pos = getTemplateNamePosition(tok);
if (pos > 0)
skip = tok->tokAt(pos);
} else {
@ -854,7 +854,7 @@ void TemplateSimplifier::getTemplateInstantiations()
size_t argMatch = 0;
for (size_t i = 0; i < declarationParams.size(); ++i) {
// fixme: only type deducton from literals is supported
bool isArgLiteral = Token::Match(instantiationArgs[i], "%num%|%str%|%char%|%bool% ,|)");
const bool isArgLiteral = Token::Match(instantiationArgs[i], "%num%|%str%|%char%|%bool% ,|)");
if (isArgLiteral && Token::Match(declarationParams[i], "const| %type% &| %name%| ,|)")) {
match++;
@ -892,7 +892,7 @@ void TemplateSimplifier::getTemplateInstantiations()
MathLib::value num(arg->str());
if (num.isFloat()) {
// MathLib::getSuffix doesn't work for floating point numbers
char suffix = arg->str().back();
const char suffix = arg->str().back();
if (suffix == 'f' || suffix == 'F')
tok->insertToken("float");
else if (suffix == 'l' || suffix == 'L') {
@ -1206,9 +1206,9 @@ void TemplateSimplifier::useDefaultArgumentValues(TokenAndName &declaration)
if (Token::Match(tok2, "(|{|["))
tok2 = tok2->link();
else if (Token::Match(tok2, "%type% <") && (tok2->strAt(2) == ">" || templateParameters(tok2->next()))) {
std::list<TokenAndName>::iterator ti = std::find_if(mTemplateInstantiations.begin(),
mTemplateInstantiations.end(),
FindToken(tok2));
const std::list<TokenAndName>::iterator ti = std::find_if(mTemplateInstantiations.begin(),
mTemplateInstantiations.end(),
FindToken(tok2));
if (ti != mTemplateInstantiations.end())
mTemplateInstantiations.erase(ti);
++indentlevel;
@ -1225,9 +1225,9 @@ void TemplateSimplifier::useDefaultArgumentValues(TokenAndName &declaration)
continue;
// don't strip args from uninstantiated templates
std::list<TokenAndName>::iterator ti2 = std::find_if(mTemplateInstantiations.begin(),
mTemplateInstantiations.end(),
FindName(declaration.name()));
const std::list<TokenAndName>::iterator ti2 = std::find_if(mTemplateInstantiations.begin(),
mTemplateInstantiations.end(),
FindName(declaration.name()));
if (ti2 == mTemplateInstantiations.end())
continue;
@ -1243,7 +1243,7 @@ void TemplateSimplifier::useDefaultArgumentValues(TokenAndName &declaration)
void TemplateSimplifier::simplifyTemplateAliases()
{
for (std::list<TokenAndName>::iterator it1 = mTemplateDeclarations.begin(); it1 != mTemplateDeclarations.end();) {
TokenAndName &aliasDeclaration = *it1;
const TokenAndName &aliasDeclaration = *it1;
if (!aliasDeclaration.isAlias()) {
++it1;
@ -1260,7 +1260,7 @@ void TemplateSimplifier::simplifyTemplateAliases()
// Look for alias usages..
bool found = false;
for (std::list<TokenAndName>::iterator it2 = mTemplateInstantiations.begin(); it2 != mTemplateInstantiations.end();) {
TokenAndName &aliasUsage = *it2;
const TokenAndName &aliasUsage = *it2;
if (!aliasUsage.token() || aliasUsage.fullName() != aliasDeclaration.fullName()) {
++it2;
continue;
@ -1627,9 +1627,9 @@ void TemplateSimplifier::expandTemplate(
end = temp2->linkAt(1)->next();
} else {
if (it != mTemplateForwardDeclarationsMap.end()) {
std::list<TokenAndName>::iterator it1 = std::find_if(mTemplateForwardDeclarations.begin(),
mTemplateForwardDeclarations.end(),
FindToken(it->second));
const std::list<TokenAndName>::iterator it1 = std::find_if(mTemplateForwardDeclarations.begin(),
mTemplateForwardDeclarations.end(),
FindToken(it->second));
if (it1 != mTemplateForwardDeclarations.end())
mMemberFunctionsToDelete.push_back(*it1);
}
@ -2015,9 +2015,9 @@ void TemplateSimplifier::expandTemplate(
while (tok3 && tok3->str() != "::")
tok3 = tok3->next();
std::list<TokenAndName>::iterator it = std::find_if(mTemplateDeclarations.begin(),
mTemplateDeclarations.end(),
FindToken(startOfTemplateDeclaration));
const std::list<TokenAndName>::iterator it = std::find_if(mTemplateDeclarations.begin(),
mTemplateDeclarations.end(),
FindToken(startOfTemplateDeclaration));
if (it != mTemplateDeclarations.end())
mMemberFunctionsToDelete.push_back(*it);
}
@ -2196,7 +2196,7 @@ void TemplateSimplifier::expandTemplate(
if (prev->strAt(-1) != "::") {
// adjust for current scope
std::string token_scope = tok3->scopeInfo()->name;
std::string::size_type end = token_scope.find_last_of(" :: ");
const std::string::size_type end = token_scope.find_last_of(" :: ");
if (end != std::string::npos) {
token_scope.resize(end);
if (scope.empty())
@ -2658,7 +2658,7 @@ bool TemplateSimplifier::simplifyCalculations(Token* frontToken, Token *backToke
tok->str("bool");
else if (MathLib::isFloat(tok->str())) {
// MathLib::getSuffix doesn't work for floating point numbers
char suffix = tok->str().back();
const char suffix = tok->str().back();
if (suffix == 'f' || suffix == 'F')
tok->str("float");
else if (suffix == 'l' || suffix == 'L') {
@ -3712,7 +3712,7 @@ void TemplateSimplifier::simplifyTemplates(
// explicit(bool)
for (Token *tok = mTokenList.front(); tok; tok = tok->next()) {
if (Token::simpleMatch(tok, "explicit (")) {
bool isFalse = Token::simpleMatch(tok->tokAt(2), "false )");
const bool isFalse = Token::simpleMatch(tok->tokAt(2), "false )");
Token::eraseTokens(tok, tok->linkAt(1)->next());
if (isFalse)
tok->deleteThis();
@ -3746,7 +3746,7 @@ void TemplateSimplifier::simplifyTemplates(
mTemplateNamePos.clear();
}
bool hasTemplates = getTemplateDeclarations();
const bool hasTemplates = getTemplateDeclarations();
if (passCount == 0)
codeWithTemplates = hasTemplates;

View File

@ -221,7 +221,7 @@ bool Token::isUpperCaseName() const
{
if (!isName())
return false;
for (char i : mStr) {
for (const char i : mStr) {
if (std::islower(i))
return false;
}
@ -1225,14 +1225,14 @@ std::string Token::stringify(const stringifyOptions& options) const
if (options.macro && isExpandedMacro())
ret += '$';
if (isName() && mStr.find(' ') != std::string::npos) {
for (char i : mStr) {
for (const char i : mStr) {
if (i != ' ')
ret += i;
}
} else if (mStr[0] != '\"' || mStr.find('\0') == std::string::npos)
ret += mStr;
else {
for (char i : mStr) {
for (const char i : mStr) {
if (i == '\0')
ret += "\\0";
else
@ -1539,7 +1539,7 @@ static std::string stringFromTokenRange(const Token* start, const Token* end)
if (tok->isLong() && !tok->isLiteral())
ret += "long ";
if (tok->tokType() == Token::eString) {
for (unsigned char c: tok->str()) {
for (const unsigned char c: tok->str()) {
if (c == '\n')
ret += "\\n";
else if (c == '\r')
@ -1699,7 +1699,7 @@ void Token::printValueFlow(bool xml, std::ostream &out) const
out << "Line " << tok->linenr() << std::endl;
line = tok->linenr();
if (!xml) {
ValueFlow::Value::ValueKind valueKind = tok->mImpl->mValues->front().valueKind;
const ValueFlow::Value::ValueKind valueKind = tok->mImpl->mValues->front().valueKind;
bool same = true;
for (const ValueFlow::Value &value : *tok->mImpl->mValues) {
if (value.valueKind != valueKind) {

View File

@ -2200,7 +2200,7 @@ namespace {
// scopes didn't match so try higher scopes
index = newScope1.size();
while (!newScope1.empty()) {
std::string::size_type separator = newScope1.rfind(" :: ", index - 1);
const std::string::size_type separator = newScope1.rfind(" :: ", index - 1);
if (separator != std::string::npos)
newScope1.resize(separator);
else
@ -5664,7 +5664,7 @@ void Tokenizer::simplifyEmptyNamespaces()
}
if (!Token::Match(tok, "namespace %name%| {"))
continue;
bool isAnonymousNS = tok->strAt(1) == "{";
const bool isAnonymousNS = tok->strAt(1) == "{";
if (tok->strAt(3 - isAnonymousNS) == "}") {
tok->deleteNext(3 - isAnonymousNS); // remove '%name%| { }'
if (!tok->previous()) {
@ -5988,7 +5988,7 @@ void Tokenizer::simplifyFunctionParameters()
if (argumentNames.size() != argumentNames2.size()) {
//move back 'tok1' to the last ';'
tok1 = tok1->previous();
for (std::pair<const std::string, Token *>& argumentName : argumentNames) {
for (const std::pair<const std::string, Token *>& argumentName : argumentNames) {
if (argumentNames2.find(argumentName.first) == argumentNames2.end()) {
//add the missing parameter argument declaration
tok1->insertToken(";");

View File

@ -43,7 +43,7 @@ bool isValidGlobPattern(const std::string& pattern)
{
for (std::string::const_iterator i = pattern.begin(); i != pattern.end(); ++i) {
if (*i == '*' || *i == '?') {
std::string::const_iterator j = i + 1;
const std::string::const_iterator j = i + 1;
if (j != pattern.end() && (*j == '*' || *j == '?')) {
return false;
}

View File

@ -558,8 +558,8 @@ static ValueFlow::Value truncateImplicitConversion(Token* parent, const ValueFlo
// If the sign is the same there is no truncation
if (vt1->sign == vt2->sign)
return value;
size_t n1 = ValueFlow::getSizeOf(*vt1, settings);
size_t n2 = ValueFlow::getSizeOf(*vt2, settings);
const size_t n1 = ValueFlow::getSizeOf(*vt1, settings);
const size_t n2 = ValueFlow::getSizeOf(*vt2, settings);
ValueType::Sign sign = ValueType::Sign::UNSIGNED;
if (n1 < n2)
sign = vt2->sign;
@ -1214,7 +1214,7 @@ static Token * valueFlowSetConstantValue(Token *tok, const Settings *settings, b
}
}
} else if (tok2->tokType() == Token::eString) {
size_t sz = Token::getStrSize(tok2, settings);
const size_t sz = Token::getStrSize(tok2, settings);
if (sz > 0) {
ValueFlow::Value value(sz);
value.setKnown();
@ -1248,7 +1248,7 @@ static Token * valueFlowSetConstantValue(Token *tok, const Settings *settings, b
const Token* num = brac->astOperand2();
if (num && ((num->isNumber() && MathLib::isInt(num->str())) || num->tokType() == Token::eChar)) {
try {
MathLib::biguint dim = MathLib::toULongNumber(num->str());
const MathLib::biguint dim = MathLib::toULongNumber(num->str());
sz *= dim;
brac = brac->astParent();
continue;
@ -1393,7 +1393,7 @@ static void valueFlowArrayBool(TokenList *tokenlist)
continue;
const Variable *var = nullptr;
bool known = false;
std::list<ValueFlow::Value>::const_iterator val =
const std::list<ValueFlow::Value>::const_iterator val =
std::find_if(tok->values().begin(), tok->values().end(), std::mem_fn(&ValueFlow::Value::isTokValue));
if (val == tok->values().end()) {
var = tok->variable();
@ -1434,7 +1434,7 @@ static void valueFlowArrayElement(TokenList* tokenlist, const Settings* settings
const Library::Container* container = getLibraryContainer(arrayTok);
if (!container || container->stdAssociativeLike)
continue;
Library::Container::Yield yield = container->getYield(tok->strAt(-1));
const Library::Container::Yield yield = container->getYield(tok->strAt(-1));
if (yield != Library::Container::Yield::AT_INDEX)
continue;
indexTok = tok->astOperand2();
@ -1606,8 +1606,8 @@ static bool getExpressionRange(const Token *expr, MathLib::bigint *minvalue, Mat
if (expr->str() == "&" && expr->astOperand1() && expr->astOperand2()) {
MathLib::bigint vals[4];
bool lhsHasKnownRange = getExpressionRange(expr->astOperand1(), &vals[0], &vals[1]);
bool rhsHasKnownRange = getExpressionRange(expr->astOperand2(), &vals[2], &vals[3]);
const bool lhsHasKnownRange = getExpressionRange(expr->astOperand1(), &vals[0], &vals[1]);
const bool rhsHasKnownRange = getExpressionRange(expr->astOperand2(), &vals[2], &vals[3]);
if (!lhsHasKnownRange && !rhsHasKnownRange)
return false;
if (!lhsHasKnownRange || !rhsHasKnownRange) {
@ -1630,7 +1630,7 @@ static bool getExpressionRange(const Token *expr, MathLib::bigint *minvalue, Mat
return false;
if (vals[2] <= 0)
return false;
bool lhsHasKnownRange = getExpressionRange(expr->astOperand1(), &vals[0], &vals[1]);
const bool lhsHasKnownRange = getExpressionRange(expr->astOperand1(), &vals[0], &vals[1]);
if (lhsHasKnownRange && vals[0] < 0)
return false;
// If lhs has unknown value, it must be unsigned
@ -1849,7 +1849,7 @@ static void valueFlowGlobalConstVar(TokenList* tokenList, const Settings *settin
for (Token* tok = tokenList->front(); tok; tok = tok->next()) {
if (!tok->variable())
continue;
std::map<const Variable*, ValueFlow::Value>::const_iterator var = vars.find(tok->variable());
const std::map<const Variable*, ValueFlow::Value>::const_iterator var = vars.find(tok->variable());
if (var == vars.end())
continue;
setTokenValue(tok, var->second, settings);
@ -1897,7 +1897,7 @@ static void valueFlowGlobalStaticVar(TokenList *tokenList, const Settings *setti
for (Token *tok = tokenList->front(); tok; tok = tok->next()) {
if (!tok->variable())
continue;
std::map<const Variable *, ValueFlow::Value>::const_iterator var = vars.find(tok->variable());
const std::map<const Variable *, ValueFlow::Value>::const_iterator var = vars.find(tok->variable());
if (var == vars.end())
continue;
setTokenValue(tok, var->second, settings);
@ -2890,7 +2890,7 @@ struct SingleValueFlowAnalyzer : ValueFlowAnalyzer {
std::ref(getVars()), std::ref(getAliasedVars())
}) {
for (const auto& p:m.get()) {
nonneg int varid = p.first;
nonneg int const varid = p.first;
const Variable* var = p.second;
if (tok->varId() == varid)
return true;
@ -3340,7 +3340,7 @@ static std::vector<LifetimeToken> getLifetimeTokens(const Token* tok,
continue;
const Token* argTok = nullptr;
if (argvar->isArgument() && (argvar->isReference() || argvar->isRValueReference())) {
int n = getArgumentPos(argvar, f);
const int n = getArgumentPos(argvar, f);
if (n < 0)
return std::vector<LifetimeToken> {};
std::vector<const Token*> args = getArguments(tok->previous());
@ -3368,7 +3368,7 @@ static std::vector<LifetimeToken> getLifetimeTokens(const Token* tok,
return result;
} else if (Token::Match(tok->tokAt(-2), ". %name% (") && tok->tokAt(-2)->originalName() != "->" && astIsContainer(tok->tokAt(-2)->astOperand1())) {
const Library::Container* library = getLibraryContainer(tok->tokAt(-2)->astOperand1());
Library::Container::Yield y = library->getYield(tok->previous()->str());
const Library::Container::Yield y = library->getYield(tok->previous()->str());
if (y == Library::Container::Yield::AT_INDEX || y == Library::Container::Yield::ITEM) {
errorPath.emplace_back(tok->previous(), "Accessing container.");
return LifetimeToken::setAddressOf(
@ -3834,7 +3834,7 @@ struct LifetimeStore {
return LifetimeStore{};
if (!var->isArgument())
return LifetimeStore{};
int n = getArgumentPos(var, f);
const int n = getArgumentPos(var, f);
if (n < 0)
return LifetimeStore{};
std::vector<const Token *> args = getArguments(tok);
@ -4106,7 +4106,7 @@ static void valueFlowLifetimeUserConstructor(Token* tok,
const Variable* paramVar = argToParam.at(ls.argtok);
if (paramCapture.count(paramVar) == 0)
return;
LifetimeCapture c = paramCapture.at(paramVar);
const LifetimeCapture c = paramCapture.at(paramVar);
if (c == LifetimeCapture::ByReference)
ls.byRef(tok, tokenlist, errorLogger, settings);
else
@ -4134,7 +4134,7 @@ static void valueFlowLifetimeFunction(Token *tok, TokenList *tokenlist, ErrorLog
Token* memtok = nullptr;
if (Token::Match(tok->astParent(), ". %name% (") && astIsRHS(tok))
memtok = tok->astParent()->astOperand1();
int returnContainer = settings->library.returnValueContainer(tok);
const int returnContainer = settings->library.returnValueContainer(tok);
if (returnContainer >= 0) {
std::vector<const Token *> args = getArguments(tok);
for (int argnr = 1; argnr <= args.size(); ++argnr) {
@ -4171,7 +4171,7 @@ static void valueFlowLifetimeFunction(Token *tok, TokenList *tokenlist, ErrorLog
} else if (memtok && Token::Match(tok->astParent(), ". push_back|push_front|insert|push|assign") &&
astIsContainer(memtok)) {
std::vector<const Token *> args = getArguments(tok);
std::size_t n = args.size();
const std::size_t n = args.size();
if (n > 1 && Token::typeStr(args[n - 2]) == Token::typeStr(args[n - 1]) &&
(((astIsIterator(args[n - 2]) && astIsIterator(args[n - 1])) ||
(astIsPointer(args[n - 2]) && astIsPointer(args[n - 1]))))) {
@ -4568,7 +4568,7 @@ static void valueFlowLifetime(TokenList *tokenlist, SymbolDatabase* /*db*/, Erro
for (const auto& p:lam.explicitCaptures) {
const Variable* var = p.first;
const Token* tok2 = p.second.first;
LifetimeCapture c = p.second.second;
const LifetimeCapture c = p.second.second;
if (Token::Match(tok2, "this !!.")) {
captureThisVariable(tok2, c);
} else if (var) {
@ -5034,8 +5034,8 @@ static bool isTruncated(const ValueType* src, const ValueType* dst, const Settin
if (src->smartPointer && dst->smartPointer)
return false;
if ((src->isIntegral() && dst->isIntegral()) || (src->isFloat() && dst->isFloat())) {
size_t srcSize = ValueFlow::getSizeOf(*src, settings);
size_t dstSize = ValueFlow::getSizeOf(*dst, settings);
const size_t srcSize = ValueFlow::getSizeOf(*src, settings);
const size_t dstSize = ValueFlow::getSizeOf(*dst, settings);
if (srcSize > dstSize)
return true;
if (srcSize == dstSize && src->sign != dst->sign)
@ -5972,7 +5972,7 @@ struct ConditionHandler {
if (Token::Match(tok->astParent(), "==|!=")) {
Token* sibling = tok->astSibling();
if (sibling->hasKnownIntValue() && (astIsBool(tok) || astIsBool(sibling))) {
bool value = sibling->values().front().intvalue;
const bool value = sibling->values().front().intvalue;
if (inverted)
*inverted ^= value == Token::simpleMatch(tok->astParent(), "!=");
continue;
@ -6313,7 +6313,7 @@ struct ConditionHandler {
}
if (values.empty())
return;
bool isKnown = std::any_of(values.begin(), values.end(), [&](const ValueFlow::Value& v) {
const bool isKnown = std::any_of(values.begin(), values.end(), [&](const ValueFlow::Value& v) {
return v.isKnown() || v.isImpossible();
});
if (isKnown && isBreakOrContinueScope(after)) {
@ -6898,7 +6898,7 @@ struct MultiValueFlowAnalyzer : ValueFlowAnalyzer {
const auto range = SelectValueFromVarIdMapRange(&values);
for (const auto& p:getVars()) {
nonneg int varid = p.first;
nonneg int const varid = p.first;
const Variable* var = p.second;
if (tok->varId() == varid)
return true;
@ -7034,7 +7034,7 @@ bool productParams(const std::unordered_map<Key, std::list<ValueFlow::Value>>& v
continue;
bool skip = false;
// Make sure all arguments are the same path
MathLib::bigint path = arg.begin()->second.path;
const MathLib::bigint path = arg.begin()->second.path;
for (const auto& p:arg) {
if (p.second.path != path) {
skip = true;
@ -7055,7 +7055,7 @@ static void valueFlowInjectParameter(TokenList* tokenlist,
const Scope* functionScope,
const std::unordered_map<const Variable*, std::list<ValueFlow::Value>>& vars)
{
bool r = productParams(vars, [&](const std::unordered_map<const Variable*, ValueFlow::Value>& arg) {
const bool r = productParams(vars, [&](const std::unordered_map<const Variable*, ValueFlow::Value>& arg) {
MultiValueFlowAnalyzer a(arg, tokenlist, symboldatabase);
valueFlowGenericForward(const_cast<Token*>(functionScope->bodyStart), functionScope->bodyEnd, a, settings);
});
@ -7510,7 +7510,7 @@ static void valueFlowUninit(TokenList* tokenlist, SymbolDatabase* /*symbolDataba
// Try to insert into map
auto pp = partialReads.insert(std::make_pair(tok2, v));
ValueFlow::Value& v2 = pp.first->second;
bool inserted = pp.second;
const bool inserted = pp.second;
// Merge the two values if it is already in map
if (!inserted) {
if (v.valueType != v2.valueType)
@ -7550,7 +7550,7 @@ static bool isContainerSizeChangedByFunction(const Token* tok, const Settings* s
return false;
// If we are accessing an element then we are not changing the container size
if (Token::Match(tok, "%name% . %name% (")) {
Library::Container::Yield yield = getLibraryContainer(tok)->getYield(tok->strAt(2));
const Library::Container::Yield yield = getLibraryContainer(tok)->getYield(tok->strAt(2));
if (yield != Library::Container::Yield::NO_YIELD)
return false;
}
@ -7630,7 +7630,7 @@ struct ContainerExpressionAnalyzer : ExpressionAnalyzer {
return Action::Read | Action::Write | Action::Incremental;
}
} else if (astIsLHS(tok) && Token::Match(tok->astParent(), ". %name% (")) {
Library::Container::Action action = container->getAction(tok->astParent()->strAt(1));
const Library::Container::Action action = container->getAction(tok->astParent()->strAt(1));
if (action == Library::Container::Action::PUSH || action == Library::Container::Action::POP) {
std::vector<const Token*> args = getArguments(tok->tokAt(3));
if (args.size() < 2)
@ -7667,7 +7667,7 @@ struct ContainerExpressionAnalyzer : ExpressionAnalyzer {
}
}
} else if (astIsLHS(tok) && Token::Match(tok->astParent(), ". %name% (")) {
Library::Container::Action action = container->getAction(tok->astParent()->strAt(1));
const Library::Container::Action action = container->getAction(tok->astParent()->strAt(1));
if (action == Library::Container::Action::PUSH)
val->intvalue++;
if (action == Library::Container::Action::POP)
@ -7727,7 +7727,7 @@ const Token* solveExprValue(const Token* expr,
return expr;
MathLib::bigint intval;
const Token* binaryTok = parseBinaryIntOp(expr, eval, intval);
bool rhs = astIsRHS(binaryTok);
const bool rhs = astIsRHS(binaryTok);
// If its on the rhs, then -1 multiplication is needed, which is not possible with simple delta analysis used currently for symbolic values
if (value.isSymbolicValue() && rhs && Token::simpleMatch(expr, "-"))
return expr;
@ -7800,7 +7800,7 @@ bool isContainerSizeChanged(const Token* tok, const Settings* settings, int dept
return false;
if (astIsLHS(tok) && Token::simpleMatch(tok->astParent(), "["))
return container->stdAssociativeLike;
Library::Container::Action action = astContainerAction(tok);
const Library::Container::Action action = astContainerAction(tok);
switch (action) {
case Library::Container::Action::RESIZE:
case Library::Container::Action::CLEAR:
@ -7813,7 +7813,7 @@ bool isContainerSizeChanged(const Token* tok, const Settings* settings, int dept
case Library::Container::Action::NO_ACTION:
// Is this an unknown member function call?
if (astIsLHS(tok) && Token::Match(tok->astParent(), ". %name% (")) {
Library::Container::Yield yield = astContainerYield(tok);
const Library::Container::Yield yield = astContainerYield(tok);
return yield == Library::Container::Yield::NO_YIELD;
}
break;
@ -7927,7 +7927,7 @@ static void valueFlowIterators(TokenList *tokenlist, const Settings *settings)
if (!astIsContainer(tok))
continue;
const Token* ftok = nullptr;
Library::Container::Yield yield = astContainerYield(tok, &ftok);
const Library::Container::Yield yield = astContainerYield(tok, &ftok);
if (ftok) {
ValueFlow::Value v(0);
v.setKnown();
@ -7960,7 +7960,7 @@ struct IteratorConditionHandler : SimpleConditionHandler {
if (!tok->astOperand1() || !tok->astOperand2())
return {};
ValueFlow::Value::ValueKind kind = ValueFlow::Value::ValueKind::Known;
const ValueFlow::Value::ValueKind kind = ValueFlow::Value::ValueKind::Known;
std::list<ValueFlow::Value> values = getIteratorValues(tok->astOperand1()->values(), &kind);
if (!values.empty()) {
cond.vartok = tok->astOperand2();
@ -8062,7 +8062,7 @@ static std::vector<ValueFlow::Value> getContainerSizeFromConstructorArgs(const s
return {makeContainerSizeValue(std::size_t{0}, known)};
// TODO: Insert iterator positions for pointers
if (Token::simpleMatch(args[1], "+")) {
nonneg int eid = args[0]->exprId();
nonneg int const eid = args[0]->exprId();
const Token* vartok = args[1]->astOperand1();
const Token* sizetok = args[1]->astOperand2();
if (sizetok->exprId() == eid)
@ -8163,7 +8163,7 @@ static void valueFlowContainerSize(TokenList* tokenlist,
bool known = true;
int size = 0;
bool nonLocal = !var->isLocal() || var->isPointer() || var->isReference() || var->isStatic();
const bool nonLocal = !var->isLocal() || var->isPointer() || var->isReference() || var->isStatic();
bool constSize = var->isConst() && !nonLocal;
bool staticSize = false;
if (var->valueType()->container->size_templateArgNo >= 0) {
@ -8250,7 +8250,7 @@ static void valueFlowContainerSize(TokenList* tokenlist,
const Token* containerTok = tok->astOperand1();
if (containerTok->exprId() == 0)
continue;
Library::Container::Action action = containerTok->valueType()->container->getAction(tok->strAt(1));
const Library::Container::Action action = containerTok->valueType()->container->getAction(tok->strAt(1));
if (action == Library::Container::Action::CLEAR) {
ValueFlow::Value value(0);
value.valueType = ValueFlow::Value::ValueType::CONTAINER_SIZE;

View File

@ -826,7 +826,7 @@ private:
Library::Container& A = library.containers["A"];
Library::Container& B = library.containers["B"];
Library::Container& C = library.containers["C"];
const Library::Container& C = library.containers["C"];
ASSERT_EQUALS(A.type_templateArgNo, 1);
ASSERT_EQUALS(A.size_templateArgNo, 4);

View File

@ -176,7 +176,7 @@ std::string TestFixture::deleteLineNumber(const std::string &message)
while ((pos = result.find(':', pos)) != std::string::npos) {
// get number
if (pos + 1 == result.find_first_of("0123456789", pos + 1)) {
std::string::size_type after = result.find_first_not_of("0123456789", pos + 1);
const std::string::size_type after = result.find_first_not_of("0123456789", pos + 1);
if (after != std::string::npos
&& result.at(after) == ':') {
// erase NUMBER

View File

@ -1319,7 +1319,7 @@ private:
void isVariablePointerToConstPointer() {
reset();
GET_SYMBOL_DB("char* const * s;");
bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(true, result);
Variable v(vartok, typetok, vartok->previous(), 0, AccessControl::Public, nullptr, nullptr, &settings1);
ASSERT(false == v.isArray());
@ -1330,7 +1330,7 @@ private:
void isVariablePointerToVolatilePointer() {
reset();
GET_SYMBOL_DB("char* volatile * s;");
bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(true, result);
Variable v(vartok, typetok, vartok->previous(), 0, AccessControl::Public, nullptr, nullptr, &settings1);
ASSERT(false == v.isArray());
@ -1341,7 +1341,7 @@ private:
void isVariablePointerToConstVolatilePointer() {
reset();
GET_SYMBOL_DB("char* const volatile * s;");
bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens(), vartok, typetok);
ASSERT_EQUALS(true, result);
Variable v(vartok, typetok, vartok->previous(), 0, AccessControl::Public, nullptr, nullptr, &settings1);
ASSERT(false == v.isArray());
@ -1352,7 +1352,7 @@ private:
void isVariableMultiplePointersAndQualifiers() {
reset();
GET_SYMBOL_DB("const char* const volatile * const volatile * const volatile * const volatile s;");
bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens()->next(), vartok, typetok);
const bool result = db->scopeList.front().isVariableDeclaration(tokenizer.tokens()->next(), vartok, typetok);
ASSERT_EQUALS(true, result);
Variable v(vartok, typetok, vartok->previous(), 0, AccessControl::Public, nullptr, nullptr, &settings1);
ASSERT(false == v.isArray());
@ -2137,9 +2137,9 @@ private:
ASSERT(db && db->scopeList.size() == 1);
std::list<Scope>::const_iterator it = db->scopeList.begin();
const std::list<Scope>::const_iterator it = db->scopeList.begin();
ASSERT(it->varlist.size() == 1);
std::list<Variable>::const_iterator var = it->varlist.begin();
const std::list<Variable>::const_iterator var = it->varlist.begin();
ASSERT(var->name() == "i");
ASSERT(var->typeStartToken()->str() == "int");
}
@ -2149,10 +2149,10 @@ private:
ASSERT(db && db->scopeList.size() == 1);
std::list<Scope>::const_iterator it = db->scopeList.begin();
const std::list<Scope>::const_iterator it = db->scopeList.begin();
ASSERT(it->varlist.size() == 1);
std::list<Variable>::const_iterator var = it->varlist.begin();
const std::list<Variable>::const_iterator var = it->varlist.begin();
ASSERT(var->name() == "array");
ASSERT(var->typeStartToken()->str() == "int");
}
@ -2162,10 +2162,10 @@ private:
ASSERT(db && db->scopeList.size() == 1);
std::list<Scope>::const_iterator it = db->scopeList.begin();
const std::list<Scope>::const_iterator it = db->scopeList.begin();
ASSERT(it->varlist.size() == 1);
std::list<Variable>::const_iterator var = it->varlist.begin();
const std::list<Variable>::const_iterator var = it->varlist.begin();
ASSERT(var->name() == "array");
ASSERT(var->typeStartToken()->str() == "int");
}

View File

@ -1867,11 +1867,11 @@ private:
"char &(b); "
"const static char *(c); "
"} ;";
static char exp[] = "struct S { "
"char * a ; "
"char & b ; "
"static const char * c ; "
"} ;";
static const char exp[] = "struct S { "
"char * a ; "
"char & b ; "
"static const char * c ; "
"} ;";
ASSERT_EQUALS(exp, tokenizeAndStringify(code));
}
@ -1879,48 +1879,48 @@ private:
// Reported case
{
static char code[] = "; * * p f ( ) int = { new int ( * [ 2 ] ) ; void }";
static char exp[] = "; * * p f ( ) int = { new int ( * [ 2 ] ) ; void }";
static const char exp[] = "; * * p f ( ) int = { new int ( * [ 2 ] ) ; void }";
ASSERT_EQUALS(exp, tokenizeAndStringify(code));
}
// Various valid cases
{
static char code[] = "int * f [ 1 ] = { new ( int ) } ;";
static char exp[] = "int * f [ 1 ] = { new int } ;";
static const char exp[] = "int * f [ 1 ] = { new int } ;";
ASSERT_EQUALS(exp, tokenizeAndStringify(code));
}
{
static char code[] = "int * * f [ 1 ] = { new ( int ) [ 1 ] } ;";
static char exp[] = "int * * f [ 1 ] = { new int [ 1 ] } ;";
static const char exp[] = "int * * f [ 1 ] = { new int [ 1 ] } ;";
ASSERT_EQUALS(exp, tokenizeAndStringify(code));
}
{
static char code[] = "list < int > * f [ 1 ] = { new ( list < int > ) } ;";
static char exp[] = "list < int > * f [ 1 ] = { new list < int > } ;";
static const char exp[] = "list < int > * f [ 1 ] = { new list < int > } ;";
ASSERT_EQUALS(exp, tokenizeAndStringify(code));
}
// don't remove parentheses in operator new overload
{
static char code[] = "void *operator new(__SIZE_TYPE__, int);";
static char exp[] = "void * operatornew ( __SIZE_TYPE__ , int ) ;";
static const char exp[] = "void * operatornew ( __SIZE_TYPE__ , int ) ;";
ASSERT_EQUALS(exp, tokenizeAndStringify(code));
}
}
void removeParentheses24() { // Ticket #7040
static char code[] = "std::hash<decltype(t._data)>()(t._data);";
static char exp[] = "std :: hash < decltype ( t . _data ) > ( ) ( t . _data ) ;";
static const char exp[] = "std :: hash < decltype ( t . _data ) > ( ) ( t . _data ) ;";
ASSERT_EQUALS(exp, tokenizeAndStringify(code));
}
void removeParentheses25() { // daca@home - a=(b,c)
static char code[] = "a=(b,c);";
static char exp[] = "a = ( b , c ) ;";
static const char exp[] = "a = ( b , c ) ;";
ASSERT_EQUALS(exp, tokenizeAndStringify(code));
}
void removeParentheses26() { // Ticket #8875 a[0](0)
static char code[] = "a[0](0);";
static char exp[] = "a [ 0 ] ( 0 ) ;";
static const char exp[] = "a [ 0 ] ( 0 ) ;";
ASSERT_EQUALS(exp, tokenizeAndStringify(code));
}

View File

@ -101,7 +101,7 @@ static void getDeps(const std::string &filename, std::vector<std::string> &depfi
pos1 += 10;
std::string::size_type pos2 = line.find(rightBracket, pos1);
const std::string::size_type pos2 = line.find(rightBracket, pos1);
std::string hfile = path + line.substr(pos1, pos2 - pos1);
if (hfile.find("/../") != std::string::npos) // TODO: Ugly fix
@ -113,7 +113,7 @@ static void getDeps(const std::string &filename, std::vector<std::string> &depfi
static void compilefiles(std::ostream &fout, const std::vector<std::string> &files, const std::string &args)
{
for (const std::string &file : files) {
bool external(file.compare(0,10,"externals/") == 0);
const bool external(file.compare(0,10,"externals/") == 0);
fout << objfile(file) << ": " << file;
std::vector<std::string> depfiles;
getDeps(file, depfiles);

View File

@ -213,7 +213,7 @@ bool MainWindow::runProcess(const QString &programName, const QStringList &argum
errorstr.append(process.errorString());
ui->statusBar->showMessage(errorstr);
} else {
int exitCode = process.exitCode();
const int exitCode = process.exitCode();
if (exitCode != 0) {
success = false;
const QByteArray stderrOutput = process.readAllStandardError();